@remit/web-client-dist 0.0.244 → 0.0.246

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/assets/{ComposeBody-C3RMgwOn.js → ComposeBody-CQDryHHT.js} +1 -1
  2. package/assets/{ConfirmDialog-DGWhqSsn.js → ConfirmDialog-BQZOydod.js} +1 -1
  3. package/assets/{ErrorState-CWJO4hHt.js → ErrorState-BwS1XlO_.js} +1 -1
  4. package/assets/{OnboardingWizard-DMmN12bN.js → OnboardingWizard-1Simemkn.js} +1 -1
  5. package/assets/{account-form-helpers-EfDwHB82.js → account-form-helpers-Bi9qE9zm.js} +1 -1
  6. package/assets/{accounts-JALVSvA3.js → accounts-DZdrKnxe.js} +1 -1
  7. package/assets/{advanced-Duu5xH0S.js → advanced-Bta8WZ92.js} +1 -1
  8. package/assets/{appearance-Cj9Wkhlk.js → appearance-DDjloFBz.js} +1 -1
  9. package/assets/{avatar-_n0xGRR2.js → avatar-cbXKbnBP.js} +1 -1
  10. package/assets/{browser-ponyfill-BmDdbLhP.js → browser-ponyfill-DEV8XWQd.js} +2 -2
  11. package/assets/{circle-check-CUv_d4UI.js → circle-check-CxgRXEL3.js} +1 -1
  12. package/assets/{download-C3HPAYGd.js → download-BTF9jChU.js} +1 -1
  13. package/assets/{filters-C1inEhTj.js → filters-gqZ6D42z.js} +1 -1
  14. package/assets/{flagged-DUj-yppy.js → flagged-Ccn115El.js} +1 -1
  15. package/assets/{folders-CLVGIuD8.js → folders-BD2BsVT2.js} +1 -1
  16. package/assets/{index-B6m2RDW6.js → index-BfGjMWZ8.js} +57 -57
  17. package/assets/{index-CWDuuqaB.js → index-CAXdYDcS.js} +1 -1
  18. package/assets/index-CpvmgpCk.js +1 -0
  19. package/assets/{kbd-_1HxaUzP.js → kbd-ChYmK8GY.js} +1 -1
  20. package/assets/{labels-A4xmXa2X.js → labels-BF_F_Lt7.js} +1 -1
  21. package/assets/{mail-e0dTd77F.js → mail-Dj2GHlez.js} +16 -16
  22. package/assets/{move-options-B8WfOmgy.js → move-options-DJt1GMvN.js} +1 -1
  23. package/assets/{move-targets-BUSjz-tN.js → move-targets-Cn8KSqpp.js} +1 -1
  24. package/assets/{onboarding-DcwDauWu.js → onboarding-C3rnl5ZZ.js} +1 -1
  25. package/assets/{senders-DCP9P7UF.js → senders-BHPDE8lY.js} +1 -1
  26. package/assets/settings-CDUZOnYX.js +1 -0
  27. package/assets/{settings-screen-B57myuej.js → settings-screen-CIbTQpXU.js} +1 -1
  28. package/assets/{shield-check-Dz2vzzOT.js → shield-check-DxP4d_Zx.js} +1 -1
  29. package/assets/{suggested-vips-CM4PkrlC.js → suggested-vips-CCPghwkD.js} +1 -1
  30. package/assets/{useDebouncedValue-C-aLzfmc.js → useDebouncedValue-BAAteqS8.js} +1 -1
  31. package/assets/{useFilters-tIW0tO5B.js → useFilters-Cq1W7Zus.js} +1 -1
  32. package/assets/{useLabels-DMgWHfkD.js → useLabels-BWgV81Q6.js} +1 -1
  33. package/assets/{useSignature-CpDwTCxu.js → useSignature-DZ23o5A5.js} +1 -1
  34. package/index.html +1 -1
  35. package/package.json +1 -1
  36. package/assets/index-DRDgOCOY.js +0 -1
  37. package/assets/settings-C43W5RwT.js +0 -1
@@ -1,11 +1,11 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-C3RMgwOn.js","assets/index-B6m2RDW6.js","assets/index-DPey6jym.css","assets/move-options-B8WfOmgy.js","assets/move-targets-BUSjz-tN.js","assets/avatar-_n0xGRR2.js","assets/kbd-_1HxaUzP.js","assets/shield-check-Dz2vzzOT.js","assets/account-form-helpers-EfDwHB82.js","assets/useSignature-CpDwTCxu.js","assets/useDebouncedValue-C-aLzfmc.js","assets/useFilters-tIW0tO5B.js","assets/ErrorState-CWJO4hHt.js","assets/format-CKZmh-Ru.js","assets/useLabels-DMgWHfkD.js","assets/ConfirmDialog-DGWhqSsn.js","assets/circle-check-CUv_d4UI.js"])))=>i.map(i=>d[i]);
2
- import{R as K,c as df,r as c,a as Ie,j as r,C as Wt,b as As,X as jt,d as V,B as le,e as St,S as Gt,f as Tt,g as ds,L as Ds,h as Ea,i as ff,k as mf,l as fn,T as Rt,u as Jn,m as Ia,n as Al,I as Ol,F as Ta,p as Pl,o as Ra,q as hf,A as Ma,D as pf,s as mn,t as gf,v as Zn,O as xf,M as bf,w as vf,x as Dl,y as yf,z as wf,E as hn,G as Sf,H as kf,J as jf,K as Cf,N as Ll,P as fs,Q as Aa,U as Nf,V as Fl,W as Ef,Y as If,Z as Tf,_ as Oa,$ as Pa,a0 as Bt,a1 as $l,a2 as Rf,a3 as Da,a4 as Mf,a5 as Af,a6 as Of,a7 as ra,a8 as Pf,a9 as Df,aa as Me,ab as Lf,ac as Ff,ad as $f,ae as _f,af as zf,ag as Bf,ah as Ho,ai as Kf,aj as Uf,ak as qf,al as La,am as _l,an as zl,ao as Yt,ap as Ke,aq as it,ar as Fa,as as _e,at as $a,au as _a,av as za,aw as Ba,ax as Ka,ay as Kn,az as Ae,aA as pn,aB as be,aC as Bl,aD as Hf,aE as Fe,aF as Kl,aG as Wf,aH as er,aI as tr,aJ as Ul,aK as ql,aL as Vf,aM as Mt,aN as st,aO as Qf,aP as mt,aQ as Hl,aR as is,aS as sr,aT as Gf,aU as nr,aV as Ua,aW as qa,aX as ms,aY as rr,aZ as hs,a_ as Yf,a$ as Xf,b0 as aa,b1 as Jf,b2 as Wl,b3 as Os,b4 as Zf,b5 as ar,b6 as em,b7 as tm,b8 as sm,b9 as Vl,ba as Ha,bb as nm,bc as Wo,bd as rm,be as am,bf as om,bg as im,bh as Kt,bi as oa,bj as lm,bk as cm,bl as um,bm as Ql,bn as dm,bo as fm,bp as mm,bq as hm,br as Vo,bs as pm,bt as gm,bu as xm,bv as bm,bw as Wa,bx as ia,by as la,bz as vm,bA as Gl,bB as ym,bC as Yl,bD as wm,bE as Va,bF as Sm,bG as km,bH as jm,bI as Cm,bJ as Nm,bK as Em,bL as Im,bM as Tm,bN as Rm,bO as Mm,bP as _t,bQ as Et,bR as Am}from"./index-B6m2RDW6.js";import{P as Om,u as Qa,b as Ga,f as Ya}from"./move-options-B8WfOmgy.js";import{A as kt,M as or,C as Pm}from"./avatar-_n0xGRR2.js";import{K as Ts}from"./kbd-_1HxaUzP.js";import{S as gn,C as Xa,R as Dm}from"./shield-check-Dz2vzzOT.js";import{M as Xl,a as Lm}from"./account-form-helpers-EfDwHB82.js";import{R as Fm,u as $m}from"./useSignature-CpDwTCxu.js";import{u as ir}from"./useDebouncedValue-C-aLzfmc.js";import{B as _m,u as Xt,a as Qo,b as Go,c as zm,d as Bm,e as Km,n as Um,o as qm,f as Hm,g as Wm,S as Vm}from"./useFilters-tIW0tO5B.js";import{E as Jt,f as Jl}from"./ErrorState-CWJO4hHt.js";import{f as Zl,a as ht,b as ec,c as Vt,d as Un,t as Qm}from"./format-CKZmh-Ru.js";import{P as Yo,u as tc,M as ot}from"./move-targets-BUSjz-tN.js";import{u as Ja}from"./useLabels-DMgWHfkD.js";import{C as Za}from"./ConfirmDialog-DGWhqSsn.js";import{C as Gm}from"./circle-check-CUv_d4UI.js";function an(e){if(Ym())e.focus({preventScroll:!0});else{let t=Xm(e);e.focus(),Jm(t)}}let jn=null;function Ym(){if(jn==null){jn=!1;try{document.createElement("div").focus({get preventScroll(){return jn=!0,!0}})}catch{}}return jn}function Xm(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 Jm(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const qt=e=>e?.ownerDocument??document,Qt=e=>e&&"window"in e&&e.window===e?e:qt(e).defaultView||window;function Zm(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function eh(e){return Zm(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let th=!1;function sc(){return th}function wt(e,t){if(!sc())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:eh(s)?s=s.host:s=s.parentNode}return!1}function We(e){if(sc()&&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 sh=typeof Element<"u"&&"checkVisibility"in Element.prototype;function nh(e){const t=Qt(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}=Qt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function rh(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 nc(e,t){return sh?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&nh(e)&&rh(e,t)&&(!e.parentElement||nc(e.parentElement,e))}const rc=["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"],ah=rc.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";rc.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function oh(e,t){return e.matches(ah)&&!ih(e)&&(t?.skipVisibilityCheck||nc(e))}function ih(e){let t=e;for(;t!=null;){if(t instanceof Qt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const eo=typeof document<"u"?K.useLayoutEffect:()=>{};function lh(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function ch(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function uh(e){for(;e&&!oh(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Qt(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=f=>{(We(f)===s||n)&&f.stopImmediatePropagation()},o=f=>{(We(f)===s||n)&&(f.stopImmediatePropagation(),!e&&!n&&(n=!0,an(s),u()))},i=f=>{(We(f)===e||n)&&f.stopImmediatePropagation()},l=f=>{(We(f)===e||n)&&(f.stopImmediatePropagation(),n||(n=!0,an(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function lr(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 to(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function Zt(e){let t=null;return()=>(t==null&&(t=e()),t)}const qn=Zt(function(){return to(/^Mac/i)}),dh=Zt(function(){return to(/^iPhone/i)}),ac=Zt(function(){return to(/^iPad/i)||qn()&&navigator.maxTouchPoints>1}),oc=Zt(function(){return dh()||ac()}),fh=Zt(function(){return lr(/AppleWebKit/i)&&!mh()}),mh=Zt(function(){return lr(/Chrome/i)}),ic=Zt(function(){return lr(/Android/i)}),hh=Zt(function(){return lr(/Firefox/i)});function ph(e){return e.pointerType===""&&e.isTrusted?!0:ic()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function gh(e){return!ic()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function on(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;hh()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(qn()?n=!0:a=!0);let l=fh()&&qn()&&!ac()?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});on.isOpening=s,an(e),e.dispatchEvent(l),on.isOpening=!1}on.isOpening=!1;let Ut=new Map,ca=new Set;function Xo(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=We(n);if(!e(n)||!a)return;let o=Ut.get(a);o||(o=new Set,Ut.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=We(n);if(!e(n)||!a)return;let o=Ut.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Ut.delete(a)),Ut.size===0)){for(let i of ca)i();ca.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?Xo():document.addEventListener("DOMContentLoaded",Xo));function xh(){for(const[e]of Ut)"isConnected"in e&&!e.isConnected&&Ut.delete(e)}function bh(e){requestAnimationFrame(()=>{xh(),Ut.size===0?e():ca.add(e)})}function lc(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let ua=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{ua.delete(e)});function vh(e,t){if(e===t)return e;let s=ua.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=ua.get(t);return n?(n.forEach(a=>a.current=e),e):t}function yh(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=Jo(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():Jo(e[o],null)})}}}function Jo(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]=lc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=df(o,i):a==="id"&&o&&i?t.id=vh(o,i):a==="ref"&&o&&i?t.ref=yh(o,i):t[a]=i!==void 0?i:o}}return t}function wh(e,t){eo(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const Sh=K.useInsertionEffect??eo;function Or(e){const t=c.useRef(null);return Sh(()=>{t.current=e},[e]),c.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let Is="default",da="",Fn=new WeakMap;function kh(e){if(oc()){if(Is==="default"){const t=qt(e);da=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}Is="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Fn.set(e,e.style[t]),e.style[t]="none"}}function Zo(e){if(oc()){if(Is!=="disabled")return;Is="restoring",setTimeout(()=>{bh(()=>{if(Is==="restoring"){const t=qt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=da||""),da="",Is="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Fn.has(e)){let t=Fn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Fn.delete(e)}}function ei(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Pr=new WeakMap;function jh(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return ei(t);if(Pr.has(t))return Pr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof Qt(s).HTMLMetaElement&&(s.nonce||s.content)||ei(t)||void 0;return n!==void 0&&Pr.set(t,n),n}const cc=K.createContext({register:()=>{}});cc.displayName="PressResponderContext";function uc(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),n=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function Ch(e){let t=c.useContext(cc);if(t){let{register:s,ref:n,...a}=t;e=Ls(a,e),s()}return wh(t,e.ref),e}class Cn{#s;constructor(t,s,n,a){this.#s=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let l,u=0,m,f=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,f=n.clientY),i&&(m!=null&&f!=null?(l=m-i.left,u=f-i.top):(l=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=l,this.y=u,this.key=n.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const ti=Symbol("linkClicked"),si="react-aria-pressable-style",ni="data-react-aria-pressable";function Nh(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:f,allowTextSelectionOnPress:d,ref:h,...v}=Ch(e),[g,p]=c.useState(!1),y=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:S}=uc(),w=c.useCallback((j,T)=>{let A=y.current;if(l||A.didFirePressStart)return!1;let I=!0;if(A.isTriggeringEvent=!0,n){let F=new Cn("pressstart",T,j);n(F),I=F.shouldStopPropagation}return s&&s(!0),A.isTriggeringEvent=!1,A.didFirePressStart=!0,p(!0),I},[l,n,s]),x=c.useCallback((j,T,A=!0)=>{let I=y.current;if(!I.didFirePressStart)return!1;I.didFirePressStart=!1,I.isTriggeringEvent=!0;let F=!0;if(a){let N=new Cn("pressend",T,j);a(N),F=N.shouldStopPropagation}if(s&&s(!1),p(!1),t&&A&&!l){let N=new Cn("press",T,j);t(N),F&&=N.shouldStopPropagation}return I.isTriggeringEvent=!1,F},[l,a,s,t]),k=Or(x),M=c.useCallback((j,T)=>{let A=y.current;if(l)return!1;if(o){A.isTriggeringEvent=!0;let I=new Cn("pressup",T,j);return o(I),A.isTriggeringEvent=!1,I.shouldStopPropagation}return!0},[l,o]),O=Or(M),C=c.useCallback(j=>{let T=y.current;if(T.isPressed&&T.target){T.didFirePressStart&&T.pointerType!=null&&x(ns(T.target,j),T.pointerType,!1),T.isPressed=!1,T.isOverTarget=!1,T.activePointerId=null,T.pointerType=null,S(),d||Zo(T.target);for(let A of T.disposables)A();T.disposables=[]}},[d,S,x]),R=Or(C);c.useEffect(()=>{l&&y.current.isPressed&&R({currentTarget:y.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let P=c.useCallback(j=>{f&&C(j)},[f,C]),E=c.useCallback(j=>{l||i?.(j)},[l,i]),L=c.useCallback((j,T)=>{if(!l&&i){let A=new MouseEvent("click",j);ch(A,T),i(lh(A))}},[l,i]),D=c.useMemo(()=>{let j=y.current,T={onKeyDown(I){if(Dr(I.nativeEvent,I.currentTarget)&&wt(I.currentTarget,We(I))){ri(We(I),I.key)&&I.preventDefault();let F=!0;!j.isPressed&&!I.repeat&&(j.target=I.currentTarget,j.isPressed=!0,j.pointerType="keyboard",F=w(I,"keyboard"));let N=I.currentTarget,q=Q=>{Dr(Q,N)&&!Q.repeat&&wt(N,We(Q))&&j.target&&O(ns(j.target,Q),"keyboard")};b(qt(I.currentTarget),"keyup",lc(q,A),!0),F&&I.stopPropagation(),I.metaKey&&qn()&&j.metaKeyEvents?.set(I.key,I.nativeEvent)}else I.key==="Meta"&&(j.metaKeyEvents=new Map)},onClick(I){if(!(I&&!wt(I.currentTarget,We(I)))&&I&&I.button===0&&!j.isTriggeringEvent&&!on.isOpening){let F=!0;if(l&&I.preventDefault(),!j.ignoreEmulatedMouseEvents&&!j.isPressed&&(j.pointerType==="virtual"||ph(I.nativeEvent))){let N=w(I,"virtual"),q=O(I,"virtual"),Q=k(I,"virtual");E(I),F=N&&q&&Q}else if(j.isPressed&&j.pointerType!=="keyboard"){let N=j.pointerType||I.nativeEvent.pointerType||"virtual",q=O(ns(I.currentTarget,I),N),Q=k(ns(I.currentTarget,I),N,!0);F=q&&Q,j.isOverTarget=!1,E(I),R(I)}j.ignoreEmulatedMouseEvents=!1,F&&I.stopPropagation()}}},A=I=>{if(j.isPressed&&j.target&&Dr(I,j.target)){ri(We(I),I.key)&&I.preventDefault();let F=We(I),N=wt(j.target,F);k(ns(j.target,I),"keyboard",N),N&&L(I,j.target),S(),I.key!=="Enter"&&so(j.target)&&wt(j.target,F)&&!I[ti]&&(I[ti]=!0,on(j.target,I,!1)),j.isPressed=!1,j.metaKeyEvents?.delete(I.key)}else if(I.key==="Meta"&&j.metaKeyEvents?.size){let F=j.metaKeyEvents;j.metaKeyEvents=void 0;for(let N of F.values())j.target?.dispatchEvent(new KeyboardEvent("keyup",N))}};if(typeof PointerEvent<"u"){T.onPointerDown=N=>{if(N.button!==0||!wt(N.currentTarget,We(N)))return;if(gh(N.nativeEvent)){j.pointerType="virtual";return}j.pointerType=N.pointerType;let q=!0;if(!j.isPressed){j.isPressed=!0,j.isOverTarget=!0,j.activePointerId=N.pointerId,j.target=N.currentTarget,d||kh(j.target),q=w(N,j.pointerType);let Q=We(N);"releasePointerCapture"in Q&&("hasPointerCapture"in Q?Q.hasPointerCapture(N.pointerId)&&Q.releasePointerCapture(N.pointerId):Q.releasePointerCapture(N.pointerId)),b(qt(N.currentTarget),"pointerup",I,!1),b(qt(N.currentTarget),"pointercancel",F,!1)}q&&N.stopPropagation()},T.onMouseDown=N=>{if(wt(N.currentTarget,We(N))&&N.button===0){if(m){let q=uh(N.target);q&&j.disposables.push(q)}N.stopPropagation()}},T.onPointerUp=N=>{!wt(N.currentTarget,We(N))||j.pointerType==="virtual"||N.button===0&&!j.isPressed&&O(N,j.pointerType||N.pointerType)},T.onPointerEnter=N=>{N.pointerId===j.activePointerId&&j.target&&!j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!0,w(ns(j.target,N),j.pointerType))},T.onPointerLeave=N=>{N.pointerId===j.activePointerId&&j.target&&j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!1,k(ns(j.target,N),j.pointerType,!1),P(N))};let I=N=>{if(N.pointerId===j.activePointerId&&j.isPressed&&N.button===0&&j.target){if(wt(j.target,We(N))&&j.pointerType!=null){let q=!1,Q=setTimeout(()=>{j.isPressed&&j.target instanceof HTMLElement&&(q?R(N):(an(j.target),j.target.click()))},80);b(N.currentTarget,"click",()=>q=!0,!0),j.disposables.push(()=>clearTimeout(Q))}else R(N);j.isOverTarget=!1}},F=N=>{R(N)};T.onDragStart=N=>{wt(N.currentTarget,We(N))&&R(N)}}return T},[b,l,m,S,d,P,w,E,L]);return c.useEffect(()=>{if(!h)return;const j=qt(h.current);if(!j||!j.head||j.getElementById(si))return;const T=j.createElement("style");T.id=si;let A=jh(j);A&&(T.nonce=A),T.textContent=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-CQDryHHT.js","assets/index-BfGjMWZ8.js","assets/index-DPey6jym.css","assets/move-options-DJt1GMvN.js","assets/move-targets-Cn8KSqpp.js","assets/avatar-cbXKbnBP.js","assets/kbd-ChYmK8GY.js","assets/shield-check-DxP4d_Zx.js","assets/account-form-helpers-Bi9qE9zm.js","assets/useSignature-DZ23o5A5.js","assets/useDebouncedValue-BAAteqS8.js","assets/useFilters-Cq1W7Zus.js","assets/ErrorState-BwS1XlO_.js","assets/format-CKZmh-Ru.js","assets/useLabels-BWgV81Q6.js","assets/ConfirmDialog-BQZOydod.js","assets/circle-check-CxgRXEL3.js"])))=>i.map(i=>d[i]);
2
+ import{R as K,c as df,r as c,a as Ie,j as r,C as Wt,b as Ms,X as Ct,d as V,B as le,e as St,S as Gt,f as Tt,g as ds,L as Ps,h as Ea,i as ff,k as mf,l as fn,T as Rt,u as Jn,m as Ia,n as Il,I as Tl,F as Ta,p as Rl,o as Ra,q as hf,A as Ma,D as pf,s as mn,t as gf,v as Zn,O as xf,M as bf,w as vf,x as Ml,y as yf,z as wf,E as hn,G as Sf,H as kf,J as Cf,K as jf,N as Al,P as fs,Q as Aa,U as Nf,V as Ol,W as Ef,Y as If,Z as Tf,_ as Oa,$ as Pa,a0 as Bt,a1 as Pl,a2 as Rf,a3 as Da,a4 as Mf,a5 as Af,a6 as Of,a7 as ra,a8 as Pf,a9 as Df,aa as Me,ab as Lf,ac as Ff,ad as $f,ae as _f,af as zf,ag as Bf,ah as Uo,ai as Kf,aj as Uf,ak as qf,al as La,am as Dl,an as Ll,ao as Yt,ap as Ke,aq as it,ar as Fa,as as _e,at as $a,au as _a,av as za,aw as Kn,ax as Ae,ay as Fl,az as pn,aA as be,aB as $l,aC as Hf,aD as Fe,aE as _l,aF as Wf,aG as er,aH as tr,aI as zl,aJ as Bl,aK as Vf,aL as Mt,aM as st,aN as Qf,aO as mt,aP as Kl,aQ as is,aR as sr,aS as Gf,aT as nr,aU as Ba,aV as Ka,aW as ms,aX as rr,aY as hs,aZ as Yf,a_ as Xf,a$ as aa,b0 as Jf,b1 as Ul,b2 as As,b3 as Zf,b4 as ar,b5 as em,b6 as tm,b7 as sm,b8 as ql,b9 as Ua,ba as nm,bb as qo,bc as rm,bd as am,be as om,bf as im,bg as Kt,bh as oa,bi as lm,bj as cm,bk as um,bl as Hl,bm as dm,bn as fm,bo as mm,bp as hm,bq as Ho,br as pm,bs as gm,bt as xm,bu as bm,bv as qa,bw as ia,bx as la,by as vm,bz as Wl,bA as ym,bB as Vl,bC as wm,bD as Ql,bE as Gl,bF as Ha,bG as Sm,bH as km,bI as Cm,bJ as jm,bK as Nm,bL as Em,bM as Im,bN as Tm,bO as Rm,bP as Mm,bQ as _t,bR as Et,bS as Am}from"./index-BfGjMWZ8.js";import{P as Om,u as Wa,b as Va,f as Qa}from"./move-options-DJt1GMvN.js";import{A as kt,M as or,C as Pm}from"./avatar-cbXKbnBP.js";import{K as Is}from"./kbd-ChYmK8GY.js";import{S as gn,C as Ga,R as Dm}from"./shield-check-DxP4d_Zx.js";import{M as Yl,a as Lm}from"./account-form-helpers-Bi9qE9zm.js";import{R as Fm,u as $m}from"./useSignature-DZ23o5A5.js";import{u as ir}from"./useDebouncedValue-BAAteqS8.js";import{B as _m,u as Xt,a as Wo,b as Vo,c as zm,d as Bm,e as Km,n as Um,o as qm,f as Hm,g as Wm,S as Vm}from"./useFilters-Cq1W7Zus.js";import{E as Jt,f as Xl}from"./ErrorState-BwS1XlO_.js";import{f as Jl,a as ht,b as Zl,c as Vt,d as Un,t as Qm}from"./format-CKZmh-Ru.js";import{P as Qo,u as ec,M as ot}from"./move-targets-Cn8KSqpp.js";import{u as Ya}from"./useLabels-BWgV81Q6.js";import{C as Xa}from"./ConfirmDialog-BQZOydod.js";import{C as Gm}from"./circle-check-CxgRXEL3.js";function an(e){if(Ym())e.focus({preventScroll:!0});else{let t=Xm(e);e.focus(),Jm(t)}}let Cn=null;function Ym(){if(Cn==null){Cn=!1;try{document.createElement("div").focus({get preventScroll(){return Cn=!0,!0}})}catch{}}return Cn}function Xm(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 Jm(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const qt=e=>e?.ownerDocument??document,Qt=e=>e&&"window"in e&&e.window===e?e:qt(e).defaultView||window;function Zm(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function eh(e){return Zm(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let th=!1;function tc(){return th}function wt(e,t){if(!tc())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:eh(s)?s=s.host:s=s.parentNode}return!1}function We(e){if(tc()&&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 sh=typeof Element<"u"&&"checkVisibility"in Element.prototype;function nh(e){const t=Qt(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}=Qt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function rh(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 sc(e,t){return sh?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&nh(e)&&rh(e,t)&&(!e.parentElement||sc(e.parentElement,e))}const nc=["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"],ah=nc.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";nc.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function oh(e,t){return e.matches(ah)&&!ih(e)&&(t?.skipVisibilityCheck||sc(e))}function ih(e){let t=e;for(;t!=null;){if(t instanceof Qt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Ja=typeof document<"u"?K.useLayoutEffect:()=>{};function lh(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function ch(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function uh(e){for(;e&&!oh(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Qt(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=f=>{(We(f)===s||n)&&f.stopImmediatePropagation()},o=f=>{(We(f)===s||n)&&(f.stopImmediatePropagation(),!e&&!n&&(n=!0,an(s),u()))},i=f=>{(We(f)===e||n)&&f.stopImmediatePropagation()},l=f=>{(We(f)===e||n)&&(f.stopImmediatePropagation(),n||(n=!0,an(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function lr(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 Za(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function Zt(e){let t=null;return()=>(t==null&&(t=e()),t)}const qn=Zt(function(){return Za(/^Mac/i)}),dh=Zt(function(){return Za(/^iPhone/i)}),rc=Zt(function(){return Za(/^iPad/i)||qn()&&navigator.maxTouchPoints>1}),ac=Zt(function(){return dh()||rc()}),fh=Zt(function(){return lr(/AppleWebKit/i)&&!mh()}),mh=Zt(function(){return lr(/Chrome/i)}),oc=Zt(function(){return lr(/Android/i)}),hh=Zt(function(){return lr(/Firefox/i)});function ph(e){return e.pointerType===""&&e.isTrusted?!0:oc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function gh(e){return!oc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function on(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;hh()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(qn()?n=!0:a=!0);let l=fh()&&qn()&&!rc()?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});on.isOpening=s,an(e),e.dispatchEvent(l),on.isOpening=!1}on.isOpening=!1;let Ut=new Map,ca=new Set;function Go(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=We(n);if(!e(n)||!a)return;let o=Ut.get(a);o||(o=new Set,Ut.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=We(n);if(!e(n)||!a)return;let o=Ut.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Ut.delete(a)),Ut.size===0)){for(let i of ca)i();ca.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?Go():document.addEventListener("DOMContentLoaded",Go));function xh(){for(const[e]of Ut)"isConnected"in e&&!e.isConnected&&Ut.delete(e)}function bh(e){requestAnimationFrame(()=>{xh(),Ut.size===0?e():ca.add(e)})}function ic(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let ua=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{ua.delete(e)});function vh(e,t){if(e===t)return e;let s=ua.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=ua.get(t);return n?(n.forEach(a=>a.current=e),e):t}function yh(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=Yo(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():Yo(e[o],null)})}}}function Yo(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ds(...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]=ic(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=df(o,i):a==="id"&&o&&i?t.id=vh(o,i):a==="ref"&&o&&i?t.ref=yh(o,i):t[a]=i!==void 0?i:o}}return t}function wh(e,t){Ja(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const Sh=K.useInsertionEffect??Ja;function Or(e){const t=c.useRef(null);return Sh(()=>{t.current=e},[e]),c.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let Es="default",da="",Fn=new WeakMap;function kh(e){if(ac()){if(Es==="default"){const t=qt(e);da=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}Es="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Fn.set(e,e.style[t]),e.style[t]="none"}}function Xo(e){if(ac()){if(Es!=="disabled")return;Es="restoring",setTimeout(()=>{bh(()=>{if(Es==="restoring"){const t=qt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=da||""),da="",Es="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Fn.has(e)){let t=Fn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Fn.delete(e)}}function Jo(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Pr=new WeakMap;function Ch(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return Jo(t);if(Pr.has(t))return Pr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof Qt(s).HTMLMetaElement&&(s.nonce||s.content)||Jo(t)||void 0;return n!==void 0&&Pr.set(t,n),n}const lc=K.createContext({register:()=>{}});lc.displayName="PressResponderContext";function cc(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),n=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function jh(e){let t=c.useContext(lc);if(t){let{register:s,ref:n,...a}=t;e=Ds(a,e),s()}return wh(t,e.ref),e}class jn{#s;constructor(t,s,n,a){this.#s=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let l,u=0,m,f=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,f=n.clientY),i&&(m!=null&&f!=null?(l=m-i.left,u=f-i.top):(l=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=l,this.y=u,this.key=n.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const Zo=Symbol("linkClicked"),ei="react-aria-pressable-style",ti="data-react-aria-pressable";function Nh(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:f,allowTextSelectionOnPress:d,ref:h,...v}=jh(e),[g,p]=c.useState(!1),y=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:S}=cc(),w=c.useCallback((C,T)=>{let A=y.current;if(l||A.didFirePressStart)return!1;let I=!0;if(A.isTriggeringEvent=!0,n){let F=new jn("pressstart",T,C);n(F),I=F.shouldStopPropagation}return s&&s(!0),A.isTriggeringEvent=!1,A.didFirePressStart=!0,p(!0),I},[l,n,s]),x=c.useCallback((C,T,A=!0)=>{let I=y.current;if(!I.didFirePressStart)return!1;I.didFirePressStart=!1,I.isTriggeringEvent=!0;let F=!0;if(a){let N=new jn("pressend",T,C);a(N),F=N.shouldStopPropagation}if(s&&s(!1),p(!1),t&&A&&!l){let N=new jn("press",T,C);t(N),F&&=N.shouldStopPropagation}return I.isTriggeringEvent=!1,F},[l,a,s,t]),k=Or(x),M=c.useCallback((C,T)=>{let A=y.current;if(l)return!1;if(o){A.isTriggeringEvent=!0;let I=new jn("pressup",T,C);return o(I),A.isTriggeringEvent=!1,I.shouldStopPropagation}return!0},[l,o]),O=Or(M),j=c.useCallback(C=>{let T=y.current;if(T.isPressed&&T.target){T.didFirePressStart&&T.pointerType!=null&&x(ns(T.target,C),T.pointerType,!1),T.isPressed=!1,T.isOverTarget=!1,T.activePointerId=null,T.pointerType=null,S(),d||Xo(T.target);for(let A of T.disposables)A();T.disposables=[]}},[d,S,x]),R=Or(j);c.useEffect(()=>{l&&y.current.isPressed&&R({currentTarget:y.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let P=c.useCallback(C=>{f&&j(C)},[f,j]),E=c.useCallback(C=>{l||i?.(C)},[l,i]),L=c.useCallback((C,T)=>{if(!l&&i){let A=new MouseEvent("click",C);ch(A,T),i(lh(A))}},[l,i]),D=c.useMemo(()=>{let C=y.current,T={onKeyDown(I){if(Dr(I.nativeEvent,I.currentTarget)&&wt(I.currentTarget,We(I))){si(We(I),I.key)&&I.preventDefault();let F=!0;!C.isPressed&&!I.repeat&&(C.target=I.currentTarget,C.isPressed=!0,C.pointerType="keyboard",F=w(I,"keyboard"));let N=I.currentTarget,q=Q=>{Dr(Q,N)&&!Q.repeat&&wt(N,We(Q))&&C.target&&O(ns(C.target,Q),"keyboard")};b(qt(I.currentTarget),"keyup",ic(q,A),!0),F&&I.stopPropagation(),I.metaKey&&qn()&&C.metaKeyEvents?.set(I.key,I.nativeEvent)}else I.key==="Meta"&&(C.metaKeyEvents=new Map)},onClick(I){if(!(I&&!wt(I.currentTarget,We(I)))&&I&&I.button===0&&!C.isTriggeringEvent&&!on.isOpening){let F=!0;if(l&&I.preventDefault(),!C.ignoreEmulatedMouseEvents&&!C.isPressed&&(C.pointerType==="virtual"||ph(I.nativeEvent))){let N=w(I,"virtual"),q=O(I,"virtual"),Q=k(I,"virtual");E(I),F=N&&q&&Q}else if(C.isPressed&&C.pointerType!=="keyboard"){let N=C.pointerType||I.nativeEvent.pointerType||"virtual",q=O(ns(I.currentTarget,I),N),Q=k(ns(I.currentTarget,I),N,!0);F=q&&Q,C.isOverTarget=!1,E(I),R(I)}C.ignoreEmulatedMouseEvents=!1,F&&I.stopPropagation()}}},A=I=>{if(C.isPressed&&C.target&&Dr(I,C.target)){si(We(I),I.key)&&I.preventDefault();let F=We(I),N=wt(C.target,F);k(ns(C.target,I),"keyboard",N),N&&L(I,C.target),S(),I.key!=="Enter"&&eo(C.target)&&wt(C.target,F)&&!I[Zo]&&(I[Zo]=!0,on(C.target,I,!1)),C.isPressed=!1,C.metaKeyEvents?.delete(I.key)}else if(I.key==="Meta"&&C.metaKeyEvents?.size){let F=C.metaKeyEvents;C.metaKeyEvents=void 0;for(let N of F.values())C.target?.dispatchEvent(new KeyboardEvent("keyup",N))}};if(typeof PointerEvent<"u"){T.onPointerDown=N=>{if(N.button!==0||!wt(N.currentTarget,We(N)))return;if(gh(N.nativeEvent)){C.pointerType="virtual";return}C.pointerType=N.pointerType;let q=!0;if(!C.isPressed){C.isPressed=!0,C.isOverTarget=!0,C.activePointerId=N.pointerId,C.target=N.currentTarget,d||kh(C.target),q=w(N,C.pointerType);let Q=We(N);"releasePointerCapture"in Q&&("hasPointerCapture"in Q?Q.hasPointerCapture(N.pointerId)&&Q.releasePointerCapture(N.pointerId):Q.releasePointerCapture(N.pointerId)),b(qt(N.currentTarget),"pointerup",I,!1),b(qt(N.currentTarget),"pointercancel",F,!1)}q&&N.stopPropagation()},T.onMouseDown=N=>{if(wt(N.currentTarget,We(N))&&N.button===0){if(m){let q=uh(N.target);q&&C.disposables.push(q)}N.stopPropagation()}},T.onPointerUp=N=>{!wt(N.currentTarget,We(N))||C.pointerType==="virtual"||N.button===0&&!C.isPressed&&O(N,C.pointerType||N.pointerType)},T.onPointerEnter=N=>{N.pointerId===C.activePointerId&&C.target&&!C.isOverTarget&&C.pointerType!=null&&(C.isOverTarget=!0,w(ns(C.target,N),C.pointerType))},T.onPointerLeave=N=>{N.pointerId===C.activePointerId&&C.target&&C.isOverTarget&&C.pointerType!=null&&(C.isOverTarget=!1,k(ns(C.target,N),C.pointerType,!1),P(N))};let I=N=>{if(N.pointerId===C.activePointerId&&C.isPressed&&N.button===0&&C.target){if(wt(C.target,We(N))&&C.pointerType!=null){let q=!1,Q=setTimeout(()=>{C.isPressed&&C.target instanceof HTMLElement&&(q?R(N):(an(C.target),C.target.click()))},80);b(N.currentTarget,"click",()=>q=!0,!0),C.disposables.push(()=>clearTimeout(Q))}else R(N);C.isOverTarget=!1}},F=N=>{R(N)};T.onDragStart=N=>{wt(N.currentTarget,We(N))&&R(N)}}return T},[b,l,m,S,d,P,w,E,L]);return c.useEffect(()=>{if(!h)return;const C=qt(h.current);if(!C||!C.head||C.getElementById(ei))return;const T=C.createElement("style");T.id=ei;let A=Ch(C);A&&(T.nonce=A),T.textContent=`
3
3
  @layer {
4
- [${ni}] {
4
+ [${ti}] {
5
5
  touch-action: pan-x pan-y pinch-zoom;
6
6
  }
7
7
  }
8
- `.trim(),j.head.prepend(T)},[h]),c.useEffect(()=>{let j=y.current;return()=>{d||Zo(j.target??void 0);for(let T of j.disposables)T();j.disposables=[]}},[d]),{isPressed:u||g,pressProps:Ls(v,D,{[ni]:!0})}}function so(e){return e.tagName==="A"&&e.hasAttribute("href")}function Dr(e,t){const{key:s,code:n}=e,a=t,o=a.getAttribute("role");return(s==="Enter"||s===" "||s==="Spacebar"||n==="Space")&&!(a instanceof Qt(a).HTMLInputElement&&!dc(a,s)||a instanceof Qt(a).HTMLTextAreaElement||a.isContentEditable)&&!((o==="link"||!o&&so(a))&&s!=="Enter")}function ns(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 Eh(e){return e instanceof HTMLInputElement?!1:e instanceof HTMLButtonElement?e.type!=="submit"&&e.type!=="reset":!so(e)}function ri(e,t){return e instanceof HTMLInputElement?!dc(e,t):Eh(e)}const Ih=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function dc(e,t){return e.type==="checkbox"||e.type==="radio"?t===" ":Ih.has(e.type)}let Th=0;const Lr=new Map;function Rh(e){let[t,s]=c.useState();return eo(()=>{if(!e)return;let n=Lr.get(e);if(n)s(n.element.id);else{let a=`react-aria-description-${Th++}`;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},Lr.set(e,n)}return n.refCount++,()=>{n&&--n.refCount===0&&(n.element.remove(),Lr.delete(e))}},[e]),{"aria-describedby":e?t:void 0}}const Mh=500;function Ah(e){let{isDisabled:t,onLongPressStart:s,onLongPressEnd:n,onLongPress:a,threshold:o=Mh,accessibilityDescription:i}=e;const l=c.useRef(void 0);let{addGlobalListener:u,removeGlobalListener:m}=uc(),{pressProps:f}=Nh({isDisabled:t,onPressStart(h){if(h.continuePropagation(),(h.pointerType==="mouse"||h.pointerType==="touch")&&(s&&s({...h,type:"longpressstart"}),l.current=setTimeout(()=>{h.target.dispatchEvent(new PointerEvent("pointercancel",{bubbles:!0})),qt(h.target).activeElement!==h.target&&an(h.target),a&&a({...h,type:"longpress"}),l.current=void 0},o),h.pointerType==="touch")){let v=p=>{p.preventDefault()},g=Qt(h.target);u(h.target,"contextmenu",v,{once:!0}),u(g,"pointerup",()=>{setTimeout(()=>{m(h.target,"contextmenu",v)},30)},{once:!0})}},onPressEnd(h){l.current&&clearTimeout(l.current),n&&(h.pointerType==="mouse"||h.pointerType==="touch")&&n({...h,type:"longpressend"})}}),d=Rh(a&&!t?i:void 0);return{longPressProps:Ls(f,d)}}const cr=Ie("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 Oh=Ie("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);const fc=Ie("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 Ph=Ie("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 ai=Ie("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 mc=Ie("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 hc=Ie("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);const pc=Ie("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 gc=Ie("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 xc=Ie("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 Dh=Ie("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 ur=Ie("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 Lh=Ie("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 Fh=Ie("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const dr=Ie("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 bc=Ie("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=Ie("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 yc=Ie("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 wc=Ie("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=Ie("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 $h=Ie("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 _h=Ie("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 zh=Ie("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 Bh=Ie("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"}]]),Kh=({address:e,showTrustedBadge:t=!1})=>{const s=t?r.jsx(cr,{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]})},Uh=({label:e,addresses:t,showTrustedBadge:s=!1})=>{const[n,a]=c.useState(!1);if(t.length===0)return null;const o=t.length>3,i=l=>{const u=s&&l.flags?.trusted?.value===!0;return r.jsx(Kh,{address:l,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((l,u)=>r.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))}):r.jsx("div",{className:"truncate",children:t.map((l,u)=>r.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))})}),o&&r.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),a(!n)},className:"shrink-0 text-fg-muted hover:text-fg transition-colors","aria-label":n?"Collapse":"Expand",children:n?r.jsx(Wt,{className:"h-4 w-4"}):r.jsx(As,{className:"h-4 w-4"})})]})},qh=({email:e,displayName:t,onRemove:s,className:n})=>r.jsxs("span",{className:V("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(jt,{className:"size-3"})})]}),Hh={unknown:{label:"Unknown sender",tone:"neutral"},wellknown:{label:"Known sender",tone:"positive"},vip:{label:"VIP",tone:"accent"}};function vs({label:e,children:t,className:s}){return r.jsxs("section",{className:V("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 Wh({sender:e}){const t=Hh[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(kt,{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(St,{tone:"danger",dot:!0,children:"Address couldn't be verified"}):r.jsx(St,{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 Vh({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(gn,{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($h,{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(le,{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 ys({icon:e,label:t,active:s,danger:n,onClick:a}){const o=a===void 0;return r.jsxs("button",{type:"button",onClick:a,disabled:o,className:V("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",o&&"cursor-not-allowed opacity-50 hover:border-line"),children:[e,t]})}const Qh={sender:"matched: sender",recipient:"matched: recipient",subject:"matched: subject",attachment:"matched: attachment",body:"matched: body",entities:"matched: entities"};function Sc({data:e,onClose:t,onShowSimilar:s,actions:n,similarState:a="ready",similarLinkComponent:o,className:i,hideCloseButton:l=!1}){const{sender:u,authenticity:m,category:f,flags:d={},similar:h}=e,v=m.verdict==="mismatch";return r.jsxs("aside",{className:V("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"}),!l&&r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(jt,{className:"size-3.5"}),onClick:t,"aria-label":"Collapse intelligence sidebar"})]}),r.jsx(vs,{label:"Sender",children:r.jsx(Wh,{sender:u})}),r.jsx(vs,{label:"Authenticity",children:r.jsx(Vh,{auth:m,onShowSimilar:s})}),r.jsx(vs,{label:"Category",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(St,{tone:v?"danger":"neutral",children:f.value}),f.overridden&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"your override"}),r.jsx("button",{type:"button",className:V("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.jsx(vs,{label:"Quick actions",children:r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[r.jsx(ys,{icon:r.jsx(Gt,{className:"size-3.5"}),label:"VIP",active:d.vip,onClick:n?.onToggleVip}),r.jsx(ys,{icon:r.jsx(fc,{className:"size-3.5"}),label:"Mute",active:d.muted,onClick:n?.onToggleMute}),r.jsx(ys,{icon:r.jsx(Oh,{className:"size-3.5"}),label:"Block",active:d.blocked,danger:!0,onClick:n?.onToggleBlock}),r.jsx(ys,{icon:r.jsx(Lh,{className:"size-3.5"}),label:"Unsubscribe",active:d.unsubscribed,onClick:n?.onToggleUnsubscribe}),n?.onNotSpam&&r.jsx(ys,{icon:r.jsx(Dh,{className:"size-3.5"}),label:"Not spam",onClick:n.onNotSpam}),n?.onMarkSpam&&r.jsx(ys,{icon:r.jsx(_h,{className:"size-3.5"}),label:"Mark spam",danger:!0,onClick:n.onMarkSpam})]})}),(a!=="ready"||h.length>0)&&r.jsx(vs,{label:"Similar messages",children:a==="loading"?r.jsx("div",{className:"animate-pulse space-y-2",children:Array.from({length:3}).map((g,p)=>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"})]},p))}):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:h.map(g=>{const p="block w-full rounded-md px-1 py-1 text-left hover:bg-surface-sunken",y=`Open message from ${g.fromName||"unknown sender"}: ${g.subject}`,b=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:g.fromName}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:g.timeLabel})]}),r.jsx("div",{className:"truncate text-xs text-fg-muted",children:g.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:Qh[g.matched]})]});return r.jsx("li",{children:o?o({mailboxId:g.mailboxId,messageId:g.id,className:p,ariaLabel:y,children:b}):r.jsx("div",{className:p,children:b})},g.id)})})}),r.jsx(vs,{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(Tt,{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(Tt,{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 Hn=e=>({shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey}),oi=e=>e.shiftKey||e.metaKey||e.ctrlKey,Gh=e=>e.shiftKey?"range":e.metaKey||e.ctrlKey?"toggle":"open",no=(e,t)=>!t&&e>0,Yh=(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)},Xh=(e,t,s,n)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:n,Jh=(e,t)=>{const s=new Set(t),n=new Set;for(const a of e)s.has(a)&&n.add(a);return n},kc=(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]},jc=e=>{const[t,s]=c.useState(()=>new Set(e?.initialSelectedIds)),[n,a]=c.useState(void 0),o=c.useCallback(p=>t.has(p),[t]),i=c.useCallback(p=>{a(p),s(y=>{const b=new Set(y);return b.has(p)?b.delete(p):b.add(p),b})},[]),l=c.useCallback(p=>{a(p),s(y=>{if(y.has(p))return y;const b=new Set(y);return b.add(p),b})},[]),u=c.useCallback(p=>{s(y=>{if(!y.has(p))return y;const b=new Set(y);return b.delete(p),b})},[]),m=c.useCallback(p=>{s(new Set(p))},[]),f=c.useCallback(()=>{a(void 0),s(new Set)},[]),d=c.useCallback(p=>{s(y=>p.every(S=>y.has(S))?new Set:new Set(p))},[]),h=c.useCallback(p=>{a(p)},[]),v=c.useCallback(p=>{s(y=>{if(y.size===0)return y;const b=Jh(y,p);return b.size===y.size?y:b})},[]),g=c.useCallback((p,y,b)=>{const S=Xh(p,n,b,y);s(w=>{const x=Yh(p,S,y);if(x.length===0)return w;const k=new Set(w);for(const M of x)k.add(M);return k}),a(S)},[n]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:l,deselect:u,selectAll:m,clearSelection:f,toggleAll:d,selectRange:g,setAnchor:h,anchorId:n,intersectWith:v}},Zh=[{keys:["j","k"],label:"navigate"},{keys:["m"],label:"mute"},{keys:["?"],label:"all shortcuts"}];function Cc({hints:e=Zh,className:t}){return r.jsx("footer",{className:V("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(ep,{hint:s},s.label))})}function ep({hint:e}){return r.jsxs("span",{className:"flex items-center gap-1",children:[e.keys.map(t=>r.jsx(Ts,{children:t},t)),r.jsx("span",{children:e.label})]})}function tp(){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 sp({filter:e,scopeLabel:t,searchQuery:s}){const n=s?.trim();return e?r.jsxs(ii,{children:[r.jsx("p",{className:"font-medium text-fg",children:ap(e.label,t,n)}),r.jsx("p",{className:"mt-1 text-sm text-fg-muted",children:np[e.reach]}),r.jsx(le,{variant:"secondary",size:"sm",className:"mt-4",onClick:e.onClear,children:"Clear filter"})]}):r.jsx(ii,{children:r.jsx("p",{className:"text-fg-muted",children:rp(n,t)})})}const np={"whole-folder":"Every message in this folder was checked.","loaded-pages":"Only the messages loaded so far were checked."};function rp(e,t){return e?"No messages match your search":t?`No messages in ${t}`:"No messages in this mailbox"}function ap(e,t,s){return s?`No results for “${s}” in ${e}`:t?`No ${e} mail in ${t}`:`No ${e} mail`}function ii({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 op(){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(Ds,{className:"size-4 animate-spin","aria-hidden":"true"}),r.jsx("span",{children:"Loading more…"})]})}function ip({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(ds,{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(le,{variant:"secondary",size:"sm",onClick:t,children:"Retry"}),s&&r.jsx(le,{variant:"ghost",size:"sm",onClick:s,children:"Report a problem"})]})]})})}const Nc="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",Ec=({active:e,focused:t})=>V("relative flex h-8 w-full items-center gap-2 px-row-inset text-left",Nc,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})=>V("relative flex w-full items-start gap-3 py-2 pl-5 pr-row-inset text-left transition-colors",Nc,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 Ic({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(Gt,{className:"size-3 fill-warning text-warning"}):t?r.jsx("span",{className:"size-1.5 rounded-full bg-accent"}):null}),r.jsx("span",{className:V("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:V(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(dr,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"w-11 shrink-0 text-right text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]})}function li(e,t){const s=t?.trim();if(!s)return e;const n=e.toLowerCase(),a=s.toLowerCase(),o=[];let i=0,l=n.indexOf(a,i),u=0;for(;l!==-1;)l>i&&o.push(e.slice(i,l)),o.push(r.jsx("mark",{className:"bg-transparent font-semibold text-fg",children:e.slice(l,l+a.length)},u++)),i=l+a.length,l=n.indexOf(a,i);return i<e.length&&o.push(e.slice(i)),o}function ln({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:V("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:V("truncate text-sm",n?"text-fg":"text-fg-muted"),children:li(e.subject,s)}),e.suspicious&&r.jsx(Fs,{className:"size-3.5 shrink-0 text-danger"}),e.starred&&r.jsx(Gt,{className:"size-3 shrink-0 fill-warning text-warning"}),e.hasAttachment&&r.jsx(dr,{className:"size-3 shrink-0 text-fg-subtle"})]}),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:li(e.snippet,s)}),e.category&&e.category!=="personal"&&r.jsx(St,{tone:ff[e.category],className:"shrink-0",children:e.category}),e.labels?.map(a=>r.jsx(mf,{label:a,className:"max-w-20"},a.labelId)),t]})]})}function lp({thread:e,selection:t}){if(!t)return r.jsx(kt,{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(kt,{name:e.fromName,email:e.fromEmail,size:"sm",className:V("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:V("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(fn,{className:"size-3"})})]})}function ro({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(lp,{thread:e,selection:t}),r.jsx(ln,{thread:e,badge:s,highlightQuery:n})]})}function cp({thread:e,active:t,focused:s,onClick:n}){return r.jsx("button",{type:"button",...Ea,onClick:n,className:Ec({active:t,focused:s}),children:r.jsx(Ic,{thread:e})})}function up({thread:e,active:t,focused:s,selection:n,onClick:a}){return r.jsx("button",{type:"button",...Ea,onClick:a,className:V("group",$s({active:t,focused:s})),children:r.jsx(ro,{thread:e,selection:n})})}let Rs;const dp=5e3;function Tc(e){e.preventDefault(),Wn()}function Wn(){Rs!==void 0&&(clearTimeout(Rs),Rs=void 0,document.removeEventListener("contextmenu",Tc,!0),document.removeEventListener("pointerup",Wn,!0))}function fp(){Rs===void 0?(document.addEventListener("contextmenu",Tc,!0),document.addEventListener("pointerup",Wn,!0)):clearTimeout(Rs),Rs=setTimeout(Wn,dp)}function Rc({onLongPress:e,isDisabled:t,delayMs:s=500,accessibilityDescription:n}){const{longPressProps:a}=Ah({isDisabled:t,threshold:s,accessibilityDescription:n,onLongPress:e}),o=c.useCallback(i=>{i.pointerType!=="touch"&&i.pointerType!=="pen"||fp()},[]);return{longPressProps:Ls(a,{onPointerDown:o})}}const ls=72,ci=10,mp=ls/2,ui="__swipeableRowAxisCancel";function di(e){return e==="leading"?ls:e==="trailing"?-ls:0}function hp(e){return e>=ls/2?"leading":e<=-ls/2?"trailing":"none"}function Mc({thread:e,selectionMode:t,checked:s,active:n,peek:a,onPeek:o,onToggleCheck:i,onLongPress:l,onOpen:u,onAct:m}){const f=c.useRef(null),[d,h]=c.useState(null),{longPressProps:v}=Rc({onLongPress:l,isDisabled:t,accessibilityDescription:"Select message"}),g=E=>{const L=new PointerEvent("pointercancel",{bubbles:!0});L[ui]=!0,E.currentTarget.dispatchEvent(L)},w=Ls(v,{onPointerDown:E=>{f.current={startX:E.clientX,startY:E.clientY,axis:"none",escaped:!1}},onPointerMove:E=>{if(t)return;const L=f.current;if(!L)return;const D=E.clientX-L.startX,j=E.clientY-L.startY;if(L.axis==="none"&&(Math.abs(j)>ci&&Math.abs(j)>Math.abs(D)?L.axis="vertical":Math.abs(D)>ci&&Math.abs(D)>Math.abs(j)&&(L.axis="horizontal",E.currentTarget.setPointerCapture(E.pointerId))),L.axis==="none")return;const T=L.axis==="horizontal"?Math.abs(D):Math.abs(j);if(!L.escaped&&T>mp&&(L.escaped=!0,g(E)),L.axis!=="horizontal")return;const A=di(a),I=Math.max(-ls,Math.min(ls,A+D));h(I)},onPointerUp:E=>{const L=f.current;f.current=null;const D=d;if(h(null),!!L){if(L.axis!=="none"&&!L.escaped&&g(E),L.axis==="horizontal"){D!==null&&o(hp(D));return}if(L.axis!=="vertical"){if(t){i();return}if(a!=="none"){o("none");return}u()}}},onPointerCancel:E=>{E.nativeEvent[ui]||(f.current=null,h(null))}}),x=d??di(a),k=x>0?"leading":x<0?"trailing":"none",M=V("relative touch-pan-y bg-surface","select-none",$s({active:s||n})),O={transform:x!==0?`translateX(${x}px)`:void 0,transition:d===null?"transform 150ms ease":"none",minHeight:44},C=!e.isRead,R=E=>E.stopPropagation(),P=t?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:V("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(fn,{className:"size-3.5"})}),r.jsx(ln,{thread:e})]}):r.jsxs(r.Fragment,{children:[C&&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:R,onPointerMove:R,onPointerUp:R,onClick:E=>{E.preventDefault(),E.stopPropagation(),l()},onKeyDown:E=>{E.key!=="Enter"&&E.key!==" "||(E.preventDefault(),E.stopPropagation(),l())},className:"-m-2 inline-flex size-11 shrink-0 items-center justify-center rounded-full",children:r.jsx(kt,{name:e.fromName,email:e.fromEmail,size:"sm"})}),r.jsx(ln,{thread:e})]});return r.jsxs("div",{className:"relative overflow-hidden",children:[k==="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(Xl,{className:"size-6"}):r.jsx(ur,{className:"size-6"})}),k==="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(Rt,{className:"size-6"})}),r.jsx("button",{type:"button",role:t?"checkbox":void 0,"aria-checked":t?s:void 0,"data-message-row":!0,...w,className:M,style:O,children:P})]})}function pp({sections:e,selectedThreadId:t,selectionMode:s,checkedIds:n,initialPeek:a,onToggleCheck:o,onEnterSelection:i,onOpenThread:l,onRefresh:u,refreshing:m,busy:f=!1}){const[d,h]=c.useState(new Set),[v,g]=c.useState(new Map),p=e.flatMap(w=>w.threads).filter(w=>!d.has(w.id)).map(w=>{const x=v.get(w.id);return x===void 0?w:{...w,isRead:x}}),[y,b]=c.useState(a&&a!=="none"&&p[1]?{id:p[1].id,side:a}:null),S=(w,x)=>{if(x==="trailing")h(k=>new Set(k).add(w));else{const k=p.find(M=>M.id===w);g(M=>new Map(M).set(w,!k?.isRead))}b(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(bc,{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(w=>r.jsx("div",{className:f?"pointer-events-none opacity-50":void 0,children:r.jsx(Mc,{thread:w,selectionMode:s,checked:n.has(w.id),active:w.id===t,peek:y?.id===w.id?y.side:"none",onPeek:x=>b(x==="none"?null:{id:w.id,side:x}),onToggleCheck:()=>o(w.id),onLongPress:()=>i(w.id),onOpen:()=>l(w.id),onAct:x=>S(w.id,x)})},w.id))}),!s&&!m&&!f&&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 gp=new Set;function Ac({listTitle:e,listMeta:t,sections:s,briefFilters:n,flatList:a,listState:o="ready",searchQuery:i,listFilter:l,listScopeLabel:u,errorMessage:m,onRetry:f,onReportError:d,briefCategory:h,selectedThreadId:v,density:g="comfortable",onSelectThread:p,onSelectBriefCategory:y,onOpenNav:b,isDesktop:S,initialTouchState:w,selection:x,selectionBar:k,paneOverlay:M,listBody:O,hideHeader:C=!1}){const R=g==="compact"?cp:up,P=c.useRef(null);Jn({containerRef:P,itemSelector:Ia});const E=!S&&!n&&o==="ready",[L,D]=c.useState(!1),j=w==="peek-trailing"?"trailing":w==="peek-leading"?"leading":void 0,T=()=>{D(!0),setTimeout(()=>D(!1),1400)},A=x?.selectedIds??gp,I=x?.onToggle,F=x?.onRowSelect,N=no(A.size,S),q=c.useCallback(U=>{if(I)return{checked:A.has(U),onToggle:z=>{z.preventDefault(),z.stopPropagation(),I(U)}}},[A,I]),Q=c.useCallback((U,z)=>F?.(U,Hn(z))?(z.preventDefault(),z.shiftKey&&window.getSelection()?.removeAllRanges(),!0):!1,[F]),ae=c.useCallback(({thread:U,active:z,onClick:ee})=>r.jsx(R,{thread:U,active:z,selection:q(U.id),onClick:me=>{Q(U.id,me)||ee?.()}}),[R,q,Q]);return r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[k??(C?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(le,{variant:"ghost",size:"sm",icon:r.jsx(or,{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(tp,{})}):o==="empty"?r.jsx(sp,{filter:l,scopeLabel:u,searchQuery:i}):o==="error"?r.jsx(ip,{message:m,onRetry:f,onReport:d}):n?r.jsx(Al,{sections:s,briefCategory:h,selectedThreadId:v,Row:ae,onSelectThread:p,onSelectBriefCategory:y}):O??(E?r.jsx(pp,{sections:s,selectedThreadId:v,selectionMode:N,checkedIds:A,initialPeek:j,onToggleCheck:U=>I?.(U),onEnterSelection:U=>I?.(U),onOpenThread:U=>p?.(U),onRefresh:T,refreshing:L}):r.jsx("div",{ref:P,className:"flex-1 overflow-y-auto",children:s.map(U=>r.jsxs("div",{children:[!a&&U.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:U.label}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:U.threads.length})]}),r.jsx("div",{className:"divide-y divide-line",children:U.threads.map(z=>r.jsx(R,{thread:z,active:z.id===v,selection:q(z.id),onClick:ee=>{Q(z.id,ee)||p?.(z.id)}},z.id))})]},U.id))})),S&&r.jsx(Cc,{}),M]})}function ao({triggerLabel:e,triggerIcon:t,triggerText:s,items:n,align:a="end",touch:o=!0,className:i,triggerClassName:l,nested:u=!1,children:m}){const[f,d]=c.useState(!1),h=c.useRef(null);return c.useEffect(()=>{if(!f)return;const v=p=>{h.current&&!h.current.contains(p.target)&&d(!1)},g=p=>{p.key==="Escape"&&d(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",g),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",g)}},[f]),n.length===0&&!m?null:r.jsxs("div",{ref:h,className:V("relative",i),...u?{role:"none"}:{},children:[r.jsx(le,{variant:"ghost",size:"sm",icon:t??r.jsx(pc,{className:"size-5"}),onClick:()=>d(v=>!v),"aria-label":e,"aria-haspopup":"menu","aria-expanded":f,...u?{role:"menuitem"}:{},className:V(o&&"min-h-11 min-w-11 px-0",l),children:s}),f&&r.jsxs("div",{role:"menu",className:V("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:()=>{d(!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 Vs="min-h-11 min-w-11 px-0";function Oc({hasThread:e,onReply:t,onReplyAll:s,onForward:n,isStarred:a,onToggleStar:o,onDelete:i,isRead:l,onToggleRead:u,moveSlot:m,overflowItems:f=[],onUnavailable:d,unavailableHint:h,className:v}){const g=(y,b)=>()=>{if(!e){d?.(y);return}b?.()},p=u?[{key:"toggle-read",label:l?"Mark as unread":"Mark as read",icon:l?r.jsx(Xl,{className:"size-4"}):r.jsx(ur,{className:"size-4"}),onSelect:g("toggleRead",u)}]:[];return r.jsxs("div",{className:V("relative",v),children:[r.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-0.5 bg-canvas px-1",children:[r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(yc,{className:"size-5"}),onClick:g("reply",t),"aria-label":"Reply",title:"Reply",className:Vs}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(vc,{className:"size-5"}),onClick:g("replyAll",s),"aria-label":"Reply all",title:"Reply all",className:Vs}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(gc,{className:"size-5"}),onClick:g("forward",n),"aria-label":"Forward",title:"Forward",className:Vs}),r.jsx("div",{className:"flex-1"}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Gt,{className:V("size-5",a&&"fill-warning text-warning")}),onClick:g("star",o),"aria-label":a?"Unstar":"Star","aria-pressed":a,title:a?"Unstar":"Star",className:Vs}),m,r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Rt,{className:"size-5"}),onClick:g("delete",i),"aria-label":"Move to Trash",title:"Move to Trash",className:Vs}),r.jsx(ao,{triggerLabel:"More actions",items:[...p,...f]})]}),!e&&h&&r.jsx("p",{role:"status",className:"bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:h})]})}function xp({open:e=!1,enabled:t=!0,onToggle:s,className:n}){return r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Ol,{className:"size-4"}),title:"Intelligence","aria-label":e?"Hide intelligence sidebar":"Show intelligence sidebar","aria-pressed":e,disabled:!t,onClick:s,className:V(e&&"bg-accent-2-soft text-accent-2",n)})}function bp({hasThread:e,onUnavailable:t,unavailableHint:s,isStarred:n,showTriage:a=!0,onReply:o,onReplyAll:i,onForward:l,onDelete:u,onToggleStar:m,moveSlot:f,onMove:d,replyTitle:h="Reply (r)",replyAllTitle:v="Reply all (a)",forwardTitle:g="Forward (f)",deleteTitle:p="Move to Trash (#)",flagTitle:y="Star (s)",children:b,className:S}){const w=(x,k)=>()=>{if(!e){t?.(x);return}k?.()};return r.jsxs("div",{className:"relative",children:[r.jsxs("header",{className:V("flex h-pane-header shrink-0 items-center gap-1 border-b border-line bg-surface px-3",S),children:[r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(yc,{className:"size-4"}),title:h,"aria-label":"Reply",onClick:w("reply",o)}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(vc,{className:"size-4"}),title:v,"aria-label":"Reply all",onClick:w("replyAll",i)}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(gc,{className:"size-4"}),title:g,"aria-label":"Forward",onClick:w("forward",l)}),a&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"mx-1 h-4 w-px bg-line","aria-hidden":!0}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Rt,{className:"size-4"}),title:p,"aria-label":"Move to Trash",onClick:w("delete",u)}),f??r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Ta,{className:"size-4"}),title:"Move to mailbox","aria-label":"Move to mailbox",onClick:w("move",d)}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Gt,{className:V("size-4",n&&"fill-warning text-warning")}),title:y,"aria-label":"Star",onClick:w("flag",m)})]}),r.jsx("div",{className:"flex-1"}),b]}),!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 vp=(e,t)=>{const n=e==="newsletter"||e==="marketing"||t;return{framed:n,isPlain:!n}},yp=()=>`
8
+ `.trim(),C.head.prepend(T)},[h]),c.useEffect(()=>{let C=y.current;return()=>{d||Xo(C.target??void 0);for(let T of C.disposables)T();C.disposables=[]}},[d]),{isPressed:u||g,pressProps:Ds(v,D,{[ti]:!0})}}function eo(e){return e.tagName==="A"&&e.hasAttribute("href")}function Dr(e,t){const{key:s,code:n}=e,a=t,o=a.getAttribute("role");return(s==="Enter"||s===" "||s==="Spacebar"||n==="Space")&&!(a instanceof Qt(a).HTMLInputElement&&!uc(a,s)||a instanceof Qt(a).HTMLTextAreaElement||a.isContentEditable)&&!((o==="link"||!o&&eo(a))&&s!=="Enter")}function ns(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 Eh(e){return e instanceof HTMLInputElement?!1:e instanceof HTMLButtonElement?e.type!=="submit"&&e.type!=="reset":!eo(e)}function si(e,t){return e instanceof HTMLInputElement?!uc(e,t):Eh(e)}const Ih=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function uc(e,t){return e.type==="checkbox"||e.type==="radio"?t===" ":Ih.has(e.type)}let Th=0;const Lr=new Map;function Rh(e){let[t,s]=c.useState();return Ja(()=>{if(!e)return;let n=Lr.get(e);if(n)s(n.element.id);else{let a=`react-aria-description-${Th++}`;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},Lr.set(e,n)}return n.refCount++,()=>{n&&--n.refCount===0&&(n.element.remove(),Lr.delete(e))}},[e]),{"aria-describedby":e?t:void 0}}const Mh=500;function Ah(e){let{isDisabled:t,onLongPressStart:s,onLongPressEnd:n,onLongPress:a,threshold:o=Mh,accessibilityDescription:i}=e;const l=c.useRef(void 0);let{addGlobalListener:u,removeGlobalListener:m}=cc(),{pressProps:f}=Nh({isDisabled:t,onPressStart(h){if(h.continuePropagation(),(h.pointerType==="mouse"||h.pointerType==="touch")&&(s&&s({...h,type:"longpressstart"}),l.current=setTimeout(()=>{h.target.dispatchEvent(new PointerEvent("pointercancel",{bubbles:!0})),qt(h.target).activeElement!==h.target&&an(h.target),a&&a({...h,type:"longpress"}),l.current=void 0},o),h.pointerType==="touch")){let v=p=>{p.preventDefault()},g=Qt(h.target);u(h.target,"contextmenu",v,{once:!0}),u(g,"pointerup",()=>{setTimeout(()=>{m(h.target,"contextmenu",v)},30)},{once:!0})}},onPressEnd(h){l.current&&clearTimeout(l.current),n&&(h.pointerType==="mouse"||h.pointerType==="touch")&&n({...h,type:"longpressend"})}}),d=Rh(a&&!t?i:void 0);return{longPressProps:Ds(f,d)}}const cr=Ie("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 Oh=Ie("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);const dc=Ie("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 Ph=Ie("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 fc=Ie("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 mc=Ie("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 hc=Ie("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);const pc=Ie("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 gc=Ie("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 xc=Ie("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 Dh=Ie("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 ur=Ie("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 Lh=Ie("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 Fh=Ie("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const dr=Ie("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 bc=Ie("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=Ie("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 yc=Ie("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 wc=Ie("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 Ls=Ie("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 $h=Ie("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 _h=Ie("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 zh=Ie("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 Bh=Ie("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"}]]),Kh=({address:e,showTrustedBadge:t=!1})=>{const s=t?r.jsx(cr,{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]})},Uh=({label:e,addresses:t,showTrustedBadge:s=!1})=>{const[n,a]=c.useState(!1);if(t.length===0)return null;const o=t.length>3,i=l=>{const u=s&&l.flags?.trusted?.value===!0;return r.jsx(Kh,{address:l,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((l,u)=>r.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))}):r.jsx("div",{className:"truncate",children:t.map((l,u)=>r.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))})}),o&&r.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),a(!n)},className:"shrink-0 text-fg-muted hover:text-fg transition-colors","aria-label":n?"Collapse":"Expand",children:n?r.jsx(Wt,{className:"h-4 w-4"}):r.jsx(Ms,{className:"h-4 w-4"})})]})},qh=({email:e,displayName:t,onRemove:s,className:n})=>r.jsxs("span",{className:V("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(Ct,{className:"size-3"})})]}),Hh={unknown:{label:"Unknown sender",tone:"neutral"},wellknown:{label:"Known sender",tone:"positive"},vip:{label:"VIP",tone:"accent"}};function vs({label:e,children:t,className:s}){return r.jsxs("section",{className:V("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 Wh({sender:e}){const t=Hh[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(kt,{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(St,{tone:"danger",dot:!0,children:"Address couldn't be verified"}):r.jsx(St,{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 Vh({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(gn,{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($h,{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(Ls,{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(le,{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 ys({icon:e,label:t,active:s,danger:n,onClick:a}){const o=a===void 0;return r.jsxs("button",{type:"button",onClick:a,disabled:o,className:V("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",o&&"cursor-not-allowed opacity-50 hover:border-line"),children:[e,t]})}const Qh={sender:"matched: sender",recipient:"matched: recipient",subject:"matched: subject",attachment:"matched: attachment",body:"matched: body",entities:"matched: entities"};function Sc({data:e,onClose:t,onShowSimilar:s,actions:n,similarState:a="ready",similarLinkComponent:o,className:i,hideCloseButton:l=!1}){const{sender:u,authenticity:m,category:f,flags:d={},similar:h}=e,v=m.verdict==="mismatch";return r.jsxs("aside",{className:V("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"}),!l&&r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Ct,{className:"size-3.5"}),onClick:t,"aria-label":"Collapse intelligence sidebar"})]}),r.jsx(vs,{label:"Sender",children:r.jsx(Wh,{sender:u})}),r.jsx(vs,{label:"Authenticity",children:r.jsx(Vh,{auth:m,onShowSimilar:s})}),r.jsx(vs,{label:"Category",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(St,{tone:v?"danger":"neutral",children:f.value}),f.overridden&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"your override"}),r.jsx("button",{type:"button",className:V("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.jsx(vs,{label:"Quick actions",children:r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[r.jsx(ys,{icon:r.jsx(Gt,{className:"size-3.5"}),label:"VIP",active:d.vip,onClick:n?.onToggleVip}),r.jsx(ys,{icon:r.jsx(dc,{className:"size-3.5"}),label:"Mute",active:d.muted,onClick:n?.onToggleMute}),r.jsx(ys,{icon:r.jsx(Oh,{className:"size-3.5"}),label:"Block",active:d.blocked,danger:!0,onClick:n?.onToggleBlock}),r.jsx(ys,{icon:r.jsx(Lh,{className:"size-3.5"}),label:"Unsubscribe",active:d.unsubscribed,onClick:n?.onToggleUnsubscribe}),n?.onNotSpam&&r.jsx(ys,{icon:r.jsx(Dh,{className:"size-3.5"}),label:"Not spam",onClick:n.onNotSpam}),n?.onMarkSpam&&r.jsx(ys,{icon:r.jsx(_h,{className:"size-3.5"}),label:"Mark spam",danger:!0,onClick:n.onMarkSpam})]})}),(a!=="ready"||h.length>0)&&r.jsx(vs,{label:"Similar messages",children:a==="loading"?r.jsx("div",{className:"animate-pulse space-y-2",children:Array.from({length:3}).map((g,p)=>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"})]},p))}):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:h.map(g=>{const p="block w-full rounded-md px-1 py-1 text-left hover:bg-surface-sunken",y=`Open message from ${g.fromName||"unknown sender"}: ${g.subject}`,b=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:g.fromName}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:g.timeLabel})]}),r.jsx("div",{className:"truncate text-xs text-fg-muted",children:g.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:Qh[g.matched]})]});return r.jsx("li",{children:o?o({mailboxId:g.mailboxId,messageId:g.id,className:p,ariaLabel:y,children:b}):r.jsx("div",{className:p,children:b})},g.id)})})}),r.jsx(vs,{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(Tt,{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(Tt,{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 Hn=e=>({shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey}),ni=e=>e.shiftKey||e.metaKey||e.ctrlKey,Gh=e=>e.shiftKey?"range":e.metaKey||e.ctrlKey?"toggle":"open",to=(e,t)=>!t&&e>0,Yh=(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)},Xh=(e,t,s,n)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:n,Jh=(e,t)=>{const s=new Set(t),n=new Set;for(const a of e)s.has(a)&&n.add(a);return n},kc=(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]},Cc=e=>{const[t,s]=c.useState(()=>new Set(e?.initialSelectedIds)),[n,a]=c.useState(void 0),o=c.useCallback(p=>t.has(p),[t]),i=c.useCallback(p=>{a(p),s(y=>{const b=new Set(y);return b.has(p)?b.delete(p):b.add(p),b})},[]),l=c.useCallback(p=>{a(p),s(y=>{if(y.has(p))return y;const b=new Set(y);return b.add(p),b})},[]),u=c.useCallback(p=>{s(y=>{if(!y.has(p))return y;const b=new Set(y);return b.delete(p),b})},[]),m=c.useCallback(p=>{s(new Set(p))},[]),f=c.useCallback(()=>{a(void 0),s(new Set)},[]),d=c.useCallback(p=>{s(y=>p.every(S=>y.has(S))?new Set:new Set(p))},[]),h=c.useCallback(p=>{a(p)},[]),v=c.useCallback(p=>{s(y=>{if(y.size===0)return y;const b=Jh(y,p);return b.size===y.size?y:b})},[]),g=c.useCallback((p,y,b)=>{const S=Xh(p,n,b,y);s(w=>{const x=Yh(p,S,y);if(x.length===0)return w;const k=new Set(w);for(const M of x)k.add(M);return k}),a(S)},[n]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:l,deselect:u,selectAll:m,clearSelection:f,toggleAll:d,selectRange:g,setAnchor:h,anchorId:n,intersectWith:v}},Zh=[{keys:["j","k"],label:"navigate"},{keys:["m"],label:"mute"},{keys:["?"],label:"all shortcuts"}];function jc({hints:e=Zh,className:t}){return r.jsx("footer",{className:V("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(ep,{hint:s},s.label))})}function ep({hint:e}){return r.jsxs("span",{className:"flex items-center gap-1",children:[e.keys.map(t=>r.jsx(Is,{children:t},t)),r.jsx("span",{children:e.label})]})}function tp(){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 sp({filter:e,scopeLabel:t,searchQuery:s}){const n=s?.trim();return e?r.jsxs(ri,{children:[r.jsx("p",{className:"font-medium text-fg",children:ap(e.label,t,n)}),r.jsx("p",{className:"mt-1 text-sm text-fg-muted",children:np[e.reach]}),r.jsx(le,{variant:"secondary",size:"sm",className:"mt-4",onClick:e.onClear,children:"Clear filter"})]}):r.jsx(ri,{children:r.jsx("p",{className:"text-fg-muted",children:rp(n,t)})})}const np={"whole-folder":"Every message in this folder was checked.","loaded-pages":"Only the messages loaded so far were checked."};function rp(e,t){return e?"No messages match your search":t?`No messages in ${t}`:"No messages in this mailbox"}function ap(e,t,s){return s?`No results for “${s}” in ${e}`:t?`No ${e} mail in ${t}`:`No ${e} mail`}function ri({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 op(){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(Ps,{className:"size-4 animate-spin","aria-hidden":"true"}),r.jsx("span",{children:"Loading more…"})]})}function ip({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(ds,{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(le,{variant:"secondary",size:"sm",onClick:t,children:"Retry"}),s&&r.jsx(le,{variant:"ghost",size:"sm",onClick:s,children:"Report a problem"})]})]})})}const Nc="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",Ec=({active:e,focused:t})=>V("relative flex h-8 w-full items-center gap-2 px-row-inset text-left",Nc,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"),Fs=({active:e,focused:t})=>V("relative flex w-full items-start gap-3 py-2 pl-5 pr-row-inset text-left transition-colors",Nc,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 Ic({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(Ls,{className:"size-3.5 text-danger"}):e.starred?r.jsx(Gt,{className:"size-3 fill-warning text-warning"}):t?r.jsx("span",{className:"size-1.5 rounded-full bg-accent"}):null}),r.jsx("span",{className:V("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:V(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(dr,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"w-11 shrink-0 text-right text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]})}function ai(e,t){const s=t?.trim();if(!s)return e;const n=e.toLowerCase(),a=s.toLowerCase(),o=[];let i=0,l=n.indexOf(a,i),u=0;for(;l!==-1;)l>i&&o.push(e.slice(i,l)),o.push(r.jsx("mark",{className:"bg-transparent font-semibold text-fg",children:e.slice(l,l+a.length)},u++)),i=l+a.length,l=n.indexOf(a,i);return i<e.length&&o.push(e.slice(i)),o}function ln({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:V("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:V("truncate text-sm",n?"text-fg":"text-fg-muted"),children:ai(e.subject,s)}),e.suspicious&&r.jsx(Ls,{className:"size-3.5 shrink-0 text-danger"}),e.starred&&r.jsx(Gt,{className:"size-3 shrink-0 fill-warning text-warning"}),e.hasAttachment&&r.jsx(dr,{className:"size-3 shrink-0 text-fg-subtle"})]}),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:ai(e.snippet,s)}),e.category&&e.category!=="personal"&&r.jsx(St,{tone:ff[e.category],className:"shrink-0",children:e.category}),e.labels?.map(a=>r.jsx(mf,{label:a,className:"max-w-20"},a.labelId)),t]})]})}function lp({thread:e,selection:t}){if(!t)return r.jsx(kt,{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(kt,{name:e.fromName,email:e.fromEmail,size:"sm",className:V("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:V("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(fn,{className:"size-3"})})]})}function so({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(lp,{thread:e,selection:t}),r.jsx(ln,{thread:e,badge:s,highlightQuery:n})]})}function cp({thread:e,active:t,focused:s,onClick:n}){return r.jsx("button",{type:"button",...Ea,onClick:n,className:Ec({active:t,focused:s}),children:r.jsx(Ic,{thread:e})})}function up({thread:e,active:t,focused:s,selection:n,onClick:a}){return r.jsx("button",{type:"button",...Ea,onClick:a,className:V("group",Fs({active:t,focused:s})),children:r.jsx(so,{thread:e,selection:n})})}let Ts;const dp=5e3;function Tc(e){e.preventDefault(),Wn()}function Wn(){Ts!==void 0&&(clearTimeout(Ts),Ts=void 0,document.removeEventListener("contextmenu",Tc,!0),document.removeEventListener("pointerup",Wn,!0))}function fp(){Ts===void 0?(document.addEventListener("contextmenu",Tc,!0),document.addEventListener("pointerup",Wn,!0)):clearTimeout(Ts),Ts=setTimeout(Wn,dp)}function Rc({onLongPress:e,isDisabled:t,delayMs:s=500,accessibilityDescription:n}){const{longPressProps:a}=Ah({isDisabled:t,threshold:s,accessibilityDescription:n,onLongPress:e}),o=c.useCallback(i=>{i.pointerType!=="touch"&&i.pointerType!=="pen"||fp()},[]);return{longPressProps:Ds(a,{onPointerDown:o})}}const ls=72,oi=10,mp=ls/2,ii="__swipeableRowAxisCancel";function li(e){return e==="leading"?ls:e==="trailing"?-ls:0}function hp(e){return e>=ls/2?"leading":e<=-ls/2?"trailing":"none"}function Mc({thread:e,selectionMode:t,checked:s,active:n,peek:a,onPeek:o,onToggleCheck:i,onLongPress:l,onOpen:u,onAct:m}){const f=c.useRef(null),[d,h]=c.useState(null),{longPressProps:v}=Rc({onLongPress:l,isDisabled:t,accessibilityDescription:"Select message"}),g=E=>{const L=new PointerEvent("pointercancel",{bubbles:!0});L[ii]=!0,E.currentTarget.dispatchEvent(L)},w=Ds(v,{onPointerDown:E=>{f.current={startX:E.clientX,startY:E.clientY,axis:"none",escaped:!1}},onPointerMove:E=>{if(t)return;const L=f.current;if(!L)return;const D=E.clientX-L.startX,C=E.clientY-L.startY;if(L.axis==="none"&&(Math.abs(C)>oi&&Math.abs(C)>Math.abs(D)?L.axis="vertical":Math.abs(D)>oi&&Math.abs(D)>Math.abs(C)&&(L.axis="horizontal",E.currentTarget.setPointerCapture(E.pointerId))),L.axis==="none")return;const T=L.axis==="horizontal"?Math.abs(D):Math.abs(C);if(!L.escaped&&T>mp&&(L.escaped=!0,g(E)),L.axis!=="horizontal")return;const A=li(a),I=Math.max(-ls,Math.min(ls,A+D));h(I)},onPointerUp:E=>{const L=f.current;f.current=null;const D=d;if(h(null),!!L){if(L.axis!=="none"&&!L.escaped&&g(E),L.axis==="horizontal"){D!==null&&o(hp(D));return}if(L.axis!=="vertical"){if(t){i();return}if(a!=="none"){o("none");return}u()}}},onPointerCancel:E=>{E.nativeEvent[ii]||(f.current=null,h(null))}}),x=d??li(a),k=x>0?"leading":x<0?"trailing":"none",M=V("relative touch-pan-y bg-surface","select-none",Fs({active:s||n})),O={transform:x!==0?`translateX(${x}px)`:void 0,transition:d===null?"transform 150ms ease":"none",minHeight:44},j=!e.isRead,R=E=>E.stopPropagation(),P=t?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:V("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(fn,{className:"size-3.5"})}),r.jsx(ln,{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:R,onPointerMove:R,onPointerUp:R,onClick:E=>{E.preventDefault(),E.stopPropagation(),l()},onKeyDown:E=>{E.key!=="Enter"&&E.key!==" "||(E.preventDefault(),E.stopPropagation(),l())},className:"-m-2 inline-flex size-11 shrink-0 items-center justify-center rounded-full",children:r.jsx(kt,{name:e.fromName,email:e.fromEmail,size:"sm"})}),r.jsx(ln,{thread:e})]});return r.jsxs("div",{className:"relative overflow-hidden",children:[k==="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(Yl,{className:"size-6"}):r.jsx(ur,{className:"size-6"})}),k==="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(Rt,{className:"size-6"})}),r.jsx("button",{type:"button",role:t?"checkbox":void 0,"aria-checked":t?s:void 0,"data-message-row":!0,...w,className:M,style:O,children:P})]})}function pp({sections:e,selectedThreadId:t,selectionMode:s,checkedIds:n,initialPeek:a,onToggleCheck:o,onEnterSelection:i,onOpenThread:l,onRefresh:u,refreshing:m,busy:f=!1}){const[d,h]=c.useState(new Set),[v,g]=c.useState(new Map),p=e.flatMap(w=>w.threads).filter(w=>!d.has(w.id)).map(w=>{const x=v.get(w.id);return x===void 0?w:{...w,isRead:x}}),[y,b]=c.useState(a&&a!=="none"&&p[1]?{id:p[1].id,side:a}:null),S=(w,x)=>{if(x==="trailing")h(k=>new Set(k).add(w));else{const k=p.find(M=>M.id===w);g(M=>new Map(M).set(w,!k?.isRead))}b(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(bc,{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(w=>r.jsx("div",{className:f?"pointer-events-none opacity-50":void 0,children:r.jsx(Mc,{thread:w,selectionMode:s,checked:n.has(w.id),active:w.id===t,peek:y?.id===w.id?y.side:"none",onPeek:x=>b(x==="none"?null:{id:w.id,side:x}),onToggleCheck:()=>o(w.id),onLongPress:()=>i(w.id),onOpen:()=>l(w.id),onAct:x=>S(w.id,x)})},w.id))}),!s&&!m&&!f&&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 gp=new Set;function Ac({listTitle:e,listMeta:t,sections:s,briefFilters:n,flatList:a,listState:o="ready",searchQuery:i,listFilter:l,listScopeLabel:u,errorMessage:m,onRetry:f,onReportError:d,briefCategory:h,selectedThreadId:v,density:g="comfortable",onSelectThread:p,onSelectBriefCategory:y,onOpenNav:b,isDesktop:S,initialTouchState:w,selection:x,selectionBar:k,paneOverlay:M,listBody:O,hideHeader:j=!1}){const R=g==="compact"?cp:up,P=c.useRef(null);Jn({containerRef:P,itemSelector:Ia});const E=!S&&!n&&o==="ready",[L,D]=c.useState(!1),C=w==="peek-trailing"?"trailing":w==="peek-leading"?"leading":void 0,T=()=>{D(!0),setTimeout(()=>D(!1),1400)},A=x?.selectedIds??gp,I=x?.onToggle,F=x?.onRowSelect,N=to(A.size,S),q=c.useCallback(U=>{if(I)return{checked:A.has(U),onToggle:z=>{z.preventDefault(),z.stopPropagation(),I(U)}}},[A,I]),Q=c.useCallback((U,z)=>F?.(U,Hn(z))?(z.preventDefault(),z.shiftKey&&window.getSelection()?.removeAllRanges(),!0):!1,[F]),ae=c.useCallback(({thread:U,active:z,onClick:ee})=>r.jsx(R,{thread:U,active:z,selection:q(U.id),onClick:me=>{Q(U.id,me)||ee?.()}}),[R,q,Q]);return r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[k??(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(le,{variant:"ghost",size:"sm",icon:r.jsx(or,{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(tp,{})}):o==="empty"?r.jsx(sp,{filter:l,scopeLabel:u,searchQuery:i}):o==="error"?r.jsx(ip,{message:m,onRetry:f,onReport:d}):n?r.jsx(Il,{sections:s,briefCategory:h,selectedThreadId:v,Row:ae,onSelectThread:p,onSelectBriefCategory:y}):O??(E?r.jsx(pp,{sections:s,selectedThreadId:v,selectionMode:N,checkedIds:A,initialPeek:C,onToggleCheck:U=>I?.(U),onEnterSelection:U=>I?.(U),onOpenThread:U=>p?.(U),onRefresh:T,refreshing:L}):r.jsx("div",{ref:P,className:"flex-1 overflow-y-auto",children:s.map(U=>r.jsxs("div",{children:[!a&&U.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:U.label}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:U.threads.length})]}),r.jsx("div",{className:"divide-y divide-line",children:U.threads.map(z=>r.jsx(R,{thread:z,active:z.id===v,selection:q(z.id),onClick:ee=>{Q(z.id,ee)||p?.(z.id)}},z.id))})]},U.id))})),S&&r.jsx(jc,{}),M]})}function no({triggerLabel:e,triggerIcon:t,triggerText:s,items:n,align:a="end",touch:o=!0,className:i,triggerClassName:l,nested:u=!1,children:m}){const[f,d]=c.useState(!1),h=c.useRef(null);return c.useEffect(()=>{if(!f)return;const v=p=>{h.current&&!h.current.contains(p.target)&&d(!1)},g=p=>{p.key==="Escape"&&d(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",g),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",g)}},[f]),n.length===0&&!m?null:r.jsxs("div",{ref:h,className:V("relative",i),...u?{role:"none"}:{},children:[r.jsx(le,{variant:"ghost",size:"sm",icon:t??r.jsx(pc,{className:"size-5"}),onClick:()=>d(v=>!v),"aria-label":e,"aria-haspopup":"menu","aria-expanded":f,...u?{role:"menuitem"}:{},className:V(o&&"min-h-11 min-w-11 px-0",l),children:s}),f&&r.jsxs("div",{role:"menu",className:V("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:()=>{d(!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 Ws="min-h-11 min-w-11 px-0";function Oc({hasThread:e,onReply:t,onReplyAll:s,onForward:n,isStarred:a,onToggleStar:o,onDelete:i,isRead:l,onToggleRead:u,moveSlot:m,overflowItems:f=[],onUnavailable:d,unavailableHint:h,className:v}){const g=(y,b)=>()=>{if(!e){d?.(y);return}b?.()},p=u?[{key:"toggle-read",label:l?"Mark as unread":"Mark as read",icon:l?r.jsx(Yl,{className:"size-4"}):r.jsx(ur,{className:"size-4"}),onSelect:g("toggleRead",u)}]:[];return r.jsxs("div",{className:V("relative",v),children:[r.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-0.5 bg-canvas px-1",children:[r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(yc,{className:"size-5"}),onClick:g("reply",t),"aria-label":"Reply",title:"Reply",className:Ws}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(vc,{className:"size-5"}),onClick:g("replyAll",s),"aria-label":"Reply all",title:"Reply all",className:Ws}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(gc,{className:"size-5"}),onClick:g("forward",n),"aria-label":"Forward",title:"Forward",className:Ws}),r.jsx("div",{className:"flex-1"}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Gt,{className:V("size-5",a&&"fill-warning text-warning")}),onClick:g("star",o),"aria-label":a?"Unstar":"Star","aria-pressed":a,title:a?"Unstar":"Star",className:Ws}),m,r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Rt,{className:"size-5"}),onClick:g("delete",i),"aria-label":"Move to Trash",title:"Move to Trash",className:Ws}),r.jsx(no,{triggerLabel:"More actions",items:[...p,...f]})]}),!e&&h&&r.jsx("p",{role:"status",className:"bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:h})]})}function xp({open:e=!1,enabled:t=!0,onToggle:s,className:n}){return r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Tl,{className:"size-4"}),title:"Intelligence","aria-label":e?"Hide intelligence sidebar":"Show intelligence sidebar","aria-pressed":e,disabled:!t,onClick:s,className:V(e&&"bg-accent-2-soft text-accent-2",n)})}function bp({hasThread:e,onUnavailable:t,unavailableHint:s,isStarred:n,showTriage:a=!0,onReply:o,onReplyAll:i,onForward:l,onDelete:u,onToggleStar:m,moveSlot:f,onMove:d,replyTitle:h="Reply (r)",replyAllTitle:v="Reply all (a)",forwardTitle:g="Forward (f)",deleteTitle:p="Move to Trash (#)",flagTitle:y="Star (s)",children:b,className:S}){const w=(x,k)=>()=>{if(!e){t?.(x);return}k?.()};return r.jsxs("div",{className:"relative",children:[r.jsxs("header",{className:V("flex h-pane-header shrink-0 items-center gap-1 border-b border-line bg-surface px-3",S),children:[r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(yc,{className:"size-4"}),title:h,"aria-label":"Reply",onClick:w("reply",o)}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(vc,{className:"size-4"}),title:v,"aria-label":"Reply all",onClick:w("replyAll",i)}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(gc,{className:"size-4"}),title:g,"aria-label":"Forward",onClick:w("forward",l)}),a&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"mx-1 h-4 w-px bg-line","aria-hidden":!0}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Rt,{className:"size-4"}),title:p,"aria-label":"Move to Trash",onClick:w("delete",u)}),f??r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Ta,{className:"size-4"}),title:"Move to mailbox","aria-label":"Move to mailbox",onClick:w("move",d)}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Gt,{className:V("size-4",n&&"fill-warning text-warning")}),title:y,"aria-label":"Star",onClick:w("flag",m)})]}),r.jsx("div",{className:"flex-1"}),b]}),!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 vp=(e,t)=>{const n=e==="newsletter"||e==="marketing"||t;return{framed:n,isPlain:!n}},yp=()=>`
9
9
  /* Zero the UA default body margin and clamp the document to the iframe width so
10
10
  wide author markup can't push the body (and the page) past the viewport. */
11
11
  html, body {
@@ -43,14 +43,14 @@ pre, code {
43
43
  overflow-wrap: anywhere;
44
44
  word-break: break-word;
45
45
  }
46
- `,wp=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,""))},Sp=/^(none|transparent|inherit|initial|unset)\s*$/i,kp=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},jp=e=>{const t=/background(?:-color)?\s*:\s*([^;}\n]+)/gi;let s;for(s=t.exec(e);s!==null;){const n=s[1].trim();if(!Sp.test(n))return!0;s=t.exec(e)}return!1},Cp=e=>{if(/\bstyle\s*=\s*["'][^"']*background/i.test(e)||/\bbgcolor\s*=/i.test(e))return!0;for(const t of kp(e))if(jp(t))return!0;return!1},Np=["script","iframe","object","embed","form","input","button","textarea","select","meta","link","base"],Ep=["onerror","onload","onclick","onmouseover","onmouseout","onfocus","onblur","onsubmit","onkeydown","onkeyup","formaction","xlink:href","data-bind"],Ip="data:image/svg+xml,"+encodeURIComponent(`
46
+ `,wp=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,""))},Sp=/^(none|transparent|inherit|initial|unset)\s*$/i,kp=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},Cp=e=>{const t=/background(?:-color)?\s*:\s*([^;}\n]+)/gi;let s;for(s=t.exec(e);s!==null;){const n=s[1].trim();if(!Sp.test(n))return!0;s=t.exec(e)}return!1},jp=e=>{if(/\bstyle\s*=\s*["'][^"']*background/i.test(e)||/\bbgcolor\s*=/i.test(e))return!0;for(const t of kp(e))if(Cp(t))return!0;return!1},Np=["script","iframe","object","embed","form","input","button","textarea","select","meta","link","base"],Ep=["onerror","onload","onclick","onmouseover","onmouseout","onfocus","onblur","onsubmit","onkeydown","onkeyup","formaction","xlink:href","data-bind"],Ip="data:image/svg+xml,"+encodeURIComponent(`
47
47
  <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
48
48
  <rect fill="#f0f0f0" width="100" height="100"/>
49
49
  <text x="50" y="50" text-anchor="middle" dy=".3em" fill="#999" font-size="12">
50
50
  Image blocked
51
51
  </text>
52
52
  </svg>
53
- `),Tp=e=>e.replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Rp=e=>e.replace(/@import[^;]*;/gi,"/* @import blocked */").replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Mp=(e={})=>{const t=Pl(),s={FORBID_TAGS:Np,FORBID_ATTR:Ep,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,""),l=e.resolveCid?.(i);l&&(n.setAttribute("src",l),n.classList.add("inline-content"));return}e.allowExternalImages||(n.setAttribute("data-blocked-src",a),n.setAttribute("src",Ip),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",Tp(a))}}),t.addHook("uponSanitizeElement",(n,a)=>{if(a.tagName==="style"){const o=n.textContent||"";n.textContent=Rp(o)}}),n=>{const a=Cp(n),o=t.sanitize(n,s);return{html:`<style>${yp()}</style>${o}`,hasAuthorBackground:a}}},Ap='"Geist Variable", "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fi={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)"}},Op=/prefers-color-scheme\s*:\s*dark|color-scheme\s*:\s*[^;}"']*\bdark\b/i,mi='<meta name="viewport" content="width=device-width, initial-scale=1">',Pp=e=>{const t=e?fi.dark:fi.light;return`
53
+ `),Tp=e=>e.replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Rp=e=>e.replace(/@import[^;]*;/gi,"/* @import blocked */").replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Mp=(e={})=>{const t=Rl(),s={FORBID_TAGS:Np,FORBID_ATTR:Ep,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,""),l=e.resolveCid?.(i);l&&(n.setAttribute("src",l),n.classList.add("inline-content"));return}e.allowExternalImages||(n.setAttribute("data-blocked-src",a),n.setAttribute("src",Ip),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",Tp(a))}}),t.addHook("uponSanitizeElement",(n,a)=>{if(a.tagName==="style"){const o=n.textContent||"";n.textContent=Rp(o)}}),n=>{const a=jp(n),o=t.sanitize(n,s);return{html:`<style>${yp()}</style>${o}`,hasAuthorBackground:a}}},Ap='"Geist Variable", "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',ci={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)"}},Op=/prefers-color-scheme\s*:\s*dark|color-scheme\s*:\s*[^;}"']*\bdark\b/i,ui='<meta name="viewport" content="width=device-width, initial-scale=1">',Pp=e=>{const t=e?ci.dark:ci.light;return`
54
54
  /* Plain-email base: UI font-stack + theme-aware colors (#424) */
55
55
  html, body {
56
56
  font-family: ${Ap};
@@ -71,13 +71,13 @@ a, a:visited {
71
71
  color: ${t.accent} !important;
72
72
  text-decoration: underline;
73
73
  }
74
- `},Dp=(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}",Lp=(e,t,s)=>{if(t==="plain")return`${mi}<style>${Pp(s)}</style>${e}`;const n=Op.test(e);return`${mi}<style>${Dp(s,n)}</style>${e}`},Fp=5e4,$p=1e4,_p="(max-width: 640px)",zp=.4,Bp="allow-same-origin allow-popups allow-popups-to-escape-sandbox",hi=(e,t,s)=>Math.min(Math.ceil(Math.max(e,t)),s),Kp=(e,t)=>e<=0||t<=0||e<=t?1:Math.max(zp,t/e),Up=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},qp=new Set(["Enter","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"]),Hp=e=>e===" "?!1:e.length===1?!0:qp.has(e),pi=e=>{if(e.metaKey||e.ctrlKey||e.altKey||!Hp(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}))},gi=({html:e,variant:t="framed",isDark:s=!1,className:n})=>{const a=c.useRef(null),o=c.useRef(null),[i,l]=c.useState(0),[u,m]=c.useState(0),[f,d]=c.useState(0),h=Up(_p),v=c.useMemo(()=>Lp(e,t,s),[e,t,s]);c.useEffect(()=>{const w=a.current;if(!w)return;const x=()=>d(M=>M===w.clientWidth?M:w.clientWidth);x();const k=new ResizeObserver(x);return k.observe(w),()=>k.disconnect()},[]),c.useEffect(()=>{const w=o.current;if(!w)return;const x=()=>{const C=w.contentDocument;if(!C?.body)return;const R=C.documentElement,P=hi(C.body.scrollHeight,R?.scrollHeight??0,Fp);l(L=>L===P?L:P);const E=hi(C.body.scrollWidth,R?.scrollWidth??0,$p);m(L=>L===E?L:E)};let k,M;const O=()=>{x();const C=w.contentDocument;C?.body&&(k=new ResizeObserver(x),k.observe(C.body),C.documentElement&&k.observe(C.documentElement),C.addEventListener("keydown",pi),M=C)};return w.addEventListener("load",O),()=>{w.removeEventListener("load",O),M?.removeEventListener("keydown",pi),k?.disconnect()}},[]);const g=h?Kp(u,f):1,p=g<1,y=p?`${u}px`:h?"100%":t==="framed"&&u>0?`max(100%, ${u}px)`:u===0?"100%":`${u}px`,b=i===0?"1px":`${i}px`,S=r.jsx("iframe",{ref:o,title:"Email content",sandbox:Bp,srcDoc:v,className:p?void 0:n,scrolling:"no",style:{width:y,maxWidth:p?"none":void 0,border:"none",display:"block",height:b,overflow:"hidden",transform:p?`scale(${g})`: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*g)}px`,overflow:"hidden"},children:S}):S})},xi=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Pc=({html:e,text:t,isDark:s=!1,category:n,allowImages:a=!1,resolveCid:o,className:i,renderBlockedNotice:l})=>{const u=c.useMemo(()=>!e||typeof document>"u"?null:Mp({allowExternalImages:a,resolveCid:o})(e),[e,a,o]),m=u?.html??null,{framed:f,isPlain:d}=vp(n,u?.hasAuthorBackground??!1),h=c.useMemo(()=>!m||a?0:(m.match(/data-blocked-src/g)||[]).length,[m,a]);return!m&&!t?r.jsx("div",{className:V("message-body",i),children:r.jsx(xi,{})}):r.jsxs("div",{className:V("message-body",i),children:[h>0&&r.jsx("div",{className:"message-body-notice",children:l?.(h)}),m?f?r.jsx("div",{className:"w-full max-w-full overflow-x-auto",children:r.jsx(gi,{html:m,variant:"framed",isDark:s})}):r.jsx("div",{className:"max-w-full overflow-x-auto lg:max-w-2xl",children:r.jsx(gi,{html:m,variant:d?"plain":"framed",isDark:s})}):t?r.jsx("pre",{className:"email-text whitespace-pre-wrap text-sm leading-relaxed",children:t}):r.jsx(xi,{})]})};function _s({message:e="Select a thread to read",icon:t,showHints:s=!0,className:n}){return r.jsxs("div",{className:V("flex flex-1 flex-col items-center justify-center text-center",n),children:[t??r.jsx(Ra,{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(Ts,{children:"j"})," / ",r.jsx(Ts,{children:"k"})," to move, ",r.jsx(Ts,{children:"Enter"})," to open"]})]})}function Dc({message:e,onClick:t,isFocused:s,isUnread:n,trailing:a}){const o=r.jsxs(r.Fragment,{children:[r.jsx(As,{className:"size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{className:"relative shrink-0",children:[r.jsx(kt,{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:V("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=V("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:l=>{hf(l)&&(l.preventDefault(),t())},className:V(i,"cursor-pointer"),children:o}):r.jsx("div",{className:i,children:o})}function Lc({message:e,warning:t,onHeaderClick:s,isFocused:n,senderBadge:a,trailing:o,to:i,indicators:l,actionMenu:u,actionBar:m,body:f}){const d=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:V("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(Wt,{className:"mt-1 size-3.5 shrink-0 text-fg-subtle"}),r.jsx(kt,{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:d}):d,l]}),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:f??r.jsx(Pc,{className:"mt-3",html:e.bodyHtml,category:e.framed?"newsletter":"personal",allowImages:!0})})]})}function Wp({thread:e,onBack:t,intelligence:s,intelligenceOpen:n,onToggleIntelligence:a,actions:o,children:i,touchHandlers:l}){const[u,m]=c.useState(!1),f=a!==void 0,d=f?n??!1:u,h=!!s||f,v=()=>{if(f){a?.();return}m(p=>!p)},g=()=>{if(f){d&&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(le,{variant:"ghost",size:"sm",icon:r.jsx(Ma,{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(le,{variant:"ghost",size:"sm",icon:r.jsx(Ol,{className:"size-4"}),onClick:v,"aria-label":d?"Hide intelligence panel":"Show intelligence panel","aria-pressed":d,title:"Intelligence",className:V("shrink-0",d&&"bg-accent-2-soft text-accent-2")})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",style:l?{touchAction:"pan-y"}:void 0,...l,children:i??e.messages.map(p=>{const y=b=>b?()=>b(p.id):void 0;return p.expanded?r.jsx(Lc,{message:p,warning:e.warning,onHeaderClick:y(o?.onToggleExpand),actionBar:r.jsx(Oc,{hasThread:!0,onReply:y(o?.onReply),onReplyAll:y(o?.onReplyAll),onForward:y(o?.onForward),onToggleStar:y(o?.onToggleStar),onDelete:y(o?.onDelete),onToggleRead:y(o?.onToggleRead),moveSlot:o?.moveSlot?.(p.id)})},p.id):r.jsx(Dc,{message:p,onClick:y(o?.onToggleExpand)},p.id)})}),s&&!f&&r.jsx(pf,{open:d,onClose:g,title:"Intelligence",anchor:"right",className:"p-0",children:r.jsx(Sc,{data:s,onClose:g,className:"h-full w-full border-l-0"})})]})}const Vp="button:not([disabled]), a[href]",os="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface-sunken";function Qp({active:e,dimmed:t,indent:s}){return V("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors",os,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 Gp({icon:e,label:t,count:s,active:n}){return r.jsxs(r.Fragment,{children:[e&&r.jsx("span",{className:V("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:V("text-2xs tabular-nums",n?"text-accent-2":"text-fg-subtle"),children:s})]})}function nn({icon:e,label:t,count:s,active:n,dimmed:a,indent:o,navId:i,linkComponent:l,ariaLabel:u,title:m,onClick:f}){const d=Qp({active:n,dimmed:a,indent:o}),h=r.jsx(Gp,{icon:e,label:t,count:s,active:n});return i&&l?l({navId:i,className:d,ariaLabel:u??t,title:m,onClick:f,children:h}):r.jsx("button",{type:"button",onClick:f,className:d,"aria-label":u,title:m,children:h})}const bi={inbox:0,flagged:1,drafts:2,sent:3,archive:4,all:5,junk:6,trash:7};function Yp(e){switch(e){case"inbox":return r.jsx(Ra,{className:"size-4"});case"flagged":return r.jsx(Gt,{className:"size-4"});case"drafts":return r.jsx(Dl,{className:"size-4"});case"sent":return r.jsx(mn,{className:"size-4"});case"archive":return r.jsx(vf,{className:"size-4"});case"all":return r.jsx(bf,{className:"size-4"});case"junk":return r.jsx(xf,{className:"size-4"});case"trash":return r.jsx(Rt,{className:"size-4"})}}const vi=e=>e.role!=null,Fr=8,yi="remit.nav.folders.open.",wi="remit.nav.account.open.";function Si(e,t,s){if(typeof localStorage>"u")return s;const n=localStorage.getItem(e+t);return n===null?s:n!=="0"}function ki(e,t,s){typeof localStorage>"u"||localStorage.setItem(e+t,s?"1":"0")}function Xp({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:V("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",os),children:[r.jsx(Zn,{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:V("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",os),children:r.jsx(jt,{className:"size-3.5"})})]})}function Jp({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:V("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-accent transition-colors hover:bg-surface",os),children:[r.jsx(Ph,{className:"size-4 shrink-0"}),r.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Save “",t,"”"]})]}),e.map(o=>r.jsx(Xp,{query:o,onSelect:()=>s?.(o),onRemove:n?()=>n(o):void 0},o))]})}function Zp({account:e,selectedNavId:t,onSelectNav:s,linkComponent:n}){const[a,o]=c.useState(()=>Si(wi,e.id,!0)),[i,l]=c.useState(()=>Si(yi,e.id,!0)),[u,m]=c.useState(!1),f=()=>{o(S=>{const w=!S;return ki(wi,e.id,w),w})},d=()=>{l(S=>{const w=!S;return ki(yi,e.id,w),w})},h=e.mailboxes.filter(vi).sort((S,w)=>bi[S.role]-bi[w.role]),v=e.mailboxes.filter(S=>!vi(S)),g=u||v.length<=Fr?v:v.slice(0,Fr),p=v.length-g.length,y=e.status??"ready",b=y==="ready"&&h.length===0&&v.length===0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("button",{type:"button",onClick:f,"aria-expanded":a,className:V("flex w-full items-center gap-1.5 px-2 pb-1 text-left transition-colors hover:text-fg",os,e.muted&&"opacity-55"),children:[a?r.jsx(Wt,{className:"size-3 shrink-0 text-fg-subtle"}):r.jsx(As,{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(fc,{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:[y==="loading"&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"Loading…"}),y==="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(ds,{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"})]}),b&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"No mailboxes"}),y==="ready"&&r.jsxs(r.Fragment,{children:[h.map(S=>r.jsx(nn,{navId:S.id,linkComponent:n,icon:Yp(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(nn,{navId:"outbox",linkComponent:n,icon:r.jsx(mn,{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:d,"aria-expanded":i,className:V("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",os),children:[i?r.jsx(Wt,{className:"size-3 shrink-0"}):r.jsx(As,{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:[g.map(S=>r.jsx(nn,{navId:S.id,linkComponent:n,icon:r.jsx(gf,{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>Fr&&r.jsx("button",{type:"button",onClick:()=>m(S=>!S),className:V("ml-7 flex items-center px-2 py-1 text-2xs font-medium text-accent transition-colors hover:underline",os),children:u?"Show less":`Show all (${v.length})`})]})]})]})]})]})}function eg({accounts:e,selectedNavId:t,briefUnseen:s,onSelectNav:n,variant:a="desktop",linkComponent:o,savedSearches:i=[],saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:f}){const d=c.useRef(null);Jn({containerRef:d,itemSelector:Vp});const h=a==="drawer",v=r.jsxs("nav",{ref:h?d:void 0,className:h?"px-2 py-2":"flex-1 overflow-y-auto px-2 py-2","aria-label":"Mailboxes",children:[r.jsx(nn,{navId:"brief",linkComponent:o,icon:r.jsx(Tt,{className:"size-4"}),label:"Daily brief",ariaLabel:"Daily brief",count:s,active:t==="brief",onClick:()=>n?.("brief")}),r.jsx(nn,{navId:"flagged",linkComponent:o,icon:r.jsx(Gt,{className:"size-4"}),label:"Starred",ariaLabel:"Starred",active:t==="flagged",onClick:()=>n?.("flagged")}),r.jsx(Jp,{savedSearches:i,saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:f}),e.length===0?r.jsx("div",{className:"px-2 py-4 text-center text-sm text-fg-muted",children:"No accounts configured"}):e.map(g=>r.jsx(Zp,{account:g,selectedNavId:t,onSelectNav:n,linkComponent:o},g.id))]});return h?v:r.jsx("aside",{ref:d,className:"flex h-full w-full flex-col bg-surface-sunken",children:v})}function tg({leading:e,search:t,actions:s,className:n}){return r.jsxs("header",{className:V("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})]})}function sg({label:e,onUndo:t,undoLabel:s="Undo",filtersHref:n,className:a}){return r.jsxs(St,{tone:"accent",className:V("py-1 text-xs",a),children:[r.jsx(Bh,{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 ng({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(Ds,{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:rg(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(Tt,{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 rg({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 ag="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",ji="pointer-events-none absolute inset-0 m-auto size-3.5 text-accent-fg";function oo({label:e,description:t,indeterminate:s=!1,checked:n,onChange:a,className:o,...i}){const l=c.useRef(null);c.useEffect(()=>{l.current&&(l.current.indeterminate=s)},[s]);const u=r.jsxs("span",{className:"relative inline-flex",children:[r.jsx("input",{ref:l,type:"checkbox",checked:n,onChange:a,className:ag,...i}),r.jsx(fn,{className:V(ji,"hidden peer-checked:block"),"aria-hidden":!0}),r.jsx(Fh,{className:V(ji,"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:V("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 og=({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 ig({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(le,{variant:"primary",size:"md","aria-busy":s,title:n?void 0:o,className:"min-h-11 rounded-full px-4",icon:s?r.jsx(Ds,{className:"size-4 animate-spin"}):r.jsx(mn,{className:"size-4"}),onClick:()=>{if(!s){if(!n){o&&i?.(o);return}e()}},children:"Send"}),r.jsx(og,{status:a})]}),r.jsx(le,{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(Rt,{className:"size-4"}),onClick:()=>{s||t()}})]})}function lg({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:"min-h-0 flex-1 overflow-auto",children:[s,n&&r.jsx("div",{className:"px-3 pb-2",children:n})]}),a]})}function cg({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 ug({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 dg(e,t){const s=t-1;return s<=0?null:e<s?e:s-1}const fg=e=>e instanceof HTMLElement?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable:!1,mg=({chips:e=[],onRemoveChip:t,value:s,onChange:n,onClear:a,onClearQuery:o,placeholder:i="Search mail...",globalFocusKey:l=!0,showClearButton:u=!0,size:m="sm",inputId:f,suggest:d,className:h})=>{const v=c.useId(),g=f??v,p=c.useRef(null),y=c.useRef([]),b=o??a,[S,w]=c.useState(null),x=c.useRef(void 0),[k,M]=c.useState(""),O=e.length>0;c.useEffect(()=>{w(T=>T!==null&&T>=e.length?null:T)},[e.length]),c.useEffect(()=>{const T=x.current;if(T!==void 0){if(x.current=void 0,T===null){p.current?.focus();return}y.current[T]?.focus()}});const C=c.useRef(void 0);c.useEffect(()=>{const T=d?.caret;if(!T||T===C.current)return;C.current=T;const A=p.current;!A||A.ownerDocument.activeElement!==A||(A.setSelectionRange(T.cursor,T.cursor),d?.onCaretChange(T.cursor))});const R=T=>{d?.onCaretChange(T.selectionStart??T.value.length)},P=c.useCallback(T=>{w(T),x.current=T},[]),E=c.useCallback(T=>{const A=e[T];A&&t&&(P(dg(T,e.length)),M(`${A.label} removed`),t(A.id))},[e,t,P]),L=c.useCallback(()=>{P(null),a()},[a,P]),D=c.useCallback(T=>{const A=T.currentTarget;if(d?.onKeyDown(T))return;const I=cg({key:T.key,shiftKey:T.shiftKey,repeat:T.repeat,caretAtStart:A.selectionStart===0&&A.selectionEnd===0,hasValue:s.length>0,chipCount:e.length});switch(I.type){case"focusChip":T.preventDefault(),P(I.index);return;case"clearQuery":b();return;case"blur":A.blur();return;case"none":return}},[e.length,s,b,P,d]),j=c.useCallback(T=>A=>{const I=ug({key:A.key,repeat:A.repeat,index:T,chipCount:e.length});switch(I.type!=="none"&&A.preventDefault(),I.type){case"removeChip":E(I.index);return;case"focusChip":P(I.index);return;case"focusInput":P(null);return;case"activateChip":return;case"none":return}},[e,E,P]);return c.useEffect(()=>{if(!l)return;const T=A=>{A.key!=="/"||A.metaKey||A.ctrlKey||A.altKey||fg(A.target)||(A.preventDefault(),p.current?.focus())};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[l]),r.jsxs("label",{htmlFor:g,className:V("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(Zn,{className:V("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:[O&&r.jsx("div",{role:"grid","aria-label":"Search filters",className:"flex min-w-0 flex-wrap items-center gap-1",children:e.map((T,A)=>r.jsx(yf,{ref:I=>{y.current[A]=I},label:T.label,tone:T.tone,focused:S===A,onFocusLabel:()=>w(A),onKeyDown:j(A),onRemove:()=>E(A)},T.id))}),r.jsx("input",{ref:p,id:g,name:"q",type:"text","aria-label":"Search mail",autoComplete:"off",value:s,tabIndex:S===null?0:-1,onChange:T=>{n(T.target.value),R(T.target)},onKeyDown:D,onKeyUp:T=>R(T.currentTarget),onClick:T=>R(T.currentTarget),onFocus:T=>{w(null),d?.onFocusChange?.(!0),R(T.currentTarget)},onBlur:()=>d?.onFocusChange?.(!1),...d?.comboboxProps,placeholder:O?void 0:i,className:"min-w-24 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted"})]}),(s||O)&&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(jt,{className:V("text-fg-muted",m==="lg"?"size-5":"size-4")})}),r.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:k})]})},io=({value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i="Search mail...",globalFocusKey:l=!0,showClearButton:u=!0,size:m,inputId:f,suggest:d,className:h})=>r.jsx(mg,{value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i,globalFocusKey:l,showClearButton:u,size:m,inputId:f,suggest:d,className:h});function hg(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 pg({result:e,onClick:t,query:s,showFolder:n=!0}){const a=n&&e.folder?wf(e.folder):void 0;return r.jsx("button",{type:"button",onClick:t,className:V("group",$s({}),"border-b border-line"),children:r.jsx(ro,{thread:hg(e),highlightQuery:s,badge:r.jsxs(r.Fragment,{children:[a&&r.jsx(St,{tone:"neutral",className:"shrink-0",children:a}),e.category&&r.jsx(St,{tone:e.category.tone??"neutral",className:"shrink-0",children:e.category.label}),e.matchedChunkLabel&&r.jsx(St,{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 gg=e=>e===1?"result":"results";function Fc({count:e,onScopeToSpam:t}){return r.jsx(hn,{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})," ",`${gg(e)} from Spam`]}),r.jsx(le,{variant:"ghost",size:"sm",onClick:t,className:"shrink-0 text-accent",children:"Go to Spam"})]})})}const Ci=6,xg={kind:"global"},bg=e=>e.kind==="folder"&&e.role==="junk",vg=e=>e.folder?.role==="junk";function lo(e){const t=[],s=[];for(const n of e)vg(n)?s.push(n):t.push(n);return{kept:t,spam:s}}function $c({onClick:e,blockedReason:t}){const s=c.useId(),[n,a]=c.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:V("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(Sf,{className:"size-3.5 shrink-0","aria-hidden":"true"}),r.jsx("span",{children:"Make this a filter"})]}),t&&r.jsx(kf,{id:s,reason:t,nudged:n,className:"px-2 pt-1 text-2xs text-warning"})]})}function yg({section:e,query:t,onSelectResult:s,showFolder:n}){const[a,o]=c.useState(e.initialCollapsed??!1),[i,l]=c.useState(!1),u=e.results.length>Ci,f=!i&&u?e.results.slice(0,Ci):e.results,d=e.results.length-f.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(Wt,{className:V("size-3 shrink-0 text-fg-subtle transition-transform duration-200",a?"rotate-0":"rotate-180")})]}),!a&&r.jsxs(r.Fragment,{children:[f.map(h=>r.jsx(pg,{result:h,query:t,showFolder:n,onClick:s?()=>s(h):void 0},h.id)),u&&r.jsxs("button",{type:"button",onClick:()=>l(h=>!h),className:"flex w-full items-center justify-center border-b border-line px-row-inset py-1.5 text-2xs font-medium text-accent transition-colors hover:bg-surface",children:[i?"Show less":`Show ${d} more`,!i&&r.jsx(Wt,{className:"ml-1 size-3"})]})]})]})}function _c({value:e,recentSearches:t,onPickRecent:s,sections:n,loading:a,onSelectResult:o,tokens:i,scope:l=xg,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(x=>r.jsxs("button",{type:"button",onClick:()=>s?.(x),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(Xa,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-fg-muted",children:x})]},x))]}):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 f=i&&i.length>0&&r.jsx(jf,{tokens:i}),d=u&&r.jsx($c,{...u});if(a)return r.jsxs("div",{className:"flex flex-col",children:[d,f,r.jsx("div",{className:"flex flex-col gap-3 px-row-inset py-4",children:[0,1,2,3].map(x=>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"})]},x))})]});const h=l.kind==="global",v=bg(l)||l.kind==="collection",g=h||l.kind==="collection",p=(n??[]).map(x=>{if(v)return{section:x,spam:[]};const{kept:k,spam:M}=lo(x.results);return{section:{...x,results:k},spam:M}}),y=p.map(x=>x.section),b=p.reduce((x,k)=>x+k.spam.length,0),S=l.kind==="global"&&b>0&&l.onScopeToSpam!==void 0?r.jsx(Fc,{count:b,onScopeToSpam:l.onScopeToSpam}):void 0;return y.some(x=>x.results.length>0)?r.jsxs("div",{className:"flex flex-col",children:[d,f,S,y.filter(x=>x.results.length>0).map(x=>r.jsx(yg,{section:x,query:e,showFolder:g,onSelectResult:o},x.id))]}):r.jsxs("div",{className:"flex flex-col",children:[d,f,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 wg({value:e,onChange:t,onClear:s,onCancel:n,filter:a,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:m,tokens:f,chips:d,onRemoveChip:h,scope:v,makeFilter:g,suggest:p,suggestList:y}){const b=r.jsx(_c,{value:e,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:m,tokens:f,scope:v,makeFilter:g});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(io,{value:e,onChange:t,onClear:s,chips:d,onRemoveChip:h,globalFocusKey:!1,showClearButton:!1,suggest:p})}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(jt,{className:"size-4"}),onClick:n,"aria-label":"Clear and close search",className:"-mr-1 shrink-0"})]}),y,a&&e.trim().length===0?r.jsx(Cf,{children:r.jsx(Ll,{...a,children:b})}):r.jsx("div",{className:"flex-1 overflow-y-auto",children:b})]})}function Sg(){const e=fs();if(!e)return null;const t=e.showNavPane?!e.navCollapsed:!1;return r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(or,{className:"size-4"}),onClick:e.toggleNav,"aria-label":t?"Hide folders":"Show folders","aria-expanded":t,title:"Folders",className:"shrink-0"})}const kg={queued:{icon:Xa,label:"Queued",className:"text-warning"},sending:{icon:Ds,label:"Sending…",className:"text-accent-2",spin:!0},sent:{icon:mc,label:"Sent",className:"text-positive"},failed:{icon:ds,label:"Failed",className:"text-danger"},blocked:{icon:Aa,label:"Blocked",className:"text-warning"}};function Ni({status:e,iconOnly:t,className:s}){const n=kg[e],a=n.icon;return r.jsxs("span",{className:V("inline-flex items-center gap-1.5 text-xs font-medium",n.className,s),children:[r.jsx(a,{className:V("size-4",n.spin&&"animate-spin")}),!t&&n.label]})}const jg=(e,t)=>t?"bg-accent-2-soft":e==="failed"?"bg-danger-soft":e==="blocked"?"bg-warning/10":"";function Cg({recipients:e,subject:t,time:s,status:n,error:a,selected:o,onSelect:i,onRetry:l,retrying:u,onEdit:m,onDelete:f,deleting:d}){const h=n==="failed"||n==="blocked";return r.jsxs("div",{className:V("flex items-start gap-3 border-b border-line px-4 py-3 transition-colors hover:bg-surface-raised",jg(n,o)),children:[r.jsxs("button",{type:"button",...Ea,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(Ni,{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(Ni,{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(Fm,{actions:[...n==="failed"&&l?[{label:"Retry sending",iconOnly:!0,icon:r.jsx(Dm,{className:"size-3.5"}),busy:u,onClick:l}]:[],{label:"Edit as draft",iconOnly:!0,icon:r.jsx(mn,{className:"size-3.5"}),onClick:m}],destructive:{label:"Delete message",iconOnly:!0,icon:r.jsx(Rt,{className:"size-3.5"}),busy:d,confirm:{prompt:"Delete this message?",confirmLabel:"Delete"},onClick:f}})})]})}const Ng=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Eg=({children:e,onRefresh:t,isRefreshing:s})=>Ng("(min-width: 1024px)")?e:r.jsx(Nf,{onRefresh:t,isPullable:!s,children:e}),Ig=({text:e,html:t,senderName:s,date:n})=>{const[a,o]=c.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(Wt,{className:"size-3"}):r.jsx(As,{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((l,u)=>r.jsx("p",{className:"min-h-[1.2em]",children:l},u))})]})},Tg=e=>e===1?"message":"messages";function Rg({count:e,onReview:t,onDismiss:s,actionLabel:n="Review & rescue"}){return r.jsx(hn,{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(gn,{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} ${Tg(e)} here`})," ","may not be spam — they're from senders we can verify."]})]}),r.jsx(le,{variant:"primary",size:"sm",onClick:t,className:"self-start",children:n})]})})}const Mg=(e,t)=>e==="vip"?"vip":e==="unknown"&&t==="md"?"unknown-pill":"hidden",zc=({senderTrust:e,size:t="sm",className:s})=>{const n=Mg(e,t);return n==="vip"?r.jsx(Tt,{className:V("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:V("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 Ag({candidate:e,selected:t,onToggle:s,hideSender:n=!1}){const{senderName:a,senderAddress:o,subject:i,snippet:l,trustReason:u,trustSubReason:m,senderTrust:f}=e;return r.jsxs("label",{className:V("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(oo,{className:"mt-0.5",checked:t,onChange:s,"aria-label":`${t?"Deselect":"Select"} ${n?i:`message from ${a}`}`}),!n&&r.jsx(kt,{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}),f&&r.jsx(zc,{senderTrust:f,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:l}),!n&&r.jsxs("span",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[r.jsxs(St,{tone:"positive",children:[r.jsx(gn,{className:"size-3","aria-hidden":!0}),u]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:m})]})]})]})}const Og=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)},Pg=(e,t)=>{const s=e.messages.filter(n=>t.has(n.id)).length;return s===0?"none":s===e.messages.length?"all":"some"},Ei=e=>e===1?"message":"messages";function Dg({group:e,selected:t,onToggleGroup:s,onToggleMessage:n}){const[a,o]=c.useState(!1),i=Pg(e,t),l=e.messages.length,u=a?Wt:As;return r.jsxs("div",{className:V(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(oo,{className:"mt-0.5",checked:i==="all",indeterminate:i==="some",onChange:()=>s(e,i!=="all"),"aria-label":`${i==="all"?"Deselect":"Select"} all ${l} ${Ei(l)} from ${e.senderName}`}),r.jsx(kt,{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(zc,{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(St,{tone:"positive",children:[r.jsx(gn,{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:[`${l} ${Ei(l)}`,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(Ag,{candidate:m,selected:t.has(m.id),onToggle:()=>n(m.id),hideSender:!0},m.id))})]})}const co=e=>e===1?"message":"messages",Lg=(e,t)=>`Moves ${e===1?"this message":`these ${e} ${co(e)}`} out of Spam to ${t} now. Nothing later.`,fa=(e,t)=>e.find(s=>s.id===t)?.label??"Inbox";function Fg(){return r.jsx(hn,{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 $g({candidates:e,selected:t,onToggle:s,onToggleGroup:n,onSelectAll:a,onSelectNone:o,onContinue:i,onCancel:l}){const[u,m]=c.useState(!1),f=t.size,d=c.useMemo(()=>Og(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(gn,{className:"size-4 text-positive","aria-hidden":!0}),"Rescue from Spam"]}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Pm,{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(Fg,{})})]}),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:`${f} of ${e.length} selected · ${d.length} ${d.length===1?"sender":"senders"}`}),r.jsxs("span",{className:"flex gap-1",children:[r.jsx(le,{variant:"ghost",size:"sm",onClick:a,children:"Select all"}),r.jsx(le,{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:d.map(h=>r.jsx(Dg,{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(le,{variant:"primary",onClick:i,className:"h-11 w-full font-semibold",children:`Continue with ${f} ${co(f)}`}),r.jsx(le,{variant:"ghost",onClick:l,className:"h-11 w-full",children:"Cancel"})]})]})}function _g({count:e,folders:t,delimiter:s,destination:n,onPick:a,onMove:o,onBack:i}){const[l,u]=c.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:l?r.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden rounded-xl border border-line bg-surface",children:r.jsx(Fl,{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:fa(t,n)}),r.jsx(le,{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:Lg(e,fa(t,n))}),r.jsx(le,{variant:"primary",onClick:o,className:"h-11 w-full font-semibold",children:`Move ${e} out of Spam`}),r.jsx(le,{variant:"ghost",onClick:i,className:"h-11 w-full",children:"Back"})]})]})}function zg({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(Gm,{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(le,{variant:"primary",onClick:s,className:"h-11 w-full font-semibold",children:"Done"})})]})}function Bg({open:e,candidates:t,defaultDestinationId:s,availableFolders:n,delimiter:a,onConfirmMove:o,onCancel:i}){const[l,u]=c.useState("review"),[m,f]=c.useState(()=>e?new Set(t.map(x=>x.id)):new Set),[d,h]=c.useState(s),[v,g]=c.useState(0),p=c.useRef(!1);c.useEffect(()=>{e&&!p.current&&(u("review"),f(new Set(t.map(x=>x.id))),h(s),g(0)),p.current=e},[e,t,s]);const y=m.size,b=x=>{f(k=>{const M=new Set(k);return M.has(x)?M.delete(x):M.add(x),M})},S=(x,k)=>{f(M=>{const O=new Set(M);for(const C of x.messages)k?O.add(C.id):O.delete(C.id);return O})},w=()=>{const x=Array.from(m);g(x.length),o(x,d),u("done")};return r.jsxs(_m,{open:e,onClose:i,dismissLabel:"Close rescue",children:[l==="review"&&r.jsx($g,{candidates:t,selected:m,onToggle:b,onToggleGroup:S,onSelectAll:()=>f(new Set(t.map(x=>x.id))),onSelectNone:()=>f(new Set),onContinue:()=>u("destination"),onCancel:i}),l==="destination"&&r.jsx(_g,{count:y,folders:n,delimiter:a,destination:d,onPick:h,onMove:w,onBack:()=>u("review")}),l==="done"&&r.jsx(zg,{count:v,destinationLabel:fa(n,d),onClose:i})]})}const Ii=e=>e.toLocaleString();function Ti({selectAll:e,selecting:t,className:s}){return r.jsx(oo,{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 uo({title:e,count:t,onCancel:s,onDelete:n,onMove:a,onOrganize:o,onJunk:i,onMarkRead:l,navSlot:u,titleMeta:m,searchSlot:f,searchField:d,idleSlot:h,overflowSlot:v,isBusy:g=!1,isCounting:p=!1,selectAll:y,statusLabel:b,progress:S,notice:w}){const x=t>0||p,k=y?.checked?`All ${Ii(t)} loaded selected`:`${Ii(t)} ${t===1?"message":"messages"} selected`,M=[];return i&&!g&&!p&&M.push({key:"junk",label:"Junk",icon:r.jsx(Fs,{className:"size-4"}),onSelect:i}),l&&!g&&!p&&M.push({key:"mark-read",label:"Mark read",icon:r.jsx(ur,{className:"size-4"}),onSelect:l}),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:[x?r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(Ma,{className:"size-5"}),onClick:s,"aria-label":"Cancel selection",className:"-ml-2 shrink-0"}):u,y&&r.jsx(Ti,{selectAll:y,selecting:x,className:"hidden shrink-0 pr-2 md:flex"}),x?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:b??k}):d?r.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:d}):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,f]}),x&&!p&&r.jsxs(r.Fragment,{children:[r.jsx(le,{variant:"ghost",size:"touch",icon:g?r.jsx(Ds,{className:"size-5 animate-spin"}):r.jsx(Rt,{className:"size-5 text-danger"}),onClick:g?void 0:n,"aria-label":"Move selected messages to Trash","aria-busy":g||void 0,className:"shrink-0"}),!g&&a&&r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(Ta,{className:"size-5"}),onClick:a,"aria-label":"Move selected messages",className:"shrink-0"}),!g&&o&&r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(Tt,{className:"size-5"}),onClick:o,"aria-label":"Organize selected messages",className:"shrink-0"})]}),x&&r.jsx(ao,{triggerLabel:"More actions",items:M,className:"shrink-0",children:!g&&!p&&v})]}),!x&&h,x&&y&&r.jsx("div",{"data-selection-bar-row":"select-all",className:"px-row-inset pb-2 md:hidden",children:r.jsx(Ti,{selectAll:y,selecting:x,className:"w-full"})}),S&&r.jsx("div",{className:"px-row-inset pb-2",children:r.jsx(Ef,{value:S.value,max:S.max,tone:S.tone})}),w&&r.jsx(hn,{"data-selection-notice":"",tone:w.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:[w.text&&r.jsx("span",{children:w.text}),w.action&&r.jsx(le,{variant:"ghost",size:"md",onClick:w.action.onClick,className:"-my-1 min-h-11 shrink-0",children:w.action.label})]})})]})}const fo=[{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"}],Bc={id:"unread",label:"Unread"},Kg={id:"flagged",label:"Starred"},Kc={id:"attachment",label:"Has attachment"};function Ug(e){if(!(e.length<=1))return e.map(t=>({id:t.id,label:t.label,count:t.count,active:t.active}))}function qg(e=[]){return{categories:[...fo],filters:If,sources:Ug(e)}}function Uc(){return{categories:[...fo],filters:[Bc,Kg,Kc]}}function Hg(){return{categories:[...fo],filters:[Bc,Kc]}}function Wg(e,t){return e.endsWith(t)?e.length===t.length||e[e.length-t.length-1]===".":!1}function Vg(e,t){const s=e.length-t.length-2,n=e.lastIndexOf(".",s);return n===-1?e:e.slice(n+1)}function Qg(e,t,s){if(s.validHosts!==null){const a=s.validHosts;for(const o of a)if(Wg(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:Vg(t,e)}const $r=/[\t\n\r]/g;let ma=!1;function Ri(e){return e>=97&&e<=122||e>=48&&e<=57||e>127||e>=65&&e<=90||e===45||e===95}function Mi(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,l=e.charCodeAt(t+3)|32;return a===104&&o===116&&i===116&&l===112?1:a===102&&o===105&&i===108&&l===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 rn(e,t,s=!1){let n=0,a=e.length,o=!1,i=!1;if(ma=!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 y=e.indexOf(":/",n);if(y!==-1){const b=Mi(e,n,y);if(b===1)for(i=!0,n=y+2;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1;else if(b===2){i=!0,n=y+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<y;S+=1){const w=e.charCodeAt(S)|32;if(!(w>=97&&w<=122||w>=48&&w<=57||w===46||w===45||w===43)){const x=e.charCodeAt(S);return x===9||x===10||x===13?rn(e.replace($r,""),t,s):null}}if(e.charCodeAt(y+2)===47)n=y+3;else return null}}else if(e.charCodeAt(n)!==91){let b=-1;for(let S=n;S<a;S+=1){const w=e.charCodeAt(S);if(w===9||w===10||w===13)return rn(e.replace($r,""),t,s);if(w===58){b=S;break}if(w===47||w===92||w===63||w===35)break}if(b!==-1){let S=!1;for(let w=b+1;w<a;w+=1){const x=e.charCodeAt(w);if(x===47||x===92||x===63||x===35)break;if(x===64){S=!0;break}}if(!S){let w=!0,x=b+1;for(;x<a;x+=1){const k=e.charCodeAt(x);if(k===47||k===92||k===63||k===35)break;if(k<48||k>57){w=!1;break}}if(x===b+1&&(w=!1),!w){const k=Mi(e,n,b);if(k===0){let M=!1;for(let O=b+1;O<a;O+=1){const C=e.charCodeAt(O);if(C===47||C===92||C===63||C===35)break;if(C===58){M=!0;break}}if(!M)return null}else if(i=!0,n=b+1,k===2){let M=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&M<2;)n+=1,M+=1;if(M<2)return null}else for(;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1}}}}}let u=-1,m=-1,f=-1,d=-1,h=!1,v=s,g=n-1,p=-1;if(s&&n<a){const y=e.charCodeAt(n);(!(Ri(y)||y===46||y===95)||y===45)&&(v=!1)}for(let y=n;y<a;y+=1){const b=e.charCodeAt(y);if(b<64)if(b===47||b===35||b===63){a=y;break}else b===58?(d===-1&&(d=y),f=y):b===9||b===10||b===13?h=!0:s&&(b===46?((y-g>64||p===46||p===45)&&(v=!1),g=y):(b<48||b>57)&&(b!==45||p===46)&&(v=!1));else if(i&&b===92){a=y;break}else b===64?(u=y,d=-1):b===93?m=y:b>=65&&b<=90?o=!0:s&&!Ri(b)&&(v=!1);s&&(p=b)}if(h)return rn(e.replace($r,""),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(f!==-1&&f>n&&f<a&&d===f&&(a=f),n>=a)return null;s&&v&&u===-1&&f===-1&&m===-1&&e.charCodeAt(a-1)!==46&&a-n<=255&&a-g-1<=63&&p!==45&&(ma=!0)}for(;a>n+1&&e.charCodeAt(a-1)===46;)a-=1;const l=n!==0||a!==e.length?e.slice(n,a):e;return o?l.toLowerCase():l}function Gg(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 Yg(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 Xg(e){return Yg(e)||Gg(e)}function Ai(e){return e>=97&&e<=122||e>=48&&e<=57||e>127}function Oi(e){if(e.length>255||e.length===0||!Ai(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(!(Ai(o)||o===45||o===95)||o===45&&s===46)return!1;s=o}return n-t-1<=63&&s!==45}function Jg({allowIcannDomains:e=!0,allowPrivateDomains:t=!1,detectIp:s=!0,detectSpecialUse:n=!1,extractHostname:a=!0,mixedInputs:o=!0,validHosts:i=null,validateHostname:l=!0}){return{allowIcannDomains:e,allowPrivateDomains:t,detectIp:s,detectSpecialUse:n,extractHostname:a,mixedInputs:o,validHosts:i,validateHostname:l}}const Zg=Jg({});function ex(e){return Zg}function tx(){return{domain:null,domainWithoutSuffix:null,hostname:null,isIcann:null,isIp:null,isPrivate:null,isSpecialUse:null,publicSuffix:null,subdomain:null}}function sx(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 nx(e,t,s,n,a){const o=ex();if(typeof e!="string")return a;let i=!1;return o.extractHostname?o.mixedInputs?(i=Oi(e),a.hostname=rn(e,i,o.validateHostname)):a.hostname=rn(e,!1,o.validateHostname):a.hostname=e,o.detectIp&&a.hostname!==null&&(a.isIp=Xg(a.hostname),a.isIp)?a:o.validateHostname&&o.extractHostname&&a.hostname!==null&&!(i&&a.hostname===e)&&!ma&&!Oi(a.hostname)?(a.hostname=null,a):(a.hostname===null||(s(a.hostname,o,a),a.publicSuffix===null)||(a.domain=Qg(a.publicSuffix,a.hostname,o)),a)}const Pi=tx();function rx(e,t){return sx(Pi),nx(e,3,Tf,t,Pi).domain}const fr=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},ax=e=>{const t=e.lastIndexOf("@");return t>=0?e.slice(t+1):e},qc=e=>rx(ax(e.trim())),ox=e=>{const t=fr(e);if(t.length<2)return null;let s=null;for(const n of t){const a=qc(n);if(a===null)return null;if(s===null)s=a;else if(s!==a)return null}return s},mr=e=>{const t=ox(e);return t!==null?[{field:"FromDomain",value:t}]:fr(e).map(s=>({field:"From",value:s}))},ix=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},Hc=e=>e.displayName?.trim()||e.normalizedEmail,lx=/^\s*(?:(?:re|aw|fwd?|vs|sv|antw|res|enc|tr)\s*(?:\[\d+\])?\s*:|\[[^\]]{1,32}\])\s*/i,cx=e=>{let t=e.replace(/\s+/g," ").trim();for(;;){const s=t.replace(lx,"");if(s===t)return t.trim();t=s}},ux=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"]),dx=3,_r=e=>e.split(" ").filter(t=>t!==""),Di=e=>e.length===0||e.join(" ").length<dx?!1:e.some(t=>!ux.has(t.toLowerCase())),fx=(e,t)=>e.findIndex((s,n)=>t.every((a,o)=>e[n+o]?.toLowerCase()===a.toLowerCase())),mx=e=>{const t=e.map(cx).filter(o=>o!=="");if(t.length===0)return;const[s,...n]=t;if(n.length===0)return Di(_r(s))?s:void 0;const a=_r(s);for(let o=a.length;o>0;o-=1)for(let i=0;i+o<=a.length;i+=1){const l=a.slice(i,i+o);if(Di(l)&&n.every(u=>fx(_r(u),l)>=0))return l.join(" ")}},hx=(e,t)=>{const s=mr(e);if(fr(e).length===1||s.length===1&&s[0].field==="FromDomain")return s;const n=mx(t);return n!==void 0?[{field:"Subject",value:n}]:s},px=({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}`:""},gx=e=>e.clauses.length>0,xx=e=>({scopedOutFolder:e.scopedOut?.label,droppedFacets:e.droppedFacets.map(t=>t.label),droppedSemantic:e.droppedSemantic});function Ht(e,t,{checkForDefaultPrevented:s=!0}={}){return function(a){if(e?.(a),s===!1||!a||!a.defaultPrevented)return t?.(a)}}function Li(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function bx(...e){return t=>{let s=!1;const n=e.map(a=>{const o=Li(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():Li(e[a],null)}}}}function ps(...e){return c.useCallback(bx(...e),e)}function vx(e,t=[]){let s=[];function n(o,i){const l=c.createContext(i);l.displayName=o+"Context";const u=s.length;s=[...s,i];const m=d=>{const{scope:h,children:v,...g}=d,p=h?.[e]?.[u]||l,y=c.useMemo(()=>g,Object.values(g));return r.jsx(p.Provider,{value:y,children:v})};m.displayName=o+"Provider";function f(d,h,v={}){const{optional:g=!1}=v,p=h?.[e]?.[u]||l,y=c.useContext(p);if(y)return y;if(i!==void 0)return i;if(!g)throw new Error(`\`${d}\` must be used within \`${o}\``)}return[m,f]}const a=()=>{const o=s.map(i=>c.createContext(i));return function(l){const u=l?.[e]||o;return c.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return a.scopeName=e,[n,yx(a,...t)]}function yx(...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((l,{useScope:u,scopeName:m})=>{const d=u(o)[`__scope${m}`];return{...l,...d}},{});return c.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return s.scopeName=t.scopeName,s}var cn=globalThis?.document?c.useLayoutEffect:()=>{},wx=Oa[" useInsertionEffect ".trim().toString()]||cn;function Sx({prop:e,defaultProp:t,onChange:s=()=>{},caller:n}){const[a,o,i]=kx({defaultProp:t,onChange:s}),l=e!==void 0,u=l?e:a;{const f=c.useRef(e!==void 0);c.useEffect(()=>{const d=f.current;d!==l&&console.warn(`${n} is changing from ${d?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=l},[l,n])}const m=c.useCallback(f=>{if(l){const d=jx(f)?f(e):f;d!==e&&i.current?.(d)}else o(f)},[l,e,o,i]);return[u,m]}function kx({defaultProp:e,onChange:t}){const[s,n]=c.useState(e),a=c.useRef(s),o=c.useRef(t);return wx(()=>{o.current=t},[t]),c.useEffect(()=>{a.current!==s&&(o.current?.(s),a.current=s)},[s,a]),[s,n,o]}function jx(e){return typeof e=="function"}function mo(e){const t=c.forwardRef((s,n)=>{let{children:a,...o}=s,i=null,l=!1;const u=[];Fi(a)&&typeof Nn=="function"&&(a=Nn(a._payload)),c.Children.forEach(a,h=>{if(Tx(h)){l=!0;const v=h;let g="child"in v.props?v.props.child:v.props.children;Fi(g)&&typeof Nn=="function"&&(g=Nn(g._payload)),i=Nx(v,g),u.push(i?.props?.children)}else u.push(h)}),i?i=c.cloneElement(i,void 0,u):!l&&c.Children.count(a)===1&&c.isValidElement(a)&&(i=a);const m=i?Ix(i):void 0,f=ps(n,m);if(!i){if(a||a===0)throw new Error(l?Ox(e):Ax(e));return a}const d=Ex(o,i.props??{});return i.type!==c.Fragment&&(d.ref=n?f:m),c.cloneElement(i,d)});return t.displayName=`${e}.Slot`,t}var uC=mo("Slot"),Cx=Symbol.for("radix.slottable"),Nx=(e,t)=>{if("child"in e.props){const s=e.props.child;return c.isValidElement(s)?c.cloneElement(s,void 0,e.props.children(s.props.children)):null}return c.isValidElement(t)?t:null};function Ex(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]=(...l)=>{const u=o(...l);return a(...l),u}:a&&(s[n]=a):n==="style"?s[n]={...a,...o}:n==="className"&&(s[n]=[a,o].filter(Boolean).join(" "))}return{...e,...s}}function Ix(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 Tx(e){return c.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Cx}var Rx=Symbol.for("react.lazy");function Fi(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Rx&&"_payload"in e&&Mx(e._payload)}function Mx(e){return typeof e=="object"&&e!==null&&"then"in e}var Ax=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,Ox=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Nn=Oa[" use ".trim().toString()],Px=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],At=Px.reduce((e,t)=>{const s=mo(`Primitive.${t}`),n=c.forwardRef((a,o)=>{const{asChild:i,...l}=a,u=i?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),r.jsx(u,{...l,ref:o})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function Dx(e,t){e&&Pa.flushSync(()=>e.dispatchEvent(t))}function un(e){const t=c.useRef(e);return c.useEffect(()=>{t.current=e}),c.useMemo(()=>((...s)=>t.current?.(...s)),[])}var Lx="DismissableLayer",ha="dismissableLayer.update",Fx="dismissableLayer.pointerDownOutside",$x="dismissableLayer.focusOutside",$i,ho=c.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Wc=c.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:n=!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:l,onDismiss:u,...m}=e,f=c.useContext(ho),[d,h]=c.useState(null),v=d?.ownerDocument??globalThis?.document,[,g]=c.useState({}),p=ps(t,h),y=Array.from(f.layers),[b]=[...f.layersWithOutsidePointerEventsDisabled].slice(-1),S=b?y.indexOf(b):-1,w=d?y.indexOf(d):-1,x=f.layersWithOutsidePointerEventsDisabled.size>0,k=w>=S,M=c.useRef(!1),O=Ux(E=>{o?.(E),l?.(E),E.defaultPrevented||u?.()},{ownerDocument:v,deferPointerDownOutside:n,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:f.dismissableSurfaces,shouldHandlePointerDownOutside:c.useCallback(E=>{if(!(E instanceof Node))return!1;const L=[...f.branches].some(D=>D.contains(E));return k&&!L},[f.branches,k])}),C=qx(E=>{if(n&&M.current)return;const L=E.target;[...f.branches].some(j=>j.contains(L))||(i?.(E),l?.(E),E.defaultPrevented||u?.())},v),R=d?w===y.length-1:!1,P=un(E=>{E.key==="Escape"&&(a?.(E),!E.defaultPrevented&&u&&(E.preventDefault(),u()))});return c.useEffect(()=>{if(R)return v.addEventListener("keydown",P,{capture:!0}),()=>v.removeEventListener("keydown",P,{capture:!0})},[v,R,P]),c.useEffect(()=>{if(d)return s&&(f.layersWithOutsidePointerEventsDisabled.size===0&&($i=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),f.layersWithOutsidePointerEventsDisabled.add(d)),f.layers.add(d),_i(),()=>{s&&(f.layersWithOutsidePointerEventsDisabled.delete(d),f.layersWithOutsidePointerEventsDisabled.size===0&&(v.body.style.pointerEvents=$i))}},[d,v,s,f]),c.useEffect(()=>()=>{d&&(f.layers.delete(d),f.layersWithOutsidePointerEventsDisabled.delete(d),_i())},[d,f]),c.useEffect(()=>{const E=()=>g({});return document.addEventListener(ha,E),()=>document.removeEventListener(ha,E)},[]),r.jsx(At.div,{...m,ref:p,style:{pointerEvents:x?k?"auto":"none":void 0,...e.style},onFocusCapture:Ht(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Ht(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Ht(e.onPointerDownCapture,O.onPointerDownCapture)})});Wc.displayName=Lx;var _x="DismissableLayerBranch",zx=c.forwardRef((e,t)=>{const s=c.useContext(ho),n=c.useRef(null),a=ps(t,n);return c.useEffect(()=>{const o=n.current;if(o)return s.branches.add(o),()=>{s.branches.delete(o)}},[s.branches]),r.jsx(At.div,{...e,ref:a})});zx.displayName=_x;function Bx(){const e=c.useContext(ho),[t,s]=c.useState(null);return c.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),s}var Kx=()=>!0;function Ux(e,t){const{ownerDocument:s=globalThis?.document,deferPointerDownOutside:n=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:o,shouldHandlePointerDownOutside:i=Kx}=t,l=un(e),u=c.useRef(!1),m=c.useRef(!1),f=c.useRef(new Map),d=c.useRef(()=>{});return c.useEffect(()=>{function h(){m.current=!1,a.current=!1,f.current.clear()}function v(){return Array.from(f.current.values()).some(Boolean)}function g(w){if(!m.current)return;const x=w.target;x instanceof Node&&[...o].some(M=>M.contains(x))||f.current.set(w.type,!0),w.type==="click"&&window.setTimeout(()=>{m.current&&d.current()},0)}function p(w){m.current&&f.current.set(w.type,!1)}const y=w=>{if(w.target&&!u.current){let x=function(){s.removeEventListener("click",d.current);const M=v();h(),M||Vc(Fx,l,k,{discrete:!0})};if(!i(w.target)){s.removeEventListener("click",d.current),h(),u.current=!1;return}const k={originalEvent:w};m.current=!0,a.current=n&&w.button===0,f.current.clear(),!n||w.button!==0?x():(s.removeEventListener("click",d.current),d.current=x,s.addEventListener("click",d.current,{once:!0}))}else s.removeEventListener("click",d.current),h();u.current=!1},b=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const w of b)s.addEventListener(w,g,!0),s.addEventListener(w,p);const S=window.setTimeout(()=>{s.addEventListener("pointerdown",y)},0);return()=>{window.clearTimeout(S),s.removeEventListener("pointerdown",y),s.removeEventListener("click",d.current);for(const w of b)s.removeEventListener(w,g,!0),s.removeEventListener(w,p)}},[s,l,n,a,o,i]),{onPointerDownCapture:()=>u.current=!0}}function qx(e,t=globalThis?.document){const s=un(e),n=c.useRef(!1);return c.useEffect(()=>{const a=o=>{o.target&&!n.current&&Vc($x,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 _i(){const e=new CustomEvent(ha);document.dispatchEvent(e)}function Vc(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?Dx(a,o):a.dispatchEvent(o)}var En=0,ws=null;function Hx(){c.useEffect(()=>{ws||(ws={start:zi(),end:zi()});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),En++,()=>{En===1&&(ws?.start.remove(),ws?.end.remove(),ws=null),En=Math.max(0,En-1)}},[])}function zi(){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",Br="focusScope.autoFocusOnUnmount",Bi={bubbles:!1,cancelable:!0},Wx="FocusScope",Qc=c.forwardRef((e,t)=>{const{loop:s=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[l,u]=c.useState(null),m=un(a),f=un(o),d=c.useRef(null),h=ps(t,u),v=c.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;c.useEffect(()=>{if(n){let p=function(w){if(v.paused||!l)return;const x=w.target;l.contains(x)?d.current=x:zt(d.current,{select:!0})},y=function(w){if(v.paused||!l)return;const x=w.relatedTarget;x!==null&&(l.contains(x)||zt(d.current,{select:!0}))},b=function(w){if(document.activeElement===document.body)for(const k of w)k.removedNodes.length>0&&zt(l)};document.addEventListener("focusin",p),document.addEventListener("focusout",y);const S=new MutationObserver(b);return l&&S.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",y),S.disconnect()}}},[n,l,v.paused]),c.useEffect(()=>{if(l){Ui.add(v);const p=document.activeElement;if(!l.contains(p)){const b=new CustomEvent(zr,Bi);l.addEventListener(zr,m),l.dispatchEvent(b),b.defaultPrevented||(Vx(Jx(Gc(l)),{select:!0}),document.activeElement===p&&zt(l))}return()=>{l.removeEventListener(zr,m),setTimeout(()=>{const b=new CustomEvent(Br,Bi);l.addEventListener(Br,f),l.dispatchEvent(b),b.defaultPrevented||zt(p??document.body,{select:!0}),l.removeEventListener(Br,f),Ui.remove(v)},0)}}},[l,m,f,v]);const g=c.useCallback(p=>{if(!s&&!n||v.paused)return;const y=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,b=document.activeElement;if(y&&b){const S=p.currentTarget,[w,x]=Qx(S);w&&x?!p.shiftKey&&b===x?(p.preventDefault(),s&&zt(w,{select:!0})):p.shiftKey&&b===w&&(p.preventDefault(),s&&zt(x,{select:!0})):b===S&&p.preventDefault()}},[s,n,v.paused]);return r.jsx(At.div,{tabIndex:-1,...i,ref:h,onKeyDown:g})});Qc.displayName=Wx;function Vx(e,{select:t=!1}={}){const s=document.activeElement;for(const n of e)if(zt(n,{select:t}),document.activeElement!==s)return}function Qx(e){const t=Gc(e),s=Ki(t,e),n=Ki(t.reverse(),e);return[s,n]}function Gc(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 Ki(e,t){const s=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const n of e)if(!(s?!n.checkVisibility({checkVisibilityCSS:!0}):Gx(n,{upTo:t})))return n}function Gx(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 Yx(e){return e instanceof HTMLInputElement&&"select"in e}function zt(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&Yx(e)&&t&&e.select()}}var Ui=Xx();function Xx(){let e=[];return{add(t){const s=e[0];t!==s&&s?.pause(),e=qi(e,t),e.unshift(t)},remove(t){e=qi(e,t),e[0]?.resume()}}}function qi(e,t){const s=[...e],n=s.indexOf(t);return n!==-1&&s.splice(n,1),s}function Jx(e){return e.filter(t=>t.tagName!=="A")}var Zx=Oa[" useId ".trim().toString()]||(()=>{}),eb=0;function Kr(e){const[t,s]=c.useState(Zx());return cn(()=>{s(n=>n??String(eb++))},[e]),e||(t?`radix-${t}`:"")}var tb="Portal",Yc=c.forwardRef((e,t)=>{const{container:s,...n}=e,[a,o]=c.useState(!1);cn(()=>o(!0),[]);const i=s||a&&globalThis?.document?.body;return i?Pa.createPortal(r.jsx(At.div,{...n,ref:t}),i):null});Yc.displayName=tb;function sb(e,t){return c.useReducer((s,n)=>t[s][n]??s,e)}var hr=e=>{const{present:t,children:s}=e,n=nb(t),a=typeof s=="function"?s({present:n.isPresent}):c.Children.only(s),o=rb(n.ref,ab(a));return typeof s=="function"||n.isPresent?c.cloneElement(a,{ref:o}):null};hr.displayName="Presence";function nb(e){const[t,s]=c.useState(),n=c.useRef(null),a=c.useRef(e),o=c.useRef("none"),i=c.useRef(void 0),l=e?"mounted":"unmounted",[u,m]=sb(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return c.useEffect(()=>{u==="mounted"?(o.current=i.current??Qs(n.current),i.current=void 0):o.current="none"},[u]),cn(()=>{const f=n.current,d=a.current;if(d!==e){const v=o.current,g=Qs(f);e?(i.current=g,m("MOUNT")):g==="none"||f?.display==="none"?m("UNMOUNT"):m(d&&v!==g?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,m]),cn(()=>{if(t){let f;const d=t.ownerDocument.defaultView??window,h=g=>{const y=Qs(n.current).includes(CSS.escape(g.animationName));if(g.target===t&&y&&(m("ANIMATION_END"),!a.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",f=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},v=g=>{g.target===t&&(o.current=Qs(n.current))};return t.addEventListener("animationstart",v),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{d.clearTimeout(f),t.removeEventListener("animationstart",v),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:c.useCallback(f=>{if(f){const d=getComputedStyle(f);n.current=d,i.current=Qs(d)}else n.current=null;s(f)},[])}}function Hi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function rb(...e){const t=c.useRef(e);return t.current=e,c.useCallback(s=>{const n=t.current;let a=!1;const o=n.map(i=>{const l=Hi(i,s);return!a&&typeof l=="function"&&(a=!0),l});if(a)return()=>{for(let i=0;i<o.length;i++){const l=o[i];typeof l=="function"?l():Hi(n[i],null)}}},[])}function Qs(e){return e?.animationName||"none"}function ab(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 ob=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ss=new WeakMap,In=new WeakMap,Tn={},Ur=0,Xc=function(e){return e&&(e.host||Xc(e.parentNode))},ib=function(e,t){return t.map(function(s){if(e.contains(s))return s;var n=Xc(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})},lb=function(e,t,s,n){var a=ib(t,Array.isArray(e)?e:[e]);Tn[s]||(Tn[s]=new WeakMap);var o=Tn[s],i=[],l=new Set,u=new Set(a),m=function(d){!d||l.has(d)||(l.add(d),m(d.parentNode))};a.forEach(m);var f=function(d){!d||u.has(d)||Array.prototype.forEach.call(d.children,function(h){if(l.has(h))f(h);else try{var v=h.getAttribute(n),g=v!==null&&v!=="false",p=(Ss.get(h)||0)+1,y=(o.get(h)||0)+1;Ss.set(h,p),o.set(h,y),i.push(h),p===1&&g&&In.set(h,!0),y===1&&h.setAttribute(s,"true"),g||h.setAttribute(n,"true")}catch(b){console.error("aria-hidden: cannot operate on ",h,b)}})};return f(t),l.clear(),Ur++,function(){i.forEach(function(d){var h=Ss.get(d)-1,v=o.get(d)-1;Ss.set(d,h),o.set(d,v),h||(In.has(d)||d.removeAttribute(n),In.delete(d)),v||d.removeAttribute(s)}),Ur--,Ur||(Ss=new WeakMap,Ss=new WeakMap,In=new WeakMap,Tn={})}},cb=function(e,t,s){s===void 0&&(s="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),a=ob(e);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live], script"))),lb(n,a,s,"aria-hidden")):function(){return null}},$n="right-scroll-bar-position",_n="width-before-scroll-bar",ub="with-scroll-bars-hidden",db="--removed-body-scroll-bar-size";function qr(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function fb(e,t){var s=c.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 mb=typeof window<"u"?c.useLayoutEffect:c.useEffect,Wi=new WeakMap;function hb(e,t){var s=fb(null,function(n){return e.forEach(function(a){return qr(a,n)})});return mb(function(){var n=Wi.get(s);if(n){var a=new Set(n),o=new Set(e),i=s.current;a.forEach(function(l){o.has(l)||qr(l,null)}),o.forEach(function(l){a.has(l)||qr(l,i)})}Wi.set(s,e)},[e]),s}function pb(e){return e}function gb(e,t){t===void 0&&(t=pb);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(l){return l!==i})}},assignSyncMedium:function(o){for(n=!0;s.length;){var i=s;s=[],i.forEach(o)}s={push:function(l){return o(l)},filter:function(){return s}}},assignMedium:function(o){n=!0;var i=[];if(s.length){var l=s;s=[],l.forEach(o),i=s}var u=function(){var f=i;i=[],f.forEach(o)},m=function(){return Promise.resolve().then(u)};m(),s={push:function(f){i.push(f),m()},filter:function(f){return i=i.filter(f),s}}}};return a}function xb(e){e===void 0&&(e={});var t=gb(null);return t.options=Bt({async:!0,ssr:!1},e),t}var Jc=function(e){var t=e.sideCar,s=$l(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 c.createElement(n,Bt({},s))};Jc.isSideCarExport=!0;function bb(e,t){return e.useMedium(t),Jc}var Zc=xb(),Hr=function(){},pr=c.forwardRef(function(e,t){var s=c.useRef(null),n=c.useState({onScrollCapture:Hr,onWheelCapture:Hr,onTouchMoveCapture:Hr}),a=n[0],o=n[1],i=e.forwardProps,l=e.children,u=e.className,m=e.removeScrollBar,f=e.enabled,d=e.shards,h=e.sideCar,v=e.noRelative,g=e.noIsolation,p=e.inert,y=e.allowPinchZoom,b=e.as,S=b===void 0?"div":b,w=e.gapMode,x=$l(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,M=hb([s,t]),O=Bt(Bt({},x),a);return c.createElement(c.Fragment,null,f&&c.createElement(k,{sideCar:Zc,removeScrollBar:m,shards:d,noRelative:v,noIsolation:g,inert:p,setCallbacks:o,allowPinchZoom:!!y,lockRef:s,gapMode:w}),i?c.cloneElement(c.Children.only(l),Bt(Bt({},O),{ref:M})):c.createElement(S,Bt({},O,{className:u,ref:M}),l))});pr.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};pr.classNames={fullWidth:_n,zeroRight:$n};var vb=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function yb(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=vb();return t&&e.setAttribute("nonce",t),e}function wb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Sb(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var kb=function(){var e=0,t=null;return{add:function(s){e==0&&(t=yb())&&(wb(t,s),Sb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},jb=function(){var e=kb();return function(t,s){c.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},eu=function(){var e=jb(),t=function(s){var n=s.styles,a=s.dynamic;return e(n,a),null};return t},Cb={left:0,top:0,right:0,gap:0},Wr=function(e){return parseInt(e||"",10)||0},Nb=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[Wr(s),Wr(n),Wr(a)]},Eb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Cb;var t=Nb(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])}},Ib=eu(),Ms="data-scroll-locked",Tb=function(e,t,s,n){var a=e.left,o=e.top,i=e.right,l=e.gap;return s===void 0&&(s="margin"),`
76
- .`.concat(ub,` {
74
+ `},Dp=(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}",Lp=(e,t,s)=>{if(t==="plain")return`${ui}<style>${Pp(s)}</style>${e}`;const n=Op.test(e);return`${ui}<style>${Dp(s,n)}</style>${e}`},Fp=5e4,$p=1e4,_p="(max-width: 640px)",zp=.4,Bp="allow-same-origin allow-popups allow-popups-to-escape-sandbox",di=(e,t,s)=>Math.min(Math.ceil(Math.max(e,t)),s),Kp=(e,t)=>e<=0||t<=0||e<=t?1:Math.max(zp,t/e),Up=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},qp=new Set(["Enter","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"]),Hp=e=>e===" "?!1:e.length===1?!0:qp.has(e),fi=e=>{if(e.metaKey||e.ctrlKey||e.altKey||!Hp(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}))},mi=({html:e,variant:t="framed",isDark:s=!1,className:n})=>{const a=c.useRef(null),o=c.useRef(null),[i,l]=c.useState(0),[u,m]=c.useState(0),[f,d]=c.useState(0),h=Up(_p),v=c.useMemo(()=>Lp(e,t,s),[e,t,s]);c.useEffect(()=>{const w=a.current;if(!w)return;const x=()=>d(M=>M===w.clientWidth?M:w.clientWidth);x();const k=new ResizeObserver(x);return k.observe(w),()=>k.disconnect()},[]),c.useEffect(()=>{const w=o.current;if(!w)return;const x=()=>{const j=w.contentDocument;if(!j?.body)return;const R=j.documentElement,P=di(j.body.scrollHeight,R?.scrollHeight??0,Fp);l(L=>L===P?L:P);const E=di(j.body.scrollWidth,R?.scrollWidth??0,$p);m(L=>L===E?L:E)};let k,M;const O=()=>{x();const j=w.contentDocument;j?.body&&(k=new ResizeObserver(x),k.observe(j.body),j.documentElement&&k.observe(j.documentElement),j.addEventListener("keydown",fi),M=j)};return w.addEventListener("load",O),()=>{w.removeEventListener("load",O),M?.removeEventListener("keydown",fi),k?.disconnect()}},[]);const g=h?Kp(u,f):1,p=g<1,y=p?`${u}px`:h?"100%":t==="framed"&&u>0?`max(100%, ${u}px)`:u===0?"100%":`${u}px`,b=i===0?"1px":`${i}px`,S=r.jsx("iframe",{ref:o,title:"Email content",sandbox:Bp,srcDoc:v,className:p?void 0:n,scrolling:"no",style:{width:y,maxWidth:p?"none":void 0,border:"none",display:"block",height:b,overflow:"hidden",transform:p?`scale(${g})`: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*g)}px`,overflow:"hidden"},children:S}):S})},hi=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Pc=({html:e,text:t,isDark:s=!1,category:n,allowImages:a=!1,resolveCid:o,className:i,renderBlockedNotice:l})=>{const u=c.useMemo(()=>!e||typeof document>"u"?null:Mp({allowExternalImages:a,resolveCid:o})(e),[e,a,o]),m=u?.html??null,{framed:f,isPlain:d}=vp(n,u?.hasAuthorBackground??!1),h=c.useMemo(()=>!m||a?0:(m.match(/data-blocked-src/g)||[]).length,[m,a]);return!m&&!t?r.jsx("div",{className:V("message-body",i),children:r.jsx(hi,{})}):r.jsxs("div",{className:V("message-body",i),children:[h>0&&r.jsx("div",{className:"message-body-notice",children:l?.(h)}),m?f?r.jsx("div",{className:"w-full max-w-full overflow-x-auto",children:r.jsx(mi,{html:m,variant:"framed",isDark:s})}):r.jsx("div",{className:"max-w-full overflow-x-auto lg:max-w-2xl",children:r.jsx(mi,{html:m,variant:d?"plain":"framed",isDark:s})}):t?r.jsx("pre",{className:"email-text whitespace-pre-wrap text-sm leading-relaxed",children:t}):r.jsx(hi,{})]})};function $s({message:e="Select a thread to read",icon:t,showHints:s=!0,className:n}){return r.jsxs("div",{className:V("flex flex-1 flex-col items-center justify-center text-center",n),children:[t??r.jsx(Ra,{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(Is,{children:"j"})," / ",r.jsx(Is,{children:"k"})," to move, ",r.jsx(Is,{children:"Enter"})," to open"]})]})}function Dc({message:e,onClick:t,isFocused:s,isUnread:n,trailing:a}){const o=r.jsxs(r.Fragment,{children:[r.jsx(Ms,{className:"size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{className:"relative shrink-0",children:[r.jsx(kt,{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:V("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=V("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:l=>{hf(l)&&(l.preventDefault(),t())},className:V(i,"cursor-pointer"),children:o}):r.jsx("div",{className:i,children:o})}function Lc({message:e,warning:t,onHeaderClick:s,isFocused:n,senderBadge:a,trailing:o,to:i,indicators:l,actionMenu:u,actionBar:m,body:f}){const d=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:V("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(Wt,{className:"mt-1 size-3.5 shrink-0 text-fg-subtle"}),r.jsx(kt,{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:d}):d,l]}),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(Ls,{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:f??r.jsx(Pc,{className:"mt-3",html:e.bodyHtml,category:e.framed?"newsletter":"personal",allowImages:!0})})]})}function Wp({thread:e,onBack:t,intelligence:s,intelligenceOpen:n,onToggleIntelligence:a,actions:o,children:i,touchHandlers:l}){const[u,m]=c.useState(!1),f=a!==void 0,d=f?n??!1:u,h=!!s||f,v=()=>{if(f){a?.();return}m(p=>!p)},g=()=>{if(f){d&&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(le,{variant:"ghost",size:"sm",icon:r.jsx(Ma,{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(le,{variant:"ghost",size:"sm",icon:r.jsx(Tl,{className:"size-4"}),onClick:v,"aria-label":d?"Hide intelligence panel":"Show intelligence panel","aria-pressed":d,title:"Intelligence",className:V("shrink-0",d&&"bg-accent-2-soft text-accent-2")})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",style:l?{touchAction:"pan-y"}:void 0,...l,children:i??e.messages.map(p=>{const y=b=>b?()=>b(p.id):void 0;return p.expanded?r.jsx(Lc,{message:p,warning:e.warning,onHeaderClick:y(o?.onToggleExpand),actionBar:r.jsx(Oc,{hasThread:!0,onReply:y(o?.onReply),onReplyAll:y(o?.onReplyAll),onForward:y(o?.onForward),onToggleStar:y(o?.onToggleStar),onDelete:y(o?.onDelete),onToggleRead:y(o?.onToggleRead),moveSlot:o?.moveSlot?.(p.id)})},p.id):r.jsx(Dc,{message:p,onClick:y(o?.onToggleExpand)},p.id)})}),s&&!f&&r.jsx(pf,{open:d,onClose:g,title:"Intelligence",anchor:"right",className:"p-0",children:r.jsx(Sc,{data:s,onClose:g,className:"h-full w-full border-l-0"})})]})}const Vp="button:not([disabled]), a[href]",os="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface-sunken";function Qp({active:e,dimmed:t,indent:s}){return V("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors",os,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 Gp({icon:e,label:t,count:s,active:n}){return r.jsxs(r.Fragment,{children:[e&&r.jsx("span",{className:V("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:V("text-2xs tabular-nums",n?"text-accent-2":"text-fg-subtle"),children:s})]})}function nn({icon:e,label:t,count:s,active:n,dimmed:a,indent:o,navId:i,linkComponent:l,ariaLabel:u,title:m,onClick:f}){const d=Qp({active:n,dimmed:a,indent:o}),h=r.jsx(Gp,{icon:e,label:t,count:s,active:n});return i&&l?l({navId:i,className:d,ariaLabel:u??t,title:m,onClick:f,children:h}):r.jsx("button",{type:"button",onClick:f,className:d,"aria-label":u,title:m,children:h})}const pi={inbox:0,flagged:1,drafts:2,sent:3,archive:4,all:5,junk:6,trash:7};function Yp(e){switch(e){case"inbox":return r.jsx(Ra,{className:"size-4"});case"flagged":return r.jsx(Gt,{className:"size-4"});case"drafts":return r.jsx(Ml,{className:"size-4"});case"sent":return r.jsx(mn,{className:"size-4"});case"archive":return r.jsx(vf,{className:"size-4"});case"all":return r.jsx(bf,{className:"size-4"});case"junk":return r.jsx(xf,{className:"size-4"});case"trash":return r.jsx(Rt,{className:"size-4"})}}const gi=e=>e.role!=null,Fr=8,xi="remit.nav.folders.open.",bi="remit.nav.account.open.";function vi(e,t,s){if(typeof localStorage>"u")return s;const n=localStorage.getItem(e+t);return n===null?s:n!=="0"}function yi(e,t,s){typeof localStorage>"u"||localStorage.setItem(e+t,s?"1":"0")}function Xp({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:V("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",os),children:[r.jsx(Zn,{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:V("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",os),children:r.jsx(Ct,{className:"size-3.5"})})]})}function Jp({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:V("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-accent transition-colors hover:bg-surface",os),children:[r.jsx(Ph,{className:"size-4 shrink-0"}),r.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Save “",t,"”"]})]}),e.map(o=>r.jsx(Xp,{query:o,onSelect:()=>s?.(o),onRemove:n?()=>n(o):void 0},o))]})}function Zp({account:e,selectedNavId:t,onSelectNav:s,linkComponent:n}){const[a,o]=c.useState(()=>vi(bi,e.id,!0)),[i,l]=c.useState(()=>vi(xi,e.id,!0)),[u,m]=c.useState(!1),f=()=>{o(S=>{const w=!S;return yi(bi,e.id,w),w})},d=()=>{l(S=>{const w=!S;return yi(xi,e.id,w),w})},h=e.mailboxes.filter(gi).sort((S,w)=>pi[S.role]-pi[w.role]),v=e.mailboxes.filter(S=>!gi(S)),g=u||v.length<=Fr?v:v.slice(0,Fr),p=v.length-g.length,y=e.status??"ready",b=y==="ready"&&h.length===0&&v.length===0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("button",{type:"button",onClick:f,"aria-expanded":a,className:V("flex w-full items-center gap-1.5 px-2 pb-1 text-left transition-colors hover:text-fg",os,e.muted&&"opacity-55"),children:[a?r.jsx(Wt,{className:"size-3 shrink-0 text-fg-subtle"}):r.jsx(Ms,{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(dc,{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:[y==="loading"&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"Loading…"}),y==="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(ds,{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"})]}),b&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"No mailboxes"}),y==="ready"&&r.jsxs(r.Fragment,{children:[h.map(S=>r.jsx(nn,{navId:S.id,linkComponent:n,icon:Yp(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(nn,{navId:"outbox",linkComponent:n,icon:r.jsx(mn,{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:d,"aria-expanded":i,className:V("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",os),children:[i?r.jsx(Wt,{className:"size-3 shrink-0"}):r.jsx(Ms,{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:[g.map(S=>r.jsx(nn,{navId:S.id,linkComponent:n,icon:r.jsx(gf,{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>Fr&&r.jsx("button",{type:"button",onClick:()=>m(S=>!S),className:V("ml-7 flex items-center px-2 py-1 text-2xs font-medium text-accent transition-colors hover:underline",os),children:u?"Show less":`Show all (${v.length})`})]})]})]})]})]})}function eg({accounts:e,selectedNavId:t,briefUnseen:s,onSelectNav:n,variant:a="desktop",linkComponent:o,savedSearches:i=[],saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:f}){const d=c.useRef(null);Jn({containerRef:d,itemSelector:Vp});const h=a==="drawer",v=r.jsxs("nav",{ref:h?d:void 0,className:h?"px-2 py-2":"flex-1 overflow-y-auto px-2 py-2","aria-label":"Mailboxes",children:[r.jsx(nn,{navId:"brief",linkComponent:o,icon:r.jsx(Tt,{className:"size-4"}),label:"Daily brief",ariaLabel:"Daily brief",count:s,active:t==="brief",onClick:()=>n?.("brief")}),r.jsx(nn,{navId:"flagged",linkComponent:o,icon:r.jsx(Gt,{className:"size-4"}),label:"Starred",ariaLabel:"Starred",active:t==="flagged",onClick:()=>n?.("flagged")}),r.jsx(Jp,{savedSearches:i,saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:f}),e.length===0?r.jsx("div",{className:"px-2 py-4 text-center text-sm text-fg-muted",children:"No accounts configured"}):e.map(g=>r.jsx(Zp,{account:g,selectedNavId:t,onSelectNav:n,linkComponent:o},g.id))]});return h?v:r.jsx("aside",{ref:d,className:"flex h-full w-full flex-col bg-surface-sunken",children:v})}function tg({leading:e,search:t,actions:s,className:n}){return r.jsxs("header",{className:V("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})]})}function sg({label:e,onUndo:t,undoLabel:s="Undo",filtersHref:n,className:a}){return r.jsxs(St,{tone:"accent",className:V("py-1 text-xs",a),children:[r.jsx(Bh,{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 ng({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(Ps,{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:rg(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(Tt,{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 rg({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 ag="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",wi="pointer-events-none absolute inset-0 m-auto size-3.5 text-accent-fg";function ro({label:e,description:t,indeterminate:s=!1,checked:n,onChange:a,className:o,...i}){const l=c.useRef(null);c.useEffect(()=>{l.current&&(l.current.indeterminate=s)},[s]);const u=r.jsxs("span",{className:"relative inline-flex",children:[r.jsx("input",{ref:l,type:"checkbox",checked:n,onChange:a,className:ag,...i}),r.jsx(fn,{className:V(wi,"hidden peer-checked:block"),"aria-hidden":!0}),r.jsx(Fh,{className:V(wi,"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:V("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 og=({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 ig({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(le,{variant:"primary",size:"md","aria-busy":s,title:n?void 0:o,className:"min-h-11 rounded-full px-4",icon:s?r.jsx(Ps,{className:"size-4 animate-spin"}):r.jsx(mn,{className:"size-4"}),onClick:()=>{if(!s){if(!n){o&&i?.(o);return}e()}},children:"Send"}),r.jsx(og,{status:a})]}),r.jsx(le,{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(Rt,{className:"size-4"}),onClick:()=>{s||t()}})]})}function lg({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:"min-h-0 flex-1 overflow-auto",children:[s,n&&r.jsx("div",{className:"px-3 pb-2",children:n})]}),a]})}function cg({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 ug({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 dg(e,t){const s=t-1;return s<=0?null:e<s?e:s-1}const fg=e=>e instanceof HTMLElement?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable:!1,mg=({chips:e=[],onRemoveChip:t,value:s,onChange:n,onClear:a,onClearQuery:o,placeholder:i="Search mail...",globalFocusKey:l=!0,showClearButton:u=!0,size:m="sm",inputId:f,suggest:d,className:h})=>{const v=c.useId(),g=f??v,p=c.useRef(null),y=c.useRef([]),b=o??a,[S,w]=c.useState(null),x=c.useRef(void 0),[k,M]=c.useState(""),O=e.length>0;c.useEffect(()=>{w(T=>T!==null&&T>=e.length?null:T)},[e.length]),c.useEffect(()=>{const T=x.current;if(T!==void 0){if(x.current=void 0,T===null){p.current?.focus();return}y.current[T]?.focus()}});const j=c.useRef(void 0);c.useEffect(()=>{const T=d?.caret;if(!T||T===j.current)return;j.current=T;const A=p.current;!A||A.ownerDocument.activeElement!==A||(A.setSelectionRange(T.cursor,T.cursor),d?.onCaretChange(T.cursor))});const R=T=>{d?.onCaretChange(T.selectionStart??T.value.length)},P=c.useCallback(T=>{w(T),x.current=T},[]),E=c.useCallback(T=>{const A=e[T];A&&t&&(P(dg(T,e.length)),M(`${A.label} removed`),t(A.id))},[e,t,P]),L=c.useCallback(()=>{P(null),a()},[a,P]),D=c.useCallback(T=>{const A=T.currentTarget;if(d?.onKeyDown(T))return;const I=cg({key:T.key,shiftKey:T.shiftKey,repeat:T.repeat,caretAtStart:A.selectionStart===0&&A.selectionEnd===0,hasValue:s.length>0,chipCount:e.length});switch(I.type){case"focusChip":T.preventDefault(),P(I.index);return;case"clearQuery":b();return;case"blur":A.blur();return;case"none":return}},[e.length,s,b,P,d]),C=c.useCallback(T=>A=>{const I=ug({key:A.key,repeat:A.repeat,index:T,chipCount:e.length});switch(I.type!=="none"&&A.preventDefault(),I.type){case"removeChip":E(I.index);return;case"focusChip":P(I.index);return;case"focusInput":P(null);return;case"activateChip":return;case"none":return}},[e,E,P]);return c.useEffect(()=>{if(!l)return;const T=A=>{A.key!=="/"||A.metaKey||A.ctrlKey||A.altKey||fg(A.target)||(A.preventDefault(),p.current?.focus())};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[l]),r.jsxs("label",{htmlFor:g,className:V("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(Zn,{className:V("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:[O&&r.jsx("div",{role:"grid","aria-label":"Search filters",className:"flex min-w-0 flex-wrap items-center gap-1",children:e.map((T,A)=>r.jsx(yf,{ref:I=>{y.current[A]=I},label:T.label,tone:T.tone,focused:S===A,onFocusLabel:()=>w(A),onKeyDown:C(A),onRemove:()=>E(A)},T.id))}),r.jsx("input",{ref:p,id:g,name:"q",type:"text","aria-label":"Search mail",autoComplete:"off",value:s,tabIndex:S===null?0:-1,onChange:T=>{n(T.target.value),R(T.target)},onKeyDown:D,onKeyUp:T=>R(T.currentTarget),onClick:T=>R(T.currentTarget),onFocus:T=>{w(null),d?.onFocusChange?.(!0),R(T.currentTarget)},onBlur:()=>d?.onFocusChange?.(!1),...d?.comboboxProps,placeholder:O?void 0:i,className:"min-w-24 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted"})]}),(s||O)&&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(Ct,{className:V("text-fg-muted",m==="lg"?"size-5":"size-4")})}),r.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:k})]})},ao=({value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i="Search mail...",globalFocusKey:l=!0,showClearButton:u=!0,size:m,inputId:f,suggest:d,className:h})=>r.jsx(mg,{value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i,globalFocusKey:l,showClearButton:u,size:m,inputId:f,suggest:d,className:h});function hg(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 pg({result:e,onClick:t,query:s,showFolder:n=!0}){const a=n&&e.folder?wf(e.folder):void 0;return r.jsx("button",{type:"button",onClick:t,className:V("group",Fs({}),"border-b border-line"),children:r.jsx(so,{thread:hg(e),highlightQuery:s,badge:r.jsxs(r.Fragment,{children:[a&&r.jsx(St,{tone:"neutral",className:"shrink-0",children:a}),e.category&&r.jsx(St,{tone:e.category.tone??"neutral",className:"shrink-0",children:e.category.label}),e.matchedChunkLabel&&r.jsx(St,{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 gg=e=>e===1?"result":"results";function Fc({count:e,onScopeToSpam:t}){return r.jsx(hn,{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})," ",`${gg(e)} from Spam`]}),r.jsx(le,{variant:"ghost",size:"sm",onClick:t,className:"shrink-0 text-accent",children:"Go to Spam"})]})})}const Si=6,xg={kind:"global"},bg=e=>e.kind==="folder"&&e.role==="junk",vg=e=>e.folder?.role==="junk";function oo(e){const t=[],s=[];for(const n of e)vg(n)?s.push(n):t.push(n);return{kept:t,spam:s}}function $c({onClick:e,blockedReason:t}){const s=c.useId(),[n,a]=c.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:V("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(Sf,{className:"size-3.5 shrink-0","aria-hidden":"true"}),r.jsx("span",{children:"Make this a filter"})]}),t&&r.jsx(kf,{id:s,reason:t,nudged:n,className:"px-2 pt-1 text-2xs text-warning"})]})}function yg({section:e,query:t,onSelectResult:s,showFolder:n}){const[a,o]=c.useState(e.initialCollapsed??!1),[i,l]=c.useState(!1),u=e.results.length>Si,f=!i&&u?e.results.slice(0,Si):e.results,d=e.results.length-f.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(Wt,{className:V("size-3 shrink-0 text-fg-subtle transition-transform duration-200",a?"rotate-0":"rotate-180")})]}),!a&&r.jsxs(r.Fragment,{children:[f.map(h=>r.jsx(pg,{result:h,query:t,showFolder:n,onClick:s?()=>s(h):void 0},h.id)),u&&r.jsxs("button",{type:"button",onClick:()=>l(h=>!h),className:"flex w-full items-center justify-center border-b border-line px-row-inset py-1.5 text-2xs font-medium text-accent transition-colors hover:bg-surface",children:[i?"Show less":`Show ${d} more`,!i&&r.jsx(Wt,{className:"ml-1 size-3"})]})]})]})}function _c({value:e,recentSearches:t,onPickRecent:s,sections:n,loading:a,onSelectResult:o,tokens:i,scope:l=xg,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(x=>r.jsxs("button",{type:"button",onClick:()=>s?.(x),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(Ga,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-fg-muted",children:x})]},x))]}):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 f=i&&i.length>0&&r.jsx(Cf,{tokens:i}),d=u&&r.jsx($c,{...u});if(a)return r.jsxs("div",{className:"flex flex-col",children:[d,f,r.jsx("div",{className:"flex flex-col gap-3 px-row-inset py-4",children:[0,1,2,3].map(x=>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"})]},x))})]});const h=l.kind==="global",v=bg(l)||l.kind==="collection",g=h||l.kind==="collection",p=(n??[]).map(x=>{if(v)return{section:x,spam:[]};const{kept:k,spam:M}=oo(x.results);return{section:{...x,results:k},spam:M}}),y=p.map(x=>x.section),b=p.reduce((x,k)=>x+k.spam.length,0),S=l.kind==="global"&&b>0&&l.onScopeToSpam!==void 0?r.jsx(Fc,{count:b,onScopeToSpam:l.onScopeToSpam}):void 0;return y.some(x=>x.results.length>0)?r.jsxs("div",{className:"flex flex-col",children:[d,f,S,y.filter(x=>x.results.length>0).map(x=>r.jsx(yg,{section:x,query:e,showFolder:g,onSelectResult:o},x.id))]}):r.jsxs("div",{className:"flex flex-col",children:[d,f,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 wg({value:e,onChange:t,onClear:s,onCancel:n,filter:a,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:m,tokens:f,chips:d,onRemoveChip:h,scope:v,makeFilter:g,suggest:p,suggestList:y}){const b=r.jsx(_c,{value:e,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:m,tokens:f,scope:v,makeFilter:g});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(ao,{value:e,onChange:t,onClear:s,chips:d,onRemoveChip:h,globalFocusKey:!1,showClearButton:!1,suggest:p})}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Ct,{className:"size-4"}),onClick:n,"aria-label":"Clear and close search",className:"-mr-1 shrink-0"})]}),y,a&&e.trim().length===0?r.jsx(jf,{children:r.jsx(Al,{...a,children:b})}):r.jsx("div",{className:"flex-1 overflow-y-auto",children:b})]})}function Sg(){const e=fs();if(!e)return null;const t=e.showNavPane?!e.navCollapsed:!1;return r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(or,{className:"size-4"}),onClick:e.toggleNav,"aria-label":t?"Hide folders":"Show folders","aria-expanded":t,title:"Folders",className:"shrink-0"})}const kg={queued:{icon:Ga,label:"Queued",className:"text-warning"},sending:{icon:Ps,label:"Sending…",className:"text-accent-2",spin:!0},sent:{icon:mc,label:"Sent",className:"text-positive"},failed:{icon:ds,label:"Failed",className:"text-danger"},blocked:{icon:Aa,label:"Blocked",className:"text-warning"}};function ki({status:e,iconOnly:t,className:s}){const n=kg[e],a=n.icon;return r.jsxs("span",{className:V("inline-flex items-center gap-1.5 text-xs font-medium",n.className,s),children:[r.jsx(a,{className:V("size-4",n.spin&&"animate-spin")}),!t&&n.label]})}const Cg=(e,t)=>t?"bg-accent-2-soft":e==="failed"?"bg-danger-soft":e==="blocked"?"bg-warning/10":"";function jg({recipients:e,subject:t,time:s,status:n,error:a,selected:o,onSelect:i,onRetry:l,retrying:u,onEdit:m,onDelete:f,deleting:d}){const h=n==="failed"||n==="blocked";return r.jsxs("div",{className:V("flex items-start gap-3 border-b border-line px-4 py-3 transition-colors hover:bg-surface-raised",Cg(n,o)),children:[r.jsxs("button",{type:"button",...Ea,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(ki,{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(ki,{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(Fm,{actions:[...n==="failed"&&l?[{label:"Retry sending",iconOnly:!0,icon:r.jsx(Dm,{className:"size-3.5"}),busy:u,onClick:l}]:[],{label:"Edit as draft",iconOnly:!0,icon:r.jsx(mn,{className:"size-3.5"}),onClick:m}],destructive:{label:"Delete message",iconOnly:!0,icon:r.jsx(Rt,{className:"size-3.5"}),busy:d,confirm:{prompt:"Delete this message?",confirmLabel:"Delete"},onClick:f}})})]})}const Ng=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Eg=({children:e,onRefresh:t,isRefreshing:s})=>Ng("(min-width: 1024px)")?e:r.jsx(Nf,{onRefresh:t,isPullable:!s,children:e}),Ig=({text:e,html:t,senderName:s,date:n})=>{const[a,o]=c.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(Wt,{className:"size-3"}):r.jsx(Ms,{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((l,u)=>r.jsx("p",{className:"min-h-[1.2em]",children:l},u))})]})},Tg=e=>e===1?"message":"messages";function Rg({count:e,onReview:t,onDismiss:s,actionLabel:n="Review & rescue"}){return r.jsx(hn,{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(gn,{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} ${Tg(e)} here`})," ","may not be spam — they're from senders we can verify."]})]}),r.jsx(le,{variant:"primary",size:"sm",onClick:t,className:"self-start",children:n})]})})}const Mg=(e,t)=>e==="vip"?"vip":e==="unknown"&&t==="md"?"unknown-pill":"hidden",zc=({senderTrust:e,size:t="sm",className:s})=>{const n=Mg(e,t);return n==="vip"?r.jsx(Tt,{className:V("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:V("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 Ag({candidate:e,selected:t,onToggle:s,hideSender:n=!1}){const{senderName:a,senderAddress:o,subject:i,snippet:l,trustReason:u,trustSubReason:m,senderTrust:f}=e;return r.jsxs("label",{className:V("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(ro,{className:"mt-0.5",checked:t,onChange:s,"aria-label":`${t?"Deselect":"Select"} ${n?i:`message from ${a}`}`}),!n&&r.jsx(kt,{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}),f&&r.jsx(zc,{senderTrust:f,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:l}),!n&&r.jsxs("span",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[r.jsxs(St,{tone:"positive",children:[r.jsx(gn,{className:"size-3","aria-hidden":!0}),u]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:m})]})]})]})}const Og=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)},Pg=(e,t)=>{const s=e.messages.filter(n=>t.has(n.id)).length;return s===0?"none":s===e.messages.length?"all":"some"},Ci=e=>e===1?"message":"messages";function Dg({group:e,selected:t,onToggleGroup:s,onToggleMessage:n}){const[a,o]=c.useState(!1),i=Pg(e,t),l=e.messages.length,u=a?Wt:Ms;return r.jsxs("div",{className:V(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(ro,{className:"mt-0.5",checked:i==="all",indeterminate:i==="some",onChange:()=>s(e,i!=="all"),"aria-label":`${i==="all"?"Deselect":"Select"} all ${l} ${Ci(l)} from ${e.senderName}`}),r.jsx(kt,{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(zc,{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(St,{tone:"positive",children:[r.jsx(gn,{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:[`${l} ${Ci(l)}`,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(Ag,{candidate:m,selected:t.has(m.id),onToggle:()=>n(m.id),hideSender:!0},m.id))})]})}const io=e=>e===1?"message":"messages",Lg=(e,t)=>`Moves ${e===1?"this message":`these ${e} ${io(e)}`} out of Spam to ${t} now. Nothing later.`,fa=(e,t)=>e.find(s=>s.id===t)?.label??"Inbox";function Fg(){return r.jsx(hn,{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 $g({candidates:e,selected:t,onToggle:s,onToggleGroup:n,onSelectAll:a,onSelectNone:o,onContinue:i,onCancel:l}){const[u,m]=c.useState(!1),f=t.size,d=c.useMemo(()=>Og(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(gn,{className:"size-4 text-positive","aria-hidden":!0}),"Rescue from Spam"]}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(Pm,{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(Fg,{})})]}),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:`${f} of ${e.length} selected · ${d.length} ${d.length===1?"sender":"senders"}`}),r.jsxs("span",{className:"flex gap-1",children:[r.jsx(le,{variant:"ghost",size:"sm",onClick:a,children:"Select all"}),r.jsx(le,{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:d.map(h=>r.jsx(Dg,{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(le,{variant:"primary",onClick:i,className:"h-11 w-full font-semibold",children:`Continue with ${f} ${io(f)}`}),r.jsx(le,{variant:"ghost",onClick:l,className:"h-11 w-full",children:"Cancel"})]})]})}function _g({count:e,folders:t,delimiter:s,destination:n,onPick:a,onMove:o,onBack:i}){const[l,u]=c.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:l?r.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden rounded-xl border border-line bg-surface",children:r.jsx(Ol,{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:fa(t,n)}),r.jsx(le,{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:Lg(e,fa(t,n))}),r.jsx(le,{variant:"primary",onClick:o,className:"h-11 w-full font-semibold",children:`Move ${e} out of Spam`}),r.jsx(le,{variant:"ghost",onClick:i,className:"h-11 w-full",children:"Back"})]})]})}function zg({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(Gm,{className:"size-10 text-positive","aria-hidden":!0}),r.jsx("p",{className:"text-base font-semibold text-fg",children:`Moved ${e} ${io(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(le,{variant:"primary",onClick:s,className:"h-11 w-full font-semibold",children:"Done"})})]})}function Bg({open:e,candidates:t,defaultDestinationId:s,availableFolders:n,delimiter:a,onConfirmMove:o,onCancel:i}){const[l,u]=c.useState("review"),[m,f]=c.useState(()=>e?new Set(t.map(x=>x.id)):new Set),[d,h]=c.useState(s),[v,g]=c.useState(0),p=c.useRef(!1);c.useEffect(()=>{e&&!p.current&&(u("review"),f(new Set(t.map(x=>x.id))),h(s),g(0)),p.current=e},[e,t,s]);const y=m.size,b=x=>{f(k=>{const M=new Set(k);return M.has(x)?M.delete(x):M.add(x),M})},S=(x,k)=>{f(M=>{const O=new Set(M);for(const j of x.messages)k?O.add(j.id):O.delete(j.id);return O})},w=()=>{const x=Array.from(m);g(x.length),o(x,d),u("done")};return r.jsxs(_m,{open:e,onClose:i,dismissLabel:"Close rescue",children:[l==="review"&&r.jsx($g,{candidates:t,selected:m,onToggle:b,onToggleGroup:S,onSelectAll:()=>f(new Set(t.map(x=>x.id))),onSelectNone:()=>f(new Set),onContinue:()=>u("destination"),onCancel:i}),l==="destination"&&r.jsx(_g,{count:y,folders:n,delimiter:a,destination:d,onPick:h,onMove:w,onBack:()=>u("review")}),l==="done"&&r.jsx(zg,{count:v,destinationLabel:fa(n,d),onClose:i})]})}const ji=e=>e.toLocaleString();function Ni({selectAll:e,selecting:t,className:s}){return r.jsx(ro,{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 lo({title:e,count:t,onCancel:s,onDelete:n,onMove:a,onOrganize:o,onJunk:i,onMarkRead:l,navSlot:u,titleMeta:m,searchSlot:f,searchField:d,idleSlot:h,overflowSlot:v,isBusy:g=!1,isCounting:p=!1,selectAll:y,statusLabel:b,progress:S,notice:w}){const x=t>0||p,k=y?.checked?`All ${ji(t)} loaded selected`:`${ji(t)} ${t===1?"message":"messages"} selected`,M=[];return i&&!g&&!p&&M.push({key:"junk",label:"Junk",icon:r.jsx(Ls,{className:"size-4"}),onSelect:i}),l&&!g&&!p&&M.push({key:"mark-read",label:"Mark read",icon:r.jsx(ur,{className:"size-4"}),onSelect:l}),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:[x?r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(Ma,{className:"size-5"}),onClick:s,"aria-label":"Cancel selection",className:"-ml-2 shrink-0"}):u,y&&r.jsx(Ni,{selectAll:y,selecting:x,className:"hidden shrink-0 pr-2 md:flex"}),x?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:b??k}):d?r.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:d}):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,f]}),x&&!p&&r.jsxs(r.Fragment,{children:[r.jsx(le,{variant:"ghost",size:"touch",icon:g?r.jsx(Ps,{className:"size-5 animate-spin"}):r.jsx(Rt,{className:"size-5 text-danger"}),onClick:g?void 0:n,"aria-label":"Move selected messages to Trash","aria-busy":g||void 0,className:"shrink-0"}),!g&&a&&r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(Ta,{className:"size-5"}),onClick:a,"aria-label":"Move selected messages",className:"shrink-0"}),!g&&o&&r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(Tt,{className:"size-5"}),onClick:o,"aria-label":"Organize selected messages",className:"shrink-0"})]}),x&&r.jsx(no,{triggerLabel:"More actions",items:M,className:"shrink-0",children:!g&&!p&&v})]}),!x&&h,x&&y&&r.jsx("div",{"data-selection-bar-row":"select-all",className:"px-row-inset pb-2 md:hidden",children:r.jsx(Ni,{selectAll:y,selecting:x,className:"w-full"})}),S&&r.jsx("div",{className:"px-row-inset pb-2",children:r.jsx(Ef,{value:S.value,max:S.max,tone:S.tone})}),w&&r.jsx(hn,{"data-selection-notice":"",tone:w.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:[w.text&&r.jsx("span",{children:w.text}),w.action&&r.jsx(le,{variant:"ghost",size:"md",onClick:w.action.onClick,className:"-my-1 min-h-11 shrink-0",children:w.action.label})]})})]})}const Kg={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function Ug({search:e,onCompose:t,onReportBug:s,onOpenSettings:n,composeShortcut:a,account:o}){return r.jsx(tg,{leading:r.jsx(Sg,{}),search:r.jsx(ao,{value:e.value,onChange:e.onChange,onClear:e.onClear,onClearQuery:e.onClearQuery,chips:e.chips,onRemoveChip:e.onRemoveChip,placeholder:Kg[e.scope]}),actions:r.jsxs(r.Fragment,{children:[r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(zh,{className:"size-4"}),title:a?`Compose (${a})`:"Compose","aria-label":"Compose",onClick:t}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(fc,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:s}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(wc,{className:"size-4"}),title:"Settings","aria-label":"Settings",onClick:n}),o]})})}const co=[{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"}],Bc={id:"unread",label:"Unread"},qg={id:"flagged",label:"Starred"},Kc={id:"attachment",label:"Has attachment"};function Hg(e){if(!(e.length<=1))return e.map(t=>({id:t.id,label:t.label,count:t.count,active:t.active}))}function Wg(e=[]){return{categories:[...co],filters:If,sources:Hg(e)}}function Uc(){return{categories:[...co],filters:[Bc,qg,Kc]}}function Vg(){return{categories:[...co],filters:[Bc,Kc]}}function Qg(e,t){return e.endsWith(t)?e.length===t.length||e[e.length-t.length-1]===".":!1}function Gg(e,t){const s=e.length-t.length-2,n=e.lastIndexOf(".",s);return n===-1?e:e.slice(n+1)}function Yg(e,t,s){if(s.validHosts!==null){const a=s.validHosts;for(const o of a)if(Qg(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:Gg(t,e)}const $r=/[\t\n\r]/g;let ma=!1;function Ei(e){return e>=97&&e<=122||e>=48&&e<=57||e>127||e>=65&&e<=90||e===45||e===95}function Ii(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,l=e.charCodeAt(t+3)|32;return a===104&&o===116&&i===116&&l===112?1:a===102&&o===105&&i===108&&l===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 rn(e,t,s=!1){let n=0,a=e.length,o=!1,i=!1;if(ma=!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 y=e.indexOf(":/",n);if(y!==-1){const b=Ii(e,n,y);if(b===1)for(i=!0,n=y+2;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1;else if(b===2){i=!0,n=y+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<y;S+=1){const w=e.charCodeAt(S)|32;if(!(w>=97&&w<=122||w>=48&&w<=57||w===46||w===45||w===43)){const x=e.charCodeAt(S);return x===9||x===10||x===13?rn(e.replace($r,""),t,s):null}}if(e.charCodeAt(y+2)===47)n=y+3;else return null}}else if(e.charCodeAt(n)!==91){let b=-1;for(let S=n;S<a;S+=1){const w=e.charCodeAt(S);if(w===9||w===10||w===13)return rn(e.replace($r,""),t,s);if(w===58){b=S;break}if(w===47||w===92||w===63||w===35)break}if(b!==-1){let S=!1;for(let w=b+1;w<a;w+=1){const x=e.charCodeAt(w);if(x===47||x===92||x===63||x===35)break;if(x===64){S=!0;break}}if(!S){let w=!0,x=b+1;for(;x<a;x+=1){const k=e.charCodeAt(x);if(k===47||k===92||k===63||k===35)break;if(k<48||k>57){w=!1;break}}if(x===b+1&&(w=!1),!w){const k=Ii(e,n,b);if(k===0){let M=!1;for(let O=b+1;O<a;O+=1){const j=e.charCodeAt(O);if(j===47||j===92||j===63||j===35)break;if(j===58){M=!0;break}}if(!M)return null}else if(i=!0,n=b+1,k===2){let M=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&M<2;)n+=1,M+=1;if(M<2)return null}else for(;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1}}}}}let u=-1,m=-1,f=-1,d=-1,h=!1,v=s,g=n-1,p=-1;if(s&&n<a){const y=e.charCodeAt(n);(!(Ei(y)||y===46||y===95)||y===45)&&(v=!1)}for(let y=n;y<a;y+=1){const b=e.charCodeAt(y);if(b<64)if(b===47||b===35||b===63){a=y;break}else b===58?(d===-1&&(d=y),f=y):b===9||b===10||b===13?h=!0:s&&(b===46?((y-g>64||p===46||p===45)&&(v=!1),g=y):(b<48||b>57)&&(b!==45||p===46)&&(v=!1));else if(i&&b===92){a=y;break}else b===64?(u=y,d=-1):b===93?m=y:b>=65&&b<=90?o=!0:s&&!Ei(b)&&(v=!1);s&&(p=b)}if(h)return rn(e.replace($r,""),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(f!==-1&&f>n&&f<a&&d===f&&(a=f),n>=a)return null;s&&v&&u===-1&&f===-1&&m===-1&&e.charCodeAt(a-1)!==46&&a-n<=255&&a-g-1<=63&&p!==45&&(ma=!0)}for(;a>n+1&&e.charCodeAt(a-1)===46;)a-=1;const l=n!==0||a!==e.length?e.slice(n,a):e;return o?l.toLowerCase():l}function Xg(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 Jg(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 Zg(e){return Jg(e)||Xg(e)}function Ti(e){return e>=97&&e<=122||e>=48&&e<=57||e>127}function Ri(e){if(e.length>255||e.length===0||!Ti(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(!(Ti(o)||o===45||o===95)||o===45&&s===46)return!1;s=o}return n-t-1<=63&&s!==45}function ex({allowIcannDomains:e=!0,allowPrivateDomains:t=!1,detectIp:s=!0,detectSpecialUse:n=!1,extractHostname:a=!0,mixedInputs:o=!0,validHosts:i=null,validateHostname:l=!0}){return{allowIcannDomains:e,allowPrivateDomains:t,detectIp:s,detectSpecialUse:n,extractHostname:a,mixedInputs:o,validHosts:i,validateHostname:l}}const tx=ex({});function sx(e){return tx}function nx(){return{domain:null,domainWithoutSuffix:null,hostname:null,isIcann:null,isIp:null,isPrivate:null,isSpecialUse:null,publicSuffix:null,subdomain:null}}function rx(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 ax(e,t,s,n,a){const o=sx();if(typeof e!="string")return a;let i=!1;return o.extractHostname?o.mixedInputs?(i=Ri(e),a.hostname=rn(e,i,o.validateHostname)):a.hostname=rn(e,!1,o.validateHostname):a.hostname=e,o.detectIp&&a.hostname!==null&&(a.isIp=Zg(a.hostname),a.isIp)?a:o.validateHostname&&o.extractHostname&&a.hostname!==null&&!(i&&a.hostname===e)&&!ma&&!Ri(a.hostname)?(a.hostname=null,a):(a.hostname===null||(s(a.hostname,o,a),a.publicSuffix===null)||(a.domain=Yg(a.publicSuffix,a.hostname,o)),a)}const Mi=nx();function ox(e,t){return rx(Mi),ax(e,3,Tf,t,Mi).domain}const fr=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},ix=e=>{const t=e.lastIndexOf("@");return t>=0?e.slice(t+1):e},qc=e=>ox(ix(e.trim())),lx=e=>{const t=fr(e);if(t.length<2)return null;let s=null;for(const n of t){const a=qc(n);if(a===null)return null;if(s===null)s=a;else if(s!==a)return null}return s},mr=e=>{const t=lx(e);return t!==null?[{field:"FromDomain",value:t}]:fr(e).map(s=>({field:"From",value:s}))},cx=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},Hc=e=>e.displayName?.trim()||e.normalizedEmail,ux=/^\s*(?:(?:re|aw|fwd?|vs|sv|antw|res|enc|tr)\s*(?:\[\d+\])?\s*:|\[[^\]]{1,32}\])\s*/i,dx=e=>{let t=e.replace(/\s+/g," ").trim();for(;;){const s=t.replace(ux,"");if(s===t)return t.trim();t=s}},fx=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"]),mx=3,_r=e=>e.split(" ").filter(t=>t!==""),Ai=e=>e.length===0||e.join(" ").length<mx?!1:e.some(t=>!fx.has(t.toLowerCase())),hx=(e,t)=>e.findIndex((s,n)=>t.every((a,o)=>e[n+o]?.toLowerCase()===a.toLowerCase())),px=e=>{const t=e.map(dx).filter(o=>o!=="");if(t.length===0)return;const[s,...n]=t;if(n.length===0)return Ai(_r(s))?s:void 0;const a=_r(s);for(let o=a.length;o>0;o-=1)for(let i=0;i+o<=a.length;i+=1){const l=a.slice(i,i+o);if(Ai(l)&&n.every(u=>hx(_r(u),l)>=0))return l.join(" ")}},gx=(e,t)=>{const s=mr(e);if(fr(e).length===1||s.length===1&&s[0].field==="FromDomain")return s;const n=px(t);return n!==void 0?[{field:"Subject",value:n}]:s},xx=({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}`:""},bx=e=>e.clauses.length>0,vx=e=>({scopedOutFolder:e.scopedOut?.label,droppedFacets:e.droppedFacets.map(t=>t.label),droppedSemantic:e.droppedSemantic});function Ht(e,t,{checkForDefaultPrevented:s=!0}={}){return function(a){if(e?.(a),s===!1||!a||!a.defaultPrevented)return t?.(a)}}function Oi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function yx(...e){return t=>{let s=!1;const n=e.map(a=>{const o=Oi(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():Oi(e[a],null)}}}}function ps(...e){return c.useCallback(yx(...e),e)}function wx(e,t=[]){let s=[];function n(o,i){const l=c.createContext(i);l.displayName=o+"Context";const u=s.length;s=[...s,i];const m=d=>{const{scope:h,children:v,...g}=d,p=h?.[e]?.[u]||l,y=c.useMemo(()=>g,Object.values(g));return r.jsx(p.Provider,{value:y,children:v})};m.displayName=o+"Provider";function f(d,h,v={}){const{optional:g=!1}=v,p=h?.[e]?.[u]||l,y=c.useContext(p);if(y)return y;if(i!==void 0)return i;if(!g)throw new Error(`\`${d}\` must be used within \`${o}\``)}return[m,f]}const a=()=>{const o=s.map(i=>c.createContext(i));return function(l){const u=l?.[e]||o;return c.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return a.scopeName=e,[n,Sx(a,...t)]}function Sx(...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((l,{useScope:u,scopeName:m})=>{const d=u(o)[`__scope${m}`];return{...l,...d}},{});return c.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return s.scopeName=t.scopeName,s}var cn=globalThis?.document?c.useLayoutEffect:()=>{},kx=Oa[" useInsertionEffect ".trim().toString()]||cn;function Cx({prop:e,defaultProp:t,onChange:s=()=>{},caller:n}){const[a,o,i]=jx({defaultProp:t,onChange:s}),l=e!==void 0,u=l?e:a;{const f=c.useRef(e!==void 0);c.useEffect(()=>{const d=f.current;d!==l&&console.warn(`${n} is changing from ${d?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=l},[l,n])}const m=c.useCallback(f=>{if(l){const d=Nx(f)?f(e):f;d!==e&&i.current?.(d)}else o(f)},[l,e,o,i]);return[u,m]}function jx({defaultProp:e,onChange:t}){const[s,n]=c.useState(e),a=c.useRef(s),o=c.useRef(t);return kx(()=>{o.current=t},[t]),c.useEffect(()=>{a.current!==s&&(o.current?.(s),a.current=s)},[s,a]),[s,n,o]}function Nx(e){return typeof e=="function"}function uo(e){const t=c.forwardRef((s,n)=>{let{children:a,...o}=s,i=null,l=!1;const u=[];Pi(a)&&typeof Nn=="function"&&(a=Nn(a._payload)),c.Children.forEach(a,h=>{if(Mx(h)){l=!0;const v=h;let g="child"in v.props?v.props.child:v.props.children;Pi(g)&&typeof Nn=="function"&&(g=Nn(g._payload)),i=Ix(v,g),u.push(i?.props?.children)}else u.push(h)}),i?i=c.cloneElement(i,void 0,u):!l&&c.Children.count(a)===1&&c.isValidElement(a)&&(i=a);const m=i?Rx(i):void 0,f=ps(n,m);if(!i){if(a||a===0)throw new Error(l?Dx(e):Px(e));return a}const d=Tx(o,i.props??{});return i.type!==c.Fragment&&(d.ref=n?f:m),c.cloneElement(i,d)});return t.displayName=`${e}.Slot`,t}var fj=uo("Slot"),Ex=Symbol.for("radix.slottable"),Ix=(e,t)=>{if("child"in e.props){const s=e.props.child;return c.isValidElement(s)?c.cloneElement(s,void 0,e.props.children(s.props.children)):null}return c.isValidElement(t)?t:null};function Tx(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]=(...l)=>{const u=o(...l);return a(...l),u}:a&&(s[n]=a):n==="style"?s[n]={...a,...o}:n==="className"&&(s[n]=[a,o].filter(Boolean).join(" "))}return{...e,...s}}function Rx(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 Mx(e){return c.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ex}var Ax=Symbol.for("react.lazy");function Pi(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Ax&&"_payload"in e&&Ox(e._payload)}function Ox(e){return typeof e=="object"&&e!==null&&"then"in e}var Px=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,Dx=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Nn=Oa[" use ".trim().toString()],Lx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],At=Lx.reduce((e,t)=>{const s=uo(`Primitive.${t}`),n=c.forwardRef((a,o)=>{const{asChild:i,...l}=a,u=i?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),r.jsx(u,{...l,ref:o})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function Fx(e,t){e&&Pa.flushSync(()=>e.dispatchEvent(t))}function un(e){const t=c.useRef(e);return c.useEffect(()=>{t.current=e}),c.useMemo(()=>((...s)=>t.current?.(...s)),[])}var $x="DismissableLayer",ha="dismissableLayer.update",_x="dismissableLayer.pointerDownOutside",zx="dismissableLayer.focusOutside",Di,fo=c.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Wc=c.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:n=!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:l,onDismiss:u,...m}=e,f=c.useContext(fo),[d,h]=c.useState(null),v=d?.ownerDocument??globalThis?.document,[,g]=c.useState({}),p=ps(t,h),y=Array.from(f.layers),[b]=[...f.layersWithOutsidePointerEventsDisabled].slice(-1),S=b?y.indexOf(b):-1,w=d?y.indexOf(d):-1,x=f.layersWithOutsidePointerEventsDisabled.size>0,k=w>=S,M=c.useRef(!1),O=Hx(E=>{o?.(E),l?.(E),E.defaultPrevented||u?.()},{ownerDocument:v,deferPointerDownOutside:n,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:f.dismissableSurfaces,shouldHandlePointerDownOutside:c.useCallback(E=>{if(!(E instanceof Node))return!1;const L=[...f.branches].some(D=>D.contains(E));return k&&!L},[f.branches,k])}),j=Wx(E=>{if(n&&M.current)return;const L=E.target;[...f.branches].some(C=>C.contains(L))||(i?.(E),l?.(E),E.defaultPrevented||u?.())},v),R=d?w===y.length-1:!1,P=un(E=>{E.key==="Escape"&&(a?.(E),!E.defaultPrevented&&u&&(E.preventDefault(),u()))});return c.useEffect(()=>{if(R)return v.addEventListener("keydown",P,{capture:!0}),()=>v.removeEventListener("keydown",P,{capture:!0})},[v,R,P]),c.useEffect(()=>{if(d)return s&&(f.layersWithOutsidePointerEventsDisabled.size===0&&(Di=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),f.layersWithOutsidePointerEventsDisabled.add(d)),f.layers.add(d),Li(),()=>{s&&(f.layersWithOutsidePointerEventsDisabled.delete(d),f.layersWithOutsidePointerEventsDisabled.size===0&&(v.body.style.pointerEvents=Di))}},[d,v,s,f]),c.useEffect(()=>()=>{d&&(f.layers.delete(d),f.layersWithOutsidePointerEventsDisabled.delete(d),Li())},[d,f]),c.useEffect(()=>{const E=()=>g({});return document.addEventListener(ha,E),()=>document.removeEventListener(ha,E)},[]),r.jsx(At.div,{...m,ref:p,style:{pointerEvents:x?k?"auto":"none":void 0,...e.style},onFocusCapture:Ht(e.onFocusCapture,j.onFocusCapture),onBlurCapture:Ht(e.onBlurCapture,j.onBlurCapture),onPointerDownCapture:Ht(e.onPointerDownCapture,O.onPointerDownCapture)})});Wc.displayName=$x;var Bx="DismissableLayerBranch",Kx=c.forwardRef((e,t)=>{const s=c.useContext(fo),n=c.useRef(null),a=ps(t,n);return c.useEffect(()=>{const o=n.current;if(o)return s.branches.add(o),()=>{s.branches.delete(o)}},[s.branches]),r.jsx(At.div,{...e,ref:a})});Kx.displayName=Bx;function Ux(){const e=c.useContext(fo),[t,s]=c.useState(null);return c.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),s}var qx=()=>!0;function Hx(e,t){const{ownerDocument:s=globalThis?.document,deferPointerDownOutside:n=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:o,shouldHandlePointerDownOutside:i=qx}=t,l=un(e),u=c.useRef(!1),m=c.useRef(!1),f=c.useRef(new Map),d=c.useRef(()=>{});return c.useEffect(()=>{function h(){m.current=!1,a.current=!1,f.current.clear()}function v(){return Array.from(f.current.values()).some(Boolean)}function g(w){if(!m.current)return;const x=w.target;x instanceof Node&&[...o].some(M=>M.contains(x))||f.current.set(w.type,!0),w.type==="click"&&window.setTimeout(()=>{m.current&&d.current()},0)}function p(w){m.current&&f.current.set(w.type,!1)}const y=w=>{if(w.target&&!u.current){let x=function(){s.removeEventListener("click",d.current);const M=v();h(),M||Vc(_x,l,k,{discrete:!0})};if(!i(w.target)){s.removeEventListener("click",d.current),h(),u.current=!1;return}const k={originalEvent:w};m.current=!0,a.current=n&&w.button===0,f.current.clear(),!n||w.button!==0?x():(s.removeEventListener("click",d.current),d.current=x,s.addEventListener("click",d.current,{once:!0}))}else s.removeEventListener("click",d.current),h();u.current=!1},b=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const w of b)s.addEventListener(w,g,!0),s.addEventListener(w,p);const S=window.setTimeout(()=>{s.addEventListener("pointerdown",y)},0);return()=>{window.clearTimeout(S),s.removeEventListener("pointerdown",y),s.removeEventListener("click",d.current);for(const w of b)s.removeEventListener(w,g,!0),s.removeEventListener(w,p)}},[s,l,n,a,o,i]),{onPointerDownCapture:()=>u.current=!0}}function Wx(e,t=globalThis?.document){const s=un(e),n=c.useRef(!1);return c.useEffect(()=>{const a=o=>{o.target&&!n.current&&Vc(zx,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 Li(){const e=new CustomEvent(ha);document.dispatchEvent(e)}function Vc(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?Fx(a,o):a.dispatchEvent(o)}var En=0,ws=null;function Vx(){c.useEffect(()=>{ws||(ws={start:Fi(),end:Fi()});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),En++,()=>{En===1&&(ws?.start.remove(),ws?.end.remove(),ws=null),En=Math.max(0,En-1)}},[])}function Fi(){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",Br="focusScope.autoFocusOnUnmount",$i={bubbles:!1,cancelable:!0},Qx="FocusScope",Qc=c.forwardRef((e,t)=>{const{loop:s=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[l,u]=c.useState(null),m=un(a),f=un(o),d=c.useRef(null),h=ps(t,u),v=c.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;c.useEffect(()=>{if(n){let p=function(w){if(v.paused||!l)return;const x=w.target;l.contains(x)?d.current=x:zt(d.current,{select:!0})},y=function(w){if(v.paused||!l)return;const x=w.relatedTarget;x!==null&&(l.contains(x)||zt(d.current,{select:!0}))},b=function(w){if(document.activeElement===document.body)for(const k of w)k.removedNodes.length>0&&zt(l)};document.addEventListener("focusin",p),document.addEventListener("focusout",y);const S=new MutationObserver(b);return l&&S.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",y),S.disconnect()}}},[n,l,v.paused]),c.useEffect(()=>{if(l){zi.add(v);const p=document.activeElement;if(!l.contains(p)){const b=new CustomEvent(zr,$i);l.addEventListener(zr,m),l.dispatchEvent(b),b.defaultPrevented||(Gx(eb(Gc(l)),{select:!0}),document.activeElement===p&&zt(l))}return()=>{l.removeEventListener(zr,m),setTimeout(()=>{const b=new CustomEvent(Br,$i);l.addEventListener(Br,f),l.dispatchEvent(b),b.defaultPrevented||zt(p??document.body,{select:!0}),l.removeEventListener(Br,f),zi.remove(v)},0)}}},[l,m,f,v]);const g=c.useCallback(p=>{if(!s&&!n||v.paused)return;const y=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,b=document.activeElement;if(y&&b){const S=p.currentTarget,[w,x]=Yx(S);w&&x?!p.shiftKey&&b===x?(p.preventDefault(),s&&zt(w,{select:!0})):p.shiftKey&&b===w&&(p.preventDefault(),s&&zt(x,{select:!0})):b===S&&p.preventDefault()}},[s,n,v.paused]);return r.jsx(At.div,{tabIndex:-1,...i,ref:h,onKeyDown:g})});Qc.displayName=Qx;function Gx(e,{select:t=!1}={}){const s=document.activeElement;for(const n of e)if(zt(n,{select:t}),document.activeElement!==s)return}function Yx(e){const t=Gc(e),s=_i(t,e),n=_i(t.reverse(),e);return[s,n]}function Gc(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 _i(e,t){const s=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const n of e)if(!(s?!n.checkVisibility({checkVisibilityCSS:!0}):Xx(n,{upTo:t})))return n}function Xx(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 Jx(e){return e instanceof HTMLInputElement&&"select"in e}function zt(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&Jx(e)&&t&&e.select()}}var zi=Zx();function Zx(){let e=[];return{add(t){const s=e[0];t!==s&&s?.pause(),e=Bi(e,t),e.unshift(t)},remove(t){e=Bi(e,t),e[0]?.resume()}}}function Bi(e,t){const s=[...e],n=s.indexOf(t);return n!==-1&&s.splice(n,1),s}function eb(e){return e.filter(t=>t.tagName!=="A")}var tb=Oa[" useId ".trim().toString()]||(()=>{}),sb=0;function Kr(e){const[t,s]=c.useState(tb());return cn(()=>{s(n=>n??String(sb++))},[e]),e||(t?`radix-${t}`:"")}var nb="Portal",Yc=c.forwardRef((e,t)=>{const{container:s,...n}=e,[a,o]=c.useState(!1);cn(()=>o(!0),[]);const i=s||a&&globalThis?.document?.body;return i?Pa.createPortal(r.jsx(At.div,{...n,ref:t}),i):null});Yc.displayName=nb;function rb(e,t){return c.useReducer((s,n)=>t[s][n]??s,e)}var hr=e=>{const{present:t,children:s}=e,n=ab(t),a=typeof s=="function"?s({present:n.isPresent}):c.Children.only(s),o=ob(n.ref,ib(a));return typeof s=="function"||n.isPresent?c.cloneElement(a,{ref:o}):null};hr.displayName="Presence";function ab(e){const[t,s]=c.useState(),n=c.useRef(null),a=c.useRef(e),o=c.useRef("none"),i=c.useRef(void 0),l=e?"mounted":"unmounted",[u,m]=rb(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return c.useEffect(()=>{u==="mounted"?(o.current=i.current??Vs(n.current),i.current=void 0):o.current="none"},[u]),cn(()=>{const f=n.current,d=a.current;if(d!==e){const v=o.current,g=Vs(f);e?(i.current=g,m("MOUNT")):g==="none"||f?.display==="none"?m("UNMOUNT"):m(d&&v!==g?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,m]),cn(()=>{if(t){let f;const d=t.ownerDocument.defaultView??window,h=g=>{const y=Vs(n.current).includes(CSS.escape(g.animationName));if(g.target===t&&y&&(m("ANIMATION_END"),!a.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",f=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},v=g=>{g.target===t&&(o.current=Vs(n.current))};return t.addEventListener("animationstart",v),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{d.clearTimeout(f),t.removeEventListener("animationstart",v),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:c.useCallback(f=>{if(f){const d=getComputedStyle(f);n.current=d,i.current=Vs(d)}else n.current=null;s(f)},[])}}function Ki(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ob(...e){const t=c.useRef(e);return t.current=e,c.useCallback(s=>{const n=t.current;let a=!1;const o=n.map(i=>{const l=Ki(i,s);return!a&&typeof l=="function"&&(a=!0),l});if(a)return()=>{for(let i=0;i<o.length;i++){const l=o[i];typeof l=="function"?l():Ki(n[i],null)}}},[])}function Vs(e){return e?.animationName||"none"}function ib(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 lb=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ss=new WeakMap,In=new WeakMap,Tn={},Ur=0,Xc=function(e){return e&&(e.host||Xc(e.parentNode))},cb=function(e,t){return t.map(function(s){if(e.contains(s))return s;var n=Xc(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})},ub=function(e,t,s,n){var a=cb(t,Array.isArray(e)?e:[e]);Tn[s]||(Tn[s]=new WeakMap);var o=Tn[s],i=[],l=new Set,u=new Set(a),m=function(d){!d||l.has(d)||(l.add(d),m(d.parentNode))};a.forEach(m);var f=function(d){!d||u.has(d)||Array.prototype.forEach.call(d.children,function(h){if(l.has(h))f(h);else try{var v=h.getAttribute(n),g=v!==null&&v!=="false",p=(Ss.get(h)||0)+1,y=(o.get(h)||0)+1;Ss.set(h,p),o.set(h,y),i.push(h),p===1&&g&&In.set(h,!0),y===1&&h.setAttribute(s,"true"),g||h.setAttribute(n,"true")}catch(b){console.error("aria-hidden: cannot operate on ",h,b)}})};return f(t),l.clear(),Ur++,function(){i.forEach(function(d){var h=Ss.get(d)-1,v=o.get(d)-1;Ss.set(d,h),o.set(d,v),h||(In.has(d)||d.removeAttribute(n),In.delete(d)),v||d.removeAttribute(s)}),Ur--,Ur||(Ss=new WeakMap,Ss=new WeakMap,In=new WeakMap,Tn={})}},db=function(e,t,s){s===void 0&&(s="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),a=lb(e);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live], script"))),ub(n,a,s,"aria-hidden")):function(){return null}},$n="right-scroll-bar-position",_n="width-before-scroll-bar",fb="with-scroll-bars-hidden",mb="--removed-body-scroll-bar-size";function qr(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function hb(e,t){var s=c.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 pb=typeof window<"u"?c.useLayoutEffect:c.useEffect,Ui=new WeakMap;function gb(e,t){var s=hb(null,function(n){return e.forEach(function(a){return qr(a,n)})});return pb(function(){var n=Ui.get(s);if(n){var a=new Set(n),o=new Set(e),i=s.current;a.forEach(function(l){o.has(l)||qr(l,null)}),o.forEach(function(l){a.has(l)||qr(l,i)})}Ui.set(s,e)},[e]),s}function xb(e){return e}function bb(e,t){t===void 0&&(t=xb);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(l){return l!==i})}},assignSyncMedium:function(o){for(n=!0;s.length;){var i=s;s=[],i.forEach(o)}s={push:function(l){return o(l)},filter:function(){return s}}},assignMedium:function(o){n=!0;var i=[];if(s.length){var l=s;s=[],l.forEach(o),i=s}var u=function(){var f=i;i=[],f.forEach(o)},m=function(){return Promise.resolve().then(u)};m(),s={push:function(f){i.push(f),m()},filter:function(f){return i=i.filter(f),s}}}};return a}function vb(e){e===void 0&&(e={});var t=bb(null);return t.options=Bt({async:!0,ssr:!1},e),t}var Jc=function(e){var t=e.sideCar,s=Pl(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 c.createElement(n,Bt({},s))};Jc.isSideCarExport=!0;function yb(e,t){return e.useMedium(t),Jc}var Zc=vb(),Hr=function(){},pr=c.forwardRef(function(e,t){var s=c.useRef(null),n=c.useState({onScrollCapture:Hr,onWheelCapture:Hr,onTouchMoveCapture:Hr}),a=n[0],o=n[1],i=e.forwardProps,l=e.children,u=e.className,m=e.removeScrollBar,f=e.enabled,d=e.shards,h=e.sideCar,v=e.noRelative,g=e.noIsolation,p=e.inert,y=e.allowPinchZoom,b=e.as,S=b===void 0?"div":b,w=e.gapMode,x=Pl(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,M=gb([s,t]),O=Bt(Bt({},x),a);return c.createElement(c.Fragment,null,f&&c.createElement(k,{sideCar:Zc,removeScrollBar:m,shards:d,noRelative:v,noIsolation:g,inert:p,setCallbacks:o,allowPinchZoom:!!y,lockRef:s,gapMode:w}),i?c.cloneElement(c.Children.only(l),Bt(Bt({},O),{ref:M})):c.createElement(S,Bt({},O,{className:u,ref:M}),l))});pr.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};pr.classNames={fullWidth:_n,zeroRight:$n};var wb=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Sb(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=wb();return t&&e.setAttribute("nonce",t),e}function kb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Cb(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var jb=function(){var e=0,t=null;return{add:function(s){e==0&&(t=Sb())&&(kb(t,s),Cb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Nb=function(){var e=jb();return function(t,s){c.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},eu=function(){var e=Nb(),t=function(s){var n=s.styles,a=s.dynamic;return e(n,a),null};return t},Eb={left:0,top:0,right:0,gap:0},Wr=function(e){return parseInt(e||"",10)||0},Ib=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[Wr(s),Wr(n),Wr(a)]},Tb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Eb;var t=Ib(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])}},Rb=eu(),Rs="data-scroll-locked",Mb=function(e,t,s,n){var a=e.left,o=e.top,i=e.right,l=e.gap;return s===void 0&&(s="margin"),`
76
+ .`.concat(fb,` {
77
77
  overflow: hidden `).concat(n,`;
78
78
  padding-right: `).concat(l,"px ").concat(n,`;
79
79
  }
80
- body[`).concat(Ms,`] {
80
+ body[`).concat(Rs,`] {
81
81
  overflow: hidden `).concat(n,`;
82
82
  overscroll-behavior: contain;
83
83
  `).concat([t&&"position: relative ".concat(n,";"),s==="margin"&&`
@@ -106,13 +106,13 @@ a, a:visited {
106
106
  margin-right: 0 `).concat(n,`;
107
107
  }
108
108
 
109
- body[`).concat(Ms,`] {
110
- `).concat(db,": ").concat(l,`px;
109
+ body[`).concat(Rs,`] {
110
+ `).concat(mb,": ").concat(l,`px;
111
111
  }
112
- `)},Vi=function(){var e=parseInt(document.body.getAttribute(Ms)||"0",10);return isFinite(e)?e:0},Rb=function(){c.useEffect(function(){return document.body.setAttribute(Ms,(Vi()+1).toString()),function(){var e=Vi()-1;e<=0?document.body.removeAttribute(Ms):document.body.setAttribute(Ms,e.toString())}},[])},Mb=function(e){var t=e.noRelative,s=e.noImportant,n=e.gapMode,a=n===void 0?"margin":n;Rb();var o=c.useMemo(function(){return Eb(a)},[a]);return c.createElement(Ib,{styles:Tb(o,!t,a,s?"":"!important")})},pa=!1;if(typeof window<"u")try{var Rn=Object.defineProperty({},"passive",{get:function(){return pa=!0,!0}});window.addEventListener("test",Rn,Rn),window.removeEventListener("test",Rn,Rn)}catch{pa=!1}var ks=pa?{passive:!1}:!1,Ab=function(e){return e.tagName==="TEXTAREA"},tu=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!Ab(e)&&s[t]==="visible")},Ob=function(e){return tu(e,"overflowY")},Pb=function(e){return tu(e,"overflowX")},Qi=function(e,t){var s=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=su(e,n);if(a){var o=nu(e,n),i=o[1],l=o[2];if(i>l)return!0}n=n.parentNode}while(n&&n!==s.body);return!1},Db=function(e){var t=e.scrollTop,s=e.scrollHeight,n=e.clientHeight;return[t,s,n]},Lb=function(e){var t=e.scrollLeft,s=e.scrollWidth,n=e.clientWidth;return[t,s,n]},su=function(e,t){return e==="v"?Ob(t):Pb(t)},nu=function(e,t){return e==="v"?Db(t):Lb(t)},Fb=function(e,t){return e==="h"&&t==="rtl"?-1:1},$b=function(e,t,s,n,a){var o=Fb(e,window.getComputedStyle(t).direction),i=o*n,l=s.target,u=t.contains(l),m=!1,f=i>0,d=0,h=0;do{if(!l)break;var v=nu(e,l),g=v[0],p=v[1],y=v[2],b=p-y-o*g;(g||b)&&su(e,l)&&(d+=b,h+=g);var S=l.parentNode;l=S&&S.nodeType===Node.DOCUMENT_FRAGMENT_NODE?S.host:S}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(f&&Math.abs(d)<1||!f&&Math.abs(h)<1)&&(m=!0),m},Mn=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Gi=function(e){return[e.deltaX,e.deltaY]},Yi=function(e){return e&&"current"in e?e.current:e},_b=function(e,t){return e[0]===t[0]&&e[1]===t[1]},zb=function(e){return`
112
+ `)},qi=function(){var e=parseInt(document.body.getAttribute(Rs)||"0",10);return isFinite(e)?e:0},Ab=function(){c.useEffect(function(){return document.body.setAttribute(Rs,(qi()+1).toString()),function(){var e=qi()-1;e<=0?document.body.removeAttribute(Rs):document.body.setAttribute(Rs,e.toString())}},[])},Ob=function(e){var t=e.noRelative,s=e.noImportant,n=e.gapMode,a=n===void 0?"margin":n;Ab();var o=c.useMemo(function(){return Tb(a)},[a]);return c.createElement(Rb,{styles:Mb(o,!t,a,s?"":"!important")})},pa=!1;if(typeof window<"u")try{var Rn=Object.defineProperty({},"passive",{get:function(){return pa=!0,!0}});window.addEventListener("test",Rn,Rn),window.removeEventListener("test",Rn,Rn)}catch{pa=!1}var ks=pa?{passive:!1}:!1,Pb=function(e){return e.tagName==="TEXTAREA"},tu=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!Pb(e)&&s[t]==="visible")},Db=function(e){return tu(e,"overflowY")},Lb=function(e){return tu(e,"overflowX")},Hi=function(e,t){var s=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=su(e,n);if(a){var o=nu(e,n),i=o[1],l=o[2];if(i>l)return!0}n=n.parentNode}while(n&&n!==s.body);return!1},Fb=function(e){var t=e.scrollTop,s=e.scrollHeight,n=e.clientHeight;return[t,s,n]},$b=function(e){var t=e.scrollLeft,s=e.scrollWidth,n=e.clientWidth;return[t,s,n]},su=function(e,t){return e==="v"?Db(t):Lb(t)},nu=function(e,t){return e==="v"?Fb(t):$b(t)},_b=function(e,t){return e==="h"&&t==="rtl"?-1:1},zb=function(e,t,s,n,a){var o=_b(e,window.getComputedStyle(t).direction),i=o*n,l=s.target,u=t.contains(l),m=!1,f=i>0,d=0,h=0;do{if(!l)break;var v=nu(e,l),g=v[0],p=v[1],y=v[2],b=p-y-o*g;(g||b)&&su(e,l)&&(d+=b,h+=g);var S=l.parentNode;l=S&&S.nodeType===Node.DOCUMENT_FRAGMENT_NODE?S.host:S}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(f&&Math.abs(d)<1||!f&&Math.abs(h)<1)&&(m=!0),m},Mn=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Wi=function(e){return[e.deltaX,e.deltaY]},Vi=function(e){return e&&"current"in e?e.current:e},Bb=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Kb=function(e){return`
113
113
  .block-interactivity-`.concat(e,` {pointer-events: none;}
114
114
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
115
- `)},Bb=0,js=[];function Kb(e){var t=c.useRef([]),s=c.useRef([0,0]),n=c.useRef(),a=c.useState(Bb++)[0],o=c.useState(eu)[0],i=c.useRef(e);c.useEffect(function(){i.current=e},[e]),c.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=Rf([e.lockRef.current],(e.shards||[]).map(Yi),!0).filter(Boolean);return p.forEach(function(y){return y.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=c.useCallback(function(p,y){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var b=Mn(p),S=s.current,w="deltaX"in p?p.deltaX:S[0]-b[0],x="deltaY"in p?p.deltaY:S[1]-b[1],k,M=p.target,O=Math.abs(w)>Math.abs(x)?"h":"v";if("touches"in p&&O==="h"&&M.type==="range")return!1;var C=window.getSelection(),R=C&&C.anchorNode,P=R?R===M||R.contains(M):!1;if(P)return!1;var E=Qi(O,M);if(!E)return!0;if(E?k=O:(k=O==="v"?"h":"v",E=Qi(O,M)),!E)return!1;if(!n.current&&"changedTouches"in p&&(w||x)&&(n.current=k),!k)return!0;var L=n.current||k;return $b(L,y,p,L==="h"?w:x)},[]),u=c.useCallback(function(p){var y=p;if(!(!js.length||js[js.length-1]!==o)){var b="deltaY"in y?Gi(y):Mn(y),S=t.current.filter(function(k){return k.name===y.type&&(k.target===y.target||y.target===k.shadowParent)&&_b(k.delta,b)})[0];if(S&&S.should){y.cancelable&&y.preventDefault();return}if(!S){var w=(i.current.shards||[]).map(Yi).filter(Boolean).filter(function(k){return k.contains(y.target)}),x=w.length>0?l(y,w[0]):!i.current.noIsolation;x&&y.cancelable&&y.preventDefault()}}},[]),m=c.useCallback(function(p,y,b,S){var w={name:p,delta:y,target:b,should:S,shadowParent:Ub(b)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(x){return x!==w})},1)},[]),f=c.useCallback(function(p){s.current=Mn(p),n.current=void 0},[]),d=c.useCallback(function(p){m(p.type,Gi(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){m(p.type,Mn(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return js.push(o),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:h}),document.addEventListener("wheel",u,ks),document.addEventListener("touchmove",u,ks),document.addEventListener("touchstart",f,ks),function(){js=js.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,ks),document.removeEventListener("touchmove",u,ks),document.removeEventListener("touchstart",f,ks)}},[]);var v=e.removeScrollBar,g=e.inert;return c.createElement(c.Fragment,null,g?c.createElement(o,{styles:zb(a)}):null,v?c.createElement(Mb,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Ub(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const qb=bb(Zc,Kb);var ru=c.forwardRef(function(e,t){return c.createElement(pr,Bt({},e,{ref:t,sideCar:qb}))});ru.classNames=pr.classNames;var Hb=class extends Da{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:l}=n,u=s.fetchMeta?.fetchMore?.direction,m=i&&u==="forward",f=a&&u==="forward",d=i&&u==="backward",h=a&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Af(t,s.data),hasPreviousPage:Mf(t,s.data),isFetchNextPageError:m,isFetchingNextPage:f,isFetchPreviousPageError:d,isFetchingPreviousPage:h,isRefetchError:l&&!m&&!d,isRefetching:o&&!f&&!h}}};function Xi(e,t){const s=new Set(t);return e.filter(n=>!s.has(n))}function Wb(e,t,s){const n=e.slice(0);return n[t]=s,n}var Vb=class extends Of{#s;#e;#a;#r;#t;#n;#o;#i;#l;#c=[];constructor(e,t,s){super(),this.#s=e,this.#r=s,this.#a=[],this.#t=[],this.#e=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#t.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#t.forEach(e=>{e.destroy()})}setQueries(e,t){this.#a=e,this.#r=t,ra.batch(()=>{const s=this.#t,n=this.#f(this.#a);n.forEach(f=>f.observer.setOptions(f.defaultedQueryOptions));const a=n.map(f=>f.observer),o=a.map(f=>f.getCurrentResult()),i=s.length!==a.length,l=a.some((f,d)=>f!==s[d]),u=i||l,m=u?!0:o.some((f,d)=>{const h=this.#e[d];return!h||!Pf(f,h)});!u&&!m||(u&&(this.#c=n,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(Xi(s,a).forEach(f=>{f.destroy()}),Xi(a,s).forEach(f=>{f.subscribe(d=>{this.#m(f,d)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const s=this.#f(e),n=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[n,o=>this.#d(o??n,t,a),()=>this.#u(n,s)]}#u(e,t){return t.map((s,n)=>{const a=e[n];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const n=this.#l,a=s!==void 0&&n!==void 0&&(n.length!==s.length||s.some((o,i)=>o!==n[i]));return(!this.#n||this.#e!==this.#i||a||t!==this.#o)&&(this.#o=t,this.#i=this.#e,s!==void 0&&(this.#l=s),this.#n=Df(this.#n,t(e))),this.#n}return e}#p(){return this.#r?.combine!==void 0&&this.#t.some((e,t)=>e.options.suspense&&this.#e[t]?.data===void 0)}#f(e){const t=new Map;this.#t.forEach(n=>{const a=n.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(n):t.set(a,[n])});const s=[];return e.forEach(n=>{const a=this.#s.defaultQueryOptions(n),i=t.get(a.queryHash)?.shift()??new Da(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=Wb(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,n=t?s:this.#d(e,this.#r?.combine);(t||s!==n)&&ra.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function pt({queries:e,...t},s){const n=Me(),a=Lf(),o=Ff(),i=c.useMemo(()=>e.map(p=>{const y=n.defaultQueryOptions(p);return y._optimisticResults=a?"isRestoring":"optimistic",y}),[e,n,a]);i.forEach(p=>{$f(p);const y=n.getQueryCache().get(p.queryHash);_f(p,o,y)}),zf(o);const[l]=c.useState(()=>new Vb(n,i,t)),[u,m,f]=l.getOptimisticResult(i,t.combine),d=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>d?l.subscribe(ra.batchCalls(p)):Bf,[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const v=u.some((p,y)=>Ho(i[y],p))?u.flatMap((p,y)=>{const b=i[y];if(b&&Ho(b,p)){const S=new Da(n,b);return Kf(b,S,o)}return[]}):[];if(v.length>0)throw Promise.all(v);const g=u.find((p,y)=>{const b=i[y];return b&&Uf({result:p,errorResetBoundary:o,throwOnError:b.throwOnError,query:n.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(g?.error)throw g.error;return m(f())}function au(e,t){return qf(e,Hb)}function Qb(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 ou(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:a=!1,withResolver:o=!1}=Qb(e),i=La(),{history:l}=i,[u,m]=c.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return c.useEffect(()=>{const f=async d=>{function h(b){const S=i.parseLocation(b),w=i.getMatchedRoutes(S.pathname);return w.foundRoute===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:w.routeParams,search:i.options.parseSearch(b.search)}:{routeId:w.foundRoute.id,fullPath:w.foundRoute.fullPath,pathname:S.pathname,params:w.routeParams,search:i.options.parseSearch(b.search)}}const v=h(d.currentLocation),g=h(d.nextLocation);if(v.routeId==="__notFound__"&&g.routeId!=="__notFound__")return!1;const p=await s({action:d.action,current:v,next:g});if(!o)return p;if(!p)return!1;const y=await new Promise(b=>{m({status:"blocked",current:v,next:g,action:d.action,proceed:()=>b(!1),reset:()=>b(!0)})});return m({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),y};return a?void 0:l.block({blockerFn:f,enableBeforeUnload:n})},[s,n,a,o,l,i]),u}function It(e){const t=La({warn:e?.router===void 0}),s=e?.router||t;return _l(s.stores.__store,zl(e,s))}function gr(e){const t=La();return _l(t.stores.location,zl(e,t))}const Gb=new Set(["outbox","flagged"]),Yb=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!Gb.has(s)};function Xb(e){const t=pt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,n]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Fa(n.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function iu(e){const{openCompose:t}=Yt(),s=Ke(),n=gr(),a=Xb(e);return c.useCallback(()=>{if(Yb(n.pathname)){c.startTransition(()=>{t({mode:"new"})});return}a&&(c.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,n.pathname,a])}const Jb=e=>e.startsWith("/mail")||e.startsWith("/settings"),Zb=({accounts:e})=>{const{state:t}=Yt(),s=gr(),n=iu(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!Jb(s.pathname)||t.isOpen||o?null:r.jsx("button",{type:"button",onClick:n,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:r.jsx(Om,{className:"size-6"})})},lu=({trigger:e,children:t,align:s="right"})=>{const[n,a]=c.useState(!1),o=c.useRef(null),i=c.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),l=c.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return c.useEffect(()=>(n&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",l)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",l)}),[n,i,l]),r.jsxs("div",{ref:o,className:"relative",children:[r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!n)},className:_e("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:_e("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})]})},sn=({onClick:e,disabled:t,destructive:s,children:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:_e("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}),cu=()=>r.jsx("div",{className:"my-1 h-px bg-line"}),uu=({children:e})=>{const{Account:t}=$a();return r.jsx(t,{children:e})},ev=({email:e,onSignOut:t})=>{const s=e??"Account";return r.jsxs(lu,{trigger:r.jsx(kt,{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(cu,{})]}),r.jsxs(sn,{onClick:t,children:[r.jsx(xc,{className:"size-4"}),"Sign out"]})]})},tv=()=>r.jsx(uu,{children:({email:e,signOut:t})=>r.jsx(ev,{email:e,onSignOut:t})}),Ji=()=>{const e=_a(),t=za(e);window.open(t,"_blank","noopener,noreferrer")};function du({variant:e="icon"}){return e==="drawer"?r.jsxs("button",{type:"button",onClick:Ji,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(ai,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]}):r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(ai,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:Ji})}const fu="/mail/",po="/mail/$mailboxId",mu="/mail/outbox",hu="/mail/flagged";function go(e){return e.some(t=>t.routeId===fu)}function xn(e){return e.some(t=>t.routeId===hu)}function xr(e){return e.some(t=>t.routeId===mu)}function pu(e){return e.some(t=>t.routeId===po)}function sv(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${po}:${t}`:xn(e)?hu:xr(e)?mu:go(e)?fu:""}const zn="search-scope";function nv(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function gu(e){return xn(e)||xr(e)||pu(e)}function xu(e){return e.find(t=>t.routeId===po)?.params?.mailboxId}function rv(e){const t=xu(e.matches);return t||(gu(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function av(e,t){return go(e)?{kind:"global"}:xn(e)?{kind:"scoped",chip:{id:zn,label:"is:starred"}}:xr(e)?{kind:"scoped",chip:{id:zn,label:"in:outbox"}}:pu(e)?t?{kind:"scoped",chip:{id:zn,label:nv(t)}}:{kind:"pending"}:{kind:"global"}}function ov(e,t,s){return t.kind==="global"?{kind:"global"}:xn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const bu=({accounts:e})=>{const t=Ba({strict:!1}),s=gr(),n=t.mailboxId,{t:a}=Ka("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=pt({queries:e.map(l=>({...it({path:{accountId:l.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!n)return null;for(let l=0;l<e.length;l++){const u=i[l]?.data?.items;if(!u)continue;const m=u.find(d=>d.mailboxId===n);if(!m)continue;const f=Fa(e[l].folderAppointments);return Kn(m,f.get(n),o)}return null},iv=({accounts:e})=>{const s=Ba({strict:!1}).mailboxId,n=pt({queries:e.map(a=>({...it({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of n){const o=a.data?.items;if(!o)continue;const i=o.find(l=>l.mailboxId===s);if(i)return i.unseenCount}return null};function vu(e){const t=Ke(),{searchInput:s}=Ae(),n=bu({accounts:e}),a=It({select:l=>l.matches}),o=av(a,n),i=c.useCallback(l=>{l===zn&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const yu=[{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 lv(e){for(const t of yu){const s=t.hints.find(n=>n.action===e);if(s)return s.keys}}function Es(e){const t=lv(e);return!t||t.length===0?"":t.length===1?`(${t[0]})`:t[0]==="g"?`(${t.join(" then ")})`:`(${t.join("")})`}const cv={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function uv({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:n,onSearchClearQuery:a}=Ae(),o=Ke(),i=iu(e),{scope:l,clearScope:u}=vu(e),m=l.kind==="scoped"?[{id:l.chip.id,label:l.chip.label,tone:"scope"}]:void 0,f=cv[l.kind];return r.jsx(tg,{leading:r.jsx(Sg,{}),search:r.jsx(io,{value:t,onChange:s,onClear:n,onClearQuery:a,chips:m,onRemoveChip:u,placeholder:f}),actions:r.jsxs(r.Fragment,{children:[r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(zh,{className:"size-4"}),title:`Compose ${Es("compose")}`,"aria-label":"Compose",onClick:i}),r.jsx(du,{}),r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(wc,{className:"size-4"}),title:"Settings","aria-label":"Settings",onClick:()=>o({to:"/settings/accounts"})}),r.jsx(tv,{})]})})}const xo=({isOpen:e,onClose:t,children:s,ariaLabel:n="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=c.useRef(null),l=c.useRef(null);if(c.useEffect(()=>{if(!e)return;l.current=document.activeElement;const 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 d=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=d,l.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return 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:_e("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(jt,{className:"size-5"})})}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},dv=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},ga={all:["messages"],detail:e=>[...ga.all,"detail",e],body:e=>[...ga.detail(e),"body"]};class as 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 fv=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},mv=8,hv="x-remit-403-reason",pv=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},gv=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,xv=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},bv=async(e,t,s=async()=>null)=>{const n={},a=await s();a&&(n.Authorization=`Bearer ${a}`);const o=await Hf(e,{headers:n});if(o.status===202)throw new as("not-ready","Message body is still syncing",202,fv(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(hv),m=pv(o.status,u);throw new as(m,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(xv(t,i))throw new as("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(gv(l,i))throw new as("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},vv=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),wu=({messageId:e,bodyParts:t,enabled:s=!0})=>{const n=t?dv(t):null,a=pn(),{getToken:o}=$a(),i=c.useRef(null),l=Me(),u=c.useRef(!1),m=c.useRef(null),f=e&&n?`${e}:${n.contentUrl}`:null;m.current!==f&&(m.current=f,u.current=!1);const d=be({queryKey:e?[...ga.body(e),n?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!n)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const g=u.current;return u.current=!1,vv({fetchContent:(p,y)=>bv(p,y,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:Bl({path:{messageId:e}})})},{contentUrl:n.contentUrl,kind:n.kind,isRetryAfterNotReady:g})},enabled:s&&!!e&&!!n,staleTime:300*1e3,gcTime:1800*1e3,retry:(g,p)=>p instanceof as&&p.reason==="not-ready"?g<mv:g<1,retryDelay:(g,p)=>p instanceof as&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=d.isLoading&&!!n;c.useEffect(()=>{h&&(i.current=performance.now())},[h]),c.useEffect(()=>{d.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[d.isSuccess,a]);const v=d.data&&n?{kind:n.kind,body:d.data}:void 0;return{picked:n,data:v,isLoading:h,isError:d.isError,error:d.error,refetch:d.refetch}},yv=({outboxMessageId:e,onDraftCreated:t})=>{const[s,n]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=Me(),u=Fe(Kl()),m=Fe(Wf()),f=c.useCallback(async g=>{if(n("saving"),o(null),e){const y=await m.mutateAsync({path:{outboxMessageId:e},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"),y}const p=await u.mutateAsync({body:{...g,sendImmediately:!1}});return t(p.outboxMessageId),n("saved"),l.invalidateQueries({queryKey:er().queryKey}),p},[e,u,m,t,l]),d=c.useCallback(g=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{f(g).catch(p=>{o(p),n("error")})},2e3)},[f]),h=c.useCallback(g=>(i.current&&clearTimeout(i.current),f(g)),[f]),v=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:d,saveImmediately:h,cancelAutoSave:v}},Su=e=>"text"in e&&!("children"in e),ku=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),wv=e=>{let t=ku(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},ju=e=>{const t=e.children.map(s=>Su(s)?wv(s):ju(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${ku(s)}">${t}</a>`}default:return`<p>${t}</p>`}},Zi=e=>e.map(ju).join(""),Cu=e=>Su(e)?e.text:e.children.map(Cu).join(""),xa=e=>e.map(Cu).join(`
116
- `),Sv=["Tab",","],el=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),kv=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(el(a))return{email:a,displayName:n}}if(el(t))return{email:t}},Vr=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=c.useState(""),i=c.useRef(null),l=ir(a,200),{data:u}=be({...tr({query:{q:l,limit:8}}),enabled:l.length>=2}),m=u?.items??[],f=new Set(t.map(x=>x.email.toLowerCase())),d=a.length>=2?m.filter(x=>!f.has(x.normalizedEmail.toLowerCase())):[],h=c.useCallback(x=>{f.has(x.email.toLowerCase())||(s([...t,x]),o(""))},[t,f,s]),v=c.useCallback(x=>{s(t.filter((k,M)=>M!==x))},[t,s]),g=c.useCallback(x=>{h({email:x.normalizedEmail,displayName:x.displayName}),i.current?.focus()},[h]),p=c.useCallback(()=>{const x=kv(a);x&&h(x)},[a,h]),y=Ul({count:d.length,acceptKeys:Sv,onAccept:x=>g(d[x])}),b=c.useMemo(()=>d.map(x=>({value:x.normalizedEmail,label:x.displayName??x.normalizedEmail,...x.displayName?{hint:x.normalizedEmail}:{}})),[d]),S=c.useCallback(x=>{if(x.key==="Backspace"&&a===""&&t.length>0){v(t.length-1);return}y.handleKeyDown(x)||(x.key==="Enter"||x.key==="Tab"||x.key===",")&&a.trim()&&(x.preventDefault(),p())},[a,t.length,v,y.handleKeyDown,p]),w=c.useCallback(()=>{setTimeout(()=>{p(),y.dismiss()},150)},[p,y.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:()=>i.current?.focus(),onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&i.current?.focus()},children:[t.map((x,k)=>r.jsx(qh,{email:x.email,displayName:x.displayName,onRemove:()=>v(k)},x.email)),r.jsx("input",{ref:i,id:`address-field-${e}`,type:"text",value:a,onChange:x=>{y.reopen(),o(x.target.value)},onKeyDown:S,onBlur:w,placeholder:t.length===0?n:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5",autoComplete:"off",...y.comboboxProps})]})]}),y.open&&r.jsx(ql,{id:y.listId,suggestions:b,activeIndex:y.activeIndex,optionId:y.optionId,onPick:x=>{const k=d.find(M=>M.normalizedEmail===x.value);k&&g(k)},onHighlight:y.setActiveIndex,label:`${e} suggestions`,className:"absolute left-12 right-0 z-50 mt-1 max-h-[200px] shadow-lg"})]})},jv=({accountId:e})=>{const t=Ke();return 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(Aa,{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:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",r.jsx(Vf,{className:"size-3","aria-hidden":"true"})]})]})]})},tl=150,Cv=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>tl}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>tl})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},Nv=({selectedAccountId:e,onSelect:t})=>{const{data:s}=be({...Mt(),staleTime:1/0}),n=s?.accounts??[];if(c.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))})]})},Ev=({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})]}),Iv=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],Tv=["href"],Rv=e=>Pl.sanitize(e,{ALLOWED_TAGS:Iv,ALLOWED_ATTR:Tv}),Mv=c.lazy(()=>Gf(()=>import("./ComposeBody-C3RMgwOn.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.ComposeBody}))),Av=()=>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"})]}),Nu=[{type:"p",children:[{text:""}]}],Ov=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],Pv=e=>e?[...Ov,{type:"p",children:[{text:e}]}]:Nu,Dv=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",Lv=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",Fv=(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(),l=new Set(o.map(m=>m.email.toLowerCase())),u=[...n.to,...n.cc].filter(m=>m.normalizedEmail.toLowerCase()!==i&&!l.has(m.normalizedEmail.toLowerCase())).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));return{to:o,cc:u}},$v=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}},_v=(e,t,s,n,a)=>e.length===0&&t.length===0&&s.length===0&&n.trim()===""&&xa(a).trim()==="",zv=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:n,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:m,showBcc:f,setShowBcc:d,subject:h,setSubject:v})=>{const g=Xt(),{isKeyboardOpen:p}=Cv();if(!g&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(S=>S.displayName??S.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.push(h),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:b.length>0?b.join(" · "):"…"}),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:"…"})]})}return r.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[r.jsx(Nv,{selectedAccountId:e,onSelect:t}),r.jsx(Vr,{label:"To",addresses:s,onChange:n,placeholder:"Recipients"}),u?r.jsx(Vr,{label:"Cc",addresses:a,onChange:o}):r.jsxs("div",{className:"flex gap-2 pl-14",children:[r.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),r.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!f&&r.jsx("div",{className:"pl-14",children:r.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),f&&r.jsx(Vr,{label:"Bcc",addresses:i,onChange:l}),r.jsx(Ev,{value:h,onChange:v})]})},bo=({mode:e,account:t,sourceMessage:s,onClose:n,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Yt(),{pushError:u}=st(),{outboxMessageId:m}=o,[f,d]=c.useState([]),[h,v]=c.useState([]),[g,p]=c.useState([]),[y,b]=c.useState(""),[S,w]=c.useState(!1),[x,k]=c.useState(!1),[M,O]=c.useState(t?.accountId),[C,R]=c.useState(!1),P=c.useRef(m);c.useEffect(()=>{P.current!==m&&(P.current=m,m&&(d([]),v([]),p([]),b(""),w(!1),k(!1),D(Nu),R(!1)))},[m]);const{signature:E}=$m(M),[L,D]=c.useState(()=>Pv(E.plainText)),{data:j}=be({...Qf({path:{outboxMessageId:m??""}}),enabled:!!m&&!C});c.useEffect(()=>{!j||C||(d(j.toAddresses.map(H=>({email:H,displayName:void 0}))),j.ccAddresses&&j.ccAddresses.length>0&&(v(j.ccAddresses.map(H=>({email:H,displayName:void 0}))),w(!0)),j.bccAddresses&&j.bccAddresses.length>0&&(p(j.bccAddresses.map(H=>({email:H,displayName:void 0}))),k(!0)),j.subject&&b(j.subject),j.textBody&&D([{type:"p",children:[{text:j.textBody}]}]),O(j.accountId),R(!0))},[j,C]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:H,cc:ie}=Fv(s,e,t?.email);d(H),v(ie),ie.length>0&&w(!0),b(Dv(s.envelope.subject))}e==="forward"&&b(Lv(s.envelope.subject))}},[e,s,t?.email]);const T=e==="reply"||e==="reply_all"||e==="forward",{data:A}=wu({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:T&&!!s}),I=A?.kind==="text"?A.body:"",F=A?.kind==="html"?Rv(A.body):void 0,N=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:q,saveError:Q,saveDraft:ae,cancelAutoSave:U}=yv({outboxMessageId:m,onDraftCreated:i});c.useEffect(()=>{Q&&u({title:"Couldn't save draft",detail:mt(Q)??"Saving the draft failed.",error:Q})},[Q,u]);const z=Fe(Kl()),ee=Fe(Hl()),me=Fe({...sr(),onError:H=>{u(is("Couldn't discard draft","The draft wasn't discarded.",H))}}),{data:fe}=be({...Mt(),staleTime:1/0}),se=fe?.accounts.find(H=>H.accountId===M),W=se?Lm(se):!1,pe=z.isPending||ee.isPending,ve=f.length>0&&!!M&&!W;c.useEffect(()=>{if(!M||m&&!C||_v(f,h,g,y,L))return;const H=xa(L),ie=Zi(L);ae({accountId:M,toAddresses:f.map(ge=>ge.email),ccAddresses:h.length>0?h.map(ge=>ge.email):void 0,bccAddresses:g.length>0?g.map(ge=>ge.email):void 0,subject:y||void 0,textBody:H||void 0,htmlBody:ie||void 0})},[M,m,C,f,h,g,y,L,ae]);const Ne=c.useCallback(async()=>{if(!M||f.length===0)return;U();const H=s&&(e==="reply"||e==="reply_all")?$v(s):{};let ie=m,ge=!1;if(!ie){const xe=xa(L),B=Zi(L),ue=await z.mutateAsync({body:{accountId:M,toAddresses:f.map(oe=>oe.email),ccAddresses:h.length>0?h.map(oe=>oe.email):void 0,bccAddresses:g.length>0?g.map(oe=>oe.email):void 0,subject:y||void 0,textBody:xe||void 0,htmlBody:B||void 0,sendImmediately:!0,...H}}).catch(oe=>(u({title:"Couldn't send message",detail:mt(oe)??"Saving the draft failed.",error:oe}),null));if(ue===null)return;ie=ue.outboxMessageId,ge=!0,i(ie)}await ee.mutateAsync({path:{outboxMessageId:ie}}).catch(xe=>(u({title:"Couldn't send message",detail:mt(xe)??(ge?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:xe}),null))!==null&&(l(ie),n())},[M,f,h,g,y,L,e,s,m,z,ee,U,l,i,u,n]),we=c.useCallback(()=>{U(),m&&me.mutate({path:{outboxMessageId:m}}),n()},[U,m,me,n]),X=c.useCallback(H=>{O(H.accountId),a?.(H)},[a]);return r.jsx(lg,{banner:se&&W?r.jsx(jv,{accountId:se.accountId}):void 0,header:r.jsx(zv,{selectedAccountId:M,onAccountChange:X,toAddresses:f,setToAddresses:d,ccAddresses:h,setCcAddresses:v,bccAddresses:g,setBccAddresses:p,showCc:S,setShowCc:w,showBcc:x,setShowBcc:k,subject:y,setSubject:b}),quoted:I||F?r.jsx(Ig,{text:I,html:F,senderName:N}):void 0,actionBar:r.jsx(ig,{onSend:Ne,onDiscard:we,sending:pe,canSend:ve,saveStatus:q,unavailableReason:W?"SMTP not configured":void 0,onUnavailable:H=>u({title:"Can't send yet",detail:H})}),children:r.jsx(c.Suspense,{fallback:r.jsx(Av,{}),children:r.jsx(Mv,{value:L,onChange:D,onSubmit:Ne,autoFocus:e==="new"})})})},sl=({mode:e,account:t,sourceMessage:s,onClose:n})=>r.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:r.jsx(bo,{mode:e,account:t,sourceMessage:s,onClose:n})}),Eu=({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})]}),vo=({enabled:e=!0,bindings:t,capture:s=!1})=>{const n=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const m=i.noModifiers??!0,f=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(m&&f)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",n,s),()=>window.removeEventListener("keydown",n,s)},[e,n,s])},yo=e=>{const{data:t,isLoading:s}=be({...Mt(),staleTime:1/0}),n=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=pt({queries:n.map(l=>({...it({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<n.length;l++)if((a[l].data?.items??[]).some(f=>f.mailboxId===e))return n[l]}},[e,n,a]),isLoading:o}},Bv=100,ba=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),Kv=(e,t=Bv)=>{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},Iu=async(e,t,s,n)=>{const a=Kv(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(n())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const m=a[u],f=await ba(t(m));if(!f.ok)return l.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:l,cancelled:!1,error:f.error};i+=m.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},br=async(e,t)=>{await Iu(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},Uv=async(e,t,s,n,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await ba(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const m=u.value;if(m.ids.length>0){const f=await ba(s(m.ids));if(!f.ok)return{done:o,failedIds:i,cancelled:!1,error:f.error};o+=m.ids.length,n({done:o,total:t})}l=m.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},qv=e=>({done:e.done,total:Math.max(e.total,e.done)}),Tu=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),Ru=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Mu=(e,t)=>e===void 0?e:Tu(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:Ru(e)?{...e,items:t(e.items)}:e,Ot=e=>{const t=[];for(const s of new Set(e))t.push(nr({path:{mailboxId:s}})),t.push(Ua({path:{mailboxId:s}}));return t.push(qa()),t},bn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),vn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,n])=>({queryKey:s,data:n})),yn=(e,t,s)=>{const n=a=>Mu(a,s);for(const a of t)e.setQueriesData({queryKey:a},n)},wn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},Pt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Hv=3e3,Wv=(e,t,s)=>{if(e.length===0)return()=>{};const n=setTimeout(()=>s(e),t);return()=>clearTimeout(n)},vr=(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]},Vn=(e,t,s)=>e.map(n=>t.has(n.messageId)?{...n,isRead:s}:n),Vv=(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),Qv=({messages:e,expandedIds:t,threadId:s,mailboxId:n,accountId:a})=>{const o=Me(),{pushError:i}=st(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:m}=Fe({...rr(),onMutate:async h=>{const v=new Set(h.body.messageIds??[]),g=h.body.isRead??!0,p=hs({path:{threadId:s}}),y=Ot(vr(v,e,n));await Promise.all([o.cancelQueries({queryKey:p}),bn(o,y)]);const b=o.getQueriesData({queryKey:p}).filter(w=>w[1]!==void 0).map(([w,x])=>({queryKey:w,data:x})),S=vn(o,y);return o.setQueriesData({queryKey:p},w=>w&&{...w,items:Vn(w.items,v,g)}),yn(o,y,w=>Vn(w,v,g)),{threadMessagesPrefix:p,listPrefixes:y,previousThreadMessages:b,previousThreadsList:S}},onSuccess:(h,v)=>{const g=v.body.messageIds??[];for(const p of g)l.current.add(p),u.current.delete(p)},onError:(h,v,g)=>{const p=v.body.messageIds??[];for(const b of p)u.current.delete(b);if(g){for(const b of g.previousThreadMessages)o.setQueryData(b.queryKey,b.data);wn(o,g.previousThreadsList)}const y=v.body.isRead??!0;i({title:y?"Couldn't mark as read":"Couldn't mark as unread",detail:mt(h),error:h})},onSettled:(h,v,g,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),Pt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:ms({path:{accountId:a}})}))}}),f=c.useCallback(h=>{const v=h.filter(g=>!l.current.has(g)&&!u.current.has(g));if(v.length!==0){for(const g of v)u.current.add(g);m({body:{messageIds:v,isRead:!0}})}},[m]),d=c.useMemo(()=>Vv(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Wv(d,Hv,f),[d,f]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},yr=e=>{const{mailboxId:t,accountId:s,messages:n}=e,a=Me(),{pushError:o}=st(),{mutateAsync:i,isPending:l}=Fe({...rr(),onError:(m,f)=>{const d=f.body.isRead??!0;o({title:d?"Couldn't mark as read":"Couldn't mark as unread",detail:mt(m),error:m})},onSettled:(m,f,d)=>{Pt(a,Ot(vr(d.body.messageIds??[],n??[],t))),s&&a.invalidateQueries({queryKey:ms({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((m,f)=>{m.length!==0&&br(m,d=>i({body:{messageIds:d,isRead:f}}))},[i]),isPending:l}},Gv=60,Yv=1.5,Xv=(e,t,s)=>{const n=Math.abs(e),a=Math.abs(t);return n<s?{direction:null}:n<a*Yv?{direction:null}:{direction:e<0?"left":"right"}},Jv=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Gv})=>{const n=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){n.current=null;return}n.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const m=n.current;if(n.current=null,!m)return;const{direction:f}=Xv(u.clientX-m.x,u.clientY-m.y,s);f==="left"&&e?.(),f==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{n.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},Zv=(e,t,s)=>t?.find(n=>n.messageId===e)?.mailboxId??s,nl=(e,t,s)=>e.map(n=>n.messageId===t?{...n,hasStars:s}:n),wo=({threadId:e,mailboxId:t,messages:s})=>{const n=Me(),{pushError:a}=st(),{mutate:o,isPending:i,variables:l}=Fe({...Yf(),onMutate:async m=>{const f=m.path.messageId,d=m.body.isStarred??!1,h=hs({path:{threadId:e}}),v=Ot([Zv(f,s,t)]);await Promise.all([n.cancelQueries({queryKey:h}),bn(n,v)]);const g=n.getQueriesData({queryKey:h}).filter(y=>y[1]!==void 0).map(([y,b])=>({queryKey:y,data:b})),p=vn(n,v);return n.setQueriesData({queryKey:h},y=>Mu(y,b=>nl(b,f,d))),yn(n,v,y=>nl(y,f,d)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:g,previousThreadsList:p}},onError:(m,f,d)=>{if(d){for(const v of d.previousThreadMessages)n.setQueryData(v.queryKey,v.data);wn(n,d.previousThreadsList)}const h=f.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:mt(m),error:m})},onSettled:(m,f,d,h)=>{h&&(n.invalidateQueries({queryKey:h.threadMessagesPrefix}),Pt(n,h.listPrefixes))}});return{toggleStar:(m,f)=>{o({path:{messageId:m},body:{isStarred:!f}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function wr(e){return e===void 0?"uncategorized":e}const ey={inbox:"Inbox",junk:"Junk"},So=e=>e.destinationMailboxId!==void 0,ty=(e,t)=>{if(So(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${ey[s]??"another folder"} by Remit`},sy=(e,t)=>{if(e===Yo.MoveToInbox)return t.inboxMailboxId;if(e===Yo.MoveToJunk)return t.junkMailboxId},ny=(e,t,s)=>{if(!e||!t)return!1;const n=So(e)?e.destinationMailboxId:sy(e.action,s);return n!==void 0&&n===t},ry=(e,t)=>{if(e){if(So(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},Sr=(e,t)=>{const{data:s,isLoading:n}=be({...Mt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:n}},ay=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},oy=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},ko=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},zs=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Junk");return{junkMailboxId:t,isLoading:s}},jo=e=>{const{data:t}=be({...Mt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},rl=(e,t)=>e.filter(s=>!t.has(s.messageId)),cs=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=Me(),{pushError:o}=st(),{mutateAsync:i,isPending:l}=Fe({...Xf(),onMutate:async m=>{const f=new Set(m.body.messageIds??[]),d=t?hs({path:{threadId:t}}):[],h=Ot([e,m.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:d})]:[],bn(a,h)]);const v=t?a.getQueriesData({queryKey:d}).filter(p=>p[1]!==void 0).map(([p,y])=>({queryKey:p,data:y})):[],g=vn(a,h);return t&&a.setQueriesData({queryKey:d},p=>p&&{...p,items:rl(p.items,f)}),yn(a,h,p=>rl(p,f)),n?.(Array.from(f)),{threadMessagesPrefix:d,listPrefixes:h,previousThreadMessages:v,previousThreadsList:g}},onError:(m,f,d)=>{if(d){for(const v of d.previousThreadMessages)a.setQueryData(v.queryKey,v.data);wn(a,d.previousThreadsList)}const h=f.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:mt(m),error:m})},onSettled:(m,f,d,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),Pt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:ms({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((m,f)=>{m.length!==0&&br(m,d=>i({body:{messageIds:d,destinationMailboxId:f}}))},[i]),isPending:l}},iy=({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a})=>{const{inboxMailboxId:o}=ko(e),{junkMailboxId:i}=zs(e),{moveMessages:l,isPending:u}=cs({mailboxId:n,threadId:s,accountId:e}),{data:m}=be({...it({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),f={inboxMailboxId:o,junkMailboxId:i},d=ny(a,n,f),h=ry(a,f),v=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!d||!a)return{show:!1,label:"",isUndoing:!1};const g=a.fromMailboxId?m?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>aa(p.fullPath))[0]:void 0;return{show:!0,label:ty(a,g),onUndo:h?v:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function ly({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a}){const o=iy({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a});return o.show?r.jsx(sg,{label:o.label,onUndo:o.onUndo,undoLabel:o.isUndoing?"Undoing…":"Undo",filtersHref:o.filtersHref}):null}const al=(e,t)=>e.filter(s=>!t.has(s.messageId)),cy=e=>e.filter(t=>t.isDeleted!==!0),us=({mailboxId:e,threadId:t,accountId:s,messages:n,onAfterOptimisticRemove:a})=>{const o=Me(),{pushError:i}=st(),{mutateAsync:l,isPending:u}=Fe({...Jf(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),h=t?hs({path:{threadId:t}}):[],v=Ot(vr(d,n??[],e));await Promise.all([o.cancelQueries({queryKey:h}),bn(o,v)]);const g=t?o.getQueriesData({queryKey:h}).filter(y=>y[1]!==void 0).map(([y,b])=>({queryKey:y,data:b})):[],p=vn(o,v);return t&&o.setQueriesData({queryKey:h},y=>y&&{...y,items:al(y.items,d)}),yn(o,v,y=>al(y,d)),a?.(Array.from(d)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:g,previousThreadsList:p}},onError:(f,d,h)=>{if(h){for(const g of h.previousThreadMessages)o.setQueryData(g.queryKey,g.data);wn(o,h.previousThreadsList)}const v=d.body.messageIds?.length??0;i({title:v>1?`Couldn't delete ${v} messages`:"Couldn't delete this message",detail:mt(f),error:f})},onSettled:(f,d,h,v)=>{v&&(t&&o.invalidateQueries({queryKey:v.threadMessagesPrefix}),Pt(o,v.listPrefixes),s&&o.invalidateQueries({queryKey:ms({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(f=>{f.length!==0&&br(f,d=>l({body:{messageIds:d}}))},[l]),isPending:u}},Au=(e,t=Date.now())=>({value:e,setAt:t}),uy=(e,t,s,n)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Au(!0,n):delete a.trusted,{...e,flags:a}},dy=(e,t,s,n)=>{const a=o=>o.map(i=>uy(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)}}},Co=({messageId:e})=>{const t=Me(),{pushError:s}=st(),{mutate:n,isPending:a,error:o,reset:i}=Fe({...Wl(),onMutate:async u=>{const m=u.path.addressId,d=u.body.flags?.trusted?.value===!0,h=Bl({path:{messageId:e}});await t.cancelQueries({queryKey:h});const v=t.getQueriesData({queryKey:h}).filter(g=>g[1]!==void 0).map(([g,p])=>({queryKey:g,data:p}));return t.setQueriesData({queryKey:h},g=>g&&dy(g,m,d)),{describePrefix:h,previous:v}},onError:(u,m,f)=>{if(f)for(const d of f.previous)t.setQueryData(d.queryKey,d.data);s(is("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,m,f,d)=>{d&&t.invalidateQueries({queryKey:d.describePrefix})}});return{toggleTrusted:(u,m)=>{n({path:{addressId:u},body:{flags:{trusted:Au(!m)}}})},isPending:a,error:o,reset:i}};var kr="Dialog",[Ou]=vx(kr),[fy,gt]=Ou(kr),Pu=e=>{const{__scopeDialog:t,children:s,open:n,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[m,f]=Sx({prop:n,defaultProp:a??!1,onChange:o,caller:kr});return r.jsx(fy,{scope:t,triggerRef:l,contentRef:u,contentId:Kr(),titleId:Kr(),descriptionId:Kr(),open:m,onOpenChange:f,onOpenToggle:c.useCallback(()=>f(d=>!d),[f]),modal:i,children:s})};Pu.displayName=kr;var Du="DialogTrigger",my=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(Du,s),o=ps(t,a.triggerRef);return r.jsx(At.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Eo(a.open),...n,ref:o,onClick:Ht(e.onClick,a.onOpenToggle)})});my.displayName=Du;var No="DialogPortal",[hy,Lu]=Ou(No,{forceMount:void 0}),Fu=e=>{const{__scopeDialog:t,forceMount:s,children:n,container:a}=e,o=gt(No,t);return r.jsx(hy,{scope:t,forceMount:s,children:c.Children.map(n,i=>r.jsx(hr,{present:s||o.open,children:r.jsx(Yc,{asChild:!0,container:a,children:i})}))})};Fu.displayName=No;var Qn="DialogOverlay",$u=c.forwardRef((e,t)=>{const s=Lu(Qn,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=gt(Qn,e.__scopeDialog);return o.modal?r.jsx(hr,{present:n||o.open,children:r.jsx(gy,{...a,ref:t})}):null});$u.displayName=Qn;var py=mo("DialogOverlay.RemoveScroll"),gy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(Qn,s),o=Bx(),i=ps(t,o);return r.jsx(ru,{as:py,allowPinchZoom:!0,shards:[a.contentRef],children:r.jsx(At.div,{"data-state":Eo(a.open),...n,ref:i,style:{pointerEvents:"auto",...n.style}})})}),Ps="DialogContent",_u=c.forwardRef((e,t)=>{const s=Lu(Ps,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=gt(Ps,e.__scopeDialog);return r.jsx(hr,{present:n||o.open,children:o.modal?r.jsx(xy,{...a,ref:t}):r.jsx(by,{...a,ref:t})})});_u.displayName=Ps;var xy=c.forwardRef((e,t)=>{const s=gt(Ps,e.__scopeDialog),n=c.useRef(null),a=ps(t,s.contentRef,n);return c.useEffect(()=>{const o=n.current;if(o)return cb(o)},[]),r.jsx(zu,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Ht(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Ht(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Ht(e.onFocusOutside,o=>o.preventDefault())})}),by=c.forwardRef((e,t)=>{const s=gt(Ps,e.__scopeDialog),n=c.useRef(!1),a=c.useRef(!1);return r.jsx(zu,{...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()}})}),zu=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=gt(Ps,s);return Hx(),r.jsx(r.Fragment,{children:r.jsx(Qc,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:r.jsx(Wc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Eo(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),Bu="DialogTitle",Ku=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(Bu,s);return r.jsx(At.h2,{id:a.titleId,...n,ref:t})});Ku.displayName=Bu;var Uu="DialogDescription",vy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(Uu,s);return r.jsx(At.p,{id:a.descriptionId,...n,ref:t})});vy.displayName=Uu;var qu="DialogClose",yy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(qu,s);return r.jsx(At.button,{type:"button",...n,ref:t,onClick:Ht(e.onClick,()=>a.onOpenChange(!1))})});yy.displayName=qu;function Eo(e){return e?"open":"closed"}function wy(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}const Hu=K.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}),Sn=()=>{const e=K.useContext(Hu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};wy(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
115
+ `)},Ub=0,Cs=[];function qb(e){var t=c.useRef([]),s=c.useRef([0,0]),n=c.useRef(),a=c.useState(Ub++)[0],o=c.useState(eu)[0],i=c.useRef(e);c.useEffect(function(){i.current=e},[e]),c.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=Rf([e.lockRef.current],(e.shards||[]).map(Vi),!0).filter(Boolean);return p.forEach(function(y){return y.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=c.useCallback(function(p,y){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var b=Mn(p),S=s.current,w="deltaX"in p?p.deltaX:S[0]-b[0],x="deltaY"in p?p.deltaY:S[1]-b[1],k,M=p.target,O=Math.abs(w)>Math.abs(x)?"h":"v";if("touches"in p&&O==="h"&&M.type==="range")return!1;var j=window.getSelection(),R=j&&j.anchorNode,P=R?R===M||R.contains(M):!1;if(P)return!1;var E=Hi(O,M);if(!E)return!0;if(E?k=O:(k=O==="v"?"h":"v",E=Hi(O,M)),!E)return!1;if(!n.current&&"changedTouches"in p&&(w||x)&&(n.current=k),!k)return!0;var L=n.current||k;return zb(L,y,p,L==="h"?w:x)},[]),u=c.useCallback(function(p){var y=p;if(!(!Cs.length||Cs[Cs.length-1]!==o)){var b="deltaY"in y?Wi(y):Mn(y),S=t.current.filter(function(k){return k.name===y.type&&(k.target===y.target||y.target===k.shadowParent)&&Bb(k.delta,b)})[0];if(S&&S.should){y.cancelable&&y.preventDefault();return}if(!S){var w=(i.current.shards||[]).map(Vi).filter(Boolean).filter(function(k){return k.contains(y.target)}),x=w.length>0?l(y,w[0]):!i.current.noIsolation;x&&y.cancelable&&y.preventDefault()}}},[]),m=c.useCallback(function(p,y,b,S){var w={name:p,delta:y,target:b,should:S,shadowParent:Hb(b)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(x){return x!==w})},1)},[]),f=c.useCallback(function(p){s.current=Mn(p),n.current=void 0},[]),d=c.useCallback(function(p){m(p.type,Wi(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){m(p.type,Mn(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return Cs.push(o),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:h}),document.addEventListener("wheel",u,ks),document.addEventListener("touchmove",u,ks),document.addEventListener("touchstart",f,ks),function(){Cs=Cs.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,ks),document.removeEventListener("touchmove",u,ks),document.removeEventListener("touchstart",f,ks)}},[]);var v=e.removeScrollBar,g=e.inert;return c.createElement(c.Fragment,null,g?c.createElement(o,{styles:Kb(a)}):null,v?c.createElement(Ob,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Hb(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Wb=yb(Zc,qb);var ru=c.forwardRef(function(e,t){return c.createElement(pr,Bt({},e,{ref:t,sideCar:Wb}))});ru.classNames=pr.classNames;var Vb=class extends Da{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:l}=n,u=s.fetchMeta?.fetchMore?.direction,m=i&&u==="forward",f=a&&u==="forward",d=i&&u==="backward",h=a&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Af(t,s.data),hasPreviousPage:Mf(t,s.data),isFetchNextPageError:m,isFetchingNextPage:f,isFetchPreviousPageError:d,isFetchingPreviousPage:h,isRefetchError:l&&!m&&!d,isRefetching:o&&!f&&!h}}};function Qi(e,t){const s=new Set(t);return e.filter(n=>!s.has(n))}function Qb(e,t,s){const n=e.slice(0);return n[t]=s,n}var Gb=class extends Of{#s;#e;#a;#r;#t;#n;#o;#i;#l;#c=[];constructor(e,t,s){super(),this.#s=e,this.#r=s,this.#a=[],this.#t=[],this.#e=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#t.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#t.forEach(e=>{e.destroy()})}setQueries(e,t){this.#a=e,this.#r=t,ra.batch(()=>{const s=this.#t,n=this.#f(this.#a);n.forEach(f=>f.observer.setOptions(f.defaultedQueryOptions));const a=n.map(f=>f.observer),o=a.map(f=>f.getCurrentResult()),i=s.length!==a.length,l=a.some((f,d)=>f!==s[d]),u=i||l,m=u?!0:o.some((f,d)=>{const h=this.#e[d];return!h||!Pf(f,h)});!u&&!m||(u&&(this.#c=n,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(Qi(s,a).forEach(f=>{f.destroy()}),Qi(a,s).forEach(f=>{f.subscribe(d=>{this.#m(f,d)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const s=this.#f(e),n=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[n,o=>this.#d(o??n,t,a),()=>this.#u(n,s)]}#u(e,t){return t.map((s,n)=>{const a=e[n];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const n=this.#l,a=s!==void 0&&n!==void 0&&(n.length!==s.length||s.some((o,i)=>o!==n[i]));return(!this.#n||this.#e!==this.#i||a||t!==this.#o)&&(this.#o=t,this.#i=this.#e,s!==void 0&&(this.#l=s),this.#n=Df(this.#n,t(e))),this.#n}return e}#p(){return this.#r?.combine!==void 0&&this.#t.some((e,t)=>e.options.suspense&&this.#e[t]?.data===void 0)}#f(e){const t=new Map;this.#t.forEach(n=>{const a=n.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(n):t.set(a,[n])});const s=[];return e.forEach(n=>{const a=this.#s.defaultQueryOptions(n),i=t.get(a.queryHash)?.shift()??new Da(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=Qb(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,n=t?s:this.#d(e,this.#r?.combine);(t||s!==n)&&ra.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function pt({queries:e,...t},s){const n=Me(),a=Lf(),o=Ff(),i=c.useMemo(()=>e.map(p=>{const y=n.defaultQueryOptions(p);return y._optimisticResults=a?"isRestoring":"optimistic",y}),[e,n,a]);i.forEach(p=>{$f(p);const y=n.getQueryCache().get(p.queryHash);_f(p,o,y)}),zf(o);const[l]=c.useState(()=>new Gb(n,i,t)),[u,m,f]=l.getOptimisticResult(i,t.combine),d=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>d?l.subscribe(ra.batchCalls(p)):Bf,[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const v=u.some((p,y)=>Uo(i[y],p))?u.flatMap((p,y)=>{const b=i[y];if(b&&Uo(b,p)){const S=new Da(n,b);return Kf(b,S,o)}return[]}):[];if(v.length>0)throw Promise.all(v);const g=u.find((p,y)=>{const b=i[y];return b&&Uf({result:p,errorResetBoundary:o,throwOnError:b.throwOnError,query:n.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(g?.error)throw g.error;return m(f())}function au(e,t){return qf(e,Vb)}function Yb(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 ou(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:a=!1,withResolver:o=!1}=Yb(e),i=La(),{history:l}=i,[u,m]=c.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return c.useEffect(()=>{const f=async d=>{function h(b){const S=i.parseLocation(b),w=i.getMatchedRoutes(S.pathname);return w.foundRoute===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:w.routeParams,search:i.options.parseSearch(b.search)}:{routeId:w.foundRoute.id,fullPath:w.foundRoute.fullPath,pathname:S.pathname,params:w.routeParams,search:i.options.parseSearch(b.search)}}const v=h(d.currentLocation),g=h(d.nextLocation);if(v.routeId==="__notFound__"&&g.routeId!=="__notFound__")return!1;const p=await s({action:d.action,current:v,next:g});if(!o)return p;if(!p)return!1;const y=await new Promise(b=>{m({status:"blocked",current:v,next:g,action:d.action,proceed:()=>b(!1),reset:()=>b(!0)})});return m({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),y};return a?void 0:l.block({blockerFn:f,enableBeforeUnload:n})},[s,n,a,o,l,i]),u}function It(e){const t=La({warn:e?.router===void 0}),s=e?.router||t;return Dl(s.stores.__store,Ll(e,s))}function gr(e){const t=La();return Dl(t.stores.location,Ll(e,t))}const Xb=new Set(["outbox","flagged"]),Jb=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!Xb.has(s)};function Zb(e){const t=pt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,n]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Fa(n.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function iu(e){const{openCompose:t}=Yt(),s=Ke(),n=gr(),a=Zb(e);return c.useCallback(()=>{if(Jb(n.pathname)){c.startTransition(()=>{t({mode:"new"})});return}a&&(c.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,n.pathname,a])}const ev=e=>e.startsWith("/mail")||e.startsWith("/settings"),tv=({accounts:e})=>{const{state:t}=Yt(),s=gr(),n=iu(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!ev(s.pathname)||t.isOpen||o?null:r.jsx("button",{type:"button",onClick:n,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:r.jsx(Om,{className:"size-6"})})},lu=({trigger:e,children:t,align:s="right"})=>{const[n,a]=c.useState(!1),o=c.useRef(null),i=c.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),l=c.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return c.useEffect(()=>(n&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",l)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",l)}),[n,i,l]),r.jsxs("div",{ref:o,className:"relative",children:[r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!n)},className:_e("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:_e("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})]})},sn=({onClick:e,disabled:t,destructive:s,children:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:_e("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}),cu=()=>r.jsx("div",{className:"my-1 h-px bg-line"}),uu=({children:e})=>{const{Account:t}=$a();return r.jsx(t,{children:e})},sv=({email:e,onSignOut:t})=>{const s=e??"Account";return r.jsxs(lu,{trigger:r.jsx(kt,{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(cu,{})]}),r.jsxs(sn,{onClick:t,children:[r.jsx(xc,{className:"size-4"}),"Sign out"]})]})},nv=()=>r.jsx(uu,{children:({email:e,signOut:t})=>r.jsx(sv,{email:e,onSignOut:t})}),du="/mail/",mo="/mail/$mailboxId",fu="/mail/outbox",mu="/mail/flagged";function ho(e){return e.some(t=>t.routeId===du)}function xn(e){return e.some(t=>t.routeId===mu)}function xr(e){return e.some(t=>t.routeId===fu)}function hu(e){return e.some(t=>t.routeId===mo)}function rv(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${mo}:${t}`:xn(e)?mu:xr(e)?fu:ho(e)?du:""}const zn="search-scope";function av(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function pu(e){return xn(e)||xr(e)||hu(e)}function gu(e){return e.find(t=>t.routeId===mo)?.params?.mailboxId}function ov(e){const t=gu(e.matches);return t||(pu(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function iv(e,t){return ho(e)?{kind:"global"}:xn(e)?{kind:"scoped",chip:{id:zn,label:"is:starred"}}:xr(e)?{kind:"scoped",chip:{id:zn,label:"in:outbox"}}:hu(e)?t?{kind:"scoped",chip:{id:zn,label:av(t)}}:{kind:"pending"}:{kind:"global"}}function lv(e,t,s){return t.kind==="global"?{kind:"global"}:xn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const xu=({accounts:e})=>{const t=_a({strict:!1}),s=gr(),n=t.mailboxId,{t:a}=za("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=pt({queries:e.map(l=>({...it({path:{accountId:l.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!n)return null;for(let l=0;l<e.length;l++){const u=i[l]?.data?.items;if(!u)continue;const m=u.find(d=>d.mailboxId===n);if(!m)continue;const f=Fa(e[l].folderAppointments);return Kn(m,f.get(n),o)}return null},cv=({accounts:e})=>{const s=_a({strict:!1}).mailboxId,n=pt({queries:e.map(a=>({...it({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of n){const o=a.data?.items;if(!o)continue;const i=o.find(l=>l.mailboxId===s);if(i)return i.unseenCount}return null};function bu(e){const t=Ke(),{searchInput:s}=Ae(),n=xu({accounts:e}),a=It({select:l=>l.matches}),o=iv(a,n),i=c.useCallback(l=>{l===zn&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const vu=[{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 uv(e){for(const t of vu){const s=t.hints.find(n=>n.action===e);if(s)return s.keys}}function yu(e){const t=uv(e);return!t||t.length===0?"":t.length===1?t[0]??"":t[0]==="g"?t.join(" then "):t.join("")}function Qs(e){const t=yu(e);return t===""?"":`(${t})`}function dv({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:n,onSearchClearQuery:a}=Ae(),o=Ke(),i=iu(e),{scope:l,clearScope:u}=bu(e),m=l.kind==="scoped"?[{id:l.chip.id,label:l.chip.label,tone:"scope"}]:void 0;return r.jsx(Ug,{search:{value:t,scope:l.kind,chips:m,onChange:s,onClear:n,onClearQuery:a,onRemoveChip:u},onCompose:i,onReportBug:Fl,onOpenSettings:()=>o({to:"/settings/accounts"}),composeShortcut:yu("compose"),account:r.jsx(nv,{})})}const po=({isOpen:e,onClose:t,children:s,ariaLabel:n="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=c.useRef(null),l=c.useRef(null);if(c.useEffect(()=>{if(!e)return;l.current=document.activeElement;const 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 d=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=d,l.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return 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:_e("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(Ct,{className:"size-5"})})}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},fv=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},ga={all:["messages"],detail:e=>[...ga.all,"detail",e],body:e=>[...ga.detail(e),"body"]};class as 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 mv=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},hv=8,pv="x-remit-403-reason",gv=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},xv=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,bv=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},vv=async(e,t,s=async()=>null)=>{const n={},a=await s();a&&(n.Authorization=`Bearer ${a}`);const o=await Hf(e,{headers:n});if(o.status===202)throw new as("not-ready","Message body is still syncing",202,mv(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(pv),m=gv(o.status,u);throw new as(m,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(bv(t,i))throw new as("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(xv(l,i))throw new as("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},yv=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),wu=({messageId:e,bodyParts:t,enabled:s=!0})=>{const n=t?fv(t):null,a=pn(),{getToken:o}=$a(),i=c.useRef(null),l=Me(),u=c.useRef(!1),m=c.useRef(null),f=e&&n?`${e}:${n.contentUrl}`:null;m.current!==f&&(m.current=f,u.current=!1);const d=be({queryKey:e?[...ga.body(e),n?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!n)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const g=u.current;return u.current=!1,yv({fetchContent:(p,y)=>vv(p,y,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:$l({path:{messageId:e}})})},{contentUrl:n.contentUrl,kind:n.kind,isRetryAfterNotReady:g})},enabled:s&&!!e&&!!n,staleTime:300*1e3,gcTime:1800*1e3,retry:(g,p)=>p instanceof as&&p.reason==="not-ready"?g<hv:g<1,retryDelay:(g,p)=>p instanceof as&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=d.isLoading&&!!n;c.useEffect(()=>{h&&(i.current=performance.now())},[h]),c.useEffect(()=>{d.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[d.isSuccess,a]);const v=d.data&&n?{kind:n.kind,body:d.data}:void 0;return{picked:n,data:v,isLoading:h,isError:d.isError,error:d.error,refetch:d.refetch}},wv=({outboxMessageId:e,onDraftCreated:t})=>{const[s,n]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=Me(),u=Fe(_l()),m=Fe(Wf()),f=c.useCallback(async g=>{if(n("saving"),o(null),e){const y=await m.mutateAsync({path:{outboxMessageId:e},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"),y}const p=await u.mutateAsync({body:{...g,sendImmediately:!1}});return t(p.outboxMessageId),n("saved"),l.invalidateQueries({queryKey:er().queryKey}),p},[e,u,m,t,l]),d=c.useCallback(g=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{f(g).catch(p=>{o(p),n("error")})},2e3)},[f]),h=c.useCallback(g=>(i.current&&clearTimeout(i.current),f(g)),[f]),v=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:d,saveImmediately:h,cancelAutoSave:v}},Su=e=>"text"in e&&!("children"in e),ku=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),Sv=e=>{let t=ku(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},Cu=e=>{const t=e.children.map(s=>Su(s)?Sv(s):Cu(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${ku(s)}">${t}</a>`}default:return`<p>${t}</p>`}},Gi=e=>e.map(Cu).join(""),ju=e=>Su(e)?e.text:e.children.map(ju).join(""),xa=e=>e.map(ju).join(`
116
+ `),kv=["Tab",","],Yi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),Cv=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(Yi(a))return{email:a,displayName:n}}if(Yi(t))return{email:t}},Vr=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=c.useState(""),i=c.useRef(null),l=ir(a,200),{data:u}=be({...tr({query:{q:l,limit:8}}),enabled:l.length>=2}),m=u?.items??[],f=new Set(t.map(x=>x.email.toLowerCase())),d=a.length>=2?m.filter(x=>!f.has(x.normalizedEmail.toLowerCase())):[],h=c.useCallback(x=>{f.has(x.email.toLowerCase())||(s([...t,x]),o(""))},[t,f,s]),v=c.useCallback(x=>{s(t.filter((k,M)=>M!==x))},[t,s]),g=c.useCallback(x=>{h({email:x.normalizedEmail,displayName:x.displayName}),i.current?.focus()},[h]),p=c.useCallback(()=>{const x=Cv(a);x&&h(x)},[a,h]),y=zl({count:d.length,acceptKeys:kv,onAccept:x=>g(d[x])}),b=c.useMemo(()=>d.map(x=>({value:x.normalizedEmail,label:x.displayName??x.normalizedEmail,...x.displayName?{hint:x.normalizedEmail}:{}})),[d]),S=c.useCallback(x=>{if(x.key==="Backspace"&&a===""&&t.length>0){v(t.length-1);return}y.handleKeyDown(x)||(x.key==="Enter"||x.key==="Tab"||x.key===",")&&a.trim()&&(x.preventDefault(),p())},[a,t.length,v,y.handleKeyDown,p]),w=c.useCallback(()=>{setTimeout(()=>{p(),y.dismiss()},150)},[p,y.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:()=>i.current?.focus(),onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&i.current?.focus()},children:[t.map((x,k)=>r.jsx(qh,{email:x.email,displayName:x.displayName,onRemove:()=>v(k)},x.email)),r.jsx("input",{ref:i,id:`address-field-${e}`,type:"text",value:a,onChange:x=>{y.reopen(),o(x.target.value)},onKeyDown:S,onBlur:w,placeholder:t.length===0?n:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5",autoComplete:"off",...y.comboboxProps})]})]}),y.open&&r.jsx(Bl,{id:y.listId,suggestions:b,activeIndex:y.activeIndex,optionId:y.optionId,onPick:x=>{const k=d.find(M=>M.normalizedEmail===x.value);k&&g(k)},onHighlight:y.setActiveIndex,label:`${e} suggestions`,className:"absolute left-12 right-0 z-50 mt-1 max-h-[200px] shadow-lg"})]})},jv=({accountId:e})=>{const t=Ke();return 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(Aa,{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:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",r.jsx(Vf,{className:"size-3","aria-hidden":"true"})]})]})]})},Xi=150,Nv=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>Xi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>Xi})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},Ev=({selectedAccountId:e,onSelect:t})=>{const{data:s}=be({...Mt(),staleTime:1/0}),n=s?.accounts??[];if(c.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))})]})},Iv=({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})]}),Tv=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],Rv=["href"],Mv=e=>Rl.sanitize(e,{ALLOWED_TAGS:Tv,ALLOWED_ATTR:Rv}),Av=c.lazy(()=>Gf(()=>import("./ComposeBody-CQDryHHT.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.ComposeBody}))),Ov=()=>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"})]}),Nu=[{type:"p",children:[{text:""}]}],Pv=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],Dv=e=>e?[...Pv,{type:"p",children:[{text:e}]}]:Nu,Lv=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",Fv=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",$v=(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(),l=new Set(o.map(m=>m.email.toLowerCase())),u=[...n.to,...n.cc].filter(m=>m.normalizedEmail.toLowerCase()!==i&&!l.has(m.normalizedEmail.toLowerCase())).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));return{to:o,cc:u}},_v=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}},zv=(e,t,s,n,a)=>e.length===0&&t.length===0&&s.length===0&&n.trim()===""&&xa(a).trim()==="",Bv=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:n,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:m,showBcc:f,setShowBcc:d,subject:h,setSubject:v})=>{const g=Xt(),{isKeyboardOpen:p}=Nv();if(!g&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(S=>S.displayName??S.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.push(h),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:b.length>0?b.join(" · "):"…"}),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:"…"})]})}return r.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[r.jsx(Ev,{selectedAccountId:e,onSelect:t}),r.jsx(Vr,{label:"To",addresses:s,onChange:n,placeholder:"Recipients"}),u?r.jsx(Vr,{label:"Cc",addresses:a,onChange:o}):r.jsxs("div",{className:"flex gap-2 pl-14",children:[r.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),r.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!f&&r.jsx("div",{className:"pl-14",children:r.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),f&&r.jsx(Vr,{label:"Bcc",addresses:i,onChange:l}),r.jsx(Iv,{value:h,onChange:v})]})},go=({mode:e,account:t,sourceMessage:s,onClose:n,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Yt(),{pushError:u}=st(),{outboxMessageId:m}=o,[f,d]=c.useState([]),[h,v]=c.useState([]),[g,p]=c.useState([]),[y,b]=c.useState(""),[S,w]=c.useState(!1),[x,k]=c.useState(!1),[M,O]=c.useState(t?.accountId),[j,R]=c.useState(!1),P=c.useRef(m);c.useEffect(()=>{P.current!==m&&(P.current=m,m&&(d([]),v([]),p([]),b(""),w(!1),k(!1),D(Nu),R(!1)))},[m]);const{signature:E}=$m(M),[L,D]=c.useState(()=>Dv(E.plainText)),{data:C}=be({...Qf({path:{outboxMessageId:m??""}}),enabled:!!m&&!j});c.useEffect(()=>{!C||j||(d(C.toAddresses.map(H=>({email:H,displayName:void 0}))),C.ccAddresses&&C.ccAddresses.length>0&&(v(C.ccAddresses.map(H=>({email:H,displayName:void 0}))),w(!0)),C.bccAddresses&&C.bccAddresses.length>0&&(p(C.bccAddresses.map(H=>({email:H,displayName:void 0}))),k(!0)),C.subject&&b(C.subject),C.textBody&&D([{type:"p",children:[{text:C.textBody}]}]),O(C.accountId),R(!0))},[C,j]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:H,cc:ie}=$v(s,e,t?.email);d(H),v(ie),ie.length>0&&w(!0),b(Lv(s.envelope.subject))}e==="forward"&&b(Fv(s.envelope.subject))}},[e,s,t?.email]);const T=e==="reply"||e==="reply_all"||e==="forward",{data:A}=wu({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:T&&!!s}),I=A?.kind==="text"?A.body:"",F=A?.kind==="html"?Mv(A.body):void 0,N=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:q,saveError:Q,saveDraft:ae,cancelAutoSave:U}=wv({outboxMessageId:m,onDraftCreated:i});c.useEffect(()=>{Q&&u({title:"Couldn't save draft",detail:mt(Q)??"Saving the draft failed.",error:Q})},[Q,u]);const z=Fe(_l()),ee=Fe(Kl()),me=Fe({...sr(),onError:H=>{u(is("Couldn't discard draft","The draft wasn't discarded.",H))}}),{data:fe}=be({...Mt(),staleTime:1/0}),se=fe?.accounts.find(H=>H.accountId===M),W=se?Lm(se):!1,pe=z.isPending||ee.isPending,ve=f.length>0&&!!M&&!W;c.useEffect(()=>{if(!M||m&&!j||zv(f,h,g,y,L))return;const H=xa(L),ie=Gi(L);ae({accountId:M,toAddresses:f.map(ge=>ge.email),ccAddresses:h.length>0?h.map(ge=>ge.email):void 0,bccAddresses:g.length>0?g.map(ge=>ge.email):void 0,subject:y||void 0,textBody:H||void 0,htmlBody:ie||void 0})},[M,m,j,f,h,g,y,L,ae]);const Ne=c.useCallback(async()=>{if(!M||f.length===0)return;U();const H=s&&(e==="reply"||e==="reply_all")?_v(s):{};let ie=m,ge=!1;if(!ie){const xe=xa(L),B=Gi(L),ue=await z.mutateAsync({body:{accountId:M,toAddresses:f.map(oe=>oe.email),ccAddresses:h.length>0?h.map(oe=>oe.email):void 0,bccAddresses:g.length>0?g.map(oe=>oe.email):void 0,subject:y||void 0,textBody:xe||void 0,htmlBody:B||void 0,sendImmediately:!0,...H}}).catch(oe=>(u({title:"Couldn't send message",detail:mt(oe)??"Saving the draft failed.",error:oe}),null));if(ue===null)return;ie=ue.outboxMessageId,ge=!0,i(ie)}await ee.mutateAsync({path:{outboxMessageId:ie}}).catch(xe=>(u({title:"Couldn't send message",detail:mt(xe)??(ge?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:xe}),null))!==null&&(l(ie),n())},[M,f,h,g,y,L,e,s,m,z,ee,U,l,i,u,n]),we=c.useCallback(()=>{U(),m&&me.mutate({path:{outboxMessageId:m}}),n()},[U,m,me,n]),X=c.useCallback(H=>{O(H.accountId),a?.(H)},[a]);return r.jsx(lg,{banner:se&&W?r.jsx(jv,{accountId:se.accountId}):void 0,header:r.jsx(Bv,{selectedAccountId:M,onAccountChange:X,toAddresses:f,setToAddresses:d,ccAddresses:h,setCcAddresses:v,bccAddresses:g,setBccAddresses:p,showCc:S,setShowCc:w,showBcc:x,setShowBcc:k,subject:y,setSubject:b}),quoted:I||F?r.jsx(Ig,{text:I,html:F,senderName:N}):void 0,actionBar:r.jsx(ig,{onSend:Ne,onDiscard:we,sending:pe,canSend:ve,saveStatus:q,unavailableReason:W?"SMTP not configured":void 0,onUnavailable:H=>u({title:"Can't send yet",detail:H})}),children:r.jsx(c.Suspense,{fallback:r.jsx(Ov,{}),children:r.jsx(Av,{value:L,onChange:D,onSubmit:Ne,autoFocus:e==="new"})})})},Ji=({mode:e,account:t,sourceMessage:s,onClose:n})=>r.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:r.jsx(go,{mode:e,account:t,sourceMessage:s,onClose:n})}),Eu=({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})]}),xo=({enabled:e=!0,bindings:t,capture:s=!1})=>{const n=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const m=i.noModifiers??!0,f=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(m&&f)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",n,s),()=>window.removeEventListener("keydown",n,s)},[e,n,s])},bo=e=>{const{data:t,isLoading:s}=be({...Mt(),staleTime:1/0}),n=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=pt({queries:n.map(l=>({...it({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<n.length;l++)if((a[l].data?.items??[]).some(f=>f.mailboxId===e))return n[l]}},[e,n,a]),isLoading:o}},Kv=100,ba=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),Uv=(e,t=Kv)=>{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},Iu=async(e,t,s,n)=>{const a=Uv(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(n())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const m=a[u],f=await ba(t(m));if(!f.ok)return l.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:l,cancelled:!1,error:f.error};i+=m.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},br=async(e,t)=>{await Iu(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},qv=async(e,t,s,n,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await ba(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const m=u.value;if(m.ids.length>0){const f=await ba(s(m.ids));if(!f.ok)return{done:o,failedIds:i,cancelled:!1,error:f.error};o+=m.ids.length,n({done:o,total:t})}l=m.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},Hv=e=>({done:e.done,total:Math.max(e.total,e.done)}),Tu=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),Ru=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Mu=(e,t)=>e===void 0?e:Tu(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:Ru(e)?{...e,items:t(e.items)}:e,Ot=e=>{const t=[];for(const s of new Set(e))t.push(nr({path:{mailboxId:s}})),t.push(Ba({path:{mailboxId:s}}));return t.push(Ka()),t},bn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),vn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,n])=>({queryKey:s,data:n})),yn=(e,t,s)=>{const n=a=>Mu(a,s);for(const a of t)e.setQueriesData({queryKey:a},n)},wn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},Pt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Wv=3e3,Vv=(e,t,s)=>{if(e.length===0)return()=>{};const n=setTimeout(()=>s(e),t);return()=>clearTimeout(n)},vr=(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]},Vn=(e,t,s)=>e.map(n=>t.has(n.messageId)?{...n,isRead:s}:n),Qv=(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),Gv=({messages:e,expandedIds:t,threadId:s,mailboxId:n,accountId:a})=>{const o=Me(),{pushError:i}=st(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:m}=Fe({...rr(),onMutate:async h=>{const v=new Set(h.body.messageIds??[]),g=h.body.isRead??!0,p=hs({path:{threadId:s}}),y=Ot(vr(v,e,n));await Promise.all([o.cancelQueries({queryKey:p}),bn(o,y)]);const b=o.getQueriesData({queryKey:p}).filter(w=>w[1]!==void 0).map(([w,x])=>({queryKey:w,data:x})),S=vn(o,y);return o.setQueriesData({queryKey:p},w=>w&&{...w,items:Vn(w.items,v,g)}),yn(o,y,w=>Vn(w,v,g)),{threadMessagesPrefix:p,listPrefixes:y,previousThreadMessages:b,previousThreadsList:S}},onSuccess:(h,v)=>{const g=v.body.messageIds??[];for(const p of g)l.current.add(p),u.current.delete(p)},onError:(h,v,g)=>{const p=v.body.messageIds??[];for(const b of p)u.current.delete(b);if(g){for(const b of g.previousThreadMessages)o.setQueryData(b.queryKey,b.data);wn(o,g.previousThreadsList)}const y=v.body.isRead??!0;i({title:y?"Couldn't mark as read":"Couldn't mark as unread",detail:mt(h),error:h})},onSettled:(h,v,g,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),Pt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:ms({path:{accountId:a}})}))}}),f=c.useCallback(h=>{const v=h.filter(g=>!l.current.has(g)&&!u.current.has(g));if(v.length!==0){for(const g of v)u.current.add(g);m({body:{messageIds:v,isRead:!0}})}},[m]),d=c.useMemo(()=>Qv(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Vv(d,Wv,f),[d,f]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},yr=e=>{const{mailboxId:t,accountId:s,messages:n}=e,a=Me(),{pushError:o}=st(),{mutateAsync:i,isPending:l}=Fe({...rr(),onError:(m,f)=>{const d=f.body.isRead??!0;o({title:d?"Couldn't mark as read":"Couldn't mark as unread",detail:mt(m),error:m})},onSettled:(m,f,d)=>{Pt(a,Ot(vr(d.body.messageIds??[],n??[],t))),s&&a.invalidateQueries({queryKey:ms({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((m,f)=>{m.length!==0&&br(m,d=>i({body:{messageIds:d,isRead:f}}))},[i]),isPending:l}},Yv=60,Xv=1.5,Jv=(e,t,s)=>{const n=Math.abs(e),a=Math.abs(t);return n<s?{direction:null}:n<a*Xv?{direction:null}:{direction:e<0?"left":"right"}},Zv=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Yv})=>{const n=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){n.current=null;return}n.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const m=n.current;if(n.current=null,!m)return;const{direction:f}=Jv(u.clientX-m.x,u.clientY-m.y,s);f==="left"&&e?.(),f==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{n.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},ey=(e,t,s)=>t?.find(n=>n.messageId===e)?.mailboxId??s,Zi=(e,t,s)=>e.map(n=>n.messageId===t?{...n,hasStars:s}:n),vo=({threadId:e,mailboxId:t,messages:s})=>{const n=Me(),{pushError:a}=st(),{mutate:o,isPending:i,variables:l}=Fe({...Yf(),onMutate:async m=>{const f=m.path.messageId,d=m.body.isStarred??!1,h=hs({path:{threadId:e}}),v=Ot([ey(f,s,t)]);await Promise.all([n.cancelQueries({queryKey:h}),bn(n,v)]);const g=n.getQueriesData({queryKey:h}).filter(y=>y[1]!==void 0).map(([y,b])=>({queryKey:y,data:b})),p=vn(n,v);return n.setQueriesData({queryKey:h},y=>Mu(y,b=>Zi(b,f,d))),yn(n,v,y=>Zi(y,f,d)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:g,previousThreadsList:p}},onError:(m,f,d)=>{if(d){for(const v of d.previousThreadMessages)n.setQueryData(v.queryKey,v.data);wn(n,d.previousThreadsList)}const h=f.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:mt(m),error:m})},onSettled:(m,f,d,h)=>{h&&(n.invalidateQueries({queryKey:h.threadMessagesPrefix}),Pt(n,h.listPrefixes))}});return{toggleStar:(m,f)=>{o({path:{messageId:m},body:{isStarred:!f}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function wr(e){return e===void 0?"uncategorized":e}const ty={inbox:"Inbox",junk:"Junk"},yo=e=>e.destinationMailboxId!==void 0,sy=(e,t)=>{if(yo(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${ty[s]??"another folder"} by Remit`},ny=(e,t)=>{if(e===Qo.MoveToInbox)return t.inboxMailboxId;if(e===Qo.MoveToJunk)return t.junkMailboxId},ry=(e,t,s)=>{if(!e||!t)return!1;const n=yo(e)?e.destinationMailboxId:ny(e.action,s);return n!==void 0&&n===t},ay=(e,t)=>{if(e){if(yo(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},Sr=(e,t)=>{const{data:s,isLoading:n}=be({...Mt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:n}},oy=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},iy=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},wo=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},_s=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Junk");return{junkMailboxId:t,isLoading:s}},So=e=>{const{data:t}=be({...Mt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},el=(e,t)=>e.filter(s=>!t.has(s.messageId)),cs=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=Me(),{pushError:o}=st(),{mutateAsync:i,isPending:l}=Fe({...Xf(),onMutate:async m=>{const f=new Set(m.body.messageIds??[]),d=t?hs({path:{threadId:t}}):[],h=Ot([e,m.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:d})]:[],bn(a,h)]);const v=t?a.getQueriesData({queryKey:d}).filter(p=>p[1]!==void 0).map(([p,y])=>({queryKey:p,data:y})):[],g=vn(a,h);return t&&a.setQueriesData({queryKey:d},p=>p&&{...p,items:el(p.items,f)}),yn(a,h,p=>el(p,f)),n?.(Array.from(f)),{threadMessagesPrefix:d,listPrefixes:h,previousThreadMessages:v,previousThreadsList:g}},onError:(m,f,d)=>{if(d){for(const v of d.previousThreadMessages)a.setQueryData(v.queryKey,v.data);wn(a,d.previousThreadsList)}const h=f.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:mt(m),error:m})},onSettled:(m,f,d,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),Pt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:ms({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((m,f)=>{m.length!==0&&br(m,d=>i({body:{messageIds:d,destinationMailboxId:f}}))},[i]),isPending:l}},ly=({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a})=>{const{inboxMailboxId:o}=wo(e),{junkMailboxId:i}=_s(e),{moveMessages:l,isPending:u}=cs({mailboxId:n,threadId:s,accountId:e}),{data:m}=be({...it({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),f={inboxMailboxId:o,junkMailboxId:i},d=ry(a,n,f),h=ay(a,f),v=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!d||!a)return{show:!1,label:"",isUndoing:!1};const g=a.fromMailboxId?m?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>aa(p.fullPath))[0]:void 0;return{show:!0,label:sy(a,g),onUndo:h?v:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function cy({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a}){const o=ly({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a});return o.show?r.jsx(sg,{label:o.label,onUndo:o.onUndo,undoLabel:o.isUndoing?"Undoing…":"Undo",filtersHref:o.filtersHref}):null}const tl=(e,t)=>e.filter(s=>!t.has(s.messageId)),uy=e=>e.filter(t=>t.isDeleted!==!0),us=({mailboxId:e,threadId:t,accountId:s,messages:n,onAfterOptimisticRemove:a})=>{const o=Me(),{pushError:i}=st(),{mutateAsync:l,isPending:u}=Fe({...Jf(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),h=t?hs({path:{threadId:t}}):[],v=Ot(vr(d,n??[],e));await Promise.all([o.cancelQueries({queryKey:h}),bn(o,v)]);const g=t?o.getQueriesData({queryKey:h}).filter(y=>y[1]!==void 0).map(([y,b])=>({queryKey:y,data:b})):[],p=vn(o,v);return t&&o.setQueriesData({queryKey:h},y=>y&&{...y,items:tl(y.items,d)}),yn(o,v,y=>tl(y,d)),a?.(Array.from(d)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:g,previousThreadsList:p}},onError:(f,d,h)=>{if(h){for(const g of h.previousThreadMessages)o.setQueryData(g.queryKey,g.data);wn(o,h.previousThreadsList)}const v=d.body.messageIds?.length??0;i({title:v>1?`Couldn't delete ${v} messages`:"Couldn't delete this message",detail:mt(f),error:f})},onSettled:(f,d,h,v)=>{v&&(t&&o.invalidateQueries({queryKey:v.threadMessagesPrefix}),Pt(o,v.listPrefixes),s&&o.invalidateQueries({queryKey:ms({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(f=>{f.length!==0&&br(f,d=>l({body:{messageIds:d}}))},[l]),isPending:u}},Au=(e,t=Date.now())=>({value:e,setAt:t}),dy=(e,t,s,n)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Au(!0,n):delete a.trusted,{...e,flags:a}},fy=(e,t,s,n)=>{const a=o=>o.map(i=>dy(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)}}},ko=({messageId:e})=>{const t=Me(),{pushError:s}=st(),{mutate:n,isPending:a,error:o,reset:i}=Fe({...Ul(),onMutate:async u=>{const m=u.path.addressId,d=u.body.flags?.trusted?.value===!0,h=$l({path:{messageId:e}});await t.cancelQueries({queryKey:h});const v=t.getQueriesData({queryKey:h}).filter(g=>g[1]!==void 0).map(([g,p])=>({queryKey:g,data:p}));return t.setQueriesData({queryKey:h},g=>g&&fy(g,m,d)),{describePrefix:h,previous:v}},onError:(u,m,f)=>{if(f)for(const d of f.previous)t.setQueryData(d.queryKey,d.data);s(is("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,m,f,d)=>{d&&t.invalidateQueries({queryKey:d.describePrefix})}});return{toggleTrusted:(u,m)=>{n({path:{addressId:u},body:{flags:{trusted:Au(!m)}}})},isPending:a,error:o,reset:i}};var kr="Dialog",[Ou]=wx(kr),[my,gt]=Ou(kr),Pu=e=>{const{__scopeDialog:t,children:s,open:n,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[m,f]=Cx({prop:n,defaultProp:a??!1,onChange:o,caller:kr});return r.jsx(my,{scope:t,triggerRef:l,contentRef:u,contentId:Kr(),titleId:Kr(),descriptionId:Kr(),open:m,onOpenChange:f,onOpenToggle:c.useCallback(()=>f(d=>!d),[f]),modal:i,children:s})};Pu.displayName=kr;var Du="DialogTrigger",hy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(Du,s),o=ps(t,a.triggerRef);return r.jsx(At.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":jo(a.open),...n,ref:o,onClick:Ht(e.onClick,a.onOpenToggle)})});hy.displayName=Du;var Co="DialogPortal",[py,Lu]=Ou(Co,{forceMount:void 0}),Fu=e=>{const{__scopeDialog:t,forceMount:s,children:n,container:a}=e,o=gt(Co,t);return r.jsx(py,{scope:t,forceMount:s,children:c.Children.map(n,i=>r.jsx(hr,{present:s||o.open,children:r.jsx(Yc,{asChild:!0,container:a,children:i})}))})};Fu.displayName=Co;var Qn="DialogOverlay",$u=c.forwardRef((e,t)=>{const s=Lu(Qn,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=gt(Qn,e.__scopeDialog);return o.modal?r.jsx(hr,{present:n||o.open,children:r.jsx(xy,{...a,ref:t})}):null});$u.displayName=Qn;var gy=uo("DialogOverlay.RemoveScroll"),xy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(Qn,s),o=Ux(),i=ps(t,o);return r.jsx(ru,{as:gy,allowPinchZoom:!0,shards:[a.contentRef],children:r.jsx(At.div,{"data-state":jo(a.open),...n,ref:i,style:{pointerEvents:"auto",...n.style}})})}),Os="DialogContent",_u=c.forwardRef((e,t)=>{const s=Lu(Os,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=gt(Os,e.__scopeDialog);return r.jsx(hr,{present:n||o.open,children:o.modal?r.jsx(by,{...a,ref:t}):r.jsx(vy,{...a,ref:t})})});_u.displayName=Os;var by=c.forwardRef((e,t)=>{const s=gt(Os,e.__scopeDialog),n=c.useRef(null),a=ps(t,s.contentRef,n);return c.useEffect(()=>{const o=n.current;if(o)return db(o)},[]),r.jsx(zu,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Ht(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Ht(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Ht(e.onFocusOutside,o=>o.preventDefault())})}),vy=c.forwardRef((e,t)=>{const s=gt(Os,e.__scopeDialog),n=c.useRef(!1),a=c.useRef(!1);return r.jsx(zu,{...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()}})}),zu=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=gt(Os,s);return Vx(),r.jsx(r.Fragment,{children:r.jsx(Qc,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:r.jsx(Wc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":jo(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),Bu="DialogTitle",Ku=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(Bu,s);return r.jsx(At.h2,{id:a.titleId,...n,ref:t})});Ku.displayName=Bu;var Uu="DialogDescription",yy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(Uu,s);return r.jsx(At.p,{id:a.descriptionId,...n,ref:t})});yy.displayName=Uu;var qu="DialogClose",wy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=gt(qu,s);return r.jsx(At.button,{type:"button",...n,ref:t,onClick:Ht(e.onClick,()=>a.onOpenChange(!1))})});wy.displayName=qu;function jo(e){return e?"open":"closed"}function Sy(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}const Hu=K.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}),Sn=()=>{const e=K.useContext(Hu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};Sy(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
117
117
  [data-state=closed]
118
- ){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function Sy(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function ky(){return Io(/^Mac/)}function jy(){return Io(/^iPhone/)}function ol(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Cy(){return Io(/^iPad/)||ky()&&navigator.maxTouchPoints>1}function Wu(){return jy()||Cy()}function Io(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const Ny=24,Ey=typeof window<"u"?c.useLayoutEffect:c.useEffect;function il(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const Qr=typeof document<"u"&&window.visualViewport;function ll(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Vu(e){for(ll(e)&&(e=e.parentElement);e&&!ll(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Iy=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let An=0,Gr;function Ty(e={}){let{isDisabled:t}=e;Ey(()=>{if(!t)return An++,An===1&&Wu()&&(Gr=Ry()),()=>{An--,An===0&&Gr?.()}},[t])}function Ry(){let e,t=0,s=d=>{e=Vu(d.target),!(e===document.documentElement&&e===document.body)&&(t=d.changedTouches[0].pageY)},n=d=>{if(!e||e===document.documentElement||e===document.body){d.preventDefault();return}let h=d.changedTouches[0].pageY,v=e.scrollTop,g=e.scrollHeight-e.clientHeight;g!==0&&((v<=0&&h>t||v>=g&&h<t)&&d.preventDefault(),t=h)},a=d=>{let h=d.target;va(h)&&h!==document.activeElement&&(d.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=d=>{let h=d.target;va(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",Qr&&(Qr.height<window.innerHeight?requestAnimationFrame(()=>{cl(h)}):Qr.addEventListener("resize",()=>cl(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,m=il(My(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let f=il(Gs(document,"touchstart",s,{passive:!1,capture:!0}),Gs(document,"touchmove",n,{passive:!1,capture:!0}),Gs(document,"touchend",a,{passive:!1,capture:!0}),Gs(document,"focus",o,!0),Gs(window,"scroll",i));return()=>{m(),f(),window.scrollTo(l,u)}}function My(e,t,s){let n=e.style[t];return e.style[t]=s,()=>{e.style[t]=n}}function Gs(e,t,s,n){return e.addEventListener(t,s,n),()=>{e.removeEventListener(t,s,n)}}function cl(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=Vu(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+Ny;o>i&&(s.scrollTop+=a-n)}e=s.parentElement}}function va(e){return e instanceof HTMLInputElement&&!Iy.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function Ay(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function Oy(...e){return t=>e.forEach(s=>Ay(s,t))}function Qu(...e){return c.useCallback(Oy(...e),e)}const Gu=new WeakMap;function Be(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&&Gu.set(e,n)}function Py(e,t){if(!e||!(e instanceof HTMLElement))return;let s=Gu.get(e);s&&(e.style[t]=s[t])}const $e=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function On(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(", ")[$e(t)?13:12]):(a=n.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[$e(t)?5:4]):null)}function Dy(e){return 8*(Math.log(e+1)-2)}function Yr(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function Ly(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const Re={DURATION:.5,EASE:[.32,.72,0,1]},Yu=.4,Fy=.25,$y=100,Xu=8,rs=16,ya=26,Xr="vaul-dragging";function Ju(e){const t=K.useRef(e);return K.useEffect(()=>{t.current=e}),K.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function _y({defaultProp:e,onChange:t}){const s=K.useState(e),[n]=s,a=K.useRef(n),o=Ju(t);return K.useEffect(()=>{a.current!==n&&(o(n),a.current=n)},[n,a,o]),s}function Zu({prop:e,defaultProp:t,onChange:s=()=>{}}){const[n,a]=_y({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:n,l=Ju(s),u=K.useCallback(m=>{if(o){const d=typeof m=="function"?m(e):m;d!==e&&l(d)}else a(m)},[o,e,a,l]);return[i,u]}function zy({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:n,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:m}){const[f,d]=Zu({prop:e,defaultProp:s?.[0],onChange:t}),[h,v]=K.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);K.useEffect(()=>{function O(){v({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]);const g=K.useMemo(()=>f===s?.[s.length-1]||null,[s,f]),p=K.useMemo(()=>{var O;return(O=s?.findIndex(C=>C===f))!=null?O:null},[s,f]),y=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===f||!s,b=K.useMemo(()=>{const O=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var C;return(C=s?.map(R=>{const P=typeof R=="string";let E=0;if(P&&(E=parseInt(R,10)),$e(l)){const D=P?E:h?R*O.height:0;return h?l==="bottom"?O.height-D:-O.height+D:D}const L=P?E:h?R*O.width:0;return h?l==="right"?O.width-L:-O.width+L:L}))!=null?C:[]},[s,h,u]),S=K.useMemo(()=>p!==null?b?.[p]:null,[b,p]),w=K.useCallback(O=>{var C;const R=(C=b?.findIndex(P=>P===O))!=null?C:null;i(R),Be(n.current,{transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,transform:$e(l)?`translate3d(0, ${O}px, 0)`:`translate3d(${O}px, 0, 0)`}),b&&R!==b.length-1&&o!==void 0&&R!==o&&R<o?Be(a.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,opacity:"0"}):Be(a.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,opacity:"1"}),d(s?.[Math.max(R,0)])},[n.current,s,b,o,a,d]);K.useEffect(()=>{if(f||e){var O;const C=(O=s?.findIndex(R=>R===e||R===f))!=null?O:-1;b&&C!==-1&&typeof b[C]=="number"&&w(b[C])}},[f,e,s,b,w]);function x({draggedDistance:O,closeDrawer:C,velocity:R,dismissible:P}){if(o===void 0)return;const E=l==="bottom"||l==="right"?(S??0)-O:(S??0)+O,L=p===o-1,D=p===0,j=O>0;if(L&&Be(a.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`}),!m&&R>2&&!j){P?C():w(b[0]);return}if(!m&&R>2&&j&&b&&s){w(b[s.length-1]);return}const T=b?.reduce((I,F)=>typeof I!="number"||typeof F!="number"?I:Math.abs(F-E)<Math.abs(I-E)?F:I),A=$e(l)?window.innerHeight:window.innerWidth;if(R>Yu&&Math.abs(O)<A*.4){const I=j?1:-1;if(I>0&&g&&s){w(b[s.length-1]);return}if(D&&I<0&&P&&C(),p===null)return;w(b[p+I]);return}w(T)}function k({draggedDistance:O}){if(S===null)return;const C=l==="bottom"||l==="right"?S-O:S+O;(l==="bottom"||l==="right")&&C<b[b.length-1]||(l==="top"||l==="left")&&C>b[b.length-1]||Be(n.current,{transform:$e(l)?`translate3d(0, ${C}px, 0)`:`translate3d(${C}px, 0, 0)`})}function M(O,C){if(!s||typeof p!="number"||!b||o===void 0)return null;const R=p===o-1;if(p>=o&&C)return 0;if(R&&!C)return 1;if(!y&&!R)return null;const E=R?p+1:p-1,L=R?b[E]-b[E-1]:b[E+1]-b[E],D=O/Math.abs(L);return R?1-D:D}return{isLastSnapPoint:g,activeSnapPoint:f,shouldFade:y,getPercentageDragged:M,setActiveSnapPoint:d,activeSnapPointIndex:p,onRelease:x,onDrag:k,snapPointsOffset:b}}const By=()=>()=>{};function Ky(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:n,noBodyStyles:a}=Sn(),o=K.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-ya)/window.innerWidth}K.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;Ly(n&&!a?Yr(document.body,{background:"black"}):By,Yr(u,{transformOrigin:$e(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Re.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Re.EASE.join(",")})`}));const m=Yr(u,{borderRadius:`${Xu}px`,overflow:"hidden",...$e(e)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{m(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},Re.DURATION*1e3)}}},[t,s,i])}let Ys=null;function Uy({isOpen:e,modal:t,nested:s,hasBeenOpened:n,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=K.useState(()=>typeof window<"u"?window.location.href:""),u=K.useRef(0),m=K.useCallback(()=>{if(ol()&&Ys===null&&e&&!o){Ys={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:d,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-d}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]),f=K.useCallback(()=>{if(ol()&&Ys!==null&&!o){const d=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Ys),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,d)}),Ys=null}},[i]);return K.useEffect(()=>{function d(){u.current=window.scrollY}return d(),window.addEventListener("scroll",d),()=>{window.removeEventListener("scroll",d)}},[]),K.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||f()}},[t,f]),K.useEffect(()=>{s||!n||(e?(!window.matchMedia("(display-mode: standalone)").matches&&m(),t||window.setTimeout(()=>{f()},500)):f())},[e,n,i,t,s,m,f]),{restorePositionSetting:f}}function qy({open:e,onOpenChange:t,children:s,onDrag:n,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=Fy,scrollLockTimeout:m=$y,dismissible:f=!0,handleOnly:d=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:v,setActiveSnapPoint:g,fixed:p,modal:y=!0,onClose:b,nested:S,noBodyStyles:w=!1,direction:x="bottom",defaultOpen:k=!1,disablePreventScroll:M=!0,snapToSequentialPoint:O=!1,preventScrollRestoration:C=!1,repositionInputs:R=!0,onAnimationEnd:P,container:E,autoFocus:L=!1}){var D,j;const[T=!1,A]=Zu({defaultProp:k,prop:e,onChange:G=>{t?.(G),!G&&!S&&Se(),setTimeout(()=>{P?.(G)},Re.DURATION*1e3),G&&!y&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),G||(document.body.style.pointerEvents="auto")}}),[I,F]=K.useState(!1),[N,q]=K.useState(!1),[Q,ae]=K.useState(!1),U=K.useRef(null),z=K.useRef(null),ee=K.useRef(null),me=K.useRef(null),fe=K.useRef(null),se=K.useRef(!1),W=K.useRef(null),pe=K.useRef(0),ve=K.useRef(!1),Ne=K.useRef(!k),we=K.useRef(0),X=K.useRef(null),H=K.useRef(((D=X.current)==null?void 0:D.getBoundingClientRect().height)||0),ie=K.useRef(((j=X.current)==null?void 0:j.getBoundingClientRect().width)||0),ge=K.useRef(0),ze=K.useCallback(G=>{o&&G===ne.length-1&&(z.current=new Date)},[]),{activeSnapPoint:xe,activeSnapPointIndex:B,setActiveSnapPoint:ue,onRelease:oe,snapPointsOffset:ne,onDrag:nt,shouldFade:Te,getPercentageDragged:J}=zy({snapPoints:o,activeSnapPointProp:v,setActiveSnapPointProp:g,drawerRef:X,fadeFromIndex:h,overlayRef:U,onSnapPointChange:ze,direction:x,container:E,snapToSequentialPoint:O});Ty({isDisabled:!T||N||!y||Q||!I||!R||!M});const{restorePositionSetting:Se}=Uy({isOpen:T,modal:y,nested:S??!1,hasBeenOpened:I,preventScrollRestoration:C,noBodyStyles:w});function Ve(){return(window.innerWidth-ya)/window.innerWidth}function Oe(G){var te,ce;!f&&!o||X.current&&!X.current.contains(G.target)||(H.current=((te=X.current)==null?void 0:te.getBoundingClientRect().height)||0,ie.current=((ce=X.current)==null?void 0:ce.getBoundingClientRect().width)||0,q(!0),ee.current=new Date,Wu()&&window.addEventListener("touchend",()=>se.current=!1,{once:!0}),G.target.setPointerCapture(G.pointerId),pe.current=$e(x)?G.pageY:G.pageX)}function he(G,te){var ce;let de=G;const ke=(ce=window.getSelection())==null?void 0:ce.toString(),Ee=X.current?On(X.current,x):null,De=new Date;if(de.tagName==="SELECT"||de.hasAttribute("data-vaul-no-drag")||de.closest("[data-vaul-no-drag]"))return!1;if(x==="right"||x==="left")return!0;if(z.current&&De.getTime()-z.current.getTime()<500)return!1;if(Ee!==null&&(x==="bottom"?Ee>0:Ee<0))return!0;if(ke&&ke.length>0)return!1;if(fe.current&&De.getTime()-fe.current.getTime()<m&&Ee===0||te)return fe.current=De,!1;for(;de;){if(de.scrollHeight>de.clientHeight){if(de.scrollTop!==0)return fe.current=new Date,!1;if(de.getAttribute("role")==="dialog")return!0}de=de.parentNode}return!0}function lt(G){if(X.current&&N){const te=x==="bottom"||x==="right"?1:-1,ce=(pe.current-($e(x)?G.pageY:G.pageX))*te,de=ce>0,ke=o&&!f&&!de;if(ke&&B===0)return;const Ee=Math.abs(ce),De=document.querySelector("[data-vaul-drawer-wrapper]"),He=x==="bottom"||x==="top"?H.current:ie.current;let ye=Ee/He;const Qe=J(Ee,de);if(Qe!==null&&(ye=Qe),ke&&ye>=1||!se.current&&!he(G.target,de))return;if(X.current.classList.add(Xr),se.current=!0,Be(X.current,{transition:"none"}),Be(U.current,{transition:"none"}),o&&nt({draggedDistance:ce}),de&&!o){const Le=Dy(ce),et=Math.min(Le*-1,0)*te;Be(X.current,{transform:$e(x)?`translate3d(0, ${et}px, 0)`:`translate3d(${et}px, 0, 0)`});return}const Ge=1-ye;if((Te||h&&B===h-1)&&(n?.(G,ye),Be(U.current,{opacity:`${Ge}`,transition:"none"},!0)),De&&U.current&&i){const Le=Math.min(Ve()+ye*(1-Ve()),1),et=8-ye*8,Ye=Math.max(0,14-ye*14);Be(De,{borderRadius:`${et}px`,transform:$e(x)?`scale(${Le}) translate3d(0, ${Ye}px, 0)`:`scale(${Le}) translate3d(${Ye}px, 0, 0)`,transition:"none"},!0)}if(!o){const Le=Ee*te;Be(X.current,{transform:$e(x)?`translate3d(0, ${Le}px, 0)`:`translate3d(${Le}px, 0, 0)`})}}}K.useEffect(()=>{window.requestAnimationFrame(()=>{Ne.current=!0})},[]),K.useEffect(()=>{var G;function te(){if(!X.current||!R)return;const ce=document.activeElement;if(va(ce)||ve.current){var de;const ke=((de=window.visualViewport)==null?void 0:de.height)||0,Ee=window.innerHeight;let De=Ee-ke;const He=X.current.getBoundingClientRect().height||0,ye=He>Ee*.8;ge.current||(ge.current=He);const Qe=X.current.getBoundingClientRect().top;if(Math.abs(we.current-De)>60&&(ve.current=!ve.current),o&&o.length>0&&ne&&B){const Ge=ne[B]||0;De+=Ge}if(we.current=De,He>ke||ve.current){const Ge=X.current.getBoundingClientRect().height;let Le=Ge;Ge>ke&&(Le=ke-(ye?Qe:ya)),p?X.current.style.height=`${Ge-Math.max(De,0)}px`:X.current.style.height=`${Math.max(Le,ke-Qe)}px`}else Sy()||(X.current.style.height=`${ge.current}px`);o&&o.length>0&&!ve.current?X.current.style.bottom="0px":X.current.style.bottom=`${Math.max(De,0)}px`}}return(G=window.visualViewport)==null||G.addEventListener("resize",te),()=>{var ce;return(ce=window.visualViewport)==null?void 0:ce.removeEventListener("resize",te)}},[B,o,ne]);function Xe(G){Ue(),b?.(),G||A(!1),setTimeout(()=>{o&&ue(o[0])},Re.DURATION*1e3)}function Pe(){if(!X.current)return;const G=document.querySelector("[data-vaul-drawer-wrapper]"),te=On(X.current,x);Be(X.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`}),Be(U.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,opacity:"1"}),i&&te&&te>0&&T&&Be(G,{borderRadius:`${Xu}px`,overflow:"hidden",...$e(x)?{transform:`scale(${Ve()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${Ve()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${Re.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Re.EASE.join(",")})`},!0)}function Ue(){!N||!X.current||(X.current.classList.remove(Xr),se.current=!1,q(!1),me.current=new Date)}function qe(G){if(!N||!X.current)return;X.current.classList.remove(Xr),se.current=!1,q(!1),me.current=new Date;const te=On(X.current,x);if(!G||!he(G.target,!1)||!te||Number.isNaN(te)||ee.current===null)return;const ce=me.current.getTime()-ee.current.getTime(),de=pe.current-($e(x)?G.pageY:G.pageX),ke=Math.abs(de)/ce;if(ke>.05&&(ae(!0),setTimeout(()=>{ae(!1)},200)),o){oe({draggedDistance:de*(x==="bottom"||x==="right"?1:-1),closeDrawer:Xe,velocity:ke,dismissible:f}),a?.(G,!0);return}if(x==="bottom"||x==="right"?de>0:de<0){Pe(),a?.(G,!0);return}if(ke>Yu){Xe(),a?.(G,!1);return}var Ee;const De=Math.min((Ee=X.current.getBoundingClientRect().height)!=null?Ee:0,window.innerHeight);var He;const ye=Math.min((He=X.current.getBoundingClientRect().width)!=null?He:0,window.innerWidth),Qe=x==="left"||x==="right";if(Math.abs(te)>=(Qe?ye:De)*u){Xe(),a?.(G,!1);return}a?.(G,!0),Pe()}K.useEffect(()=>(T&&(Be(document.documentElement,{scrollBehavior:"auto"}),z.current=new Date),()=>{Py(document.documentElement,"scrollBehavior")}),[T]);function Ze(G){const te=G?(window.innerWidth-rs)/window.innerWidth:1,ce=G?-rs:0;W.current&&window.clearTimeout(W.current),Be(X.current,{transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,transform:$e(x)?`scale(${te}) translate3d(0, ${ce}px, 0)`:`scale(${te}) translate3d(${ce}px, 0, 0)`}),!G&&X.current&&(W.current=setTimeout(()=>{const de=On(X.current,x);Be(X.current,{transition:"none",transform:$e(x)?`translate3d(0, ${de}px, 0)`:`translate3d(${de}px, 0, 0)`})},500))}function rt(G,te){if(te<0)return;const ce=(window.innerWidth-rs)/window.innerWidth,de=ce+te*(1-ce),ke=-rs+te*rs;Be(X.current,{transform:$e(x)?`scale(${de}) translate3d(0, ${ke}px, 0)`:`scale(${de}) translate3d(${ke}px, 0, 0)`,transition:"none"})}function je(G,te){const ce=$e(x)?window.innerHeight:window.innerWidth,de=te?(ce-rs)/ce:1,ke=te?-rs:0;te&&Be(X.current,{transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,transform:$e(x)?`scale(${de}) translate3d(0, ${ke}px, 0)`:`scale(${de}) translate3d(${ke}px, 0, 0)`})}return K.useEffect(()=>{y||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[y]),K.createElement(Pu,{defaultOpen:k,onOpenChange:G=>{!f&&!G||(G?F(!0):Xe(!0),A(G))},open:T},K.createElement(Hu.Provider,{value:{activeSnapPoint:xe,snapPoints:o,setActiveSnapPoint:ue,drawerRef:X,overlayRef:U,onOpenChange:t,onPress:Oe,onRelease:qe,onDrag:lt,dismissible:f,shouldAnimate:Ne,handleOnly:d,isOpen:T,isDragging:N,shouldFade:Te,closeDrawer:Xe,onNestedDrag:rt,onNestedOpenChange:Ze,onNestedRelease:je,keyboardIsOpen:ve,modal:y,snapPointsOffset:ne,activeSnapPointIndex:B,direction:x,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:w,container:E,autoFocus:L}},s))}const ed=K.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:n,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=Sn(),m=Qu(t,s),f=n&&n.length>0;if(!l)return null;const d=K.useCallback(h=>a(h),[a]);return K.createElement($u,{onMouseUp:d,ref:m,"data-vaul-overlay":"","data-vaul-snap-points":i&&f?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});ed.displayName="Drawer.Overlay";const td=K.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...n},a){const{drawerRef:o,onPress:i,onRelease:l,onDrag:u,keyboardIsOpen:m,snapPointsOffset:f,activeSnapPointIndex:d,modal:h,isOpen:v,direction:g,snapPoints:p,container:y,handleOnly:b,shouldAnimate:S,autoFocus:w}=Sn(),[x,k]=K.useState(!1),M=Qu(a,o),O=K.useRef(null),C=K.useRef(null),R=K.useRef(!1),P=p&&p.length>0;Ky();const E=(D,j,T=0)=>{if(R.current)return!0;const A=Math.abs(D.y),I=Math.abs(D.x),F=I>A,N=["bottom","right"].includes(j)?1:-1;if(j==="left"||j==="right"){if(!(D.x*N<0)&&I>=0&&I<=T)return F}else if(!(D.y*N<0)&&A>=0&&A<=T)return!F;return R.current=!0,!0};K.useEffect(()=>{P&&window.requestAnimationFrame(()=>{k(!0)})},[]);function L(D){O.current=null,R.current=!1,l(D)}return K.createElement(_u,{"data-vaul-drawer-direction":g,"data-vaul-drawer":"","data-vaul-delayed-snap-points":x?"true":"false","data-vaul-snap-points":v&&P?"true":"false","data-vaul-custom-container":y?"true":"false","data-vaul-animate":S?.current?"true":"false",...n,ref:M,style:f&&f.length>0?{"--snap-point-height":`${f[d??0]}px`,...t}:t,onPointerDown:D=>{b||(n.onPointerDown==null||n.onPointerDown.call(n,D),O.current={x:D.pageX,y:D.pageY},i(D))},onOpenAutoFocus:D=>{s?.(D),w||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(C.current=D,b||(n.onPointerMove==null||n.onPointerMove.call(n,D),!O.current))return;const j=D.pageY-O.current.y,T=D.pageX-O.current.x,A=D.pointerType==="touch"?10:2;E({x:T,y:j},g,A)?u(D):(Math.abs(T)>A||Math.abs(j)>A)&&(O.current=null)},onPointerUp:D=>{n.onPointerUp==null||n.onPointerUp.call(n,D),O.current=null,R.current=!1,l(D)},onPointerOut:D=>{n.onPointerOut==null||n.onPointerOut.call(n,D),L(C.current)},onContextMenu:D=>{n.onContextMenu==null||n.onContextMenu.call(n,D),C.current&&L(C.current)}})});td.displayName="Drawer.Content";const Hy=250,Wy=120,sd=K.forwardRef(function({preventCycle:e=!1,children:t,...s},n){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:l,setActiveSnapPoint:u,dismissible:m,handleOnly:f,isOpen:d,onPress:h,onDrag:v}=Sn(),g=K.useRef(null),p=K.useRef(!1);function y(){if(p.current){w();return}window.setTimeout(()=>{b()},Wy)}function b(){if(o||e||p.current){w();return}if(w(),!i||i.length===0){m||a();return}if(l===i[i.length-1]&&m){a();return}const k=i.findIndex(O=>O===l);if(k===-1)return;const M=i[k+1];u(M)}function S(){g.current=window.setTimeout(()=>{p.current=!0},Hy)}function w(){g.current&&window.clearTimeout(g.current),p.current=!1}return K.createElement("div",{onClick:y,onPointerCancel:w,onPointerDown:x=>{f&&h(x),S()},onPointerMove:x=>{f&&v(x)},ref:n,"data-vaul-drawer-visible":d?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},K.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});sd.displayName="Drawer.Handle";function Vy(e){const t=Sn(),{container:s=t.container,...n}=e;return K.createElement(Fu,{container:s,...n})}const ft={Root:qy,Content:td,Overlay:ed,Portal:Vy,Handle:sd,Title:Ku},nd="inline-flex items-center justify-center transition-colors",Qy=_e(nd,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Gy=_e(nd,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),To=({accountId:e,currentMailboxId:t,onMove:s,disabled:n=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),[m,f]=c.useState(),d=Xt(),h=c.useRef(null),v=i??"Move to folder",g=c.useId(),{t:p}=Ka("mail",{useSuspense:!1}),y=Qa(),{data:b,isLoading:S,isError:w,error:x,refetch:k}=be({...it({path:{accountId:e}}),staleTime:1/0,enabled:l}),M=jo(e),{createFolderIn:O}=tc(e),C=c.useMemo(()=>Ga({mailboxes:b?.items??[],folderAppointments:M,currentMailboxId:t,translator:y}),[b?.items,M,t,y]),R=Ya(b?.items??[]),P=C.find(I=>I.id===m),E=c.useCallback(()=>{u(!1),f(void 0)},[]),L=c.useCallback(()=>{P&&(E(),s(P.id))},[P,E,s]);c.useEffect(()=>{if(!l||!d)return;const I=N=>{h.current&&!h.current.contains(N.target)&&E()},F=N=>{N.key==="Escape"&&E()};return document.addEventListener("mousedown",I),document.addEventListener("keydown",F),()=>{document.removeEventListener("mousedown",I),document.removeEventListener("keydown",F)}},[l,d,E]);const D=n||!!a,j=r.jsxs("button",{type:"button",onClick:I=>{I.stopPropagation(),!D&&u(F=>!F)},"aria-label":v,"aria-haspopup":d?"tree":"dialog","aria-expanded":l,"aria-controls":l?g:void 0,title:a,className:o==="icon-only"?Qy:Gy,children:[r.jsx(Ta,{className:o==="icon-only"?"size-5":"size-4"}),o==="compact"&&r.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),T=S?r.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):w?r.jsx("div",{className:"p-3",children:r.jsx(Jt,{variant:"inline",title:"Couldn't load folders",error:x,onRetry:()=>k()})}):r.jsx(Fl,{folders:C,selectedId:m,delimiter:R,onSelect:f,onCreateFolder:O,onCancel:E,labels:{filterPlaceholder:p("move_picker_filter_placeholder",{defaultValue:"Filter folders…"}),filterAriaLabel:p("move_picker_filter_label",{defaultValue:"Filter folders"})}}),A=P&&r.jsx("div",{className:"shrink-0 border-t border-line p-2",children:r.jsx(le,{variant:"primary",onClick:L,className:"h-11 w-full font-semibold",children:`Move to ${P.label}`})});return d?r.jsxs("div",{ref:h,className:"relative inline-block",children:[j,l&&r.jsxs("div",{id:g,className:_e("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:[T,A]})]}):r.jsxs(r.Fragment,{children:[j,r.jsx(ft.Root,{open:l,onOpenChange:I=>I?u(!0):E(),children:r.jsxs(ft.Portal,{children:[r.jsx(ft.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(ft.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{maxHeight:"85dvh"},id:g,children:[r.jsx(ft.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),r.jsx(ft.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:T}),A]})]})})]})},Yy=({messageId:e,threadId:t,mailboxId:s,isRead:n,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const m=Me(),f=Ke(),{pushError:d}=st(),{selectedMessageId:h}=Os({strict:!1}),{mutate:v,isPending:g}=Fe({...rr(),onMutate:async T=>{const A=T.body.isRead??!0,I=new Set(T.body.messageIds??[]),F=hs({path:{threadId:t}}),N=Ot([s]);await Promise.all([m.cancelQueries({queryKey:F}),bn(m,N)]);const q=m.getQueriesData({queryKey:F}).filter(ae=>ae[1]!==void 0).map(([ae,U])=>({queryKey:ae,data:U})),Q=vn(m,N);return m.setQueriesData({queryKey:F},ae=>ae&&{...ae,items:Vn(ae.items,I,A)}),yn(m,N,ae=>Vn(ae,I,A)),{threadMessagesPrefix:F,listPrefixes:N,previousThreadMessages:q,previousThreadsList:Q}},onError:(T,A,I)=>{if(I){for(const N of I.previousThreadMessages)m.setQueryData(N.queryKey,N.data);wn(m,I.previousThreadsList)}const F=A.body.isRead??!0;d({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:mt(T),error:T})},onSettled:(T,A,I,F)=>{F&&(m.invalidateQueries({queryKey:F.threadMessagesPrefix}),Pt(m,F.listPrefixes))}}),p=c.useCallback(T=>{h&&T.includes(h)&&f({to:"/mail/$mailboxId",params:{mailboxId:s},search:A=>({...A,selectedMessageId:void 0})})},[h,s,f]),{deleteMessages:y,isPending:b}=us({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:S,isPending:w}=cs({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:x,isPending:k,error:M,reset:O}=Co({messageId:e}),C=()=>{v({body:{messageIds:[e],isRead:!1}})},R=()=>{y([e])},P=()=>{o&&x(o,i)},E=g||b||w||k,L=E||!o,D=c.useCallback(T=>{S([e],T)},[S,e]),j=o?void 0:"Sender has no parseable address";return r.jsxs("div",{className:"flex flex-col items-end gap-1",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[a&&r.jsx(To,{accountId:a,currentMailboxId:s,onMove:D,disabled:E,label:"Move this message"}),r.jsxs(lu,{trigger:r.jsx(pc,{className:"size-4"}),children:[r.jsxs(sn,{onClick:P,disabled:L,children:[i?r.jsx(cr,{className:"size-4 text-positive"}):r.jsx(fn,{className:"size-4 opacity-0"}),r.jsx("span",{title:j,children:"Trusted sender"})]}),n&&r.jsxs(sn,{onClick:C,disabled:E,children:[r.jsx(ur,{className:"size-4"}),"Mark as unread"]}),u&&r.jsxs(sn,{onClick:u,children:[r.jsx(hc,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),r.jsx(cu,{}),r.jsxs(sn,{onClick:R,disabled:E,destructive:!0,children:[r.jsx(Rt,{className:"size-4"}),"Delete"]})]})]}),M&&r.jsx("div",{className:"w-64",children:r.jsx(Jt,{variant:"inline",title:"Couldn't update trust",error:M,onRetry:()=>{O(),P()}})})]})},Xy=()=>{const[e,t]=c.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return c.useEffect(()=>{const s=document.documentElement,n=new MutationObserver(()=>{t(s.classList.contains("dark"))});return n.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e},Jy=({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"})]})]}),Zy=(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}}},e0=e=>e instanceof as?e.reason:"generic",t0=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",s0=({error:e,onRetry:t})=>{const s=e0(e),n=t0(e),{title:a,detail:o}=Zy(s,n),[i,l]=c.useState(!1),{Account:u}=$a();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(ds,{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:()=>l(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:r.jsx(jt,{className:"size-4","aria-hidden":"true"})})]})]})},n0=()=>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"})]}),ul=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),rd=({bodyParts:e,html:t,text:s,isTrusted:n=!1,messageId:a,fromAddressId:o,category:i,className:l})=>{const[u,m]=c.useState(!1),f=n||u,d=Xy(),{toggleTrusted:h,isPending:v}=Co({messageId:a??""}),g=!!e&&e.length>0,{picked:p,data:y,isLoading:b,isError:S,error:w,refetch:x}=wu({messageId:a,bodyParts:e,enabled:g}),k=c.useMemo(()=>wp(e??[]),[e]),M=g&&y?.kind==="html"?y.body:t,O=g&&y?.kind==="text"?y.body:s;if(g){if(b)return r.jsx("div",{className:_e("message-body",l),children:r.jsx(n0,{})});if(S)return r.jsx("div",{className:_e("message-body",l),children:r.jsx(s0,{error:w,onRetry:()=>x()})});if(!p)return r.jsx("div",{className:_e("message-body",l),children:r.jsx(ul,{})})}else if(!t&&!s)return r.jsx("div",{className:_e("message-body",l),children:r.jsx(ul,{})});const C=!!(o&&a),R=()=>{!o||v||(m(!0),h(o,!1))};return r.jsx(Pc,{className:l,html:M,text:O,isDark:d,category:i,allowImages:f,resolveCid:k,renderBlockedNotice:P=>r.jsx(Jy,{blockedImageCount:P,canAlwaysTrust:C,isTrustPending:v,onLoadOnce:()=>m(!0),onAlwaysTrust:R})})},r0=({messageId:e,threadId:t,mailboxId:s,accountId:n,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:l,isTrusted:u,showRaw:m,onToggleRaw:f,onReply:d,onReplyAll:h,onForward:v})=>{const g=Me(),{deleteMessages:p}=us({mailboxId:s,threadId:t}),{moveMessages:y}=cs({mailboxId:s,threadId:t,accountId:n}),{toggleTrusted:b}=Co({messageId:e}),{mutate:S}=Fe({...rr(),onSettled:()=>{g.invalidateQueries({queryKey:hs({path:{threadId:t}})}),Pt(g,Ot([s]))}}),w=c.useCallback(O=>{y([e],O)},[y,e]),x=c.useCallback(()=>{p([e])},[p,e]),k=c.useCallback(()=>{S({body:{messageIds:[e],isRead:!a}})},[S,e,a]),M=[];return l&&M.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?r.jsx(cr,{className:"size-4 text-positive"}):r.jsx(fn,{className:"size-4"}),onSelect:()=>b(l,u)}),f&&M.push({key:"raw",label:m?"Show formatted":"Show raw email",icon:r.jsx(hc,{className:"size-4"}),onSelect:f}),r.jsx(Oc,{hasThread:!0,onReply:d,onReplyAll:h,onForward:v,isStarred:o,onToggleStar:i,onDelete:x,isRead:a,onToggleRead:k,overflowItems:M,moveSlot:n?r.jsx(To,{accountId:n,currentMailboxId:s,onMove:w,label:"Move this message"}):void 0})},a0=()=>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"})]}),o0=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:n,isError:a,error:o,refetch:i}=be({...Zf({path:{messageId:e}}),enabled:t});if(n)return r.jsx("div",{className:"message-body",children:r.jsx(a0,{})});if(a)return r.jsx("div",{className:"message-body",children:r.jsx(Jt,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const l=s?.raw??"";return l===""?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:l})})},i0=()=>r.jsx(cr,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),ad=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),od=({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:_e("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":_e("text-fg-subtle hover:text-warning",n&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:r.jsx(Gt,{className:_e("size-3.5",e&&"fill-current")})}),l0=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:n,isStarPending:a})=>{const o=Zl(e.sentDate,"datetime"),i=ad(e,o);return r.jsx(Dc,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:r.jsxs(r.Fragment,{children:[e.hasAttachment&&r.jsx(dr,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx(od,{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})]})})},c0=({threadMessage:e,messageData:t,isLoading:s,isError:n,error:a,onRetry:o,isFocused:i,onToggle:l,onToggleStar:u,isStarPending:m,accountId:f,showRaw:d,onToggleRaw:h,mobile:v,onReply:g,onReplyAll:p,onForward:y})=>{const b=Zl(e.sentDate,"long"),S=!e.isRead,w=t?.envelope.from[0]?.flags?.trusted?.value===!0,x=t?.envelope.from[0]?.addressId,k=ad(e,b),M=e.autoMoved?r.jsx(ly,{accountId:f,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved}):null;return r.jsx(Lc,{message:k,isFocused:v?!1:i,onHeaderClick:l,senderBadge:w?r.jsx(i0,{}):void 0,trailing:r.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:b}),to:t?r.jsx(Uh,{label:"To",addresses:t.envelope.to}):null,indicators:M||!v?r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[M,!v&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[r.jsx(od,{isStarred:e.hasStars,onToggleStar:u,isStarPending:m}),e.hasAttachment&&r.jsx("span",{className:"text-fg-subtle p-0.5",children:r.jsx(dr,{className:"size-3.5"})})]}),S&&r.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:v?void 0:r.jsx(Yy,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:f,fromAddressId:x,isTrusted:w,showRaw:d,onToggleRaw:h}),actionBar:v?r.jsx(r0,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:f,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:x,isTrusted:w,showRaw:d,onToggleRaw:h,onReply:g,onReplyAll:p,onForward:y}):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&&em(a)?r.jsx("div",{className:"mt-3",children:r.jsx(Eu,{message:"This message has been deleted"})}):n?r.jsx("div",{className:"mt-3",children:r.jsx(Jt,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):d?r.jsx("div",{className:"mt-3",children:r.jsx(o0,{messageId:e.messageId})}):r.jsx("div",{className:"mt-3",children:r.jsx(rd,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:w,category:wr(e.category)})})})},u0=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,mobile:l,onReply:u,onReplyAll:m,onForward:f})=>{const[d,h]=c.useState(!1),{data:v,isLoading:g,isError:p,error:y,refetch:b}=be({...ar({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?r.jsx(c0,{threadMessage:e,messageData:v,isLoading:g,isError:p,error:y,onRetry:()=>b(),isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,showRaw:d,onToggleRaw:()=>h(S=>!S),mobile:l,onReply:u,onReplyAll:m,onForward:f}):r.jsx(l0,{threadMessage:e,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o})},d0=()=>r.jsxs("div",{className:"animate-pulse p-4",children:[r.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),r.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>r.jsxs("div",{className:"flex gap-3 py-3",children:[r.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function dl({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?r.jsxs("div",{className:"flex items-start gap-2 rounded-none border-b border-danger/20 bg-danger-soft px-5 py-2.5 text-sm",children:[r.jsx(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 Bs=({threadId:e,mailboxId:t,subject:s,selectedMessageId:n,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:l,onComposeClose:u,onSwipeNext:m,onSwipePrevious:f,mobileIntelligenceOpen:d})=>{const h=Xt(),{handlers:v}=Jv({onSwipeLeft:m,onSwipeRight:f}),{accountId:g}=yo(t),{data:p,isLoading:y,isError:b,error:S,refetch:w}=be({...tm({path:{threadId:e}})}),x=c.useMemo(()=>p?.items??[],[p?.items]),k=x[x.length-1],M=c.useRef(new Map),[O,C]=c.useState(new Set),[R,P]=c.useState(null),[E,L]=c.useState(0);c.useEffect(()=>{if(x.length>0&&e!==R){P(e);const H=new Set([x[x.length-1].threadMessageId]);if(n){const ie=x.find(ge=>ge.messageId===n);ie&&H.add(ie.threadMessageId)}C(H),L(x.length-1)}},[e,x,R,n]);const D=c.useCallback(H=>{C(ie=>{const ge=new Set(ie);return ge.has(H)?ge.delete(H):ge.add(H),ge})},[]),j=c.useCallback(H=>{const ie=x[H];if(!ie)return;M.current.get(ie.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[x]),T=c.useCallback(()=>{if(x.length===0)return;const H=Math.min(E+1,x.length-1);L(H),j(H)},[x.length,E,j]),A=c.useCallback(()=>{if(x.length===0)return;const H=Math.max(E-1,0);L(H),j(H)},[x.length,E,j]),I=c.useCallback(()=>{const H=x[E];H&&D(H.threadMessageId)},[x,E,D]),{data:F}=be({...Mt(),staleTime:1/0}),N=F?.accounts?.[0],q=!!N?.smtpHost;Qv({messages:x,expandedIds:O,threadId:e,mailboxId:t,accountId:N?.accountId});const{toggleStar:Q,isPending:ae,pendingMessageId:U}=wo({threadId:e,mailboxId:t,messages:x}),[z,ee]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(ee(l),u?.())},[l,u]);const{data:me}=be({...ar({path:{messageId:k?.messageId??""}}),enabled:!!k&&z!==null}),fe=c.useCallback(()=>{ee("reply")},[]),se=c.useCallback(()=>{ee("reply_all")},[]),W=c.useCallback(()=>{ee("forward")},[]),pe=c.useCallback(()=>{ee(null),u?.()},[u]);if(vo({enabled:!y&&x.length>0&&z===null,bindings:[{key:"j",handler:T,preventDefault:!0},{key:"ArrowDown",handler:T,preventDefault:!0},{key:"k",handler:A,preventDefault:!0},{key:"ArrowUp",handler:A,preventDefault:!0},{key:"Enter",handler:I,preventDefault:!0},{key:"o",handler:I,preventDefault:!0},...q?[{key:"r",handler:fe,preventDefault:!0},{key:"R",handler:se,noModifiers:!1,preventDefault:!0},{key:"f",handler:W,preventDefault:!0}]:[]]}),y)return r.jsx(d0,{});if(b)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(Jt,{title:"Couldn't load this conversation",error:S,onRetry:()=>w()})});if(x.length===0)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(Eu,{message:"No messages in this thread"})});const ve=s||x[0]?.subject||"(No subject)",Ne=x.length,we=H=>r.jsx("div",{children:x.map((ie,ge)=>r.jsx("div",{ref:ze=>{ze&&M.current.set(ie.threadMessageId,ze)},children:r.jsx(u0,{threadMessage:ie,isExpanded:O.has(ie.threadMessageId),isFocused:ge===E,onToggle:()=>D(ie.threadMessageId),onToggleStar:()=>Q(ie.messageId,ie.hasStars),isStarPending:ae&&U===ie.messageId,accountId:g,mobile:H,onReply:H&&q?fe:void 0,onReplyAll:H&&q?se:void 0,onForward:H&&q?W:void 0})},ie.threadMessageId))}),X=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:ve}),r.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Ne," ",Ne===1?"message":"messages"]})]});return h?r.jsxs("article",{className:"h-full flex flex-col",children:[X,a?.dkimMismatch&&r.jsx(dl,{authenticity:a,onOpenIntelligence:o}),r.jsx("div",{className:"flex-1 overflow-auto",children:we(!1)}),z!==null&&r.jsx(sl,{mode:z,account:N,sourceMessage:me,onClose:pe})]}):r.jsxs(Wp,{thread:{subject:ve,messages:[]},onBack:i??(()=>{}),intelligenceOpen:d,onToggleIntelligence:o,touchHandlers:v,children:[a?.dkimMismatch&&r.jsx(dl,{authenticity:a,onOpenIntelligence:o}),we(!0),z!==null&&r.jsx(sl,{mode:z,account:N,sourceMessage:me,onClose:pe})]})},f0=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function id(e){return!!e&&f0.has(e)}const ld=3e3,m0=ld*2,fl={syncing:!1,resolved:!1,synced:0,total:0};function h0(e,t){const s=e.join(","),[n,a]=c.useState(!1),[o,i]=c.useState(!1);c.useEffect(()=>{a(!1),i(!1)},[s,t]),c.useEffect(()=>{if(!t)return;const g=setTimeout(()=>i(!0),m0);return()=>clearTimeout(g)},[s,t]);const l=pt({queries:e.map(g=>({...sm({path:{accountId:g}}),enabled:t&&!n,refetchInterval:ld,meta:{softError:!0}}))}),u=l.every(g=>g.isSuccess||g.isError),m=l.length===0||u||o;let f=!1,d=0,h=0;for(const g of l)if(id(g.data?.syncPhase)){f=!0;for(const p of g.data?.mailboxes??[])d+=p.messagesSynced,h+=p.messagesTotal}const v=t&&m&&!f;return c.useEffect(()=>{v&&a(!0)},[v]),!t||!m?fl:{syncing:f,resolved:!0,synced:d,total:h}}function gs(){const{mailboxNameIndex:e,accountNameIndex:t}=Ae();return{...It({select:n=>gu(n.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Ro=e=>e.trim().toLocaleLowerCase(),cd={personal:"Personal",uncategorized:"Unclassified",transactional:"Transactional",newsletter:"Newsletter",marketing:"Marketing",social:"Social",automated:"Automated"},p0=Object.values(ot).map(e=>({value:e,label:cd[e]})),g0={unclassified:"uncategorized"},wa=[{name:"from",label:"Sender",values:"contact"},{name:"subject",label:"Subject",values:"text"},{name:"category",label:"Category",values:"fixed",options:p0},{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"}],x0=new Map(wa.map(e=>[e.name,e])),ud=e=>x0.get(e.toLowerCase()),b0=/^\d{4}-\d{2}-\d{2}$/,v0=e=>/[\s"]/.test(e),y0=e=>v0(e)?`"${e.replace(/"/g,"")}"`:e,dd=(e,t)=>`${e}:${y0(t)}`,w0=e=>{if(!e.startsWith('"'))return e;const t=e.slice(1);return t.endsWith('"')?t.slice(0,-1):t};function Mo(e){const t=[];let s=-1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];if(o==='"'){n=!n,s<0&&(s=a);continue}if(!n&&/\s/.test(o)){s>=0&&t.push({raw:e.slice(s,a),start:s,end:a}),s=-1;continue}s<0&&(s=a)}return s>=0&&t.push({raw:e.slice(s),start:s,end:e.length}),t}function fd(e){const t=e.indexOf(":");if(t<=0)return;const s=e.slice(t+1);return{name:e.slice(0,t).toLowerCase(),value:w0(s),rawValue:s}}function S0(e,t,s){if(!b0.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 k0(e){const t=e.toLowerCase(),s=g0[t];return s||Object.values(ot).find(a=>a===t)}function j0(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 C0(e,t){const s=fd(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=k0(a);return o?{type:"category",raw:e,value:a,category:o}:void 0}case"is":return j0(e,a);case"has":return a.toLowerCase()==="attachment"?{type:"hasAttachment",raw:e}:void 0;case"before":case"after":return S0(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 Ks(e,t={}){const s=[],n=[];for(const a of Mo(e)){const o=C0(a.raw,t);o?s.push(o):n.push(a.raw)}return{freeText:n.join(" "),tokens:s}}function N0(e,t){return Mo(e).filter(s=>s.raw!==t.raw).map(s=>s.raw).join(" ")}function md(e){switch(e.type){case"from":return`From: ${e.value}`;case"subject":return`Subject: ${e.value}`;case"category":return`Category: ${cd[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 E0=20,I0=new Set(Object.values(ot)),T0=e=>e!==void 0&&I0.has(e)?e:void 0,R0=e=>{if(e.some(t=>t.type==="isUnread"))return!1;if(e.some(t=>t.type==="isRead"))return!0};function hd({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Ae(),n=gs(),a=It({select:x=>x.matches}),o=Ro(s),{freeText:i,tokens:l}=Ks(o,n),u=i.length>0,m=l.find(x=>x.type==="category"),f=T0(t)??m?.category,d=l.some(x=>x.type==="hasAttachment")?!0:void 0,h=l.some(x=>x.type==="isStarred")?!0:void 0,v=R0(l),g=l.find(x=>x.type==="after"),p=l.find(x=>x.type==="before"),y=l.find(x=>x.type==="in"),b=rv({matches:a,callerMailboxId:e,inTokenMailboxId:y?.mailboxId}),{data:S,isLoading:w}=be({...Vl({query:{query:i,mailboxId:b,limit:E0,...f!==void 0?{category:f}:{},...d!==void 0?{hasAttachment:d}:{},...h!==void 0?{hasStars:h}:{},...v!==void 0?{isRead:v}:{},...g?{sentDateFrom:g.epochSeconds}:{},...p?{sentDateTo:p.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:S?.items??[],isLoading:u&&w}}const M0=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),A0=e=>[...e].sort(M0);function Gn(e){const t=e.authenticity?.dkimMismatch===!0;return{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:ht(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:wr(e.category),suspicious:t}}function ml(e){return e.filter(t=>t.muted!==!0)}function O0(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 hl=[{id:"personal",label:"Personal",category:ot.personal},{id:"transactional",label:"Transactional",category:ot.transactional},{id:"newsletter",label:"Newsletter",category:ot.newsletter},{id:"marketing",label:"Marketing",category:ot.marketing},{id:"social",label:"Social",category:ot.social},{id:"automated",label:"Automated",category:ot.automated},{id:"uncategorized",label:"Unclassified",category:ot.uncategorized}];function P0(e){const t=new Map(hl.map(n=>[n.category,[]]));for(const n of e){const a=n.category??ot.uncategorized;(t.get(a)??t.get(ot.uncategorized))?.push(n)}const s=[];for(const n of hl){const a=t.get(n.category);a&&a.length>0&&s.push({id:n.id,label:n.label,threads:a})}return s}function pd(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Ao(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 D0={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function L0(e){return D0[e]??e}function F0(e,t){const{folder:s}=Ha(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:ht(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Sa(e,t){const{folder:s}=Ha(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.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function $0(e,t){const{mailboxId:s,folder:n}=Ha(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?ht(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:L0(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...n?{folder:n}:{}}}function gd(e,t,s){const n=new Set(t),a=[];for(const o of[...e].sort((i,l)=>l.score-i.score))n.has(o.threadId)||(n.add(o.threadId),a.push($0(o,s)));return a}function xd(e){const{spam:t}=lo([...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 _0=e=>{const{mailboxId:t,messages:s}=e,n=Me(),{pushError:a}=st(),{mutateAsync:o,isPending:i}=Fe({...nm(),onError:(u,m)=>{a({title:m.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:mt(u),error:u})},onSettled:(u,m,f)=>{Pt(n,Ot(vr(f.body.messageIds??[],s??[],t)))}});return{applyLabel:c.useCallback((u,m,f)=>{u.length!==0&&br(u,d=>o({body:{messageIds:d,labelId:m,action:f}}))},[o]),isPending:i}};function bd({accountId:e,mailboxId:t,messageIds:s}){const{labels:n}=Ja(e),{applyLabel:a}=_0({mailboxId:t}),o=c.useMemo(()=>n.map(i=>({key:i.labelId,label:i.name,icon:r.jsx("span",{className:`size-2.5 rounded-full ${rm(i.color)?Wo[i.color]:Wo.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[n,s,a]);return o.length===0?null:r.jsx(ao,{triggerLabel:"Apply label to selected messages",triggerIcon:r.jsx(am,{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 z0=768,B0=1024,vd=e=>e!=="desktop",jr=()=>{const e=Qo(`(min-width: ${z0}px)`);return Qo(`(min-width: ${B0}px)`)?"desktop":e?"tablet":"phone"},yd=8;function Oo(e,t){const s=Math.max(0,Math.min(t,e.length)),n=Mo(e).find(o=>s>=o.start&&s<=o.end);if(!n)return{start:s,end:s,raw:""};const a=fd(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 K0(e,t){const s=Oo(e,t);if(s.name===void 0)return{kind:"token",query:s.raw};const n=ud(s.name);if(n)return{kind:"value",token:n.name,source:n.values,query:s.value??""}}const U0={mailbox:"mailboxes",account:"accounts",contact:"contacts"},q0=(e,t)=>{if(e.values==="fixed")return e.options??[];const s=U0[e.values];return s?t[s]??[]:[]},H0=(e,t)=>{if(t==="")return 1;const s=e.toLowerCase();return s.startsWith(t)?0:s.includes(t)?1:-1},ka=(e,...t)=>{let s=-1;for(const n of t){if(n===void 0)continue;const a=H0(n,e);a<0||(s<0||a<s)&&(s=a)}return s},wd=e=>{const t=new Set;return e.filter(s=>s.rank>=0).sort((s,n)=>s.rank-n.rank).filter(s=>{const n=s.suggestion.value.toLowerCase();return t.has(n)?!1:(t.add(n),!0)}).slice(0,yd).map(s=>s.suggestion)},pl=e=>({value:`${e.name}:`,label:`${e.name}:`,hint:e.label});function W0(e){const t=e.trim().toLowerCase();if(t==="")return wa.map(pl);const s=[];for(const n of wa)if(s.push({rank:ka(t,`${n.name}:`,n.label),suggestion:pl(n)}),n.values==="fixed")for(const a of n.options??[]){const o=dd(n.name,a.value);s.push({rank:ka(t,o,a.label),suggestion:{value:o,label:a.label??o,hint:o}})}return wd(s)}function V0(e,t,s){const n=t.trim().toLowerCase(),a=q0(e,s).map(o=>({rank:ka(n,o.value,o.label),suggestion:{value:dd(e.name,o.value),label:o.label??o.value,...o.hint?{hint:o.hint}:{}}}));return wd(a)}function Q0(e,t,s={}){const n=Oo(e,t);if(n.name===void 0)return W0(n.raw);const a=ud(n.name);return a?V0(a,n.value??"",s):[]}function G0(e,t,s){const n=Oo(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 Y0=e=>({value:e.normalizedEmail,...e.displayName?{label:e.displayName,hint:e.normalizedEmail}:{}});function X0(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 J0(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 Z0(e,t=[]){const s=e.flat().filter(o=>o.fullPath),n=new Map;for(const o of s){const i=aa(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=aa(o.fullPath),l=n.get(i.toLowerCase())===1,u=t.length>1?a.get(o.accountId):void 0;return{value:l?i:o.fullPath,label:o.displayNameOverride?.trim()||i,...u?{hint:u}:{}}})}function ew(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 tw=250,sw=2;function nw({query:e,cursor:t,enabled:s}){const{accounts:n}=Ae(),{mailboxesByName:a}=gs(),o=a!==void 0,i=s?K0(e,t):void 0,l=i?.source==="contact"?i.query.trim():"",u=ir(l,tw),{data:m}=be({...tr({query:{q:u,limit:yd}}),enabled:u.length>=sw}),f=pt({queries:n.map(g=>({...it({path:{accountId:g.accountId}}),staleTime:1/0}))}),d=c.useMemo(()=>o?Z0(f.map(g=>g.data?.items??[]),n):[],[o,f,n]),h=c.useMemo(()=>ew(n),[n]),v=c.useMemo(()=>(m?.items??[]).map(Y0),[m]);return c.useMemo(()=>{if(!s)return[];const g=Q0(e,t,{mailboxes:d,accounts:h,contacts:v});return o?g:g.filter(p=>p.value!=="in:")},[s,e,t,d,h,v,o])}const rw={title:"",navSlot:null,titleMeta:null,searchSlot:null,searchField:null,searchResults:null,makeFilterSlot:null},ja=c.createContext(rw),Cr=()=>c.useContext(ja),aw=new Set(["hasAttachment","isUnread","isRead","isStarred","category","before","after"]),ow=e=>aw.has(e),iw=(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}ow(u.type)&&n.push({type:u.type,label:md(u)})}const i=e.freeText.trim(),l=i.length>0;return l&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:n,targetAccountId:o,keptTerms:l,droppedSemantic:l&&t}},lw=(e,t,s)=>e.targetAccountId??t??s[0]?.accountId,Sd="remit.recentSearches",cw=5;function Ca(){try{const e=localStorage.getItem(Sd);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function gl(e){const t=e.trim();if(!t)return Ca();const s=[t,...Ca().filter(n=>n!==t)].slice(0,cw);try{localStorage.setItem(Sd,JSON.stringify(s))}catch{return s}return s}const uw=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function kd({title:e,unreadCount:t,children:s,selectionBar:n,paneOverlay:a,footer:o,searchFilter:i,searchResults:l,searchLoading:u,relatedResults:m,relatedLoading:f,onSelectSearchResult:d,searchResultsLabel:h="Top matches",relatedResultsLabel:v="Related",searchResultsInBody:g=!1}){const{accounts:p,resultFolderIndex:y,searchQuery:b,searchInput:S,onSearchChange:w,onSearchClear:x,searchViewKey:k}=Ae(),M=gs(),O=Ke(),C=fs(),R=jr(),[P,E]=c.useState(!1),[L,D]=c.useState(Ca),j=om(),T=c.useRef(k);c.useEffect(()=>{T.current!==k&&(T.current=k,E(!1))},[k]);const[A,I]=c.useState(0),[F,N]=c.useState(!1),[q,Q]=c.useState(void 0),ae=nw({query:S,cursor:A,enabled:F&&S.trim().length>0}),U=c.useCallback(te=>{const ce=G0(S,A,te);w(ce.query),Q({cursor:ce.cursor})},[S,A,w]),z=Ul({count:ae.length,onAccept:te=>{const ce=ae[te];ce&&U(ce)}}),{comboboxProps:ee,handleKeyDown:me}=z,fe=c.useMemo(()=>({comboboxProps:ee,onKeyDown:me,onCaretChange:I,onFocusChange:N,...q?{caret:q}:{}}),[ee,me,q]),se=z.open?r.jsx(ql,{id:z.listId,suggestions:ae,activeIndex:z.activeIndex,optionId:z.optionId,onPick:U,onHighlight:z.setActiveIndex,label:"Search suggestions",className:"mx-row-inset mt-1 shrink-0"}):null,W=S.trim().length>0,{mailboxesByName:pe,accountsByName:ve}=M,Ne=c.useMemo(()=>Ks(S,{mailboxesByName:pe,accountsByName:ve}),[S,pe,ve]),we=Ne.tokens.map(te=>({label:md(te),onRemove:()=>w(N0(S,te))})),X=l??[],H=m??[],ie=W?[{id:"top",label:h,results:X},{id:"related",label:v,results:H}]:[],ze=!(X.length+H.length>0)&&(u===!0||f===!0),{scope:xe}=vu(p),B=It({select:te=>te.matches}),ue=xu(B),oe=ov(B,xe,ue?y.get(ue)?.role:void 0),ne=oe.kind==="global"?xd([...X,...H]):void 0,nt=ne?{kind:"global",onScopeToSpam:()=>O({to:"/mail/$mailboxId",params:{mailboxId:ne.mailboxId},search:{q:b||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:oe,Te=H.length>0,J=c.useMemo(()=>iw(Ne,{searchHadSemanticReach:Te}),[Ne,Te]),Se=W?J:void 0,Ve=W?{onClick:()=>{E(!1),j("properties","search")},blockedReason:gx(J)?void 0:"Add a sender or words to filter on"}:void 0,Oe=Ve?r.jsx($c,{...Ve}):null,he=uw({tier:R,hasLiveInput:W,hasCommittedQuery:b.trim().length>0,bodyRendersCommittedResults:g}),lt=te=>{D(gl(S)),d?.(te)},Xe=r.jsx(_c,{value:S,sections:ie,loading:ze,onSelectResult:lt,tokens:we,scope:nt}),Pe=n===void 0,Ue=he?r.jsx("div",{className:"h-full overflow-y-auto",children:Xe}):null,qe=Ue&&!Pe?Ue:s,Ze=Ue&&Pe?Ue:null,rt=vd(R),je=rt&&(P||W),G=c.useMemo(()=>({title:e,searchResults:Ze,makeFilterSlot:Oe,searchConversion:Se,navSlot:C&&!C.showNavPane&&r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(or,{className:"size-5"}),onClick:()=>C.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(im,{})]}),searchSlot:rt&&!je&&r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(Zn,{className:"size-5"}),onClick:()=>E(!0),"aria-label":"Search",className:"shrink-0"}),searchField:je&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(io,{value:S,onChange:w,onClear:x,globalFocusKey:!1,showClearButton:!1,suggest:fe})}),r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(jt,{className:"size-5"}),onClick:()=>{x(),E(!1)},"aria-label":"Close search",className:"shrink-0"})]})}),[e,t,C,rt,je,S,w,x,fe,Ze,Oe,Se]);if(R==="phone"&&P){const te=ce=>{D(gl(S)),E(!1),d?.(ce)};return r.jsxs(ja.Provider,{value:G,children:[r.jsx(wg,{value:S,onChange:w,onClear:x,onCancel:()=>{E(!1),x()},filter:i,recentSearches:L,onPickRecent:w,makeFilter:Ve,sections:ie,loading:ze,onSelectResult:te,tokens:we,scope:nt,suggest:fe,suggestList:se}),a]})}return r.jsx(ja.Provider,{value:G,children:r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[n?.(G),se,r.jsx("div",{className:"min-h-0 flex-1",children:qe}),o,a]})})}const dw=120,jd=({keyboardFocusedMessageId:e,openMessageId:t,enabled:s,open:n,delayMs:a=dw})=>{const o=c.useRef(n);o.current=n;const i=c.useRef(void 0);c.useEffect(()=>{const l=e;if(!s){i.current=l;return}if(l===void 0||l===t)return;if(l===i.current){i.current=void 0;return}const u=setTimeout(()=>o.current(l),a);return()=>clearTimeout(u)},[s,e,t,a])},fw=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:n})=>{const[a,o]=c.useState(s),[i,l]=c.useState(),u=c.useCallback(A=>{l(I=>I===A?I:void 0),o(A)},[]),m=jc(),{selectedCount:f,toggle:d,clearSelection:h,selectRange:v,setAnchor:g,selectAll:p}=m,y=no(f,t),b=c.useRef(null),S=c.useRef(!1),w=c.useCallback(()=>{n?.(),h()},[h,n]),x=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),k=c.useCallback(A=>{if(A<0||A>=e.length)return;const I=e[A];if(y){d(I);return}b.current=I,S.current=!1,l(I),o(I)},[e,y,d]),M=c.useCallback(()=>{e.length!==0&&k(x<0?0:Math.min(x+1,e.length-1))},[e.length,x,k]),O=c.useCallback(()=>{e.length!==0&&k(x<=0?0:x-1)},[e.length,x,k]),C=c.useCallback(()=>k(0),[k]),R=c.useCallback(()=>k(e.length-1),[k,e.length]),P=c.useCallback(()=>{a&&d(a)},[a,d]),E=c.useCallback((A,I)=>{const F=Gh(I);return F==="range"?(v(e,A,a),!0):F==="toggle"?(d(A),!0):(w(),g(A),!1)},[e,a,v,d,w,g]),L=c.useCallback(A=>{const I=kc(e,a,A);I!==void 0&&(v(e,I),b.current=I,S.current=!1,l(void 0),o(I))},[e,a,v]),D=c.useCallback(()=>L(-1),[L]),j=c.useCallback(()=>L(1),[L]),T=c.useCallback(()=>{e.length>0&&p(e)},[e,p]);return{focusedMessageId:a,setFocusedMessageId:u,keyboardFocusedMessageId:i,focusIndex:x,pendingDomFocusRef:b,cursorMovedByPointerRef:S,selection:m,isMultiSelectMode:y,exitSelection:w,moveFocusToIndex:k,focusNext:M,focusPrevious:O,focusFirst:C,focusLast:R,toggleFocusedSelection:P,extendRangeUp:D,extendRangeDown:j,selectAllLoaded:T,handleRowSelect:E}};function Cd(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Po=c.createContext(null),mw=e=>{const t=c.useContext(Po);return t?t.rowInteraction(e):null},Do=()=>{const e=c.useContext(Po);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},hw="[data-message-id]",pw=e=>Array.from(e.querySelectorAll(hw)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),gw=(e,t)=>e.length===t.length&&e.every((s,n)=>s===t[n]),xw=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const n=e.current;if(!n)return;const a=()=>{const i=pw(n);s(l=>gw(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(n,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function Nd({selectedMessageId:e,onOpen:t,onDeleteMessages:s,onSelectionVerb:n,wizardOpen:a=!1,isDeleting:o=!1,commandsRef:i,onTriageContextChange:l,children:u}){const m=Xt(),f=c.useRef(null),d=xw(f),h=fw({orderedIds:d,isDesktop:m,initialFocusedId:e}),{focusedMessageId:v,setFocusedMessageId:g,pendingDomFocusRef:p,cursorMovedByPointerRef:y,selection:b,isMultiSelectMode:S,exitSelection:w,handleRowSelect:x}=h,{selectedIds:k,selectedCount:M,isSelected:O,toggle:C,select:R,toggleAll:P}=b,E=d.length>0&&d.every(W=>k.has(W)),L=c.useCallback(()=>{d.length>0&&P(d)},[d,P]),{intersectWith:D}=b;c.useEffect(()=>{D(d)},[D,d]),c.useEffect(()=>{const W=p.current;W!==null&&(p.current=null,f.current?.querySelector(`[data-message-id="${W}"]`)?.focus())});const j=c.useCallback(W=>{y.current=!0,g(W)},[y,g]),T=c.useCallback(W=>{m||R(W)},[m,R]),A=c.useCallback(()=>{v&&t(v)},[v,t]),I=c.useCallback(W=>t(W,{replace:!0}),[t]);jd({keyboardFocusedMessageId:h.keyboardFocusedMessageId,openMessageId:e,enabled:m&&M===0,open:I});const[F,N]=c.useState(null),q=c.useCallback(W=>F!==null?!0:M>0?(n(W),!0):W!=="delete"||!v?!1:(N([v]),!0),[F,M,n,v]),Q=c.useCallback(()=>{F!==null&&(s(F),N(null),w())},[F,s,w]),ae=c.useCallback(()=>N(null),[]),U=c.useCallback(()=>M===0?!1:(w(),!0),[M,w]),z=d.length>0;c.useEffect(()=>{if(i){if(!z){i.current=null;return}return i.current={focusNext:h.focusNext,focusPrevious:h.focusPrevious,focusFirst:h.focusFirst,focusLast:h.focusLast,openFocused:A,toggleSelect:h.toggleFocusedSelection,extendSelectDown:h.extendRangeDown,extendSelectUp:h.extendRangeUp,selectAll:h.selectAllLoaded,clearSelection:U,requestVerb:q,toggleDensity:()=>{}},()=>{i.current=null}}},[i,z,h.focusNext,h.focusPrevious,h.focusFirst,h.focusLast,h.toggleFocusedSelection,h.extendRangeDown,h.extendRangeUp,h.selectAllLoaded,A,U,q]);const ee=c.useMemo(()=>Array.from(k),[k]),me=F!==null;c.useEffect(()=>{l?.({focusedMessageId:v,selectedIds:ee,orderedIds:d,hasList:z,blocksKeyboard:me||a})},[l,v,ee,d,z,me,a]);const fe=Cd(d,v),se=c.useMemo(()=>({selectedIds:k,selectedCount:M,exitSelection:w,startSelectionVerb:n,orderedIds:d,allSelected:E,toggleAllLoaded:L,rowInteraction:W=>({focused:W===v,isTabStop:W===fe,isDesktop:m,onFocusRow:j,selection:{isChecked:O(W),onToggleCheck:C,onRowSelect:x,isMultiSelectMode:S,onLongPress:T}})}),[k,M,w,n,d,E,L,v,fe,m,j,O,C,x,S,T]);return r.jsxs(Po.Provider,{value:se,children:[r.jsx("div",{ref:f,className:"contents",children:u}),r.jsx(Za,{isOpen:me,title:ec(F?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:o,onConfirm:Q,onCancel:ae})]})}function bw({title:e,isDeleting:t}){const s=Cr(),{selectedCount:n,exitSelection:a,startSelectionVerb:o,orderedIds:i,allSelected:l,toggleAllLoaded:u}=Do();return r.jsx(uo,{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:l,indeterminate:n>0&&!l,onChange:u}:void 0})}const Jr=e=>{e.preventDefault(),e.stopPropagation()},vw=(e,t)=>{const s=c.useRef(!1),n=c.useCallback(i=>{if(s.current=!1,i.button!==0)return;const l=Hn(i);oi(l)&&t?.(e,l)&&(Jr(i),s.current=!0,i.currentTarget.focus(),l.shiftKey&&window.getSelection()?.removeAllRanges())},[t,e]),a=c.useCallback(i=>{!i.ctrlKey||!t||i.preventDefault()},[t]),o=c.useCallback(i=>{if(s.current)return s.current=!1,Jr(i),!0;const l=Hn(i);return!oi(l)||!t?.(e,l)?!1:(Jr(i),l.shiftKey&&window.getSelection()?.removeAllRanges(),!0)},[t,e]);return{onMouseDown:n,onContextMenu:a,claimClick:o}},yw=({thread:e,active:t=!1,focused:s,isTabStop:n,density:a="comfortable",isDesktop:o,badge:i,selection:l,inListbox:u=!1,linkMailboxId:m,onClick:f,onFocusRow:d})=>{const h=Me(),v=e.id,g=mw(v),p=s??g?.focused??!1,y=n??g?.isTabStop??!1,b=l??g?.selection,S=d??g?.onFocusRow,w=o??g?.isDesktop??!0,x=b?.isChecked??!1,k=b?.isMultiSelectMode??!1,M=b?.onToggleCheck,O=b?.onRowSelect,C=b?.onLongPress,R=c.useCallback(N=>{N.preventDefault(),N.stopPropagation(),M?.(v)},[M,v]),P=vw(v,O),E=c.useCallback(N=>{if(!P.claimClick(N)){if(!w){if(k){N.preventDefault(),N.stopPropagation(),M?.(v);return}f?.();return}O?.(v,Hn(N)),f?.()}},[P,w,k,M,O,f,v]),L=c.useCallback(()=>{C?.(v)},[C,v]),{longPressProps:D}=Rc({onLongPress:L,accessibilityDescription:x?"Deselect message":"Select message"}),j=c.useCallback(()=>{h.prefetchQuery(ar({path:{messageId:v}}))},[h,v]),T=c.useCallback(()=>{j(),S?.(v)},[j,S,v]),A=Ls({"data-list-row":"","data-message-row":!0,"data-message-id":v,...u?{role:"option","aria-selected":x}:{},tabIndex:y?0:-1,onClick:E,onMouseDown:P.onMouseDown,onContextMenu:P.onContextMenu,onMouseEnter:j,onFocus:T},w||!b?{}:D),I=_e(a==="compact"?Ec({active:t,focused:p}):_e("group",$s({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",x&&"bg-accent-soft",!w&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?r.jsx(Ic,{thread:e}):r.jsx(ro,{thread:e,badge:i,selection:b?{checked:x,alwaysVisible:k,onToggle:R}:void 0});return m===void 0?r.jsx("button",{type:"button",...A,className:I,children:F}):r.jsx(Kt,{to:"/mail/$mailboxId",params:{mailboxId:m},search:N=>({...N,selectedMessageId:v}),...A,className:I,children:F})},Lo=c.memo(yw),Ed=8,Id=e=>e==="From"||e==="FromDomain",ww=e=>({value:e.email,label:e.displayName??e.email,...e.displayName?{hint:e.email}:{},...e.fromSelection?{source:"selected"}:{}}),Sw=e=>{const t=qc(e.email);if(t!==null)return{value:t,...e.fromSelection?{source:"selected"}:{}}},kw=(e,t)=>e.value.toLowerCase().includes(t)||(e.label??"").toLowerCase().includes(t),jw=(e,t,s)=>{if(!Id(e))return[];const n=t.trim().toLowerCase(),a=new Set,o=[];for(const i of s){if(i.email.trim()==="")continue;const l=e==="From"?ww(i):Sw(i);if(!l)continue;const u=l.value.toLowerCase();if(!(u===""||a.has(u))&&(a.add(u),u!==n&&!(n!==""&&!kw(l,n))&&(o.push(l),o.length===Ed)))break}return o},Cw=250,Nw=2,Ew=(e,t,s)=>{const n=t.trim(),a=ir(n,Cw),o=e!==void 0&&Id(e),{data:i}=be({...tr({query:{q:a,limit:Ed}}),enabled:o&&a.length>=Nw});if(!o||e===void 0)return[];const l=[...s.map(u=>({email:u,fromSelection:!0})),...(i?.items??[]).map(u=>({email:u.normalizedEmail,...u.displayName?{displayName:u.displayName}:{}}))];return jw(e,n,l)},Iw={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},Td={delete:"moved to Trash",move:"moved",markRead:"marked as read"},Tw={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},Rw={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},Mw={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},Aw=(e,t,s)=>Iw[e](Vt(t),Vt(s)),xl=(e,t)=>`${Vt(t)} ${Td[e]}. Your mail server is still catching up.`,Ow=e=>`Stopped after ${Vt(e)}`,Pw=(e,t,s)=>`${Vt(t)} of ${Vt(s)} ${Td[e]}. Nothing was sent for the rest, so they are untouched.`,Dw=(e,t)=>t>0?`Stopped after ${Vt(t)} — some messages ${Tw[e]}`:Rw[e],Lw=e=>Mw[e],Fw=e=>e==="delete"?"danger":"info",$w=100,_w=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],Rd=({mailboxId:e,accountId:t,enabled:s,predicateKey:n,searchQuery:a})=>{const[o,i]=c.useState({kind:"idle"}),[l,u]=c.useState(void 0),[m,f]=c.useState(void 0),d=c.useRef(!1),h=c.useRef(!1),v=Me(),{pushError:g}=st();c.useEffect(()=>{h.current||(d.current=!0),i({kind:"idle"})},[s,n]);const p=c.useRef(a);p.current=a;const y=c.useCallback(C=>async R=>{const{data:P}=await oa({path:{mailboxId:e},query:{...C,continuationToken:R,limit:$w},throwOnError:!0});return{ids:(P.items??[]).map(E=>E.messageId),continuationToken:P.continuationToken}},[e]),b=c.useCallback(async()=>{const{data:C}=await oa({path:{mailboxId:e},query:{...p.current,count:!0,results:!1},throwOnError:!0});if(C.count===void 0)throw new Error("the search returned no count for the selection");return C.count},[e]),S=c.useCallback(C=>async R=>{if(C.kind==="move"){const{data:E}=await lm({body:{messageIds:R,destinationMailboxId:C.destinationMailboxId},throwOnError:!0});return E}if(C.kind==="markRead"){const{data:E}=await cm({body:{messageIds:R,isRead:!0},throwOnError:!0});return E}const{data:P}=await um({body:{messageIds:R},throwOnError:!0});return P},[]),w=c.useCallback(C=>{Pt(v,Ot(_w(C,e))),t&&v.invalidateQueries({queryKey:ms({path:{accountId:t}})})},[v,e,t]),x=c.useCallback(()=>{d.current=!1,i({kind:"counting"}),b().then(C=>{if(d.current){i({kind:"idle"});return}i({kind:"escalated",total:C})},C=>{g(is("Couldn't count matching messages","The count didn't finish.",C)),i({kind:"idle"})})},[b,g]),k=c.useCallback(()=>{d.current=!0},[]),M=c.useCallback(()=>{h.current||(d.current=!0,i({kind:"idle"}))},[]),O=c.useCallback(async(C,R)=>{d.current=!1,h.current=!0,u(C);const P=j=>f(qv(j)),E=S(C),L=y(p.current);let D;try{D=R!==void 0?await Iu(R,E,P,()=>d.current):await Uv(L,o.kind==="escalated"?o.total:0,E,P,()=>d.current)}finally{h.current=!1}return u(void 0),f(void 0),i({kind:"idle"}),D.error&&g(is(Dw(C.kind,D.done),Lw(C.kind),D.error)),D.done>0&&w(C),D},[S,y,o,g,w]);return{phase:o,escalate:x,stop:k,clear:M,isRunning:l!==void 0,runningAction:l,progress:m,runAction:O}},Md=12,zw=e=>{const{envelope:t}=e,s=t.from[0];return{id:t.messageId,sender:s?Hc({normalizedEmail:s.normalizedEmail,displayName:s.displayName}):"Unknown",subject:t.subject??"(No subject)",date:ht(t.date)}},Bw=(e,t)=>{const s=e!==void 0&&t!==void 0,{data:n,isLoading:a}=be({...Ql({path:{mailboxId:e??""},query:{...t,limit:Md}}),enabled:s,staleTime:3e4});return{messages:(n?.items??[]).map(Kw),isPending:s&&a}},Kw=e=>({id:e.messageId,sender:e.fromName||e.fromEmail||"Unknown",subject:e.subject??"(No subject)",date:ht(e.sentDate)}),Uw=e=>pt({queries:e.slice(0,Md).map(t=>({...ar({path:{messageId:t}}),staleTime:Number.POSITIVE_INFINITY})),combine:t=>({messages:t.map(s=>s.data).filter(s=>s!==void 0).map(zw),isPending:t.some(s=>s.isPending)})}),qw=e=>({matchOperator:"Or",literalClauses:mr(e)}),Hw=(e,t,s)=>{const n=Fe(dm()),{mutate:a,reset:o}=n,[i,l]=c.useState(!1),u=c.useMemo(()=>fr(s),[s]),m=c.useCallback(()=>{!e||!t||(l(!1),a({path:{accountId:e},body:Go({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),f=c.useCallback(()=>{l(!1),o()},[o]),d=n.data,h=d?.semanticUnavailable===!0&&!i&&u.length>0;c.useEffect(()=>{!h||!e||(l(!0),a({path:{accountId:e},body:Go(qw(u))}))},[h,e,u,a]);const v=i||(d?.semanticUnavailable??!1),g=n.isPending||h,p=i?{matchOperator:"Or",literalClauses:mr(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:m,reset:f,matchedCount:g?void 0:d?.matchedCount,messageIds:g?void 0:d?.messageIds,semanticUnavailable:v,senderFallback:i,senders:u,matchPredicate:p,isPending:g,isError:n.isError,error:n.error}},Ww=()=>[nr({path:{mailboxId:""}}),Ua({path:{mailboxId:""}}),qa()].map(e=>[{_id:e[0]._id}]),Vw=e=>Tu(e)?e.pages:Ru(e)?[e]:[],Qw=e=>typeof e=="object"&&e!==null&&typeof e.messageId=="string",Gw=(e,t)=>{const s=new Set(t),n=new Map;for(const a of e)for(const o of Vw(a))for(const i of o.items){if(!Qw(i)||!s.has(i.messageId))continue;const l=i.subject?.trim();l&&n.set(i.messageId,l)}return t.map(a=>n.get(a)).filter(a=>a!==void 0)},Yw=e=>{const t=Me(),s=e.join("\0");return c.useMemo(()=>{const n=Ww().flatMap(a=>t.getQueriesData({queryKey:a}).map(([,o])=>o));return Gw(n,e)},[t,s])},Xw=({failure:e,isStarting:t,isRunning:s,isDone:n,failedCount:a,ruleSaved:o})=>e?.kind==="startFailed"?o?"backApplyStartFailed":"commitFailed":n?a>0?"backApplyFailed":"backApplyComplete":e?.kind==="statusUnreadable"?"statusUnknown":t||s?"backApplyRunning":"saving",Jw={clauses:[],matchOperator:"any"},Zw={clauses:[],matchOperator:"all",droppedFacets:[],keptTerms:!1,droppedSemantic:!1},eS=[],Cs={state:"saving",matched:0,applied:0,failed:0,failures:[]},Zr=(e,t)=>e.map((s,n)=>({...s,id:`${t}-${n}`})),bl=(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},ea=e=>e==="move"||e==="junk"||e==="organize",vl=(e,t)=>({done:0,failedIds:[...t],cancelled:!1,error:new Error(e==="junk"?"This account has no Junk folder appointed, so there is nowhere to file these. Appoint one under Settings › Folders.":"No destination was chosen, so there is nowhere to file these. Go back and pick a folder.")});function tS({verb:e,accountId:t,mailboxId:s,selection:n,crossAccount:a=!1,escalated:o,escalatedProgress:i,searchConversion:l,onFinished:u,onRunEnded:m,step:f,goToStep:d,goBack:h,closeWizard:v}){const[g]=c.useState(()=>l),[p]=c.useState(()=>o),y=g!==void 0,[b,S]=c.useState(y?"properties":"selected"),w=p?"escalated":b,[x,k]=c.useState(()=>g?{clauses:Zr(g.clauses,"search"),matchOperator:g.matchOperator}:Jw),[M,O]=c.useState(void 0),[C,R]=c.useState(void 0),[P,E]=c.useState(!1),[L,D]=c.useState(void 0),[j,T]=c.useState(void 0),[A,I]=c.useState(),F=c.useRef(!1),N=c.useRef(!1),q=c.useMemo(()=>n.map(_=>_.id),[n]),Q=c.useMemo(()=>n.map(_=>_.email).filter(Boolean),[n]),ae=q[0],U=Yw(q),{junkMailboxId:z}=zs(t),ee=Hw(p?void 0:t,ae,Q),{preview:me}=ee;c.useEffect(()=>{me()},[me]);const fe=w==="similar"||w==="properties",se=c.useMemo(()=>({matchOperator:x.matchOperator==="all"?"And":"Or",literalClauses:x.clauses.map(_=>({field:_.field,value:_.value}))}),[x.clauses,x.matchOperator]),W=w==="similar"?ee.matchPredicate:se,{count:pe,matchedIds:ve}=zm(fe?t:void 0,W),Ne=Uw(fe?ve:[]),we=Bw(p?s:void 0,p?.searchQuery),X=p?{status:"ready",count:p.total}:fe?pe:{status:"ready",count:n.length},{data:H}=be({...it({path:{accountId:t??""}}),enabled:!!t,staleTime:Number.POSITIVE_INFINITY}),ie=jo(t),ge=Qa(),ze=c.useMemo(()=>Ga({mailboxes:H?.items??[],folderAppointments:ie,currentMailboxId:s,translator:ge}),[H?.items,ie,s,ge]),{createFolderIn:xe}=tc(t),B=ze.find(_=>_.id===x.moveMailboxId)?.label,ue=ix(n.map(_=>({normalizedEmail:_.email,displayName:_.sender}))),oe=px({match:w==="properties"&&x.clauses[0]?.value.trim()||void 0,sender:ue?Hc(ue):void 0,folder:B}),ne=c.useMemo(()=>({...x,name:x.name??oe}),[x,oe]),nt=Ew(M?.draft.field,M?.draft.value??"",Q),Te=Bm(t),J=Km(t),Se=Rd({mailboxId:s??"",accountId:t,enabled:!1,predicateKey:"selection-wizard",searchQuery:{}}),{runAction:Ve}=Se,Oe=hm({verb:e,mode:w,scope:x.scope,fromSearch:y}),he=Oe[Vo(Oe,f)],lt=!a&&!!t,Xe=lt?void 0:xm,Pe=lt?void 0:bm,qe=(_=>{if(_==="folder")return Pe;if(_==="rule")return ne.scope==="standing"||ne.scope==="until"?Xe:void 0})(he)??pm(he,ne,X),Ze=c.useCallback(()=>Zr(hx(Q,U),"seed"),[Q,U]),rt=c.useCallback(_=>{S(_),k(Y=>({...Y,widen:_==="similar"&&ae?{anchorCount:Math.max(n.length,1)}:void 0,..._==="properties"&&Y.clauses.length===0?{clauses:Ze()}:{}}))},[ae,n.length,Ze]),je=c.useCallback(()=>{E(!0),S("properties"),k(_=>({..._,widen:void 0,clauses:Zr(mr(Q),"sender"),matchOperator:"any"})),d("properties")},[Q,d]),G=ee.semanticUnavailable||ee.isError;c.useEffect(()=>{he==="match"&&(w!=="similar"||!G||P||je())},[he,w,G,P,je]);const te=c.useCallback(()=>{O({mode:"add",draft:{field:"From",value:""}})},[]),ce=c.useCallback(_=>{const Y=x.clauses.find(Ce=>Ce.id===_);Y&&O({mode:"edit",clauseId:_,draft:{field:Y.field,value:Y.value}})},[x.clauses]),de=c.useCallback(_=>{k(Y=>({...Y,clauses:Y.clauses.filter(Ce=>Ce.id!==_)}))},[]),ke=c.useCallback(_=>{O(Y=>Y&&{...Y,draft:_})},[]),Ee=c.useCallback(()=>{O(_=>{if(!_)return;const Y=Um(_.draft.field,_.draft.value),Ce={..._.draft,value:Y};k(ut=>({...ut,clauses:_.clauseId?ut.clauses.map(bt=>bt.id===_.clauseId?{...bt,...Ce}:bt):[...ut.clauses,{id:crypto.randomUUID(),...Ce}]}))})},[]),De=c.useCallback(()=>{if(qe){R(he);return}R(void 0);const _=Oe[Vo(Oe,he)+1];_&&d(_)},[qe,he,Oe,d]),He=c.useCallback(async _=>{const Y=bl(e,ne.moveMailboxId,z);if(!Y){T({matched:_.length,outcome:vl(e,_)});return}T({matched:_.length});const Ce=await Ve(Y,[..._]);T({matched:_.length,outcome:Ce}),N.current&&m?.(Y.kind,_.length,Ce)},[e,ne.moveMailboxId,z,Ve,m]),ye=c.useCallback(async()=>{if(!p)return;const _=bl(e,ne.moveMailboxId,z);if(!_){T({matched:p.total,outcome:vl(e,[])});return}T({matched:p.total});const Y=await p.run(_);T({matched:p.total,outcome:Y}),N.current&&m?.(_.kind,p.total,Y)},[p,e,ne.moveMailboxId,z,m]),{start:Qe}=Te,{createFilterAsync:Ge}=J,Le=c.useCallback(()=>{if(p){ye();return}const _=qm({mode:b,ruleScope:ne.scope}),Y=Hm({mode:b,ruleScope:ne.scope,anchorMessageId:ae,clauses:ne.clauses,matchOperator:ne.matchOperator,moveMailboxId:ne.moveMailboxId,until:ne.until});if(D(_),_==="standing"||_==="temporary"){const Ce=Wm(Y)?Y:void 0;I(Ce),Ge(Y,_,(ne.name??"").trim()).then(ut=>{ut&&Ce&&Qe(Ce)});return}if(_==="all-like-these"&&ea(e)){Qe(Y);return}He(_==="just-these"?q:ve)},[p,ye,b,ne,ae,e,q,ve,Ge,Qe,He]),et=c.useCallback(()=>{if(qe){R(he);return}F.current||(F.current=!0,d("run"),Le())},[qe,he,d,Le]),Ye=c.useCallback(_=>{const Y=Te.progress,Ce=Xw({failure:Te.failure,isStarting:Te.isStarting,isRunning:Te.isRunning,isDone:Te.isDone,failedCount:Y.failedCount,ruleSaved:_});return Ce==="saving"||Ce==="commitFailed"||Ce==="backApplyStartFailed"?{...Cs,state:Ce}:{state:Ce,matched:Y.matchedCount,applied:Y.appliedCount,failed:Ce==="backApplyFailed"?Y.failedCount:0,failures:[]}},[Te]),Dt=c.useMemo(()=>{const _=new Map;for(const Y of[...n,...Ne.messages,...we.messages])_.set(Y.id,Y);return _},[n,Ne.messages,we.messages]),es=p?i:Se.progress,Lt=c.useCallback(()=>{if(!j)return Cs;const{matched:_,outcome:Y}=j;if(!Y){const vt=es?.done??0;return{state:"backApplyRunning",matched:Math.max(_,vt),applied:vt,failed:0,failures:[]}}if(!(Y.cancelled||Y.error!==void 0))return{state:"backApplyComplete",matched:Math.max(_,Y.done),applied:Y.done,failed:0,failures:[]};if(Y.done===0)return{...Cs,state:"commitFailed"};const ut=Y.failedIds.map(vt=>Dt.get(vt)).filter(vt=>vt!==void 0),bt=Y.failedIds.length>0?Y.failedIds.length:Math.max(_-Y.done,1);return{state:"runStopped",matched:Math.max(_,Y.done),applied:Y.done,failed:bt,failures:ut}},[j,es,Dt]),tt=p?Lt():L==="standing"||L==="temporary"?J.isError?{...Cs,state:"commitFailed"}:J.isSuccess?A?Ye(!0):{...Cs,state:"filterSaved"}:Cs:L==="all-like-these"&&ea(e)?Ye(!1):Lt(),xt=()=>{if(tt.state==="statusUnknown"){Te.refreshStatus();return}if(p){ye();return}if(L==="standing"||L==="temporary"){if(J.isError){J.reset(),Le();return}A&&Qe(A);return}if(L==="all-like-these"&&ea(e)){Le();return}const _=j?.outcome?.failedIds??[];He(_.length>0?_:q)},Ft=c.useCallback(()=>{v(Oe,he)},[v,Oe,he]),ct=c.useCallback(()=>{N.current=!0,v(Oe,he),u()},[v,Oe,he,u]),{stop:$t}=Se,qs=j!==void 0&&j.outcome===void 0,Hs=c.useCallback(()=>{if(p){p.stop();return}$t()},[p,$t]);ou({shouldBlockFn:({action:_})=>_!=="BACK"?!1:(ct(),!0),enableBeforeUnload:!1,disabled:he!=="run"});const ts={messages:p?we.messages:fe?Ne.messages:n,count:X,label:w==="selected"?"Your selection":"A sample of what matches",emptyReason:w==="similar"&&G?"notIndexed":"noMatch",loading:p?we.isPending:fe&&(X.status==="loading"||Ne.isPending)};return r.jsx(gm,{verb:e,steps:Oe,step:he,blockedReason:qe,nudged:C===he,onBack:h,onExit:he==="run"?ct:Ft,onContinue:De,onCommit:et,match:{selectedCount:n.length,mode:w,onModeChange:rt,semanticUnavailable:G,semanticErrorDetail:ee.error instanceof Error?ee.error.message:void 0,semanticFallbackTaken:P,onSemanticFallback:je,escalatedScope:p?.scope,sample:ts},properties:{clauses:ne.clauses,matchOperator:ne.matchOperator,onMatchOperatorChange:_=>k(Y=>({...Y,matchOperator:_})),clauseEdit:M,onStartAddClause:te,onStartEditClause:ce,onRemoveClause:de,onChangeDraft:ke,onSubmitClause:Ee,onCancelClause:()=>O(void 0),clauseFields:Vm,clauseSuggestions:nt,conversionNotice:g?xx(g):void 0,semanticFallbackTaken:P,sample:{...ts,label:"What this matches"}},folder:{folders:ze,mailboxId:ne.moveMailboxId,delimiter:Ya(H?.items??[]),onSelect:_=>k(Y=>({...Y,moveMailboxId:_})),onCreateFolder:t?xe:void 0,restriction:Pe},rule:{draft:ne,onScopeChange:_=>k(Y=>({...Y,scope:_})),onUntilChange:_=>k(Y=>({...Y,until:_})),restriction:Xe},name:{name:ne.name??"",onNameChange:_=>k(Y=>({...Y,name:_})),nudged:C===he},review:{verb:e,mode:w,selectedCount:n.length,clauses:ne.clauses,matchOperator:ne.matchOperator,folder:B,scope:ne.scope,until:ne.until,ruleName:Oe.includes("name")?ne.name:void 0,escalatedScope:p?.scope,sample:ts},run:{state:tt.state,verb:e,scope:ne.scope,matched:tt.matched,applied:tt.applied,failedCount:tt.failed,failures:tt.failures,onRetry:xt,onDismiss:ct,onCancelRun:qs?Hs:void 0}})}function Fo(e){const t=fm()==="search",{searchConversion:s}=Cr(),{accounts:n}=Ae(),{step:a,goToStep:o,goBack:i,closeWizard:l}=mm(t?"properties":"match");if(!a)return null;const u=t?s??Zw:void 0;return r.jsx(tS,{...e,...u?{verb:"organize",accountId:lw(u,e.accountId,n),selection:eS,crossAccount:!1,escalated:void 0,searchConversion:u}:{},step:a,goToStep:o,goBack:i,closeWizard:l})}const sS=200,yl=()=>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))}),nS=({accountEmail:e})=>{const t=Ke();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(ds,{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"})]})},rS=(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 aS({header:e,rows:t,wizard:s,children:n}){const{selectedIds:a,selectedCount:o,exitSelection:i,orderedIds:l,allSelected:u,toggleAllLoaded:m}=Do(),f=c.useMemo(()=>rS(t,a),[t,a]),{junkMailboxId:d}=zs(f.accountId),{labels:h}=Ja(f.accountId),v=c.useMemo(()=>Array.from(a),[a]),g=c.useMemo(()=>t.filter(w=>a.has(w.id)).map(w=>({id:w.id,sender:w.fromName,email:w.fromEmail,subject:w.subject,date:w.timeLabel})),[t,a]),p=!!d&&d!==f.mailboxId,y=c.useMemo(()=>l.length>0?{checked:u,indeterminate:o>0&&!u,onChange:m}:void 0,[l.length,u,o,m]),b=f.moveDisabledHint?{tone:"warning",text:f.moveDisabledHint}:void 0,S=w=>r.jsx(uo,{title:w.title,navSlot:w.navSlot,titleMeta:w.titleMeta,searchSlot:w.searchSlot,searchField:w.searchField,idleSlot:w.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:f.accountId&&f.mailboxId&&o>0&&h.length>0?r.jsx(bd,{accountId:f.accountId,mailboxId:f.mailboxId,messageIds:v}):void 0,selectAll:y,notice:b});return r.jsx(kd,{...e,selectionBar:S,paneOverlay:r.jsx(Fo,{verb:s.verb,accountId:f.accountId,mailboxId:f.mailboxId,selection:g,crossAccount:f.moveDisabledHint!==void 0,onFinished:i}),children:n})}function oS({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:n,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i}){const{searchQuery:l,searchInput:u,resultFolderIndex:m}=Ae(),f=gs(),d=Xt(),h=Wa(),v=Ke(),g=c.useMemo(()=>A0(e.filter(B=>!B.muted?.value)),[e]),[p,y]=c.useState("all"),[b,S]=c.useState("all"),[w,x]=c.useState(new Set),[k,M]=c.useState(!1),O=c.useCallback(B=>{x(ue=>{const oe=new Set(ue);return oe.has(B)?oe.delete(B):oe.add(B),oe})},[]),C=c.useCallback(()=>x(new Set),[]),R=u.trim().length>0,{data:P,isLoading:E,isError:L,refetch:D}=be({...ia(),staleTime:6e4}),j=pt({queries:g.map(B=>({...it({path:{accountId:B.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),T=c.useMemo(()=>{const B=new Map;for(let ue=0;ue<g.length;ue++){const oe=g[ue].accountId,nt=(j[ue]?.data?.items??[]).reduce((Te,J)=>Te+(J.unseenCount??0),0);B.set(oe,nt)}return B},[g,j]),A=c.useMemo(()=>g.filter((B,ue)=>{const oe=j[ue];return oe?.isError?!la(oe.error):!1}),[g,j]),{freeText:I,tokens:F}=Ks(l.trim().toLowerCase(),f),{data:N,isFetching:q}=be({...ia({query:{query:I,limit:sS}}),enabled:I.length>0,staleTime:3e4}),Q=c.useMemo(()=>{const B=ml(P?.items??[]).map(Gn);return(I?O0(B.filter(oe=>pd(oe,I)),ml(N?.items??[]).map(Gn)):B).filter(oe=>(p==="all"||oe.accountId===p)&&Ao(oe,F))},[P,N,p,I,F]),{bodyRows:ae,briefSpamOffer:U}=c.useMemo(()=>{if(!I)return{bodyRows:Q,briefSpamOffer:void 0};const B=Q.map(ne=>Sa(ne,m)),{spam:ue}=lo(B);if(ue.length===0)return{bodyRows:Q,briefSpamOffer:void 0};const oe=new Set(ue.map(ne=>ne.id));return{bodyRows:Q.filter(ne=>!oe.has(ne.id)),briefSpamOffer:xd(B)}},[Q,I,m]),z=c.useMemo(()=>P0(ae),[ae]),ee=c.useMemo(()=>g.length<=1?[]:[{id:"all",label:"All",active:p==="all"},...g.map(B=>({id:B.accountId,label:B.email.split("@")[0]??B.email,count:T.get(B.accountId),active:p===B.accountId}))],[g,T,p]),me=c.useMemo(()=>e.filter(B=>B.muted?.value).length,[e]),fe=c.useMemo(()=>Array.from(T.values()).reduce((B,ue)=>B+ue,0),[T]),se=c.useMemo(()=>Q.filter(B=>(b==="all"||B.category===b)&&vm(B,w)).map(B=>Sa(B,m)),[Q,b,w,m]),{hits:W,isLoading:pe}=hd(),ve=c.useMemo(()=>{const B=new Map;for(const oe of P?.items??[])B.set(oe.messageId,oe.threadId);const ue=se.map(oe=>B.get(oe.id)).filter(oe=>oe!=null);return gd(W,ue,m)},[W,se,P,m]),Ne=c.useMemo(()=>{const B=qg(ee.map(ue=>({id:ue.id,label:ue.label,count:ue.count,active:ue.active})));return{categories:B.categories,filters:B.filters,sources:B.sources,sourcesNote:me>0?`+${me} muted`:void 0,selectedCategory:b,activeFilters:w,expanded:k,onExpandedChange:M,onSelectCategory:ue=>S(ue),onSelectSource:y,onToggleFilter:ue=>O(ue),onClear:()=>{S("all"),y("all"),C()}}},[ee,me,b,w,k,O,C]),we=z.length===0&&p==="all"&&I.length===0&&F.length===0,X=c.useMemo(()=>g.map(B=>B.accountId),[g]),H=c.useMemo(()=>g.some(B=>id(B.syncPhase)),[g]),ie=h0(X,we||H),ge=r.jsxs("div",{className:"h-full overflow-y-auto",children:[r.jsx(yl,{}),r.jsx(yl,{})]}),ze=!E&&!L&&!we,xe=ze?r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[U&&r.jsx(Fc,{count:U.count,onScopeToSpam:()=>v({to:"/mail/$mailboxId",params:{mailboxId:U.mailboxId},search:{q:l||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}),r.jsx("div",{className:"min-h-0 flex-1",children:r.jsx(Al,{sections:z,briefCategory:b,Row:Lo,selectedThreadId:t,onSelectThread:s,onSelectBriefCategory:S,sources:ee,sourcesNote:me>0?`+${me} muted`:void 0,onSelectSource:y,activeFilters:w,onToggleFilter:O,onClearFilters:C,hideChrome:R})})]}):E?ge:L?r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[r.jsx(ds,{className:"size-8 text-danger"}),r.jsx("p",{children:"Couldn't load your messages"}),r.jsxs("button",{type:"button",onClick:()=>D(),className:"flex items-center gap-1 text-accent underline text-xs",children:[r.jsx(bc,{className:"size-3.5"}),"Try again"]})]}):ie.resolved?r.jsx(ng,{sync:ie.syncing?{synced:ie.synced,total:ie.total}:void 0}):ge;return r.jsx(Gl,{hasSheet:ze&&!R,children:r.jsx(Nd,{selectedMessageId:t,onOpen:(B,ue)=>s?.(B,ue),onDeleteMessages:i,onSelectionVerb:h.start,wizardOpen:h.isOpen,commandsRef:a,onTriageContextChange:o,children:r.jsx(aS,{wizard:h,header:{title:"Daily brief",unreadCount:fe,footer:d?r.jsx(Cc,{}):void 0,searchFilter:Ne,searchResults:se,searchLoading:E||q,relatedResults:ve,relatedLoading:pe,onSelectSearchResult:n,searchResultsInBody:!0},rows:Q,children:r.jsxs("div",{className:"flex h-full flex-col",children:[A.map(B=>r.jsx(nS,{accountEmail:B.email,accountId:B.accountId},B.accountId)),r.jsx("div",{className:"min-h-0 flex-1",children:xe})]})})})})}const iS=10,Ad=e=>({q:e?.toLowerCase()??"",limit:iS}),lS=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(n=>n.normalizedEmail===s)};function cS(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Un(t,{month:"short",year:"numeric"})}function Od(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const uS="We can't verify the sender of this email, which could mean it's from an insecure source.",dS="We couldn't read this sender's address, so we can't confirm who really sent this message.";function fS(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?cS(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Od(e.fromEmail)}}function mS(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 hS(e,t){const s=t>0?t:void 0;if(Od(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:dS,similarCount:s};const n=e.authenticity;if(!n)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:uS};if(!n.dkimMismatch)return{verdict:"aligned",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,summary:n.dkimDomain?`We verified this message was really sent by ${n.fromDomain}.`:"Nothing looks unusual about this sender."};const a=n.fromDomain,o=n.dkimDomain,i=e.fromName&&e.fromName!==e.fromEmail?e.fromName:void 0,l=i?`The display name claims "${i}", but this message was actually sent from ${o??"another sender"} — not ${a}. Real senders use their own address.`:`This message claims to be from ${a}, but it was actually sent from ${o??"a different sender"}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:l,similarCount:s}}function Pd(e,t){const s=e?.fromEmail??null,n=e?.subject??"",{data:a,error:o}=be({...tr({query:Ad(s??void 0)}),enabled:!!s,staleTime:3e4}),i=lS(a?.items,s??void 0),l=[n,s].filter(Boolean).join(" "),{data:u,isLoading:m,error:f}=be({...Vl({query:{query:l,limit:5}}),enabled:!!(e&&l.length>3),staleTime:6e4,retry:1});return{data:c.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(b=>b.messageId!==e.messageId).map(b=>({id:b.messageId,mailboxId:t!=null&&b.mailboxIds.includes(t)?t:b.mailboxIds[0]??"",fromName:b.fromName??"",subject:b.subject??"(No subject)",timeLabel:b.sentDate!=null?ht(b.sentDate*1e3):"",matched:b.matchedChunkType})),v=fS(e,i),g=hS(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},y=mS(i);return{sender:v,authenticity:g,category:p,flags:y,similar:h}},[e,i,u,t]),isSimilarLoading:m,similarError:f,similarErrorIsFatal:la(f),addressErrorIsFatal:la(o),addressId:i?.addressId,address:i}}function pS(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 Dd({addressId:e,senderEmail:t}){const s=Me(),{pushError:n}=st(),a=ym({query:Ad(t)}),{mutate:o,isPending:i}=Fe({...Wl(),onMutate:async u=>{const m=u.body.flags??{};await s.cancelQueries({queryKey:a});const f=s.getQueryData(a);return s.setQueryData(a,d=>d&&{...d,items:d.items.map(h=>h.addressId===u.path.addressId?{...h,flags:pS(h.flags,m)}:h)}),{previous:f}},onError:(u,m,f)=>{f?.previous!==void 0&&s.setQueryData(a,f.previous),n({title:"Couldn't update sender preference",detail:mt(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){Yl(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 gS=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Ld=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function xS(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function bS(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function vS(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Fd(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const yS=["personal","newsletter","marketing","automated","transactional","social"],wS=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:n}=e;return t?s&&t===s?n?"notSpam":null:s?"markSpam":null:null},SS=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:n}=e;return t&&!s?"error":n?"loading":"ready"};function kS(){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(Tt,{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 jS({isOpen:e,current:t,onSelect:s,onCancel:n}){return e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:n,children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),r.jsx("div",{className:"mt-4 flex flex-col gap-1",children:yS.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 CS({thread:e,onClose:t,mailboxId:s,accountId:n,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:m}=Pd(e,s),[f,d]=c.useState(!1),[h,v]=c.useState(!1),g=e.fromEmail??void 0,{updateFlags:p,isPending:y}=Dd({addressId:i,senderEmail:g}),{junkMailboxId:b}=zs(n),{inboxMailboxId:S}=ko(n),{moveMessages:w}=cs({mailboxId:s??"",threadId:e.threadId,accountId:n}),x=pn(),k=wS({mailboxId:s,junkMailboxId:b,inboxMailboxId:S}),M=c.useCallback(()=>{S&&w([e.messageId],S)},[S,w,e.messageId]),O=c.useCallback(()=>{b&&(Fd(x,{count:1,senderTrust:e.senderTrust,wasRescuable:Ld(e)}),w([e.messageId],b))},[b,w,e,x]),C=c.useCallback(()=>{},[]),R=c.useCallback(()=>{const N=o?.flags?.vip!==!0;p({vip:{value:N}})},[o?.flags?.vip,p]),P=c.useCallback(()=>{const N=o?.flags?.muted!==!0;p({muted:{value:N}})},[o?.flags?.muted,p]),E=c.useCallback(()=>{o?.flags?.blocked===!0?p({blocked:{value:!1}}):d(!0)},[o?.flags?.blocked,p]),L=c.useCallback(()=>{d(!1),p({blocked:{value:!0}})},[p]),D=c.useCallback(()=>{const N=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:N}})},[o?.flags?.unsubscribed,p]),j=c.useCallback(N=>{v(!1),p({category:{value:N}})},[p]),T=i!==void 0,A={onToggleVip:T?R:void 0,onToggleMute:T?P:void 0,onToggleBlock:T?E:void 0,onToggleUnsubscribe:T?D:void 0,onReclassify:T?()=>v(!0):void 0,onNotSpam:k==="notSpam"?M:void 0,onMarkSpam:k==="markSpam"?O:void 0},I=({mailboxId:N,messageId:q,className:Q,ariaLabel:ae,children:U})=>r.jsx(Kt,{to:"/mail/$mailboxId",params:{mailboxId:N},search:z=>({...z,selectedMessageId:q}),className:Q,"aria-label":ae,children:U});if(!o)return r.jsx(kS,{});const F=SS({similarError:u,similarErrorIsFatal:m,isSimilarLoading:l});return r.jsxs(r.Fragment,{children:[r.jsx(Sc,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:C,actions:A,similarState:F,similarLinkComponent:I,className:"border-l-0 h-full w-full"}),r.jsx(Za,{isOpen:f,title:"Block this sender?",description:`Messages from ${g??"this sender"} will never load images and will be flagged. You can undo this in Settings → Senders.`,confirmLabel:"Block sender",destructive:!0,isBusy:y,onConfirm:L,onCancel:()=>d(!1)}),r.jsx(jS,{isOpen:h,current:o.category.value,onSelect:j,onCancel:()=>v(!1)})]})}const Us=({onClose:e,thread:t,mailboxId:s,accountId:n,hideCloseButton:a})=>t?r.jsx(CS,{thread:t,onClose:e,mailboxId:s,accountId:n,hideCloseButton:a}):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(Tt,{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(Tt,{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."})]})]}),ta="Open a message first",$o=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:n,onReply:a,onReplyAll:o,onForward:i,onDelete:l,canDelete:u,onToggleStar:m,isStarred:f,moveContext:d})=>{const[h,v]=c.useState(null),g=u??e,p=y=>()=>v(y);return r.jsx(bp,{hasThread:e,isStarred:f,onUnavailable:y=>v(ta),unavailableHint:h,replyTitle:`Reply ${Es("reply")}`,replyAllTitle:`Reply all ${Es("replyAll")}`,forwardTitle:`Forward ${Es("forward")}`,deleteTitle:`Move to Trash ${Es("delete")}`,flagTitle:`Star ${Es("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:g?l:p(ta),onToggleStar:m,onMove:p(ta),moveSlot:d?r.jsx(To,{accountId:d.accountId,currentMailboxId:d.currentMailboxId,onMove:d.onMove,label:"Move to mailbox"}):void 0,children:r.jsx(xp,{open:t,enabled:s,onToggle:n})})},$d=()=>{const e=Me();return c.useCallback(t=>{const s=hs({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])},dn=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=t??e?.mailboxId,o=s??e?.accountId,{accountId:i}=yo(o?void 0:a),l=o??i,u=$d(),{deleteMessages:m}=us({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:n}),{moveMessages:f}=cs({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:n}),{toggleStar:d}=wo({threadId:e?.threadId??"",mailboxId:a??""}),h=c.useCallback(()=>{e&&m(u(e))},[e,u,m]),v=c.useCallback(S=>{e&&f(u(e),S)},[e,u,f]),g=c.useCallback(()=>{e&&d(e.messageId,e.hasStars)},[e,d]),[p,y]=c.useState(null),b=c.useCallback(()=>y(null),[]);return{mailboxId:a,accountId:l,isStarred:e?.hasStars,deleteThread:h,moveThread:v,toggleStar:g,composeRequest:p,requestCompose:y,clearComposeRequest:b}},Xs={action:null,nextPrefix:null,preventDefault:!1},NS={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},ES={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 IS(e,t){const s=e.key.toLowerCase(),n=e.metaKey||e.ctrlKey;if(e.inEditable)return{...Xs,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...Xs,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{...Xs,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=NS[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=ES[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?Xs:{action:a.action,nextPrefix:null,preventDefault:!0}}return Xs}function TS(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const RS="data-message-row",MS='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function AS(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(MS);return t?!t.hasAttribute(RS):!1}function OS({handlers:e,enabled:t=!0,sequenceTimeoutMs:s=1e3}){const n=c.useRef(e);n.current=e;const a=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{if(!t)return;const i=()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},l=u=>{const m=IS({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:TS(u.target),onControl:AS(u.target)},a.current);if(i(),a.current=m.nextPrefix,m.nextPrefix!==null&&(o.current=setTimeout(()=>{a.current=null,o.current=null},s)),m.action===null)return;const f=n.current[m.action];f&&(m.preventDefault&&u.preventDefault(),f())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l),i(),a.current=null}},[t,s])}const 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]},_o=()=>{const[e,t]=c.useState(void 0),[s,n]=c.useState([]),[a,o]=c.useState([]),i=c.useRef(null),[l,u]=c.useState(!1),[m,f]=c.useState(!1),d=c.useCallback(h=>{t(h.focusedMessageId),n(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),f(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:d,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:l,blocksKeyboard:m}},zo=({context:e,orderedIds:t,selectedMessageId:s,enabled:n=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:l,blocksKeyboard:u}=e,m=c.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return OS({enabled:n&&!u,handlers:{...l?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:m,...o}}),{goBack:m,nextMessageId:wl(t,s,"next")??void 0,previousMessageId:wl(t,s,"previous")??void 0}};function PS(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function _d(e,t){if(e)return PS(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const zd=c.createContext(null);function Nr(){const e=c.useContext(zd);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function DS({selectedMessageId:e,children:t}){const s=Ke(),{searchInput:n}=Ae(),{selectedThreadId:a,selectedMailboxId:o}=Os({strict:!1}),{data:i}=be({...ia(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(R=>R.messageId===e)},[i,e]),u=c.useMemo(()=>_d(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),m=c.useCallback((R,P)=>{s({to:"/mail",search:E=>({...E,selectedMessageId:R,selectedThreadId:void 0,selectedMailboxId:void 0}),replace:P?.replace})},[s]),f=c.useCallback(R=>{s({to:"/mail",search:P=>({...P,q:n||void 0,selectedMessageId:R.id,selectedThreadId:R.threadId,selectedMailboxId:R.mailboxId})})},[s,n]),d=c.useCallback(R=>{e&&R.includes(e)&&s({to:"/mail",search:P=>({...P,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=dn({thread:l,onAfterOptimisticRemove:d}),v=c.useCallback(()=>{s({to:"/mail",search:R=>({...R,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),g=_o(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:y}=us({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:d}),{toggleReadFor:b}=yr({mailboxId:l?.mailboxId??"",messages:p}),S=g.focusedMessageId,x=c.useMemo(()=>i?.items.find(R=>R.messageId===S),[i,S])??l,k=dn({thread:x}),{nextMessageId:M,previousMessageId:O}=zo({context:g,orderedIds:g.orderedIds,selectedMessageId:e,onClose:v,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{g.listCommandsRef.current?.requestVerb("delete")||k.deleteThread()},toggleStar:k.toggleStar,toggleRead:()=>{g.listCommandsRef.current?.requestVerb("markRead")||x&&b([x.messageId],!x.isRead)},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),C={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:m,onSelectSearchResult:f,onCloseThread:v,actions:h,triage:g,onDeleteMessages:y,nextMessageId:M,previousMessageId:O};return r.jsx(zd.Provider,{value:C,children:t})}function Bd(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:n,onDeleteMessages:a}=Nr(),{accounts:o}=Ae();return r.jsx(oS,{accounts:o,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:n.listCommandsRef,onTriageContextChange:n.onTriageContextChange,onDeleteMessages:a})}function LS(){const{conversation:e,actions:t}=Nr(),{intelligenceOpen:s,onToggleIntelligence:n}=Ae(),a=fs()?.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($o,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(_s,{})})]})}function FS(){const{selectedThread:e}=Nr(),{onToggleIntelligence:t}=Ae();return r.jsx(Us,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function $S(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:n,nextMessageId:a,previousMessageId:o}=Nr(),{intelligenceOpen:i,onToggleIntelligence:l}=Ae();return t?r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:n,onOpenIntelligence:l,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:i}),r.jsx(xo,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:r.jsx(Us,{onClose:l,thread:e,hideCloseButton:!0})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Bd,{})})}const Js=Object.assign(DS,{List:Bd,Reading:LS,Intelligence:FS,Phone:$S}),_S=()=>qa({query:{starred:!0,order:"desc"}});function Kd(){const{data:e,isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=au({queryKey:_S(),queryFn:async({pageParam:m})=>{const{data:f}=await wm({query:{starred:!0,order:"desc",continuationToken:m},throwOnError:!0});return f},initialPageParam:void 0,getNextPageParam:m=>m.continuationToken,staleTime:6e4});return{threads:c.useMemo(()=>(e?.pages??[]).flatMap(m=>m.items??[]),[e]),isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}}const zS=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function Ud({title:e,unreadCount:t,preset:s,selectedCategory:n,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:l,onClearFilters:u,children:m,footer:f,searchResults:d,searchLoading:h,relatedResults:v,relatedLoading:g,onSelectSearchResult:p,searchResultsLabel:y,relatedResultsLabel:b,searchResultsInBody:S}){const{searchInput:w}=Ae(),x=w.trim().length>0,k={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:n,activeFilters:a,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return r.jsx(Gl,{hasSheet:!x,children:r.jsx(kd,{title:e,unreadCount:t,footer:f,searchFilter:k,searchResults:d,searchLoading:h,relatedResults:v,relatedLoading:g,onSelectSearchResult:p,searchResultsLabel:y,relatedResultsLabel:b,searchResultsInBody:S,children:r.jsx(Ll,{...k,hideChrome:x,children:m})})})}const BS={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function KS({rows:e,verb:t}){const{selectedIds:s,exitSelection:n}=Do(),a=c.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(Fo,{verb:t,selection:a,crossAccount:!0,onFinished:n})}function US({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:n,onDeleteMessages:a}){const{searchQuery:o,resultFolderIndex:i}=Ae(),l=gs(),u=Xt(),m=Wa(),[f,d]=c.useState("all"),[h,v]=c.useState(new Set),g=c.useCallback(F=>{v(N=>{const q=new Set(N);return q.has(F)?q.delete(F):q.add(F),q})},[]),p=c.useCallback(()=>{d("all"),v(new Set)},[]),{threads:y,isLoading:b,isError:S,error:w,refetch:x,fetchNextPage:k,hasNextPage:M,isFetchingNextPage:O}=Kd(),{freeText:C,tokens:R}=Ks(o.trim().toLowerCase(),l),P=c.useMemo(()=>{const F=Array.from(h).map(N=>BS[N]).filter(N=>N!=null);return zS(y).map(Gn).filter(N=>(f==="all"||N.category===f)&&F.every(q=>q(N))&&(!C||pd(N,C))&&Ao(N,R))},[y,f,h,C,R]),E=c.useMemo(()=>Hg(),[]),L=c.useMemo(()=>P.map(F=>Sa(F,i)),[P,i]),D=c.useMemo(()=>P.filter(F=>!F.isRead).length,[P]),j=b?"loading":S?"error":P.length===0?"empty":"ready",T=c.useCallback(()=>{const F=za(_a());window.open(F,"_blank","noopener,noreferrer")},[]),A=Cr(),I=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(Lo,{thread:F,active:F.id===e,onClick:()=>t?.(F.id)},F.id))}),M?r.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>k(),disabled:O,children:O?"Loading…":"Load more"}):null]})});return r.jsx(Ud,{title:"Starred",unreadCount:D,preset:E,selectedCategory:f,activeFilters:h,onSelectCategory:d,onToggleFilter:g,onClearFilters:p,searchResults:L,searchLoading:b,onSelectSearchResult:F=>t?.(F.id),searchResultsInBody:!0,children:r.jsxs(Nd,{selectedMessageId:e,onOpen:(F,N)=>t?.(F,N),onDeleteMessages:a,onSelectionVerb:m.start,wizardOpen:m.isOpen,commandsRef:s,onTriageContextChange:n,children:[r.jsx(Ac,{listTitle:"Starred",sections:[{id:"flagged",threads:P}],flatList:!0,hideHeader:!0,listState:A.searchResults?"ready":j,searchQuery:C?o:void 0,errorMessage:S?Jl(w):void 0,onRetry:()=>x(),onReportError:T,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:u,selectionBar:r.jsx(bw,{title:"Starred"}),listBody:A.searchResults??(j==="ready"?I:void 0)}),r.jsx(KS,{rows:P,verb:m.verb})]})})}const qd=c.createContext(null);function Er(){const e=c.useContext(qd);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function qS({selectedMessageId:e,children:t}){const s=Ke(),{threads:n}=Kd(),a=c.useMemo(()=>{if(e)return n.find(w=>w.messageId===e)},[n,e]),o=c.useCallback((w,x)=>{s({to:"/mail/flagged",search:k=>({...k,selectedMessageId:w}),replace:x?.replace})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:w=>({...w,selectedMessageId:void 0})})},[s]),l=c.useCallback(w=>{e&&w.includes(e)&&i()},[e,i]),u=dn({thread:a,onAfterOptimisticRemove:l}),m=_o(),{deleteMessages:f}=us({mailboxId:a?.mailboxId??"",messages:n,onAfterOptimisticRemove:l}),{toggleReadFor:d}=yr({mailboxId:a?.mailboxId??"",messages:n}),h=m.focusedMessageId,g=c.useMemo(()=>n.find(w=>w.messageId===h),[n,h])??a,p=dn({thread:g}),{nextMessageId:y,previousMessageId:b}=zo({context:m,orderedIds:m.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{m.listCommandsRef.current?.requestVerb("delete")||p.deleteThread()},toggleStar:p.toggleStar,toggleRead:()=>{m.listCommandsRef.current?.requestVerb("markRead")||g&&d([g.messageId],!g.isRead)},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),S={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:m,onDeleteMessages:f,nextMessageId:y,previousMessageId:b};return r.jsx(qd.Provider,{value:S,children:t})}function Hd(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:n}=Er();return r.jsx(US,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:n})}function HS(){const{selectedThread:e,actions:t}=Er(),{intelligenceOpen:s,onToggleIntelligence:n}=Ae(),a=fs()?.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($o,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(_s,{})})]})}function WS(){const{selectedThread:e}=Er(),{onToggleIntelligence:t}=Ae();return r.jsx(Us,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function VS(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:n,previousMessageId:a}=Er(),{intelligenceOpen:o,onToggleIntelligence:i}=Ae();return e?r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:i,onSwipeNext:n?()=>s(n):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:o}),r.jsx(xo,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:r.jsx(Us,{onClose:i,thread:e,hideCloseButton:!0})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Hd,{})})}const Zs=Object.assign(qS,{List:Hd,Reading:HS,Intelligence:WS,Phone:VS}),QS={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},GS=()=>{const e=c.useRef(!1);return c.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector("[data-slate-editor]")?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},YS=()=>{const{state:e,closeCompose:t}=Yt(),s=GS(),[n,a]=c.useState(!1),{isError:o,error:i,refetch:l}=be({...Mt(),staleTime:1/0}),u=c.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),m=c.useCallback(()=>{a(!1),t()},[t]),f=c.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const d=QS[e.mode]??"New Message";return r.jsxs(ft.Root,{open:e.isOpen,onOpenChange:u,children:[r.jsxs(ft.Portal,{children:[r.jsx(ft.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(ft.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[r.jsx(ft.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),r.jsx(ft.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:d}),o?r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(Jt,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):r.jsx("div",{className:"flex-1 overflow-hidden",children:r.jsx(bo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),n&&r.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50",children:r.jsxs("div",{className:"mx-4 w-full max-w-sm rounded-xl bg-canvas p-6 shadow-xl",children:[r.jsx("h3",{className:"text-lg font-semibold",children:"Discard draft?"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Your message has unsaved content. Are you sure you want to discard it?"}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx("button",{type:"button",onClick:f,className:"rounded-md px-4 py-2 text-sm font-medium hover:bg-surface-raised transition-colors",children:"Keep editing"}),r.jsx("button",{type:"button",onClick:m,className:"rounded-md bg-danger px-4 py-2 text-sm font-medium text-canvas hover:bg-danger/90 transition-colors",children:"Discard"})]})]})})]})},XS={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Wd=()=>{const{state:e,closeCompose:t}=Yt(),s=Xt(),{isError:n,error:a,refetch:o}=be({...Mt(),staleTime:1/0});if(!s)return r.jsx(YS,{});if(!e.isOpen)return null;const i=XS[e.mode]??"New Message",l=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(jt,{className:"size-5"})})]});return n?r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[l,r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(Jt,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):r.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[l,r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:r.jsx(bo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function JS(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:ht(e.updatedAt),isRead:!0}}function ZS(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:ht(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function ek({outboxMessages:e,accountId:t,imapThreads:s}){const n=e.filter(i=>i.status==="draft"&&i.accountId===t).map(JS),a=s.map(ZS),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 Bo(){const e=fs();return!e||e.showNavPane?null:r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(or,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const tk=({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})]}),sk=({row:e,isSelected:t,onOpen:s,onDelete:n,isDeleting:a})=>r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:V("group",$s({active:t})),children:[r.jsx(Dl,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),r.jsx(ln,{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(Rt,{className:"size-3.5"})})})]}),nk=({row:e,isSelected:t,onOpen:s})=>{const n=!e.isRead;return r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:V("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(kt,{name:e.fromName,email:e.fromEmail,size:"sm"}),r.jsx(ln,{thread:e})]})};function rk({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:n,title:a,unreadCount:o}){const{openCompose:i,state:l}=Yt(),u=Ke(),m=Me(),{data:f}=be(er()),d=c.useMemo(()=>ek({outboxMessages:f?.items??[],accountId:t,imapThreads:n}),[f?.items,t,n]),h=Fe({...sr(),onSuccess:()=>{m.invalidateQueries({queryKey:Va()})}}),v=b=>{h.mutate({path:{outboxMessageId:b}})},g=b=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:b})},p=b=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:b}})},y=d.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(Bo,{}),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:y?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[r.jsx(Ra,{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."})]}):d.map(b=>r.jsxs("div",{children:[b.label&&r.jsx(tk,{label:b.label,count:b.threads.length}),r.jsx("div",{className:"divide-y divide-line",children:b.threads.map(S=>b.id==="remit-drafts"?r.jsx(sk,{row:S,isSelected:l.isOpen&&S.id===l.outboxMessageId,onOpen:g,onDelete:v,isDeleting:h.isPending},S.id):r.jsx(nk,{row:S,isSelected:S.id===s,onOpen:p},S.id))})]},b.id))})]})}function ak(e,t,s){const n=new Array(e);return new Proxy(n,{get(a,o,i){if(typeof o=="string"){const l=o.charCodeAt(0);if(l>=48&&l<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let m=a[u];if(!m){const f=t[u*2];m=a[u]={index:u,key:s(u),start:f,size:t[u*2+1],end:f+t[u*2+1],lane:0}}return m}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function Ns(e,t,s){let n=s.initialDeps??[],a,o=!0;function i(){const l=e();return(l.length!==n.length||l.some((m,f)=>n[f]!==m))&&(n=l,a=t(...l),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=l=>{n=l},i}function Sl(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const ok=(e,t)=>Math.abs(e-t)<1.01,ik=(e,t,s)=>{let n;return function(...a){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,a),s)}};let en;const sa=()=>{if(en!==void 0)return en;if(typeof navigator>"u")return en=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return en=!0;const e=navigator.maxTouchPoints;return en=navigator.platform==="MacIntel"&&e!==void 0&&e>0},kl=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},lk=e=>e,ck=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},uk=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const a=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(a(kl(s)),!n.ResizeObserver)return()=>{};const o=new n.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u?.borderBoxSize){const m=u.borderBoxSize[0];if(m){a({width:m.inlineSize,height:m.blockSize});return}}a(kl(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},Yn={passive:!0},dk=typeof window>"u"?!0:"onscrollend"in window,fk=(e,t,s)=>{const n=e.scrollElement;if(!n)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&dk;let i=0;const l=o?null:ik(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=d=>()=>{i=s(n),l?.(),t(i,d)},m=u(!0),f=u(!1);return n.addEventListener("scroll",m,Yn),o&&n.addEventListener("scrollend",f,Yn),()=>{n.removeEventListener("scroll",m),o&&n.removeEventListener("scrollend",f)}},mk=(e,t)=>fk(e,t,s=>{const{horizontal:n,isRtl:a}=e.options;return n?s.scrollLeft*(a&&-1||1):s.scrollTop}),hk=(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"]},pk=(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=pk;class xk{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 l=o.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[m,f]of this.elementsCache)if(f===l){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=n())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=n())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=n())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var n,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:lk,rangeExtractor:ck,onChange:()=>{},measureElement:hk,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 l=null,u=null,m=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,v=o.count,g=this.getMeasurements(),p=h>0?((n=g[0])==null?void 0:n.key)??i.getItemKey(0):null,y=h>0?((a=g[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(v!==h||h>0&&v>0&&(o.getItemKey(0)!==p||o.getItemKey(v-1)!==y)){m=!0;const w=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??g[0]:null;w&&(l=[w.key,this.getScrollOffset()-w.start]);const x=o.followOnAppend===!0?"auto":o.followOnAppend||null;x&&v>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(v-1)!==y)&&(u=x)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let f=!1,d=0;if(l&&this.scrollOffset!==null){const[h,v]=l,g=this.getMeasurements(),{count:p,getItemKey:y}=this.options;let b=0;for(;b<p&&y(b)!==h;)b++;if(b<p){const S=g[b];if(S){const w=S.start+v;w!==this.scrollOffset&&(d=w-this.scrollOffset,this.scrollOffset=w,f=!0)}}}(f||u)&&(this.pendingScrollAnchor=[f?l[0]:null,f?l[1]:0,u,d])},this.notify=s=>{var n,a;(a=(n=this.options).onChange)==null||a.call(n,this,s)},this.maybeNotify=Ns(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}if(this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===o?this.scrollDirection:l<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!sa()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,Yn),o.addEventListener("touchend",l,Yn),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,l,u]=a;o!==null&&!l&&(sa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),n=this.getMaxScrollOffset();if(s<0||s>n)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=Ns(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,n,a,o,i,l,u,m)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:m}),{key:!1}),this.getMeasurements=Ns(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:m},f)=>{const d=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const b of this.laneAssignments.keys())b>=s&&this.laneAssignments.delete(b);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(b=>{this.itemSizeCache.set(b.key,b.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),l===1){const b=s*2;let S=this._flatMeasurements;if(!S||S.length<b){const k=new Float64Array(b);S&&h>0&&k.set(S.subarray(0,h*2)),S=k,this._flatMeasurements=S}let w;if(h===0)w=n+a;else{const k=h-1;w=S[k*2]+S[k*2+1]+m}for(let k=h;k<s;k++){const M=o(k),O=d.get(M),C=typeof O=="number"?O:this.options.estimateSize(k);S[k*2]=w,S[k*2+1]=C,w+=C+m}const x=ak(s,S,o);return this.measurementsCache=x,x}const v=this.measurementsCache.slice(0,h),g=new Array(l).fill(void 0),p=new Float64Array(l);let y=0;for(let b=0;b<h;b++){const S=v[b];S&&(g[S.lane]===void 0&&y++,g[S.lane]=b,p[S.lane]=S.end)}for(let b=h;b<s;b++){const S=o(b),w=this.laneAssignments.get(b);let x,k;const M=u==="estimate"||d.has(S);if(w!==void 0&&this.options.lanes>1){x=w;const P=g[x],E=P!==void 0?v[P]:void 0;k=E?E.end+m:n+a}else if(y===l){let P=0,E=p[0],L=g[0];for(let D=1;D<l;D++){const j=p[D];(j<E||j===E&&g[D]<L)&&(P=D,E=j,L=g[D])}x=P,k=E+m,M&&this.laneAssignments.set(b,x)}else x=b%this.options.lanes,k=n+a,M&&this.laneAssignments.set(b,x);const O=d.get(S),C=typeof O=="number"?O:this.options.estimateSize(b),R=k+C;v[b]={index:b,start:k,size:C,end:R,key:S,lane:x},g[x]===void 0&&y++,g[x]=b,p[x]=R}return this.measurementsCache=v,v},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ns(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,a,o)=>s.length===0||n===0?(this.range=null,null):(this.range=vk(s,n,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ns(()=>{let s=null,n=null;const a=this.calculateRange();return a&&(s=a.startIndex,n=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:n,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,a=s.getAttribute(n);return a?parseInt(a,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),l=Math.min(this.options.count-1,a+o);return s>=i&&s<=l}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const 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,l,u;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)u=this.options.getItemKey(s),l=m[s*2],i=m[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,l=h.start,i=h.size}const f=this.itemSizeCache.get(u)??i,d=n-f;if(d!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,v=h?this.getTotalSize():0,g=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:l,size:i,end:l+i,lane:0},d,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,n),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-v):g&&this.applyScrollAdjustment(d),this.notify(!1)}},this.getVirtualItems=Ns(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const l=s[o],u=n[l];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=Vd(0,n.length-1,o?l=>a[l*2]:l=>Sl(n[l]).start,s);return Sl(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 l=this.getMaxScrollOffset();return Math.max(Math.min(l,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 l=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,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,l]=o,u=this.now();this.scrollState={index:s,align:l,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior: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(l=>l===null);){const l=n[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}a=Math.max(...o.filter(l=>l!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const 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&&(sa()&&(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&&ok(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&u>l;this.scrollState.lastTargetOffset=a,m||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Vd=(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 bk(e,t,s){let n=0;for(;n<=t;){const a=(n+t)/2|0,o=e[a*2];if(o<s)n=a+1;else if(o>s)t=a-1;else return a}return n>0?n-1:0}function vk(e,t,s,n,a){const o=e.length-1;if(e.length<=n)return{startIndex:0,endIndex:o};if(n===1&&a!==null){const m=bk(a,o,s);let f=m;const d=s+t;for(;f<o&&a[f*2]+a[f*2+1]<d;)f++;return{startIndex:m,endIndex:f}}let l=Vd(0,o,m=>e[m].start,s),u=l;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(d=>d<s+t);){const d=e[u];m[d.lane]=d.end,u++}const f=Array(n).fill(s+t);for(;l>=0&&f.some(d=>d>=s);){const d=e[l];f[d.lane]=d.start,l--}l=Math.max(0,l-l%n),u=Math.min(o,u+(n-1-u%n))}return{startIndex:l,endIndex:u}}const na=typeof document<"u"?c.useLayoutEffect:c.useEffect;function yk({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...n}){const a=c.useReducer(m=>m+1,0)[1],o=c.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=m=>{const f=o.current;if(!f.enabled||!f.container)return;const d=m.getTotalSize();if(d!==f.lastSize){f.lastSize=d;const b=m.options.horizontal?"width":"height";f.container.style[b]=`${d}px`}const h=!!m.options.horizontal,v=f.mode==="transform",g=h?"left":"top",p=m.options.scrollMargin,y=m.getVirtualItems();for(const b of y){const S=b.start-p,w=m.elementsCache.get(b.key);w&&f.lastPositions.get(w)!==S&&(f.lastPositions.set(w,S),v?w.style.transform=h?`translate3d(${S}px, 0, 0)`:`translate3d(0, ${S}px, 0)`:w.style[g]=`${S}px`)}},l={...n,onChange:(m,f)=>{var d;const h=o.current;let v=!0;if(h.enabled){i(m);const g=m.range,p=h.prevRange;v=!p||p.isScrolling!==m.isScrolling||p.startIndex!==g?.startIndex||p.endIndex!==g?.endIndex,v&&(h.prevRange=g?{startIndex:g.startIndex,endIndex:g.endIndex,isScrolling:m.isScrolling}:null)}v&&(e&&f?Pa.flushSync(a):a()),(d=n.onChange)==null||d.call(n,m,f)}},[u]=c.useState(()=>{const m=new xk(l);return Object.assign(m,{containerRef:f=>{const d=o.current;if(d.container=f,d.lastSize=null,f&&d.enabled){const h=m.getTotalSize();d.lastSize=h;const v=m.options.horizontal?"width":"height";f.style[v]=`${h}px`}}})});return u.setOptions(l),na(()=>u._didMount(),[]),na(()=>u._willUpdate()),na(()=>{i(u)}),u}function wk(e){return yk({observeElementRect:uk,observeElementOffset:mk,scrollToFn:gk,...e})}const Ko=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",Sk=e=>`Select all ${Ko(e)}`,kk=(e,t)=>`All ${Vt(t)} ${Ko(e)} selected`,jk=(e,t,s)=>e==="BACK"&&t&&s===void 0,Ck=(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:ht(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:wr(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),Nk=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,messageCount:m,isMultiSelectMode:f,onLongPress:d,isDesktop:h,density:v})=>r.jsx(Lo,{thread:Ck(e,m),linkMailboxId:t,inListbox:!0,active:s,focused:n,isTabStop:a,density:v,isDesktop:h,onFocusRow:o,selection:{isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:f,onLongPress:d}}),Ek=c.memo(Nk),Ik=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:ht(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:wr(e.category),suspicious:t}},Tk=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:m,onLongPress:f,isDesktop:d,onDelete:h,onToggleRead:v,density:g})=>{const[p,y]=c.useState("none"),b=Ke(),S=c.useCallback(M=>{navigator.vibrate?.(10),M==="trailing"?h(e.messageId):v(e.messageId,e.isRead),y("none")},[h,v,e.messageId,e.isRead]),w=c.useCallback(()=>{f(e.messageId)},[f,e.messageId]),x=c.useCallback(()=>{l(e.messageId)},[l,e.messageId]),k=c.useCallback(()=>{b({to:"/mail/$mailboxId",params:{mailboxId:t},search:M=>({...M,selectedMessageId:e.messageId})})},[b,t,e.messageId]);return d||m?r.jsx(Ek,{thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:m,onLongPress:f,isDesktop:d,density:g}):r.jsx(Mc,{thread:Ik(e),selectionMode:!1,checked:!1,active:s,peek:p,onPeek:y,onToggleCheck:x,onLongPress:w,onOpen:k,onAct:S})},Rk=72,Mk=32,Ak=5,Qd="remit:list-density",Ok=()=>{try{const e=localStorage.getItem(Qd);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},Pk=({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(Zn,{className:"size-4 text-fg-muted"}),r.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),Dk=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:n,isError:a=!1,error:o,onRetry:i,searchQuery:l,searchPredicate:u,onDeleteMessages:m,isDeleting:f=!1,isMoving:d=!1,onLoadMore:h,hasMore:v=!1,isLoadingMore:g=!1,accountId:p,listTitle:y,listMeta:b,listFilter:S,listScopeLabel:w,onTriageContextChange:x,commandsRef:k,hideHeader:M=!1})=>{const O=c.useRef(null),C=Ke(),R=Xt(),P=Wa(),{verb:E,start:L,startFromSearch:D}=P,j=Sm(),T=!!l?.trim(),A=Cr(),{labels:I}=Ja(p),{pushError:F}=st(),[N,q]=c.useState(s),[Q,ae]=c.useState(),U=c.useCallback($=>{ae(re=>re===$?re:void 0),q($)},[]),[z,ee]=c.useState(Ok),me=c.useCallback(()=>{ee($=>{const re=$==="comfortable"?"compact":"comfortable";try{localStorage.setItem(Qd,re)}catch{}return re})},[]),{toggleReadFor:fe}=yr({mailboxId:e}),{junkMailboxId:se}=zs(p),{selectedIds:W,selectedCount:pe,hasSelection:ve,isSelected:Ne,toggle:we,select:X,clearSelection:H,selectRange:ie,setAnchor:ge,selectAll:ze,toggleAll:xe,intersectWith:B}=jc(),ue=no(pe,R),[oe,ne]=c.useState(null),nt=T&&!!u,Te=`${e}|${JSON.stringify(u??{})}`,J=Rd({mailboxId:e,accountId:p,enabled:nt,predicateKey:Te,searchQuery:u??{}}),Se=c.useCallback(($,re,yt)=>{if(yt.error===void 0){if(yt.cancelled){F({severity:"warning",title:Ow(yt.done),detail:Pw($,yt.done,re)});return}F({severity:"info",title:xl($,yt.done)})}},[F]),Ve=J.phase.kind,Oe=J.clear,he=c.useCallback(()=>{Ve==="escalated"&&Oe(),H()},[H,Oe,Ve]),[lt,Xe]=c.useState(null),Pe=c.useRef(null),Ue=c.useRef(!1),qe=c.useRef(null),Ze=!n&&t.length>0,rt=oe!==null,je=wk({count:t.length,getScrollElement:()=>O.current,estimateSize:()=>z==="compact"?Mk:Rk,overscan:Ak}),G=s?t.findIndex($=>$.messageId===s):-1,te=N?t.findIndex($=>$.messageId===N):-1,ce=c.useCallback($=>{if($<0||$>=t.length)return;const re=t[$];if(ue){we(re.messageId);return}Pe.current=re.messageId,Ue.current=!1,ae(re.messageId),q(re.messageId)},[t,ue,we]),de=c.useCallback(()=>{if(t.length===0)return;const $=te<0?0:Math.min(te+1,t.length-1);ce($)},[t.length,te,ce]),ke=c.useCallback(()=>{if(t.length===0)return;const $=te<=0?0:te-1;ce($)},[t.length,te,ce]),Ee=c.useCallback(()=>ce(0),[ce]),De=c.useCallback(()=>ce(t.length-1),[ce,t.length]),He=c.useCallback(()=>{N&&we(N)},[N,we]),ye=c.useMemo(()=>t.map($=>$.messageId),[t]),Qe=c.useMemo(()=>{const $=[];for(const re of t)W.has(re.messageId)&&$.push({id:re.messageId,sender:re.fromName??re.fromEmail??"Unknown",email:re.fromEmail??"",subject:re.subject??"(No subject)",date:ht(re.sentDate)});return $},[t,W]),Ge=c.useCallback(($,re)=>re.shiftKey?(ie(ye,$,N),!0):re.metaKey||re.ctrlKey?(we($),!0):(he(),ge($),!1),[ye,N,ie,we,he,ge]),Le=c.useCallback($=>{!m||$.length===0||(qe.current=N??null,ne($))},[m,N]),et=c.useCallback($=>{const re=kc(ye,N,$);re!==void 0&&(ie(ye,re),Pe.current=re,Ue.current=!1,ae(void 0),q(re))},[ye,N,ie]),Ye=c.useCallback(()=>et(-1),[et]),Dt=c.useCallback(()=>et(1),[et]),es=c.useCallback(()=>{ye.length>0&&ze(ye)},[ye,ze]),Lt=c.useCallback($=>oe!==null?!0:ve?(L($),!0):$!=="delete"||!m||!N?!1:(Le([N]),!0),[oe,m,ve,L,N,Le]),xs=c.useCallback(()=>{N&&C({to:"/mail/$mailboxId",params:{mailboxId:e},search:$=>({...$,selectedMessageId:N})})},[N,C,e]),tt=c.useCallback($=>{C({to:"/mail/$mailboxId",params:{mailboxId:e},search:re=>({...re,selectedMessageId:$}),replace:!0})},[C,e]);jd({keyboardFocusedMessageId:Q,openMessageId:s,enabled:R&&pe===0,open:tt});const xt=J.phase.kind==="escalated"?{scope:Ko(u??{}),total:J.phase.total,searchQuery:u??{},run:$=>J.runAction($),stop:J.stop}:void 0,Ft=c.useCallback(()=>{if(!oe)return;const $=oe;if($.length===0){ne(null);return}const re=new Set($),yt=t.findIndex(Je=>re.has(Je.messageId));let Nt;for(let Je=yt+1;Je<t.length;Je++)if(!re.has(t[Je].messageId)){Nt=t[Je].messageId;break}if(Nt===void 0){for(let Je=yt-1;Je>=0;Je--)if(!re.has(t[Je].messageId)){Nt=t[Je].messageId;break}}m?.($),he(),qe.current=null,ne(null),Nt!==void 0&&(Pe.current=Nt,Ue.current=!1,U(Nt),R&&C({to:"/mail/$mailboxId",params:{mailboxId:e},search:Je=>({...Je,selectedMessageId:Nt}),replace:!0})),R||Xe(xl("delete",$.length))},[oe,t,m,he,C,e,R,U]),ct=c.useCallback(()=>{const $=qe.current;qe.current=null,ne(null),$!==null&&(Pe.current=$,Ue.current=!1,U($))},[U]),$t=c.useMemo(()=>{if(pe===0)return;const $=new Set;for(const re of t)W.has(re.messageId)&&$.add(re.accountConfigId);if($.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[pe,W,t]),qs=c.useCallback(()=>{if(xt){D();return}L("organize")},[xt,D,L]),Hs=c.useCallback($=>{m?.([$])},[m]),Ct=c.useCallback(($,re)=>{fe([$],!re)},[fe]),ts=c.useCallback($=>{R||X($)},[R,X]),_=c.useCallback(()=>{if(J.isRunning||J.phase.kind==="counting"){J.stop();return}he()},[J,he]),Y=c.useCallback(()=>{J.clear()},[J]);c.useEffect(()=>{if(Ue.current||!R&&s)return;const $=te>=0?te:G;$>=0&&je.scrollToIndex($,{align:"auto"})},[te,G,je,R,s]),c.useEffect(()=>{s&&(Ue.current=!1,U(s))},[s,U]),c.useEffect(()=>{N&&(t.some($=>$.messageId===N)||U(t[0]?.messageId))},[t,N,U]),c.useEffect(()=>{x?.({focusedMessageId:N,selectedIds:Array.from(W),hasList:Ze,blocksKeyboard:rt||P.isOpen})},[N,W,Ze,rt,P.isOpen,x]);const Ce=c.useRef(x);Ce.current=x,c.useEffect(()=>()=>Ce.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{J.phase.kind!=="idle"||J.isRunning||B(t.map($=>$.messageId))},[t,B,J.phase,J.isRunning]);const ut=c.useRef(e);c.useEffect(()=>{ut.current!==e&&(ut.current=e,he())},[e,he]),ou({shouldBlockFn:({action:$})=>jk($,ve,j)?(he(),!0):!1,enableBeforeUnload:!1,disabled:!ve||j!==void 0}),c.useEffect(()=>{const $=O.current;if(!$||!v||!h)return;const re=()=>{if(g)return;const{scrollTop:yt,scrollHeight:Nt,clientHeight:Je}=$;yt+Je>=Nt-200&&h()};return $.addEventListener("scroll",re,{passive:!0}),re(),()=>$.removeEventListener("scroll",re)},[v,g,h]),c.useEffect(()=>{const $=Pe.current;if(!$)return;const re=O.current?.querySelector(`[data-message-id="${$}"]`);re&&(Pe.current=null,re.focus({preventScroll:!0}))}),c.useEffect(()=>{if(k){if(!Ze){k.current=null;return}return k.current={focusNext:de,focusPrevious:ke,focusFirst:Ee,focusLast:De,openFocused:xs,toggleSelect:He,extendSelectDown:Dt,extendSelectUp:Ye,selectAll:es,clearSelection:()=>ve?(he(),!0):!1,requestVerb:Lt,toggleDensity:me},()=>{k.current=null}}},[k,Ze,de,ke,Ee,De,xs,He,Dt,Ye,es,ve,he,Lt,me]);const bt=n?"loading":a?"error":t.length===0?"empty":"ready",vt=a?Jl(o):void 0,ss=c.useCallback(()=>{const $=za(_a());window.open($,"_blank","noopener,noreferrer")},[]),kn=[{id:"inbox",threads:[]}],bs=ye.length>0&&ye.every($=>W.has($)),Tr=nt&&v&&bs&&!f&&!d&&J.phase.kind==="idle"&&!J.isRunning,Rr=f||d||J.isRunning,Ws=J.phase.kind==="escalated"?J.phase.total:pe,Mr=J.runningAction?Aw(J.runningAction.kind,J.progress?.done??0,J.progress?.total??Ws):J.phase.kind==="counting"?"Counting matches…":J.phase.kind==="escalated"?kk(u??{},J.phase.total):void 0,Ar=J.phase.kind!=="escalated"&&ye.length>0?{checked:bs,indeterminate:pe>0&&!bs,onChange:()=>xe(ye)}:void 0,Z=J.runningAction?{value:J.progress?.done??0,max:J.progress?.total??Ws,tone:Fw(J.runningAction.kind)}:void 0,at=(J.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:J.stop}}:J.phase.kind==="escalated"&&!J.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:Y}}:Tr?{tone:"info",text:"",action:{label:Sk(u??{}),onClick:J.escalate}}:void 0)??($t?{tone:"warning",text:$t}:void 0),of=r.jsx(uo,{title:A.title||y,navSlot:A.navSlot,titleMeta:A.titleMeta,searchSlot:A.searchSlot,searchField:A.searchField,idleSlot:A.makeFilterSlot,count:Ws,onCancel:_,onDelete:()=>L("delete"),onMove:()=>L("move"),onOrganize:qs,onJunk:se&&se!==e?()=>L("junk"):void 0,onMarkRead:()=>L("markRead"),overflowSlot:p&&e&&pe>0&&I.length>0?r.jsx(bd,{accountId:p,mailboxId:e,messageIds:Array.from(W)}):void 0,isBusy:Rr,isCounting:J.phase.kind==="counting",selectAll:Ar,statusLabel:Mr,progress:Z,notice:at}),lf=Cd(ye,N),cf=c.useCallback($=>{Ue.current=!0,U($)},[U]),uf=r.jsxs(r.Fragment,{children:[T&&l&&r.jsx(Pk,{query:l}),r.jsxs("div",{ref:O,role:"listbox","aria-multiselectable":!0,"aria-label":y,className:"flex-1 overflow-y-auto",children:[r.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${je.getTotalSize()}px`},children:je.getVirtualItems().map($=>{const re=t[$.index];return r.jsx("div",{role:"presentation","data-index":$.index,ref:je.measureElement,className:_e("absolute left-0 top-0 w-full border-b border-line",J.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${$.start}px)`},children:r.jsx(Tk,{thread:re,mailboxId:e,isSelected:s===re.messageId,isFocused:N===re.messageId,isTabStop:lf===re.messageId,onFocusRow:cf,isChecked:Ne(re.messageId),onToggleCheck:we,onRowSelect:Ge,isMultiSelectMode:ue,onLongPress:ts,isDesktop:R,onDelete:Hs,onToggleRead:Ct,density:z})},$.key)})}),g&&r.jsx(op,{})]})]});return r.jsxs(r.Fragment,{children:[lt&&!R&&r.jsx(hn,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>Xe(null),children:lt}),r.jsx(Ac,{listTitle:y,listMeta:b,sections:kn,flatList:!0,listState:A.searchResults?"ready":bt,searchQuery:T?l:void 0,listFilter:S,listScopeLabel:w,errorMessage:vt,onRetry:i,onReportError:ss,density:z,selectedThreadId:s,onSelectThread:$=>C({to:"/mail/$mailboxId",params:{mailboxId:e},search:re=>({...re,selectedMessageId:$})}),onSelectBriefCategory:()=>{},isDesktop:R,hideHeader:M,selectionBar:of,listBody:A.searchResults??(bt==="ready"?uf:void 0)}),r.jsx(Za,{isOpen:oe!==null,title:ec(oe?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:f,onConfirm:Ft,onCancel:ct}),r.jsx(Fo,{verb:E,accountId:p,mailboxId:e,selection:Qe,crossAccount:$t!==void 0,escalated:xt,escalatedProgress:J.progress,onFinished:he,onRunEnded:Se})]})},Lk=e=>ms({path:{accountId:e}}),Fk=e=>{const t=Me(),s=pn(),n=Fe({...km(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:Lk(e)})}});return{trigger:()=>{n.mutate({path:{accountId:e}})},triggerAsync:()=>n.mutateAsync({path:{accountId:e}}),isPending:n.isPending,error:n.error,reset:n.reset}},$k=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:n}=Fk(e);return r.jsx(Eg,{onRefresh:s,isRefreshing:n,children:t})};function _k({accountId:e,currentMailboxId:t,candidates:s,onMove:n,children:a}){const[o,i]=c.useState(!1),l=pn(),u=Qa(),{inboxMailboxId:m}=ko(e),f=jo(e),{data:d}=be({...it({path:{accountId:e}}),staleTime:1/0}),h=c.useMemo(()=>Ga({mailboxes:d?.items??[],folderAppointments:f,currentMailboxId:t,translator:u}),[d?.items,f,t,u]),v=c.useMemo(()=>m||(h.find(S=>S.label.toLowerCase()==="inbox")?.id??h.find(S=>!S.isCurrent)?.id??""),[m,h]),g=c.useRef(!1);c.useEffect(()=>{g.current||(g.current=!0,xS(l,s.length))},[l,s.length]);const p=c.useCallback(()=>{bS(l,s.length),i(!0)},[l,s.length]),y=c.useCallback((b,S)=>{vS(l,{selected:b.length,total:s.length,toInbox:S===m}),n(b,S)},[l,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(Rg,{count:s.length,onReview:p})}),r.jsx("div",{className:"min-h-0 flex-1",children:a}),r.jsx(Bg,{open:o,candidates:s,defaultDestinationId:v,availableFolders:h,delimiter:Ya(d?.items??[]),onConfirmMove:y,onCancel:()=>i(!1)})]})}const zk="We can verify this sender";function Bk(e){const{data:t}=be({...Ql({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:zk,trustSubReason:gS(n.senderTrust),senderTrust:n.senderTrust}))}}const Kk=e=>{const t=new Set,s=[];for(const n of e)t.has(n.threadMessageId)||(t.add(n.threadMessageId),s.push(n));return s},Uk={unread:"unread",flagged:"starred",attachment:"attachments"},qk=new Set(Object.values(ot)),Gd=e=>qk.has(e),Hk=e=>Gd(e.category)||e.attributes.size>0,Wk=e=>{const t={};Gd(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const n=Uk[s];n&&(t[n]=!0)}return t},Vk=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",Qk=["category","unread","starred","attachments"],jl=e=>JSON.stringify(Qk.map(t=>e?.[t]??null)),Gk=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},Yk=(e,t)=>{const s=Gk(e);return s?jl(s)===jl(t):!1},Yd="remit:intelligence-open";function Xk(){try{return localStorage.getItem(Yd)!=="closed"}catch{return!0}}function Cl(e){try{localStorage.setItem(Yd,e?"open":"closed")}catch{}}const Jk=(e,t)=>e!==t,Zk=(e,t,s)=>{if(!(s||!t))return e.find(n=>n.messageId===t)},ej=(e,t,s,n)=>{if(e)return e;if(!(n||!s))return t?.messageId===s?t:void 0},Pn=e=>e[0],tj=e=>{const t=Pn(e.filter(l=>l.type==="from").map(l=>l.value)),s=Pn(e.filter(l=>l.type==="subject").map(l=>l.value)),n=Pn(e.filter(l=>l.type==="category").map(l=>l.category)),a=Pn(e.filter(l=>l.type==="isUnread"||l.type==="isRead").map(l=>l.type==="isUnread")),o=e.some(l=>l.type==="isStarred")?!0:void 0,i=e.some(l=>l.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}:{}}},sj=(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 nj(e,t={}){const s=tj(e),n={...s,...t};return{params:s,residual:e.filter(a=>!sj(n,a))}}function rj(e,t,s){if(t.length===0)return e;const n=[...t];return e.filter(a=>{const o=Gn(a);return Ao({...o,accountId:o.accountId??s},n)})}const aj=50,oj=new Map(Uc().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),Xd=c.createContext(null);function Ir(){const e=c.useContext(Xd);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function ij({mailboxId:e,selectedMessageId:t,children:s}){const n=Ke(),o=jr()==="desktop",i=pn(),{accounts:l,searchQuery:u,searchInput:m,intelligenceOpen:f,onToggleIntelligence:d,onSetIntelligenceOpen:h}=Ae(),v=gs(),g=Ro(u),p=g.length>0,{freeText:y,tokens:b}=Ks(g,v),[S,w]=c.useState("all"),[x,k]=c.useState(new Set),M=c.useMemo(()=>({category:S,attributes:x}),[S,x]),O=c.useMemo(()=>Wk(M),[M]),C=p||Hk(M),{params:R,residual:P}=nj(b,O),E={order:"desc",limit:aj,...y?{query:y}:{},...R,...O},L={category:E.category,unread:E.unread,starred:E.starred,attachments:E.attachments},D=C?Ua({path:{mailboxId:e},query:E}):nr({path:{mailboxId:e},query:{order:"desc"}}),{data:j,isLoading:T,isError:A,error:I,refetch:F,fetchNextPage:N,hasNextPage:q,isFetchingNextPage:Q}=au({queryKey:D,queryFn:async({pageParam:Z})=>{if(C){const{data:at}=await oa({path:{mailboxId:e},query:{...E,continuationToken:Z},throwOnError:!0});return at}const{data:dt}=await jm({path:{mailboxId:e},query:{order:"desc",continuationToken:Z},throwOnError:!0});return dt},initialPageParam:void 0,getNextPageParam:Z=>Z.continuationToken,placeholderData:(Z,dt)=>Yk(dt?.queryKey,L)?Z:void 0}),ae=c.useCallback(Z=>{t&&Z.includes(t)&&n({to:"/mail/$mailboxId",params:{mailboxId:e},search:dt=>({...dt,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,n]),{deleteMessages:U,isPending:z}=us({mailboxId:e,onAfterOptimisticRemove:ae}),{accountId:ee}=yo(e),me=bu({accounts:l}),{moveMessages:fe,isPending:se}=cs({mailboxId:e,accountId:ee,onAfterOptimisticRemove:ae}),W=rj(cy(Kk(j?.pages.flatMap(Z=>Z.items??[])??[])),P,ee),pe=c.useCallback(Z=>{w(Z)},[]),ve=c.useCallback(Z=>{k(dt=>{const at=new Set(dt);return at.has(Z)?at.delete(Z):at.add(Z),at})},[]),Ne=c.useCallback(()=>{w("all"),k(new Set)},[]),we=oj.get(S),X=we?{label:we,reach:P.length>0?"loaded-pages":Vk(E),onClear:Ne}:void 0,H=Jk(m,u),ie=Zk(W,t,H),[ge,ze]=c.useState(void 0);c.useEffect(()=>{ie&&ze(ie)},[ie]);const xe=ej(ie,ge,t,H),{selectedThreadId:B}=Os({strict:!1}),ue=c.useMemo(()=>_d(xe,{messageId:t,threadId:H?void 0:B,mailboxId:e}),[xe,t,B,H,e]),oe=_o(),{listCommandsRef:ne,onTriageContextChange:nt,focusedMessageId:Te,selectedIds:J}=oe,Se=W.find(Z=>Z.messageId===Te)??xe,Ve=c.useRef(null);c.useEffect(()=>{const Z=xe?.messageId??null;Z&&Ve.current!==Z&&xe?.authenticity?.dkimMismatch&&(Ve.current=Z,f||d())},[xe?.messageId,xe?.authenticity?.dkimMismatch,f,d]);const Oe=c.useRef(!1);c.useEffect(()=>{Oe.current||o&&xe?.messageId&&(Oe.current=!0,Xk()&&!f&&h(!0))},[o,xe?.messageId,f,h]);const he=iv({accounts:l})??0,lt=Me(),{pushError:Xe}=st(),Pe=dn({thread:xe,mailboxId:e,accountId:ee,onAfterOptimisticRemove:ae}),{draftsMailboxId:Ue}=oy(ee),qe=Ue!==void 0&&Ue===e,{archiveMailboxId:Ze}=ay(ee),rt=$d(),{requestCompose:je}=Pe,G=c.useCallback(()=>{je("reply")},[je]),te=c.useCallback(()=>{je("reply_all")},[je]),ce=c.useCallback(()=>{je("forward")},[je]),{state:de,openCompose:ke,closeCompose:Ee}=Yt(),De=c.useCallback(()=>{ke({mode:"new"})},[ke]),He=Fe({...sr(),onError:Z=>{Xe(is("Couldn't discard draft","The draft wasn't deleted.",Z))}}),ye=c.useCallback(()=>{const Z=de.outboxMessageId;Z&&(He.mutate({path:{outboxMessageId:Z}}),lt.invalidateQueries({queryKey:Va()}),Ee())},[de.outboxMessageId,He,lt,Ee]),Qe=c.useCallback(()=>{n({to:"/mail/$mailboxId",params:{mailboxId:e},search:Z=>({...Z,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,n]),Ge=c.useCallback(Z=>Z?rt(Z):[],[rt]),{toggleStar:Le}=wo({threadId:Se?.threadId??"",mailboxId:e}),{toggleReadFor:et}=yr({mailboxId:e,accountId:ee}),{junkMailboxId:Ye}=zs(ee),Dt=Ye!=null&&Ye===e,{candidates:es}=Bk(Dt?Ye:void 0),{moveMessages:Lt}=cs({mailboxId:e,threadId:Se?.threadId,accountId:ee,onAfterOptimisticRemove:ae}),{deleteMessages:xs}=us({mailboxId:e,threadId:Se?.threadId,onAfterOptimisticRemove:ae}),{addressId:tt,address:xt}=Pd(Se),{updateFlags:Ft}=Dd({addressId:tt,senderEmail:Se?.fromEmail??void 0}),ct=c.useCallback(()=>t||!Te?!1:(n({to:"/mail/$mailboxId",params:{mailboxId:e},search:Z=>({...Z,selectedMessageId:Te})}),!0),[t,Te,e,n]),$t=c.useCallback(()=>{ct()||xe&&je("reply")},[ct,xe,je]),qs=c.useCallback(()=>{ct()||xe&&je("reply_all")},[ct,xe,je]),Hs=c.useCallback(()=>{ct()||xe&&je("forward")},[ct,xe,je]),Ct=c.useCallback(()=>Ge(Se),[Ge,Se]),ts=c.useCallback(()=>{if(ne.current?.requestVerb("delete"))return;const Z=Ct();Z.length>0&&xs(Z)},[ne,Ct,xs]),_=c.useCallback(()=>{if(ne.current?.requestVerb("junk")||!Ye)return;const Z=Ct();Z.length!==0&&(Fd(i,{count:Z.length,senderTrust:Se?.senderTrust??"unknown",wasRescuable:Se?Ld(Se):!1}),Lt(Z,Ye))},[ne,Ye,Ct,Lt,i,Se]),Y=c.useCallback(()=>{if(J.length>0){const Z=!(Se?.hasStars??!1),dt=new Set(J);for(const at of W)dt.has(at.messageId)&&at.hasStars!==Z&&Le(at.messageId,at.hasStars);return}Se&&Le(Se.messageId,Se.hasStars)},[J,W,Se,Le]),Ce=c.useCallback(()=>{if(ne.current?.requestVerb("markRead"))return;const Z=Ct();if(Z.length===0)return;const dt=!(Se?.isRead??!1);et(Z,dt)},[ne,Ct,Se,et]),ut=c.useCallback(()=>{if(!tt)return;const Z=xt?.flags?.muted?.value!==!0;Ft({muted:{value:Z}})},[tt,xt,Ft]),bt=c.useCallback(()=>{if(!tt)return;const Z=xt?.flags?.vip?.value!==!0;Ft({vip:{value:Z}})},[tt,xt,Ft]),vt=c.useCallback(()=>{f||d()},[f,d]),ss=c.useCallback(Z=>{n({to:Z})},[n]),kn=qe?"drafts":Ze===e?"archive":Ye===e?"junk":"inbox",bs=c.useRef("");c.useEffect(()=>{const Z=bs.current;bs.current=g,g.length>0&&Z.length===0&&i.recordEvent("search.submitted",{mailboxType:kn})},[g,kn,i]);const Tr=qe&&de.isOpen&&!!de.outboxMessageId&&!xe,{goBack:Rr,nextMessageId:Ws,previousMessageId:Mr}=zo({context:oe,orderedIds:W.map(Z=>Z.messageId),selectedMessageId:t,enabled:!de.isOpen,onClose:Qe,handlers:{reply:$t,replyAll:qs,forward:Hs,delete:ts,toggleStar:Y,toggleRead:Ce,muteSender:ut,blockSender:vt,vipSender:bt,markJunk:_,toggleIntelligence:xe?d:void 0,compose:De,goBrief:()=>ss("/mail"),goInbox:()=>ss("/mail"),goSent:()=>ss("/mail"),goFlagged:()=>ss("/mail/flagged"),goSettings:()=>ss("/settings")}});vo({enabled:de.isOpen,bindings:[{key:"Escape",handler:Ee,preventDefault:!0}]});const Ar={mailboxId:e,selectedMessageId:t,selectedThread:xe,conversation:ue,threads:W,isLoading:T,isError:A,error:I,mailboxAccountId:ee,mailboxName:me,unreadCount:he,isDraftsMailbox:qe,isSpamFolder:Dt,rescueCandidates:es,filterCategory:S,filterAttributes:x,onSelectFilterCategory:pe,onToggleFilterAttribute:ve,onClearFilters:Ne,listFilter:X,intelligenceOpen:f,onToggleIntelligence:d,searchPredicate:p&&P.length===0?E:void 0,onDeleteMessages:U,onMoveMessages:fe,isDeleting:z,isMoving:se,onLoadMore:N,hasMore:q,isLoadingMore:Q,onTriageContextChange:nt,listCommandsRef:ne,onRetry:()=>F(),toolbarComposeRequest:Pe.composeRequest,onToolbarReply:G,onToolbarReplyAll:te,onToolbarForward:ce,onClearComposeRequest:Pe.clearComposeRequest,onToolbarDelete:Pe.deleteThread,onToolbarStar:Pe.toggleStar,onToolbarDiscardDraft:ye,onToolbarMove:Pe.moveThread,composeState:de,closeCompose:Ee,hasRemitDraftOpen:Tr,onBack:Rr,nextMessageId:Ws,previousMessageId:Mr};return r.jsx(Xd.Provider,{value:Ar,children:s})}function Jd(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:n,isError:a,error:o,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:m,onLoadMore:f,hasMore:d,isLoadingMore:h,mailboxAccountId:v,mailboxName:g,unreadCount:p,isDraftsMailbox:y,isSpamFolder:b,rescueCandidates:S,onTriageContextChange:w,listCommandsRef:x,onRetry:k,filterCategory:M,filterAttributes:O,onSelectFilterCategory:C,onToggleFilterAttribute:R,onClearFilters:P,listFilter:E,searchPredicate:L}=Ir(),{searchQuery:D,searchInput:j,accounts:T,resultFolderIndex:A}=Ae(),I=jr(),F=Ke(),N=g??"Inbox",q=c.useMemo(()=>Uc(),[]),Q=c.useMemo(()=>s.map(pe=>F0(pe,A)),[s,A]),{hits:ae,isLoading:U}=hd({mailboxId:e,filterCategory:M}),z=c.useMemo(()=>gd(ae,s.map(pe=>pe.threadId),A),[ae,s,A]),ee=c.useCallback(pe=>F({to:"/mail/$mailboxId",params:{mailboxId:pe.mailboxId??e},search:ve=>({...ve,q:j||void 0,selectedMessageId:pe.id,selectedThreadId:pe.threadId})}),[e,F,j]);if(y&&v)return r.jsx(rk,{mailboxId:e,accountId:v,selectedMessageId:t,imapThreads:s,title:g??"Drafts",unreadCount:p??void 0});const me=r.jsx(Dk,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:n,isError:a,error:o,onRetry:k,searchQuery:D,searchPredicate:L,onDeleteMessages:i,isDeleting:u,isMoving:m,onLoadMore:f,hasMore:d,isLoadingMore:h,accountId:v,listTitle:N,listFilter:E,listScopeLabel:N,hideHeader:!0,onTriageContextChange:w,commandsRef:x}),fe=T[0]?.accountId,se=I==="phone"&&fe?r.jsx($k,{accountId:fe,children:me}):me,W=b&&S.length>0&&v?r.jsx(_k,{accountId:v,currentMailboxId:e,candidates:S,onMove:l,children:se}):se;return r.jsx(Ud,{title:N,unreadCount:p,preset:q,selectedCategory:M,activeFilters:O,onSelectCategory:C,onToggleFilter:R,onClearFilters:P,searchResults:Q,searchLoading:n,relatedResults:z,relatedLoading:U,onSelectSearchResult:ee,searchResultsInBody:!0,children:W})}function lj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:l,onToolbarReply:u,onToolbarReplyAll:m,onToolbarForward:f,onClearComposeRequest:d,onToolbarDelete:h,onToolbarStar:v,onToolbarDiscardDraft:g,onToolbarMove:p,composeState:y}=Ir(),b=fs()?.showIntelligencePane??!1,S=!!n,w=b&&S,x=y.isOpen&&!n?r.jsx(Wd,{}):n?r.jsx(Bs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onOpenIntelligence:n.authenticity?.dkimMismatch?i:void 0,composeRequest:l,onComposeClose:d}):r.jsx(_s,{});return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx($o,{hasThread:S,intelligenceOpen:w&&o,canToggleIntelligence:w,onToggleIntelligence:i,onReply:S?u:void 0,onReplyAll:S?m:void 0,onForward:S?f:void 0,canDelete:S||a,onDelete:S?h:a?g:void 0,onToggleStar:S?v:void 0,isStarred:s?.hasStars,moveContext:S&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:x})]})}function cj(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:n}=Ir();return r.jsx(Us,{onClose:n,thread:s,mailboxId:e,accountId:t})}function uj(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:n,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=Ir(),m=Ke();if(s){const f=d=>m({to:"/mail/$mailboxId",params:{mailboxId:e},search:h=>({...h,selectedMessageId:d,selectedThreadId:void 0})});return r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:s.threadId,mailboxId:s.mailboxId,subject:s.subject,selectedMessageId:s.messageId,authenticity:s.authenticity,onBack:o,onOpenIntelligence:a,onSwipeNext:i?()=>f(i):void 0,onSwipePrevious:l?()=>f(l):void 0,mobileIntelligenceOpen:n}),r.jsx(xo,{isOpen:n,onClose:a,ariaLabel:"Message details",side:"right",children:r.jsx(Us,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?r.jsx("div",{className:"h-full",children:r.jsx(Wd,{})}):r.jsx(Jd,{})}const tn=Object.assign(ij,{List:Jd,Reading:lj,Intelligence:cj,Phone:uj}),Zd=e=>e==="failed"||e==="blocked",ef=e=>e!=="draft"&&e!=="sent",Uo="remit.savedSearches",dj=25;function Xn(){try{const e=localStorage.getItem(Uo);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function fj(e){const t=e.trim();if(!t)return Xn();const s=[t,...Xn().filter(n=>n!==t)].slice(0,dj);try{localStorage.setItem(Uo,JSON.stringify(s))}catch{return s}return s}function mj(e){const t=Xn().filter(s=>s!==e);try{localStorage.setItem(Uo,JSON.stringify(t))}catch{return t}return t}const Nl=e=>/^\d/.test(e),hj=(e,t)=>{const s=Nl(e),n=Nl(t);return s&&!n?-1:!s&&n?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function pj(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)=>hj(Kn(o,void 0,s),Kn(i,void 0,s))),{system:n,labels:a}}function gj(e,t,s){const n=Cm(t)&&e.unseenCount>0;return{id:e.mailboxId,name:Kn(e,t,s),unseen:n?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function xj(){const e=gr(),t=Ba({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 El({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const n=Me(),a=Ke(),o=xj(),{searchInput:i,onSearchChange:l}=Ae(),[u,m]=c.useState(Xn),{t:f}=Ka("mail",{useSuspense:!1}),d=c.useCallback((C,R)=>f(C,{defaultValue:R}),[f]),h=pt({queries:e.map(C=>({...it({path:{accountId:C.accountId}}),staleTime:1/0}))}),{data:v}=be(er()),g=c.useMemo(()=>(v?.items??[]).filter(C=>ef(C.status)).length,[v?.items]),p=c.useMemo(()=>e.map((C,R)=>{const P=h[R],E=P?.data?.items??[],L=Fa(C.folderAppointments),{system:D,labels:j}=pj(E,L,d),T=P?.isError?"error":P?.isLoading?"loading":"ready";return{id:C.accountId,label:C.email,email:C.email,muted:!!C.muted,outboxPending:g,status:T,onRetry:()=>P?.refetch(),mailboxes:[...D,...j].map(A=>gj(A,L.get(A.mailboxId),d))}}),[e,h,g,d]),y=C=>{n.invalidateQueries({queryKey:nr({path:{mailboxId:C},query:{order:"desc"}})})},b=({navId:C,className:R,ariaLabel:P,title:E,children:L,onClick:D})=>C==="brief"?r.jsx(Kt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>D?.(),className:R,"aria-label":P,title:E,children:L}):C==="outbox"?r.jsx(Kt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>D?.(),className:R,"aria-label":P,title:E,children:L}):C==="flagged"?r.jsx(Kt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>D?.(),className:R,"aria-label":P,title:E,children:L}):C==="settings"?r.jsx(Kt,{to:"/settings/accounts",onClick:()=>D?.(),className:R,"aria-label":P,title:E,children:L}):r.jsx(Kt,{to:"/mail/$mailboxId",params:{mailboxId:C},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{y(C),D?.()},className:R,"aria-label":P,title:E,children:L}),S=()=>{l(""),t?.()},w=i.trim(),x=w.length>0&&!u.includes(w)?w:void 0,k=c.useCallback(()=>{x&&m(fj(x))},[x]),M=c.useCallback(C=>{m(mj(C))},[]),O=c.useCallback(C=>{l(C),a({to:"/mail",search:{q:C,selectedMessageId:void 0}}),t?.()},[l,a,t]);return r.jsx(eg,{accounts:p,selectedNavId:o,onSelectNav:S,linkComponent:b,variant:s,savedSearches:u,saveableQuery:x,onSaveCurrentSearch:k,onSelectSavedSearch:O,onRemoveSavedSearch:M})}function bj({accounts:e,onMailboxSelect:t}){return fs()?.showNavPane??!0?r.jsx(El,{accounts:e}):r.jsxs("div",{className:"flex h-full flex-col",children:[r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(El,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),r.jsxs("div",{className:"border-t border-line px-2 py-2",children:[r.jsxs(Kt,{to:"/settings/accounts",onClick:t,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[r.jsx(wc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),r.jsx(du,{variant:"drawer"}),r.jsx(uu,{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(xc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function vj(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const n=[e.subject,e.fromAddress,e.fromName,...e.toAddresses??[],...e.ccAddresses??[]].filter(a=>typeof a=="string").join(" ").toLowerCase();return s.split(/\s+/).every(a=>a.length===0||n.includes(a))}function yj(e){return e.tokens.length>0&&e.freeText.trim().length===0}const tf={queued:{icon:Xa,label:"Queued",className:"text-warning"},sending:{icon:Ds,label:"Sending…",className:"text-accent-2"},sent:{icon:mc,label:"Sent",className:"text-positive"},failed:{icon:ds,label:"Failed",className:"text-danger"},blocked:{icon:Aa,label:"Blocked",className:"text-warning"}},wj=e=>Qm(e).toDateString()===new Date().toDateString()?Un(e,{hour:"numeric",minute:"2-digit"}):Un(e,{month:"short",day:"numeric"}),Il=e=>Un(e,{dateStyle:"medium",timeStyle:"short"}),Sj=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},sf=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",nf=c.createContext(null);function qo(){const e=c.useContext(nf);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function kj({children:e}){const t=Ke(),{selectedOutboxMessageId:s}=Os({strict:!1}),{data:n,isLoading:a}=be(er()),{searchQuery:o}=Ae(),i=gs(),l=Ro(o),u=Ks(l,i),m=l.length>0,f=yj(u),d=c.useMemo(()=>f?[]:(n?.items??[]).filter(p=>ef(p.status)).filter(p=>vj(p,u.freeText)),[n,u.freeText,f]),h=c.useMemo(()=>d.find(p=>p.outboxMessageId===s),[d,s]),v=c.useCallback(p=>{t({to:"/mail/outbox",search:y=>({...y,selectedOutboxMessageId:p})})},[t]),g={messages:d,hasQuery:m,unsupportedQuery:f,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:v};return r.jsx(nf.Provider,{value:g,children:e})}function rf({message:e,isSelected:t,onSelect:s}){const n=Me(),{openCompose:a}=Yt(),{pushError:o}=st(),i=c.useCallback(()=>{n.invalidateQueries({queryKey:Va()})},[n]),l=Fe({...Hl(),onSuccess:i,onError:d=>{o(is("Couldn't resend message","The message wasn't sent.",d))}}),u=Fe({...sr(),onSuccess:i,onError:d=>{o(is("Couldn't delete message","The message wasn't deleted.",d))}}),m=e.status;if(!tf[m])return null;const f=Zd(e.status);return r.jsx(Cg,{recipients:Sj(e),subject:e.subject||"",time:wj(e.sentAt??e.updatedAt),status:m,error:f?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:m==="failed"?()=>l.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:l.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function af({message:e,onBack:t}){const s=e.status,n=tf[s],a=n?.icon??mn,o=e.sentAt?Il(e.sentAt):Il(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(Ma,{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:_e("size-4",n.className,s==="sending"&&"animate-spin")}),r.jsx("span",{className:_e("text-xs font-medium",n.className),children:n.label}),Zd(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(rd,{html:e.htmlBody,text:e.textBody})})]})}function jj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,onSelectMessage:o}=qo(),i=c.useRef(null);return Jn({containerRef:i,itemSelector:Ia}),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:sf(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(Bo,{}),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(l=>r.jsx(rf,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function Cj(){const{selectedMessage:e}=qo();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(af,{message:e}):r.jsx(_s,{message:"Select a message to read",showHints:!1})})]})}function Nj(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=qo(),l=c.useRef(null);return Jn({containerRef:l,itemSelector:Ia}),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(af,{message:o,onBack:()=>i(void 0)}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(_s,{message:sf(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(Bo,{}),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:l,className:"flex-1 overflow-y-auto",children:e.map(u=>r.jsx(rf,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const Dn=Object.assign(kj,{List:jj,Reading:Cj,Phone:Nj}),Ej=({isOpen:e,onClose:t})=>{const s=c.useCallback(n=>{n.key==="Escape"&&(n.preventDefault(),t())},[t]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:t,onKeyDown:n=>n.key==="Escape"&&t(),children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.jsxs("div",{className:_e("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),onClick:n=>n.stopPropagation(),onKeyDown:n=>{n.key!=="Escape"&&n.stopPropagation()},children:[r.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),r.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:r.jsx(jt,{className:"size-5"})})]}),r.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:yu.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(c.Fragment,{children:[i>0&&a.keys[0]==="g"&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),r.jsx(Ts,{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(Ts,{children:"Esc"})," to close"]})})]})]}):null};function Ij(e){const t=pt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>J0(t.map(s=>s.data?.items??[])),[t])}const Tj=e=>e.map(t=>t.data?.items??[]);function Rj(e){const t=pt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0})),combine:Tj});return c.useMemo(()=>Nm(e.map((s,n)=>({folderAppointments:s.folderAppointments,mailboxes:t[n]??[]}))),[e,t])}var Ln={exports:{}},Tl;function Mj(){if(Tl)return Ln.exports;Tl=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 l=[],u=t[Symbol.iterator]();let m=!1,f=!1,d=0,h=0;const v=()=>{if(m)return;const g=u.next(),p=h;if(h++,g.done){f=!0,d===0&&a(l);return}d++,Promise.resolve(g.value).then(y=>s(y,p)).then(y=>{l[p]=y,d--,v()},y=>{m=!0,o(y)})};for(let g=0;g<i&&(v(),!f);g++);});return Ln.exports=e,Ln.exports.default=e,Ln.exports}var Aj=Mj();const Oj=Em(Aj),Pj=900*1e3,Dj=300,Lj=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},Fj=60*1e3,$j=e=>Math.max(Lj(e,Dj)*1e3,Fj),Bn=$j(Rm().mailboxPollIntervalSeconds),_j=5,Na=new Set,zj=(e,t,s=Pj)=>e.filter(n=>{const a=n.lastSyncAt;return a==null?!0:t-a>s}).map(n=>n.accountId),Bj=(e,t,s=Bn)=>e-t>=s,Kj=(e,t)=>e.filter(s=>!t.has(s)),Rl=(e,t)=>{if(Na.delete(e),Tm(t,{softError:!0})){Yl(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},Ml=(e,t)=>Im({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:ms({path:{accountId:e}})})}),Uj=e=>{const t=Me(),s=c.useRef(e);s.current=e;const n=e.map(a=>a.accountId).join(",");c.useEffect(()=>{const a=Date.now(),i=zj(s.current,a).filter(l=>!Na.has(l));if(i.length!==0)for(const l of i)Na.add(l),Ml(l,t).catch(u=>{Rl(l,u)})},[n,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const f=Kj(s.current.map(d=>d.accountId),i);for(const d of f)i.add(d);Oj(f,d=>Ml(d,t).catch(h=>{Rl(d,h)}).finally(()=>{i.delete(d)}),{concurrency:_j})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,Bn);return}},m=()=>{document.visibilityState==="visible"&&Bj(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,Bn))};return o=setTimeout(u,Bn),document.addEventListener("visibilitychange",m),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",m)}},[n,t])};function qj(e,t,s){if(e!==t)return s}function Hj(e,t){return e===""?"":t}function Wj(e,t,s){return t!==e?!1:t!==s}function Vj(){const{q:e=""}=Os({from:"/mail"}),t=Ke(),s=jr(),n=vd(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,m]=c.useState(!1),f=c.useCallback(se=>{m(se),Cl(se)},[]),[d,h]=c.useState(e),v=ir(d,200),g=Hj(d,v),p=c.useRef(e);p.current=e;const y=It({select:se=>sv(se.matches)}),[b,S]=c.useState(y);if(b!==y){const se=qj(b,y,e);S(y),se!==void 0&&h(se)}c.useEffect(()=>{Wj(d,g,p.current)&&t({to:".",search:se=>{const W=se.q===g;return{...se,q:g||void 0,...g&&!W?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[d,g,t]);const{data:w,isLoading:x,isError:k,error:M,refetch:O}=be({...Mt(),staleTime:1/0}),C=!!(w&&(w.accounts?.length??0)===0);c.useEffect(()=>{C&&t({to:"/onboarding",replace:!0})},[C,t]),vo({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const R=c.useCallback(se=>{h(se)},[]),P=c.useCallback(()=>{h("")},[]),E=c.useCallback(()=>{h("")},[]),L=c.useCallback(()=>{m(se=>{const W=!se;return Cl(W),W})},[]),D=w?.accounts??[],j=Ij(D),T=Rj(D),A=c.useMemo(()=>X0(D),[D]),I=It({select:se=>se.matches.find(pe=>"mailboxId"in pe.params)?.params.mailboxId}),{selectedMessageId:F}=Os({strict:!1}),N=It({select:se=>go(se.matches)}),q=It({select:se=>xn(se.matches)}),Q=It({select:se=>xr(se.matches)});Uj(D);const ae=c.useCallback(()=>{l(!1)},[]),U={accounts:D,mailboxNameIndex:j,accountNameIndex:A,resultFolderIndex:T,searchQuery:g,searchInput:d,searchViewKey:y,onSearchChange:R,onSearchClear:P,onSearchClearQuery:E,intelligenceOpen:u,onToggleIntelligence:L,onSetIntelligenceOpen:f},z=r.jsx(bj,{accounts:D,onMailboxSelect:ae}),ee=n?r.jsx(Zb,{accounts:D}):void 0,me=n?void 0:r.jsx(uv,{accounts:D}),fe={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return r.jsxs(Mm.Provider,{value:U,children:[k?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:r.jsx(Jt,{title:"Couldn't load your account",error:M,onRetry:()=>{O()}})}):N?r.jsx(Js,{selectedMessageId:F,children:n?r.jsx(_t,{nav:z,list:r.jsx(Js.Phone,{}),intelligenceOpen:u,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||C,...fe}):r.jsx(_t,{nav:z,topBar:me,list:r.jsx(Js.List,{}),reading:r.jsx(Js.Reading,{}),intelligence:r.jsx(Js.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||C,...fe})}):q?r.jsx(Zs,{selectedMessageId:F,children:n?r.jsx(_t,{nav:z,list:r.jsx(Zs.Phone,{}),intelligenceOpen:u,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||C,...fe}):r.jsx(_t,{nav:z,topBar:me,list:r.jsx(Zs.List,{}),reading:r.jsx(Zs.Reading,{}),intelligence:r.jsx(Zs.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||C,...fe})}):I?r.jsx(tn,{mailboxId:I,selectedMessageId:F,children:n?r.jsx(_t,{nav:z,list:r.jsx(tn.Phone,{}),intelligenceOpen:u,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||C,...fe}):r.jsx(_t,{nav:z,topBar:me,list:r.jsx(tn.List,{}),reading:r.jsx(tn.Reading,{}),intelligence:r.jsx(tn.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||C,...fe})}):Q?r.jsx(Dn,{children:n?r.jsx(_t,{nav:z,list:r.jsx(Dn.Phone,{}),intelligenceOpen:!1,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||C,...fe}):r.jsx(_t,{nav:z,topBar:me,list:r.jsx(Dn.List,{}),reading:r.jsx(Dn.Reading,{}),intelligenceOpen:!1,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||C,...fe})}):r.jsx(Et,{}),r.jsx(Ej,{isOpen:a,onClose:()=>o(!1)}),r.jsx(Am,{})]})}const dC=Object.freeze(Object.defineProperty({__proto__:null,component:Vj,useMailContext:Ae},Symbol.toStringTag,{value:"Module"}));export{uC as S,Bh as U,dC as m};
118
+ ){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function ky(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function Cy(){return No(/^Mac/)}function jy(){return No(/^iPhone/)}function sl(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Ny(){return No(/^iPad/)||Cy()&&navigator.maxTouchPoints>1}function Wu(){return jy()||Ny()}function No(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const Ey=24,Iy=typeof window<"u"?c.useLayoutEffect:c.useEffect;function nl(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const Qr=typeof document<"u"&&window.visualViewport;function rl(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Vu(e){for(rl(e)&&(e=e.parentElement);e&&!rl(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Ty=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let An=0,Gr;function Ry(e={}){let{isDisabled:t}=e;Iy(()=>{if(!t)return An++,An===1&&Wu()&&(Gr=My()),()=>{An--,An===0&&Gr?.()}},[t])}function My(){let e,t=0,s=d=>{e=Vu(d.target),!(e===document.documentElement&&e===document.body)&&(t=d.changedTouches[0].pageY)},n=d=>{if(!e||e===document.documentElement||e===document.body){d.preventDefault();return}let h=d.changedTouches[0].pageY,v=e.scrollTop,g=e.scrollHeight-e.clientHeight;g!==0&&((v<=0&&h>t||v>=g&&h<t)&&d.preventDefault(),t=h)},a=d=>{let h=d.target;va(h)&&h!==document.activeElement&&(d.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=d=>{let h=d.target;va(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",Qr&&(Qr.height<window.innerHeight?requestAnimationFrame(()=>{al(h)}):Qr.addEventListener("resize",()=>al(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,m=nl(Ay(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let f=nl(Gs(document,"touchstart",s,{passive:!1,capture:!0}),Gs(document,"touchmove",n,{passive:!1,capture:!0}),Gs(document,"touchend",a,{passive:!1,capture:!0}),Gs(document,"focus",o,!0),Gs(window,"scroll",i));return()=>{m(),f(),window.scrollTo(l,u)}}function Ay(e,t,s){let n=e.style[t];return e.style[t]=s,()=>{e.style[t]=n}}function Gs(e,t,s,n){return e.addEventListener(t,s,n),()=>{e.removeEventListener(t,s,n)}}function al(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=Vu(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+Ey;o>i&&(s.scrollTop+=a-n)}e=s.parentElement}}function va(e){return e instanceof HTMLInputElement&&!Ty.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function Oy(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function Py(...e){return t=>e.forEach(s=>Oy(s,t))}function Qu(...e){return c.useCallback(Py(...e),e)}const Gu=new WeakMap;function Be(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&&Gu.set(e,n)}function Dy(e,t){if(!e||!(e instanceof HTMLElement))return;let s=Gu.get(e);s&&(e.style[t]=s[t])}const $e=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function On(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(", ")[$e(t)?13:12]):(a=n.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[$e(t)?5:4]):null)}function Ly(e){return 8*(Math.log(e+1)-2)}function Yr(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function Fy(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const Re={DURATION:.5,EASE:[.32,.72,0,1]},Yu=.4,$y=.25,_y=100,Xu=8,rs=16,ya=26,Xr="vaul-dragging";function Ju(e){const t=K.useRef(e);return K.useEffect(()=>{t.current=e}),K.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function zy({defaultProp:e,onChange:t}){const s=K.useState(e),[n]=s,a=K.useRef(n),o=Ju(t);return K.useEffect(()=>{a.current!==n&&(o(n),a.current=n)},[n,a,o]),s}function Zu({prop:e,defaultProp:t,onChange:s=()=>{}}){const[n,a]=zy({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:n,l=Ju(s),u=K.useCallback(m=>{if(o){const d=typeof m=="function"?m(e):m;d!==e&&l(d)}else a(m)},[o,e,a,l]);return[i,u]}function By({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:n,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:m}){const[f,d]=Zu({prop:e,defaultProp:s?.[0],onChange:t}),[h,v]=K.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);K.useEffect(()=>{function O(){v({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]);const g=K.useMemo(()=>f===s?.[s.length-1]||null,[s,f]),p=K.useMemo(()=>{var O;return(O=s?.findIndex(j=>j===f))!=null?O:null},[s,f]),y=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===f||!s,b=K.useMemo(()=>{const O=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(R=>{const P=typeof R=="string";let E=0;if(P&&(E=parseInt(R,10)),$e(l)){const D=P?E:h?R*O.height:0;return h?l==="bottom"?O.height-D:-O.height+D:D}const L=P?E:h?R*O.width:0;return h?l==="right"?O.width-L:-O.width+L:L}))!=null?j:[]},[s,h,u]),S=K.useMemo(()=>p!==null?b?.[p]:null,[b,p]),w=K.useCallback(O=>{var j;const R=(j=b?.findIndex(P=>P===O))!=null?j:null;i(R),Be(n.current,{transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,transform:$e(l)?`translate3d(0, ${O}px, 0)`:`translate3d(${O}px, 0, 0)`}),b&&R!==b.length-1&&o!==void 0&&R!==o&&R<o?Be(a.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,opacity:"0"}):Be(a.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,opacity:"1"}),d(s?.[Math.max(R,0)])},[n.current,s,b,o,a,d]);K.useEffect(()=>{if(f||e){var O;const j=(O=s?.findIndex(R=>R===e||R===f))!=null?O:-1;b&&j!==-1&&typeof b[j]=="number"&&w(b[j])}},[f,e,s,b,w]);function x({draggedDistance:O,closeDrawer:j,velocity:R,dismissible:P}){if(o===void 0)return;const E=l==="bottom"||l==="right"?(S??0)-O:(S??0)+O,L=p===o-1,D=p===0,C=O>0;if(L&&Be(a.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`}),!m&&R>2&&!C){P?j():w(b[0]);return}if(!m&&R>2&&C&&b&&s){w(b[s.length-1]);return}const T=b?.reduce((I,F)=>typeof I!="number"||typeof F!="number"?I:Math.abs(F-E)<Math.abs(I-E)?F:I),A=$e(l)?window.innerHeight:window.innerWidth;if(R>Yu&&Math.abs(O)<A*.4){const I=C?1:-1;if(I>0&&g&&s){w(b[s.length-1]);return}if(D&&I<0&&P&&j(),p===null)return;w(b[p+I]);return}w(T)}function k({draggedDistance:O}){if(S===null)return;const j=l==="bottom"||l==="right"?S-O:S+O;(l==="bottom"||l==="right")&&j<b[b.length-1]||(l==="top"||l==="left")&&j>b[b.length-1]||Be(n.current,{transform:$e(l)?`translate3d(0, ${j}px, 0)`:`translate3d(${j}px, 0, 0)`})}function M(O,j){if(!s||typeof p!="number"||!b||o===void 0)return null;const R=p===o-1;if(p>=o&&j)return 0;if(R&&!j)return 1;if(!y&&!R)return null;const E=R?p+1:p-1,L=R?b[E]-b[E-1]:b[E+1]-b[E],D=O/Math.abs(L);return R?1-D:D}return{isLastSnapPoint:g,activeSnapPoint:f,shouldFade:y,getPercentageDragged:M,setActiveSnapPoint:d,activeSnapPointIndex:p,onRelease:x,onDrag:k,snapPointsOffset:b}}const Ky=()=>()=>{};function Uy(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:n,noBodyStyles:a}=Sn(),o=K.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-ya)/window.innerWidth}K.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;Fy(n&&!a?Yr(document.body,{background:"black"}):Ky,Yr(u,{transformOrigin:$e(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Re.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Re.EASE.join(",")})`}));const m=Yr(u,{borderRadius:`${Xu}px`,overflow:"hidden",...$e(e)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{m(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},Re.DURATION*1e3)}}},[t,s,i])}let Ys=null;function qy({isOpen:e,modal:t,nested:s,hasBeenOpened:n,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=K.useState(()=>typeof window<"u"?window.location.href:""),u=K.useRef(0),m=K.useCallback(()=>{if(sl()&&Ys===null&&e&&!o){Ys={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:d,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-d}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]),f=K.useCallback(()=>{if(sl()&&Ys!==null&&!o){const d=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Ys),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,d)}),Ys=null}},[i]);return K.useEffect(()=>{function d(){u.current=window.scrollY}return d(),window.addEventListener("scroll",d),()=>{window.removeEventListener("scroll",d)}},[]),K.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||f()}},[t,f]),K.useEffect(()=>{s||!n||(e?(!window.matchMedia("(display-mode: standalone)").matches&&m(),t||window.setTimeout(()=>{f()},500)):f())},[e,n,i,t,s,m,f]),{restorePositionSetting:f}}function Hy({open:e,onOpenChange:t,children:s,onDrag:n,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=$y,scrollLockTimeout:m=_y,dismissible:f=!0,handleOnly:d=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:v,setActiveSnapPoint:g,fixed:p,modal:y=!0,onClose:b,nested:S,noBodyStyles:w=!1,direction:x="bottom",defaultOpen:k=!1,disablePreventScroll:M=!0,snapToSequentialPoint:O=!1,preventScrollRestoration:j=!1,repositionInputs:R=!0,onAnimationEnd:P,container:E,autoFocus:L=!1}){var D,C;const[T=!1,A]=Zu({defaultProp:k,prop:e,onChange:G=>{t?.(G),!G&&!S&&Se(),setTimeout(()=>{P?.(G)},Re.DURATION*1e3),G&&!y&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),G||(document.body.style.pointerEvents="auto")}}),[I,F]=K.useState(!1),[N,q]=K.useState(!1),[Q,ae]=K.useState(!1),U=K.useRef(null),z=K.useRef(null),ee=K.useRef(null),me=K.useRef(null),fe=K.useRef(null),se=K.useRef(!1),W=K.useRef(null),pe=K.useRef(0),ve=K.useRef(!1),Ne=K.useRef(!k),we=K.useRef(0),X=K.useRef(null),H=K.useRef(((D=X.current)==null?void 0:D.getBoundingClientRect().height)||0),ie=K.useRef(((C=X.current)==null?void 0:C.getBoundingClientRect().width)||0),ge=K.useRef(0),ze=K.useCallback(G=>{o&&G===ne.length-1&&(z.current=new Date)},[]),{activeSnapPoint:xe,activeSnapPointIndex:B,setActiveSnapPoint:ue,onRelease:oe,snapPointsOffset:ne,onDrag:nt,shouldFade:Te,getPercentageDragged:J}=By({snapPoints:o,activeSnapPointProp:v,setActiveSnapPointProp:g,drawerRef:X,fadeFromIndex:h,overlayRef:U,onSnapPointChange:ze,direction:x,container:E,snapToSequentialPoint:O});Ry({isDisabled:!T||N||!y||Q||!I||!R||!M});const{restorePositionSetting:Se}=qy({isOpen:T,modal:y,nested:S??!1,hasBeenOpened:I,preventScrollRestoration:j,noBodyStyles:w});function Ve(){return(window.innerWidth-ya)/window.innerWidth}function Oe(G){var te,ce;!f&&!o||X.current&&!X.current.contains(G.target)||(H.current=((te=X.current)==null?void 0:te.getBoundingClientRect().height)||0,ie.current=((ce=X.current)==null?void 0:ce.getBoundingClientRect().width)||0,q(!0),ee.current=new Date,Wu()&&window.addEventListener("touchend",()=>se.current=!1,{once:!0}),G.target.setPointerCapture(G.pointerId),pe.current=$e(x)?G.pageY:G.pageX)}function he(G,te){var ce;let de=G;const ke=(ce=window.getSelection())==null?void 0:ce.toString(),Ee=X.current?On(X.current,x):null,De=new Date;if(de.tagName==="SELECT"||de.hasAttribute("data-vaul-no-drag")||de.closest("[data-vaul-no-drag]"))return!1;if(x==="right"||x==="left")return!0;if(z.current&&De.getTime()-z.current.getTime()<500)return!1;if(Ee!==null&&(x==="bottom"?Ee>0:Ee<0))return!0;if(ke&&ke.length>0)return!1;if(fe.current&&De.getTime()-fe.current.getTime()<m&&Ee===0||te)return fe.current=De,!1;for(;de;){if(de.scrollHeight>de.clientHeight){if(de.scrollTop!==0)return fe.current=new Date,!1;if(de.getAttribute("role")==="dialog")return!0}de=de.parentNode}return!0}function lt(G){if(X.current&&N){const te=x==="bottom"||x==="right"?1:-1,ce=(pe.current-($e(x)?G.pageY:G.pageX))*te,de=ce>0,ke=o&&!f&&!de;if(ke&&B===0)return;const Ee=Math.abs(ce),De=document.querySelector("[data-vaul-drawer-wrapper]"),He=x==="bottom"||x==="top"?H.current:ie.current;let ye=Ee/He;const Qe=J(Ee,de);if(Qe!==null&&(ye=Qe),ke&&ye>=1||!se.current&&!he(G.target,de))return;if(X.current.classList.add(Xr),se.current=!0,Be(X.current,{transition:"none"}),Be(U.current,{transition:"none"}),o&&nt({draggedDistance:ce}),de&&!o){const Le=Ly(ce),et=Math.min(Le*-1,0)*te;Be(X.current,{transform:$e(x)?`translate3d(0, ${et}px, 0)`:`translate3d(${et}px, 0, 0)`});return}const Ge=1-ye;if((Te||h&&B===h-1)&&(n?.(G,ye),Be(U.current,{opacity:`${Ge}`,transition:"none"},!0)),De&&U.current&&i){const Le=Math.min(Ve()+ye*(1-Ve()),1),et=8-ye*8,Ye=Math.max(0,14-ye*14);Be(De,{borderRadius:`${et}px`,transform:$e(x)?`scale(${Le}) translate3d(0, ${Ye}px, 0)`:`scale(${Le}) translate3d(${Ye}px, 0, 0)`,transition:"none"},!0)}if(!o){const Le=Ee*te;Be(X.current,{transform:$e(x)?`translate3d(0, ${Le}px, 0)`:`translate3d(${Le}px, 0, 0)`})}}}K.useEffect(()=>{window.requestAnimationFrame(()=>{Ne.current=!0})},[]),K.useEffect(()=>{var G;function te(){if(!X.current||!R)return;const ce=document.activeElement;if(va(ce)||ve.current){var de;const ke=((de=window.visualViewport)==null?void 0:de.height)||0,Ee=window.innerHeight;let De=Ee-ke;const He=X.current.getBoundingClientRect().height||0,ye=He>Ee*.8;ge.current||(ge.current=He);const Qe=X.current.getBoundingClientRect().top;if(Math.abs(we.current-De)>60&&(ve.current=!ve.current),o&&o.length>0&&ne&&B){const Ge=ne[B]||0;De+=Ge}if(we.current=De,He>ke||ve.current){const Ge=X.current.getBoundingClientRect().height;let Le=Ge;Ge>ke&&(Le=ke-(ye?Qe:ya)),p?X.current.style.height=`${Ge-Math.max(De,0)}px`:X.current.style.height=`${Math.max(Le,ke-Qe)}px`}else ky()||(X.current.style.height=`${ge.current}px`);o&&o.length>0&&!ve.current?X.current.style.bottom="0px":X.current.style.bottom=`${Math.max(De,0)}px`}}return(G=window.visualViewport)==null||G.addEventListener("resize",te),()=>{var ce;return(ce=window.visualViewport)==null?void 0:ce.removeEventListener("resize",te)}},[B,o,ne]);function Xe(G){Ue(),b?.(),G||A(!1),setTimeout(()=>{o&&ue(o[0])},Re.DURATION*1e3)}function Pe(){if(!X.current)return;const G=document.querySelector("[data-vaul-drawer-wrapper]"),te=On(X.current,x);Be(X.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`}),Be(U.current,{transition:`opacity ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,opacity:"1"}),i&&te&&te>0&&T&&Be(G,{borderRadius:`${Xu}px`,overflow:"hidden",...$e(x)?{transform:`scale(${Ve()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${Ve()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${Re.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Re.EASE.join(",")})`},!0)}function Ue(){!N||!X.current||(X.current.classList.remove(Xr),se.current=!1,q(!1),me.current=new Date)}function qe(G){if(!N||!X.current)return;X.current.classList.remove(Xr),se.current=!1,q(!1),me.current=new Date;const te=On(X.current,x);if(!G||!he(G.target,!1)||!te||Number.isNaN(te)||ee.current===null)return;const ce=me.current.getTime()-ee.current.getTime(),de=pe.current-($e(x)?G.pageY:G.pageX),ke=Math.abs(de)/ce;if(ke>.05&&(ae(!0),setTimeout(()=>{ae(!1)},200)),o){oe({draggedDistance:de*(x==="bottom"||x==="right"?1:-1),closeDrawer:Xe,velocity:ke,dismissible:f}),a?.(G,!0);return}if(x==="bottom"||x==="right"?de>0:de<0){Pe(),a?.(G,!0);return}if(ke>Yu){Xe(),a?.(G,!1);return}var Ee;const De=Math.min((Ee=X.current.getBoundingClientRect().height)!=null?Ee:0,window.innerHeight);var He;const ye=Math.min((He=X.current.getBoundingClientRect().width)!=null?He:0,window.innerWidth),Qe=x==="left"||x==="right";if(Math.abs(te)>=(Qe?ye:De)*u){Xe(),a?.(G,!1);return}a?.(G,!0),Pe()}K.useEffect(()=>(T&&(Be(document.documentElement,{scrollBehavior:"auto"}),z.current=new Date),()=>{Dy(document.documentElement,"scrollBehavior")}),[T]);function Ze(G){const te=G?(window.innerWidth-rs)/window.innerWidth:1,ce=G?-rs:0;W.current&&window.clearTimeout(W.current),Be(X.current,{transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,transform:$e(x)?`scale(${te}) translate3d(0, ${ce}px, 0)`:`scale(${te}) translate3d(${ce}px, 0, 0)`}),!G&&X.current&&(W.current=setTimeout(()=>{const de=On(X.current,x);Be(X.current,{transition:"none",transform:$e(x)?`translate3d(0, ${de}px, 0)`:`translate3d(${de}px, 0, 0)`})},500))}function rt(G,te){if(te<0)return;const ce=(window.innerWidth-rs)/window.innerWidth,de=ce+te*(1-ce),ke=-rs+te*rs;Be(X.current,{transform:$e(x)?`scale(${de}) translate3d(0, ${ke}px, 0)`:`scale(${de}) translate3d(${ke}px, 0, 0)`,transition:"none"})}function Ce(G,te){const ce=$e(x)?window.innerHeight:window.innerWidth,de=te?(ce-rs)/ce:1,ke=te?-rs:0;te&&Be(X.current,{transition:`transform ${Re.DURATION}s cubic-bezier(${Re.EASE.join(",")})`,transform:$e(x)?`scale(${de}) translate3d(0, ${ke}px, 0)`:`scale(${de}) translate3d(${ke}px, 0, 0)`})}return K.useEffect(()=>{y||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[y]),K.createElement(Pu,{defaultOpen:k,onOpenChange:G=>{!f&&!G||(G?F(!0):Xe(!0),A(G))},open:T},K.createElement(Hu.Provider,{value:{activeSnapPoint:xe,snapPoints:o,setActiveSnapPoint:ue,drawerRef:X,overlayRef:U,onOpenChange:t,onPress:Oe,onRelease:qe,onDrag:lt,dismissible:f,shouldAnimate:Ne,handleOnly:d,isOpen:T,isDragging:N,shouldFade:Te,closeDrawer:Xe,onNestedDrag:rt,onNestedOpenChange:Ze,onNestedRelease:Ce,keyboardIsOpen:ve,modal:y,snapPointsOffset:ne,activeSnapPointIndex:B,direction:x,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:w,container:E,autoFocus:L}},s))}const ed=K.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:n,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=Sn(),m=Qu(t,s),f=n&&n.length>0;if(!l)return null;const d=K.useCallback(h=>a(h),[a]);return K.createElement($u,{onMouseUp:d,ref:m,"data-vaul-overlay":"","data-vaul-snap-points":i&&f?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});ed.displayName="Drawer.Overlay";const td=K.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...n},a){const{drawerRef:o,onPress:i,onRelease:l,onDrag:u,keyboardIsOpen:m,snapPointsOffset:f,activeSnapPointIndex:d,modal:h,isOpen:v,direction:g,snapPoints:p,container:y,handleOnly:b,shouldAnimate:S,autoFocus:w}=Sn(),[x,k]=K.useState(!1),M=Qu(a,o),O=K.useRef(null),j=K.useRef(null),R=K.useRef(!1),P=p&&p.length>0;Uy();const E=(D,C,T=0)=>{if(R.current)return!0;const A=Math.abs(D.y),I=Math.abs(D.x),F=I>A,N=["bottom","right"].includes(C)?1:-1;if(C==="left"||C==="right"){if(!(D.x*N<0)&&I>=0&&I<=T)return F}else if(!(D.y*N<0)&&A>=0&&A<=T)return!F;return R.current=!0,!0};K.useEffect(()=>{P&&window.requestAnimationFrame(()=>{k(!0)})},[]);function L(D){O.current=null,R.current=!1,l(D)}return K.createElement(_u,{"data-vaul-drawer-direction":g,"data-vaul-drawer":"","data-vaul-delayed-snap-points":x?"true":"false","data-vaul-snap-points":v&&P?"true":"false","data-vaul-custom-container":y?"true":"false","data-vaul-animate":S?.current?"true":"false",...n,ref:M,style:f&&f.length>0?{"--snap-point-height":`${f[d??0]}px`,...t}:t,onPointerDown:D=>{b||(n.onPointerDown==null||n.onPointerDown.call(n,D),O.current={x:D.pageX,y:D.pageY},i(D))},onOpenAutoFocus:D=>{s?.(D),w||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,b||(n.onPointerMove==null||n.onPointerMove.call(n,D),!O.current))return;const C=D.pageY-O.current.y,T=D.pageX-O.current.x,A=D.pointerType==="touch"?10:2;E({x:T,y:C},g,A)?u(D):(Math.abs(T)>A||Math.abs(C)>A)&&(O.current=null)},onPointerUp:D=>{n.onPointerUp==null||n.onPointerUp.call(n,D),O.current=null,R.current=!1,l(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)}})});td.displayName="Drawer.Content";const Wy=250,Vy=120,sd=K.forwardRef(function({preventCycle:e=!1,children:t,...s},n){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:l,setActiveSnapPoint:u,dismissible:m,handleOnly:f,isOpen:d,onPress:h,onDrag:v}=Sn(),g=K.useRef(null),p=K.useRef(!1);function y(){if(p.current){w();return}window.setTimeout(()=>{b()},Vy)}function b(){if(o||e||p.current){w();return}if(w(),!i||i.length===0){m||a();return}if(l===i[i.length-1]&&m){a();return}const k=i.findIndex(O=>O===l);if(k===-1)return;const M=i[k+1];u(M)}function S(){g.current=window.setTimeout(()=>{p.current=!0},Wy)}function w(){g.current&&window.clearTimeout(g.current),p.current=!1}return K.createElement("div",{onClick:y,onPointerCancel:w,onPointerDown:x=>{f&&h(x),S()},onPointerMove:x=>{f&&v(x)},ref:n,"data-vaul-drawer-visible":d?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},K.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});sd.displayName="Drawer.Handle";function Qy(e){const t=Sn(),{container:s=t.container,...n}=e;return K.createElement(Fu,{container:s,...n})}const ft={Root:Hy,Content:td,Overlay:ed,Portal:Qy,Handle:sd,Title:Ku},nd="inline-flex items-center justify-center transition-colors",Gy=_e(nd,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Yy=_e(nd,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),Eo=({accountId:e,currentMailboxId:t,onMove:s,disabled:n=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),[m,f]=c.useState(),d=Xt(),h=c.useRef(null),v=i??"Move to folder",g=c.useId(),{t:p}=za("mail",{useSuspense:!1}),y=Wa(),{data:b,isLoading:S,isError:w,error:x,refetch:k}=be({...it({path:{accountId:e}}),staleTime:1/0,enabled:l}),M=So(e),{createFolderIn:O}=ec(e),j=c.useMemo(()=>Va({mailboxes:b?.items??[],folderAppointments:M,currentMailboxId:t,translator:y}),[b?.items,M,t,y]),R=Qa(b?.items??[]),P=j.find(I=>I.id===m),E=c.useCallback(()=>{u(!1),f(void 0)},[]),L=c.useCallback(()=>{P&&(E(),s(P.id))},[P,E,s]);c.useEffect(()=>{if(!l||!d)return;const I=N=>{h.current&&!h.current.contains(N.target)&&E()},F=N=>{N.key==="Escape"&&E()};return document.addEventListener("mousedown",I),document.addEventListener("keydown",F),()=>{document.removeEventListener("mousedown",I),document.removeEventListener("keydown",F)}},[l,d,E]);const D=n||!!a,C=r.jsxs("button",{type:"button",onClick:I=>{I.stopPropagation(),!D&&u(F=>!F)},"aria-label":v,"aria-haspopup":d?"tree":"dialog","aria-expanded":l,"aria-controls":l?g:void 0,title:a,className:o==="icon-only"?Gy:Yy,children:[r.jsx(Ta,{className:o==="icon-only"?"size-5":"size-4"}),o==="compact"&&r.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),T=S?r.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):w?r.jsx("div",{className:"p-3",children:r.jsx(Jt,{variant:"inline",title:"Couldn't load folders",error:x,onRetry:()=>k()})}):r.jsx(Ol,{folders:j,selectedId:m,delimiter:R,onSelect:f,onCreateFolder:O,onCancel:E,labels:{filterPlaceholder:p("move_picker_filter_placeholder",{defaultValue:"Filter folders…"}),filterAriaLabel:p("move_picker_filter_label",{defaultValue:"Filter folders"})}}),A=P&&r.jsx("div",{className:"shrink-0 border-t border-line p-2",children:r.jsx(le,{variant:"primary",onClick:L,className:"h-11 w-full font-semibold",children:`Move to ${P.label}`})});return d?r.jsxs("div",{ref:h,className:"relative inline-block",children:[C,l&&r.jsxs("div",{id:g,className:_e("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:[T,A]})]}):r.jsxs(r.Fragment,{children:[C,r.jsx(ft.Root,{open:l,onOpenChange:I=>I?u(!0):E(),children:r.jsxs(ft.Portal,{children:[r.jsx(ft.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(ft.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{maxHeight:"85dvh"},id:g,children:[r.jsx(ft.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),r.jsx(ft.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:T}),A]})]})})]})},Xy=({messageId:e,threadId:t,mailboxId:s,isRead:n,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const m=Me(),f=Ke(),{pushError:d}=st(),{selectedMessageId:h}=As({strict:!1}),{mutate:v,isPending:g}=Fe({...rr(),onMutate:async T=>{const A=T.body.isRead??!0,I=new Set(T.body.messageIds??[]),F=hs({path:{threadId:t}}),N=Ot([s]);await Promise.all([m.cancelQueries({queryKey:F}),bn(m,N)]);const q=m.getQueriesData({queryKey:F}).filter(ae=>ae[1]!==void 0).map(([ae,U])=>({queryKey:ae,data:U})),Q=vn(m,N);return m.setQueriesData({queryKey:F},ae=>ae&&{...ae,items:Vn(ae.items,I,A)}),yn(m,N,ae=>Vn(ae,I,A)),{threadMessagesPrefix:F,listPrefixes:N,previousThreadMessages:q,previousThreadsList:Q}},onError:(T,A,I)=>{if(I){for(const N of I.previousThreadMessages)m.setQueryData(N.queryKey,N.data);wn(m,I.previousThreadsList)}const F=A.body.isRead??!0;d({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:mt(T),error:T})},onSettled:(T,A,I,F)=>{F&&(m.invalidateQueries({queryKey:F.threadMessagesPrefix}),Pt(m,F.listPrefixes))}}),p=c.useCallback(T=>{h&&T.includes(h)&&f({to:"/mail/$mailboxId",params:{mailboxId:s},search:A=>({...A,selectedMessageId:void 0})})},[h,s,f]),{deleteMessages:y,isPending:b}=us({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:S,isPending:w}=cs({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:x,isPending:k,error:M,reset:O}=ko({messageId:e}),j=()=>{v({body:{messageIds:[e],isRead:!1}})},R=()=>{y([e])},P=()=>{o&&x(o,i)},E=g||b||w||k,L=E||!o,D=c.useCallback(T=>{S([e],T)},[S,e]),C=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(Eo,{accountId:a,currentMailboxId:s,onMove:D,disabled:E,label:"Move this message"}),r.jsxs(lu,{trigger:r.jsx(pc,{className:"size-4"}),children:[r.jsxs(sn,{onClick:P,disabled:L,children:[i?r.jsx(cr,{className:"size-4 text-positive"}):r.jsx(fn,{className:"size-4 opacity-0"}),r.jsx("span",{title:C,children:"Trusted sender"})]}),n&&r.jsxs(sn,{onClick:j,disabled:E,children:[r.jsx(ur,{className:"size-4"}),"Mark as unread"]}),u&&r.jsxs(sn,{onClick:u,children:[r.jsx(hc,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),r.jsx(cu,{}),r.jsxs(sn,{onClick:R,disabled:E,destructive:!0,children:[r.jsx(Rt,{className:"size-4"}),"Delete"]})]})]}),M&&r.jsx("div",{className:"w-64",children:r.jsx(Jt,{variant:"inline",title:"Couldn't update trust",error:M,onRetry:()=>{O(),P()}})})]})},Jy=()=>{const[e,t]=c.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return c.useEffect(()=>{const s=document.documentElement,n=new MutationObserver(()=>{t(s.classList.contains("dark"))});return n.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e},Zy=({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"})]})]}),e0=(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}}},t0=e=>e instanceof as?e.reason:"generic",s0=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",n0=({error:e,onRetry:t})=>{const s=t0(e),n=s0(e),{title:a,detail:o}=e0(s,n),[i,l]=c.useState(!1),{Account:u}=$a();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(ds,{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:()=>l(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:r.jsx(Ct,{className:"size-4","aria-hidden":"true"})})]})]})},r0=()=>r.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),ol=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),rd=({bodyParts:e,html:t,text:s,isTrusted:n=!1,messageId:a,fromAddressId:o,category:i,className:l})=>{const[u,m]=c.useState(!1),f=n||u,d=Jy(),{toggleTrusted:h,isPending:v}=ko({messageId:a??""}),g=!!e&&e.length>0,{picked:p,data:y,isLoading:b,isError:S,error:w,refetch:x}=wu({messageId:a,bodyParts:e,enabled:g}),k=c.useMemo(()=>wp(e??[]),[e]),M=g&&y?.kind==="html"?y.body:t,O=g&&y?.kind==="text"?y.body:s;if(g){if(b)return r.jsx("div",{className:_e("message-body",l),children:r.jsx(r0,{})});if(S)return r.jsx("div",{className:_e("message-body",l),children:r.jsx(n0,{error:w,onRetry:()=>x()})});if(!p)return r.jsx("div",{className:_e("message-body",l),children:r.jsx(ol,{})})}else if(!t&&!s)return r.jsx("div",{className:_e("message-body",l),children:r.jsx(ol,{})});const j=!!(o&&a),R=()=>{!o||v||(m(!0),h(o,!1))};return r.jsx(Pc,{className:l,html:M,text:O,isDark:d,category:i,allowImages:f,resolveCid:k,renderBlockedNotice:P=>r.jsx(Zy,{blockedImageCount:P,canAlwaysTrust:j,isTrustPending:v,onLoadOnce:()=>m(!0),onAlwaysTrust:R})})},a0=({messageId:e,threadId:t,mailboxId:s,accountId:n,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:l,isTrusted:u,showRaw:m,onToggleRaw:f,onReply:d,onReplyAll:h,onForward:v})=>{const g=Me(),{deleteMessages:p}=us({mailboxId:s,threadId:t}),{moveMessages:y}=cs({mailboxId:s,threadId:t,accountId:n}),{toggleTrusted:b}=ko({messageId:e}),{mutate:S}=Fe({...rr(),onSettled:()=>{g.invalidateQueries({queryKey:hs({path:{threadId:t}})}),Pt(g,Ot([s]))}}),w=c.useCallback(O=>{y([e],O)},[y,e]),x=c.useCallback(()=>{p([e])},[p,e]),k=c.useCallback(()=>{S({body:{messageIds:[e],isRead:!a}})},[S,e,a]),M=[];return l&&M.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?r.jsx(cr,{className:"size-4 text-positive"}):r.jsx(fn,{className:"size-4"}),onSelect:()=>b(l,u)}),f&&M.push({key:"raw",label:m?"Show formatted":"Show raw email",icon:r.jsx(hc,{className:"size-4"}),onSelect:f}),r.jsx(Oc,{hasThread:!0,onReply:d,onReplyAll:h,onForward:v,isStarred:o,onToggleStar:i,onDelete:x,isRead:a,onToggleRead:k,overflowItems:M,moveSlot:n?r.jsx(Eo,{accountId:n,currentMailboxId:s,onMove:w,label:"Move this message"}):void 0})},o0=()=>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"})]}),i0=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:n,isError:a,error:o,refetch:i}=be({...Zf({path:{messageId:e}}),enabled:t});if(n)return r.jsx("div",{className:"message-body",children:r.jsx(o0,{})});if(a)return r.jsx("div",{className:"message-body",children:r.jsx(Jt,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const l=s?.raw??"";return l===""?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:l})})},l0=()=>r.jsx(cr,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),ad=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),od=({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:_e("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":_e("text-fg-subtle hover:text-warning",n&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:r.jsx(Gt,{className:_e("size-3.5",e&&"fill-current")})}),c0=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:n,isStarPending:a})=>{const o=Jl(e.sentDate,"datetime"),i=ad(e,o);return r.jsx(Dc,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:r.jsxs(r.Fragment,{children:[e.hasAttachment&&r.jsx(dr,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx(od,{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})]})})},u0=({threadMessage:e,messageData:t,isLoading:s,isError:n,error:a,onRetry:o,isFocused:i,onToggle:l,onToggleStar:u,isStarPending:m,accountId:f,showRaw:d,onToggleRaw:h,mobile:v,onReply:g,onReplyAll:p,onForward:y})=>{const b=Jl(e.sentDate,"long"),S=!e.isRead,w=t?.envelope.from[0]?.flags?.trusted?.value===!0,x=t?.envelope.from[0]?.addressId,k=ad(e,b),M=e.autoMoved?r.jsx(cy,{accountId:f,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved}):null;return r.jsx(Lc,{message:k,isFocused:v?!1:i,onHeaderClick:l,senderBadge:w?r.jsx(l0,{}):void 0,trailing:r.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:b}),to:t?r.jsx(Uh,{label:"To",addresses:t.envelope.to}):null,indicators:M||!v?r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[M,!v&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[r.jsx(od,{isStarred:e.hasStars,onToggleStar:u,isStarPending:m}),e.hasAttachment&&r.jsx("span",{className:"text-fg-subtle p-0.5",children:r.jsx(dr,{className:"size-3.5"})})]}),S&&r.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:v?void 0:r.jsx(Xy,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:f,fromAddressId:x,isTrusted:w,showRaw:d,onToggleRaw:h}),actionBar:v?r.jsx(a0,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:f,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:x,isTrusted:w,showRaw:d,onToggleRaw:h,onReply:g,onReplyAll:p,onForward:y}):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&&em(a)?r.jsx("div",{className:"mt-3",children:r.jsx(Eu,{message:"This message has been deleted"})}):n?r.jsx("div",{className:"mt-3",children:r.jsx(Jt,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):d?r.jsx("div",{className:"mt-3",children:r.jsx(i0,{messageId:e.messageId})}):r.jsx("div",{className:"mt-3",children:r.jsx(rd,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:w,category:wr(e.category)})})})},d0=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,mobile:l,onReply:u,onReplyAll:m,onForward:f})=>{const[d,h]=c.useState(!1),{data:v,isLoading:g,isError:p,error:y,refetch:b}=be({...ar({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?r.jsx(u0,{threadMessage:e,messageData:v,isLoading:g,isError:p,error:y,onRetry:()=>b(),isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,showRaw:d,onToggleRaw:()=>h(S=>!S),mobile:l,onReply:u,onReplyAll:m,onForward:f}):r.jsx(c0,{threadMessage:e,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o})},f0=()=>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 il({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(Ls,{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:l,onComposeClose:u,onSwipeNext:m,onSwipePrevious:f,mobileIntelligenceOpen:d})=>{const h=Xt(),{handlers:v}=Zv({onSwipeLeft:m,onSwipeRight:f}),{accountId:g}=bo(t),{data:p,isLoading:y,isError:b,error:S,refetch:w}=be({...tm({path:{threadId:e}})}),x=c.useMemo(()=>p?.items??[],[p?.items]),k=x[x.length-1],M=c.useRef(new Map),[O,j]=c.useState(new Set),[R,P]=c.useState(null),[E,L]=c.useState(0);c.useEffect(()=>{if(x.length>0&&e!==R){P(e);const H=new Set([x[x.length-1].threadMessageId]);if(n){const ie=x.find(ge=>ge.messageId===n);ie&&H.add(ie.threadMessageId)}j(H),L(x.length-1)}},[e,x,R,n]);const D=c.useCallback(H=>{j(ie=>{const ge=new Set(ie);return ge.has(H)?ge.delete(H):ge.add(H),ge})},[]),C=c.useCallback(H=>{const ie=x[H];if(!ie)return;M.current.get(ie.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[x]),T=c.useCallback(()=>{if(x.length===0)return;const H=Math.min(E+1,x.length-1);L(H),C(H)},[x.length,E,C]),A=c.useCallback(()=>{if(x.length===0)return;const H=Math.max(E-1,0);L(H),C(H)},[x.length,E,C]),I=c.useCallback(()=>{const H=x[E];H&&D(H.threadMessageId)},[x,E,D]),{data:F}=be({...Mt(),staleTime:1/0}),N=F?.accounts?.[0],q=!!N?.smtpHost;Gv({messages:x,expandedIds:O,threadId:e,mailboxId:t,accountId:N?.accountId});const{toggleStar:Q,isPending:ae,pendingMessageId:U}=vo({threadId:e,mailboxId:t,messages:x}),[z,ee]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(ee(l),u?.())},[l,u]);const{data:me}=be({...ar({path:{messageId:k?.messageId??""}}),enabled:!!k&&z!==null}),fe=c.useCallback(()=>{ee("reply")},[]),se=c.useCallback(()=>{ee("reply_all")},[]),W=c.useCallback(()=>{ee("forward")},[]),pe=c.useCallback(()=>{ee(null),u?.()},[u]);if(xo({enabled:!y&&x.length>0&&z===null,bindings:[{key:"j",handler:T,preventDefault:!0},{key:"ArrowDown",handler:T,preventDefault:!0},{key:"k",handler:A,preventDefault:!0},{key:"ArrowUp",handler:A,preventDefault:!0},{key:"Enter",handler:I,preventDefault:!0},{key:"o",handler:I,preventDefault:!0},...q?[{key:"r",handler:fe,preventDefault:!0},{key:"R",handler:se,noModifiers:!1,preventDefault:!0},{key:"f",handler:W,preventDefault:!0}]:[]]}),y)return r.jsx(f0,{});if(b)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(Jt,{title:"Couldn't load this conversation",error:S,onRetry:()=>w()})});if(x.length===0)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(Eu,{message:"No messages in this thread"})});const ve=s||x[0]?.subject||"(No subject)",Ne=x.length,we=H=>r.jsx("div",{children:x.map((ie,ge)=>r.jsx("div",{ref:ze=>{ze&&M.current.set(ie.threadMessageId,ze)},children:r.jsx(d0,{threadMessage:ie,isExpanded:O.has(ie.threadMessageId),isFocused:ge===E,onToggle:()=>D(ie.threadMessageId),onToggleStar:()=>Q(ie.messageId,ie.hasStars),isStarPending:ae&&U===ie.messageId,accountId:g,mobile:H,onReply:H&&q?fe:void 0,onReplyAll:H&&q?se:void 0,onForward:H&&q?W:void 0})},ie.threadMessageId))}),X=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:ve}),r.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Ne," ",Ne===1?"message":"messages"]})]});return h?r.jsxs("article",{className:"h-full flex flex-col",children:[X,a?.dkimMismatch&&r.jsx(il,{authenticity:a,onOpenIntelligence:o}),r.jsx("div",{className:"flex-1 overflow-auto",children:we(!1)}),z!==null&&r.jsx(Ji,{mode:z,account:N,sourceMessage:me,onClose:pe})]}):r.jsxs(Wp,{thread:{subject:ve,messages:[]},onBack:i??(()=>{}),intelligenceOpen:d,onToggleIntelligence:o,touchHandlers:v,children:[a?.dkimMismatch&&r.jsx(il,{authenticity:a,onOpenIntelligence:o}),we(!0),z!==null&&r.jsx(Ji,{mode:z,account:N,sourceMessage:me,onClose:pe})]})},m0=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function id(e){return!!e&&m0.has(e)}const ld=3e3,h0=ld*2,ll={syncing:!1,resolved:!1,synced:0,total:0};function p0(e,t){const s=e.join(","),[n,a]=c.useState(!1),[o,i]=c.useState(!1);c.useEffect(()=>{a(!1),i(!1)},[s,t]),c.useEffect(()=>{if(!t)return;const g=setTimeout(()=>i(!0),h0);return()=>clearTimeout(g)},[s,t]);const l=pt({queries:e.map(g=>({...sm({path:{accountId:g}}),enabled:t&&!n,refetchInterval:ld,meta:{softError:!0}}))}),u=l.every(g=>g.isSuccess||g.isError),m=l.length===0||u||o;let f=!1,d=0,h=0;for(const g of l)if(id(g.data?.syncPhase)){f=!0;for(const p of g.data?.mailboxes??[])d+=p.messagesSynced,h+=p.messagesTotal}const v=t&&m&&!f;return c.useEffect(()=>{v&&a(!0)},[v]),!t||!m?ll:{syncing:f,resolved:!0,synced:d,total:h}}function gs(){const{mailboxNameIndex:e,accountNameIndex:t}=Ae();return{...It({select:n=>pu(n.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Io=e=>e.trim().toLocaleLowerCase(),cd={personal:"Personal",uncategorized:"Unclassified",transactional:"Transactional",newsletter:"Newsletter",marketing:"Marketing",social:"Social",automated:"Automated"},g0=Object.values(ot).map(e=>({value:e,label:cd[e]})),x0={unclassified:"uncategorized"},wa=[{name:"from",label:"Sender",values:"contact"},{name:"subject",label:"Subject",values:"text"},{name:"category",label:"Category",values:"fixed",options:g0},{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"}],b0=new Map(wa.map(e=>[e.name,e])),ud=e=>b0.get(e.toLowerCase()),v0=/^\d{4}-\d{2}-\d{2}$/,y0=e=>/[\s"]/.test(e),w0=e=>y0(e)?`"${e.replace(/"/g,"")}"`:e,dd=(e,t)=>`${e}:${w0(t)}`,S0=e=>{if(!e.startsWith('"'))return e;const t=e.slice(1);return t.endsWith('"')?t.slice(0,-1):t};function To(e){const t=[];let s=-1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];if(o==='"'){n=!n,s<0&&(s=a);continue}if(!n&&/\s/.test(o)){s>=0&&t.push({raw:e.slice(s,a),start:s,end:a}),s=-1;continue}s<0&&(s=a)}return s>=0&&t.push({raw:e.slice(s),start:s,end:e.length}),t}function fd(e){const t=e.indexOf(":");if(t<=0)return;const s=e.slice(t+1);return{name:e.slice(0,t).toLowerCase(),value:S0(s),rawValue:s}}function k0(e,t,s){if(!v0.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 C0(e){const t=e.toLowerCase(),s=x0[t];return s||Object.values(ot).find(a=>a===t)}function j0(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 N0(e,t){const s=fd(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=C0(a);return o?{type:"category",raw:e,value:a,category:o}:void 0}case"is":return j0(e,a);case"has":return a.toLowerCase()==="attachment"?{type:"hasAttachment",raw:e}:void 0;case"before":case"after":return k0(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 To(e)){const o=N0(a.raw,t);o?s.push(o):n.push(a.raw)}return{freeText:n.join(" "),tokens:s}}function E0(e,t){return To(e).filter(s=>s.raw!==t.raw).map(s=>s.raw).join(" ")}function md(e){switch(e.type){case"from":return`From: ${e.value}`;case"subject":return`Subject: ${e.value}`;case"category":return`Category: ${cd[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 I0=20,T0=new Set(Object.values(ot)),R0=e=>e!==void 0&&T0.has(e)?e:void 0,M0=e=>{if(e.some(t=>t.type==="isUnread"))return!1;if(e.some(t=>t.type==="isRead"))return!0};function hd({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Ae(),n=gs(),a=It({select:x=>x.matches}),o=Io(s),{freeText:i,tokens:l}=Bs(o,n),u=i.length>0,m=l.find(x=>x.type==="category"),f=R0(t)??m?.category,d=l.some(x=>x.type==="hasAttachment")?!0:void 0,h=l.some(x=>x.type==="isStarred")?!0:void 0,v=M0(l),g=l.find(x=>x.type==="after"),p=l.find(x=>x.type==="before"),y=l.find(x=>x.type==="in"),b=ov({matches:a,callerMailboxId:e,inTokenMailboxId:y?.mailboxId}),{data:S,isLoading:w}=be({...ql({query:{query:i,mailboxId:b,limit:I0,...f!==void 0?{category:f}:{},...d!==void 0?{hasAttachment:d}:{},...h!==void 0?{hasStars:h}:{},...v!==void 0?{isRead:v}:{},...g?{sentDateFrom:g.epochSeconds}:{},...p?{sentDateTo:p.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:S?.items??[],isLoading:u&&w}}const A0=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),O0=e=>[...e].sort(A0);function Gn(e){const t=e.authenticity?.dkimMismatch===!0;return{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:ht(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:wr(e.category),suspicious:t}}function cl(e){return e.filter(t=>t.muted!==!0)}function P0(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 ul=[{id:"personal",label:"Personal",category:ot.personal},{id:"transactional",label:"Transactional",category:ot.transactional},{id:"newsletter",label:"Newsletter",category:ot.newsletter},{id:"marketing",label:"Marketing",category:ot.marketing},{id:"social",label:"Social",category:ot.social},{id:"automated",label:"Automated",category:ot.automated},{id:"uncategorized",label:"Unclassified",category:ot.uncategorized}];function D0(e){const t=new Map(ul.map(n=>[n.category,[]]));for(const n of e){const a=n.category??ot.uncategorized;(t.get(a)??t.get(ot.uncategorized))?.push(n)}const s=[];for(const n of ul){const a=t.get(n.category);a&&a.length>0&&s.push({id:n.id,label:n.label,threads:a})}return s}function pd(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Ro(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 L0={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function F0(e){return L0[e]??e}function $0(e,t){const{folder:s}=Ua(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:ht(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Sa(e,t){const{folder:s}=Ua(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.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function _0(e,t){const{mailboxId:s,folder:n}=Ua(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?ht(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:F0(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...n?{folder:n}:{}}}function gd(e,t,s){const n=new Set(t),a=[];for(const o of[...e].sort((i,l)=>l.score-i.score))n.has(o.threadId)||(n.add(o.threadId),a.push(_0(o,s)));return a}function xd(e){const{spam:t}=oo([...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 z0=e=>{const{mailboxId:t,messages:s}=e,n=Me(),{pushError:a}=st(),{mutateAsync:o,isPending:i}=Fe({...nm(),onError:(u,m)=>{a({title:m.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:mt(u),error:u})},onSettled:(u,m,f)=>{Pt(n,Ot(vr(f.body.messageIds??[],s??[],t)))}});return{applyLabel:c.useCallback((u,m,f)=>{u.length!==0&&br(u,d=>o({body:{messageIds:d,labelId:m,action:f}}))},[o]),isPending:i}};function bd({accountId:e,mailboxId:t,messageIds:s}){const{labels:n}=Ya(e),{applyLabel:a}=z0({mailboxId:t}),o=c.useMemo(()=>n.map(i=>({key:i.labelId,label:i.name,icon:r.jsx("span",{className:`size-2.5 rounded-full ${rm(i.color)?qo[i.color]:qo.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[n,s,a]);return o.length===0?null:r.jsx(no,{triggerLabel:"Apply label to selected messages",triggerIcon:r.jsx(am,{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 B0=768,K0=1024,vd=e=>e!=="desktop",Cr=()=>{const e=Wo(`(min-width: ${B0}px)`);return Wo(`(min-width: ${K0}px)`)?"desktop":e?"tablet":"phone"},yd=8;function Mo(e,t){const s=Math.max(0,Math.min(t,e.length)),n=To(e).find(o=>s>=o.start&&s<=o.end);if(!n)return{start:s,end:s,raw:""};const a=fd(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 U0(e,t){const s=Mo(e,t);if(s.name===void 0)return{kind:"token",query:s.raw};const n=ud(s.name);if(n)return{kind:"value",token:n.name,source:n.values,query:s.value??""}}const q0={mailbox:"mailboxes",account:"accounts",contact:"contacts"},H0=(e,t)=>{if(e.values==="fixed")return e.options??[];const s=q0[e.values];return s?t[s]??[]:[]},W0=(e,t)=>{if(t==="")return 1;const s=e.toLowerCase();return s.startsWith(t)?0:s.includes(t)?1:-1},ka=(e,...t)=>{let s=-1;for(const n of t){if(n===void 0)continue;const a=W0(n,e);a<0||(s<0||a<s)&&(s=a)}return s},wd=e=>{const t=new Set;return e.filter(s=>s.rank>=0).sort((s,n)=>s.rank-n.rank).filter(s=>{const n=s.suggestion.value.toLowerCase();return t.has(n)?!1:(t.add(n),!0)}).slice(0,yd).map(s=>s.suggestion)},dl=e=>({value:`${e.name}:`,label:`${e.name}:`,hint:e.label});function V0(e){const t=e.trim().toLowerCase();if(t==="")return wa.map(dl);const s=[];for(const n of wa)if(s.push({rank:ka(t,`${n.name}:`,n.label),suggestion:dl(n)}),n.values==="fixed")for(const a of n.options??[]){const o=dd(n.name,a.value);s.push({rank:ka(t,o,a.label),suggestion:{value:o,label:a.label??o,hint:o}})}return wd(s)}function Q0(e,t,s){const n=t.trim().toLowerCase(),a=H0(e,s).map(o=>({rank:ka(n,o.value,o.label),suggestion:{value:dd(e.name,o.value),label:o.label??o.value,...o.hint?{hint:o.hint}:{}}}));return wd(a)}function G0(e,t,s={}){const n=Mo(e,t);if(n.name===void 0)return V0(n.raw);const a=ud(n.name);return a?Q0(a,n.value??"",s):[]}function Y0(e,t,s){const n=Mo(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 X0=e=>({value:e.normalizedEmail,...e.displayName?{label:e.displayName,hint:e.normalizedEmail}:{}});function J0(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 Z0(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 ew(e,t=[]){const s=e.flat().filter(o=>o.fullPath),n=new Map;for(const o of s){const i=aa(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=aa(o.fullPath),l=n.get(i.toLowerCase())===1,u=t.length>1?a.get(o.accountId):void 0;return{value:l?i:o.fullPath,label:o.displayNameOverride?.trim()||i,...u?{hint:u}:{}}})}function tw(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 sw=250,nw=2;function rw({query:e,cursor:t,enabled:s}){const{accounts:n}=Ae(),{mailboxesByName:a}=gs(),o=a!==void 0,i=s?U0(e,t):void 0,l=i?.source==="contact"?i.query.trim():"",u=ir(l,sw),{data:m}=be({...tr({query:{q:u,limit:yd}}),enabled:u.length>=nw}),f=pt({queries:n.map(g=>({...it({path:{accountId:g.accountId}}),staleTime:1/0}))}),d=c.useMemo(()=>o?ew(f.map(g=>g.data?.items??[]),n):[],[o,f,n]),h=c.useMemo(()=>tw(n),[n]),v=c.useMemo(()=>(m?.items??[]).map(X0),[m]);return c.useMemo(()=>{if(!s)return[];const g=G0(e,t,{mailboxes:d,accounts:h,contacts:v});return o?g:g.filter(p=>p.value!=="in:")},[s,e,t,d,h,v,o])}const aw={title:"",navSlot:null,titleMeta:null,searchSlot:null,searchField:null,searchResults:null,makeFilterSlot:null},Ca=c.createContext(aw),jr=()=>c.useContext(Ca),ow=new Set(["hasAttachment","isUnread","isRead","isStarred","category","before","after"]),iw=e=>ow.has(e),lw=(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}iw(u.type)&&n.push({type:u.type,label:md(u)})}const i=e.freeText.trim(),l=i.length>0;return l&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:n,targetAccountId:o,keptTerms:l,droppedSemantic:l&&t}},cw=(e,t,s)=>e.targetAccountId??t??s[0]?.accountId,Sd="remit.recentSearches",uw=5;function ja(){try{const e=localStorage.getItem(Sd);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function fl(e){const t=e.trim();if(!t)return ja();const s=[t,...ja().filter(n=>n!==t)].slice(0,uw);try{localStorage.setItem(Sd,JSON.stringify(s))}catch{return s}return s}const dw=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function kd({title:e,unreadCount:t,children:s,selectionBar:n,paneOverlay:a,footer:o,searchFilter:i,searchResults:l,searchLoading:u,relatedResults:m,relatedLoading:f,onSelectSearchResult:d,searchResultsLabel:h="Top matches",relatedResultsLabel:v="Related",searchResultsInBody:g=!1}){const{accounts:p,resultFolderIndex:y,searchQuery:b,searchInput:S,onSearchChange:w,onSearchClear:x,searchViewKey:k}=Ae(),M=gs(),O=Ke(),j=fs(),R=Cr(),[P,E]=c.useState(!1),[L,D]=c.useState(ja),C=om(),T=c.useRef(k);c.useEffect(()=>{T.current!==k&&(T.current=k,E(!1))},[k]);const[A,I]=c.useState(0),[F,N]=c.useState(!1),[q,Q]=c.useState(void 0),ae=rw({query:S,cursor:A,enabled:F&&S.trim().length>0}),U=c.useCallback(te=>{const ce=Y0(S,A,te);w(ce.query),Q({cursor:ce.cursor})},[S,A,w]),z=zl({count:ae.length,onAccept:te=>{const ce=ae[te];ce&&U(ce)}}),{comboboxProps:ee,handleKeyDown:me}=z,fe=c.useMemo(()=>({comboboxProps:ee,onKeyDown:me,onCaretChange:I,onFocusChange:N,...q?{caret:q}:{}}),[ee,me,q]),se=z.open?r.jsx(Bl,{id:z.listId,suggestions:ae,activeIndex:z.activeIndex,optionId:z.optionId,onPick:U,onHighlight:z.setActiveIndex,label:"Search suggestions",className:"mx-row-inset mt-1 shrink-0"}):null,W=S.trim().length>0,{mailboxesByName:pe,accountsByName:ve}=M,Ne=c.useMemo(()=>Bs(S,{mailboxesByName:pe,accountsByName:ve}),[S,pe,ve]),we=Ne.tokens.map(te=>({label:md(te),onRemove:()=>w(E0(S,te))})),X=l??[],H=m??[],ie=W?[{id:"top",label:h,results:X},{id:"related",label:v,results:H}]:[],ze=!(X.length+H.length>0)&&(u===!0||f===!0),{scope:xe}=bu(p),B=It({select:te=>te.matches}),ue=gu(B),oe=lv(B,xe,ue?y.get(ue)?.role:void 0),ne=oe.kind==="global"?xd([...X,...H]):void 0,nt=ne?{kind:"global",onScopeToSpam:()=>O({to:"/mail/$mailboxId",params:{mailboxId:ne.mailboxId},search:{q:b||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:oe,Te=H.length>0,J=c.useMemo(()=>lw(Ne,{searchHadSemanticReach:Te}),[Ne,Te]),Se=W?J:void 0,Ve=W?{onClick:()=>{E(!1),C("properties","search")},blockedReason:bx(J)?void 0:"Add a sender or words to filter on"}:void 0,Oe=Ve?r.jsx($c,{...Ve}):null,he=dw({tier:R,hasLiveInput:W,hasCommittedQuery:b.trim().length>0,bodyRendersCommittedResults:g}),lt=te=>{D(fl(S)),d?.(te)},Xe=r.jsx(_c,{value:S,sections:ie,loading:ze,onSelectResult:lt,tokens:we,scope:nt}),Pe=n===void 0,Ue=he?r.jsx("div",{className:"h-full overflow-y-auto",children:Xe}):null,qe=Ue&&!Pe?Ue:s,Ze=Ue&&Pe?Ue:null,rt=vd(R),Ce=rt&&(P||W),G=c.useMemo(()=>({title:e,searchResults:Ze,makeFilterSlot:Oe,searchConversion:Se,navSlot:j&&!j.showNavPane&&r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(or,{className:"size-5"}),onClick:()=>j.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(im,{})]}),searchSlot:rt&&!Ce&&r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(Zn,{className:"size-5"}),onClick:()=>E(!0),"aria-label":"Search",className:"shrink-0"}),searchField:Ce&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(ao,{value:S,onChange:w,onClear:x,globalFocusKey:!1,showClearButton:!1,suggest:fe})}),r.jsx(le,{variant:"ghost",size:"touch",icon:r.jsx(Ct,{className:"size-5"}),onClick:()=>{x(),E(!1)},"aria-label":"Close search",className:"shrink-0"})]})}),[e,t,j,rt,Ce,S,w,x,fe,Ze,Oe,Se]);if(R==="phone"&&P){const te=ce=>{D(fl(S)),E(!1),d?.(ce)};return r.jsxs(Ca.Provider,{value:G,children:[r.jsx(wg,{value:S,onChange:w,onClear:x,onCancel:()=>{E(!1),x()},filter:i,recentSearches:L,onPickRecent:w,makeFilter:Ve,sections:ie,loading:ze,onSelectResult:te,tokens:we,scope:nt,suggest:fe,suggestList:se}),a]})}return r.jsx(Ca.Provider,{value:G,children:r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[n?.(G),se,r.jsx("div",{className:"min-h-0 flex-1",children:qe}),o,a]})})}const fw=120,Cd=({keyboardFocusedMessageId:e,openMessageId:t,enabled:s,open:n,delayMs:a=fw})=>{const o=c.useRef(n);o.current=n;const i=c.useRef(void 0);c.useEffect(()=>{const l=e;if(!s){i.current=l;return}if(l===void 0||l===t)return;if(l===i.current){i.current=void 0;return}const u=setTimeout(()=>o.current(l),a);return()=>clearTimeout(u)},[s,e,t,a])},mw=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:n})=>{const[a,o]=c.useState(s),[i,l]=c.useState(),u=c.useCallback(A=>{l(I=>I===A?I:void 0),o(A)},[]),m=Cc(),{selectedCount:f,toggle:d,clearSelection:h,selectRange:v,setAnchor:g,selectAll:p}=m,y=to(f,t),b=c.useRef(null),S=c.useRef(!1),w=c.useCallback(()=>{n?.(),h()},[h,n]),x=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),k=c.useCallback(A=>{if(A<0||A>=e.length)return;const I=e[A];if(y){d(I);return}b.current=I,S.current=!1,l(I),o(I)},[e,y,d]),M=c.useCallback(()=>{e.length!==0&&k(x<0?0:Math.min(x+1,e.length-1))},[e.length,x,k]),O=c.useCallback(()=>{e.length!==0&&k(x<=0?0:x-1)},[e.length,x,k]),j=c.useCallback(()=>k(0),[k]),R=c.useCallback(()=>k(e.length-1),[k,e.length]),P=c.useCallback(()=>{a&&d(a)},[a,d]),E=c.useCallback((A,I)=>{const F=Gh(I);return F==="range"?(v(e,A,a),!0):F==="toggle"?(d(A),!0):(w(),g(A),!1)},[e,a,v,d,w,g]),L=c.useCallback(A=>{const I=kc(e,a,A);I!==void 0&&(v(e,I),b.current=I,S.current=!1,l(void 0),o(I))},[e,a,v]),D=c.useCallback(()=>L(-1),[L]),C=c.useCallback(()=>L(1),[L]),T=c.useCallback(()=>{e.length>0&&p(e)},[e,p]);return{focusedMessageId:a,setFocusedMessageId:u,keyboardFocusedMessageId:i,focusIndex:x,pendingDomFocusRef:b,cursorMovedByPointerRef:S,selection:m,isMultiSelectMode:y,exitSelection:w,moveFocusToIndex:k,focusNext:M,focusPrevious:O,focusFirst:j,focusLast:R,toggleFocusedSelection:P,extendRangeUp:D,extendRangeDown:C,selectAllLoaded:T,handleRowSelect:E}};function jd(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Ao=c.createContext(null),hw=e=>{const t=c.useContext(Ao);return t?t.rowInteraction(e):null},Oo=()=>{const e=c.useContext(Ao);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},pw="[data-message-id]",gw=e=>Array.from(e.querySelectorAll(pw)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),xw=(e,t)=>e.length===t.length&&e.every((s,n)=>s===t[n]),bw=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const n=e.current;if(!n)return;const a=()=>{const i=gw(n);s(l=>xw(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(n,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function Nd({selectedMessageId:e,onOpen:t,onDeleteMessages:s,onSelectionVerb:n,wizardOpen:a=!1,isDeleting:o=!1,commandsRef:i,onTriageContextChange:l,children:u}){const m=Xt(),f=c.useRef(null),d=bw(f),h=mw({orderedIds:d,isDesktop:m,initialFocusedId:e}),{focusedMessageId:v,setFocusedMessageId:g,pendingDomFocusRef:p,cursorMovedByPointerRef:y,selection:b,isMultiSelectMode:S,exitSelection:w,handleRowSelect:x}=h,{selectedIds:k,selectedCount:M,isSelected:O,toggle:j,select:R,toggleAll:P}=b,E=d.length>0&&d.every(W=>k.has(W)),L=c.useCallback(()=>{d.length>0&&P(d)},[d,P]),{intersectWith:D}=b;c.useEffect(()=>{D(d)},[D,d]),c.useEffect(()=>{const W=p.current;W!==null&&(p.current=null,f.current?.querySelector(`[data-message-id="${W}"]`)?.focus())});const C=c.useCallback(W=>{y.current=!0,g(W)},[y,g]),T=c.useCallback(W=>{m||R(W)},[m,R]),A=c.useCallback(()=>{v&&t(v)},[v,t]),I=c.useCallback(W=>t(W,{replace:!0}),[t]);Cd({keyboardFocusedMessageId:h.keyboardFocusedMessageId,openMessageId:e,enabled:m&&M===0,open:I});const[F,N]=c.useState(null),q=c.useCallback(W=>F!==null?!0:M>0?(n(W),!0):W!=="delete"||!v?!1:(N([v]),!0),[F,M,n,v]),Q=c.useCallback(()=>{F!==null&&(s(F),N(null),w())},[F,s,w]),ae=c.useCallback(()=>N(null),[]),U=c.useCallback(()=>M===0?!1:(w(),!0),[M,w]),z=d.length>0;c.useEffect(()=>{if(i){if(!z){i.current=null;return}return i.current={focusNext:h.focusNext,focusPrevious:h.focusPrevious,focusFirst:h.focusFirst,focusLast:h.focusLast,openFocused:A,toggleSelect:h.toggleFocusedSelection,extendSelectDown:h.extendRangeDown,extendSelectUp:h.extendRangeUp,selectAll:h.selectAllLoaded,clearSelection:U,requestVerb:q,toggleDensity:()=>{}},()=>{i.current=null}}},[i,z,h.focusNext,h.focusPrevious,h.focusFirst,h.focusLast,h.toggleFocusedSelection,h.extendRangeDown,h.extendRangeUp,h.selectAllLoaded,A,U,q]);const ee=c.useMemo(()=>Array.from(k),[k]),me=F!==null;c.useEffect(()=>{l?.({focusedMessageId:v,selectedIds:ee,orderedIds:d,hasList:z,blocksKeyboard:me||a})},[l,v,ee,d,z,me,a]);const fe=jd(d,v),se=c.useMemo(()=>({selectedIds:k,selectedCount:M,exitSelection:w,startSelectionVerb:n,orderedIds:d,allSelected:E,toggleAllLoaded:L,rowInteraction:W=>({focused:W===v,isTabStop:W===fe,isDesktop:m,onFocusRow:C,selection:{isChecked:O(W),onToggleCheck:j,onRowSelect:x,isMultiSelectMode:S,onLongPress:T}})}),[k,M,w,n,d,E,L,v,fe,m,C,O,j,x,S,T]);return r.jsxs(Ao.Provider,{value:se,children:[r.jsx("div",{ref:f,className:"contents",children:u}),r.jsx(Xa,{isOpen:me,title:Zl(F?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:o,onConfirm:Q,onCancel:ae})]})}function vw({title:e,isDeleting:t}){const s=jr(),{selectedCount:n,exitSelection:a,startSelectionVerb:o,orderedIds:i,allSelected:l,toggleAllLoaded:u}=Oo();return r.jsx(lo,{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:l,indeterminate:n>0&&!l,onChange:u}:void 0})}const Jr=e=>{e.preventDefault(),e.stopPropagation()},yw=(e,t)=>{const s=c.useRef(!1),n=c.useCallback(i=>{if(s.current=!1,i.button!==0)return;const l=Hn(i);ni(l)&&t?.(e,l)&&(Jr(i),s.current=!0,i.currentTarget.focus(),l.shiftKey&&window.getSelection()?.removeAllRanges())},[t,e]),a=c.useCallback(i=>{!i.ctrlKey||!t||i.preventDefault()},[t]),o=c.useCallback(i=>{if(s.current)return s.current=!1,Jr(i),!0;const l=Hn(i);return!ni(l)||!t?.(e,l)?!1:(Jr(i),l.shiftKey&&window.getSelection()?.removeAllRanges(),!0)},[t,e]);return{onMouseDown:n,onContextMenu:a,claimClick:o}},ww=({thread:e,active:t=!1,focused:s,isTabStop:n,density:a="comfortable",isDesktop:o,badge:i,selection:l,inListbox:u=!1,linkMailboxId:m,onClick:f,onFocusRow:d})=>{const h=Me(),v=e.id,g=hw(v),p=s??g?.focused??!1,y=n??g?.isTabStop??!1,b=l??g?.selection,S=d??g?.onFocusRow,w=o??g?.isDesktop??!0,x=b?.isChecked??!1,k=b?.isMultiSelectMode??!1,M=b?.onToggleCheck,O=b?.onRowSelect,j=b?.onLongPress,R=c.useCallback(N=>{N.preventDefault(),N.stopPropagation(),M?.(v)},[M,v]),P=yw(v,O),E=c.useCallback(N=>{if(!P.claimClick(N)){if(!w){if(k){N.preventDefault(),N.stopPropagation(),M?.(v);return}f?.();return}O?.(v,Hn(N)),f?.()}},[P,w,k,M,O,f,v]),L=c.useCallback(()=>{j?.(v)},[j,v]),{longPressProps:D}=Rc({onLongPress:L,accessibilityDescription:x?"Deselect message":"Select message"}),C=c.useCallback(()=>{h.prefetchQuery(ar({path:{messageId:v}}))},[h,v]),T=c.useCallback(()=>{C(),S?.(v)},[C,S,v]),A=Ds({"data-list-row":"","data-message-row":!0,"data-message-id":v,...u?{role:"option","aria-selected":x}:{},tabIndex:y?0:-1,onClick:E,onMouseDown:P.onMouseDown,onContextMenu:P.onContextMenu,onMouseEnter:C,onFocus:T},w||!b?{}:D),I=_e(a==="compact"?Ec({active:t,focused:p}):_e("group",Fs({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",x&&"bg-accent-soft",!w&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?r.jsx(Ic,{thread:e}):r.jsx(so,{thread:e,badge:i,selection:b?{checked:x,alwaysVisible:k,onToggle:R}:void 0});return m===void 0?r.jsx("button",{type:"button",...A,className:I,children:F}):r.jsx(Kt,{to:"/mail/$mailboxId",params:{mailboxId:m},search:N=>({...N,selectedMessageId:v}),...A,className:I,children:F})},Po=c.memo(ww),Ed=8,Id=e=>e==="From"||e==="FromDomain",Sw=e=>({value:e.email,label:e.displayName??e.email,...e.displayName?{hint:e.email}:{},...e.fromSelection?{source:"selected"}:{}}),kw=e=>{const t=qc(e.email);if(t!==null)return{value:t,...e.fromSelection?{source:"selected"}:{}}},Cw=(e,t)=>e.value.toLowerCase().includes(t)||(e.label??"").toLowerCase().includes(t),jw=(e,t,s)=>{if(!Id(e))return[];const n=t.trim().toLowerCase(),a=new Set,o=[];for(const i of s){if(i.email.trim()==="")continue;const l=e==="From"?Sw(i):kw(i);if(!l)continue;const u=l.value.toLowerCase();if(!(u===""||a.has(u))&&(a.add(u),u!==n&&!(n!==""&&!Cw(l,n))&&(o.push(l),o.length===Ed)))break}return o},Nw=250,Ew=2,Iw=(e,t,s)=>{const n=t.trim(),a=ir(n,Nw),o=e!==void 0&&Id(e),{data:i}=be({...tr({query:{q:a,limit:Ed}}),enabled:o&&a.length>=Ew});if(!o||e===void 0)return[];const l=[...s.map(u=>({email:u,fromSelection:!0})),...(i?.items??[]).map(u=>({email:u.normalizedEmail,...u.displayName?{displayName:u.displayName}:{}}))];return jw(e,n,l)},Tw={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},Td={delete:"moved to Trash",move:"moved",markRead:"marked as read"},Rw={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},Mw={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},Aw={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},Ow=(e,t,s)=>Tw[e](Vt(t),Vt(s)),ml=(e,t)=>`${Vt(t)} ${Td[e]}. Your mail server is still catching up.`,Pw=e=>`Stopped after ${Vt(e)}`,Dw=(e,t,s)=>`${Vt(t)} of ${Vt(s)} ${Td[e]}. Nothing was sent for the rest, so they are untouched.`,Lw=(e,t)=>t>0?`Stopped after ${Vt(t)} — some messages ${Rw[e]}`:Mw[e],Fw=e=>Aw[e],$w=e=>e==="delete"?"danger":"info",_w=100,zw=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],Rd=({mailboxId:e,accountId:t,enabled:s,predicateKey:n,searchQuery:a})=>{const[o,i]=c.useState({kind:"idle"}),[l,u]=c.useState(void 0),[m,f]=c.useState(void 0),d=c.useRef(!1),h=c.useRef(!1),v=Me(),{pushError:g}=st();c.useEffect(()=>{h.current||(d.current=!0),i({kind:"idle"})},[s,n]);const p=c.useRef(a);p.current=a;const y=c.useCallback(j=>async R=>{const{data:P}=await oa({path:{mailboxId:e},query:{...j,continuationToken:R,limit:_w},throwOnError:!0});return{ids:(P.items??[]).map(E=>E.messageId),continuationToken:P.continuationToken}},[e]),b=c.useCallback(async()=>{const{data:j}=await oa({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=c.useCallback(j=>async R=>{if(j.kind==="move"){const{data:E}=await lm({body:{messageIds:R,destinationMailboxId:j.destinationMailboxId},throwOnError:!0});return E}if(j.kind==="markRead"){const{data:E}=await cm({body:{messageIds:R,isRead:!0},throwOnError:!0});return E}const{data:P}=await um({body:{messageIds:R},throwOnError:!0});return P},[]),w=c.useCallback(j=>{Pt(v,Ot(zw(j,e))),t&&v.invalidateQueries({queryKey:ms({path:{accountId:t}})})},[v,e,t]),x=c.useCallback(()=>{d.current=!1,i({kind:"counting"}),b().then(j=>{if(d.current){i({kind:"idle"});return}i({kind:"escalated",total:j})},j=>{g(is("Couldn't count matching messages","The count didn't finish.",j)),i({kind:"idle"})})},[b,g]),k=c.useCallback(()=>{d.current=!0},[]),M=c.useCallback(()=>{h.current||(d.current=!0,i({kind:"idle"}))},[]),O=c.useCallback(async(j,R)=>{d.current=!1,h.current=!0,u(j);const P=C=>f(Hv(C)),E=S(j),L=y(p.current);let D;try{D=R!==void 0?await Iu(R,E,P,()=>d.current):await qv(L,o.kind==="escalated"?o.total:0,E,P,()=>d.current)}finally{h.current=!1}return u(void 0),f(void 0),i({kind:"idle"}),D.error&&g(is(Lw(j.kind,D.done),Fw(j.kind),D.error)),D.done>0&&w(j),D},[S,y,o,g,w]);return{phase:o,escalate:x,stop:k,clear:M,isRunning:l!==void 0,runningAction:l,progress:m,runAction:O}},Md=12,Bw=e=>{const{envelope:t}=e,s=t.from[0];return{id:t.messageId,sender:s?Hc({normalizedEmail:s.normalizedEmail,displayName:s.displayName}):"Unknown",subject:t.subject??"(No subject)",date:ht(t.date)}},Kw=(e,t)=>{const s=e!==void 0&&t!==void 0,{data:n,isLoading:a}=be({...Hl({path:{mailboxId:e??""},query:{...t,limit:Md}}),enabled:s,staleTime:3e4});return{messages:(n?.items??[]).map(Uw),isPending:s&&a}},Uw=e=>({id:e.messageId,sender:e.fromName||e.fromEmail||"Unknown",subject:e.subject??"(No subject)",date:ht(e.sentDate)}),qw=e=>pt({queries:e.slice(0,Md).map(t=>({...ar({path:{messageId:t}}),staleTime:Number.POSITIVE_INFINITY})),combine:t=>({messages:t.map(s=>s.data).filter(s=>s!==void 0).map(Bw),isPending:t.some(s=>s.isPending)})}),Hw=e=>({matchOperator:"Or",literalClauses:mr(e)}),Ww=(e,t,s)=>{const n=Fe(dm()),{mutate:a,reset:o}=n,[i,l]=c.useState(!1),u=c.useMemo(()=>fr(s),[s]),m=c.useCallback(()=>{!e||!t||(l(!1),a({path:{accountId:e},body:Vo({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),f=c.useCallback(()=>{l(!1),o()},[o]),d=n.data,h=d?.semanticUnavailable===!0&&!i&&u.length>0;c.useEffect(()=>{!h||!e||(l(!0),a({path:{accountId:e},body:Vo(Hw(u))}))},[h,e,u,a]);const v=i||(d?.semanticUnavailable??!1),g=n.isPending||h,p=i?{matchOperator:"Or",literalClauses:mr(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:m,reset:f,matchedCount:g?void 0:d?.matchedCount,messageIds:g?void 0:d?.messageIds,semanticUnavailable:v,senderFallback:i,senders:u,matchPredicate:p,isPending:g,isError:n.isError,error:n.error}},Vw=()=>[nr({path:{mailboxId:""}}),Ba({path:{mailboxId:""}}),Ka()].map(e=>[{_id:e[0]._id}]),Qw=e=>Tu(e)?e.pages:Ru(e)?[e]:[],Gw=e=>typeof e=="object"&&e!==null&&typeof e.messageId=="string",Yw=(e,t)=>{const s=new Set(t),n=new Map;for(const a of e)for(const o of Qw(a))for(const i of o.items){if(!Gw(i)||!s.has(i.messageId))continue;const l=i.subject?.trim();l&&n.set(i.messageId,l)}return t.map(a=>n.get(a)).filter(a=>a!==void 0)},Xw=e=>{const t=Me(),s=e.join("\0");return c.useMemo(()=>{const n=Vw().flatMap(a=>t.getQueriesData({queryKey:a}).map(([,o])=>o));return Yw(n,e)},[t,s])},Jw=({failure:e,isStarting:t,isRunning:s,isDone:n,failedCount:a,ruleSaved:o})=>e?.kind==="startFailed"?o?"backApplyStartFailed":"commitFailed":n?a>0?"backApplyFailed":"backApplyComplete":e?.kind==="statusUnreadable"?"statusUnknown":t||s?"backApplyRunning":"saving",Zw={clauses:[],matchOperator:"any"},eS={clauses:[],matchOperator:"all",droppedFacets:[],keptTerms:!1,droppedSemantic:!1},tS=[],js={state:"saving",matched:0,applied:0,failed:0,failures:[]},Zr=(e,t)=>e.map((s,n)=>({...s,id:`${t}-${n}`})),hl=(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},ea=e=>e==="move"||e==="junk"||e==="organize",pl=(e,t)=>({done:0,failedIds:[...t],cancelled:!1,error:new Error(e==="junk"?"This account has no Junk folder appointed, so there is nowhere to file these. Appoint one under Settings › Folders.":"No destination was chosen, so there is nowhere to file these. Go back and pick a folder.")});function sS({verb:e,accountId:t,mailboxId:s,selection:n,crossAccount:a=!1,escalated:o,escalatedProgress:i,searchConversion:l,onFinished:u,onRunEnded:m,step:f,goToStep:d,goBack:h,closeWizard:v}){const[g]=c.useState(()=>l),[p]=c.useState(()=>o),y=g!==void 0,[b,S]=c.useState(y?"properties":"selected"),w=p?"escalated":b,[x,k]=c.useState(()=>g?{clauses:Zr(g.clauses,"search"),matchOperator:g.matchOperator}:Zw),[M,O]=c.useState(void 0),[j,R]=c.useState(void 0),[P,E]=c.useState(!1),[L,D]=c.useState(void 0),[C,T]=c.useState(void 0),[A,I]=c.useState(),F=c.useRef(!1),N=c.useRef(!1),q=c.useMemo(()=>n.map(_=>_.id),[n]),Q=c.useMemo(()=>n.map(_=>_.email).filter(Boolean),[n]),ae=q[0],U=Xw(q),{junkMailboxId:z}=_s(t),ee=Ww(p?void 0:t,ae,Q),{preview:me}=ee;c.useEffect(()=>{me()},[me]);const fe=w==="similar"||w==="properties",se=c.useMemo(()=>({matchOperator:x.matchOperator==="all"?"And":"Or",literalClauses:x.clauses.map(_=>({field:_.field,value:_.value}))}),[x.clauses,x.matchOperator]),W=w==="similar"?ee.matchPredicate:se,{count:pe,matchedIds:ve}=zm(fe?t:void 0,W),Ne=qw(fe?ve:[]),we=Kw(p?s:void 0,p?.searchQuery),X=p?{status:"ready",count:p.total}:fe?pe:{status:"ready",count:n.length},{data:H}=be({...it({path:{accountId:t??""}}),enabled:!!t,staleTime:Number.POSITIVE_INFINITY}),ie=So(t),ge=Wa(),ze=c.useMemo(()=>Va({mailboxes:H?.items??[],folderAppointments:ie,currentMailboxId:s,translator:ge}),[H?.items,ie,s,ge]),{createFolderIn:xe}=ec(t),B=ze.find(_=>_.id===x.moveMailboxId)?.label,ue=cx(n.map(_=>({normalizedEmail:_.email,displayName:_.sender}))),oe=xx({match:w==="properties"&&x.clauses[0]?.value.trim()||void 0,sender:ue?Hc(ue):void 0,folder:B}),ne=c.useMemo(()=>({...x,name:x.name??oe}),[x,oe]),nt=Iw(M?.draft.field,M?.draft.value??"",Q),Te=Bm(t),J=Km(t),Se=Rd({mailboxId:s??"",accountId:t,enabled:!1,predicateKey:"selection-wizard",searchQuery:{}}),{runAction:Ve}=Se,Oe=hm({verb:e,mode:w,scope:x.scope,fromSearch:y}),he=Oe[Ho(Oe,f)],lt=!a&&!!t,Xe=lt?void 0:xm,Pe=lt?void 0:bm,qe=(_=>{if(_==="folder")return Pe;if(_==="rule")return ne.scope==="standing"||ne.scope==="until"?Xe:void 0})(he)??pm(he,ne,X),Ze=c.useCallback(()=>Zr(gx(Q,U),"seed"),[Q,U]),rt=c.useCallback(_=>{S(_),k(Y=>({...Y,widen:_==="similar"&&ae?{anchorCount:Math.max(n.length,1)}:void 0,..._==="properties"&&Y.clauses.length===0?{clauses:Ze()}:{}}))},[ae,n.length,Ze]),Ce=c.useCallback(()=>{E(!0),S("properties"),k(_=>({..._,widen:void 0,clauses:Zr(mr(Q),"sender"),matchOperator:"any"})),d("properties")},[Q,d]),G=ee.semanticUnavailable||ee.isError;c.useEffect(()=>{he==="match"&&(w!=="similar"||!G||P||Ce())},[he,w,G,P,Ce]);const te=c.useCallback(()=>{O({mode:"add",draft:{field:"From",value:""}})},[]),ce=c.useCallback(_=>{const Y=x.clauses.find(je=>je.id===_);Y&&O({mode:"edit",clauseId:_,draft:{field:Y.field,value:Y.value}})},[x.clauses]),de=c.useCallback(_=>{k(Y=>({...Y,clauses:Y.clauses.filter(je=>je.id!==_)}))},[]),ke=c.useCallback(_=>{O(Y=>Y&&{...Y,draft:_})},[]),Ee=c.useCallback(()=>{O(_=>{if(!_)return;const Y=Um(_.draft.field,_.draft.value),je={..._.draft,value:Y};k(ut=>({...ut,clauses:_.clauseId?ut.clauses.map(bt=>bt.id===_.clauseId?{...bt,...je}:bt):[...ut.clauses,{id:crypto.randomUUID(),...je}]}))})},[]),De=c.useCallback(()=>{if(qe){R(he);return}R(void 0);const _=Oe[Ho(Oe,he)+1];_&&d(_)},[qe,he,Oe,d]),He=c.useCallback(async _=>{const Y=hl(e,ne.moveMailboxId,z);if(!Y){T({matched:_.length,outcome:pl(e,_)});return}T({matched:_.length});const je=await Ve(Y,[..._]);T({matched:_.length,outcome:je}),N.current&&m?.(Y.kind,_.length,je)},[e,ne.moveMailboxId,z,Ve,m]),ye=c.useCallback(async()=>{if(!p)return;const _=hl(e,ne.moveMailboxId,z);if(!_){T({matched:p.total,outcome:pl(e,[])});return}T({matched:p.total});const Y=await p.run(_);T({matched:p.total,outcome:Y}),N.current&&m?.(_.kind,p.total,Y)},[p,e,ne.moveMailboxId,z,m]),{start:Qe}=Te,{createFilterAsync:Ge}=J,Le=c.useCallback(()=>{if(p){ye();return}const _=qm({mode:b,ruleScope:ne.scope}),Y=Hm({mode:b,ruleScope:ne.scope,anchorMessageId:ae,clauses:ne.clauses,matchOperator:ne.matchOperator,moveMailboxId:ne.moveMailboxId,until:ne.until});if(D(_),_==="standing"||_==="temporary"){const je=Wm(Y)?Y:void 0;I(je),Ge(Y,_,(ne.name??"").trim()).then(ut=>{ut&&je&&Qe(je)});return}if(_==="all-like-these"&&ea(e)){Qe(Y);return}He(_==="just-these"?q:ve)},[p,ye,b,ne,ae,e,q,ve,Ge,Qe,He]),et=c.useCallback(()=>{if(qe){R(he);return}F.current||(F.current=!0,d("run"),Le())},[qe,he,d,Le]),Ye=c.useCallback(_=>{const Y=Te.progress,je=Jw({failure:Te.failure,isStarting:Te.isStarting,isRunning:Te.isRunning,isDone:Te.isDone,failedCount:Y.failedCount,ruleSaved:_});return je==="saving"||je==="commitFailed"||je==="backApplyStartFailed"?{...js,state:je}:{state:je,matched:Y.matchedCount,applied:Y.appliedCount,failed:je==="backApplyFailed"?Y.failedCount:0,failures:[]}},[Te]),Dt=c.useMemo(()=>{const _=new Map;for(const Y of[...n,...Ne.messages,...we.messages])_.set(Y.id,Y);return _},[n,Ne.messages,we.messages]),es=p?i:Se.progress,Lt=c.useCallback(()=>{if(!C)return js;const{matched:_,outcome:Y}=C;if(!Y){const vt=es?.done??0;return{state:"backApplyRunning",matched:Math.max(_,vt),applied:vt,failed:0,failures:[]}}if(!(Y.cancelled||Y.error!==void 0))return{state:"backApplyComplete",matched:Math.max(_,Y.done),applied:Y.done,failed:0,failures:[]};if(Y.done===0)return{...js,state:"commitFailed"};const ut=Y.failedIds.map(vt=>Dt.get(vt)).filter(vt=>vt!==void 0),bt=Y.failedIds.length>0?Y.failedIds.length:Math.max(_-Y.done,1);return{state:"runStopped",matched:Math.max(_,Y.done),applied:Y.done,failed:bt,failures:ut}},[C,es,Dt]),tt=p?Lt():L==="standing"||L==="temporary"?J.isError?{...js,state:"commitFailed"}:J.isSuccess?A?Ye(!0):{...js,state:"filterSaved"}:js:L==="all-like-these"&&ea(e)?Ye(!1):Lt(),xt=()=>{if(tt.state==="statusUnknown"){Te.refreshStatus();return}if(p){ye();return}if(L==="standing"||L==="temporary"){if(J.isError){J.reset(),Le();return}A&&Qe(A);return}if(L==="all-like-these"&&ea(e)){Le();return}const _=C?.outcome?.failedIds??[];He(_.length>0?_:q)},Ft=c.useCallback(()=>{v(Oe,he)},[v,Oe,he]),ct=c.useCallback(()=>{N.current=!0,v(Oe,he),u()},[v,Oe,he,u]),{stop:$t}=Se,Us=C!==void 0&&C.outcome===void 0,qs=c.useCallback(()=>{if(p){p.stop();return}$t()},[p,$t]);ou({shouldBlockFn:({action:_})=>_!=="BACK"?!1:(ct(),!0),enableBeforeUnload:!1,disabled:he!=="run"});const ts={messages:p?we.messages:fe?Ne.messages:n,count:X,label:w==="selected"?"Your selection":"A sample of what matches",emptyReason:w==="similar"&&G?"notIndexed":"noMatch",loading:p?we.isPending:fe&&(X.status==="loading"||Ne.isPending)};return r.jsx(gm,{verb:e,steps:Oe,step:he,blockedReason:qe,nudged:j===he,onBack:h,onExit:he==="run"?ct:Ft,onContinue:De,onCommit:et,match:{selectedCount:n.length,mode:w,onModeChange:rt,semanticUnavailable:G,semanticErrorDetail:ee.error instanceof Error?ee.error.message:void 0,semanticFallbackTaken:P,onSemanticFallback:Ce,escalatedScope:p?.scope,sample:ts},properties:{clauses:ne.clauses,matchOperator:ne.matchOperator,onMatchOperatorChange:_=>k(Y=>({...Y,matchOperator:_})),clauseEdit:M,onStartAddClause:te,onStartEditClause:ce,onRemoveClause:de,onChangeDraft:ke,onSubmitClause:Ee,onCancelClause:()=>O(void 0),clauseFields:Vm,clauseSuggestions:nt,conversionNotice:g?vx(g):void 0,semanticFallbackTaken:P,sample:{...ts,label:"What this matches"}},folder:{folders:ze,mailboxId:ne.moveMailboxId,delimiter:Qa(H?.items??[]),onSelect:_=>k(Y=>({...Y,moveMailboxId:_})),onCreateFolder:t?xe:void 0,restriction:Pe},rule:{draft:ne,onScopeChange:_=>k(Y=>({...Y,scope:_})),onUntilChange:_=>k(Y=>({...Y,until:_})),restriction:Xe},name:{name:ne.name??"",onNameChange:_=>k(Y=>({...Y,name:_})),nudged:j===he},review:{verb:e,mode:w,selectedCount:n.length,clauses:ne.clauses,matchOperator:ne.matchOperator,folder:B,scope:ne.scope,until:ne.until,ruleName:Oe.includes("name")?ne.name:void 0,escalatedScope:p?.scope,sample:ts},run:{state:tt.state,verb:e,scope:ne.scope,matched:tt.matched,applied:tt.applied,failedCount:tt.failed,failures:tt.failures,onRetry:xt,onDismiss:ct,onCancelRun:Us?qs:void 0}})}function Do(e){const t=fm()==="search",{searchConversion:s}=jr(),{accounts:n}=Ae(),{step:a,goToStep:o,goBack:i,closeWizard:l}=mm(t?"properties":"match");if(!a)return null;const u=t?s??eS:void 0;return r.jsx(sS,{...e,...u?{verb:"organize",accountId:cw(u,e.accountId,n),selection:tS,crossAccount:!1,escalated:void 0,searchConversion:u}:{},step:a,goToStep:o,goBack:i,closeWizard:l})}const nS=200,gl=()=>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))}),rS=({accountEmail:e})=>{const t=Ke();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(ds,{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"})]})},aS=(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 oS({header:e,rows:t,wizard:s,children:n}){const{selectedIds:a,selectedCount:o,exitSelection:i,orderedIds:l,allSelected:u,toggleAllLoaded:m}=Oo(),f=c.useMemo(()=>aS(t,a),[t,a]),{junkMailboxId:d}=_s(f.accountId),{labels:h}=Ya(f.accountId),v=c.useMemo(()=>Array.from(a),[a]),g=c.useMemo(()=>t.filter(w=>a.has(w.id)).map(w=>({id:w.id,sender:w.fromName,email:w.fromEmail,subject:w.subject,date:w.timeLabel})),[t,a]),p=!!d&&d!==f.mailboxId,y=c.useMemo(()=>l.length>0?{checked:u,indeterminate:o>0&&!u,onChange:m}:void 0,[l.length,u,o,m]),b=f.moveDisabledHint?{tone:"warning",text:f.moveDisabledHint}:void 0,S=w=>r.jsx(lo,{title:w.title,navSlot:w.navSlot,titleMeta:w.titleMeta,searchSlot:w.searchSlot,searchField:w.searchField,idleSlot:w.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:f.accountId&&f.mailboxId&&o>0&&h.length>0?r.jsx(bd,{accountId:f.accountId,mailboxId:f.mailboxId,messageIds:v}):void 0,selectAll:y,notice:b});return r.jsx(kd,{...e,selectionBar:S,paneOverlay:r.jsx(Do,{verb:s.verb,accountId:f.accountId,mailboxId:f.mailboxId,selection:g,crossAccount:f.moveDisabledHint!==void 0,onFinished:i}),children:n})}function iS({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:n,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i}){const{searchQuery:l,searchInput:u,resultFolderIndex:m}=Ae(),f=gs(),d=Xt(),h=qa(),v=Ke(),g=c.useMemo(()=>O0(e.filter(B=>!B.muted?.value)),[e]),[p,y]=c.useState("all"),[b,S]=c.useState("all"),[w,x]=c.useState(new Set),[k,M]=c.useState(!1),O=c.useCallback(B=>{x(ue=>{const oe=new Set(ue);return oe.has(B)?oe.delete(B):oe.add(B),oe})},[]),j=c.useCallback(()=>x(new Set),[]),R=u.trim().length>0,{data:P,isLoading:E,isError:L,refetch:D}=be({...ia(),staleTime:6e4}),C=pt({queries:g.map(B=>({...it({path:{accountId:B.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),T=c.useMemo(()=>{const B=new Map;for(let ue=0;ue<g.length;ue++){const oe=g[ue].accountId,nt=(C[ue]?.data?.items??[]).reduce((Te,J)=>Te+(J.unseenCount??0),0);B.set(oe,nt)}return B},[g,C]),A=c.useMemo(()=>g.filter((B,ue)=>{const oe=C[ue];return oe?.isError?!la(oe.error):!1}),[g,C]),{freeText:I,tokens:F}=Bs(l.trim().toLowerCase(),f),{data:N,isFetching:q}=be({...ia({query:{query:I,limit:nS}}),enabled:I.length>0,staleTime:3e4}),Q=c.useMemo(()=>{const B=cl(P?.items??[]).map(Gn);return(I?P0(B.filter(oe=>pd(oe,I)),cl(N?.items??[]).map(Gn)):B).filter(oe=>(p==="all"||oe.accountId===p)&&Ro(oe,F))},[P,N,p,I,F]),{bodyRows:ae,briefSpamOffer:U}=c.useMemo(()=>{if(!I)return{bodyRows:Q,briefSpamOffer:void 0};const B=Q.map(ne=>Sa(ne,m)),{spam:ue}=oo(B);if(ue.length===0)return{bodyRows:Q,briefSpamOffer:void 0};const oe=new Set(ue.map(ne=>ne.id));return{bodyRows:Q.filter(ne=>!oe.has(ne.id)),briefSpamOffer:xd(B)}},[Q,I,m]),z=c.useMemo(()=>D0(ae),[ae]),ee=c.useMemo(()=>g.length<=1?[]:[{id:"all",label:"All",active:p==="all"},...g.map(B=>({id:B.accountId,label:B.email.split("@")[0]??B.email,count:T.get(B.accountId),active:p===B.accountId}))],[g,T,p]),me=c.useMemo(()=>e.filter(B=>B.muted?.value).length,[e]),fe=c.useMemo(()=>Array.from(T.values()).reduce((B,ue)=>B+ue,0),[T]),se=c.useMemo(()=>Q.filter(B=>(b==="all"||B.category===b)&&vm(B,w)).map(B=>Sa(B,m)),[Q,b,w,m]),{hits:W,isLoading:pe}=hd(),ve=c.useMemo(()=>{const B=new Map;for(const oe of P?.items??[])B.set(oe.messageId,oe.threadId);const ue=se.map(oe=>B.get(oe.id)).filter(oe=>oe!=null);return gd(W,ue,m)},[W,se,P,m]),Ne=c.useMemo(()=>{const B=Wg(ee.map(ue=>({id:ue.id,label:ue.label,count:ue.count,active:ue.active})));return{categories:B.categories,filters:B.filters,sources:B.sources,sourcesNote:me>0?`+${me} muted`:void 0,selectedCategory:b,activeFilters:w,expanded:k,onExpandedChange:M,onSelectCategory:ue=>S(ue),onSelectSource:y,onToggleFilter:ue=>O(ue),onClear:()=>{S("all"),y("all"),j()}}},[ee,me,b,w,k,O,j]),we=z.length===0&&p==="all"&&I.length===0&&F.length===0,X=c.useMemo(()=>g.map(B=>B.accountId),[g]),H=c.useMemo(()=>g.some(B=>id(B.syncPhase)),[g]),ie=p0(X,we||H),ge=r.jsxs("div",{className:"h-full overflow-y-auto",children:[r.jsx(gl,{}),r.jsx(gl,{})]}),ze=!E&&!L&&!we,xe=ze?r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[U&&r.jsx(Fc,{count:U.count,onScopeToSpam:()=>v({to:"/mail/$mailboxId",params:{mailboxId:U.mailboxId},search:{q:l||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}),r.jsx("div",{className:"min-h-0 flex-1",children:r.jsx(Il,{sections:z,briefCategory:b,Row:Po,selectedThreadId:t,onSelectThread:s,onSelectBriefCategory:S,sources:ee,sourcesNote:me>0?`+${me} muted`:void 0,onSelectSource:y,activeFilters:w,onToggleFilter:O,onClearFilters:j,hideChrome:R})})]}):E?ge:L?r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[r.jsx(ds,{className:"size-8 text-danger"}),r.jsx("p",{children:"Couldn't load your messages"}),r.jsxs("button",{type:"button",onClick:()=>D(),className:"flex items-center gap-1 text-accent underline text-xs",children:[r.jsx(bc,{className:"size-3.5"}),"Try again"]})]}):ie.resolved?r.jsx(ng,{sync:ie.syncing?{synced:ie.synced,total:ie.total}:void 0}):ge;return r.jsx(Wl,{hasSheet:ze&&!R,children:r.jsx(Nd,{selectedMessageId:t,onOpen:(B,ue)=>s?.(B,ue),onDeleteMessages:i,onSelectionVerb:h.start,wizardOpen:h.isOpen,commandsRef:a,onTriageContextChange:o,children:r.jsx(oS,{wizard:h,header:{title:"Daily brief",unreadCount:fe,footer:d?r.jsx(jc,{}):void 0,searchFilter:Ne,searchResults:se,searchLoading:E||q,relatedResults:ve,relatedLoading:pe,onSelectSearchResult:n,searchResultsInBody:!0},rows:Q,children:r.jsxs("div",{className:"flex h-full flex-col",children:[A.map(B=>r.jsx(rS,{accountEmail:B.email,accountId:B.accountId},B.accountId)),r.jsx("div",{className:"min-h-0 flex-1",children:xe})]})})})})}const lS=10,Ad=e=>({q:e?.toLowerCase()??"",limit:lS}),cS=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(n=>n.normalizedEmail===s)};function uS(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Un(t,{month:"short",year:"numeric"})}function Od(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const dS="We can't verify the sender of this email, which could mean it's from an insecure source.",fS="We couldn't read this sender's address, so we can't confirm who really sent this message.";function mS(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?uS(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Od(e.fromEmail)}}function hS(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 pS(e,t){const s=t>0?t:void 0;if(Od(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:fS,similarCount:s};const n=e.authenticity;if(!n)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:dS};if(!n.dkimMismatch)return{verdict:"aligned",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,summary:n.dkimDomain?`We verified this message was really sent by ${n.fromDomain}.`:"Nothing looks unusual about this sender."};const a=n.fromDomain,o=n.dkimDomain,i=e.fromName&&e.fromName!==e.fromEmail?e.fromName:void 0,l=i?`The display name claims "${i}", but this message was actually sent from ${o??"another sender"} — not ${a}. Real senders use their own address.`:`This message claims to be from ${a}, but it was actually sent from ${o??"a different sender"}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:l,similarCount:s}}function Pd(e,t){const s=e?.fromEmail??null,n=e?.subject??"",{data:a,error:o}=be({...tr({query:Ad(s??void 0)}),enabled:!!s,staleTime:3e4}),i=cS(a?.items,s??void 0),l=[n,s].filter(Boolean).join(" "),{data:u,isLoading:m,error:f}=be({...ql({query:{query:l,limit:5}}),enabled:!!(e&&l.length>3),staleTime:6e4,retry:1});return{data:c.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(b=>b.messageId!==e.messageId).map(b=>({id:b.messageId,mailboxId:t!=null&&b.mailboxIds.includes(t)?t:b.mailboxIds[0]??"",fromName:b.fromName??"",subject:b.subject??"(No subject)",timeLabel:b.sentDate!=null?ht(b.sentDate*1e3):"",matched:b.matchedChunkType})),v=mS(e,i),g=pS(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},y=hS(i);return{sender:v,authenticity:g,category:p,flags:y,similar:h}},[e,i,u,t]),isSimilarLoading:m,similarError:f,similarErrorIsFatal:la(f),addressErrorIsFatal:la(o),addressId:i?.addressId,address:i}}function gS(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 Dd({addressId:e,senderEmail:t}){const s=Me(),{pushError:n}=st(),a=ym({query:Ad(t)}),{mutate:o,isPending:i}=Fe({...Ul(),onMutate:async u=>{const m=u.body.flags??{};await s.cancelQueries({queryKey:a});const f=s.getQueryData(a);return s.setQueryData(a,d=>d&&{...d,items:d.items.map(h=>h.addressId===u.path.addressId?{...h,flags:gS(h.flags,m)}:h)}),{previous:f}},onError:(u,m,f)=>{f?.previous!==void 0&&s.setQueryData(a,f.previous),n({title:"Couldn't update sender preference",detail:mt(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){Vl(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 xS=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Ld=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function bS(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function vS(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function yS(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Fd(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const wS=["personal","newsletter","marketing","automated","transactional","social"],SS=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:n}=e;return t?s&&t===s?n?"notSpam":null:s?"markSpam":null:null},kS=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:n}=e;return t&&!s?"error":n?"loading":"ready"};function CS(){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(Tt,{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 jS({isOpen:e,current:t,onSelect:s,onCancel:n}){return e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:n,children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),r.jsx("div",{className:"mt-4 flex flex-col gap-1",children:wS.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 NS({thread:e,onClose:t,mailboxId:s,accountId:n,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:m}=Pd(e,s),[f,d]=c.useState(!1),[h,v]=c.useState(!1),g=e.fromEmail??void 0,{updateFlags:p,isPending:y}=Dd({addressId:i,senderEmail:g}),{junkMailboxId:b}=_s(n),{inboxMailboxId:S}=wo(n),{moveMessages:w}=cs({mailboxId:s??"",threadId:e.threadId,accountId:n}),x=pn(),k=SS({mailboxId:s,junkMailboxId:b,inboxMailboxId:S}),M=c.useCallback(()=>{S&&w([e.messageId],S)},[S,w,e.messageId]),O=c.useCallback(()=>{b&&(Fd(x,{count:1,senderTrust:e.senderTrust,wasRescuable:Ld(e)}),w([e.messageId],b))},[b,w,e,x]),j=c.useCallback(()=>{},[]),R=c.useCallback(()=>{const N=o?.flags?.vip!==!0;p({vip:{value:N}})},[o?.flags?.vip,p]),P=c.useCallback(()=>{const N=o?.flags?.muted!==!0;p({muted:{value:N}})},[o?.flags?.muted,p]),E=c.useCallback(()=>{o?.flags?.blocked===!0?p({blocked:{value:!1}}):d(!0)},[o?.flags?.blocked,p]),L=c.useCallback(()=>{d(!1),p({blocked:{value:!0}})},[p]),D=c.useCallback(()=>{const N=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:N}})},[o?.flags?.unsubscribed,p]),C=c.useCallback(N=>{v(!1),p({category:{value:N}})},[p]),T=i!==void 0,A={onToggleVip:T?R:void 0,onToggleMute:T?P:void 0,onToggleBlock:T?E:void 0,onToggleUnsubscribe:T?D:void 0,onReclassify:T?()=>v(!0):void 0,onNotSpam:k==="notSpam"?M:void 0,onMarkSpam:k==="markSpam"?O:void 0},I=({mailboxId:N,messageId:q,className:Q,ariaLabel:ae,children:U})=>r.jsx(Kt,{to:"/mail/$mailboxId",params:{mailboxId:N},search:z=>({...z,selectedMessageId:q}),className:Q,"aria-label":ae,children:U});if(!o)return r.jsx(CS,{});const F=kS({similarError:u,similarErrorIsFatal:m,isSimilarLoading:l});return r.jsxs(r.Fragment,{children:[r.jsx(Sc,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:j,actions:A,similarState:F,similarLinkComponent:I,className:"border-l-0 h-full w-full"}),r.jsx(Xa,{isOpen:f,title:"Block this sender?",description:`Messages from ${g??"this sender"} will never load images and will be flagged. You can undo this in Settings → Senders.`,confirmLabel:"Block sender",destructive:!0,isBusy:y,onConfirm:L,onCancel:()=>d(!1)}),r.jsx(jS,{isOpen:h,current:o.category.value,onSelect:C,onCancel:()=>v(!1)})]})}const Ks=({onClose:e,thread:t,mailboxId:s,accountId:n,hideCloseButton:a})=>t?r.jsx(NS,{thread:t,onClose:e,mailboxId:s,accountId:n,hideCloseButton:a}):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(Tt,{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(Tt,{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."})]})]}),ta="Open a message first",Lo=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:n,onReply:a,onReplyAll:o,onForward:i,onDelete:l,canDelete:u,onToggleStar:m,isStarred:f,moveContext:d})=>{const[h,v]=c.useState(null),g=u??e,p=y=>()=>v(y);return r.jsx(bp,{hasThread:e,isStarred:f,onUnavailable:y=>v(ta),unavailableHint:h,replyTitle:`Reply ${Qs("reply")}`,replyAllTitle:`Reply all ${Qs("replyAll")}`,forwardTitle:`Forward ${Qs("forward")}`,deleteTitle:`Move to Trash ${Qs("delete")}`,flagTitle:`Star ${Qs("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:g?l:p(ta),onToggleStar:m,onMove:p(ta),moveSlot:d?r.jsx(Eo,{accountId:d.accountId,currentMailboxId:d.currentMailboxId,onMove:d.onMove,label:"Move to mailbox"}):void 0,children:r.jsx(xp,{open:t,enabled:s,onToggle:n})})},$d=()=>{const e=Me();return c.useCallback(t=>{const s=hs({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])},dn=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=t??e?.mailboxId,o=s??e?.accountId,{accountId:i}=bo(o?void 0:a),l=o??i,u=$d(),{deleteMessages:m}=us({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:n}),{moveMessages:f}=cs({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:n}),{toggleStar:d}=vo({threadId:e?.threadId??"",mailboxId:a??""}),h=c.useCallback(()=>{e&&m(u(e))},[e,u,m]),v=c.useCallback(S=>{e&&f(u(e),S)},[e,u,f]),g=c.useCallback(()=>{e&&d(e.messageId,e.hasStars)},[e,d]),[p,y]=c.useState(null),b=c.useCallback(()=>y(null),[]);return{mailboxId:a,accountId:l,isStarred:e?.hasStars,deleteThread:h,moveThread:v,toggleStar:g,composeRequest:p,requestCompose:y,clearComposeRequest:b}},Xs={action:null,nextPrefix:null,preventDefault:!1},ES={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},IS={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 TS(e,t){const s=e.key.toLowerCase(),n=e.metaKey||e.ctrlKey;if(e.inEditable)return{...Xs,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...Xs,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{...Xs,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=ES[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=IS[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?Xs:{action:a.action,nextPrefix:null,preventDefault:!0}}return Xs}function RS(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const MS="data-message-row",AS='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function OS(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(AS);return t?!t.hasAttribute(MS):!1}function PS({handlers:e,enabled:t=!0,sequenceTimeoutMs:s=1e3}){const n=c.useRef(e);n.current=e;const a=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{if(!t)return;const i=()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},l=u=>{const m=TS({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:RS(u.target),onControl:OS(u.target)},a.current);if(i(),a.current=m.nextPrefix,m.nextPrefix!==null&&(o.current=setTimeout(()=>{a.current=null,o.current=null},s)),m.action===null)return;const f=n.current[m.action];f&&(m.preventDefault&&u.preventDefault(),f())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l),i(),a.current=null}},[t,s])}const xl=(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]},Fo=()=>{const[e,t]=c.useState(void 0),[s,n]=c.useState([]),[a,o]=c.useState([]),i=c.useRef(null),[l,u]=c.useState(!1),[m,f]=c.useState(!1),d=c.useCallback(h=>{t(h.focusedMessageId),n(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),f(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:d,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:l,blocksKeyboard:m}},$o=({context:e,orderedIds:t,selectedMessageId:s,enabled:n=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:l,blocksKeyboard:u}=e,m=c.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return PS({enabled:n&&!u,handlers:{...l?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:m,...o}}),{goBack:m,nextMessageId:xl(t,s,"next")??void 0,previousMessageId:xl(t,s,"previous")??void 0}};function DS(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function _d(e,t){if(e)return DS(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const zd=c.createContext(null);function Nr(){const e=c.useContext(zd);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function LS({selectedMessageId:e,children:t}){const s=Ke(),{searchInput:n}=Ae(),{selectedThreadId:a,selectedMailboxId:o}=As({strict:!1}),{data:i}=be({...ia(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(R=>R.messageId===e)},[i,e]),u=c.useMemo(()=>_d(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),m=c.useCallback((R,P)=>{s({to:"/mail",search:E=>({...E,selectedMessageId:R,selectedThreadId:void 0,selectedMailboxId:void 0}),replace:P?.replace})},[s]),f=c.useCallback(R=>{s({to:"/mail",search:P=>({...P,q:n||void 0,selectedMessageId:R.id,selectedThreadId:R.threadId,selectedMailboxId:R.mailboxId})})},[s,n]),d=c.useCallback(R=>{e&&R.includes(e)&&s({to:"/mail",search:P=>({...P,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=dn({thread:l,onAfterOptimisticRemove:d}),v=c.useCallback(()=>{s({to:"/mail",search:R=>({...R,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),g=Fo(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:y}=us({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:d}),{toggleReadFor:b}=yr({mailboxId:l?.mailboxId??"",messages:p}),S=g.focusedMessageId,x=c.useMemo(()=>i?.items.find(R=>R.messageId===S),[i,S])??l,k=dn({thread:x}),{nextMessageId:M,previousMessageId:O}=$o({context:g,orderedIds:g.orderedIds,selectedMessageId:e,onClose:v,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{g.listCommandsRef.current?.requestVerb("delete")||k.deleteThread()},toggleStar:k.toggleStar,toggleRead:()=>{g.listCommandsRef.current?.requestVerb("markRead")||x&&b([x.messageId],!x.isRead)},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),j={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:m,onSelectSearchResult:f,onCloseThread:v,actions:h,triage:g,onDeleteMessages:y,nextMessageId:M,previousMessageId:O};return r.jsx(zd.Provider,{value:j,children:t})}function Bd(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:n,onDeleteMessages:a}=Nr(),{accounts:o}=Ae();return r.jsx(iS,{accounts:o,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:n.listCommandsRef,onTriageContextChange:n.onTriageContextChange,onDeleteMessages:a})}function FS(){const{conversation:e,actions:t}=Nr(),{intelligenceOpen:s,onToggleIntelligence:n}=Ae(),a=fs()?.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(Lo,{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 $S(){const{selectedThread:e}=Nr(),{onToggleIntelligence:t}=Ae();return r.jsx(Ks,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function _S(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:n,nextMessageId:a,previousMessageId:o}=Nr(),{intelligenceOpen:i,onToggleIntelligence:l}=Ae();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:l,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:i}),r.jsx(po,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:l,thread:e,hideCloseButton:!0})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Bd,{})})}const Js=Object.assign(LS,{List:Bd,Reading:FS,Intelligence:$S,Phone:_S}),zS=()=>Ka({query:{starred:!0,order:"desc"}});function Kd(){const{data:e,isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=au({queryKey:zS(),queryFn:async({pageParam:m})=>{const{data:f}=await wm({query:{starred:!0,order:"desc",continuationToken:m},throwOnError:!0});return f},initialPageParam:void 0,getNextPageParam:m=>m.continuationToken,staleTime:6e4});return{threads:c.useMemo(()=>(e?.pages??[]).flatMap(m=>m.items??[]),[e]),isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}}const BS=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function Ud({title:e,unreadCount:t,preset:s,selectedCategory:n,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:l,onClearFilters:u,children:m,footer:f,searchResults:d,searchLoading:h,relatedResults:v,relatedLoading:g,onSelectSearchResult:p,searchResultsLabel:y,relatedResultsLabel:b,searchResultsInBody:S}){const{searchInput:w}=Ae(),x=w.trim().length>0,k={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:n,activeFilters:a,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return r.jsx(Wl,{hasSheet:!x,children:r.jsx(kd,{title:e,unreadCount:t,footer:f,searchFilter:k,searchResults:d,searchLoading:h,relatedResults:v,relatedLoading:g,onSelectSearchResult:p,searchResultsLabel:y,relatedResultsLabel:b,searchResultsInBody:S,children:r.jsx(Al,{...k,hideChrome:x,children:m})})})}const KS={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function US({rows:e,verb:t}){const{selectedIds:s,exitSelection:n}=Oo(),a=c.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(Do,{verb:t,selection:a,crossAccount:!0,onFinished:n})}function qS({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:n,onDeleteMessages:a}){const{searchQuery:o,resultFolderIndex:i}=Ae(),l=gs(),u=Xt(),m=qa(),[f,d]=c.useState("all"),[h,v]=c.useState(new Set),g=c.useCallback(F=>{v(N=>{const q=new Set(N);return q.has(F)?q.delete(F):q.add(F),q})},[]),p=c.useCallback(()=>{d("all"),v(new Set)},[]),{threads:y,isLoading:b,isError:S,error:w,refetch:x,fetchNextPage:k,hasNextPage:M,isFetchingNextPage:O}=Kd(),{freeText:j,tokens:R}=Bs(o.trim().toLowerCase(),l),P=c.useMemo(()=>{const F=Array.from(h).map(N=>KS[N]).filter(N=>N!=null);return BS(y).map(Gn).filter(N=>(f==="all"||N.category===f)&&F.every(q=>q(N))&&(!j||pd(N,j))&&Ro(N,R))},[y,f,h,j,R]),E=c.useMemo(()=>Vg(),[]),L=c.useMemo(()=>P.map(F=>Sa(F,i)),[P,i]),D=c.useMemo(()=>P.filter(F=>!F.isRead).length,[P]),C=b?"loading":S?"error":P.length===0?"empty":"ready",T=c.useCallback(()=>{const F=Ql(Gl());window.open(F,"_blank","noopener,noreferrer")},[]),A=jr(),I=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(Po,{thread:F,active:F.id===e,onClick:()=>t?.(F.id)},F.id))}),M?r.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>k(),disabled:O,children:O?"Loading…":"Load more"}):null]})});return r.jsx(Ud,{title:"Starred",unreadCount:D,preset:E,selectedCategory:f,activeFilters:h,onSelectCategory:d,onToggleFilter:g,onClearFilters:p,searchResults:L,searchLoading:b,onSelectSearchResult:F=>t?.(F.id),searchResultsInBody:!0,children:r.jsxs(Nd,{selectedMessageId:e,onOpen:(F,N)=>t?.(F,N),onDeleteMessages:a,onSelectionVerb:m.start,wizardOpen:m.isOpen,commandsRef:s,onTriageContextChange:n,children:[r.jsx(Ac,{listTitle:"Starred",sections:[{id:"flagged",threads:P}],flatList:!0,hideHeader:!0,listState:A.searchResults?"ready":C,searchQuery:j?o:void 0,errorMessage:S?Xl(w):void 0,onRetry:()=>x(),onReportError:T,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:u,selectionBar:r.jsx(vw,{title:"Starred"}),listBody:A.searchResults??(C==="ready"?I:void 0)}),r.jsx(US,{rows:P,verb:m.verb})]})})}const qd=c.createContext(null);function Er(){const e=c.useContext(qd);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function HS({selectedMessageId:e,children:t}){const s=Ke(),{threads:n}=Kd(),a=c.useMemo(()=>{if(e)return n.find(w=>w.messageId===e)},[n,e]),o=c.useCallback((w,x)=>{s({to:"/mail/flagged",search:k=>({...k,selectedMessageId:w}),replace:x?.replace})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:w=>({...w,selectedMessageId:void 0})})},[s]),l=c.useCallback(w=>{e&&w.includes(e)&&i()},[e,i]),u=dn({thread:a,onAfterOptimisticRemove:l}),m=Fo(),{deleteMessages:f}=us({mailboxId:a?.mailboxId??"",messages:n,onAfterOptimisticRemove:l}),{toggleReadFor:d}=yr({mailboxId:a?.mailboxId??"",messages:n}),h=m.focusedMessageId,g=c.useMemo(()=>n.find(w=>w.messageId===h),[n,h])??a,p=dn({thread:g}),{nextMessageId:y,previousMessageId:b}=$o({context:m,orderedIds:m.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{m.listCommandsRef.current?.requestVerb("delete")||p.deleteThread()},toggleStar:p.toggleStar,toggleRead:()=>{m.listCommandsRef.current?.requestVerb("markRead")||g&&d([g.messageId],!g.isRead)},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),S={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:m,onDeleteMessages:f,nextMessageId:y,previousMessageId:b};return r.jsx(qd.Provider,{value:S,children:t})}function Hd(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:n}=Er();return r.jsx(qS,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:n})}function WS(){const{selectedThread:e,actions:t}=Er(),{intelligenceOpen:s,onToggleIntelligence:n}=Ae(),a=fs()?.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(Lo,{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 VS(){const{selectedThread:e}=Er(),{onToggleIntelligence:t}=Ae();return r.jsx(Ks,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function QS(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:n,previousMessageId:a}=Er(),{intelligenceOpen:o,onToggleIntelligence:i}=Ae();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:i,onSwipeNext:n?()=>s(n):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:o}),r.jsx(po,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:i,thread:e,hideCloseButton:!0})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Hd,{})})}const Zs=Object.assign(HS,{List:Hd,Reading:WS,Intelligence:VS,Phone:QS}),GS={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},YS=()=>{const e=c.useRef(!1);return c.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector("[data-slate-editor]")?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},XS=()=>{const{state:e,closeCompose:t}=Yt(),s=YS(),[n,a]=c.useState(!1),{isError:o,error:i,refetch:l}=be({...Mt(),staleTime:1/0}),u=c.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),m=c.useCallback(()=>{a(!1),t()},[t]),f=c.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const d=GS[e.mode]??"New Message";return r.jsxs(ft.Root,{open:e.isOpen,onOpenChange:u,children:[r.jsxs(ft.Portal,{children:[r.jsx(ft.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(ft.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[r.jsx(ft.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),r.jsx(ft.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:d}),o?r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(Jt,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):r.jsx("div",{className:"flex-1 overflow-hidden",children:r.jsx(go,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),n&&r.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50",children:r.jsxs("div",{className:"mx-4 w-full max-w-sm rounded-xl bg-canvas p-6 shadow-xl",children:[r.jsx("h3",{className:"text-lg font-semibold",children:"Discard draft?"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Your message has unsaved content. Are you sure you want to discard it?"}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx("button",{type:"button",onClick:f,className:"rounded-md px-4 py-2 text-sm font-medium hover:bg-surface-raised transition-colors",children:"Keep editing"}),r.jsx("button",{type:"button",onClick:m,className:"rounded-md bg-danger px-4 py-2 text-sm font-medium text-canvas hover:bg-danger/90 transition-colors",children:"Discard"})]})]})})]})},JS={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Wd=()=>{const{state:e,closeCompose:t}=Yt(),s=Xt(),{isError:n,error:a,refetch:o}=be({...Mt(),staleTime:1/0});if(!s)return r.jsx(XS,{});if(!e.isOpen)return null;const i=JS[e.mode]??"New Message",l=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(Ct,{className:"size-5"})})]});return n?r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[l,r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(Jt,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):r.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[l,r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:r.jsx(go,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function ZS(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:ht(e.updatedAt),isRead:!0}}function ek(e){return{id:e.messageId,accountId:e.accountId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:ht(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function tk({outboxMessages:e,accountId:t,imapThreads:s}){const n=e.filter(i=>i.status==="draft"&&i.accountId===t).map(ZS),a=s.map(ek),o=[];return n.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:n}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function _o(){const e=fs();return!e||e.showNavPane?null:r.jsx(le,{variant:"ghost",size:"sm",icon:r.jsx(or,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const sk=({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})]}),nk=({row:e,isSelected:t,onOpen:s,onDelete:n,isDeleting:a})=>r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:V("group",Fs({active:t})),children:[r.jsx(Ml,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),r.jsx(ln,{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(Rt,{className:"size-3.5"})})})]}),rk=({row:e,isSelected:t,onOpen:s})=>{const n=!e.isRead;return r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:V("group",Fs({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(kt,{name:e.fromName,email:e.fromEmail,size:"sm"}),r.jsx(ln,{thread:e})]})};function ak({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:n,title:a,unreadCount:o}){const{openCompose:i,state:l}=Yt(),u=Ke(),m=Me(),{data:f}=be(er()),d=c.useMemo(()=>tk({outboxMessages:f?.items??[],accountId:t,imapThreads:n}),[f?.items,t,n]),h=Fe({...sr(),onSuccess:()=>{m.invalidateQueries({queryKey:Ha()})}}),v=b=>{h.mutate({path:{outboxMessageId:b}})},g=b=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:b})},p=b=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:b}})},y=d.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(_o,{}),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:y?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[r.jsx(Ra,{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."})]}):d.map(b=>r.jsxs("div",{children:[b.label&&r.jsx(sk,{label:b.label,count:b.threads.length}),r.jsx("div",{className:"divide-y divide-line",children:b.threads.map(S=>b.id==="remit-drafts"?r.jsx(nk,{row:S,isSelected:l.isOpen&&S.id===l.outboxMessageId,onOpen:g,onDelete:v,isDeleting:h.isPending},S.id):r.jsx(rk,{row:S,isSelected:S.id===s,onOpen:p},S.id))})]},b.id))})]})}function ok(e,t,s){const n=new Array(e);return new Proxy(n,{get(a,o,i){if(typeof o=="string"){const l=o.charCodeAt(0);if(l>=48&&l<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let m=a[u];if(!m){const f=t[u*2];m=a[u]={index:u,key:s(u),start:f,size:t[u*2+1],end:f+t[u*2+1],lane:0}}return m}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function Ns(e,t,s){let n=s.initialDeps??[],a,o=!0;function i(){const l=e();return(l.length!==n.length||l.some((m,f)=>n[f]!==m))&&(n=l,a=t(...l),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=l=>{n=l},i}function bl(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const ik=(e,t)=>Math.abs(e-t)<1.01,lk=(e,t,s)=>{let n;return function(...a){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,a),s)}};let en;const sa=()=>{if(en!==void 0)return en;if(typeof navigator>"u")return en=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return en=!0;const e=navigator.maxTouchPoints;return en=navigator.platform==="MacIntel"&&e!==void 0&&e>0},vl=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},ck=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},dk=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const a=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(a(vl(s)),!n.ResizeObserver)return()=>{};const o=new n.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u?.borderBoxSize){const m=u.borderBoxSize[0];if(m){a({width:m.inlineSize,height:m.blockSize});return}}a(vl(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},Yn={passive:!0},fk=typeof window>"u"?!0:"onscrollend"in window,mk=(e,t,s)=>{const n=e.scrollElement;if(!n)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&fk;let i=0;const l=o?null:lk(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=d=>()=>{i=s(n),l?.(),t(i,d)},m=u(!0),f=u(!1);return n.addEventListener("scroll",m,Yn),o&&n.addEventListener("scrollend",f,Yn),()=>{n.removeEventListener("scroll",m),o&&n.removeEventListener("scrollend",f)}},hk=(e,t)=>mk(e,t,s=>{const{horizontal:n,isRtl:a}=e.options;return n?s.scrollLeft*(a&&-1||1):s.scrollTop}),pk=(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"]},gk=(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})},xk=gk;class bk{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 l=o.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[m,f]of this.elementsCache)if(f===l){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=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:ck,rangeExtractor:uk,onChange:()=>{},measureElement:pk,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 l=null,u=null,m=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,v=o.count,g=this.getMeasurements(),p=h>0?((n=g[0])==null?void 0:n.key)??i.getItemKey(0):null,y=h>0?((a=g[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(v!==h||h>0&&v>0&&(o.getItemKey(0)!==p||o.getItemKey(v-1)!==y)){m=!0;const w=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??g[0]:null;w&&(l=[w.key,this.getScrollOffset()-w.start]);const x=o.followOnAppend===!0?"auto":o.followOnAppend||null;x&&v>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(v-1)!==y)&&(u=x)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let f=!1,d=0;if(l&&this.scrollOffset!==null){const[h,v]=l,g=this.getMeasurements(),{count:p,getItemKey:y}=this.options;let b=0;for(;b<p&&y(b)!==h;)b++;if(b<p){const S=g[b];if(S){const w=S.start+v;w!==this.scrollOffset&&(d=w-this.scrollOffset,this.scrollOffset=w,f=!0)}}}(f||u)&&(this.pendingScrollAnchor=[f?l[0]:null,f?l[1]:0,u,d])},this.notify=s=>{var n,a;(a=(n=this.options).onChange)==null||a.call(n,this,s)},this.maybeNotify=Ns(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}if(this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===o?this.scrollDirection:l<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!sa()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,Yn),o.addEventListener("touchend",l,Yn),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,l,u]=a;o!==null&&!l&&(sa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),n=this.getMaxScrollOffset();if(s<0||s>n)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=Ns(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,n,a,o,i,l,u,m)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:m}),{key:!1}),this.getMeasurements=Ns(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:m},f)=>{const d=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const b of this.laneAssignments.keys())b>=s&&this.laneAssignments.delete(b);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(b=>{this.itemSizeCache.set(b.key,b.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),l===1){const b=s*2;let S=this._flatMeasurements;if(!S||S.length<b){const k=new Float64Array(b);S&&h>0&&k.set(S.subarray(0,h*2)),S=k,this._flatMeasurements=S}let w;if(h===0)w=n+a;else{const k=h-1;w=S[k*2]+S[k*2+1]+m}for(let k=h;k<s;k++){const M=o(k),O=d.get(M),j=typeof O=="number"?O:this.options.estimateSize(k);S[k*2]=w,S[k*2+1]=j,w+=j+m}const x=ok(s,S,o);return this.measurementsCache=x,x}const v=this.measurementsCache.slice(0,h),g=new Array(l).fill(void 0),p=new Float64Array(l);let y=0;for(let b=0;b<h;b++){const S=v[b];S&&(g[S.lane]===void 0&&y++,g[S.lane]=b,p[S.lane]=S.end)}for(let b=h;b<s;b++){const S=o(b),w=this.laneAssignments.get(b);let x,k;const M=u==="estimate"||d.has(S);if(w!==void 0&&this.options.lanes>1){x=w;const P=g[x],E=P!==void 0?v[P]:void 0;k=E?E.end+m:n+a}else if(y===l){let P=0,E=p[0],L=g[0];for(let D=1;D<l;D++){const C=p[D];(C<E||C===E&&g[D]<L)&&(P=D,E=C,L=g[D])}x=P,k=E+m,M&&this.laneAssignments.set(b,x)}else x=b%this.options.lanes,k=n+a,M&&this.laneAssignments.set(b,x);const O=d.get(S),j=typeof O=="number"?O:this.options.estimateSize(b),R=k+j;v[b]={index:b,start:k,size:j,end:R,key:S,lane:x},g[x]===void 0&&y++,g[x]=b,p[x]=R}return this.measurementsCache=v,v},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ns(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,a,o)=>s.length===0||n===0?(this.range=null,null):(this.range=yk(s,n,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ns(()=>{let s=null,n=null;const a=this.calculateRange();return a&&(s=a.startIndex,n=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:n,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,a=s.getAttribute(n);return a?parseInt(a,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),l=Math.min(this.options.count-1,a+o);return s>=i&&s<=l}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const 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,l,u;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)u=this.options.getItemKey(s),l=m[s*2],i=m[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,l=h.start,i=h.size}const f=this.itemSizeCache.get(u)??i,d=n-f;if(d!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,v=h?this.getTotalSize():0,g=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:l,size:i,end:l+i,lane:0},d,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,n),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-v):g&&this.applyScrollAdjustment(d),this.notify(!1)}},this.getVirtualItems=Ns(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const l=s[o],u=n[l];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=Vd(0,n.length-1,o?l=>a[l*2]:l=>bl(n[l]).start,s);return bl(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 l=this.getMaxScrollOffset();return Math.max(Math.min(l,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 l=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,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,l]=o,u=this.now();this.scrollState={index:s,align:l,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior: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(l=>l===null);){const l=n[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}a=Math.max(...o.filter(l=>l!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const 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&&(sa()&&(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&&ik(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&u>l;this.scrollState.lastTargetOffset=a,m||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Vd=(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 vk(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 yk(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=vk(a,o,s);let f=m;const d=s+t;for(;f<o&&a[f*2]+a[f*2+1]<d;)f++;return{startIndex:m,endIndex:f}}let l=Vd(0,o,m=>e[m].start,s),u=l;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(d=>d<s+t);){const d=e[u];m[d.lane]=d.end,u++}const f=Array(n).fill(s+t);for(;l>=0&&f.some(d=>d>=s);){const d=e[l];f[d.lane]=d.start,l--}l=Math.max(0,l-l%n),u=Math.min(o,u+(n-1-u%n))}return{startIndex:l,endIndex:u}}const na=typeof document<"u"?c.useLayoutEffect:c.useEffect;function wk({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...n}){const a=c.useReducer(m=>m+1,0)[1],o=c.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=m=>{const f=o.current;if(!f.enabled||!f.container)return;const d=m.getTotalSize();if(d!==f.lastSize){f.lastSize=d;const b=m.options.horizontal?"width":"height";f.container.style[b]=`${d}px`}const h=!!m.options.horizontal,v=f.mode==="transform",g=h?"left":"top",p=m.options.scrollMargin,y=m.getVirtualItems();for(const b of y){const S=b.start-p,w=m.elementsCache.get(b.key);w&&f.lastPositions.get(w)!==S&&(f.lastPositions.set(w,S),v?w.style.transform=h?`translate3d(${S}px, 0, 0)`:`translate3d(0, ${S}px, 0)`:w.style[g]=`${S}px`)}},l={...n,onChange:(m,f)=>{var d;const h=o.current;let v=!0;if(h.enabled){i(m);const g=m.range,p=h.prevRange;v=!p||p.isScrolling!==m.isScrolling||p.startIndex!==g?.startIndex||p.endIndex!==g?.endIndex,v&&(h.prevRange=g?{startIndex:g.startIndex,endIndex:g.endIndex,isScrolling:m.isScrolling}:null)}v&&(e&&f?Pa.flushSync(a):a()),(d=n.onChange)==null||d.call(n,m,f)}},[u]=c.useState(()=>{const m=new bk(l);return Object.assign(m,{containerRef:f=>{const d=o.current;if(d.container=f,d.lastSize=null,f&&d.enabled){const h=m.getTotalSize();d.lastSize=h;const v=m.options.horizontal?"width":"height";f.style[v]=`${h}px`}}})});return u.setOptions(l),na(()=>u._didMount(),[]),na(()=>u._willUpdate()),na(()=>{i(u)}),u}function Sk(e){return wk({observeElementRect:dk,observeElementOffset:hk,scrollToFn:xk,...e})}const zo=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",kk=e=>`Select all ${zo(e)}`,Ck=(e,t)=>`All ${Vt(t)} ${zo(e)} selected`,jk=(e,t,s)=>e==="BACK"&&t&&s===void 0,Nk=(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:ht(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:wr(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),Ek=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,messageCount:m,isMultiSelectMode:f,onLongPress:d,isDesktop:h,density:v})=>r.jsx(Po,{thread:Nk(e,m),linkMailboxId:t,inListbox:!0,active:s,focused:n,isTabStop:a,density:v,isDesktop:h,onFocusRow:o,selection:{isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:f,onLongPress:d}}),Ik=c.memo(Ek),Tk=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:ht(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:wr(e.category),suspicious:t}},Rk=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:m,onLongPress:f,isDesktop:d,onDelete:h,onToggleRead:v,density:g})=>{const[p,y]=c.useState("none"),b=Ke(),S=c.useCallback(M=>{navigator.vibrate?.(10),M==="trailing"?h(e.messageId):v(e.messageId,e.isRead),y("none")},[h,v,e.messageId,e.isRead]),w=c.useCallback(()=>{f(e.messageId)},[f,e.messageId]),x=c.useCallback(()=>{l(e.messageId)},[l,e.messageId]),k=c.useCallback(()=>{b({to:"/mail/$mailboxId",params:{mailboxId:t},search:M=>({...M,selectedMessageId:e.messageId})})},[b,t,e.messageId]);return d||m?r.jsx(Ik,{thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:m,onLongPress:f,isDesktop:d,density:g}):r.jsx(Mc,{thread:Tk(e),selectionMode:!1,checked:!1,active:s,peek:p,onPeek:y,onToggleCheck:x,onLongPress:w,onOpen:k,onAct:S})},Mk=72,Ak=32,Ok=5,Qd="remit:list-density",Pk=()=>{try{const e=localStorage.getItem(Qd);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},Dk=({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(Zn,{className:"size-4 text-fg-muted"}),r.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),Lk=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:n,isError:a=!1,error:o,onRetry:i,searchQuery:l,searchPredicate:u,onDeleteMessages:m,isDeleting:f=!1,isMoving:d=!1,onLoadMore:h,hasMore:v=!1,isLoadingMore:g=!1,accountId:p,listTitle:y,listMeta:b,listFilter:S,listScopeLabel:w,onTriageContextChange:x,commandsRef:k,hideHeader:M=!1})=>{const O=c.useRef(null),j=Ke(),R=Xt(),P=qa(),{verb:E,start:L,startFromSearch:D}=P,C=Sm(),T=!!l?.trim(),A=jr(),{labels:I}=Ya(p),{pushError:F}=st(),[N,q]=c.useState(s),[Q,ae]=c.useState(),U=c.useCallback($=>{ae(re=>re===$?re:void 0),q($)},[]),[z,ee]=c.useState(Pk),me=c.useCallback(()=>{ee($=>{const re=$==="comfortable"?"compact":"comfortable";try{localStorage.setItem(Qd,re)}catch{}return re})},[]),{toggleReadFor:fe}=yr({mailboxId:e}),{junkMailboxId:se}=_s(p),{selectedIds:W,selectedCount:pe,hasSelection:ve,isSelected:Ne,toggle:we,select:X,clearSelection:H,selectRange:ie,setAnchor:ge,selectAll:ze,toggleAll:xe,intersectWith:B}=Cc(),ue=to(pe,R),[oe,ne]=c.useState(null),nt=T&&!!u,Te=`${e}|${JSON.stringify(u??{})}`,J=Rd({mailboxId:e,accountId:p,enabled:nt,predicateKey:Te,searchQuery:u??{}}),Se=c.useCallback(($,re,yt)=>{if(yt.error===void 0){if(yt.cancelled){F({severity:"warning",title:Pw(yt.done),detail:Dw($,yt.done,re)});return}F({severity:"info",title:ml($,yt.done)})}},[F]),Ve=J.phase.kind,Oe=J.clear,he=c.useCallback(()=>{Ve==="escalated"&&Oe(),H()},[H,Oe,Ve]),[lt,Xe]=c.useState(null),Pe=c.useRef(null),Ue=c.useRef(!1),qe=c.useRef(null),Ze=!n&&t.length>0,rt=oe!==null,Ce=Sk({count:t.length,getScrollElement:()=>O.current,estimateSize:()=>z==="compact"?Ak:Mk,overscan:Ok}),G=s?t.findIndex($=>$.messageId===s):-1,te=N?t.findIndex($=>$.messageId===N):-1,ce=c.useCallback($=>{if($<0||$>=t.length)return;const re=t[$];if(ue){we(re.messageId);return}Pe.current=re.messageId,Ue.current=!1,ae(re.messageId),q(re.messageId)},[t,ue,we]),de=c.useCallback(()=>{if(t.length===0)return;const $=te<0?0:Math.min(te+1,t.length-1);ce($)},[t.length,te,ce]),ke=c.useCallback(()=>{if(t.length===0)return;const $=te<=0?0:te-1;ce($)},[t.length,te,ce]),Ee=c.useCallback(()=>ce(0),[ce]),De=c.useCallback(()=>ce(t.length-1),[ce,t.length]),He=c.useCallback(()=>{N&&we(N)},[N,we]),ye=c.useMemo(()=>t.map($=>$.messageId),[t]),Qe=c.useMemo(()=>{const $=[];for(const re of t)W.has(re.messageId)&&$.push({id:re.messageId,sender:re.fromName??re.fromEmail??"Unknown",email:re.fromEmail??"",subject:re.subject??"(No subject)",date:ht(re.sentDate)});return $},[t,W]),Ge=c.useCallback(($,re)=>re.shiftKey?(ie(ye,$,N),!0):re.metaKey||re.ctrlKey?(we($),!0):(he(),ge($),!1),[ye,N,ie,we,he,ge]),Le=c.useCallback($=>{!m||$.length===0||(qe.current=N??null,ne($))},[m,N]),et=c.useCallback($=>{const re=kc(ye,N,$);re!==void 0&&(ie(ye,re),Pe.current=re,Ue.current=!1,ae(void 0),q(re))},[ye,N,ie]),Ye=c.useCallback(()=>et(-1),[et]),Dt=c.useCallback(()=>et(1),[et]),es=c.useCallback(()=>{ye.length>0&&ze(ye)},[ye,ze]),Lt=c.useCallback($=>oe!==null?!0:ve?(L($),!0):$!=="delete"||!m||!N?!1:(Le([N]),!0),[oe,m,ve,L,N,Le]),xs=c.useCallback(()=>{N&&j({to:"/mail/$mailboxId",params:{mailboxId:e},search:$=>({...$,selectedMessageId:N})})},[N,j,e]),tt=c.useCallback($=>{j({to:"/mail/$mailboxId",params:{mailboxId:e},search:re=>({...re,selectedMessageId:$}),replace:!0})},[j,e]);Cd({keyboardFocusedMessageId:Q,openMessageId:s,enabled:R&&pe===0,open:tt});const xt=J.phase.kind==="escalated"?{scope:zo(u??{}),total:J.phase.total,searchQuery:u??{},run:$=>J.runAction($),stop:J.stop}:void 0,Ft=c.useCallback(()=>{if(!oe)return;const $=oe;if($.length===0){ne(null);return}const re=new Set($),yt=t.findIndex(Je=>re.has(Je.messageId));let Nt;for(let Je=yt+1;Je<t.length;Je++)if(!re.has(t[Je].messageId)){Nt=t[Je].messageId;break}if(Nt===void 0){for(let Je=yt-1;Je>=0;Je--)if(!re.has(t[Je].messageId)){Nt=t[Je].messageId;break}}m?.($),he(),qe.current=null,ne(null),Nt!==void 0&&(Pe.current=Nt,Ue.current=!1,U(Nt),R&&j({to:"/mail/$mailboxId",params:{mailboxId:e},search:Je=>({...Je,selectedMessageId:Nt}),replace:!0})),R||Xe(ml("delete",$.length))},[oe,t,m,he,j,e,R,U]),ct=c.useCallback(()=>{const $=qe.current;qe.current=null,ne(null),$!==null&&(Pe.current=$,Ue.current=!1,U($))},[U]),$t=c.useMemo(()=>{if(pe===0)return;const $=new Set;for(const re of t)W.has(re.messageId)&&$.add(re.accountConfigId);if($.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[pe,W,t]),Us=c.useCallback(()=>{if(xt){D();return}L("organize")},[xt,D,L]),qs=c.useCallback($=>{m?.([$])},[m]),jt=c.useCallback(($,re)=>{fe([$],!re)},[fe]),ts=c.useCallback($=>{R||X($)},[R,X]),_=c.useCallback(()=>{if(J.isRunning||J.phase.kind==="counting"){J.stop();return}he()},[J,he]),Y=c.useCallback(()=>{J.clear()},[J]);c.useEffect(()=>{if(Ue.current||!R&&s)return;const $=te>=0?te:G;$>=0&&Ce.scrollToIndex($,{align:"auto"})},[te,G,Ce,R,s]),c.useEffect(()=>{s&&(Ue.current=!1,U(s))},[s,U]),c.useEffect(()=>{N&&(t.some($=>$.messageId===N)||U(t[0]?.messageId))},[t,N,U]),c.useEffect(()=>{x?.({focusedMessageId:N,selectedIds:Array.from(W),hasList:Ze,blocksKeyboard:rt||P.isOpen})},[N,W,Ze,rt,P.isOpen,x]);const je=c.useRef(x);je.current=x,c.useEffect(()=>()=>je.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{J.phase.kind!=="idle"||J.isRunning||B(t.map($=>$.messageId))},[t,B,J.phase,J.isRunning]);const ut=c.useRef(e);c.useEffect(()=>{ut.current!==e&&(ut.current=e,he())},[e,he]),ou({shouldBlockFn:({action:$})=>jk($,ve,C)?(he(),!0):!1,enableBeforeUnload:!1,disabled:!ve||C!==void 0}),c.useEffect(()=>{const $=O.current;if(!$||!v||!h)return;const re=()=>{if(g)return;const{scrollTop:yt,scrollHeight:Nt,clientHeight:Je}=$;yt+Je>=Nt-200&&h()};return $.addEventListener("scroll",re,{passive:!0}),re(),()=>$.removeEventListener("scroll",re)},[v,g,h]),c.useEffect(()=>{const $=Pe.current;if(!$)return;const re=O.current?.querySelector(`[data-message-id="${$}"]`);re&&(Pe.current=null,re.focus({preventScroll:!0}))}),c.useEffect(()=>{if(k){if(!Ze){k.current=null;return}return k.current={focusNext:de,focusPrevious:ke,focusFirst:Ee,focusLast:De,openFocused:xs,toggleSelect:He,extendSelectDown:Dt,extendSelectUp:Ye,selectAll:es,clearSelection:()=>ve?(he(),!0):!1,requestVerb:Lt,toggleDensity:me},()=>{k.current=null}}},[k,Ze,de,ke,Ee,De,xs,He,Dt,Ye,es,ve,he,Lt,me]);const bt=n?"loading":a?"error":t.length===0?"empty":"ready",vt=a?Xl(o):void 0,ss=c.useCallback(()=>{const $=Ql(Gl());window.open($,"_blank","noopener,noreferrer")},[]),kn=[{id:"inbox",threads:[]}],bs=ye.length>0&&ye.every($=>W.has($)),Tr=nt&&v&&bs&&!f&&!d&&J.phase.kind==="idle"&&!J.isRunning,Rr=f||d||J.isRunning,Hs=J.phase.kind==="escalated"?J.phase.total:pe,Mr=J.runningAction?Ow(J.runningAction.kind,J.progress?.done??0,J.progress?.total??Hs):J.phase.kind==="counting"?"Counting matches…":J.phase.kind==="escalated"?Ck(u??{},J.phase.total):void 0,Ar=J.phase.kind!=="escalated"&&ye.length>0?{checked:bs,indeterminate:pe>0&&!bs,onChange:()=>xe(ye)}:void 0,Z=J.runningAction?{value:J.progress?.done??0,max:J.progress?.total??Hs,tone:$w(J.runningAction.kind)}:void 0,at=(J.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:J.stop}}:J.phase.kind==="escalated"&&!J.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:Y}}:Tr?{tone:"info",text:"",action:{label:kk(u??{}),onClick:J.escalate}}:void 0)??($t?{tone:"warning",text:$t}:void 0),of=r.jsx(lo,{title:A.title||y,navSlot:A.navSlot,titleMeta:A.titleMeta,searchSlot:A.searchSlot,searchField:A.searchField,idleSlot:A.makeFilterSlot,count:Hs,onCancel:_,onDelete:()=>L("delete"),onMove:()=>L("move"),onOrganize:Us,onJunk:se&&se!==e?()=>L("junk"):void 0,onMarkRead:()=>L("markRead"),overflowSlot:p&&e&&pe>0&&I.length>0?r.jsx(bd,{accountId:p,mailboxId:e,messageIds:Array.from(W)}):void 0,isBusy:Rr,isCounting:J.phase.kind==="counting",selectAll:Ar,statusLabel:Mr,progress:Z,notice:at}),lf=jd(ye,N),cf=c.useCallback($=>{Ue.current=!0,U($)},[U]),uf=r.jsxs(r.Fragment,{children:[T&&l&&r.jsx(Dk,{query:l}),r.jsxs("div",{ref:O,role:"listbox","aria-multiselectable":!0,"aria-label":y,className:"flex-1 overflow-y-auto",children:[r.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${Ce.getTotalSize()}px`},children:Ce.getVirtualItems().map($=>{const re=t[$.index];return r.jsx("div",{role:"presentation","data-index":$.index,ref:Ce.measureElement,className:_e("absolute left-0 top-0 w-full border-b border-line",J.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${$.start}px)`},children:r.jsx(Rk,{thread:re,mailboxId:e,isSelected:s===re.messageId,isFocused:N===re.messageId,isTabStop:lf===re.messageId,onFocusRow:cf,isChecked:Ne(re.messageId),onToggleCheck:we,onRowSelect:Ge,isMultiSelectMode:ue,onLongPress:ts,isDesktop:R,onDelete:qs,onToggleRead:jt,density:z})},$.key)})}),g&&r.jsx(op,{})]})]});return r.jsxs(r.Fragment,{children:[lt&&!R&&r.jsx(hn,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>Xe(null),children:lt}),r.jsx(Ac,{listTitle:y,listMeta:b,sections:kn,flatList:!0,listState:A.searchResults?"ready":bt,searchQuery:T?l:void 0,listFilter:S,listScopeLabel:w,errorMessage:vt,onRetry:i,onReportError:ss,density:z,selectedThreadId:s,onSelectThread:$=>j({to:"/mail/$mailboxId",params:{mailboxId:e},search:re=>({...re,selectedMessageId:$})}),onSelectBriefCategory:()=>{},isDesktop:R,hideHeader:M,selectionBar:of,listBody:A.searchResults??(bt==="ready"?uf:void 0)}),r.jsx(Xa,{isOpen:oe!==null,title:Zl(oe?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:f,onConfirm:Ft,onCancel:ct}),r.jsx(Do,{verb:E,accountId:p,mailboxId:e,selection:Qe,crossAccount:$t!==void 0,escalated:xt,escalatedProgress:J.progress,onFinished:he,onRunEnded:Se})]})},Fk=e=>ms({path:{accountId:e}}),$k=e=>{const t=Me(),s=pn(),n=Fe({...km(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:Fk(e)})}});return{trigger:()=>{n.mutate({path:{accountId:e}})},triggerAsync:()=>n.mutateAsync({path:{accountId:e}}),isPending:n.isPending,error:n.error,reset:n.reset}},_k=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:n}=$k(e);return r.jsx(Eg,{onRefresh:s,isRefreshing:n,children:t})};function zk({accountId:e,currentMailboxId:t,candidates:s,onMove:n,children:a}){const[o,i]=c.useState(!1),l=pn(),u=Wa(),{inboxMailboxId:m}=wo(e),f=So(e),{data:d}=be({...it({path:{accountId:e}}),staleTime:1/0}),h=c.useMemo(()=>Va({mailboxes:d?.items??[],folderAppointments:f,currentMailboxId:t,translator:u}),[d?.items,f,t,u]),v=c.useMemo(()=>m||(h.find(S=>S.label.toLowerCase()==="inbox")?.id??h.find(S=>!S.isCurrent)?.id??""),[m,h]),g=c.useRef(!1);c.useEffect(()=>{g.current||(g.current=!0,bS(l,s.length))},[l,s.length]);const p=c.useCallback(()=>{vS(l,s.length),i(!0)},[l,s.length]),y=c.useCallback((b,S)=>{yS(l,{selected:b.length,total:s.length,toInbox:S===m}),n(b,S)},[l,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(Rg,{count:s.length,onReview:p})}),r.jsx("div",{className:"min-h-0 flex-1",children:a}),r.jsx(Bg,{open:o,candidates:s,defaultDestinationId:v,availableFolders:h,delimiter:Qa(d?.items??[]),onConfirmMove:y,onCancel:()=>i(!1)})]})}const Bk="We can verify this sender";function Kk(e){const{data:t}=be({...Hl({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:Bk,trustSubReason:xS(n.senderTrust),senderTrust:n.senderTrust}))}}const Uk=e=>{const t=new Set,s=[];for(const n of e)t.has(n.threadMessageId)||(t.add(n.threadMessageId),s.push(n));return s},qk={unread:"unread",flagged:"starred",attachment:"attachments"},Hk=new Set(Object.values(ot)),Gd=e=>Hk.has(e),Wk=e=>Gd(e.category)||e.attributes.size>0,Vk=e=>{const t={};Gd(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const n=qk[s];n&&(t[n]=!0)}return t},Qk=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",Gk=["category","unread","starred","attachments"],yl=e=>JSON.stringify(Gk.map(t=>e?.[t]??null)),Yk=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},Xk=(e,t)=>{const s=Yk(e);return s?yl(s)===yl(t):!1},Yd="remit:intelligence-open";function Jk(){try{return localStorage.getItem(Yd)!=="closed"}catch{return!0}}function wl(e){try{localStorage.setItem(Yd,e?"open":"closed")}catch{}}const Zk=(e,t)=>e!==t,eC=(e,t,s)=>{if(!(s||!t))return e.find(n=>n.messageId===t)},tC=(e,t,s,n)=>{if(e)return e;if(!(n||!s))return t?.messageId===s?t:void 0},Pn=e=>e[0],sC=e=>{const t=Pn(e.filter(l=>l.type==="from").map(l=>l.value)),s=Pn(e.filter(l=>l.type==="subject").map(l=>l.value)),n=Pn(e.filter(l=>l.type==="category").map(l=>l.category)),a=Pn(e.filter(l=>l.type==="isUnread"||l.type==="isRead").map(l=>l.type==="isUnread")),o=e.some(l=>l.type==="isStarred")?!0:void 0,i=e.some(l=>l.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}:{}}},nC=(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 rC(e,t={}){const s=sC(e),n={...s,...t};return{params:s,residual:e.filter(a=>!nC(n,a))}}function aC(e,t,s){if(t.length===0)return e;const n=[...t];return e.filter(a=>{const o=Gn(a);return Ro({...o,accountId:o.accountId??s},n)})}const oC=50,iC=new Map(Uc().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),Xd=c.createContext(null);function Ir(){const e=c.useContext(Xd);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function lC({mailboxId:e,selectedMessageId:t,children:s}){const n=Ke(),o=Cr()==="desktop",i=pn(),{accounts:l,searchQuery:u,searchInput:m,intelligenceOpen:f,onToggleIntelligence:d,onSetIntelligenceOpen:h}=Ae(),v=gs(),g=Io(u),p=g.length>0,{freeText:y,tokens:b}=Bs(g,v),[S,w]=c.useState("all"),[x,k]=c.useState(new Set),M=c.useMemo(()=>({category:S,attributes:x}),[S,x]),O=c.useMemo(()=>Vk(M),[M]),j=p||Wk(M),{params:R,residual:P}=rC(b,O),E={order:"desc",limit:oC,...y?{query:y}:{},...R,...O},L={category:E.category,unread:E.unread,starred:E.starred,attachments:E.attachments},D=j?Ba({path:{mailboxId:e},query:E}):nr({path:{mailboxId:e},query:{order:"desc"}}),{data:C,isLoading:T,isError:A,error:I,refetch:F,fetchNextPage:N,hasNextPage:q,isFetchingNextPage:Q}=au({queryKey:D,queryFn:async({pageParam:Z})=>{if(j){const{data:at}=await oa({path:{mailboxId:e},query:{...E,continuationToken:Z},throwOnError:!0});return at}const{data:dt}=await Cm({path:{mailboxId:e},query:{order:"desc",continuationToken:Z},throwOnError:!0});return dt},initialPageParam:void 0,getNextPageParam:Z=>Z.continuationToken,placeholderData:(Z,dt)=>Xk(dt?.queryKey,L)?Z:void 0}),ae=c.useCallback(Z=>{t&&Z.includes(t)&&n({to:"/mail/$mailboxId",params:{mailboxId:e},search:dt=>({...dt,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,n]),{deleteMessages:U,isPending:z}=us({mailboxId:e,onAfterOptimisticRemove:ae}),{accountId:ee}=bo(e),me=xu({accounts:l}),{moveMessages:fe,isPending:se}=cs({mailboxId:e,accountId:ee,onAfterOptimisticRemove:ae}),W=aC(uy(Uk(C?.pages.flatMap(Z=>Z.items??[])??[])),P,ee),pe=c.useCallback(Z=>{w(Z)},[]),ve=c.useCallback(Z=>{k(dt=>{const at=new Set(dt);return at.has(Z)?at.delete(Z):at.add(Z),at})},[]),Ne=c.useCallback(()=>{w("all"),k(new Set)},[]),we=iC.get(S),X=we?{label:we,reach:P.length>0?"loaded-pages":Qk(E),onClear:Ne}:void 0,H=Zk(m,u),ie=eC(W,t,H),[ge,ze]=c.useState(void 0);c.useEffect(()=>{ie&&ze(ie)},[ie]);const xe=tC(ie,ge,t,H),{selectedThreadId:B}=As({strict:!1}),ue=c.useMemo(()=>_d(xe,{messageId:t,threadId:H?void 0:B,mailboxId:e}),[xe,t,B,H,e]),oe=Fo(),{listCommandsRef:ne,onTriageContextChange:nt,focusedMessageId:Te,selectedIds:J}=oe,Se=W.find(Z=>Z.messageId===Te)??xe,Ve=c.useRef(null);c.useEffect(()=>{const Z=xe?.messageId??null;Z&&Ve.current!==Z&&xe?.authenticity?.dkimMismatch&&(Ve.current=Z,f||d())},[xe?.messageId,xe?.authenticity?.dkimMismatch,f,d]);const Oe=c.useRef(!1);c.useEffect(()=>{Oe.current||o&&xe?.messageId&&(Oe.current=!0,Jk()&&!f&&h(!0))},[o,xe?.messageId,f,h]);const he=cv({accounts:l})??0,lt=Me(),{pushError:Xe}=st(),Pe=dn({thread:xe,mailboxId:e,accountId:ee,onAfterOptimisticRemove:ae}),{draftsMailboxId:Ue}=iy(ee),qe=Ue!==void 0&&Ue===e,{archiveMailboxId:Ze}=oy(ee),rt=$d(),{requestCompose:Ce}=Pe,G=c.useCallback(()=>{Ce("reply")},[Ce]),te=c.useCallback(()=>{Ce("reply_all")},[Ce]),ce=c.useCallback(()=>{Ce("forward")},[Ce]),{state:de,openCompose:ke,closeCompose:Ee}=Yt(),De=c.useCallback(()=>{ke({mode:"new"})},[ke]),He=Fe({...sr(),onError:Z=>{Xe(is("Couldn't discard draft","The draft wasn't deleted.",Z))}}),ye=c.useCallback(()=>{const Z=de.outboxMessageId;Z&&(He.mutate({path:{outboxMessageId:Z}}),lt.invalidateQueries({queryKey:Ha()}),Ee())},[de.outboxMessageId,He,lt,Ee]),Qe=c.useCallback(()=>{n({to:"/mail/$mailboxId",params:{mailboxId:e},search:Z=>({...Z,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,n]),Ge=c.useCallback(Z=>Z?rt(Z):[],[rt]),{toggleStar:Le}=vo({threadId:Se?.threadId??"",mailboxId:e}),{toggleReadFor:et}=yr({mailboxId:e,accountId:ee}),{junkMailboxId:Ye}=_s(ee),Dt=Ye!=null&&Ye===e,{candidates:es}=Kk(Dt?Ye:void 0),{moveMessages:Lt}=cs({mailboxId:e,threadId:Se?.threadId,accountId:ee,onAfterOptimisticRemove:ae}),{deleteMessages:xs}=us({mailboxId:e,threadId:Se?.threadId,onAfterOptimisticRemove:ae}),{addressId:tt,address:xt}=Pd(Se),{updateFlags:Ft}=Dd({addressId:tt,senderEmail:Se?.fromEmail??void 0}),ct=c.useCallback(()=>t||!Te?!1:(n({to:"/mail/$mailboxId",params:{mailboxId:e},search:Z=>({...Z,selectedMessageId:Te})}),!0),[t,Te,e,n]),$t=c.useCallback(()=>{ct()||xe&&Ce("reply")},[ct,xe,Ce]),Us=c.useCallback(()=>{ct()||xe&&Ce("reply_all")},[ct,xe,Ce]),qs=c.useCallback(()=>{ct()||xe&&Ce("forward")},[ct,xe,Ce]),jt=c.useCallback(()=>Ge(Se),[Ge,Se]),ts=c.useCallback(()=>{if(ne.current?.requestVerb("delete"))return;const Z=jt();Z.length>0&&xs(Z)},[ne,jt,xs]),_=c.useCallback(()=>{if(ne.current?.requestVerb("junk")||!Ye)return;const Z=jt();Z.length!==0&&(Fd(i,{count:Z.length,senderTrust:Se?.senderTrust??"unknown",wasRescuable:Se?Ld(Se):!1}),Lt(Z,Ye))},[ne,Ye,jt,Lt,i,Se]),Y=c.useCallback(()=>{if(J.length>0){const Z=!(Se?.hasStars??!1),dt=new Set(J);for(const at of W)dt.has(at.messageId)&&at.hasStars!==Z&&Le(at.messageId,at.hasStars);return}Se&&Le(Se.messageId,Se.hasStars)},[J,W,Se,Le]),je=c.useCallback(()=>{if(ne.current?.requestVerb("markRead"))return;const Z=jt();if(Z.length===0)return;const dt=!(Se?.isRead??!1);et(Z,dt)},[ne,jt,Se,et]),ut=c.useCallback(()=>{if(!tt)return;const Z=xt?.flags?.muted?.value!==!0;Ft({muted:{value:Z}})},[tt,xt,Ft]),bt=c.useCallback(()=>{if(!tt)return;const Z=xt?.flags?.vip?.value!==!0;Ft({vip:{value:Z}})},[tt,xt,Ft]),vt=c.useCallback(()=>{f||d()},[f,d]),ss=c.useCallback(Z=>{n({to:Z})},[n]),kn=qe?"drafts":Ze===e?"archive":Ye===e?"junk":"inbox",bs=c.useRef("");c.useEffect(()=>{const Z=bs.current;bs.current=g,g.length>0&&Z.length===0&&i.recordEvent("search.submitted",{mailboxType:kn})},[g,kn,i]);const Tr=qe&&de.isOpen&&!!de.outboxMessageId&&!xe,{goBack:Rr,nextMessageId:Hs,previousMessageId:Mr}=$o({context:oe,orderedIds:W.map(Z=>Z.messageId),selectedMessageId:t,enabled:!de.isOpen,onClose:Qe,handlers:{reply:$t,replyAll:Us,forward:qs,delete:ts,toggleStar:Y,toggleRead:je,muteSender:ut,blockSender:vt,vipSender:bt,markJunk:_,toggleIntelligence:xe?d:void 0,compose:De,goBrief:()=>ss("/mail"),goInbox:()=>ss("/mail"),goSent:()=>ss("/mail"),goFlagged:()=>ss("/mail/flagged"),goSettings:()=>ss("/settings")}});xo({enabled:de.isOpen,bindings:[{key:"Escape",handler:Ee,preventDefault:!0}]});const Ar={mailboxId:e,selectedMessageId:t,selectedThread:xe,conversation:ue,threads:W,isLoading:T,isError:A,error:I,mailboxAccountId:ee,mailboxName:me,unreadCount:he,isDraftsMailbox:qe,isSpamFolder:Dt,rescueCandidates:es,filterCategory:S,filterAttributes:x,onSelectFilterCategory:pe,onToggleFilterAttribute:ve,onClearFilters:Ne,listFilter:X,intelligenceOpen:f,onToggleIntelligence:d,searchPredicate:p&&P.length===0?E:void 0,onDeleteMessages:U,onMoveMessages:fe,isDeleting:z,isMoving:se,onLoadMore:N,hasMore:q,isLoadingMore:Q,onTriageContextChange:nt,listCommandsRef:ne,onRetry:()=>F(),toolbarComposeRequest:Pe.composeRequest,onToolbarReply:G,onToolbarReplyAll:te,onToolbarForward:ce,onClearComposeRequest:Pe.clearComposeRequest,onToolbarDelete:Pe.deleteThread,onToolbarStar:Pe.toggleStar,onToolbarDiscardDraft:ye,onToolbarMove:Pe.moveThread,composeState:de,closeCompose:Ee,hasRemitDraftOpen:Tr,onBack:Rr,nextMessageId:Hs,previousMessageId:Mr};return r.jsx(Xd.Provider,{value:Ar,children:s})}function Jd(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:n,isError:a,error:o,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:m,onLoadMore:f,hasMore:d,isLoadingMore:h,mailboxAccountId:v,mailboxName:g,unreadCount:p,isDraftsMailbox:y,isSpamFolder:b,rescueCandidates:S,onTriageContextChange:w,listCommandsRef:x,onRetry:k,filterCategory:M,filterAttributes:O,onSelectFilterCategory:j,onToggleFilterAttribute:R,onClearFilters:P,listFilter:E,searchPredicate:L}=Ir(),{searchQuery:D,searchInput:C,accounts:T,resultFolderIndex:A}=Ae(),I=Cr(),F=Ke(),N=g??"Inbox",q=c.useMemo(()=>Uc(),[]),Q=c.useMemo(()=>s.map(pe=>$0(pe,A)),[s,A]),{hits:ae,isLoading:U}=hd({mailboxId:e,filterCategory:M}),z=c.useMemo(()=>gd(ae,s.map(pe=>pe.threadId),A),[ae,s,A]),ee=c.useCallback(pe=>F({to:"/mail/$mailboxId",params:{mailboxId:pe.mailboxId??e},search:ve=>({...ve,q:C||void 0,selectedMessageId:pe.id,selectedThreadId:pe.threadId})}),[e,F,C]);if(y&&v)return r.jsx(ak,{mailboxId:e,accountId:v,selectedMessageId:t,imapThreads:s,title:g??"Drafts",unreadCount:p??void 0});const me=r.jsx(Lk,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:n,isError:a,error:o,onRetry:k,searchQuery:D,searchPredicate:L,onDeleteMessages:i,isDeleting:u,isMoving:m,onLoadMore:f,hasMore:d,isLoadingMore:h,accountId:v,listTitle:N,listFilter:E,listScopeLabel:N,hideHeader:!0,onTriageContextChange:w,commandsRef:x}),fe=T[0]?.accountId,se=I==="phone"&&fe?r.jsx(_k,{accountId:fe,children:me}):me,W=b&&S.length>0&&v?r.jsx(zk,{accountId:v,currentMailboxId:e,candidates:S,onMove:l,children:se}):se;return r.jsx(Ud,{title:N,unreadCount:p,preset:q,selectedCategory:M,activeFilters:O,onSelectCategory:j,onToggleFilter:R,onClearFilters:P,searchResults:Q,searchLoading:n,relatedResults:z,relatedLoading:U,onSelectSearchResult:ee,searchResultsInBody:!0,children:W})}function cC(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:l,onToolbarReply:u,onToolbarReplyAll:m,onToolbarForward:f,onClearComposeRequest:d,onToolbarDelete:h,onToolbarStar:v,onToolbarDiscardDraft:g,onToolbarMove:p,composeState:y}=Ir(),b=fs()?.showIntelligencePane??!1,S=!!n,w=b&&S,x=y.isOpen&&!n?r.jsx(Wd,{}):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:l,onComposeClose:d}):r.jsx($s,{});return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Lo,{hasThread:S,intelligenceOpen:w&&o,canToggleIntelligence:w,onToggleIntelligence:i,onReply:S?u:void 0,onReplyAll:S?m:void 0,onForward:S?f:void 0,canDelete:S||a,onDelete:S?h:a?g:void 0,onToggleStar:S?v:void 0,isStarred:s?.hasStars,moveContext:S&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:x})]})}function uC(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:n}=Ir();return r.jsx(Ks,{onClose:n,thread:s,mailboxId:e,accountId:t})}function dC(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:n,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=Ir(),m=Ke();if(s){const f=d=>m({to:"/mail/$mailboxId",params:{mailboxId:e},search:h=>({...h,selectedMessageId:d,selectedThreadId:void 0})});return r.jsxs(r.Fragment,{children:[r.jsx(zs,{threadId:s.threadId,mailboxId:s.mailboxId,subject:s.subject,selectedMessageId:s.messageId,authenticity:s.authenticity,onBack:o,onOpenIntelligence:a,onSwipeNext:i?()=>f(i):void 0,onSwipePrevious:l?()=>f(l):void 0,mobileIntelligenceOpen:n}),r.jsx(po,{isOpen:n,onClose:a,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?r.jsx("div",{className:"h-full",children:r.jsx(Wd,{})}):r.jsx(Jd,{})}const tn=Object.assign(lC,{List:Jd,Reading:cC,Intelligence:uC,Phone:dC}),Zd=e=>e==="failed"||e==="blocked",ef=e=>e!=="draft"&&e!=="sent",Bo="remit.savedSearches",fC=25;function Xn(){try{const e=localStorage.getItem(Bo);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function mC(e){const t=e.trim();if(!t)return Xn();const s=[t,...Xn().filter(n=>n!==t)].slice(0,fC);try{localStorage.setItem(Bo,JSON.stringify(s))}catch{return s}return s}function hC(e){const t=Xn().filter(s=>s!==e);try{localStorage.setItem(Bo,JSON.stringify(t))}catch{return t}return t}const Sl=e=>/^\d/.test(e),pC=(e,t)=>{const s=Sl(e),n=Sl(t);return s&&!n?-1:!s&&n?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function gC(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)=>pC(Kn(o,void 0,s),Kn(i,void 0,s))),{system:n,labels:a}}function xC(e,t,s){const n=jm(t)&&e.unseenCount>0;return{id:e.mailboxId,name:Kn(e,t,s),unseen:n?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function bC(){const e=gr(),t=_a({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 kl({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const n=Me(),a=Ke(),o=bC(),{searchInput:i,onSearchChange:l}=Ae(),[u,m]=c.useState(Xn),{t:f}=za("mail",{useSuspense:!1}),d=c.useCallback((j,R)=>f(j,{defaultValue:R}),[f]),h=pt({queries:e.map(j=>({...it({path:{accountId:j.accountId}}),staleTime:1/0}))}),{data:v}=be(er()),g=c.useMemo(()=>(v?.items??[]).filter(j=>ef(j.status)).length,[v?.items]),p=c.useMemo(()=>e.map((j,R)=>{const P=h[R],E=P?.data?.items??[],L=Fa(j.folderAppointments),{system:D,labels:C}=gC(E,L,d),T=P?.isError?"error":P?.isLoading?"loading":"ready";return{id:j.accountId,label:j.email,email:j.email,muted:!!j.muted,outboxPending:g,status:T,onRetry:()=>P?.refetch(),mailboxes:[...D,...C].map(A=>xC(A,L.get(A.mailboxId),d))}}),[e,h,g,d]),y=j=>{n.invalidateQueries({queryKey:nr({path:{mailboxId:j},query:{order:"desc"}})})},b=({navId:j,className:R,ariaLabel:P,title:E,children:L,onClick:D})=>j==="brief"?r.jsx(Kt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>D?.(),className:R,"aria-label":P,title:E,children:L}):j==="outbox"?r.jsx(Kt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>D?.(),className:R,"aria-label":P,title:E,children:L}):j==="flagged"?r.jsx(Kt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>D?.(),className:R,"aria-label":P,title:E,children:L}):j==="settings"?r.jsx(Kt,{to:"/settings/accounts",onClick:()=>D?.(),className:R,"aria-label":P,title:E,children:L}):r.jsx(Kt,{to:"/mail/$mailboxId",params:{mailboxId:j},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{y(j),D?.()},className:R,"aria-label":P,title:E,children:L}),S=()=>{l(""),t?.()},w=i.trim(),x=w.length>0&&!u.includes(w)?w:void 0,k=c.useCallback(()=>{x&&m(mC(x))},[x]),M=c.useCallback(j=>{m(hC(j))},[]),O=c.useCallback(j=>{l(j),a({to:"/mail",search:{q:j,selectedMessageId:void 0}}),t?.()},[l,a,t]);return r.jsx(eg,{accounts:p,selectedNavId:o,onSelectNav:S,linkComponent:b,variant:s,savedSearches:u,saveableQuery:x,onSaveCurrentSearch:k,onSelectSavedSearch:O,onRemoveSavedSearch:M})}function vC(){return r.jsxs("button",{type:"button",onClick:Fl,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(fc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]})}function yC({accounts:e,onMailboxSelect:t}){return fs()?.showNavPane??!0?r.jsx(kl,{accounts:e}):r.jsxs("div",{className:"flex h-full flex-col",children:[r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(kl,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),r.jsxs("div",{className:"border-t border-line px-2 py-2",children:[r.jsxs(Kt,{to:"/settings/accounts",onClick:t,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[r.jsx(wc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),r.jsx(vC,{}),r.jsx(uu,{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(xc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function wC(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 SC(e){return e.tokens.length>0&&e.freeText.trim().length===0}const tf={queued:{icon:Ga,label:"Queued",className:"text-warning"},sending:{icon:Ps,label:"Sending…",className:"text-accent-2"},sent:{icon:mc,label:"Sent",className:"text-positive"},failed:{icon:ds,label:"Failed",className:"text-danger"},blocked:{icon:Aa,label:"Blocked",className:"text-warning"}},kC=e=>Qm(e).toDateString()===new Date().toDateString()?Un(e,{hour:"numeric",minute:"2-digit"}):Un(e,{month:"short",day:"numeric"}),Cl=e=>Un(e,{dateStyle:"medium",timeStyle:"short"}),CC=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},sf=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",nf=c.createContext(null);function Ko(){const e=c.useContext(nf);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function jC({children:e}){const t=Ke(),{selectedOutboxMessageId:s}=As({strict:!1}),{data:n,isLoading:a}=be(er()),{searchQuery:o}=Ae(),i=gs(),l=Io(o),u=Bs(l,i),m=l.length>0,f=SC(u),d=c.useMemo(()=>f?[]:(n?.items??[]).filter(p=>ef(p.status)).filter(p=>wC(p,u.freeText)),[n,u.freeText,f]),h=c.useMemo(()=>d.find(p=>p.outboxMessageId===s),[d,s]),v=c.useCallback(p=>{t({to:"/mail/outbox",search:y=>({...y,selectedOutboxMessageId:p})})},[t]),g={messages:d,hasQuery:m,unsupportedQuery:f,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:v};return r.jsx(nf.Provider,{value:g,children:e})}function rf({message:e,isSelected:t,onSelect:s}){const n=Me(),{openCompose:a}=Yt(),{pushError:o}=st(),i=c.useCallback(()=>{n.invalidateQueries({queryKey:Ha()})},[n]),l=Fe({...Kl(),onSuccess:i,onError:d=>{o(is("Couldn't resend message","The message wasn't sent.",d))}}),u=Fe({...sr(),onSuccess:i,onError:d=>{o(is("Couldn't delete message","The message wasn't deleted.",d))}}),m=e.status;if(!tf[m])return null;const f=Zd(e.status);return r.jsx(jg,{recipients:CC(e),subject:e.subject||"",time:kC(e.sentAt??e.updatedAt),status:m,error:f?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:m==="failed"?()=>l.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:l.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function af({message:e,onBack:t}){const s=e.status,n=tf[s],a=n?.icon??mn,o=e.sentAt?Cl(e.sentAt):Cl(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(Ma,{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:_e("size-4",n.className,s==="sending"&&"animate-spin")}),r.jsx("span",{className:_e("text-xs font-medium",n.className),children:n.label}),Zd(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(rd,{html:e.htmlBody,text:e.textBody})})]})}function NC(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,onSelectMessage:o}=Ko(),i=c.useRef(null);return Jn({containerRef:i,itemSelector:Ia}),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:sf(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(_o,{}),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(l=>r.jsx(rf,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function EC(){const{selectedMessage:e}=Ko();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(af,{message:e}):r.jsx($s,{message:"Select a message to read",showHints:!1})})]})}function IC(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=Ko(),l=c.useRef(null);return Jn({containerRef:l,itemSelector:Ia}),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(af,{message:o,onBack:()=>i(void 0)}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx($s,{message:sf(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(_o,{}),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:l,className:"flex-1 overflow-y-auto",children:e.map(u=>r.jsx(rf,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const Dn=Object.assign(jC,{List:NC,Reading:EC,Phone:IC}),TC=({isOpen:e,onClose:t})=>{const s=c.useCallback(n=>{n.key==="Escape"&&(n.preventDefault(),t())},[t]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:t,onKeyDown:n=>n.key==="Escape"&&t(),children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.jsxs("div",{className:_e("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),onClick:n=>n.stopPropagation(),onKeyDown:n=>{n.key!=="Escape"&&n.stopPropagation()},children:[r.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),r.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:r.jsx(Ct,{className:"size-5"})})]}),r.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:vu.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(c.Fragment,{children:[i>0&&a.keys[0]==="g"&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),r.jsx(Is,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},n.title))}),r.jsx("div",{className:"mt-6 border-t border-line pt-4",children:r.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",r.jsx(Is,{children:"Esc"})," to close"]})})]})]}):null};function RC(e){const t=pt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>Z0(t.map(s=>s.data?.items??[])),[t])}const MC=e=>e.map(t=>t.data?.items??[]);function AC(e){const t=pt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0})),combine:MC});return c.useMemo(()=>Nm(e.map((s,n)=>({folderAppointments:s.folderAppointments,mailboxes:t[n]??[]}))),[e,t])}var Ln={exports:{}},jl;function OC(){if(jl)return Ln.exports;jl=1;const e=(t,s,n)=>new Promise((a,o)=>{if(n=Object.assign({concurrency:1/0},n),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=n;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const l=[],u=t[Symbol.iterator]();let m=!1,f=!1,d=0,h=0;const v=()=>{if(m)return;const g=u.next(),p=h;if(h++,g.done){f=!0,d===0&&a(l);return}d++,Promise.resolve(g.value).then(y=>s(y,p)).then(y=>{l[p]=y,d--,v()},y=>{m=!0,o(y)})};for(let g=0;g<i&&(v(),!f);g++);});return Ln.exports=e,Ln.exports.default=e,Ln.exports}var PC=OC();const DC=Em(PC),LC=900*1e3,FC=300,$C=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},_C=60*1e3,zC=e=>Math.max($C(e,FC)*1e3,_C),Bn=zC(Rm().mailboxPollIntervalSeconds),BC=5,Na=new Set,KC=(e,t,s=LC)=>e.filter(n=>{const a=n.lastSyncAt;return a==null?!0:t-a>s}).map(n=>n.accountId),UC=(e,t,s=Bn)=>e-t>=s,qC=(e,t)=>e.filter(s=>!t.has(s)),Nl=(e,t)=>{if(Na.delete(e),Tm(t,{softError:!0})){Vl(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},El=(e,t)=>Im({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:ms({path:{accountId:e}})})}),HC=e=>{const t=Me(),s=c.useRef(e);s.current=e;const n=e.map(a=>a.accountId).join(",");c.useEffect(()=>{const a=Date.now(),i=KC(s.current,a).filter(l=>!Na.has(l));if(i.length!==0)for(const l of i)Na.add(l),El(l,t).catch(u=>{Nl(l,u)})},[n,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const f=qC(s.current.map(d=>d.accountId),i);for(const d of f)i.add(d);DC(f,d=>El(d,t).catch(h=>{Nl(d,h)}).finally(()=>{i.delete(d)}),{concurrency:BC})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,Bn);return}},m=()=>{document.visibilityState==="visible"&&UC(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,Bn))};return o=setTimeout(u,Bn),document.addEventListener("visibilitychange",m),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",m)}},[n,t])};function WC(e,t,s){if(e!==t)return s}function VC(e,t){return e===""?"":t}function QC(e,t,s){return t!==e?!1:t!==s}function GC(){const{q:e=""}=As({from:"/mail"}),t=Ke(),s=Cr(),n=vd(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,m]=c.useState(!1),f=c.useCallback(se=>{m(se),wl(se)},[]),[d,h]=c.useState(e),v=ir(d,200),g=VC(d,v),p=c.useRef(e);p.current=e;const y=It({select:se=>rv(se.matches)}),[b,S]=c.useState(y);if(b!==y){const se=WC(b,y,e);S(y),se!==void 0&&h(se)}c.useEffect(()=>{QC(d,g,p.current)&&t({to:".",search:se=>{const W=se.q===g;return{...se,q:g||void 0,...g&&!W?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[d,g,t]);const{data:w,isLoading:x,isError:k,error:M,refetch:O}=be({...Mt(),staleTime:1/0}),j=!!(w&&(w.accounts?.length??0)===0);c.useEffect(()=>{j&&t({to:"/onboarding",replace:!0})},[j,t]),xo({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const R=c.useCallback(se=>{h(se)},[]),P=c.useCallback(()=>{h("")},[]),E=c.useCallback(()=>{h("")},[]),L=c.useCallback(()=>{m(se=>{const W=!se;return wl(W),W})},[]),D=w?.accounts??[],C=RC(D),T=AC(D),A=c.useMemo(()=>J0(D),[D]),I=It({select:se=>se.matches.find(pe=>"mailboxId"in pe.params)?.params.mailboxId}),{selectedMessageId:F}=As({strict:!1}),N=It({select:se=>ho(se.matches)}),q=It({select:se=>xn(se.matches)}),Q=It({select:se=>xr(se.matches)});HC(D);const ae=c.useCallback(()=>{l(!1)},[]),U={accounts:D,mailboxNameIndex:C,accountNameIndex:A,resultFolderIndex:T,searchQuery:g,searchInput:d,searchViewKey:y,onSearchChange:R,onSearchClear:P,onSearchClearQuery:E,intelligenceOpen:u,onToggleIntelligence:L,onSetIntelligenceOpen:f},z=r.jsx(yC,{accounts:D,onMailboxSelect:ae}),ee=n?r.jsx(tv,{accounts:D}):void 0,me=n?void 0:r.jsx(dv,{accounts:D}),fe={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return r.jsxs(Mm.Provider,{value:U,children:[k?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:r.jsx(Jt,{title:"Couldn't load your account",error:M,onRetry:()=>{O()}})}):N?r.jsx(Js,{selectedMessageId:F,children:n?r.jsx(_t,{nav:z,list:r.jsx(Js.Phone,{}),intelligenceOpen:u,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||j,...fe}):r.jsx(_t,{nav:z,topBar:me,list:r.jsx(Js.List,{}),reading:r.jsx(Js.Reading,{}),intelligence:r.jsx(Js.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||j,...fe})}):q?r.jsx(Zs,{selectedMessageId:F,children:n?r.jsx(_t,{nav:z,list:r.jsx(Zs.Phone,{}),intelligenceOpen:u,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||j,...fe}):r.jsx(_t,{nav:z,topBar:me,list:r.jsx(Zs.List,{}),reading:r.jsx(Zs.Reading,{}),intelligence:r.jsx(Zs.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||j,...fe})}):I?r.jsx(tn,{mailboxId:I,selectedMessageId:F,children:n?r.jsx(_t,{nav:z,list:r.jsx(tn.Phone,{}),intelligenceOpen:u,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||j,...fe}):r.jsx(_t,{nav:z,topBar:me,list:r.jsx(tn.List,{}),reading:r.jsx(tn.Reading,{}),intelligence:r.jsx(tn.Intelligence,{}),intelligenceOpen:u,hasThread:!!F,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||j,...fe})}):Q?r.jsx(Dn,{children:n?r.jsx(_t,{nav:z,list:r.jsx(Dn.Phone,{}),intelligenceOpen:!1,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||j,...fe}):r.jsx(_t,{nav:z,topBar:me,list:r.jsx(Dn.List,{}),reading:r.jsx(Dn.Reading,{}),intelligenceOpen:!1,overlay:ee,skeleton:r.jsx(Et,{}),isLoading:x||j,...fe})}):r.jsx(Et,{}),r.jsx(TC,{isOpen:a,onClose:()=>o(!1)}),r.jsx(Am,{})]})}const mj=Object.freeze(Object.defineProperty({__proto__:null,component:GC,useMailContext:Ae},Symbol.toStringTag,{value:"Module"}));export{fj as S,Bh as U,mj as m};