@remit/web-client-dist 0.0.196 → 0.0.197

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 (44) hide show
  1. package/assets/{ComposeBody-PaioGRCf.js → ComposeBody-B2vOXJks.js} +1 -1
  2. package/assets/{ConfirmDialog-DZRbTR_Q.js → ConfirmDialog-C6CU1OjE.js} +1 -1
  3. package/assets/{ErrorState-B1m0Htkw.js → ErrorState-M_pFu8aN.js} +1 -1
  4. package/assets/OnboardingWizard-BTnABhRN.js +1 -0
  5. package/assets/{account-form-helpers-Dw8IX5ad.js → account-form-helpers-Bhi4Rzf0.js} +1 -1
  6. package/assets/accounts-DGEE_GG9.js +1 -0
  7. package/assets/{advanced-BmGalmey.js → advanced-l8YQZ8iy.js} +1 -1
  8. package/assets/{appearance-C6Sr9VRe.js → appearance-lYNZiyOz.js} +1 -1
  9. package/assets/{avatar-BFql-Wf3.js → avatar-CfkjR-kb.js} +1 -1
  10. package/assets/{browser-ponyfill-CIc2O2ss.js → browser-ponyfill-C6nW6Z5s.js} +1 -1
  11. package/assets/{circle-check-BzcLYagA.js → circle-check-D0TxZacD.js} +1 -1
  12. package/assets/{download-D3vX661x.js → download-CTFEbpLY.js} +1 -1
  13. package/assets/{filters-BNIvedmO.js → filters-BhE2Lagq.js} +1 -1
  14. package/assets/{flagged-CiFVGUbQ.js → flagged-BfJP3n4r.js} +1 -1
  15. package/assets/{folders-CALbsNI3.js → folders-CGvd9tQZ.js} +1 -1
  16. package/assets/{index-CptAZLJ2.css → index--xj3F7pg.css} +1 -1
  17. package/assets/{index-c7-N9vnh.js → index-BFqSByFz.js} +1 -1
  18. package/assets/index-Hyxyg__Y.js +1 -0
  19. package/assets/{index-CKFUe2Hf.js → index-mws8rN6y.js} +66 -66
  20. package/assets/{kbd-BlUZIvOx.js → kbd-DlrOv9Zh.js} +1 -1
  21. package/assets/{labels-7OoO6vj3.js → labels-DQ2TVqxg.js} +1 -1
  22. package/assets/mail-5BbrAW29.js +118 -0
  23. package/assets/{move-mailbox-picker-aWLZRXnO.js → move-mailbox-picker-D8AYTyKZ.js} +1 -1
  24. package/assets/{move-targets-BznNJwIY.js → move-targets-D4Fi-JcC.js} +1 -1
  25. package/assets/onboarding-B3AEvWJv.js +1 -0
  26. package/assets/{search-B2bPE-iK.js → search-DPurpJuT.js} +1 -1
  27. package/assets/{senders-B6P4l5Pi.js → senders-Dk38XyTY.js} +1 -1
  28. package/assets/settings-qsl12LHc.js +1 -0
  29. package/assets/{settings-screen-CLOXT-9K.js → settings-screen-zXXIRIb1.js} +1 -1
  30. package/assets/{shield-check-DpuRrVB8.js → shield-check-CiIrS9RF.js} +1 -1
  31. package/assets/{suggested-vips-DfHKQsjf.js → suggested-vips-B4HyglJH.js} +1 -1
  32. package/assets/{useDebouncedValue-oa1RpC9E.js → useDebouncedValue-Dgz4NsSl.js} +1 -1
  33. package/assets/{useLabels-Cvsyvf4k.js → useLabels-CZy77x33.js} +1 -1
  34. package/assets/useRulePreview-DT4XJtYS.js +1 -0
  35. package/assets/{useSignature-BRr_qVQ8.js → useSignature-DdJIWFO1.js} +1 -1
  36. package/index.html +2 -2
  37. package/package.json +1 -1
  38. package/assets/OnboardingWizard-CWaVbxbx.js +0 -1
  39. package/assets/accounts-X1ShI88H.js +0 -1
  40. package/assets/index-C0v7_T0F.js +0 -1
  41. package/assets/mail-CPS9KUT6.js +0 -118
  42. package/assets/onboarding-DbR84ysV.js +0 -1
  43. package/assets/settings-Cu83jD12.js +0 -1
  44. package/assets/useRulePreview-CNVWuuDh.js +0 -1
@@ -0,0 +1,118 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-B2vOXJks.js","assets/index-mws8rN6y.js","assets/index--xj3F7pg.css","assets/search-DPurpJuT.js","assets/avatar-CfkjR-kb.js","assets/kbd-DlrOv9Zh.js","assets/shield-check-CiIrS9RF.js","assets/account-form-helpers-Bhi4Rzf0.js","assets/useSignature-DdJIWFO1.js","assets/useDebouncedValue-Dgz4NsSl.js","assets/useRulePreview-DT4XJtYS.js","assets/ErrorState-M_pFu8aN.js","assets/format-B6Elex-n.js","assets/move-targets-D4Fi-JcC.js","assets/move-mailbox-picker-D8AYTyKZ.js","assets/circle-check-D0TxZacD.js","assets/ConfirmDialog-C6CU1OjE.js","assets/useLabels-CZy77x33.js"])))=>i.map(i=>d[i]);
2
+ import{R as K,c as jf,r as c,a as he,j as n,C as Dt,X as Ze,b as H,B as W,d as pt,S as Ft,e as xt,f as ts,L as et,g as Na,h as kf,i as Cf,k as nn,T as ct,l as ss,u as er,m as Ea,n as Nf,I as Ia,p as jl,o as Ta,q as Ef,D as Ra,s as rn,O as If,M as Tf,A as Rf,F as kl,t as Mf,v as Af,w as Of,x as Df,y as Cl,z as Ma,P as Pf,E as Lf,G as Aa,H as Oa,_ as Rt,J as Nl,K as Ff,Q as Da,N as $f,U as _f,V as zf,W as aa,Y as Bf,Z as Kf,$ as we,a0 as Uf,a1 as qf,a2 as Hf,a3 as Wf,a4 as Vf,a5 as Qf,a6 as qo,a7 as Yf,a8 as Gf,a9 as Xf,aa as Pa,ab as El,ac as Il,ad as $t,ae as $e,af as Ue,ag as an,ah as Ne,ai as La,aj as Fa,ak as $a,al as _a,am as tr,an as js,ao as ke,ap as on,aq as ue,ar as Tl,as as Jf,at as je,au as Rl,av as Zf,aw as sr,ax as nr,ay as Ml,az as Al,aA as jt,aB as tt,aC as em,aD as lt,aE as Ol,aF as Jt,aG as rr,aH as tm,aI as ar,aJ as za,aK as Ba,aL as ns,aM as or,aN as rs,aO as sm,aP as nm,aQ as ks,aR as rm,aS as Dl,aT as Cs,aU as am,aV as Ka,aW as om,aX as im,aY as lm,aZ as Pl,a_ as Ua,a$ as Ll,b0 as Fl,b1 as Is,b2 as cm,b3 as Ho,b4 as um,b5 as dm,b6 as wt,b7 as fm,b8 as oa,b9 as ia,ba as mm,bb as hm,bc as $l,bd as pm,be as qa,bf as _l,bg as gm,bh as xm,bi as bm,bj as vm,bk as ym,bl as wm,bm as Sm,bn as jm,bo as km,bp as Cm,bq as Nm,br as Em,bs as Im,bt as It,bu as yt,bv as Tm}from"./index-mws8rN6y.js";import{S as ir}from"./search-DPurpJuT.js";import{A as bt,M as Ha,C as Rm}from"./avatar-CfkjR-kb.js";import{K as vs}from"./kbd-DlrOv9Zh.js";import{S as ln,C as Wa,R as Mm}from"./shield-check-CiIrS9RF.js";import{M as zl,a as Am}from"./account-form-helpers-Bhi4Rzf0.js";import{R as Om,u as Dm}from"./useSignature-DdJIWFO1.js";import{u as lr}from"./useDebouncedValue-Dgz4NsSl.js";import{B as Bl,u as _t,a as Wo,i as Pm,b as la,n as Lm,S as Va,c as Kl,r as Qa,d as Ul,e as ql,f as Hl,g as Fm,h as $m,j as _m,s as zm,k as Bm,l as Km,m as Um,o as qm}from"./useRulePreview-DT4XJtYS.js";import{E as zt,f as Wl}from"./ErrorState-M_pFu8aN.js";import{f as Vl,a as Bt,b as Ql,c as qn,d as gt,t as Hm}from"./format-B6Elex-n.js";import{P as Vo,u as Yl,b as cn,M as Je}from"./move-targets-D4Fi-JcC.js";import{F as Ya,a as Wm,M as Gl}from"./move-mailbox-picker-D8AYTyKZ.js";import{C as cr}from"./circle-check-D0TxZacD.js";import{C as Ga}from"./ConfirmDialog-C6CU1OjE.js";import{u as Xl,a as Vm}from"./useLabels-CZy77x33.js";function Xs(e){if(Qm())e.focus({preventScroll:!0});else{let t=Ym(e);e.focus(),Gm(t)}}let Cn=null;function Qm(){if(Cn==null){Cn=!1;try{document.createElement("div").focus({get preventScroll(){return Cn=!0,!0}})}catch{}}return Cn}function Ym(e){let t=e.parentNode,s=[],r=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==r;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return r instanceof HTMLElement&&s.push({element:r,scrollTop:r.scrollTop,scrollLeft:r.scrollLeft}),s}function Gm(e){for(let{element:t,scrollTop:s,scrollLeft:r}of e)t.scrollTop=s,t.scrollLeft=r}const At=e=>e?.ownerDocument??document,Pt=e=>e&&"window"in e&&e.window===e?e:At(e).defaultView||window;function Xm(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function Jm(e){return Xm(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let Zm=!1;function Jl(){return Zm}function ht(e,t){if(!Jl())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:Jm(s)?s=s.host:s=s.parentNode}return!1}function Oe(e){if(Jl()&&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 eh=typeof Element<"u"&&"checkVisibility"in Element.prototype;function th(e){const t=Pt(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:r}=e.style,a=s!=="none"&&r!=="hidden"&&r!=="collapse";if(a){const{getComputedStyle:o}=Pt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function sh(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 Zl(e,t){return eh?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&th(e)&&sh(e,t)&&(!e.parentElement||Zl(e.parentElement,e))}const ec=["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"],nh=ec.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";ec.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function rh(e,t){return e.matches(nh)&&!ah(e)&&(t?.skipVisibilityCheck||Zl(e))}function ah(e){let t=e;for(;t!=null;){if(t instanceof Pt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Xa=typeof document<"u"?K.useLayoutEffect:()=>{};function oh(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function ih(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function lh(e){for(;e&&!rh(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Pt(e),s=t.document.activeElement;if(!s||s===e)return;let r=!1,a=d=>{(Oe(d)===s||r)&&d.stopImmediatePropagation()},o=d=>{(Oe(d)===s||r)&&(d.stopImmediatePropagation(),!e&&!r&&(r=!0,Xs(s),u()))},i=d=>{(Oe(d)===e||r)&&d.stopImmediatePropagation()},l=d=>{(Oe(d)===e||r)&&(d.stopImmediatePropagation(),r||(r=!0,Xs(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(f),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),r=!1},f=requestAnimationFrame(u);return u}function ur(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 Ja(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function Kt(e){let t=null;return()=>(t==null&&(t=e()),t)}const Hn=Kt(function(){return Ja(/^Mac/i)}),ch=Kt(function(){return Ja(/^iPhone/i)}),tc=Kt(function(){return Ja(/^iPad/i)||Hn()&&navigator.maxTouchPoints>1}),sc=Kt(function(){return ch()||tc()}),uh=Kt(function(){return ur(/AppleWebKit/i)&&!dh()}),dh=Kt(function(){return ur(/Chrome/i)}),nc=Kt(function(){return ur(/Android/i)}),fh=Kt(function(){return ur(/Firefox/i)});function mh(e){return e.pointerType===""&&e.isTrusted?!0:nc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function hh(e){return!nc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function Js(e,t,s=!0){let{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}=t;fh()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Hn()?r=!0:a=!0);let l=uh()&&Hn()&&!tc()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:r,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:r,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});Js.isOpening=s,Xs(e),e.dispatchEvent(l),Js.isOpening=!1}Js.isOpening=!1;let Mt=new Map,ca=new Set;function Qo(){if(typeof window>"u")return;function e(r){return"propertyName"in r}let t=r=>{let a=Oe(r);if(!e(r)||!a)return;let o=Mt.get(a);o||(o=new Set,Mt.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(r.propertyName)},s=r=>{let a=Oe(r);if(!e(r)||!a)return;let o=Mt.get(a);if(o&&(o.delete(r.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Mt.delete(a)),Mt.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"?Qo():document.addEventListener("DOMContentLoaded",Qo));function ph(){for(const[e]of Mt)"isConnected"in e&&!e.isConnected&&Mt.delete(e)}function gh(e){requestAnimationFrame(()=>{ph(),Mt.size===0?e():ca.add(e)})}function rc(...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 xh(e,t){if(e===t)return e;let s=ua.get(e);if(s)return s.forEach(a=>a.current=t),t;let r=ua.get(t);return r?(r.forEach(a=>a.current=e),e):t}function bh(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const r=e.map(a=>{const o=Yo(a,t);return s||=typeof o=="function",o});if(s)return()=>{r.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 Ts(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let r=e[s];for(let a in r){let o=t[a],i=r[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=rc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=jf(o,i):a==="id"&&o&&i?t.id=xh(o,i):a==="ref"&&o&&i?t.ref=bh(o,i):t[a]=i!==void 0?i:o}}return t}function vh(e,t){Xa(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const yh=K.useInsertionEffect??Xa;function Fr(e){const t=c.useRef(null);return yh(()=>{t.current=e},[e]),c.useCallback((...s)=>{const r=t.current;return r?.(...s)},[])}let gs="default",da="",_n=new WeakMap;function wh(e){if(sc()){if(gs==="default"){const t=At(e);da=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}gs="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";_n.set(e,e.style[t]),e.style[t]="none"}}function Go(e){if(sc()){if(gs!=="disabled")return;gs="restoring",setTimeout(()=>{gh(()=>{if(gs==="restoring"){const t=At(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=da||""),da="",gs="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&_n.has(e)){let t=_n.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),_n.delete(e)}}function Xo(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let $r=new WeakMap;function Sh(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return Xo(t);if($r.has(t))return $r.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),r=s&&s instanceof Pt(s).HTMLMetaElement&&(s.nonce||s.content)||Xo(t)||void 0;return r!==void 0&&$r.set(t,r),r}const ac=K.createContext({register:()=>{}});ac.displayName="PressResponderContext";function oc(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...f)=>{e.current.delete(i),i(...f)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),r=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>r,[r]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:r}}function jh(e){let t=c.useContext(ac);if(t){let{register:s,ref:r,...a}=t;e=Ts(a,e),s()}return vh(t,e.ref),e}class Nn{#s;constructor(t,s,r,a){this.#s=!0;const i=(a?.target??r.currentTarget)?.getBoundingClientRect();let l,u=0,f,d=null;r.clientX!=null&&r.clientY!=null&&(f=r.clientX,d=r.clientY),i&&(f!=null&&d!=null?(l=f-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=r.currentTarget,this.shiftKey=r.shiftKey,this.metaKey=r.metaKey,this.ctrlKey=r.ctrlKey,this.altKey=r.altKey,this.x=l,this.y=u,this.key=r.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const Jo=Symbol("linkClicked"),Zo="react-aria-pressable-style",ei="data-react-aria-pressable";function kh(e){let{onPress:t,onPressChange:s,onPressStart:r,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:f,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:m,ref:h,...g}=jh(e),[x,p]=c.useState(!1),b=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:v,removeAllGlobalListeners:S}=oc(),w=c.useCallback((j,F)=>{let D=b.current;if(l||D.didFirePressStart)return!1;let k=!0;if(D.isTriggeringEvent=!0,r){let L=new Nn("pressstart",F,j);r(L),k=L.shouldStopPropagation}return s&&s(!0),D.isTriggeringEvent=!1,D.didFirePressStart=!0,p(!0),k},[l,r,s]),y=c.useCallback((j,F,D=!0)=>{let k=b.current;if(!k.didFirePressStart)return!1;k.didFirePressStart=!1,k.isTriggeringEvent=!0;let L=!0;if(a){let T=new Nn("pressend",F,j);a(T),L=T.shouldStopPropagation}if(s&&s(!1),p(!1),t&&D&&!l){let T=new Nn("press",F,j);t(T),L&&=T.shouldStopPropagation}return k.isTriggeringEvent=!1,L},[l,a,s,t]),N=Fr(y),C=c.useCallback((j,F)=>{let D=b.current;if(l)return!1;if(o){D.isTriggeringEvent=!0;let k=new Nn("pressup",F,j);return o(k),D.isTriggeringEvent=!1,k.shouldStopPropagation}return!0},[l,o]),E=Fr(C),I=c.useCallback(j=>{let F=b.current;if(F.isPressed&&F.target){F.didFirePressStart&&F.pointerType!=null&&y(Qt(F.target,j),F.pointerType,!1),F.isPressed=!1,F.isOverTarget=!1,F.activePointerId=null,F.pointerType=null,S(),m||Go(F.target);for(let D of F.disposables)D();F.disposables=[]}},[m,S,y]),O=Fr(I);c.useEffect(()=>{l&&b.current.isPressed&&O({currentTarget:b.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let A=c.useCallback(j=>{d&&I(j)},[d,I]),M=c.useCallback(j=>{l||i?.(j)},[l,i]),P=c.useCallback((j,F)=>{if(!l&&i){let D=new MouseEvent("click",j);ih(D,F),i(oh(D))}},[l,i]),R=c.useMemo(()=>{let j=b.current,F={onKeyDown(k){if(_r(k.nativeEvent,k.currentTarget)&&ht(k.currentTarget,Oe(k))){ti(Oe(k),k.key)&&k.preventDefault();let L=!0;!j.isPressed&&!k.repeat&&(j.target=k.currentTarget,j.isPressed=!0,j.pointerType="keyboard",L=w(k,"keyboard"));let T=k.currentTarget,$=V=>{_r(V,T)&&!V.repeat&&ht(T,Oe(V))&&j.target&&E(Qt(j.target,V),"keyboard")};v(At(k.currentTarget),"keyup",rc($,D),!0),L&&k.stopPropagation(),k.metaKey&&Hn()&&j.metaKeyEvents?.set(k.key,k.nativeEvent)}else k.key==="Meta"&&(j.metaKeyEvents=new Map)},onClick(k){if(!(k&&!ht(k.currentTarget,Oe(k)))&&k&&k.button===0&&!j.isTriggeringEvent&&!Js.isOpening){let L=!0;if(l&&k.preventDefault(),!j.ignoreEmulatedMouseEvents&&!j.isPressed&&(j.pointerType==="virtual"||mh(k.nativeEvent))){let T=w(k,"virtual"),$=E(k,"virtual"),V=N(k,"virtual");M(k),L=T&&$&&V}else if(j.isPressed&&j.pointerType!=="keyboard"){let T=j.pointerType||k.nativeEvent.pointerType||"virtual",$=E(Qt(k.currentTarget,k),T),V=N(Qt(k.currentTarget,k),T,!0);L=$&&V,j.isOverTarget=!1,M(k),O(k)}j.ignoreEmulatedMouseEvents=!1,L&&k.stopPropagation()}}},D=k=>{if(j.isPressed&&j.target&&_r(k,j.target)){ti(Oe(k),k.key)&&k.preventDefault();let L=Oe(k),T=ht(j.target,L);N(Qt(j.target,k),"keyboard",T),T&&P(k,j.target),S(),k.key!=="Enter"&&Za(j.target)&&ht(j.target,L)&&!k[Jo]&&(k[Jo]=!0,Js(j.target,k,!1)),j.isPressed=!1,j.metaKeyEvents?.delete(k.key)}else if(k.key==="Meta"&&j.metaKeyEvents?.size){let L=j.metaKeyEvents;j.metaKeyEvents=void 0;for(let T of L.values())j.target?.dispatchEvent(new KeyboardEvent("keyup",T))}};if(typeof PointerEvent<"u"){F.onPointerDown=T=>{if(T.button!==0||!ht(T.currentTarget,Oe(T)))return;if(hh(T.nativeEvent)){j.pointerType="virtual";return}j.pointerType=T.pointerType;let $=!0;if(!j.isPressed){j.isPressed=!0,j.isOverTarget=!0,j.activePointerId=T.pointerId,j.target=T.currentTarget,m||wh(j.target),$=w(T,j.pointerType);let V=Oe(T);"releasePointerCapture"in V&&("hasPointerCapture"in V?V.hasPointerCapture(T.pointerId)&&V.releasePointerCapture(T.pointerId):V.releasePointerCapture(T.pointerId)),v(At(T.currentTarget),"pointerup",k,!1),v(At(T.currentTarget),"pointercancel",L,!1)}$&&T.stopPropagation()},F.onMouseDown=T=>{if(ht(T.currentTarget,Oe(T))&&T.button===0){if(f){let $=lh(T.target);$&&j.disposables.push($)}T.stopPropagation()}},F.onPointerUp=T=>{!ht(T.currentTarget,Oe(T))||j.pointerType==="virtual"||T.button===0&&!j.isPressed&&E(T,j.pointerType||T.pointerType)},F.onPointerEnter=T=>{T.pointerId===j.activePointerId&&j.target&&!j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!0,w(Qt(j.target,T),j.pointerType))},F.onPointerLeave=T=>{T.pointerId===j.activePointerId&&j.target&&j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!1,N(Qt(j.target,T),j.pointerType,!1),A(T))};let k=T=>{if(T.pointerId===j.activePointerId&&j.isPressed&&T.button===0&&j.target){if(ht(j.target,Oe(T))&&j.pointerType!=null){let $=!1,V=setTimeout(()=>{j.isPressed&&j.target instanceof HTMLElement&&($?O(T):(Xs(j.target),j.target.click()))},80);v(T.currentTarget,"click",()=>$=!0,!0),j.disposables.push(()=>clearTimeout(V))}else O(T);j.isOverTarget=!1}},L=T=>{O(T)};F.onDragStart=T=>{ht(T.currentTarget,Oe(T))&&O(T)}}return F},[v,l,f,S,m,A,w,M,P]);return c.useEffect(()=>{if(!h)return;const j=At(h.current);if(!j||!j.head||j.getElementById(Zo))return;const F=j.createElement("style");F.id=Zo;let D=Sh(j);D&&(F.nonce=D),F.textContent=`
3
+ @layer {
4
+ [${ei}] {
5
+ touch-action: pan-x pan-y pinch-zoom;
6
+ }
7
+ }
8
+ `.trim(),j.head.prepend(F)},[h]),c.useEffect(()=>{let j=b.current;return()=>{m||Go(j.target??void 0);for(let F of j.disposables)F();j.disposables=[]}},[m]),{isPressed:u||x,pressProps:Ts(g,R,{[ei]:!0})}}function Za(e){return e.tagName==="A"&&e.hasAttribute("href")}function _r(e,t){const{key:s,code:r}=e,a=t,o=a.getAttribute("role");return(s==="Enter"||s===" "||s==="Spacebar"||r==="Space")&&!(a instanceof Pt(a).HTMLInputElement&&!ic(a,s)||a instanceof Pt(a).HTMLTextAreaElement||a.isContentEditable)&&!((o==="link"||!o&&Za(a))&&s!=="Enter")}function Qt(e,t){let s=t.clientX,r=t.clientY;return{currentTarget:e,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,altKey:t.altKey,clientX:s,clientY:r,key:t.key}}function Ch(e){return e instanceof HTMLInputElement?!1:e instanceof HTMLButtonElement?e.type!=="submit"&&e.type!=="reset":!Za(e)}function ti(e,t){return e instanceof HTMLInputElement?!ic(e,t):Ch(e)}const Nh=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function ic(e,t){return e.type==="checkbox"||e.type==="radio"?t===" ":Nh.has(e.type)}let Eh=0;const zr=new Map;function Ih(e){let[t,s]=c.useState();return Xa(()=>{if(!e)return;let r=zr.get(e);if(r)s(r.element.id);else{let a=`react-aria-description-${Eh++}`;s(a);let o=document.createElement("div");o.id=a,o.style.display="none",o.textContent=e,document.body.appendChild(o),r={refCount:0,element:o},zr.set(e,r)}return r.refCount++,()=>{r&&--r.refCount===0&&(r.element.remove(),zr.delete(e))}},[e]),{"aria-describedby":e?t:void 0}}const Th=500;function Rh(e){let{isDisabled:t,onLongPressStart:s,onLongPressEnd:r,onLongPress:a,threshold:o=Th,accessibilityDescription:i}=e;const l=c.useRef(void 0);let{addGlobalListener:u,removeGlobalListener:f}=oc(),{pressProps:d}=kh({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})),At(h.target).activeElement!==h.target&&Xs(h.target),a&&a({...h,type:"longpress"}),l.current=void 0},o),h.pointerType==="touch")){let g=p=>{p.preventDefault()},x=Pt(h.target);u(h.target,"contextmenu",g,{once:!0}),u(x,"pointerup",()=>{setTimeout(()=>{f(h.target,"contextmenu",g)},30)},{once:!0})}},onPressEnd(h){l.current&&clearTimeout(l.current),r&&(h.pointerType==="mouse"||h.pointerType==="touch")&&r({...h,type:"longpressend"})}}),m=Ih(a&&!t?i:void 0);return{longPressProps:Ts(d,m)}}const lc=he("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);const Mh=he("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);const Ah=he("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const dr=he("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=he("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);const cc=he("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 Dh=he("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 si=he("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 Ns=he("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const Ph=he("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);const uc=he("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 dc=he("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);const fc=he("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 mc=he("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 hc=he("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 Lh=he("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 Rs=he("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 Fh=he("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 $h=he("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const fr=he("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 _h=he("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);const pc=he("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 gc=he("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 xc=he("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 eo=he("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 Ms=he("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 zh=he("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 Bh=he("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 Kh=he("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 Uh=he("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"}]]),qh=({address:e,showTrustedBadge:t=!1})=>{const s=t?n.jsx(dr,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}):null;return e.displayName?n.jsxs("span",{children:[n.jsx("span",{className:"text-fg",children:e.displayName}),n.jsxs("span",{className:"text-fg-muted",children:[" ","<",e.normalizedEmail,">"]}),s]}):n.jsxs("span",{className:"text-fg",children:[e.normalizedEmail,s]})},Hh=({label:e,addresses:t,showTrustedBadge:s=!1})=>{const[r,a]=c.useState(!1);if(t.length===0)return null;const o=t.length>3,i=l=>{const u=s&&l.flags?.trusted?.value===!0;return n.jsx(qh,{address:l,showTrustedBadge:u})};return n.jsxs("div",{className:"flex gap-2 text-sm",children:[n.jsxs("span",{className:"text-fg-muted shrink-0 w-12",children:[e,":"]}),n.jsx("div",{className:"flex-1 min-w-0",children:r?n.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((l,u)=>n.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))}):n.jsx("div",{className:"truncate",children:t.map((l,u)=>n.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))})}),o&&n.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),a(!r)},className:"shrink-0 text-fg-muted hover:text-fg transition-colors","aria-label":r?"Collapse":"Expand",children:r?n.jsx(Dt,{className:"h-4 w-4"}):n.jsx(Ns,{className:"h-4 w-4"})})]})},Wh=({email:e,displayName:t,onRemove:s,className:r})=>n.jsxs("span",{className:H("inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-accent-2-soft text-sm max-w-[200px]",r),children:[n.jsx("span",{className:"truncate",children:t||e}),n.jsx("button",{type:"button",onClick:s,className:"shrink-0 p-0.5 rounded-full hover:bg-fg-muted/20 transition-colors","aria-label":`Remove ${e}`,children:n.jsx(Ze,{className:"size-3"})})]}),Vh={unknown:{label:"Unknown sender",tone:"neutral"},wellknown:{label:"Known sender",tone:"positive"},vip:{label:"VIP",tone:"accent"}};function ls({label:e,children:t,className:s}){return n.jsxs("section",{className:H("border-b border-line px-row-inset py-3",s),children:[n.jsx("h3",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),n.jsx("div",{className:"mt-2",children:t})]})}function Qh({sender:e}){const t=Vh[e.trust],s=e.inboundCount==null?null:(e.replyCount??0)>0?`${e.inboundCount} received · you replied ${e.replyCount}×`:`${e.inboundCount} received · you've never replied`;return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(bt,{name:e.name,email:e.email,size:"md"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"truncate text-sm font-semibold text-fg",children:e.name}),n.jsx("div",{className:"truncate text-2xs text-fg-subtle",children:e.email})]})]}),n.jsx("div",{className:"mt-2 flex items-center gap-2",children:e.addressUnverified?n.jsx(pt,{tone:"danger",dot:!0,children:"Address couldn't be verified"}):n.jsx(pt,{tone:t.tone,dot:!0,children:t.label})}),n.jsxs("p",{className:"mt-2 text-xs text-fg-muted",children:["First seen ",e.firstSeenLabel,s?` · ${s}`:""]})]})}function Yh({auth:e,onShowSimilar:t}){if(e.verdict==="aligned")return n.jsxs("div",{className:"flex items-start gap-2 text-xs text-fg-muted",children:[n.jsx(ln,{className:"mt-0.5 size-3.5 shrink-0 text-positive"}),n.jsx("span",{children:e.summary})]});if(e.verdict==="caution")return n.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-warning/10 p-3 text-warning",children:[n.jsx(zh,{className:"mt-0.5 size-4 shrink-0"}),n.jsx("p",{className:"text-xs leading-relaxed",children:e.summary})]});const s=e.addressUnreadable?"This sender can't be verified":"This message may be impersonating someone";return n.jsxs("div",{className:"rounded-md bg-danger-soft p-3",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(Ms,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"text-sm font-semibold text-danger",children:s}),n.jsx("p",{className:"mt-1 text-xs leading-relaxed text-fg",children:e.summary}),!e.addressUnreadable&&e.dkimDomain&&n.jsxs("p",{className:"mt-1 text-2xs text-fg-muted",children:["Sent from"," ",n.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.dkimDomain}),", claims to be"," ",n.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.fromDomain})]})]})]}),e.similarCount!=null&&e.similarCount>0&&n.jsxs(W,{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 cs({icon:e,label:t,active:s,danger:r,onClick:a}){const o=a===void 0;return n.jsxs("button",{type:"button",onClick:a,disabled:o,className:H("flex items-center gap-2 rounded-md border px-2 py-1 text-xs transition-colors",s?"border-accent-2 bg-accent-2-soft text-accent-2":"border-line text-fg-muted hover:border-line-strong hover:text-fg",r&&!s&&"text-danger hover:bg-danger-soft",o&&"cursor-not-allowed opacity-50 hover:border-line"),children:[e,t]})}const Gh={sender:"matched: sender",recipient:"matched: recipient",subject:"matched: subject",attachment:"matched: attachment",body:"matched: body",entities:"matched: entities"};function bc({data:e,onClose:t,onShowSimilar:s,actions:r,similarState:a="ready",similarLinkComponent:o,className:i,hideCloseButton:l=!1}){const{sender:u,authenticity:f,category:d,flags:m={},similar:h}=e,g=f.verdict==="mismatch";return n.jsxs("aside",{className:H("flex w-76 shrink-0 flex-col overflow-y-auto border-l border-line bg-surface",i),children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center justify-between border-b border-line px-row-inset",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"}),!l&&n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Ze,{className:"size-3.5"}),onClick:t,"aria-label":"Collapse intelligence sidebar"})]}),n.jsx(ls,{label:"Sender",children:n.jsx(Qh,{sender:u})}),n.jsx(ls,{label:"Authenticity",children:n.jsx(Yh,{auth:f,onShowSimilar:s})}),n.jsx(ls,{label:"Category",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(pt,{tone:g?"danger":"neutral",children:d.value}),d.overridden&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"your override"}),n.jsx("button",{type:"button",className:H("ml-auto text-2xs text-accent hover:underline",!r?.onReclassify&&"cursor-not-allowed opacity-50 hover:no-underline"),disabled:!r?.onReclassify,onClick:r?.onReclassify,children:"reclassify"})]})}),n.jsx(ls,{label:"Quick actions",children:n.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[n.jsx(cs,{icon:n.jsx(Ft,{className:"size-3.5"}),label:"VIP",active:m.vip,onClick:r?.onToggleVip}),n.jsx(cs,{icon:n.jsx(cc,{className:"size-3.5"}),label:"Mute",active:m.muted,onClick:r?.onToggleMute}),n.jsx(cs,{icon:n.jsx(Oh,{className:"size-3.5"}),label:"Block",active:m.blocked,danger:!0,onClick:r?.onToggleBlock}),n.jsx(cs,{icon:n.jsx(Fh,{className:"size-3.5"}),label:"Unsubscribe",active:m.unsubscribed,onClick:r?.onToggleUnsubscribe}),r?.onNotSpam&&n.jsx(cs,{icon:n.jsx(Lh,{className:"size-3.5"}),label:"Not spam",onClick:r.onNotSpam}),r?.onMarkSpam&&n.jsx(cs,{icon:n.jsx(Bh,{className:"size-3.5"}),label:"Mark spam",danger:!0,onClick:r.onMarkSpam})]})}),(a!=="ready"||h.length>0)&&n.jsx(ls,{label:"Similar messages",children:a==="loading"?n.jsx("div",{className:"animate-pulse space-y-2",children:Array.from({length:3}).map((x,p)=>n.jsxs("div",{className:"space-y-1",children:[n.jsx("div",{className:"h-3 w-3/4 rounded bg-surface-sunken"}),n.jsx("div",{className:"h-2.5 w-1/2 rounded bg-surface-sunken"})]},p))}):a==="error"?n.jsx("p",{className:"text-xs text-fg-subtle",children:"Similarity search unavailable"}):n.jsx("ul",{className:"-mx-1 space-y-1",children:h.map(x=>{const p="block w-full rounded-md px-1 py-1 text-left hover:bg-surface-sunken",b=`Open message from ${x.fromName||"unknown sender"}: ${x.subject}`,v=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[n.jsx("span",{className:"truncate text-xs font-medium text-fg",children:x.fromName}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:x.timeLabel})]}),n.jsx("div",{className:"truncate text-xs text-fg-muted",children:x.subject}),n.jsx("span",{className:"mt-1 inline-block rounded-full bg-surface-sunken px-1.5 py-px text-2xs text-fg-subtle",children:Gh[x.matched]})]});return n.jsx("li",{children:o?o({mailboxId:x.mailboxId,messageId:x.id,className:p,ariaLabel:b,children:v}):n.jsx("div",{className:p,children:v})},x.id)})})}),n.jsx(ls,{label:"Coming soon",className:"border-b-0 opacity-70",children:n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[n.jsx(xt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Suggested actions"}),n.jsx("div",{className:"text-2xs text-fg-subtle",children:'"Create a filter for messages like this" — on-device model'})]})]}),n.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[n.jsx(xt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Thread summary"}),n.jsx("div",{className:"text-2xs text-fg-subtle",children:"One-paragraph digest — Bedrock"})]})]})]})})]})}const Xh=[{keys:["j","k"],label:"navigate"},{keys:["m"],label:"mute"},{keys:["?"],label:"all shortcuts"}];function vc({hints:e=Xh,className:t}){return n.jsx("footer",{className:H("flex items-center gap-2 border-t border-line px-row-inset py-1 text-2xs text-fg-subtle",t),children:e.map(s=>n.jsx(Jh,{hint:s},s.label))})}function Jh({hint:e}){return n.jsxs("span",{className:"flex items-center gap-1",children:[e.keys.map(t=>n.jsx(vs,{children:t},t)),n.jsx("span",{children:e.label})]})}function Zh(){return n.jsx("div",{className:"space-y-0",role:"status","aria-busy":"true","aria-label":"Loading messages",children:Array.from({length:8}).map((e,t)=>n.jsxs("div",{className:"animate-pulse border-b border-line px-3 py-2",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[n.jsx("div",{className:"h-4 w-32 rounded bg-surface-sunken"}),n.jsx("div",{className:"h-3 w-16 rounded bg-surface-sunken"})]}),n.jsx("div",{className:"mb-2 h-4 w-48 rounded bg-surface-sunken"}),n.jsx("div",{className:"h-3 w-full rounded bg-surface-sunken"})]},t))})}function ep({filter:e,scopeLabel:t,searchQuery:s}){const r=s?.trim();return e?n.jsxs(ni,{children:[n.jsx("p",{className:"font-medium text-fg",children:np(e.label,t,r)}),n.jsx("p",{className:"mt-1 text-sm text-fg-muted",children:tp[e.reach]}),n.jsx(W,{variant:"secondary",size:"sm",className:"mt-4",onClick:e.onClear,children:"Clear filter"})]}):n.jsx(ni,{children:n.jsx("p",{className:"text-fg-muted",children:sp(r,t)})})}const tp={"whole-folder":"Every message in this folder was checked.","loaded-pages":"Only the messages loaded so far were checked."};function sp(e,t){return e?"No messages match your search":t?`No messages in ${t}`:"No messages in this mailbox"}function np(e,t,s){return s?`No results for “${s}” in ${e}`:t?`No ${e} mail in ${t}`:`No ${e} mail`}function ni({children:e}){return n.jsx("div",{className:"flex h-full flex-1 items-center justify-center",children:n.jsx("div",{className:"flex max-w-sm flex-col items-center justify-center p-8 text-center",children:e})})}function rp(){return n.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-sm text-fg-muted",role:"status","aria-live":"polite",children:[n.jsx(et,{className:"size-4 animate-spin","aria-hidden":"true"}),n.jsx("span",{children:"Loading more…"})]})}function ap({message:e="Something went wrong loading this mailbox.",onRetry:t,onReport:s}){return n.jsx("div",{className:"flex h-full flex-1 items-center justify-center p-4",children:n.jsxs("div",{role:"alert",className:"flex max-w-sm flex-col items-center justify-center gap-3 text-center",children:[n.jsx(ts,{className:"size-8 text-danger","aria-hidden":"true"}),n.jsxs("div",{children:[n.jsx("p",{className:"font-medium text-danger",children:"Couldn't load messages"}),n.jsx("p",{className:"mt-1 break-words text-sm text-fg-muted",children:e})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[t&&n.jsx(W,{variant:"secondary",size:"sm",onClick:t,children:"Retry"}),s&&n.jsx(W,{variant:"ghost",size:"sm",onClick:s,children:"Report a problem"})]})]})})}const yc="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",wc=({active:e,focused:t})=>H("relative flex h-8 w-full items-center gap-2 px-row-inset text-left",yc,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"),As=({active:e,focused:t})=>H("relative flex w-full items-start gap-3 py-2 pl-5 pr-row-inset text-left transition-colors",yc,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 Sc({thread:e}){const t=!e.isRead;return n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex w-4 shrink-0 items-center justify-center",children:e.suspicious?n.jsx(Ms,{className:"size-3.5 text-danger"}):e.starred?n.jsx(Ft,{className:"size-3 fill-warning text-warning"}):t?n.jsx("span",{className:"size-1.5 rounded-full bg-accent"}):null}),n.jsx("span",{className:H("w-36 shrink-0 truncate text-xs",t?"font-semibold text-fg":"text-fg-muted"),children:e.fromName}),n.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs",children:[n.jsx("span",{className:H(t?"font-medium text-fg":"text-fg-muted"),children:e.subject}),n.jsxs("span",{className:"text-fg-subtle",children:[" — ",e.snippet]})]}),e.hasAttachment&&n.jsx(fr,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"w-11 shrink-0 text-right text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]})}function ri(e,t){const s=t?.trim();if(!s)return e;const r=e.toLowerCase(),a=s.toLowerCase(),o=[];let i=0,l=r.indexOf(a,i),u=0;for(;l!==-1;)l>i&&o.push(e.slice(i,l)),o.push(n.jsx("mark",{className:"bg-transparent font-semibold text-fg",children:e.slice(l,l+a.length)},u++)),i=l+a.length,l=r.indexOf(a,i);return i<e.length&&o.push(e.slice(i)),o}function Zs({thread:e,badge:t,highlightQuery:s}){const r=!e.isRead;return n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsxs("span",{className:"flex items-baseline justify-between gap-2",children:[n.jsxs("span",{className:H("flex min-w-0 items-center gap-1.5 truncate text-sm",r?"font-semibold text-fg":"font-medium text-fg-muted"),children:[e.trust==="vip"&&n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-accent-2"}),n.jsx("span",{className:"truncate",children:e.fromName}),e.messageCount!=null&&e.messageCount>1&&n.jsx("span",{className:"shrink-0 text-2xs font-normal text-fg-subtle",children:e.messageCount})]}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]}),n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:H("truncate text-sm",r?"text-fg":"text-fg-muted"),children:ri(e.subject,s)}),e.suspicious&&n.jsx(Ms,{className:"size-3.5 shrink-0 text-danger"}),e.starred&&n.jsx(Ft,{className:"size-3 shrink-0 fill-warning text-warning"}),e.hasAttachment&&n.jsx(fr,{className:"size-3 shrink-0 text-fg-subtle"})]}),n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"line-clamp-1 min-w-0 flex-1 text-xs text-fg-subtle",children:ri(e.snippet,s)}),e.category&&e.category!=="personal"&&n.jsx(pt,{tone:kf[e.category],className:"shrink-0",children:e.category}),e.labels?.map(a=>n.jsx(Cf,{label:a,className:"max-w-20"},a.labelId)),t]})]})}function op({thread:e,selection:t}){if(!t)return n.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"sm"});const{checked:s,alwaysVisible:r}=t;return n.jsxs("span",{className:"relative size-7 shrink-0",children:[n.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"sm",className:H("absolute inset-0 transition-opacity sm:group-hover:opacity-0",(s||r)&&"opacity-0")}),n.jsx("span",{role:"button",tabIndex:-1,onClick:t.onToggle,onKeyDown:a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),a.stopPropagation(),t.onToggle(a))},className:H("absolute inset-0 size-7 items-center justify-center rounded-full border transition-opacity",r?"flex":"hidden sm:flex",s?"bg-accent border-accent text-accent-fg opacity-100":r?"border-fg-subtle/40 bg-canvas opacity-100":"border-fg-subtle/40 bg-canvas opacity-0 group-hover:opacity-100"),"aria-label":s?"Deselect message":"Select message",children:s&&n.jsx(nn,{className:"size-3"})})]})}function to({thread:e,selection:t,badge:s,highlightQuery:r}){const a=!e.isRead;return n.jsxs(n.Fragment,{children:[a&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx(op,{thread:e,selection:t}),n.jsx(Zs,{thread:e,badge:s,highlightQuery:r})]})}function ip({thread:e,active:t,focused:s,onClick:r}){return n.jsx("button",{type:"button",...Na,onClick:r,className:wc({active:t,focused:s}),children:n.jsx(Sc,{thread:e})})}function lp({thread:e,active:t,focused:s,selection:r,onClick:a}){return n.jsx("button",{type:"button",...Na,onClick:a,className:H("group",As({active:t,focused:s})),children:n.jsx(to,{thread:e,selection:r})})}const cp="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",ai="pointer-events-none absolute inset-0 m-auto size-3.5 text-accent-fg";function un({label:e,description:t,indeterminate:s=!1,checked:r,onChange:a,className:o,...i}){const l=c.useRef(null);c.useEffect(()=>{l.current&&(l.current.indeterminate=s)},[s]);const u=n.jsxs("span",{className:"relative inline-flex",children:[n.jsx("input",{ref:l,type:"checkbox",checked:r,onChange:a,className:cp,...i}),n.jsx(nn,{className:H(ai,"hidden peer-checked:block"),"aria-hidden":!0}),n.jsx($h,{className:H(ai,"hidden peer-indeterminate:block"),"aria-hidden":!0})]});return e===void 0&&t===void 0?n.jsx("span",{className:o,children:u}):n.jsxs("label",{className:H("flex min-h-11 cursor-pointer items-center gap-3 text-left",o),children:[u,n.jsxs("span",{className:"flex min-w-0 flex-col",children:[e!==void 0&&n.jsx("span",{className:"text-sm text-fg",children:e}),t!==void 0&&n.jsx("span",{className:"text-xs text-fg-subtle",children:t})]})]})}const up={info:"bg-accent-2",success:"bg-positive",warning:"bg-warning",danger:"bg-danger"};function so({value:e,max:t,tone:s="info",indeterminate:r=!1,className:a}){const o=r?100:t<=0?0:Math.min(100,Math.max(0,e/t*100));return n.jsx("div",{role:"progressbar","aria-valuenow":r?void 0:e,"aria-valuemin":r?void 0:0,"aria-valuemax":r?void 0:t,className:H("h-1.5 w-full overflow-hidden rounded-full bg-surface-sunken",a),children:n.jsx("div",{className:H("h-full rounded-full transition-[width] duration-300 ease-out",up[s],r&&"w-1/3 animate-pulse"),style:r?void 0:{width:`${o}%`}})})}const oi=e=>e.toLocaleString();function dp({count:e,onCancel:t,onMarkRead:s,onDelete:r,moveSlot:a,isBusy:o=!1,isCounting:i=!1,selectAll:l,statusLabel:u,progress:f,notice:d}){const m=l?.checked?`All ${oi(e)} loaded selected`:`${oi(e)} ${e===1?"message":"messages"} selected`;return n.jsxs("header",{className:"flex shrink-0 flex-col border-b border-line bg-surface-sunken",children:[n.jsxs("div",{className:"flex h-pane-header items-center gap-2 px-row-inset",children:[n.jsx(W,{variant:"ghost",size:"touch",icon:n.jsx(Ze,{className:"size-4"}),onClick:t,"aria-label":"Cancel selection",className:"-ml-2 shrink-0"}),l&&n.jsx("label",{className:"-ml-1.5 flex size-11 shrink-0 cursor-pointer items-center justify-center",children:n.jsx(un,{"aria-label":"Select all",checked:l.checked,indeterminate:l.indeterminate,onChange:l.onChange})}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-fg",role:"status","aria-live":"polite",children:u??m}),s&&!o&&n.jsx(W,{variant:"ghost",size:"touch",icon:n.jsx(Rs,{className:"size-4"}),onClick:s,"aria-label":"Mark as read",className:"shrink-0"}),a,!i&&n.jsx(W,{variant:"ghost",size:"touch",icon:o?n.jsx(et,{className:"size-4 animate-spin"}):n.jsx(ct,{className:"size-4 text-danger"}),onClick:o?void 0:r,"aria-label":"Move selected messages to Trash","aria-busy":o||void 0,className:"ml-4 shrink-0"})]}),f&&n.jsx("div",{className:"px-row-inset pb-2",children:n.jsx(so,{value:f.value,max:f.max,tone:f.tone})}),d&&n.jsx(ss,{tone:d.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-row-inset mb-2",children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.text&&n.jsx("span",{children:d.text}),d.action&&n.jsx(W,{variant:"ghost",size:"md",onClick:d.action.onClick,className:"-my-1 min-h-11 shrink-0",children:d.action.label})]})})]})}let ys;const fp=5e3;function jc(e){e.preventDefault(),Wn()}function Wn(){ys!==void 0&&(clearTimeout(ys),ys=void 0,document.removeEventListener("contextmenu",jc,!0),document.removeEventListener("pointerup",Wn,!0))}function mp(){ys===void 0?(document.addEventListener("contextmenu",jc,!0),document.addEventListener("pointerup",Wn,!0)):clearTimeout(ys),ys=setTimeout(Wn,fp)}function kc({onLongPress:e,isDisabled:t,delayMs:s=500,accessibilityDescription:r}){const{longPressProps:a}=Rh({isDisabled:t,threshold:s,accessibilityDescription:r,onLongPress:e}),o=c.useCallback(i=>{i.pointerType!=="touch"&&i.pointerType!=="pen"||mp()},[]);return{longPressProps:Ts(a,{onPointerDown:o})}}const Zt=72,ii=10,hp=Zt/2,li="__swipeableRowAxisCancel";function ci(e){return e==="leading"?Zt:e==="trailing"?-Zt:0}function pp(e){return e>=Zt/2?"leading":e<=-Zt/2?"trailing":"none"}function Cc({thread:e,selectionMode:t,checked:s,active:r,peek:a,onPeek:o,onToggleCheck:i,onLongPress:l,onOpen:u,onAct:f,linkComponent:d}){const m=c.useRef(null),[h,g]=c.useState(null),{longPressProps:x}=kc({onLongPress:l,isDisabled:t,accessibilityDescription:"Select message"}),p=R=>{const j=new PointerEvent("pointercancel",{bubbles:!0});j[li]=!0,R.currentTarget.dispatchEvent(j)},y=Ts(x,{onPointerDown:R=>{m.current={startX:R.clientX,startY:R.clientY,axis:"none",escaped:!1}},onPointerMove:R=>{if(t)return;const j=m.current;if(!j)return;const F=R.clientX-j.startX,D=R.clientY-j.startY;if(j.axis==="none"&&(Math.abs(D)>ii&&Math.abs(D)>Math.abs(F)?j.axis="vertical":Math.abs(F)>ii&&Math.abs(F)>Math.abs(D)&&(j.axis="horizontal",R.currentTarget.setPointerCapture(R.pointerId))),j.axis==="none")return;const k=j.axis==="horizontal"?Math.abs(F):Math.abs(D);if(!j.escaped&&k>hp&&(j.escaped=!0,p(R)),j.axis!=="horizontal")return;const L=ci(a),T=Math.max(-Zt,Math.min(Zt,L+F));g(T)},onPointerUp:R=>{const j=m.current;m.current=null;const F=h;if(g(null),!!j){if(j.axis!=="none"&&!j.escaped&&p(R),j.axis==="horizontal"){F!==null&&o(pp(F));return}if(j.axis!=="vertical"){if(t){i();return}if(a!=="none"){o("none");return}d||u()}}},onPointerCancel:R=>{R.nativeEvent[li]||(m.current=null,g(null))}}),N=R=>{a!=="none"&&R.preventDefault()},C=h??ci(a),E=C>0?"leading":C<0?"trailing":"none",I=H("relative touch-pan-y bg-surface","select-none [-webkit-touch-callout:none]",As({active:s||r})),O={transform:C!==0?`translateX(${C}px)`:void 0,transition:h===null?"transform 150ms ease":"none",minHeight:44},A=!e.isRead,M=R=>R.stopPropagation(),P=t?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:H("inline-flex size-7 shrink-0 items-center justify-center rounded-full border",s?"border-accent bg-accent text-accent-fg":"border-line-strong bg-canvas"),children:s&&n.jsx(nn,{className:"size-3.5"})}),n.jsx(Zs,{thread:e})]}):n.jsxs(n.Fragment,{children:[A&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx("button",{type:"button",role:"checkbox","aria-checked":s,"aria-label":`Select message from ${e.fromName}`,onPointerDown:M,onPointerMove:M,onPointerUp:M,onClick:R=>{R.preventDefault(),R.stopPropagation(),l()},className:"-m-2 inline-flex size-11 shrink-0 items-center justify-center rounded-full",children:n.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"sm"})}),n.jsx(Zs,{thread:e})]});return n.jsxs("div",{className:"relative overflow-hidden",children:[E==="leading"&&n.jsx("button",{type:"button",onClick:()=>f("leading"),"aria-label":e.isRead?"Mark as unread":"Mark as read",className:"absolute inset-y-0 left-0 flex items-center justify-start bg-accent-2 px-6 text-accent-fg",children:e.isRead?n.jsx(zl,{className:"size-6"}):n.jsx(Rs,{className:"size-6"})}),E==="trailing"&&n.jsx("button",{type:"button",onClick:()=>f("trailing"),"aria-label":"Delete message",className:"absolute inset-y-0 right-0 flex items-center justify-end bg-danger px-6 text-canvas",children:n.jsx(ct,{className:"size-6"})}),d&&!t?d({...y,className:I,style:O,onOpenClick:N,children:P}):n.jsx("button",{type:"button",role:t?"checkbox":void 0,"aria-checked":t?s:void 0,...y,className:I,style:O,children:P})]})}function gp({sections:e,selectedThreadId:t,selectionMode:s,checkedIds:r,initialPeek:a,onToggleCheck:o,onEnterSelection:i,onOpenThread:l,onRefresh:u,refreshing:f,busy:d=!1}){const[m,h]=c.useState(()=>e.flatMap(b=>b.threads)),[g,x]=c.useState(a&&a!=="none"&&m[1]?{id:m[1].id,side:a}:null),p=(b,v)=>{h(v==="trailing"?S=>S.filter(w=>w.id!==b):S=>S.map(w=>w.id===b?{...w,isRead:!w.isRead}:w)),x(null)};return n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[f&&n.jsxs("div",{className:"flex items-center justify-center gap-2 border-b border-line py-3 text-fg-muted",children:[n.jsx(pc,{className:"size-4 animate-spin"}),n.jsx("span",{className:"text-xs",children:"Checking for new mail…"})]}),n.jsx("div",{className:"divide-y divide-line",children:m.map(b=>n.jsx("div",{className:d?"pointer-events-none opacity-50":void 0,children:n.jsx(Cc,{thread:b,selectionMode:s,checked:r.has(b.id),active:b.id===t,peek:g?.id===b.id?g.side:"none",onPeek:v=>x(v==="none"?null:{id:b.id,side:v}),onToggleCheck:()=>o(b.id),onLongPress:()=>i(b.id),onOpen:()=>l(b.id),onAct:v=>p(b.id,v)})},b.id))}),!s&&!f&&!d&&n.jsx("button",{type:"button",onClick:u,className:"w-full border-t border-line py-2 text-center text-2xs text-fg-subtle transition-colors hover:bg-surface-sunken",children:"Pull to refresh"})]})}function Nc({listTitle:e,listMeta:t,sections:s,briefFilters:r,flatList:a,listState:o="ready",searchQuery:i,listFilter:l,listScopeLabel:u,errorMessage:f,onRetry:d,onReportError:m,briefCategory:h,selectedThreadId:g,density:x="comfortable",onSelectThread:p,onSelectBriefCategory:b,onOpenNav:v,isDesktop:S,initialTouchState:w,selectionBar:y,selectionSheet:N,listBody:C,hideHeader:E=!1}){const I=x==="compact"?ip:lp,O=c.useRef(null);er({containerRef:O,itemSelector:Ea});const A=!S&&!r&&o==="ready",M=s.flatMap(q=>q.threads),[P,R]=c.useState(w==="selection"),[j,F]=c.useState(()=>w==="selection"?new Set(M.slice(0,2).map(q=>q.id)):new Set),[D,k]=c.useState(!1),L=w==="peek-trailing"?"trailing":w==="peek-leading"?"leading":void 0,T=q=>{F(Q=>{const J=new Set(Q);return J.has(q)?J.delete(q):J.add(q),J.size===0&&R(!1),J})},$=q=>{R(!0),F(new Set([q]))},V=()=>{R(!1),F(new Set)},ne=()=>{k(!0),setTimeout(()=>k(!1),1400)},re=!y&&A&&P&&j.size>0;return n.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[y??(re?n.jsx(dp,{count:j.size,onCancel:V,onMarkRead:V,onDelete:V}):E?null:n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[v&&n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Ha,{className:"size-4"}),onClick:v,"aria-label":"Open folders",className:"-ml-1 shrink-0"}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),t&&n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:t})]})),o==="loading"?n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(Zh,{})}):o==="empty"?n.jsx(ep,{filter:l,scopeLabel:u,searchQuery:i}):o==="error"?n.jsx(ap,{message:f,onRetry:d,onReport:m}):r?n.jsx(Nf,{sections:s,briefCategory:h,selectedThreadId:g,Row:I,onSelectThread:p,onSelectBriefCategory:b}):C??(A?n.jsx(gp,{sections:s,selectedThreadId:g,selectionMode:P,checkedIds:j,initialPeek:L,onToggleCheck:T,onEnterSelection:$,onOpenThread:q=>p?.(q),onRefresh:ne,refreshing:D}):n.jsx("div",{ref:O,className:"flex-1 overflow-y-auto",children:s.map(q=>n.jsxs("div",{children:[!a&&q.label&&n.jsxs("div",{className:"sticky top-0 flex h-section-row items-center justify-between border-b border-line bg-surface-sunken px-row-inset",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:q.label}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:q.threads.length})]}),n.jsx("div",{className:"divide-y divide-line",children:q.threads.map(Q=>n.jsx(I,{thread:Q,active:Q.id===g,onClick:()=>p?.(Q.id)},Q.id))})]},q.id))})),S&&n.jsx(vc,{}),N]})}function Ec({triggerLabel:e,triggerIcon:t,items:s,align:r="end",touch:a=!0,className:o}){const[i,l]=c.useState(!1),u=c.useRef(null);return c.useEffect(()=>{if(!i)return;const f=m=>{u.current&&!u.current.contains(m.target)&&l(!1)},d=m=>{m.key==="Escape"&&l(!1)};return document.addEventListener("mousedown",f),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",d)}},[i]),s.length===0?null:n.jsxs("div",{ref:u,className:H("relative",o),children:[n.jsx(W,{variant:"ghost",size:"sm",icon:t??n.jsx(fc,{className:"size-5"}),onClick:()=>l(f=>!f),"aria-label":e,"aria-haspopup":"menu","aria-expanded":i,className:H(a&&"min-h-11 min-w-11 px-0")}),i&&n.jsx("div",{role:"menu",className:H("absolute top-full z-50 mt-1 flex min-w-44 flex-col rounded-md border border-line bg-surface py-1 shadow-lg",r==="end"?"right-0":"left-0"),children:s.map(f=>n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{l(!1),f.onSelect()},className:"flex min-h-11 items-center gap-3 px-4 py-2.5 text-left text-sm text-fg transition-colors hover:bg-surface-sunken",children:[f.icon&&n.jsx("span",{className:"shrink-0 text-fg-subtle",children:f.icon}),f.label]},f.key))})]})}const Ks="min-h-11 min-w-11 px-0";function Ic({hasThread:e,onReply:t,onReplyAll:s,onForward:r,isStarred:a,onToggleStar:o,onDelete:i,isRead:l,onToggleRead:u,moveSlot:f,overflowItems:d=[],onUnavailable:m,unavailableHint:h,className:g}){const x=(b,v)=>()=>{if(!e){m?.(b);return}v?.()},p=u?[{key:"toggle-read",label:l?"Mark as unread":"Mark as read",icon:l?n.jsx(zl,{className:"size-4"}):n.jsx(Rs,{className:"size-4"}),onSelect:x("toggleRead",u)}]:[];return n.jsxs("div",{className:H("relative",g),children:[n.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-0.5 bg-canvas px-1",children:[n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(xc,{className:"size-5"}),onClick:x("reply",t),"aria-label":"Reply",title:"Reply",className:Ks}),n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(gc,{className:"size-5"}),onClick:x("replyAll",s),"aria-label":"Reply all",title:"Reply all",className:Ks}),n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(mc,{className:"size-5"}),onClick:x("forward",r),"aria-label":"Forward",title:"Forward",className:Ks}),n.jsx("div",{className:"flex-1"}),n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Ft,{className:H("size-5",a&&"fill-warning text-warning")}),onClick:x("star",o),"aria-label":a?"Unstar":"Star","aria-pressed":a,title:a?"Unstar":"Star",className:Ks}),f,n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(ct,{className:"size-5"}),onClick:x("delete",i),"aria-label":"Move to Trash",title:"Move to Trash",className:Ks}),n.jsx(Ec,{triggerLabel:"More actions",items:[...p,...d]})]}),!e&&h&&n.jsx("p",{role:"status",className:"bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:h})]})}function xp({open:e=!1,enabled:t=!0,onToggle:s,className:r}){return n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Ia,{className:"size-4"}),title:"Intelligence","aria-label":e?"Hide intelligence sidebar":"Show intelligence sidebar","aria-pressed":e,disabled:!t,onClick:s,className:H(e&&"bg-accent-2-soft text-accent-2",r)})}function bp({hasThread:e,onUnavailable:t,unavailableHint:s,isStarred:r,showTriage:a=!0,onReply:o,onReplyAll:i,onForward:l,onDelete:u,onToggleStar:f,moveSlot:d,onMove:m,replyTitle:h="Reply (r)",replyAllTitle:g="Reply all (a)",forwardTitle:x="Forward (f)",deleteTitle:p="Move to Trash (#)",flagTitle:b="Star (s)",children:v,className:S}){const w=(y,N)=>()=>{if(!e){t?.(y);return}N?.()};return n.jsxs("div",{className:"relative",children:[n.jsxs("header",{className:H("flex h-pane-header shrink-0 items-center gap-1 border-b border-line bg-surface px-3",S),children:[n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(xc,{className:"size-4"}),title:h,"aria-label":"Reply",onClick:w("reply",o)}),n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(gc,{className:"size-4"}),title:g,"aria-label":"Reply all",onClick:w("replyAll",i)}),n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(mc,{className:"size-4"}),title:x,"aria-label":"Forward",onClick:w("forward",l)}),a&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"mx-1 h-4 w-px bg-line","aria-hidden":!0}),n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(ct,{className:"size-4"}),title:p,"aria-label":"Move to Trash",onClick:w("delete",u)}),d??n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Ya,{className:"size-4"}),title:"Move to mailbox","aria-label":"Move to mailbox",onClick:w("move",m)}),n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Ft,{className:H("size-4",r&&"fill-warning text-warning")}),title:b,"aria-label":"Star",onClick:w("flag",f)})]}),n.jsx("div",{className:"flex-1"}),v]}),!e&&s&&n.jsx("p",{role:"status",className:"border-b border-line bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:s})]})}const vp=(e,t)=>{const r=e==="newsletter"||e==="marketing"||t;return{framed:r,isPlain:!r}},yp=()=>`
9
+ /* Zero the UA default body margin and clamp the document to the iframe width so
10
+ wide author markup can't push the body (and the page) past the viewport. */
11
+ html, body {
12
+ margin: 0;
13
+ padding: 0;
14
+ max-width: 100%;
15
+ }
16
+ body {
17
+ overflow-wrap: anywhere;
18
+ word-break: break-word;
19
+ }
20
+ /* Media never wider than the frame; keep aspect ratio when width is capped. */
21
+ img, video, iframe, svg, canvas {
22
+ max-width: 100% !important;
23
+ height: auto;
24
+ }
25
+ /* Fixed-width author tables (\`<table width="600">\`) collapse to fit. */
26
+ table {
27
+ max-width: 100% !important;
28
+ table-layout: auto;
29
+ }
30
+ /* Cells carry the fixed widths in real newsletters (\`<td width="600">\`);
31
+ cap them too or the table can't actually shrink. */
32
+ td, th {
33
+ max-width: 100% !important;
34
+ }
35
+ /* \`max-width\` alone can't beat an inline \`min-width\`; zeroing the min lets
36
+ flex / grid / table children actually collapse to the clamped width. */
37
+ * {
38
+ min-width: 0;
39
+ }
40
+ /* Long unbroken strings (URLs, tokens) wrap instead of forcing a wide line. */
41
+ pre, code {
42
+ white-space: pre-wrap;
43
+ overflow-wrap: anywhere;
44
+ word-break: break-word;
45
+ }
46
+ `,wp=e=>{const t=new Map;for(const s of e){if(!s.contentId||s.contentUrl.length===0)continue;const r=s.contentId.replace(/^<|>$/g,"");t.set(r,s.contentUrl)}return s=>t.get(s.replace(/^<|>$/g,""))},Sp=/^(none|transparent|inherit|initial|unset)\s*$/i,jp=e=>{const t=[],s=/<style[^>]*>([\s\S]*?)<\/style>/gi;let r;for(r=s.exec(e);r!==null;)t.push(r[1]),r=s.exec(e);return t},kp=e=>{const t=/background(?:-color)?\s*:\s*([^;}\n]+)/gi;let s;for(s=t.exec(e);s!==null;){const r=s[1].trim();if(!Sp.test(r))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 jp(e))if(kp(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
+ <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
48
+ <rect fill="#f0f0f0" width="100" height="100"/>
49
+ <text x="50" y="50" text-anchor="middle" dy=".3em" fill="#999" font-size="12">
50
+ Image blocked
51
+ </text>
52
+ </svg>
53
+ `),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=jl(),s={FORBID_TAGS:Np,FORBID_ATTR:Ep,ALLOW_DATA_ATTR:!1,ALLOW_UNKNOWN_PROTOCOLS:!1};return t.addHook("afterSanitizeAttributes",r=>{if(r.tagName==="IMG"){const a=r.getAttribute("src")||"";if(a.startsWith("data:"))return;if(a.startsWith("cid:")){const i=a.slice(4).replace(/^<|>$/g,""),l=e.resolveCid?.(i);l&&(r.setAttribute("src",l),r.classList.add("inline-content"));return}e.allowExternalImages||(r.setAttribute("data-blocked-src",a),r.setAttribute("src",Ip),r.setAttribute("alt","[Blocked image]"),r.classList.add("blocked-image"))}if(r.tagName==="A"){const a=r.getAttribute("href")||"";if(/^(javascript|data):/i.test(a)){r.removeAttribute("href");return}r.setAttribute("target","_blank"),r.setAttribute("rel","noopener noreferrer nofollow"),r.classList.add("external-link")}if(r.hasAttribute("style")){const a=r.getAttribute("style")||"";r.setAttribute("style",Tp(a))}}),t.addHook("uponSanitizeElement",(r,a)=>{if(a.tagName==="style"){const o=r.textContent||"";r.textContent=Rp(o)}}),r=>{const a=Cp(r),o=t.sanitize(r,s);return{html:`<style>${yp()}</style>${o}`,hasAuthorBackground:a}}},Ap='"Geist Variable", "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',ui={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,di='<meta name="viewport" content="width=device-width, initial-scale=1">',Dp=e=>{const t=e?ui.dark:ui.light;return`
54
+ /* Plain-email base: UI font-stack + theme-aware colors (#424) */
55
+ html, body {
56
+ font-family: ${Ap};
57
+ font-size: 14px;
58
+ line-height: 1.6;
59
+ color: ${t.fg};
60
+ background-color: ${t.surface};
61
+ margin: 0;
62
+ padding: 0;
63
+ }
64
+ /* Strip author unreadable text colors and element backgrounds, scoped to body
65
+ descendants so the themed html/body surface above survives this reset. */
66
+ body * {
67
+ color: inherit !important;
68
+ background-color: transparent !important;
69
+ }
70
+ a, a:visited {
71
+ color: ${t.accent} !important;
72
+ text-decoration: underline;
73
+ }
74
+ `},Pp=(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`${di}<style>${Dp(s)}</style>${e}`;const r=Op.test(e);return`${di}<style>${Pp(s,r)}</style>${e}`},Fp=5e4,$p=1e4,_p="(max-width: 640px)",zp=.4,Bp="allow-same-origin allow-popups allow-popups-to-escape-sandbox",fi=(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 r=window.matchMedia(e);s(r.matches);const a=o=>s(o.matches);return r.addEventListener("change",a),()=>r.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),mi=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}))},hi=({html:e,variant:t="framed",isDark:s=!1,className:r})=>{const a=c.useRef(null),o=c.useRef(null),[i,l]=c.useState(0),[u,f]=c.useState(0),[d,m]=c.useState(0),h=Up(_p),g=c.useMemo(()=>Lp(e,t,s),[e,t,s]);c.useEffect(()=>{const w=a.current;if(!w)return;const y=()=>m(C=>C===w.clientWidth?C:w.clientWidth);y();const N=new ResizeObserver(y);return N.observe(w),()=>N.disconnect()},[]),c.useEffect(()=>{const w=o.current;if(!w)return;const y=()=>{const I=w.contentDocument;if(!I?.body)return;const O=I.documentElement,A=fi(I.body.scrollHeight,O?.scrollHeight??0,Fp);l(P=>P===A?P:A);const M=fi(I.body.scrollWidth,O?.scrollWidth??0,$p);f(P=>P===M?P:M)};let N,C;const E=()=>{y();const I=w.contentDocument;I?.body&&(N=new ResizeObserver(y),N.observe(I.body),I.documentElement&&N.observe(I.documentElement),I.addEventListener("keydown",mi),C=I)};return w.addEventListener("load",E),()=>{w.removeEventListener("load",E),C?.removeEventListener("keydown",mi),N?.disconnect()}},[]);const x=h?Kp(u,d):1,p=x<1,b=p?`${u}px`:h?"100%":t==="framed"&&u>0?`max(100%, ${u}px)`:u===0?"100%":`${u}px`,v=i===0?"1px":`${i}px`,S=n.jsx("iframe",{ref:o,title:"Email content",sandbox:Bp,srcDoc:g,className:p?void 0:r,scrolling:"no",style:{width:b,maxWidth:p?"none":void 0,border:"none",display:"block",height:v,overflow:"hidden",transform:p?`scale(${x})`:void 0,transformOrigin:p?"top left":void 0,colorScheme:"normal"}});return n.jsx("div",{ref:a,className:p?r:void 0,children:p?n.jsx("div",{style:{width:"100%",height:`${Math.ceil(i*x)}px`,overflow:"hidden"},children:S}):S})},pi=()=>n.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Tc=({html:e,text:t,isDark:s=!1,category:r,allowImages:a=!1,resolveCid:o,className:i,renderBlockedNotice:l})=>{const u=c.useMemo(()=>!e||typeof document>"u"?null:Mp({allowExternalImages:a,resolveCid:o})(e),[e,a,o]),f=u?.html??null,{framed:d,isPlain:m}=vp(r,u?.hasAuthorBackground??!1),h=c.useMemo(()=>!f||a?0:(f.match(/data-blocked-src/g)||[]).length,[f,a]);return!f&&!t?n.jsx("div",{className:H("message-body",i),children:n.jsx(pi,{})}):n.jsxs("div",{className:H("message-body",i),children:[h>0&&n.jsx("div",{className:"message-body-notice",children:l?.(h)}),f?d?n.jsx("div",{className:"w-full max-w-full overflow-x-auto",children:n.jsx(hi,{html:f,variant:"framed",isDark:s})}):n.jsx("div",{className:"max-w-full overflow-x-auto lg:max-w-2xl",children:n.jsx(hi,{html:f,variant:m?"plain":"framed",isDark:s})}):t?n.jsx("pre",{className:"email-text whitespace-pre-wrap text-sm leading-relaxed",children:t}):n.jsx(pi,{})]})};function Os({message:e="Select a thread to read",icon:t,showHints:s=!0,className:r}){return n.jsxs("div",{className:H("flex flex-1 flex-col items-center justify-center text-center",r),children:[t??n.jsx(Ta,{className:"size-10 text-fg-subtle"}),n.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:e}),s&&n.jsxs("p",{className:"text-2xs text-fg-subtle",children:[n.jsx(vs,{children:"j"})," / ",n.jsx(vs,{children:"k"})," to move, ",n.jsx(vs,{children:"Enter"})," to open"]})]})}function Rc({message:e,onClick:t,isFocused:s,isUnread:r,trailing:a}){const o=n.jsxs(n.Fragment,{children:[n.jsx(Ns,{className:"size-3.5 shrink-0 text-fg-subtle"}),n.jsxs("div",{className:"relative shrink-0",children:[n.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"md"}),r&&n.jsx("span",{className:"absolute -top-0.5 -right-0.5 size-2 rounded-full border border-canvas bg-accent"})]}),n.jsx("span",{className:H("w-36 shrink-0 truncate text-sm",r?"font-semibold text-fg":"font-medium text-fg-muted"),children:e.fromName}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-fg-subtle",children:e.snippet}),a??n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.dateLabel})]}),i=H("group flex h-section-row w-full items-center gap-3 border-b border-line px-2 text-left transition-colors hover:bg-surface-sunken lg:px-4",s&&"bg-surface-sunken ring-1 ring-inset ring-accent/30");return t?n.jsx("div",{role:"button",tabIndex:0,"aria-expanded":!1,onClick:t,onKeyDown:l=>{Ef(l)&&(l.preventDefault(),t())},className:H(i,"cursor-pointer"),children:o}):n.jsx("div",{className:i,children:o})}function Mc({message:e,warning:t,onHeaderClick:s,isFocused:r,senderBadge:a,trailing:o,to:i,indicators:l,actionMenu:u,actionBar:f,body:d}){const m=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[n.jsxs("span",{className:"text-sm font-semibold text-fg",children:[e.fromName,a]}),o??n.jsx("span",{className:"text-2xs text-fg-subtle",children:e.dateLabel})]}),n.jsx("div",{className:"text-xs text-fg-subtle",children:e.fromEmail}),i!==null&&n.jsx("div",{className:"text-xs text-fg-subtle",children:i??n.jsxs(n.Fragment,{children:["to ",e.toLabel]})})]});return n.jsxs("div",{className:H("px-2 py-3 lg:px-4",r&&"ring-1 ring-inset ring-accent/30"),children:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx(Dt,{className:"mt-1 size-3.5 shrink-0 text-fg-subtle"}),n.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"md"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[s?n.jsx("button",{type:"button",onClick:s,className:"w-full text-left",children:m}):m,l]}),u&&n.jsx("div",{className:"shrink-0",children:u})]}),t&&n.jsxs("div",{className:"mt-3 flex items-start gap-3 rounded-md bg-danger-soft p-3",children:[n.jsx(Ms,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("div",{className:"text-sm text-fg",children:[n.jsx("span",{className:"font-semibold text-danger",children:"Caution: "}),t," ",n.jsx("button",{type:"button",className:"text-accent underline",children:"Why?"})]})]}),f&&n.jsx("div",{className:"mt-3 -mx-2 lg:-mx-4",children:f}),n.jsx("div",{className:"-mx-2 [&_.message-body-notice]:px-2 lg:mx-0 lg:[&_.message-body-notice]:px-0",children:d??n.jsx(Tc,{className:"mt-3",html:e.bodyHtml,category:e.framed?"newsletter":"personal",allowImages:!0})})]})}function Wp({thread:e,onBack:t,intelligence:s,intelligenceOpen:r,onToggleIntelligence:a,actions:o,children:i,touchHandlers:l}){const[u,f]=c.useState(!1),d=a!==void 0,m=d?r??!1:u,h=!!s||d,g=()=>{if(d){a?.();return}f(p=>!p)},x=()=>{if(d){m&&a?.();return}f(!1)};return n.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(lc,{className:"size-4"}),onClick:t,"aria-label":"Back to messages",className:"-ml-1 shrink-0"}),n.jsx("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e.subject}),h&&n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Ia,{className:"size-4"}),onClick:g,"aria-label":m?"Hide intelligence panel":"Show intelligence panel","aria-pressed":m,title:"Intelligence",className:H("shrink-0",m&&"bg-accent-2-soft text-accent-2")})]}),n.jsx("div",{className:"flex-1 overflow-y-auto",style:l?{touchAction:"pan-y"}:void 0,...l,children:i??e.messages.map(p=>{const b=v=>v?()=>v(p.id):void 0;return p.expanded?n.jsx(Mc,{message:p,warning:e.warning,onHeaderClick:b(o?.onToggleExpand),actionBar:n.jsx(Ic,{hasThread:!0,onReply:b(o?.onReply),onReplyAll:b(o?.onReplyAll),onForward:b(o?.onForward),onToggleStar:b(o?.onToggleStar),onDelete:b(o?.onDelete),onToggleRead:b(o?.onToggleRead),moveSlot:o?.moveSlot?.(p.id)})},p.id):n.jsx(Rc,{message:p,onClick:b(o?.onToggleExpand)},p.id)})}),s&&!d&&n.jsx(Ra,{open:m,onClose:x,title:"Intelligence",anchor:"right",className:"p-0",children:n.jsx(bc,{data:s,onClose:x,className:"h-full w-full border-l-0"})})]})}const Vp="button:not([disabled]), a[href]",Xt="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 H("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors",Xt,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 Yp({icon:e,label:t,count:s,active:r}){return n.jsxs(n.Fragment,{children:[e&&n.jsx("span",{className:H("shrink-0",r?"text-accent-2":"text-fg-subtle"),children:e}),n.jsx("span",{className:"flex-1 truncate",children:t}),s!=null&&s>0&&n.jsx("span",{className:H("text-2xs tabular-nums",r?"text-accent-2":"text-fg-subtle"),children:s})]})}function ws({icon:e,label:t,count:s,active:r,dimmed:a,indent:o,navId:i,linkComponent:l,ariaLabel:u,title:f,onClick:d}){const m=Qp({active:r,dimmed:a,indent:o}),h=n.jsx(Yp,{icon:e,label:t,count:s,active:r});return i&&l?l({navId:i,className:m,ariaLabel:u??t,title:f,onClick:d,children:h}):n.jsx("button",{type:"button",onClick:d,className:m,"aria-label":u,title:f,children:h})}const gi={inbox:0,flagged:1,drafts:2,sent:3,archive:4,all:5,junk:6,trash:7};function Gp(e){switch(e){case"inbox":return n.jsx(Ta,{className:"size-4"});case"flagged":return n.jsx(Ft,{className:"size-4"});case"drafts":return n.jsx(kl,{className:"size-4"});case"sent":return n.jsx(rn,{className:"size-4"});case"archive":return n.jsx(Rf,{className:"size-4"});case"all":return n.jsx(Tf,{className:"size-4"});case"junk":return n.jsx(If,{className:"size-4"});case"trash":return n.jsx(ct,{className:"size-4"})}}const xi=e=>e.role!=null,Br=8,bi="remit.nav.folders.open.",vi="remit.nav.account.open.";function yi(e,t,s){if(typeof localStorage>"u")return s;const r=localStorage.getItem(e+t);return r===null?s:r!=="0"}function wi(e,t,s){typeof localStorage>"u"||localStorage.setItem(e+t,s?"1":"0")}function Xp({query:e,onSelect:t,onRemove:s}){return n.jsxs("div",{className:"group flex w-full items-center gap-1 rounded-md pr-1 hover:bg-surface",children:[n.jsxs("button",{type:"button",onClick:t,className:H("flex min-w-0 flex-1 items-center gap-2 px-2 py-1 text-left text-sm text-fg-muted transition-colors hover:text-fg",Xt),children:[n.jsx(ir,{className:"size-4 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"min-w-0 flex-1 truncate",children:e})]}),s&&n.jsx("button",{type:"button",onClick:s,"aria-label":`Remove saved search: ${e}`,className:H("shrink-0 rounded-full p-1 text-fg-subtle opacity-0 transition-opacity hover:bg-surface-sunken hover:text-fg group-hover:opacity-100 focus-visible:opacity-100",Xt),children:n.jsx(Ze,{className:"size-3.5"})})]})}function Jp({savedSearches:e,saveableQuery:t,onSelectSavedSearch:s,onRemoveSavedSearch:r,onSaveCurrentSearch:a}){return e.length===0&&!t?null:n.jsxs("div",{className:"mt-3",children:[n.jsx("div",{className:"px-2 pb-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Saved searches"}),t&&n.jsxs("button",{type:"button",onClick:a,className:H("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-accent transition-colors hover:bg-surface",Xt),children:[n.jsx(Dh,{className:"size-4 shrink-0"}),n.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Save “",t,"”"]})]}),e.map(o=>n.jsx(Xp,{query:o,onSelect:()=>s?.(o),onRemove:r?()=>r(o):void 0},o))]})}function Zp({account:e,selectedNavId:t,onSelectNav:s,linkComponent:r}){const[a,o]=c.useState(()=>yi(vi,e.id,!0)),[i,l]=c.useState(()=>yi(bi,e.id,!0)),[u,f]=c.useState(!1),d=()=>{o(S=>{const w=!S;return wi(vi,e.id,w),w})},m=()=>{l(S=>{const w=!S;return wi(bi,e.id,w),w})},h=e.mailboxes.filter(xi).sort((S,w)=>gi[S.role]-gi[w.role]),g=e.mailboxes.filter(S=>!xi(S)),x=u||g.length<=Br?g:g.slice(0,Br),p=g.length-x.length,b=e.status??"ready",v=b==="ready"&&h.length===0&&g.length===0;return n.jsxs("div",{className:"mt-3",children:[n.jsxs("button",{type:"button",onClick:d,"aria-expanded":a,className:H("flex w-full items-center gap-1.5 px-2 pb-1 text-left transition-colors hover:text-fg",Xt,e.muted&&"opacity-55"),children:[a?n.jsx(Dt,{className:"size-3 shrink-0 text-fg-subtle"}):n.jsx(Ns,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"truncate text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),e.muted&&n.jsxs(n.Fragment,{children:[n.jsx(cc,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:"muted"})]})]}),a&&n.jsxs(n.Fragment,{children:[b==="loading"&&n.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"Loading…"}),b==="error"&&n.jsxs("div",{role:"alert",className:"mx-2 my-1 flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-2 py-1.5 text-sm",children:[n.jsx(ts,{className:"mt-0.5 size-4 shrink-0 text-danger","aria-hidden":"true"}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx("p",{className:"font-medium text-danger",children:"Couldn't load mailboxes"})}),e.onRetry&&n.jsx("button",{type:"button",onClick:e.onRetry,className:"shrink-0 text-sm font-medium text-accent hover:underline",children:"Retry"})]}),v&&n.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"No mailboxes"}),b==="ready"&&n.jsxs(n.Fragment,{children:[h.map(S=>n.jsx(ws,{navId:S.id,linkComponent:r,icon:Gp(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&&n.jsx(ws,{navId:"outbox",linkComponent:r,icon:n.jsx(rn,{className:"size-4"}),label:"Outbox",ariaLabel:"Outbox",count:e.outboxPending>0?e.outboxPending:void 0,active:t==="outbox",dimmed:e.muted,onClick:()=>s?.("outbox")}),g.length>0&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{type:"button",onClick:m,"aria-expanded":i,className:H("mt-1 flex w-full items-center gap-1 px-2 py-1 text-left text-2xs font-semibold uppercase tracking-wider text-fg-subtle transition-colors hover:text-fg",Xt),children:[i?n.jsx(Dt,{className:"size-3 shrink-0"}):n.jsx(Ns,{className:"size-3 shrink-0"}),n.jsx("span",{className:"flex-1",children:"Folders"}),n.jsx("span",{className:"tabular-nums opacity-70",children:g.length})]}),i&&n.jsxs(n.Fragment,{children:[x.map(S=>n.jsx(ws,{navId:S.id,linkComponent:r,icon:n.jsx(Wm,{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)&&g.length>Br&&n.jsx("button",{type:"button",onClick:()=>f(S=>!S),className:H("ml-7 flex items-center px-2 py-1 text-2xs font-medium text-accent transition-colors hover:underline",Xt),children:u?"Show less":`Show all (${g.length})`})]})]})]})]})]})}function eg({accounts:e,selectedNavId:t,briefUnseen:s,onSelectNav:r,variant:a="desktop",linkComponent:o,savedSearches:i=[],saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:f,onSaveCurrentSearch:d}){const m=c.useRef(null);er({containerRef:m,itemSelector:Vp});const h=a==="drawer",g=n.jsxs("nav",{ref:h?m:void 0,className:h?"px-2 py-2":"flex-1 overflow-y-auto px-2 py-2","aria-label":"Mailboxes",children:[n.jsx(ws,{navId:"brief",linkComponent:o,icon:n.jsx(xt,{className:"size-4"}),label:"Daily brief",ariaLabel:"Daily brief",count:s,active:t==="brief",onClick:()=>r?.("brief")}),n.jsx(ws,{navId:"flagged",linkComponent:o,icon:n.jsx(Ft,{className:"size-4"}),label:"Starred",ariaLabel:"Starred",active:t==="flagged",onClick:()=>r?.("flagged")}),n.jsx(Jp,{savedSearches:i,saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:f,onSaveCurrentSearch:d}),e.length===0?n.jsx("div",{className:"px-2 py-4 text-center text-sm text-fg-muted",children:"No accounts configured"}):e.map(x=>n.jsx(Zp,{account:x,selectedNavId:t,onSelectNav:r,linkComponent:o},x.id))]});return h?g:n.jsxs("aside",{ref:m,className:"flex h-full w-full flex-col bg-surface-sunken",children:[g,n.jsx("div",{className:"border-t border-line px-2 py-2",children:n.jsx(ws,{navId:"settings",linkComponent:o,icon:n.jsx(eo,{className:"size-4"}),label:"Settings",ariaLabel:"Settings",active:t==="settings",onClick:()=>r?.("settings")})})]})}function tg({search:e,actions:t,className:s}){return n.jsxs("header",{className:H("flex min-h-16 w-full shrink-0 items-center gap-3 border-b border-line bg-canvas px-3 py-2",s),children:[n.jsx("div",{className:"flex min-w-0 flex-1 justify-start",children:n.jsx("div",{className:"w-full max-w-2xl",children:e})}),t&&n.jsx("div",{className:"flex shrink-0 items-center gap-1",children:t})]})}function sg({label:e,onUndo:t,undoLabel:s="Undo",filtersHref:r,manageLabel:a="Manage filter",className:o}){return n.jsxs(pt,{tone:"accent",className:H("py-1 text-xs",o),children:[n.jsx(Uh,{className:"size-3.5 shrink-0","aria-hidden":!0}),n.jsx("span",{children:e}),t&&n.jsx("button",{type:"button",onClick:i=>{i.stopPropagation(),t()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:s}),r&&n.jsx("a",{href:r,onClick:i=>{i.stopPropagation()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:a})]})}function ng({sync:e}){return e?n.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:[n.jsx(et,{className:"size-8 animate-spin text-fg-subtle","aria-hidden":"true"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Still syncing your mail"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:rg(e)})]}):n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[n.jsx(xt,{className:"size-8 text-fg-subtle","aria-hidden":"true"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"You're caught up"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Nothing needs attention."})]})}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=({status:e})=>e==="saving"?n.jsx("span",{className:"animate-pulse text-xs text-fg-muted",children:"Saving..."}):e==="saved"?n.jsx("span",{className:"text-xs text-fg-muted",children:"Draft saved"}):e==="error"?n.jsx("span",{className:"text-xs text-danger",children:"Save failed"}):null;function og({onSend:e,onDiscard:t,sending:s,canSend:r,saveStatus:a="idle",unavailableReason:o,onUnavailable:i}){return n.jsxs("div",{className:"flex items-center justify-between border-t border-line px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(W,{variant:"primary",size:"md","aria-busy":s,title:r?void 0:o,className:"min-h-11 rounded-full px-4",icon:s?n.jsx(et,{className:"size-4 animate-spin"}):n.jsx(rn,{className:"size-4"}),onClick:()=>{if(!s){if(!r){o&&i?.(o);return}e()}},children:"Send"}),n.jsx(ag,{status:a})]}),n.jsx(W,{variant:"ghost",size:"md","aria-busy":s,"aria-label":"Discard",className:"min-h-11 min-w-11 px-2 hover:text-danger",icon:n.jsx(ct,{className:"size-4"}),onClick:()=>{s||t()}})]})}function ig({banner:e,header:t,children:s,quoted:r,actionBar:a}){return n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e,t,n.jsxs("div",{className:"min-h-0 flex-1 overflow-auto",children:[s,r&&n.jsx("div",{className:"px-3 pb-2",children:r})]}),a]})}function lg({key:e,shiftKey:t=!1,repeat:s=!1,caretAtStart:r,hasValue:a,chipCount:o}){const i=o-1;return e==="Escape"?a?{type:"clearQuery"}:{type:"blur"}:e==="Tab"&&t?o===0?{type:"none"}:{type:"focusChip",index:i}:e==="Backspace"||e==="ArrowLeft"?!r||o===0?{type:"none"}:s?{type:"none"}:{type:"focusChip",index:i}:{type:"none"}}function cg({key:e,repeat:t=!1,index:s,chipCount:r}){return e==="Backspace"||e==="Delete"?t?{type:"none"}:{type:"removeChip",index:s}:e==="ArrowLeft"?s===0?{type:"none"}:{type:"focusChip",index:s-1}:e==="ArrowRight"?s>=r-1?{type:"focusInput"}:{type:"focusChip",index:s+1}:e==="Enter"||e===" "?{type:"activateChip",index:s}:e==="Escape"?{type:"focusInput"}:{type:"none"}}function ug(e,t){const s=t-1;return s<=0?null:e<s?e:s-1}const dg=e=>e instanceof HTMLElement?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable:!1,fg=({chips:e=[],onRemoveChip:t,onActivateChip:s,value:r,onChange:a,onClear:o,onClearQuery:i,placeholder:l="Search mail...",globalFocusKey:u=!0,showClearButton:f=!0,size:d="sm",inputId:m,chipsLabel:h="Search filters",suggest:g,className:x})=>{const p=c.useId(),b=m??p,v=c.useRef(null),S=c.useRef([]),w=i??o,[y,N]=c.useState(null),C=c.useRef(void 0),[E,I]=c.useState(""),O=e.length>0;c.useEffect(()=>{N(k=>k!==null&&k>=e.length?null:k)},[e.length]),c.useEffect(()=>{const k=C.current;if(k!==void 0){if(C.current=void 0,k===null){v.current?.focus();return}S.current[k]?.focus()}});const A=c.useRef(void 0);c.useEffect(()=>{const k=g?.caret;if(!k||k===A.current)return;A.current=k;const L=v.current;!L||L.ownerDocument.activeElement!==L||(L.setSelectionRange(k.cursor,k.cursor),g?.onCaretChange(k.cursor))});const M=k=>{g?.onCaretChange(k.selectionStart??k.value.length)},P=c.useCallback(k=>{N(k),C.current=k},[]),R=c.useCallback(k=>{const L=e[k];L&&t&&(P(ug(k,e.length)),I(`${L.label} removed`),t(L.id))},[e,t,P]),j=c.useCallback(()=>{P(null),o()},[o,P]),F=c.useCallback(k=>{const L=k.currentTarget;if(g?.onKeyDown(k))return;const T=lg({key:k.key,shiftKey:k.shiftKey,repeat:k.repeat,caretAtStart:L.selectionStart===0&&L.selectionEnd===0,hasValue:r.length>0,chipCount:e.length});switch(T.type){case"focusChip":k.preventDefault(),P(T.index);return;case"clearQuery":w();return;case"blur":L.blur();return;case"none":return}},[e.length,r,w,P,g]),D=c.useCallback(k=>L=>{const T=cg({key:L.key,repeat:L.repeat,index:k,chipCount:e.length});switch(T.type!=="none"&&L.preventDefault(),T.type){case"removeChip":R(T.index);return;case"focusChip":P(T.index);return;case"focusInput":P(null);return;case"activateChip":{const $=e[T.index];$&&s&&s($.id);return}case"none":return}},[e,R,P,s]);return c.useEffect(()=>{if(!u)return;const k=L=>{L.key!=="/"||L.metaKey||L.ctrlKey||L.altKey||dg(L.target)||(L.preventDefault(),v.current?.focus())};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[u]),n.jsxs("label",{htmlFor:b,className:H("flex w-full items-center gap-1.5 text-sm","bg-surface-sunken/50 border border-transparent","focus-within:bg-canvas focus-within:border-line focus-within:ring-2 focus-within:ring-ring","transition-colors",d==="lg"?"rounded-xl px-4 py-2":"rounded-md px-2.5 py-1",x),children:[n.jsx(ir,{className:H("shrink-0 text-fg-muted pointer-events-none",d==="lg"?"size-5":"size-4")}),n.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1",children:[O&&n.jsx("div",{role:"grid","aria-label":h,className:"flex min-w-0 flex-wrap items-center gap-1",children:e.map((k,L)=>n.jsx(Mf,{ref:T=>{S.current[L]=T},label:k.label,tone:k.tone,focused:y===L,onFocusLabel:()=>N(L),onKeyDown:D(L),onRemove:()=>R(L),onActivate:s?()=>s(k.id):void 0},k.id))}),n.jsx("input",{ref:v,id:b,name:"q",type:"text","aria-label":"Search mail",autoComplete:"off",value:r,tabIndex:y===null?0:-1,onChange:k=>{a(k.target.value),M(k.target)},onKeyDown:F,onKeyUp:k=>M(k.currentTarget),onClick:k=>M(k.currentTarget),onFocus:k=>{N(null),g?.onFocusChange?.(!0),M(k.currentTarget)},onBlur:()=>g?.onFocusChange?.(!1),...g?.comboboxProps,placeholder:O?void 0:l,className:"min-w-24 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted"})]}),(r||O)&&f&&n.jsx("button",{type:"button",onClick:j,className:"shrink-0 rounded p-0.5 hover:bg-surface-raised transition-colors","aria-label":"Clear search",children:n.jsx(Ze,{className:H("text-fg-muted",d==="lg"?"size-5":"size-4")})}),n.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:E})]})},no=({value:e,onChange:t,onClear:s,onClearQuery:r,chips:a,onRemoveChip:o,placeholder:i="Search mail...",globalFocusKey:l=!0,showClearButton:u=!0,size:f,inputId:d,suggest:m,className:h})=>n.jsx(fg,{value:e,onChange:t,onClear:s,onClearQuery:r,chips:a,onRemoveChip:o,placeholder:i,globalFocusKey:l,showClearButton:u,size:f,inputId:d,suggest:m,className:h});function mg({title:e,unreadCount:t,isDesktop:s,onMenuClick:r,searchValue:a,onSearchChange:o,onSearchClear:i,searchOpen:l,onSearchOpenChange:u,showSearch:f=!0,searchSuggest:d}){const m=`${t.toLocaleString()} unread`,h=i??(()=>o("")),g=()=>{h(),u(!1)},x=b=>n.jsx(no,{value:a,onChange:o,onClear:h,globalFocusKey:!1,showClearButton:b,suggest:d}),p=n.jsx(W,{variant:"ghost",icon:n.jsx(Ha,{className:"size-5"}),onClick:r,"aria-label":"Menu",className:"min-h-11 min-w-11 shrink-0 px-0"});return n.jsx("header",{className:"flex shrink-0 flex-col bg-canvas",children:n.jsx("div",{className:"flex h-12 items-center gap-2 px-row-inset",children:f?s?n.jsxs(n.Fragment,{children:[p,n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:m}),n.jsx("div",{className:"w-64 max-w-[40%] shrink-0",children:x(!0)})]}):l||a.trim().length>0?n.jsxs("div",{className:"flex flex-1 items-center gap-1",children:[n.jsx("div",{className:"flex-1",children:x(!1)}),n.jsx(W,{variant:"ghost",icon:n.jsx(Ze,{className:"size-5"}),onClick:g,"aria-label":"Close search",className:"min-h-11 min-w-11 shrink-0 px-0"})]}):n.jsxs(n.Fragment,{children:[p,n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:m}),n.jsx(W,{variant:"ghost",icon:n.jsx(ir,{className:"size-5"}),onClick:()=>u(!0),"aria-label":"Search",className:"min-h-11 min-w-11 shrink-0 px-0"})]}):n.jsxs(n.Fragment,{children:[p,n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:m})]})})})}const hg=(e,t)=>e==="vip"?"vip":e==="unknown"&&t==="md"?"unknown-pill":"hidden",Ac=({senderTrust:e,size:t="sm",className:s})=>{const r=hg(e,t);return r==="vip"?n.jsx(xt,{className:H("text-warning shrink-0",t==="sm"&&"size-3.5",t==="md"&&"size-4",s),"aria-label":"VIP sender","data-testid":"sender-trust-vip"}):r==="unknown-pill"?n.jsx("span",{className:H("inline-flex items-center rounded border border-dashed border-fg-subtle/40 font-medium uppercase tracking-wide text-fg-muted/80 shrink-0","px-2 py-0.5 text-xs",s),title:"First message from this sender","aria-label":"First message from this sender","data-testid":"sender-trust-unknown",children:"new"}):null};function pg(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 gg({result:e,onClick:t,query:s,showFolder:r=!0}){const a=r&&e.folder?Af(e.folder):void 0;return n.jsx("button",{type:"button",onClick:t,className:H("group",As({}),"border-b border-line"),children:n.jsx(to,{thread:pg(e),highlightQuery:s,badge:n.jsxs(n.Fragment,{children:[a&&n.jsx(pt,{tone:"neutral",className:"shrink-0",children:a}),e.category&&n.jsx(pt,{tone:e.category.tone??"neutral",className:"shrink-0",children:e.category.label}),e.matchedChunkLabel&&n.jsx(pt,{tone:"neutral",className:"shrink-0",children:`matched: ${e.matchedChunkLabel}`}),e.score!=null&&n.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.score.toFixed(2)})]})})})}const xg=e=>e===1?"result":"results";function bg({count:e,onScopeToSpam:t}){return n.jsx(ss,{tone:"info",variant:"soft",className:"items-center justify-between gap-3 rounded-none border-b border-line",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("p",{className:"min-w-0 text-xs text-fg-muted",children:[n.jsx("span",{className:"font-semibold text-fg tabular-nums",children:e})," ",`${xg(e)} from Spam`]}),n.jsx(W,{variant:"ghost",size:"sm",onClick:t,className:"shrink-0 text-accent",children:"Go to Spam"})]})})}const Si=6,vg={kind:"global"},yg=e=>e.kind==="folder"&&e.role==="junk",wg=e=>e.folder?.role==="junk";function Oc(e){const t=[],s=[];for(const r of e)wg(r)?s.push(r):t.push(r);return{kept:t,spam:s}}function Dc({onClick:e,disabledReason:t}){const s=t!==void 0;return n.jsx("div",{className:"border-b border-line px-row-inset py-1.5",children:n.jsxs("button",{type:"button",onClick:e,disabled:s,title:t,className:H("flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs font-medium transition-colors",s?"cursor-not-allowed text-fg-subtle":"text-accent hover:bg-surface-sunken"),children:[n.jsx(Of,{className:"size-3.5 shrink-0","aria-hidden":"true"}),n.jsx("span",{children:"Make this a filter"}),s&&n.jsx("span",{className:"ml-auto truncate text-2xs font-normal text-fg-subtle",children:t})]})})}function Sg({section:e,query:t,onSelectResult:s,showFolder:r}){const[a,o]=c.useState(e.initialCollapsed??!1),[i,l]=c.useState(!1),u=e.results.length>Si,d=!i&&u?e.results.slice(0,Si):e.results,m=e.results.length-d.length;return n.jsxs("div",{children:[n.jsxs("button",{type:"button","aria-expanded":!a,onClick:()=>o(h=>!h),className:"sticky top-0 z-10 flex h-section-row w-full items-center gap-1.5 border-b border-line bg-surface-sunken px-row-inset text-left transition-colors hover:bg-surface",children:[n.jsx("span",{className:"flex-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:e.results.length}),n.jsx(Dt,{className:H("size-3 shrink-0 text-fg-subtle transition-transform duration-200",a?"rotate-0":"rotate-180")})]}),!a&&n.jsxs(n.Fragment,{children:[d.map(h=>n.jsx(gg,{result:h,query:t,showFolder:r,onClick:s?()=>s(h):void 0},h.id)),u&&n.jsxs("button",{type:"button",onClick:()=>l(h=>!h),className:"flex w-full items-center justify-center border-b border-line px-row-inset py-1.5 text-2xs font-medium text-accent transition-colors hover:bg-surface",children:[i?"Show less":`Show ${m} more`,!i&&n.jsx(Dt,{className:"ml-1 size-3"})]})]})]})}function Pc({value:e,recentSearches:t,onPickRecent:s,sections:r,loading:a,onSelectResult:o,tokens:i,scope:l=vg,makeFilter:u}){if(!(e.trim().length>0))return t&&t.length>0?n.jsxs("div",{className:"flex flex-col",children:[n.jsx("h3",{className:"px-row-inset pb-1 pt-3 text-2xs font-semibold uppercase tracking-wide text-fg-subtle",children:"Recent searches"}),t.map(y=>n.jsxs("button",{type:"button",onClick:()=>s?.(y),className:"flex w-full items-center gap-2.5 border-b border-line px-row-inset py-2.5 text-left transition-colors hover:bg-surface-sunken",children:[n.jsx(Wa,{className:"size-4 shrink-0 text-fg-subtle"}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-fg-muted",children:y})]},y))]}):n.jsx("p",{className:"px-row-inset py-6 text-center text-sm text-fg-subtle",children:"Search across your mail by sender, subject or words in the message."});const d=i&&i.length>0&&n.jsx(Df,{tokens:i}),m=u&&n.jsx(Dc,{onClick:u.onClick,disabledReason:u.disabledReason});if(a)return n.jsxs("div",{className:"flex flex-col",children:[m,d,n.jsx("div",{className:"flex flex-col gap-3 px-row-inset py-4",children:[0,1,2,3].map(y=>n.jsxs("div",{className:"flex flex-col gap-1.5",children:[n.jsx("div",{className:"h-3 w-1/3 animate-pulse rounded bg-surface-sunken"}),n.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-surface-sunken"}),n.jsx("div",{className:"h-2.5 w-1/2 animate-pulse rounded bg-surface-sunken"})]},y))})]});const h=l.kind==="global",g=yg(l)||l.kind==="collection",x=h||l.kind==="collection",p=(r??[]).map(y=>{if(g)return{section:y,spam:[]};const{kept:N,spam:C}=Oc(y.results);return{section:{...y,results:N},spam:C}}),b=p.map(y=>y.section),v=p.reduce((y,N)=>y+N.spam.length,0),S=l.kind==="global"&&v>0&&l.onScopeToSpam!==void 0?n.jsx(bg,{count:v,onScopeToSpam:l.onScopeToSpam}):void 0;return b.some(y=>y.results.length>0)?n.jsxs("div",{className:"flex flex-col",children:[m,d,S,b.filter(y=>y.results.length>0).map(y=>n.jsx(Sg,{section:y,query:e,showFolder:x,onSelectResult:o},y.id))]}):n.jsxs("div",{className:"flex flex-col",children:[m,d,S,n.jsxs("div",{className:"px-row-inset py-10 text-center",children:[n.jsxs("p",{className:"text-sm font-medium text-fg",children:["No matches for “",e,"”"]}),n.jsx("p",{className:"mt-1 text-xs text-fg-subtle",children:"Try a different word, or adjust the filters above."})]})]})}function jg({value:e,onChange:t,onClear:s,onCancel:r,filter:a,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:f,tokens:d,chips:m,onRemoveChip:h,scope:g,makeFilter:x,suggest:p,suggestList:b}){const v=n.jsx(Pc,{value:e,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:f,tokens:d,scope:g,makeFilter:x});return n.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx(no,{value:e,onChange:t,onClear:s,chips:m,onRemoveChip:h,globalFocusKey:!1,showClearButton:!1,suggest:p})}),n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Ze,{className:"size-4"}),onClick:r,"aria-label":"Clear and close search",className:"-mr-1 shrink-0"})]}),b,a&&e.trim().length===0?n.jsx(Cl,{...a,children:v}):n.jsx("div",{className:"flex-1 overflow-y-auto",children:v})]})}const kg={queued:{icon:Wa,label:"Queued",className:"text-warning"},sending:{icon:et,label:"Sending…",className:"text-accent-2",spin:!0},sent:{icon:uc,label:"Sent",className:"text-positive"},failed:{icon:ts,label:"Failed",className:"text-danger"},blocked:{icon:Ma,label:"Blocked",className:"text-warning"}};function ji({status:e,iconOnly:t,className:s}){const r=kg[e],a=r.icon;return n.jsxs("span",{className:H("inline-flex items-center gap-1.5 text-xs font-medium",r.className,s),children:[n.jsx(a,{className:H("size-4",r.spin&&"animate-spin")}),!t&&r.label]})}const Cg=(e,t)=>t?"bg-accent-2-soft":e==="failed"?"bg-danger-soft":e==="blocked"?"bg-warning/10":"";function Ng({recipients:e,subject:t,time:s,status:r,error:a,selected:o,onSelect:i,onRetry:l,retrying:u,onEdit:f,onDelete:d,deleting:m}){const h=r==="failed"||r==="blocked";return n.jsxs("div",{className:H("flex items-start gap-3 border-b border-line px-4 py-3 transition-colors hover:bg-surface-raised",Cg(r,o)),children:[n.jsxs("button",{type:"button",...Na,onClick:i,className:"flex flex-1 min-w-0 items-start gap-3 text-left",children:[n.jsx("div",{className:"mt-0.5 shrink-0",children:n.jsx(ji,{status:r,iconOnly:!0})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"truncate text-sm font-medium",children:e}),n.jsx("span",{className:"shrink-0 text-xs text-fg-muted",children:s})]}),n.jsx("div",{className:"truncate text-sm",children:t||"No subject"}),n.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[n.jsx(ji,{status:r}),a&&n.jsxs("span",{className:"truncate text-xs text-fg-muted",children:["— ",a]})]})]})]}),h&&n.jsx("div",{className:"shrink-0",children:n.jsx(Om,{actions:[...r==="failed"&&l?[{label:"Retry sending",iconOnly:!0,icon:n.jsx(Mm,{className:"size-3.5"}),busy:u,onClick:l}]:[],{label:"Edit as draft",iconOnly:!0,icon:n.jsx(rn,{className:"size-3.5"}),onClick:f}],destructive:{label:"Delete message",iconOnly:!0,icon:n.jsx(ct,{className:"size-3.5"}),busy:m,confirm:{prompt:"Delete this message?",confirmLabel:"Delete"},onClick:d}})})]})}const Eg=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia(e);s(r.matches);const a=o=>s(o.matches);return r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[e]),t},Ig=({children:e,onRefresh:t,isRefreshing:s})=>Eg("(min-width: 1024px)")?e:n.jsx(Pf,{onRefresh:t,isPullable:!s,children:e}),Tg=({text:e,html:t,senderName:s,date:r})=>{const[a,o]=c.useState(!1);if(!e&&!t)return null;const i=[s,r].filter(Boolean).join(" on ");return n.jsxs("div",{className:"mt-2 px-3 pb-2",children:[n.jsxs("button",{type:"button",onClick:()=>o(!a),"aria-expanded":a,className:"flex items-center gap-1 text-xs text-fg-muted hover:text-fg transition-colors",children:[a?n.jsx(Dt,{className:"size-3"}):n.jsx(Ns,{className:"size-3"}),i?`${i} wrote:`:"Show quoted text"]}),a&&n.jsx("blockquote",{className:"mt-2 pl-3 border-l-2 border-fg-subtle/30 text-sm text-fg-muted [&_a]:text-accent [&_a]:underline [&_blockquote]:pl-3 [&_blockquote]:border-l-2 [&_blockquote]:border-fg-subtle/30",children:t?n.jsx("div",{dangerouslySetInnerHTML:{__html:t}}):e.split(`
75
+ `).map((l,u)=>n.jsx("p",{className:"min-h-[1.2em]",children:l},u))})]})},Rg=e=>e===1?"message":"messages";function Mg({count:e,onReview:t,onDismiss:s,actionLabel:r="Review & rescue"}){return n.jsx(ss,{tone:"info",variant:"soft",onDismiss:s,children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("p",{className:"flex items-start gap-2 text-sm text-fg",children:[n.jsx(ln,{className:"mt-0.5 size-4 shrink-0 text-positive","aria-hidden":!0}),n.jsxs("span",{children:[n.jsx("span",{className:"font-semibold text-fg",children:`${e} ${Rg(e)} here`})," ","may not be spam — they're from senders we can verify."]})]}),n.jsx(W,{variant:"primary",size:"sm",onClick:t,className:"self-start",children:r})]})})}function Ag({candidate:e,selected:t,onToggle:s,hideSender:r=!1}){const{senderName:a,senderAddress:o,subject:i,snippet:l,trustReason:u,trustSubReason:f,senderTrust:d}=e;return n.jsxs("label",{className:H("flex w-full cursor-pointer items-start gap-3 px-3 py-2.5 text-left transition-colors",r&&"pl-11",t?"bg-positive/10":"bg-surface hover:bg-surface-sunken"),children:[n.jsx(un,{className:"mt-0.5",checked:t,onChange:s,"aria-label":`${t?"Deselect":"Select"} ${r?i:`message from ${a}`}`}),!r&&n.jsx(bt,{name:a,email:o,size:"sm"}),n.jsxs("span",{className:"min-w-0 flex-1",children:[!r&&n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-sm font-medium text-fg",children:a}),d&&n.jsx(Ac,{senderTrust:d,size:"sm"}),n.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:o})]}),n.jsx("span",{className:"block truncate text-sm text-fg-muted",children:i}),n.jsx("span",{className:"block line-clamp-1 text-xs text-fg-subtle",children:l}),!r&&n.jsxs("span",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[n.jsxs(pt,{tone:"positive",children:[n.jsx(ln,{className:"size-3","aria-hidden":!0}),u]}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:f})]})]})]})}const Og=e=>{const t=new Map,s=[];for(const r of e){const a=(r.senderAddress||r.senderName).toLowerCase(),o=t.get(a);if(o){o.messages.push(r);continue}t.set(a,{key:a,senderName:r.senderName,senderAddress:r.senderAddress,trustReason:r.trustReason,trustSubReason:r.trustSubReason,senderTrust:r.senderTrust,messages:[r]}),s.push(a)}return s.map(r=>t.get(r)).sort((r,a)=>a.messages.length-r.messages.length)},Dg=(e,t)=>{const s=e.messages.filter(r=>t.has(r.id)).length;return s===0?"none":s===e.messages.length?"all":"some"},ki=e=>e===1?"message":"messages";function Pg({group:e,selected:t,onToggleGroup:s,onToggleMessage:r}){const[a,o]=c.useState(!1),i=Dg(e,t),l=e.messages.length,u=a?Dt:Ns;return n.jsxs("div",{className:H(i!=="none"?"bg-positive/10":"bg-surface"),children:[n.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-2.5",children:[n.jsx(un,{className:"mt-0.5",checked:i==="all",indeterminate:i==="some",onChange:()=>s(e,i!=="all"),"aria-label":`${i==="all"?"Deselect":"Select"} all ${l} ${ki(l)} from ${e.senderName}`}),n.jsx(bt,{name:e.senderName,email:e.senderAddress,size:"sm"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-sm font-medium text-fg",children:e.senderName}),e.senderTrust&&n.jsx(Ac,{senderTrust:e.senderTrust,size:"sm"}),n.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:e.senderAddress})]}),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[n.jsxs(pt,{tone:"positive",children:[n.jsx(ln,{className:"size-3","aria-hidden":!0}),e.trustReason]}),n.jsx("span",{className:"text-2xs text-fg-subtle",children:e.trustSubReason})]})]}),n.jsxs("button",{type:"button",onClick:()=>o(f=>!f),"aria-expanded":a,className:"flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-2xs text-fg-muted transition-colors hover:bg-surface-sunken hover:text-fg",children:[`${l} ${ki(l)}`,n.jsx(u,{className:"size-3.5","aria-hidden":!0})]})]}),a&&n.jsx("div",{className:"divide-y divide-line border-t border-line",children:e.messages.map(f=>n.jsx(Ag,{candidate:f,selected:t.has(f.id),onToggle:()=>r(f.id),hideSender:!0},f.id))})]})}const ro=e=>e===1?"message":"messages",Lg=(e,t)=>`Moves ${e===1?"this message":`these ${e} ${ro(e)}`} out of Spam to ${t} now. Nothing later.`,fa=(e,t)=>e.find(s=>s.id===t)?.label??"Inbox";function Fg(){return n.jsx(ss,{tone:"info",variant:"soft",children:n.jsx("p",{className:"text-2xs text-fg-muted",children:"We list a message here only when we can confirm the sender is who they say — usually someone you've emailed before, write to often, or a service that consistently checks out. We never guess from words in the subject. Anything we can't confirm stays in Spam."})})}function $g({candidates:e,selected:t,onToggle:s,onToggleGroup:r,onSelectAll:a,onSelectNone:o,onContinue:i,onCancel:l}){const[u,f]=c.useState(!1),d=t.size,m=c.useMemo(()=>Og(e),[e]);return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("h2",{className:"flex items-center gap-2 text-sm font-semibold text-fg",children:[n.jsx(ln,{className:"size-4 text-positive","aria-hidden":!0}),"Rescue from Spam"]}),n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Rm,{className:"size-3.5"}),onClick:()=>f(h=>!h),className:"-mr-1.5 -mt-0.5",children:"Why these?"})]}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"These look safe — from senders we can verify. Uncheck any sender that belongs in Spam, or open a sender to pick individual messages."}),u&&n.jsx("div",{className:"mt-2",children:n.jsx(Fg,{})})]}),n.jsxs("div",{className:"flex items-center justify-between px-row-inset pb-1.5",children:[n.jsx("span",{className:"text-2xs font-medium text-fg-muted",children:`${d} of ${e.length} selected · ${m.length} ${m.length===1?"sender":"senders"}`}),n.jsxs("span",{className:"flex gap-1",children:[n.jsx(W,{variant:"ghost",size:"sm",onClick:a,children:"Select all"}),n.jsx(W,{variant:"ghost",size:"sm",onClick:o,children:"Select none"})]})]}),n.jsx("div",{className:"min-h-0 flex-1 divide-y divide-line overflow-y-auto border-y border-line",children:m.map(h=>n.jsx(Pg,{group:h,selected:t,onToggleGroup:r,onToggleMessage:s},h.key))}),n.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[n.jsx(W,{variant:"primary",onClick:i,className:"h-11 w-full font-semibold",children:`Continue with ${d} ${ro(d)}`}),n.jsx(W,{variant:"ghost",onClick:l,className:"h-11 w-full",children:"Cancel"})]})]})}function _g({count:e,folders:t,destination:s,onPick:r,onMove:a,onBack:o}){const[i,l]=c.useState(!1);return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg",children:"Where should they go?"}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Pick a folder, then we move them out of Spam."})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-row-inset py-2",children:i?n.jsx("div",{className:"overflow-hidden rounded-xl border border-line bg-surface",children:n.jsx(Gl,{mailboxes:t,autoFocus:!0,onSelect:u=>{r(u),l(!1)},onCancel:()=>l(!1)})}):n.jsxs("div",{className:"rounded-xl border border-line bg-surface-sunken p-3",children:[n.jsx("p",{className:"text-2xs text-fg-subtle",children:"Destination"}),n.jsx("p",{className:"mt-0.5 text-sm font-medium text-fg",children:fa(t,s)}),n.jsx(W,{variant:"ghost",size:"sm",onClick:()=>l(!0),className:"mt-2 px-0",children:"Move to a different folder"})]})}),n.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[n.jsx("p",{className:"text-2xs text-fg-subtle",children:Lg(e,fa(t,s))}),n.jsx(W,{variant:"primary",onClick:a,className:"h-11 w-full font-semibold",children:`Move ${e} out of Spam`}),n.jsx(W,{variant:"ghost",onClick:o,className:"h-11 w-full",children:"Back"})]})]})}function zg({count:e,destinationLabel:t,onClose:s}){return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 px-row-inset py-10 text-center",children:[n.jsx(cr,{className:"size-10 text-positive","aria-hidden":!0}),n.jsx("p",{className:"text-base font-semibold text-fg",children:`Moved ${e} ${ro(e)} out of Spam.`}),n.jsx("p",{className:"text-2xs text-fg-subtle",children:`You'll find them in ${t}.`})]}),n.jsx("div",{className:"border-t border-line bg-surface px-row-inset py-3",children:n.jsx(W,{variant:"primary",onClick:s,className:"h-11 w-full font-semibold",children:"Done"})})]})}function Bg({open:e,candidates:t,defaultDestinationId:s,availableFolders:r,onConfirmMove:a,onCancel:o}){const[i,l]=c.useState("review"),[u,f]=c.useState(()=>e?new Set(t.map(w=>w.id)):new Set),[d,m]=c.useState(s),[h,g]=c.useState(0),x=c.useRef(!1);c.useEffect(()=>{e&&!x.current&&(l("review"),f(new Set(t.map(w=>w.id))),m(s),g(0)),x.current=e},[e,t,s]);const p=u.size,b=w=>{f(y=>{const N=new Set(y);return N.has(w)?N.delete(w):N.add(w),N})},v=(w,y)=>{f(N=>{const C=new Set(N);for(const E of w.messages)y?C.add(E.id):C.delete(E.id);return C})},S=()=>{const w=Array.from(u);g(w.length),a(w,d),l("done")};return n.jsxs(Bl,{open:e,onClose:o,dismissLabel:"Close rescue",children:[i==="review"&&n.jsx($g,{candidates:t,selected:u,onToggle:b,onToggleGroup:v,onSelectAll:()=>f(new Set(t.map(w=>w.id))),onSelectNone:()=>f(new Set),onContinue:()=>l("destination"),onCancel:o}),i==="destination"&&n.jsx(_g,{count:p,folders:r,destination:d,onPick:m,onMove:S,onBack:()=>l("review")}),i==="done"&&n.jsx(zg,{count:h,destinationLabel:fa(r,d),onClose:o})]})}function Kg(e){return e.scopedOutFolder!==void 0||(e.droppedFacets?.length??0)>0||e.droppedSemantic===!0}function Ug(e){return`Your search was limited to ${e}. This filter matches these messages in any folder — it can't be pinned to one.`}const qg=e=>e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`;function Hg(e){const t=e.length===1?"a filter condition":"filter conditions",s=e.length===1?"isn't":"aren't";return`${qg(e)} ${s} ${t}, so ${e.length===1?"it was":"they were"} left out — the filter still matches everything else you searched for.`}const Wg="The filter matches these words literally. Your search also found similar mail by meaning — a filter can't carry that, so it won't catch mail that means the same thing without these words.";function Kr({icon:e,children:t}){return n.jsxs("li",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"mt-0.5 shrink-0 text-fg-subtle","aria-hidden":"true",children:e}),n.jsx("span",{children:t})]})}function Vg({notice:e}){return Kg(e)?n.jsxs("div",{className:"rounded-md border border-line bg-surface-sunken px-3 py-2.5",children:[n.jsx("p",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"From your search"}),n.jsxs("ul",{className:"mt-1.5 space-y-1.5 text-xs text-fg-muted",children:[e.scopedOutFolder!==void 0&&n.jsx(Kr,{icon:n.jsx(Ya,{className:"size-3.5"}),children:Ug(e.scopedOutFolder)}),e.droppedFacets&&e.droppedFacets.length>0&&n.jsx(Kr,{icon:n.jsx(Ia,{className:"size-3.5"}),children:Hg(e.droppedFacets)}),e.droppedSemantic&&n.jsx(Kr,{icon:n.jsx(xt,{className:"size-3.5"}),children:Wg})]})]}):null}const Ci=e=>e.toLocaleString(),xs=56,Qg=70,Yg=320,Gg=320,Xg="cubic-bezier(0.32, 0.9, 0.3, 1)",Jg=.5;function En(e){return Math.sign(e)*Math.sqrt(Math.abs(e))*4}function Zg({expanded:e,delta:t,velocity:s,expandedHeight:r,teaserHeight:a,flickVelocity:o=Jg}){if(Math.abs(s)>o)return s<0;const i=(r-a)/2;return e?t<i:t<-i}function Lc({count:e,mode:t="idle",onCancel:s,onDelete:r,onJunk:a,onMarkRead:o,onSelectSimilar:i,onSomethingElse:l,moveSlot:u,isBusy:f=!1,selectAll:d,statusLabel:m,progress:h,notice:g,startExpanded:x=!1}){const[p,b]=c.useState(x),v=c.useRef(null),[S,w]=c.useState(Yg),y=t==="counting"||t==="running";c.useEffect(()=>{y&&b(!0)},[y]),c.useLayoutEffect(()=>{const $=v.current;if(!$)return;const V=()=>w($.offsetHeight);V();const ne=new ResizeObserver(V);return ne.observe($),()=>ne.disconnect()},[]);const[N,C]=c.useState(null),E=c.useRef(null),I=c.useRef(!1),O=c.useCallback($=>{y||($.currentTarget.setPointerCapture($.pointerId),E.current={startY:$.clientY,lastY:$.clientY,lastT:$.timeStamp,velocity:0},I.current=!1,C(0))},[y]),A=c.useCallback($=>{const V=E.current;if(!V)return;const ne=$.timeStamp-V.lastT;ne>0&&(V.velocity=($.clientY-V.lastY)/ne),V.lastY=$.clientY,V.lastT=$.timeStamp;const re=$.clientY-V.startY;Math.abs(re)>4&&(I.current=!0);const q=S-xs,Q=p?re<0?En(re):Math.min(re,q+En(Math.max(0,re-q))):re>0?En(re):Math.max(re,-q+En(Math.min(0,re+q)));C(Q)},[p,S]),M=c.useCallback(()=>{const $=E.current;E.current=null,$&&(C(null),b(Zg({expanded:p,delta:$.lastY-$.startY,velocity:$.velocity,expandedHeight:S,teaserHeight:xs})))},[p,S]),P=S-xs,R=p?0:P,j=N!==null,F=R+(N??0),D=j?"none":`transform ${Gg}ms ${Xg}`,k=d?.checked?`All ${Ci(e)} loaded selected`:`${Ci(e)} ${e===1?"message":"messages"} selected`,L=t==="idle"||t==="escalated",T=t==="idle";return n.jsxs("div",{ref:v,"data-selection-sheet":"",className:"absolute inset-x-0 bottom-0 z-30 flex select-none flex-col rounded-t-2xl border-t border-line bg-surface shadow-2xl shadow-black/40",style:{maxHeight:`${Qg}dvh`,minHeight:`${xs}px`,transform:`translateY(${F}px)`,transition:D},children:[n.jsxs("div",{role:"slider","aria-label":p?"Collapse selection actions":"Expand selection actions","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":p?1:0,tabIndex:0,onPointerDown:O,onPointerMove:A,onPointerUp:M,onPointerCancel:M,onClick:()=>{if(I.current){I.current=!1;return}!j&&!y&&b($=>!$)},className:H("flex touch-none flex-col items-center pt-2",y?"":"cursor-grab active:cursor-grabbing"),children:[n.jsx("div",{className:"mb-1.5 h-1 w-10 rounded-full bg-fg-subtle/40"}),n.jsxs("div",{className:"flex w-full items-center gap-2 px-4 pb-3",children:[n.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",role:"status","aria-live":"polite",children:m??k}),p?n.jsxs(n.Fragment,{children:[o&&!f&&t!=="counting"&&n.jsx(W,{variant:"ghost",size:"touch",icon:n.jsx(Rs,{className:"size-4"}),onPointerDown:$=>$.stopPropagation(),onClick:$=>{$.stopPropagation(),o()},"aria-label":"Mark as read",className:"-my-2 shrink-0"}),n.jsx(W,{variant:"ghost",size:"touch",icon:n.jsx(Ze,{className:"size-4"}),onPointerDown:$=>$.stopPropagation(),onClick:$=>{$.stopPropagation(),s()},"aria-label":"Cancel selection",className:"-my-2 -mr-2 shrink-0"})]}):n.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-xs text-fg-subtle",children:[n.jsx("span",{children:"Swipe up for actions"}),n.jsx(Ph,{className:"size-4"})]})]})]}),n.jsxs("div",{inert:p?void 0:!0,className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-4 pb-4",children:[h&&n.jsx("div",{className:"mb-3",children:n.jsx(so,{value:h.value,max:h.max,tone:h.tone})}),d&&t!=="running"&&n.jsxs("label",{className:"mb-3 flex min-h-11 cursor-pointer items-center gap-3 text-sm font-medium text-fg-muted",children:[n.jsx(un,{"aria-label":"Select all",checked:d.checked,indeterminate:d.indeterminate,onChange:d.onChange}),"Select all loaded"]}),L&&n.jsxs("div",{className:"mb-3 flex items-stretch justify-around gap-1 border-b border-line pb-3",children:[n.jsx(W,{variant:"ghost",onClick:r,icon:f?n.jsx(et,{className:"size-5 animate-spin"}):n.jsx(ct,{className:"size-5 text-danger"}),"aria-label":"Move selected messages to Trash","aria-busy":f||void 0,className:"h-auto flex-1 flex-col gap-1 px-0 py-1.5 text-[11px]",children:"Delete"}),u&&n.jsxs("div",{className:"flex flex-1 flex-col items-center gap-1",children:[u,n.jsx("span",{"aria-hidden":"true",className:"text-[11px] text-fg-muted",children:"Move"})]}),a&&n.jsx(W,{variant:"ghost",onClick:a,icon:n.jsx(Ms,{className:"size-5"}),"aria-label":"Move selected messages to Junk",className:"h-auto flex-1 flex-col gap-1 px-0 py-1.5 text-[11px]",children:"Junk"})]}),T&&(i||l)&&n.jsxs("div",{className:"flex flex-col gap-2",children:[i&&n.jsxs(W,{variant:"primary",onClick:i,className:"h-auto flex-col items-start gap-0 px-4 py-2.5 text-left",children:[n.jsx("span",{className:"text-sm font-semibold leading-tight",children:"Select similar messages"}),n.jsx("span",{className:"text-xs opacity-80",children:"find more like these"})]}),l&&n.jsxs(W,{variant:"secondary",onClick:l,className:"h-auto flex-col items-start gap-0 px-4 py-2.5 text-left",children:[n.jsx("span",{className:"text-sm font-medium leading-tight",children:"Something else"}),n.jsx("span",{className:"text-xs text-fg-subtle",children:"just deal with these"})]})]}),g&&n.jsx(ss,{tone:g.tone,variant:"soft",role:"status","aria-live":"polite",className:H(L||h?"mt-1":"mt-0"),children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.text&&n.jsx("span",{children:g.text}),g.action&&n.jsx(W,{variant:"ghost",size:"md",onClick:g.action.onClick,className:"-my-1 min-h-11 shrink-0",children:g.action.label})]})})]})]})}const ao=[{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"}],Fc={id:"unread",label:"Unread"},ex={id:"flagged",label:"Starred"},$c={id:"attachment",label:"Has attachment"};function tx(e){if(!(e.length<=1))return e.map(t=>({id:t.id,label:t.label,count:t.count,active:t.active}))}function sx(e=[]){return{categories:[...ao],filters:Lf,sources:tx(e)}}function _c(){return{categories:[...ao],filters:[Fc,ex,$c]}}function nx(){return{categories:[...ao],filters:[Fc,$c]}}function Ot(e,t,{checkForDefaultPrevented:s=!0}={}){return function(a){if(e?.(a),s===!1||!a||!a.defaultPrevented)return t?.(a)}}function Ni(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function rx(...e){return t=>{let s=!1;const r=e.map(a=>{const o=Ni(a,t);return!s&&typeof o=="function"&&(s=!0),o});if(s)return()=>{for(let a=0;a<r.length;a++){const o=r[a];typeof o=="function"?o():Ni(e[a],null)}}}}function as(...e){return c.useCallback(rx(...e),e)}function ax(e,t=[]){let s=[];function r(o,i){const l=c.createContext(i);l.displayName=o+"Context";const u=s.length;s=[...s,i];const f=m=>{const{scope:h,children:g,...x}=m,p=h?.[e]?.[u]||l,b=c.useMemo(()=>x,Object.values(x));return n.jsx(p.Provider,{value:b,children:g})};f.displayName=o+"Provider";function d(m,h,g={}){const{optional:x=!1}=g,p=h?.[e]?.[u]||l,b=c.useContext(p);if(b)return b;if(i!==void 0)return i;if(!x)throw new Error(`\`${m}\` must be used within \`${o}\``)}return[f,d]}const a=()=>{const o=s.map(i=>c.createContext(i));return function(l){const u=l?.[e]||o;return c.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return a.scopeName=e,[r,ox(a,...t)]}function ox(...e){const t=e[0];if(e.length===1)return t;const s=()=>{const r=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(o){const i=r.reduce((l,{useScope:u,scopeName:f})=>{const m=u(o)[`__scope${f}`];return{...l,...m}},{});return c.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return s.scopeName=t.scopeName,s}var en=globalThis?.document?c.useLayoutEffect:()=>{},ix=Aa[" useInsertionEffect ".trim().toString()]||en;function lx({prop:e,defaultProp:t,onChange:s=()=>{},caller:r}){const[a,o,i]=cx({defaultProp:t,onChange:s}),l=e!==void 0,u=l?e:a;{const d=c.useRef(e!==void 0);c.useEffect(()=>{const m=d.current;m!==l&&console.warn(`${r} is changing from ${m?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=l},[l,r])}const f=c.useCallback(d=>{if(l){const m=ux(d)?d(e):d;m!==e&&i.current?.(m)}else o(d)},[l,e,o,i]);return[u,f]}function cx({defaultProp:e,onChange:t}){const[s,r]=c.useState(e),a=c.useRef(s),o=c.useRef(t);return ix(()=>{o.current=t},[t]),c.useEffect(()=>{a.current!==s&&(o.current?.(s),a.current=s)},[s,a]),[s,r,o]}function ux(e){return typeof e=="function"}function oo(e){const t=c.forwardRef((s,r)=>{let{children:a,...o}=s,i=null,l=!1;const u=[];Ei(a)&&typeof In=="function"&&(a=In(a._payload)),c.Children.forEach(a,h=>{if(px(h)){l=!0;const g=h;let x="child"in g.props?g.props.child:g.props.children;Ei(x)&&typeof In=="function"&&(x=In(x._payload)),i=fx(g,x),u.push(i?.props?.children)}else u.push(h)}),i?i=c.cloneElement(i,void 0,u):!l&&c.Children.count(a)===1&&c.isValidElement(a)&&(i=a);const f=i?hx(i):void 0,d=as(r,f);if(!i){if(a||a===0)throw new Error(l?vx(e):bx(e));return a}const m=mx(o,i.props??{});return i.type!==c.Fragment&&(m.ref=r?d:f),c.cloneElement(i,m)});return t.displayName=`${e}.Slot`,t}var rC=oo("Slot"),dx=Symbol.for("radix.slottable"),fx=(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 mx(e,t){const s={...t};for(const r in t){const a=e[r],o=t[r];/^on[A-Z]/.test(r)?a&&o?s[r]=(...l)=>{const u=o(...l);return a(...l),u}:a&&(s[r]=a):r==="style"?s[r]={...a,...o}:r==="className"&&(s[r]=[a,o].filter(Boolean).join(" "))}return{...e,...s}}function hx(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 px(e){return c.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===dx}var gx=Symbol.for("react.lazy");function Ei(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===gx&&"_payload"in e&&xx(e._payload)}function xx(e){return typeof e=="object"&&e!==null&&"then"in e}var bx=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,vx=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,In=Aa[" use ".trim().toString()],yx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],kt=yx.reduce((e,t)=>{const s=oo(`Primitive.${t}`),r=c.forwardRef((a,o)=>{const{asChild:i,...l}=a,u=i?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),n.jsx(u,{...l,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function wx(e,t){e&&Oa.flushSync(()=>e.dispatchEvent(t))}function tn(e){const t=c.useRef(e);return c.useEffect(()=>{t.current=e}),c.useMemo(()=>((...s)=>t.current?.(...s)),[])}var Sx="DismissableLayer",ma="dismissableLayer.update",jx="dismissableLayer.pointerDownOutside",kx="dismissableLayer.focusOutside",Ii,io=c.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),zc=c.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:l,onDismiss:u,...f}=e,d=c.useContext(io),[m,h]=c.useState(null),g=m?.ownerDocument??globalThis?.document,[,x]=c.useState({}),p=as(t,h),b=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),S=v?b.indexOf(v):-1,w=m?b.indexOf(m):-1,y=d.layersWithOutsidePointerEventsDisabled.size>0,N=w>=S,C=c.useRef(!1),E=Tx(M=>{o?.(M),l?.(M),M.defaultPrevented||u?.()},{ownerDocument:g,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:C,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:c.useCallback(M=>{if(!(M instanceof Node))return!1;const P=[...d.branches].some(R=>R.contains(M));return N&&!P},[d.branches,N])}),I=Rx(M=>{if(r&&C.current)return;const P=M.target;[...d.branches].some(j=>j.contains(P))||(i?.(M),l?.(M),M.defaultPrevented||u?.())},g),O=m?w===b.length-1:!1,A=tn(M=>{M.key==="Escape"&&(a?.(M),!M.defaultPrevented&&u&&(M.preventDefault(),u()))});return c.useEffect(()=>{if(O)return g.addEventListener("keydown",A,{capture:!0}),()=>g.removeEventListener("keydown",A,{capture:!0})},[g,O,A]),c.useEffect(()=>{if(m)return s&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Ii=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(m)),d.layers.add(m),Ti(),()=>{s&&(d.layersWithOutsidePointerEventsDisabled.delete(m),d.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=Ii))}},[m,g,s,d]),c.useEffect(()=>()=>{m&&(d.layers.delete(m),d.layersWithOutsidePointerEventsDisabled.delete(m),Ti())},[m,d]),c.useEffect(()=>{const M=()=>x({});return document.addEventListener(ma,M),()=>document.removeEventListener(ma,M)},[]),n.jsx(kt.div,{...f,ref:p,style:{pointerEvents:y?N?"auto":"none":void 0,...e.style},onFocusCapture:Ot(e.onFocusCapture,I.onFocusCapture),onBlurCapture:Ot(e.onBlurCapture,I.onBlurCapture),onPointerDownCapture:Ot(e.onPointerDownCapture,E.onPointerDownCapture)})});zc.displayName=Sx;var Cx="DismissableLayerBranch",Nx=c.forwardRef((e,t)=>{const s=c.useContext(io),r=c.useRef(null),a=as(t,r);return c.useEffect(()=>{const o=r.current;if(o)return s.branches.add(o),()=>{s.branches.delete(o)}},[s.branches]),n.jsx(kt.div,{...e,ref:a})});Nx.displayName=Cx;function Ex(){const e=c.useContext(io),[t,s]=c.useState(null);return c.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),s}var Ix=()=>!0;function Tx(e,t){const{ownerDocument:s=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:o,shouldHandlePointerDownOutside:i=Ix}=t,l=tn(e),u=c.useRef(!1),f=c.useRef(!1),d=c.useRef(new Map),m=c.useRef(()=>{});return c.useEffect(()=>{function h(){f.current=!1,a.current=!1,d.current.clear()}function g(){return Array.from(d.current.values()).some(Boolean)}function x(w){if(!f.current)return;const y=w.target;y instanceof Node&&[...o].some(C=>C.contains(y))||d.current.set(w.type,!0),w.type==="click"&&window.setTimeout(()=>{f.current&&m.current()},0)}function p(w){f.current&&d.current.set(w.type,!1)}const b=w=>{if(w.target&&!u.current){let y=function(){s.removeEventListener("click",m.current);const C=g();h(),C||Bc(jx,l,N,{discrete:!0})};if(!i(w.target)){s.removeEventListener("click",m.current),h(),u.current=!1;return}const N={originalEvent:w};f.current=!0,a.current=r&&w.button===0,d.current.clear(),!r||w.button!==0?y():(s.removeEventListener("click",m.current),m.current=y,s.addEventListener("click",m.current,{once:!0}))}else s.removeEventListener("click",m.current),h();u.current=!1},v=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const w of v)s.addEventListener(w,x,!0),s.addEventListener(w,p);const S=window.setTimeout(()=>{s.addEventListener("pointerdown",b)},0);return()=>{window.clearTimeout(S),s.removeEventListener("pointerdown",b),s.removeEventListener("click",m.current);for(const w of v)s.removeEventListener(w,x,!0),s.removeEventListener(w,p)}},[s,l,r,a,o,i]),{onPointerDownCapture:()=>u.current=!0}}function Rx(e,t=globalThis?.document){const s=tn(e),r=c.useRef(!1);return c.useEffect(()=>{const a=o=>{o.target&&!r.current&&Bc(kx,s,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,s]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Ti(){const e=new CustomEvent(ma);document.dispatchEvent(e)}function Bc(e,t,s,{discrete:r}){const a=s.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:s});t&&a.addEventListener(e,t,{once:!0}),r?wx(a,o):a.dispatchEvent(o)}var Tn=0,us=null;function Mx(){c.useEffect(()=>{us||(us={start:Ri(),end:Ri()});const{start:e,end:t}=us;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Tn++,()=>{Tn===1&&(us?.start.remove(),us?.end.remove(),us=null),Tn=Math.max(0,Tn-1)}},[])}function Ri(){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 Ur="focusScope.autoFocusOnMount",qr="focusScope.autoFocusOnUnmount",Mi={bubbles:!1,cancelable:!0},Ax="FocusScope",Kc=c.forwardRef((e,t)=>{const{loop:s=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[l,u]=c.useState(null),f=tn(a),d=tn(o),m=c.useRef(null),h=as(t,u),g=c.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;c.useEffect(()=>{if(r){let p=function(w){if(g.paused||!l)return;const y=w.target;l.contains(y)?m.current=y:Tt(m.current,{select:!0})},b=function(w){if(g.paused||!l)return;const y=w.relatedTarget;y!==null&&(l.contains(y)||Tt(m.current,{select:!0}))},v=function(w){if(document.activeElement===document.body)for(const N of w)N.removedNodes.length>0&&Tt(l)};document.addEventListener("focusin",p),document.addEventListener("focusout",b);const S=new MutationObserver(v);return l&&S.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",b),S.disconnect()}}},[r,l,g.paused]),c.useEffect(()=>{if(l){Oi.add(g);const p=document.activeElement;if(!l.contains(p)){const v=new CustomEvent(Ur,Mi);l.addEventListener(Ur,f),l.dispatchEvent(v),v.defaultPrevented||(Ox($x(Uc(l)),{select:!0}),document.activeElement===p&&Tt(l))}return()=>{l.removeEventListener(Ur,f),setTimeout(()=>{const v=new CustomEvent(qr,Mi);l.addEventListener(qr,d),l.dispatchEvent(v),v.defaultPrevented||Tt(p??document.body,{select:!0}),l.removeEventListener(qr,d),Oi.remove(g)},0)}}},[l,f,d,g]);const x=c.useCallback(p=>{if(!s&&!r||g.paused)return;const b=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,v=document.activeElement;if(b&&v){const S=p.currentTarget,[w,y]=Dx(S);w&&y?!p.shiftKey&&v===y?(p.preventDefault(),s&&Tt(w,{select:!0})):p.shiftKey&&v===w&&(p.preventDefault(),s&&Tt(y,{select:!0})):v===S&&p.preventDefault()}},[s,r,g.paused]);return n.jsx(kt.div,{tabIndex:-1,...i,ref:h,onKeyDown:x})});Kc.displayName=Ax;function Ox(e,{select:t=!1}={}){const s=document.activeElement;for(const r of e)if(Tt(r,{select:t}),document.activeElement!==s)return}function Dx(e){const t=Uc(e),s=Ai(t,e),r=Ai(t.reverse(),e);return[s,r]}function Uc(e){const t=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)t.push(s.currentNode);return t}function Ai(e,t){const s=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(s?!r.checkVisibility({checkVisibilityCSS:!0}):Px(r,{upTo:t})))return r}function Px(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 Lx(e){return e instanceof HTMLInputElement&&"select"in e}function Tt(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&Lx(e)&&t&&e.select()}}var Oi=Fx();function Fx(){let e=[];return{add(t){const s=e[0];t!==s&&s?.pause(),e=Di(e,t),e.unshift(t)},remove(t){e=Di(e,t),e[0]?.resume()}}}function Di(e,t){const s=[...e],r=s.indexOf(t);return r!==-1&&s.splice(r,1),s}function $x(e){return e.filter(t=>t.tagName!=="A")}var _x=Aa[" useId ".trim().toString()]||(()=>{}),zx=0;function Hr(e){const[t,s]=c.useState(_x());return en(()=>{s(r=>r??String(zx++))},[e]),e||(t?`radix-${t}`:"")}var Bx="Portal",qc=c.forwardRef((e,t)=>{const{container:s,...r}=e,[a,o]=c.useState(!1);en(()=>o(!0),[]);const i=s||a&&globalThis?.document?.body;return i?Oa.createPortal(n.jsx(kt.div,{...r,ref:t}),i):null});qc.displayName=Bx;function Kx(e,t){return c.useReducer((s,r)=>t[s][r]??s,e)}var mr=e=>{const{present:t,children:s}=e,r=Ux(t),a=typeof s=="function"?s({present:r.isPresent}):c.Children.only(s),o=qx(r.ref,Hx(a));return typeof s=="function"||r.isPresent?c.cloneElement(a,{ref:o}):null};mr.displayName="Presence";function Ux(e){const[t,s]=c.useState(),r=c.useRef(null),a=c.useRef(e),o=c.useRef("none"),i=c.useRef(void 0),l=e?"mounted":"unmounted",[u,f]=Kx(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??Us(r.current),i.current=void 0):o.current="none"},[u]),en(()=>{const d=r.current,m=a.current;if(m!==e){const g=o.current,x=Us(d);e?(i.current=x,f("MOUNT")):x==="none"||d?.display==="none"?f("UNMOUNT"):f(m&&g!==x?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,f]),en(()=>{if(t){let d;const m=t.ownerDocument.defaultView??window,h=x=>{const b=Us(r.current).includes(CSS.escape(x.animationName));if(x.target===t&&b&&(f("ANIMATION_END"),!a.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",d=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},g=x=>{x.target===t&&(o.current=Us(r.current))};return t.addEventListener("animationstart",g),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{m.clearTimeout(d),t.removeEventListener("animationstart",g),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else f("ANIMATION_END")},[t,f]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:c.useCallback(d=>{if(d){const m=getComputedStyle(d);r.current=m,i.current=Us(m)}else r.current=null;s(d)},[])}}function Pi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function qx(...e){const t=c.useRef(e);return t.current=e,c.useCallback(s=>{const r=t.current;let a=!1;const o=r.map(i=>{const l=Pi(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():Pi(r[i],null)}}},[])}function Us(e){return e?.animationName||"none"}function Hx(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 Wx=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},ds=new WeakMap,Rn=new WeakMap,Mn={},Wr=0,Hc=function(e){return e&&(e.host||Hc(e.parentNode))},Vx=function(e,t){return t.map(function(s){if(e.contains(s))return s;var r=Hc(s);return r&&e.contains(r)?r:(console.error("aria-hidden",s,"in not contained inside",e,". Doing nothing"),null)}).filter(function(s){return!!s})},Qx=function(e,t,s,r){var a=Vx(t,Array.isArray(e)?e:[e]);Mn[s]||(Mn[s]=new WeakMap);var o=Mn[s],i=[],l=new Set,u=new Set(a),f=function(m){!m||l.has(m)||(l.add(m),f(m.parentNode))};a.forEach(f);var d=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(h){if(l.has(h))d(h);else try{var g=h.getAttribute(r),x=g!==null&&g!=="false",p=(ds.get(h)||0)+1,b=(o.get(h)||0)+1;ds.set(h,p),o.set(h,b),i.push(h),p===1&&x&&Rn.set(h,!0),b===1&&h.setAttribute(s,"true"),x||h.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",h,v)}})};return d(t),l.clear(),Wr++,function(){i.forEach(function(m){var h=ds.get(m)-1,g=o.get(m)-1;ds.set(m,h),o.set(m,g),h||(Rn.has(m)||m.removeAttribute(r),Rn.delete(m)),g||m.removeAttribute(s)}),Wr--,Wr||(ds=new WeakMap,ds=new WeakMap,Rn=new WeakMap,Mn={})}},Yx=function(e,t,s){s===void 0&&(s="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),a=Wx(e);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live], script"))),Qx(r,a,s,"aria-hidden")):function(){return null}},zn="right-scroll-bar-position",Bn="width-before-scroll-bar",Gx="with-scroll-bars-hidden",Xx="--removed-body-scroll-bar-size";function Vr(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Jx(e,t){var s=c.useState(function(){return{value:e,callback:t,facade:{get current(){return s.value},set current(r){var a=s.value;a!==r&&(s.value=r,s.callback(r,a))}}}})[0];return s.callback=t,s.facade}var Zx=typeof window<"u"?c.useLayoutEffect:c.useEffect,Li=new WeakMap;function eb(e,t){var s=Jx(null,function(r){return e.forEach(function(a){return Vr(a,r)})});return Zx(function(){var r=Li.get(s);if(r){var a=new Set(r),o=new Set(e),i=s.current;a.forEach(function(l){o.has(l)||Vr(l,null)}),o.forEach(function(l){a.has(l)||Vr(l,i)})}Li.set(s,e)},[e]),s}function tb(e){return e}function sb(e,t){t===void 0&&(t=tb);var s=[],r=!1,a={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return s.length?s[s.length-1]:e},useMedium:function(o){var i=t(o,r);return s.push(i),function(){s=s.filter(function(l){return l!==i})}},assignSyncMedium:function(o){for(r=!0;s.length;){var i=s;s=[],i.forEach(o)}s={push:function(l){return o(l)},filter:function(){return s}}},assignMedium:function(o){r=!0;var i=[];if(s.length){var l=s;s=[],l.forEach(o),i=s}var u=function(){var d=i;i=[],d.forEach(o)},f=function(){return Promise.resolve().then(u)};f(),s={push:function(d){i.push(d),f()},filter:function(d){return i=i.filter(d),s}}}};return a}function nb(e){e===void 0&&(e={});var t=sb(null);return t.options=Rt({async:!0,ssr:!1},e),t}var Wc=function(e){var t=e.sideCar,s=Nl(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return c.createElement(r,Rt({},s))};Wc.isSideCarExport=!0;function rb(e,t){return e.useMedium(t),Wc}var Vc=nb(),Qr=function(){},hr=c.forwardRef(function(e,t){var s=c.useRef(null),r=c.useState({onScrollCapture:Qr,onWheelCapture:Qr,onTouchMoveCapture:Qr}),a=r[0],o=r[1],i=e.forwardProps,l=e.children,u=e.className,f=e.removeScrollBar,d=e.enabled,m=e.shards,h=e.sideCar,g=e.noRelative,x=e.noIsolation,p=e.inert,b=e.allowPinchZoom,v=e.as,S=v===void 0?"div":v,w=e.gapMode,y=Nl(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),N=h,C=eb([s,t]),E=Rt(Rt({},y),a);return c.createElement(c.Fragment,null,d&&c.createElement(N,{sideCar:Vc,removeScrollBar:f,shards:m,noRelative:g,noIsolation:x,inert:p,setCallbacks:o,allowPinchZoom:!!b,lockRef:s,gapMode:w}),i?c.cloneElement(c.Children.only(l),Rt(Rt({},E),{ref:C})):c.createElement(S,Rt({},E,{className:u,ref:C}),l))});hr.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};hr.classNames={fullWidth:Bn,zeroRight:zn};var ab=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function ob(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=ab();return t&&e.setAttribute("nonce",t),e}function ib(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function lb(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var cb=function(){var e=0,t=null;return{add:function(s){e==0&&(t=ob())&&(ib(t,s),lb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},ub=function(){var e=cb();return function(t,s){c.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},Qc=function(){var e=ub(),t=function(s){var r=s.styles,a=s.dynamic;return e(r,a),null};return t},db={left:0,top:0,right:0,gap:0},Yr=function(e){return parseInt(e||"",10)||0},fb=function(e){var t=window.getComputedStyle(document.body),s=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return[Yr(s),Yr(r),Yr(a)]},mb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return db;var t=fb(e),s=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-s+t[2]-t[0])}},hb=Qc(),Ss="data-scroll-locked",pb=function(e,t,s,r){var a=e.left,o=e.top,i=e.right,l=e.gap;return s===void 0&&(s="margin"),`
76
+ .`.concat(Gx,` {
77
+ overflow: hidden `).concat(r,`;
78
+ padding-right: `).concat(l,"px ").concat(r,`;
79
+ }
80
+ body[`).concat(Ss,`] {
81
+ overflow: hidden `).concat(r,`;
82
+ overscroll-behavior: contain;
83
+ `).concat([t&&"position: relative ".concat(r,";"),s==="margin"&&`
84
+ padding-left: `.concat(a,`px;
85
+ padding-top: `).concat(o,`px;
86
+ padding-right: `).concat(i,`px;
87
+ margin-left:0;
88
+ margin-top:0;
89
+ margin-right: `).concat(l,"px ").concat(r,`;
90
+ `),s==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),`
91
+ }
92
+
93
+ .`).concat(zn,` {
94
+ right: `).concat(l,"px ").concat(r,`;
95
+ }
96
+
97
+ .`).concat(Bn,` {
98
+ margin-right: `).concat(l,"px ").concat(r,`;
99
+ }
100
+
101
+ .`).concat(zn," .").concat(zn,` {
102
+ right: 0 `).concat(r,`;
103
+ }
104
+
105
+ .`).concat(Bn," .").concat(Bn,` {
106
+ margin-right: 0 `).concat(r,`;
107
+ }
108
+
109
+ body[`).concat(Ss,`] {
110
+ `).concat(Xx,": ").concat(l,`px;
111
+ }
112
+ `)},Fi=function(){var e=parseInt(document.body.getAttribute(Ss)||"0",10);return isFinite(e)?e:0},gb=function(){c.useEffect(function(){return document.body.setAttribute(Ss,(Fi()+1).toString()),function(){var e=Fi()-1;e<=0?document.body.removeAttribute(Ss):document.body.setAttribute(Ss,e.toString())}},[])},xb=function(e){var t=e.noRelative,s=e.noImportant,r=e.gapMode,a=r===void 0?"margin":r;gb();var o=c.useMemo(function(){return mb(a)},[a]);return c.createElement(hb,{styles:pb(o,!t,a,s?"":"!important")})},ha=!1;if(typeof window<"u")try{var An=Object.defineProperty({},"passive",{get:function(){return ha=!0,!0}});window.addEventListener("test",An,An),window.removeEventListener("test",An,An)}catch{ha=!1}var fs=ha?{passive:!1}:!1,bb=function(e){return e.tagName==="TEXTAREA"},Yc=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!bb(e)&&s[t]==="visible")},vb=function(e){return Yc(e,"overflowY")},yb=function(e){return Yc(e,"overflowX")},$i=function(e,t){var s=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=Gc(e,r);if(a){var o=Xc(e,r),i=o[1],l=o[2];if(i>l)return!0}r=r.parentNode}while(r&&r!==s.body);return!1},wb=function(e){var t=e.scrollTop,s=e.scrollHeight,r=e.clientHeight;return[t,s,r]},Sb=function(e){var t=e.scrollLeft,s=e.scrollWidth,r=e.clientWidth;return[t,s,r]},Gc=function(e,t){return e==="v"?vb(t):yb(t)},Xc=function(e,t){return e==="v"?wb(t):Sb(t)},jb=function(e,t){return e==="h"&&t==="rtl"?-1:1},kb=function(e,t,s,r,a){var o=jb(e,window.getComputedStyle(t).direction),i=o*r,l=s.target,u=t.contains(l),f=!1,d=i>0,m=0,h=0;do{if(!l)break;var g=Xc(e,l),x=g[0],p=g[1],b=g[2],v=p-b-o*x;(x||v)&&Gc(e,l)&&(m+=v,h+=x);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(d&&Math.abs(m)<1||!d&&Math.abs(h)<1)&&(f=!0),f},On=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},_i=function(e){return[e.deltaX,e.deltaY]},zi=function(e){return e&&"current"in e?e.current:e},Cb=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Nb=function(e){return`
113
+ .block-interactivity-`.concat(e,` {pointer-events: none;}
114
+ .allow-interactivity-`).concat(e,` {pointer-events: all;}
115
+ `)},Eb=0,ms=[];function Ib(e){var t=c.useRef([]),s=c.useRef([0,0]),r=c.useRef(),a=c.useState(Eb++)[0],o=c.useState(Qc)[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=Ff([e.lockRef.current],(e.shards||[]).map(zi),!0).filter(Boolean);return p.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=c.useCallback(function(p,b){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var v=On(p),S=s.current,w="deltaX"in p?p.deltaX:S[0]-v[0],y="deltaY"in p?p.deltaY:S[1]-v[1],N,C=p.target,E=Math.abs(w)>Math.abs(y)?"h":"v";if("touches"in p&&E==="h"&&C.type==="range")return!1;var I=window.getSelection(),O=I&&I.anchorNode,A=O?O===C||O.contains(C):!1;if(A)return!1;var M=$i(E,C);if(!M)return!0;if(M?N=E:(N=E==="v"?"h":"v",M=$i(E,C)),!M)return!1;if(!r.current&&"changedTouches"in p&&(w||y)&&(r.current=N),!N)return!0;var P=r.current||N;return kb(P,b,p,P==="h"?w:y)},[]),u=c.useCallback(function(p){var b=p;if(!(!ms.length||ms[ms.length-1]!==o)){var v="deltaY"in b?_i(b):On(b),S=t.current.filter(function(N){return N.name===b.type&&(N.target===b.target||b.target===N.shadowParent)&&Cb(N.delta,v)})[0];if(S&&S.should){b.cancelable&&b.preventDefault();return}if(!S){var w=(i.current.shards||[]).map(zi).filter(Boolean).filter(function(N){return N.contains(b.target)}),y=w.length>0?l(b,w[0]):!i.current.noIsolation;y&&b.cancelable&&b.preventDefault()}}},[]),f=c.useCallback(function(p,b,v,S){var w={name:p,delta:b,target:v,should:S,shadowParent:Tb(v)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(y){return y!==w})},1)},[]),d=c.useCallback(function(p){s.current=On(p),r.current=void 0},[]),m=c.useCallback(function(p){f(p.type,_i(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){f(p.type,On(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return ms.push(o),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:h}),document.addEventListener("wheel",u,fs),document.addEventListener("touchmove",u,fs),document.addEventListener("touchstart",d,fs),function(){ms=ms.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,fs),document.removeEventListener("touchmove",u,fs),document.removeEventListener("touchstart",d,fs)}},[]);var g=e.removeScrollBar,x=e.inert;return c.createElement(c.Fragment,null,x?c.createElement(o,{styles:Nb(a)}):null,g?c.createElement(xb,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Tb(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Rb=rb(Vc,Ib);var Jc=c.forwardRef(function(e,t){return c.createElement(hr,Rt({},e,{ref:t,sideCar:Rb}))});Jc.classNames=hr.classNames;var Mb=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,r=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:l}=r,u=s.fetchMeta?.fetchMore?.direction,f=i&&u==="forward",d=a&&u==="forward",m=i&&u==="backward",h=a&&u==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:_f(t,s.data),hasPreviousPage:$f(t,s.data),isFetchNextPageError:f,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:h,isRefetchError:l&&!f&&!m,isRefetching:o&&!d&&!h}}};function Bi(e,t){const s=new Set(t);return e.filter(r=>!s.has(r))}function Ab(e,t,s){const r=e.slice(0);return r[t]=s,r}var Ob=class extends zf{#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,aa.batch(()=>{const s=this.#t,r=this.#f(this.#a);r.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=r.map(d=>d.observer),o=a.map(d=>d.getCurrentResult()),i=s.length!==a.length,l=a.some((d,m)=>d!==s[m]),u=i||l,f=u?!0:o.some((d,m)=>{const h=this.#e[m];return!h||!Bf(d,h)});!u&&!f||(u&&(this.#c=r,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(Bi(s,a).forEach(d=>{d.destroy()}),Bi(a,s).forEach(d=>{d.subscribe(m=>{this.#m(d,m)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const s=this.#f(e),r=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[r,o=>this.#d(o??r,t,a),()=>this.#u(r,s)]}#u(e,t){return t.map((s,r)=>{const a=e[r];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const r=this.#l,a=s!==void 0&&r!==void 0&&(r.length!==s.length||s.some((o,i)=>o!==r[i]));return(!this.#n||this.#e!==this.#i||a||t!==this.#o)&&(this.#o=t,this.#i=this.#e,s!==void 0&&(this.#l=s),this.#n=Kf(this.#n,t(e))),this.#n}return e}#p(){return this.#r?.combine!==void 0&&this.#t.some((e,t)=>e.options.suspense&&this.#e[t]?.data===void 0)}#f(e){const t=new Map;this.#t.forEach(r=>{const a=r.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(r):t.set(a,[r])});const s=[];return e.forEach(r=>{const a=this.#s.defaultQueryOptions(r),i=t.get(a.queryHash)?.shift()??new Da(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=Ab(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,r=t?s:this.#d(e,this.#r?.combine);(t||s!==r)&&aa.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function vt({queries:e,...t},s){const r=we(),a=Uf(),o=qf(),i=c.useMemo(()=>e.map(p=>{const b=r.defaultQueryOptions(p);return b._optimisticResults=a?"isRestoring":"optimistic",b}),[e,r,a]);i.forEach(p=>{Hf(p);const b=r.getQueryCache().get(p.queryHash);Wf(p,o,b)}),Vf(o);const[l]=c.useState(()=>new Ob(r,i,t)),[u,f,d]=l.getOptimisticResult(i,t.combine),m=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>m?l.subscribe(aa.batchCalls(p)):Qf,[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const g=u.some((p,b)=>qo(i[b],p))?u.flatMap((p,b)=>{const v=i[b];if(v&&qo(v,p)){const S=new Da(r,v);return Yf(v,S,o)}return[]}):[];if(g.length>0)throw Promise.all(g);const x=u.find((p,b)=>{const v=i[b];return v&&Gf({result:p,errorResetBoundary:o,throwOnError:v.throwOnError,query:r.getQueryCache().get(v.queryHash),suspense:v.suspense})});if(x?.error)throw x.error;return f(d())}function Zc(e,t){return Xf(e,Mb)}function Db(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const s=!!(e.condition??!0),r=e.blockerFn;return{shouldBlockFn:async()=>s&&r!==void 0?await r():s,enableBeforeUnload:s,withResolver:r===void 0}}function Pb(e,t){const{shouldBlockFn:s,enableBeforeUnload:r=!0,disabled:a=!1,withResolver:o=!1}=Db(e),i=Pa(),{history:l}=i,[u,f]=c.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return c.useEffect(()=>{const d=async m=>{function h(v){const S=i.parseLocation(v),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(v.search)}:{routeId:w.foundRoute.id,fullPath:w.foundRoute.fullPath,pathname:S.pathname,params:w.routeParams,search:i.options.parseSearch(v.search)}}const g=h(m.currentLocation),x=h(m.nextLocation);if(g.routeId==="__notFound__"&&x.routeId!=="__notFound__")return!1;const p=await s({action:m.action,current:g,next:x});if(!o)return p;if(!p)return!1;const b=await new Promise(v=>{f({status:"blocked",current:g,next:x,action:m.action,proceed:()=>v(!1),reset:()=>v(!0)})});return f({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),b};return a?void 0:l.block({blockerFn:d,enableBeforeUnload:r})},[s,r,a,o,l,i]),u}function St(e){const t=Pa({warn:e?.router===void 0}),s=e?.router||t;return El(s.stores.__store,Il(e,s))}function pr(e){const t=Pa();return El(t.stores.location,Il(e,t))}const Lb=new Set(["outbox","flagged"]),Fb=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!Lb.has(s)};function $b(e){const t=vt({queries:e.map(s=>({...Ue({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,r]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=an(r.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function eu(e){const{openCompose:t}=$t(),s=$e(),r=pr(),a=$b(e);return c.useCallback(()=>{if(Fb(r.pathname)){c.startTransition(()=>{t({mode:"new"})});return}a&&(c.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,r.pathname,a])}const _b=e=>e.startsWith("/mail")||e.startsWith("/settings"),zb=({accounts:e})=>{const{state:t}=$t(),s=pr(),r=eu(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!_b(s.pathname)||t.isOpen||o?null:n.jsx("button",{type:"button",onClick:r,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:n.jsx(_h,{className:"size-6"})})},tu=({trigger:e,children:t,align:s="right"})=>{const[r,a]=c.useState(!1),o=c.useRef(null),i=c.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),l=c.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return c.useEffect(()=>(r&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",l)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",l)}),[r,i,l]),n.jsxs("div",{ref:o,className:"relative",children:[n.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!r)},className:Ne("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),r&&n.jsx("div",{className:Ne("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})]})},bs=({onClick:e,disabled:t,destructive:s,children:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:Ne("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:r}),pa=()=>n.jsx("div",{className:"my-1 h-px bg-line"}),su=({children:e})=>{const{Account:t}=La();return n.jsx(t,{children:e})},Bb=({email:e,onSignOut:t})=>{const s=$e(),r=e??"Account";return n.jsxs(tu,{trigger:n.jsx(bt,{name:r,email:e??void 0,size:"sm"}),align:"right",children:[e&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),n.jsx(pa,{})]}),n.jsxs(bs,{onClick:()=>s({to:"/settings/accounts"}),children:[n.jsx(eo,{className:"size-4"}),"Settings"]}),n.jsx(pa,{}),n.jsxs(bs,{onClick:t,children:[n.jsx(hc,{className:"size-4"}),"Sign out"]})]})},Kb=()=>n.jsx(su,{children:({email:e,signOut:t})=>n.jsx(Bb,{email:e,onSignOut:t})}),Ki=()=>{const e=Fa(),t=$a(e);window.open(t,"_blank","noopener,noreferrer")};function nu({variant:e="icon"}){return e==="drawer"?n.jsxs("button",{type:"button",onClick:Ki,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(si,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]}):n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(si,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:Ki})}const ru="/mail/",lo="/mail/$mailboxId",au="/mail/outbox",ou="/mail/flagged";function co(e){return e.some(t=>t.routeId===ru)}function dn(e){return e.some(t=>t.routeId===ou)}function gr(e){return e.some(t=>t.routeId===au)}function iu(e){return e.some(t=>t.routeId===lo)}function Ub(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${lo}:${t}`:dn(e)?ou:gr(e)?au:co(e)?ru:""}const Kn="search-scope";function qb(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function lu(e){return dn(e)||gr(e)||iu(e)}function cu(e){return e.find(t=>t.routeId===lo)?.params?.mailboxId}function Hb(e){const t=cu(e.matches);return t||(lu(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function Wb(e,t){return co(e)?{kind:"global"}:dn(e)?{kind:"scoped",chip:{id:Kn,label:"is:starred"}}:gr(e)?{kind:"scoped",chip:{id:Kn,label:"in:outbox"}}:iu(e)?t?{kind:"scoped",chip:{id:Kn,label:qb(t)}}:{kind:"pending"}:{kind:"global"}}function Vb(e,t,s){return t.kind==="global"?{kind:"global"}:dn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const uu=({accounts:e})=>{const t=_a({strict:!1}),s=pr(),r=t.mailboxId,{t:a}=tr("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=vt({queries:e.map(l=>({...Ue({path:{accountId:l.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!r)return null;for(let l=0;l<e.length;l++){const u=i[l]?.data?.items;if(!u)continue;const f=u.find(m=>m.mailboxId===r);if(!f)continue;const d=an(e[l].folderAppointments);return js(f,d.get(r),o)}return null},Qb=({accounts:e})=>{const s=_a({strict:!1}).mailboxId,r=vt({queries:e.map(a=>({...Ue({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of r){const o=a.data?.items;if(!o)continue;const i=o.find(l=>l.mailboxId===s);if(i)return i.unseenCount}return null};function du(e){const t=$e(),{searchInput:s}=ke(),r=uu({accounts:e}),a=St({select:l=>l.matches}),o=Wb(a,r),i=c.useCallback(l=>{l===Kn&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const fu=[{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 Yb(e){for(const t of fu){const s=t.hints.find(r=>r.action===e);if(s)return s.keys}}function ps(e){const t=Yb(e);return!t||t.length===0?"":t.length===1?`(${t[0]})`:t[0]==="g"?`(${t.join(" then ")})`:`(${t.join("")})`}const Gb={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function Xb({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:r,onSearchClearQuery:a}=ke(),o=eu(e),{scope:i,clearScope:l}=du(e),u=i.kind==="scoped"?[{id:i.chip.id,label:i.chip.label,tone:"scope"}]:void 0,f=Gb[i.kind];return n.jsx(tg,{search:n.jsx(no,{value:t,onChange:s,onClear:r,onClearQuery:a,chips:u,onRemoveChip:l,placeholder:f,size:"lg"}),actions:n.jsxs(n.Fragment,{children:[n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Kh,{className:"size-4"}),title:`Compose ${ps("compose")}`,"aria-label":"Compose",onClick:o}),n.jsx(nu,{}),n.jsx(Kb,{})]})})}const uo=({isOpen:e,onClose:t,children:s,ariaLabel:r="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=c.useRef(null),l=c.useRef(null);if(c.useEffect(()=>{if(!e)return;l.current=document.activeElement;const f=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",f),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const m=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",f),document.body.style.overflow=m,l.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return n.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":r,children:[n.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),n.jsxs("div",{ref:i,className:Ne("absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[n.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:n.jsx(Ze,{className:"size-5"})})}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},Jb=e=>{const t=e.filter(a=>!a.isMultipart&&a.disposition!=="attachment"&&a.mediaType==="TEXT"&&a.contentUrl.length>0),s=t.find(a=>a.mediaSubtype.toUpperCase()==="HTML");if(s)return{kind:"html",contentUrl:s.contentUrl};const r=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return r?{kind:"text",contentUrl:r.contentUrl}:null},ga={all:["messages"],detail:e=>[...ga.all,"detail",e],body:e=>[...ga.detail(e),"body"]};class Gt extends Error{reason;status;retryAfterSeconds;constructor(t,s,r,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=r,this.retryAfterSeconds=a}}const Zb=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},ev=8,tv="x-remit-403-reason",sv=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},nv=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,rv=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},av=async(e,t,s=async()=>null)=>{const r={},a=await s();a&&(r.Authorization=`Bearer ${a}`);const o=await Jf(e,{headers:r});if(o.status===202)throw new Gt("not-ready","Message body is still syncing",202,Zb(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(tv),f=sv(o.status,u);throw new Gt(f,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(rv(t,i))throw new Gt("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(nv(l,i))throw new Gt("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},ov=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),mu=({messageId:e,bodyParts:t,enabled:s=!0})=>{const r=t?Jb(t):null,a=on(),{getToken:o}=La(),i=c.useRef(null),l=we(),u=c.useRef(!1),f=c.useRef(null),d=e&&r?`${e}:${r.contentUrl}`:null;f.current!==d&&(f.current=d,u.current=!1);const m=ue({queryKey:e?[...ga.body(e),r?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!r)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const x=u.current;return u.current=!1,ov({fetchContent:(p,b)=>av(p,b,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:Tl({path:{messageId:e}})})},{contentUrl:r.contentUrl,kind:r.kind,isRetryAfterNotReady:x})},enabled:s&&!!e&&!!r,staleTime:300*1e3,gcTime:1800*1e3,retry:(x,p)=>p instanceof Gt&&p.reason==="not-ready"?x<ev:x<1,retryDelay:(x,p)=>p instanceof Gt&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=m.isLoading&&!!r;c.useEffect(()=>{h&&(i.current=performance.now())},[h]),c.useEffect(()=>{m.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[m.isSuccess,a]);const g=m.data&&r?{kind:r.kind,body:m.data}:void 0;return{picked:r,data:g,isLoading:h,isError:m.isError,error:m.error,refetch:m.refetch}},iv=({outboxMessageId:e,onDraftCreated:t})=>{const[s,r]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=we(),u=je(Rl()),f=je(Zf()),d=c.useCallback(async x=>{if(r("saving"),o(null),e){const b=await f.mutateAsync({path:{outboxMessageId:e},body:{toAddresses:x.toAddresses,ccAddresses:x.ccAddresses,bccAddresses:x.bccAddresses,subject:x.subject,textBody:x.textBody,htmlBody:x.htmlBody,inReplyTo:x.inReplyTo,references:x.references}});return r("saved"),b}const p=await u.mutateAsync({body:{...x,sendImmediately:!1}});return t(p.outboxMessageId),r("saved"),l.invalidateQueries({queryKey:sr().queryKey}),p},[e,u,f,t,l]),m=c.useCallback(x=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{d(x).catch(p=>{o(p),r("error")})},2e3)},[d]),h=c.useCallback(x=>(i.current&&clearTimeout(i.current),d(x)),[d]),g=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:m,saveImmediately:h,cancelAutoSave:g}},hu=e=>"text"in e&&!("children"in e),pu=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),lv=e=>{let t=pu(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},gu=e=>{const t=e.children.map(s=>hu(s)?lv(s):gu(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${pu(s)}">${t}</a>`}default:return`<p>${t}</p>`}},Ui=e=>e.map(gu).join(""),xu=e=>hu(e)?e.text:e.children.map(xu).join(""),xa=e=>e.map(xu).join(`
116
+ `),cv=["Tab",","],qi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),uv=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const r=s[1].trim(),a=s[2].trim();if(qi(a))return{email:a,displayName:r}}if(qi(t))return{email:t}},Gr=({label:e,addresses:t,onChange:s,placeholder:r})=>{const[a,o]=c.useState(""),i=c.useRef(null),l=lr(a,200),{data:u}=ue({...nr({query:{q:l,limit:8}}),enabled:l.length>=2}),f=u?.items??[],d=new Set(t.map(y=>y.email.toLowerCase())),m=a.length>=2?f.filter(y=>!d.has(y.normalizedEmail.toLowerCase())):[],h=c.useCallback(y=>{d.has(y.email.toLowerCase())||(s([...t,y]),o(""))},[t,d,s]),g=c.useCallback(y=>{s(t.filter((N,C)=>C!==y))},[t,s]),x=c.useCallback(y=>{h({email:y.normalizedEmail,displayName:y.displayName}),i.current?.focus()},[h]),p=c.useCallback(()=>{const y=uv(a);y&&h(y)},[a,h]),b=Ml({count:m.length,acceptKeys:cv,onAccept:y=>x(m[y])}),v=c.useMemo(()=>m.map(y=>({value:y.normalizedEmail,label:y.displayName??y.normalizedEmail,...y.displayName?{hint:y.normalizedEmail}:{}})),[m]),S=c.useCallback(y=>{if(y.key==="Backspace"&&a===""&&t.length>0){g(t.length-1);return}b.handleKeyDown(y)||(y.key==="Enter"||y.key==="Tab"||y.key===",")&&a.trim()&&(y.preventDefault(),p())},[a,t.length,g,b.handleKeyDown,p]),w=c.useCallback(()=>{setTimeout(()=>{p(),b.dismiss()},150)},[p,b.dismiss]);return n.jsxs("div",{className:"relative",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),n.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>i.current?.focus(),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&i.current?.focus()},children:[t.map((y,N)=>n.jsx(Wh,{email:y.email,displayName:y.displayName,onRemove:()=>g(N)},y.email)),n.jsx("input",{ref:i,id:`address-field-${e}`,type:"text",value:a,onChange:y=>{b.reopen(),o(y.target.value)},onKeyDown:S,onBlur:w,placeholder:t.length===0?r:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5",autoComplete:"off",...b.comboboxProps})]})]}),b.open&&n.jsx(Al,{id:b.listId,suggestions:v,activeIndex:b.activeIndex,optionId:b.optionId,onPick:y=>{const N=m.find(C=>C.normalizedEmail===y.value);N&&x(N)},onHighlight:b.setActiveIndex,label:`${e} suggestions`,className:"absolute left-12 right-0 z-50 mt-1 max-h-[200px] shadow-lg"})]})},dv=({accountId:e})=>{const t=$e();return n.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[n.jsx(Ma,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),n.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",n.jsx(Mh,{className:"size-3","aria-hidden":"true"})]})]})]})},Hi=150,fv=()=>{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>Hi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,r=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>Hi})};return r(),s.addEventListener("resize",r),()=>s.removeEventListener("resize",r)},[]),e},mv=({selectedAccountId:e,onSelect:t})=>{const{data:s}=ue({...jt(),staleTime:1/0}),r=s?.accounts??[];if(c.useEffect(()=>{!e&&r.length===1&&r[0]&&t(r[0])},[e,r,t]),r.length<=1){const a=r[0];return a?n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),n.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=r.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:r.map(a=>n.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},hv=({value:e,onChange:t})=>n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),n.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),pv=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],gv=["href"],xv=e=>jl.sanitize(e,{ALLOWED_TAGS:pv,ALLOWED_ATTR:gv}),bv=c.lazy(()=>tm(()=>import("./ComposeBody-B2vOXJks.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.ComposeBody}))),vv=()=>n.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[n.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),n.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),bu=[{type:"p",children:[{text:""}]}],yv=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],wv=e=>e?[...yv,{type:"p",children:[{text:e}]}]:bu,Sv=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",jv=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",kv=(e,t,s)=>{const{envelope:r}=e,o=(r.replyTo.length>0?r.replyTo:r.from).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(f=>f.email.toLowerCase())),u=[...r.to,...r.cc].filter(f=>f.normalizedEmail.toLowerCase()!==i&&!l.has(f.normalizedEmail.toLowerCase())).map(f=>({email:f.normalizedEmail,displayName:f.displayName}));return{to:o,cc:u}},Cv=e=>{const t=e.envelope.messageIdValue,r=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!r.includes(t)&&r.push(t),{inReplyTo:t,references:r}},Nv=(e,t,s,r,a)=>e.length===0&&t.length===0&&s.length===0&&r.trim()===""&&xa(a).trim()==="",Ev=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:r,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:f,showBcc:d,setShowBcc:m,subject:h,setSubject:g})=>{const x=_t(),{isKeyboardOpen:p}=fv();if(!x&&p){const v=[];return s.length>0&&v.push(`To: ${s.map(S=>S.displayName??S.email).join(", ")}`),a.length>0&&v.push(`Cc: ${a.length}`),i.length>0&&v.push(`Bcc: ${i.length}`),h&&v.push(h),n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[n.jsx("span",{className:"truncate text-xs text-fg-muted",children:v.length>0?v.join(" · "):"…"}),n.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return n.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[n.jsx(mv,{selectedAccountId:e,onSelect:t}),n.jsx(Gr,{label:"To",addresses:s,onChange:r,placeholder:"Recipients"}),u?n.jsx(Gr,{label:"Cc",addresses:a,onChange:o}):n.jsxs("div",{className:"flex gap-2 pl-14",children:[n.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&n.jsx("div",{className:"pl-14",children:n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&n.jsx(Gr,{label:"Bcc",addresses:i,onChange:l}),n.jsx(hv,{value:h,onChange:g})]})},fo=({mode:e,account:t,sourceMessage:s,onClose:r,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=$t(),{pushError:u}=tt(),{outboxMessageId:f}=o,[d,m]=c.useState([]),[h,g]=c.useState([]),[x,p]=c.useState([]),[b,v]=c.useState(""),[S,w]=c.useState(!1),[y,N]=c.useState(!1),[C,E]=c.useState(t?.accountId),[I,O]=c.useState(!1),A=c.useRef(f);c.useEffect(()=>{A.current!==f&&(A.current=f,f&&(m([]),g([]),p([]),v(""),w(!1),N(!1),R(bu),O(!1)))},[f]);const{signature:M}=Dm(C),[P,R]=c.useState(()=>wv(M.plainText)),{data:j}=ue({...em({path:{outboxMessageId:f??""}}),enabled:!!f&&!I});c.useEffect(()=>{!j||I||(m(j.toAddresses.map(B=>({email:B,displayName:void 0}))),j.ccAddresses&&j.ccAddresses.length>0&&(g(j.ccAddresses.map(B=>({email:B,displayName:void 0}))),w(!0)),j.bccAddresses&&j.bccAddresses.length>0&&(p(j.bccAddresses.map(B=>({email:B,displayName:void 0}))),N(!0)),j.subject&&v(j.subject),j.textBody&&R([{type:"p",children:[{text:j.textBody}]}]),E(j.accountId),O(!0))},[j,I]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:B,cc:le}=kv(s,e,t?.email);m(B),g(le),le.length>0&&w(!0),v(Sv(s.envelope.subject))}e==="forward"&&v(jv(s.envelope.subject))}},[e,s,t?.email]);const F=e==="reply"||e==="reply_all"||e==="forward",{data:D}=mu({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:F&&!!s}),k=D?.kind==="text"?D.body:"",L=D?.kind==="html"?xv(D.body):void 0,T=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:$,saveError:V,saveDraft:ne,cancelAutoSave:re}=iv({outboxMessageId:f,onDraftCreated:i});c.useEffect(()=>{V&&u({title:"Couldn't save draft",detail:lt(V)??"Saving the draft failed.",error:V})},[V,u]);const q=je(Rl()),Q=je(Ol()),J=je({...rr(),onError:B=>{u(Jt("Couldn't discard draft","The draft wasn't discarded.",B))}}),{data:te}=ue({...jt(),staleTime:1/0}),Z=te?.accounts.find(B=>B.accountId===C),se=Z?Am(Z):!1,ce=q.isPending||Q.isPending,xe=d.length>0&&!!C&&!se;c.useEffect(()=>{if(!C||f&&!I||Nv(d,h,x,b,P))return;const B=xa(P),le=Ui(P);ne({accountId:C,toAddresses:d.map(de=>de.email),ccAddresses:h.length>0?h.map(de=>de.email):void 0,bccAddresses:x.length>0?x.map(de=>de.email):void 0,subject:b||void 0,textBody:B||void 0,htmlBody:le||void 0})},[C,f,I,d,h,x,b,P,ne]);const Te=c.useCallback(async()=>{if(!C||d.length===0)return;re();const B=s&&(e==="reply"||e==="reply_all")?Cv(s):{};let le=f,de=!1;if(!le){const ae=xa(P),Ce=Ui(P),qe=await q.mutateAsync({body:{accountId:C,toAddresses:d.map(Me=>Me.email),ccAddresses:h.length>0?h.map(Me=>Me.email):void 0,bccAddresses:x.length>0?x.map(Me=>Me.email):void 0,subject:b||void 0,textBody:ae||void 0,htmlBody:Ce||void 0,sendImmediately:!0,...B}}).catch(Me=>(u({title:"Couldn't send message",detail:lt(Me)??"Saving the draft failed.",error:Me}),null));if(qe===null)return;le=qe.outboxMessageId,de=!0,i(le)}await Q.mutateAsync({path:{outboxMessageId:le}}).catch(ae=>(u({title:"Couldn't send message",detail:lt(ae)??(de?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:ae}),null))!==null&&(l(le),r())},[C,d,h,x,b,P,e,s,f,q,Q,re,l,i,u,r]),Y=c.useCallback(()=>{re(),f&&J.mutate({path:{outboxMessageId:f}}),r()},[re,f,J,r]),z=c.useCallback(B=>{E(B.accountId),a?.(B)},[a]);return n.jsx(ig,{banner:Z&&se?n.jsx(dv,{accountId:Z.accountId}):void 0,header:n.jsx(Ev,{selectedAccountId:C,onAccountChange:z,toAddresses:d,setToAddresses:m,ccAddresses:h,setCcAddresses:g,bccAddresses:x,setBccAddresses:p,showCc:S,setShowCc:w,showBcc:y,setShowBcc:N,subject:b,setSubject:v}),quoted:k||L?n.jsx(Tg,{text:k,html:L,senderName:T}):void 0,actionBar:n.jsx(og,{onSend:Te,onDiscard:Y,sending:ce,canSend:xe,saveStatus:$,unavailableReason:se?"SMTP not configured":void 0,onUnavailable:B=>u({title:"Can't send yet",detail:B})}),children:n.jsx(c.Suspense,{fallback:n.jsx(vv,{}),children:n.jsx(bv,{value:P,onChange:R,onSubmit:Te,autoFocus:e==="new"})})})},Wi=({mode:e,account:t,sourceMessage:s,onClose:r})=>n.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:n.jsx(fo,{mode:e,account:t,sourceMessage:s,onClose:r})}),vu=({message:e,icon:t})=>n.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&n.jsx("div",{className:"mb-4 text-fg-muted",children:t}),n.jsx("p",{className:"text-fg-muted",children:e})]}),mo=({enabled:e=!0,bindings:t,capture:s=!1})=>{const r=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const f=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(f&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",r,s),()=>window.removeEventListener("keydown",r,s)},[e,r,s])},ho=e=>{const{data:t,isLoading:s}=ue({...jt(),staleTime:1/0}),r=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=vt({queries:r.map(l=>({...Ue({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<r.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return r[l]}},[e,r,a]),isLoading:o}},yu=100,Vn=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),Iv=(e,t=yu)=>{if(e.length===0)return[];const s=[];for(let r=0;r<e.length;r+=t)s.push(e.slice(r,r+t));return s},wu=async(e,t,s,r)=>{const a=Iv(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(r())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const f=a[u],d=await Vn(t(f));if(!d.ok)return l.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:l,cancelled:!1,error:d.error};i+=f.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},xr=async(e,t)=>{await wu(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},Tv=async(e,t,s,r,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await Vn(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const f=u.value;if(f.ids.length>0){const d=await Vn(s(f.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=f.ids.length,r({done:o,total:t})}l=f.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},Rv=e=>({done:e.done,total:Math.max(e.total,e.done)}),Mv=async(e,t,s)=>{let r=0,a;do{if(s())return{total:r,cancelled:!0};const o=await Vn(e(a));if(!o.ok)return{total:r,cancelled:!1,error:o.error};const i=o.value;r+=i.ids.length,t(r),a=i.continuationToken}while(a);return{total:r,cancelled:!1}},Av=e=>e.failedIds.length>0?{exit:!1,retryIds:e.failedIds}:e.cancelled||e.error?{exit:!1,retryIds:[]}:{exit:!0,retryIds:[]},Su=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),ju=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),ku=(e,t)=>e===void 0?e:Su(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:ju(e)?{...e,items:t(e.items)}:e,Ct=e=>{const t=[];for(const s of new Set(e))t.push(ar({path:{mailboxId:s}})),t.push(za({path:{mailboxId:s}}));return t.push(Ba()),t},fn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),mn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,r])=>({queryKey:s,data:r})),hn=(e,t,s)=>{const r=a=>ku(a,s);for(const a of t)e.setQueriesData({queryKey:a},r)},pn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},Nt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Ov=3e3,Dv=(e,t,s)=>{if(e.length===0)return()=>{};const r=setTimeout(()=>s(e),t);return()=>clearTimeout(r)},br=(e,t,s)=>{const r=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(r.get(o)??s);return[...a]},Qn=(e,t,s)=>e.map(r=>t.has(r.messageId)?{...r,isRead:s}:r),Pv=(e,t,s,r)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!r.has(a.messageId)).map(a=>a.messageId),Lv=({messages:e,expandedIds:t,threadId:s,mailboxId:r,accountId:a})=>{const o=we(),{pushError:i}=tt(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:f}=je({...or(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),x=h.body.isRead??!0,p=rs({path:{threadId:s}}),b=Ct(br(g,e,r));await Promise.all([o.cancelQueries({queryKey:p}),fn(o,b)]);const v=o.getQueriesData({queryKey:p}).filter(w=>w[1]!==void 0).map(([w,y])=>({queryKey:w,data:y})),S=mn(o,b);return o.setQueriesData({queryKey:p},w=>w&&{...w,items:Qn(w.items,g,x)}),hn(o,b,w=>Qn(w,g,x)),{threadMessagesPrefix:p,listPrefixes:b,previousThreadMessages:v,previousThreadsList:S}},onSuccess:(h,g)=>{const x=g.body.messageIds??[];for(const p of x)l.current.add(p),u.current.delete(p)},onError:(h,g,x)=>{const p=g.body.messageIds??[];for(const v of p)u.current.delete(v);if(x){for(const v of x.previousThreadMessages)o.setQueryData(v.queryKey,v.data);pn(o,x.previousThreadsList)}const b=g.body.isRead??!0;i({title:b?"Couldn't mark as read":"Couldn't mark as unread",detail:lt(h),error:h})},onSettled:(h,g,x,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),Nt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:ns({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(x=>!l.current.has(x)&&!u.current.has(x));if(g.length!==0){for(const x of g)u.current.add(x);f({body:{messageIds:g,isRead:!0}})}},[f]),m=c.useMemo(()=>Pv(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Dv(m,Ov,d),[m,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},vr=e=>{const{mailboxId:t,accountId:s,messages:r}=e,a=we(),{pushError:o}=tt(),{mutateAsync:i,isPending:l}=je({...or(),onError:(f,d)=>{const m=d.body.isRead??!0;o({title:m?"Couldn't mark as read":"Couldn't mark as unread",detail:lt(f),error:f})},onSettled:(f,d,m)=>{Nt(a,Ct(br(m.body.messageIds??[],r??[],t))),s&&a.invalidateQueries({queryKey:ns({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((f,d)=>{f.length!==0&&xr(f,m=>i({body:{messageIds:m,isRead:d}}))},[i]),isPending:l}},Fv=60,$v=1.5,_v=(e,t,s)=>{const r=Math.abs(e),a=Math.abs(t);return r<s?{direction:null}:r<a*$v?{direction:null}:{direction:e<0?"left":"right"}},zv=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Fv})=>{const r=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){r.current=null;return}r.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const f=r.current;if(r.current=null,!f)return;const{direction:d}=_v(u.clientX-f.x,u.clientY-f.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{r.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},Bv=(e,t,s)=>t?.find(r=>r.messageId===e)?.mailboxId??s,Vi=(e,t,s)=>e.map(r=>r.messageId===t?{...r,hasStars:s}:r),po=({threadId:e,mailboxId:t,messages:s})=>{const r=we(),{pushError:a}=tt(),{mutate:o,isPending:i,variables:l}=je({...sm(),onMutate:async f=>{const d=f.path.messageId,m=f.body.isStarred??!1,h=rs({path:{threadId:e}}),g=Ct([Bv(d,s,t)]);await Promise.all([r.cancelQueries({queryKey:h}),fn(r,g)]);const x=r.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,v])=>({queryKey:b,data:v})),p=mn(r,g);return r.setQueriesData({queryKey:h},b=>ku(b,v=>Vi(v,d,m))),hn(r,g,b=>Vi(b,d,m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:x,previousThreadsList:p}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)r.setQueryData(g.queryKey,g.data);pn(r,m.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:lt(f),error:f})},onSettled:(f,d,m,h)=>{h&&(r.invalidateQueries({queryKey:h.threadMessagesPrefix}),Nt(r,h.listPrefixes))}});return{toggleStar:(f,d)=>{o({path:{messageId:f},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function yr(e){return e===void 0?"uncategorized":e}const Kv={inbox:"Inbox",junk:"Junk"},go=e=>e.destinationMailboxId!==void 0,Uv=(e,t)=>{if(go(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${Kv[s]??"another folder"} by Remit`},qv=(e,t)=>{if(e===Vo.MoveToInbox)return t.inboxMailboxId;if(e===Vo.MoveToJunk)return t.junkMailboxId},Hv=(e,t,s)=>{if(!e||!t)return!1;const r=go(e)?e.destinationMailboxId:qv(e.action,s);return r!==void 0&&r===t},Wv=(e,t)=>{if(e){if(go(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},wr=(e,t)=>{const{data:s,isLoading:r}=ue({...jt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:r}},Vv=e=>{const{mailboxId:t,isLoading:s}=wr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Qv=e=>{const{mailboxId:t,isLoading:s}=wr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},xo=e=>{const{mailboxId:t,isLoading:s}=wr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},gn=e=>{const{mailboxId:t,isLoading:s}=wr(e,"Junk");return{junkMailboxId:t,isLoading:s}},Cu=e=>{const{data:t}=ue({...jt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Qi=(e,t)=>e.filter(s=>!t.has(s.messageId)),Lt=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=we(),{pushError:o}=tt(),{mutateAsync:i,isPending:l}=je({...nm(),onMutate:async f=>{const d=new Set(f.body.messageIds??[]),m=t?rs({path:{threadId:t}}):[],h=Ct([e,f.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:m})]:[],fn(a,h)]);const g=t?a.getQueriesData({queryKey:m}).filter(p=>p[1]!==void 0).map(([p,b])=>({queryKey:p,data:b})):[],x=mn(a,h);return t&&a.setQueriesData({queryKey:m},p=>p&&{...p,items:Qi(p.items,d)}),hn(a,h,p=>Qi(p,d)),r?.(Array.from(d)),{threadMessagesPrefix:m,listPrefixes:h,previousThreadMessages:g,previousThreadsList:x}},onError:(f,d,m)=>{if(m){for(const g of m.previousThreadMessages)a.setQueryData(g.queryKey,g.data);pn(a,m.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:lt(f),error:f})},onSettled:(f,d,m,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),Nt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:ns({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((f,d)=>{f.length!==0&&xr(f,m=>i({body:{messageIds:m,destinationMailboxId:d}}))},[i]),isPending:l}},Yv=({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a})=>{const{inboxMailboxId:o}=xo(e),{junkMailboxId:i}=gn(e),{moveMessages:l,isPending:u}=Lt({mailboxId:r,threadId:s,accountId:e}),{data:f}=ue({...Ue({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},m=Hv(a,r,d),h=Wv(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!m||!a)return{show:!1,label:"",isUndoing:!1};const x=a.fromMailboxId?f?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>ks(p.fullPath))[0]:void 0;return{show:!0,label:Uv(a,x),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function Gv({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a}){const o=Yv({accountId:e,messageId:t,threadId:s,mailboxId:r,autoMoved:a});return o.show?n.jsx(sg,{label:o.label,onUndo:o.onUndo,undoLabel:o.isUndoing?"Undoing…":"Undo",filtersHref:o.filtersHref}):null}const Yi=(e,t)=>e.filter(s=>!t.has(s.messageId)),Xv=e=>e.filter(t=>t.isDeleted!==!0),es=({mailboxId:e,threadId:t,accountId:s,messages:r,onAfterOptimisticRemove:a})=>{const o=we(),{pushError:i}=tt(),{mutateAsync:l,isPending:u}=je({...rm(),onMutate:async d=>{const m=new Set(d.body.messageIds??[]),h=t?rs({path:{threadId:t}}):[],g=Ct(br(m,r??[],e));await Promise.all([o.cancelQueries({queryKey:h}),fn(o,g)]);const x=t?o.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,v])=>({queryKey:b,data:v})):[],p=mn(o,g);return t&&o.setQueriesData({queryKey:h},b=>b&&{...b,items:Yi(b.items,m)}),hn(o,g,b=>Yi(b,m)),a?.(Array.from(m)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:x,previousThreadsList:p}},onError:(d,m,h)=>{if(h){for(const x of h.previousThreadMessages)o.setQueryData(x.queryKey,x.data);pn(o,h.previousThreadsList)}const g=m.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:lt(d),error:d})},onSettled:(d,m,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),Nt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:ns({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&xr(d,m=>l({body:{messageIds:m}}))},[l]),isPending:u}},Nu=(e,t=Date.now())=>({value:e,setAt:t}),Jv=(e,t,s,r)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Nu(!0,r):delete a.trusted,{...e,flags:a}},Zv=(e,t,s,r)=>{const a=o=>o.map(i=>Jv(i,t,s,r));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},bo=({messageId:e})=>{const t=we(),{pushError:s}=tt(),{mutate:r,isPending:a,error:o,reset:i}=je({...Dl(),onMutate:async u=>{const f=u.path.addressId,m=u.body.flags?.trusted?.value===!0,h=Tl({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,p])=>({queryKey:x,data:p}));return t.setQueriesData({queryKey:h},x=>x&&Zv(x,f,m)),{describePrefix:h,previous:g}},onError:(u,f,d)=>{if(d)for(const m of d.previous)t.setQueryData(m.queryKey,m.data);s(Jt("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,f,d,m)=>{m&&t.invalidateQueries({queryKey:m.describePrefix})}});return{toggleTrusted:(u,f)=>{r({path:{addressId:u},body:{flags:{trusted:Nu(!f)}}})},isPending:a,error:o,reset:i}};var Sr="Dialog",[Eu]=ax(Sr),[ey,ut]=Eu(Sr),Iu=e=>{const{__scopeDialog:t,children:s,open:r,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[f,d]=lx({prop:r,defaultProp:a??!1,onChange:o,caller:Sr});return n.jsx(ey,{scope:t,triggerRef:l,contentRef:u,contentId:Hr(),titleId:Hr(),descriptionId:Hr(),open:f,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(m=>!m),[d]),modal:i,children:s})};Iu.displayName=Sr;var Tu="DialogTrigger",ty=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ut(Tu,s),o=as(t,a.triggerRef);return n.jsx(kt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":yo(a.open),...r,ref:o,onClick:Ot(e.onClick,a.onOpenToggle)})});ty.displayName=Tu;var vo="DialogPortal",[sy,Ru]=Eu(vo,{forceMount:void 0}),Mu=e=>{const{__scopeDialog:t,forceMount:s,children:r,container:a}=e,o=ut(vo,t);return n.jsx(sy,{scope:t,forceMount:s,children:c.Children.map(r,i=>n.jsx(mr,{present:s||o.open,children:n.jsx(qc,{asChild:!0,container:a,children:i})}))})};Mu.displayName=vo;var Yn="DialogOverlay",Au=c.forwardRef((e,t)=>{const s=Ru(Yn,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=ut(Yn,e.__scopeDialog);return o.modal?n.jsx(mr,{present:r||o.open,children:n.jsx(ry,{...a,ref:t})}):null});Au.displayName=Yn;var ny=oo("DialogOverlay.RemoveScroll"),ry=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ut(Yn,s),o=Ex(),i=as(t,o);return n.jsx(Jc,{as:ny,allowPinchZoom:!0,shards:[a.contentRef],children:n.jsx(kt.div,{"data-state":yo(a.open),...r,ref:i,style:{pointerEvents:"auto",...r.style}})})}),Es="DialogContent",Ou=c.forwardRef((e,t)=>{const s=Ru(Es,e.__scopeDialog),{forceMount:r=s.forceMount,...a}=e,o=ut(Es,e.__scopeDialog);return n.jsx(mr,{present:r||o.open,children:o.modal?n.jsx(ay,{...a,ref:t}):n.jsx(oy,{...a,ref:t})})});Ou.displayName=Es;var ay=c.forwardRef((e,t)=>{const s=ut(Es,e.__scopeDialog),r=c.useRef(null),a=as(t,s.contentRef,r);return c.useEffect(()=>{const o=r.current;if(o)return Yx(o)},[]),n.jsx(Du,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Ot(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Ot(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Ot(e.onFocusOutside,o=>o.preventDefault())})}),oy=c.forwardRef((e,t)=>{const s=ut(Es,e.__scopeDialog),r=c.useRef(!1),a=c.useRef(!1);return n.jsx(Du,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||s.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),Du=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=ut(Es,s);return Mx(),n.jsx(n.Fragment,{children:n.jsx(Kc,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:o,children:n.jsx(zc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":yo(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),Pu="DialogTitle",Lu=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ut(Pu,s);return n.jsx(kt.h2,{id:a.titleId,...r,ref:t})});Lu.displayName=Pu;var Fu="DialogDescription",iy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ut(Fu,s);return n.jsx(kt.p,{id:a.descriptionId,...r,ref:t})});iy.displayName=Fu;var $u="DialogClose",ly=c.forwardRef((e,t)=>{const{__scopeDialog:s,...r}=e,a=ut($u,s);return n.jsx(kt.button,{type:"button",...r,ref:t,onClick:Ot(e.onClick,()=>a.onOpenChange(!1))})});ly.displayName=$u;function yo(e){return e?"open":"closed"}function cy(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 _u=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}),xn=()=>{const e=K.useContext(_u);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};cy(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
117
+ [data-state=closed]
118
+ ){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function uy(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function dy(){return wo(/^Mac/)}function fy(){return wo(/^iPhone/)}function Gi(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function my(){return wo(/^iPad/)||dy()&&navigator.maxTouchPoints>1}function zu(){return fy()||my()}function wo(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const hy=24,py=typeof window<"u"?c.useLayoutEffect:c.useEffect;function Xi(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const Xr=typeof document<"u"&&window.visualViewport;function Ji(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Bu(e){for(Ji(e)&&(e=e.parentElement);e&&!Ji(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const gy=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Dn=0,Jr;function xy(e={}){let{isDisabled:t}=e;py(()=>{if(!t)return Dn++,Dn===1&&zu()&&(Jr=by()),()=>{Dn--,Dn===0&&Jr?.()}},[t])}function by(){let e,t=0,s=m=>{e=Bu(m.target),!(e===document.documentElement&&e===document.body)&&(t=m.changedTouches[0].pageY)},r=m=>{if(!e||e===document.documentElement||e===document.body){m.preventDefault();return}let h=m.changedTouches[0].pageY,g=e.scrollTop,x=e.scrollHeight-e.clientHeight;x!==0&&((g<=0&&h>t||g>=x&&h<t)&&m.preventDefault(),t=h)},a=m=>{let h=m.target;ba(h)&&h!==document.activeElement&&(m.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=m=>{let h=m.target;ba(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",Xr&&(Xr.height<window.innerHeight?requestAnimationFrame(()=>{Zi(h)}):Xr.addEventListener("resize",()=>Zi(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,f=Xi(vy(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=Xi(qs(document,"touchstart",s,{passive:!1,capture:!0}),qs(document,"touchmove",r,{passive:!1,capture:!0}),qs(document,"touchend",a,{passive:!1,capture:!0}),qs(document,"focus",o,!0),qs(window,"scroll",i));return()=>{f(),d(),window.scrollTo(l,u)}}function vy(e,t,s){let r=e.style[t];return e.style[t]=s,()=>{e.style[t]=r}}function qs(e,t,s,r){return e.addEventListener(t,s,r),()=>{e.removeEventListener(t,s,r)}}function Zi(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=Bu(e);if(s!==document.documentElement&&s!==document.body&&s!==e){let r=s.getBoundingClientRect().top,a=e.getBoundingClientRect().top,o=e.getBoundingClientRect().bottom;const i=s.getBoundingClientRect().bottom+hy;o>i&&(s.scrollTop+=a-r)}e=s.parentElement}}function ba(e){return e instanceof HTMLInputElement&&!gy.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function yy(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function wy(...e){return t=>e.forEach(s=>yy(s,t))}function Ku(...e){return c.useCallback(wy(...e),e)}const Uu=new WeakMap;function Re(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let r={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}r[a]=e.style[a],e.style[a]=o}),!s&&Uu.set(e,r)}function Sy(e,t){if(!e||!(e instanceof HTMLElement))return;let s=Uu.get(e);s&&(e.style[t]=s[t])}const Ie=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function Pn(e,t){if(!e)return null;const s=window.getComputedStyle(e),r=s.transform||s.webkitTransform||s.mozTransform;let a=r.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[Ie(t)?13:12]):(a=r.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[Ie(t)?5:4]):null)}function jy(e){return 8*(Math.log(e+1)-2)}function Zr(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function ky(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const ye={DURATION:.5,EASE:[.32,.72,0,1]},qu=.4,Cy=.25,Ny=100,Hu=8,Yt=16,va=26,ea="vaul-dragging";function Wu(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 Ey({defaultProp:e,onChange:t}){const s=K.useState(e),[r]=s,a=K.useRef(r),o=Wu(t);return K.useEffect(()=>{a.current!==r&&(o(r),a.current=r)},[r,a,o]),s}function Vu({prop:e,defaultProp:t,onChange:s=()=>{}}){const[r,a]=Ey({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:r,l=Wu(s),u=K.useCallback(f=>{if(o){const m=typeof f=="function"?f(e):f;m!==e&&l(m)}else a(f)},[o,e,a,l]);return[i,u]}function Iy({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:r,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:f}){const[d,m]=Vu({prop:e,defaultProp:s?.[0],onChange:t}),[h,g]=K.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);K.useEffect(()=>{function E(){g({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]);const x=K.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=K.useMemo(()=>{var E;return(E=s?.findIndex(I=>I===d))!=null?E:null},[s,d]),b=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,v=K.useMemo(()=>{const E=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var I;return(I=s?.map(O=>{const A=typeof O=="string";let M=0;if(A&&(M=parseInt(O,10)),Ie(l)){const R=A?M:h?O*E.height:0;return h?l==="bottom"?E.height-R:-E.height+R:R}const P=A?M:h?O*E.width:0;return h?l==="right"?E.width-P:-E.width+P:P}))!=null?I:[]},[s,h,u]),S=K.useMemo(()=>p!==null?v?.[p]:null,[v,p]),w=K.useCallback(E=>{var I;const O=(I=v?.findIndex(A=>A===E))!=null?I:null;i(O),Re(r.current,{transition:`transform ${ye.DURATION}s cubic-bezier(${ye.EASE.join(",")})`,transform:Ie(l)?`translate3d(0, ${E}px, 0)`:`translate3d(${E}px, 0, 0)`}),v&&O!==v.length-1&&o!==void 0&&O!==o&&O<o?Re(a.current,{transition:`opacity ${ye.DURATION}s cubic-bezier(${ye.EASE.join(",")})`,opacity:"0"}):Re(a.current,{transition:`opacity ${ye.DURATION}s cubic-bezier(${ye.EASE.join(",")})`,opacity:"1"}),m(s?.[Math.max(O,0)])},[r.current,s,v,o,a,m]);K.useEffect(()=>{if(d||e){var E;const I=(E=s?.findIndex(O=>O===e||O===d))!=null?E:-1;v&&I!==-1&&typeof v[I]=="number"&&w(v[I])}},[d,e,s,v,w]);function y({draggedDistance:E,closeDrawer:I,velocity:O,dismissible:A}){if(o===void 0)return;const M=l==="bottom"||l==="right"?(S??0)-E:(S??0)+E,P=p===o-1,R=p===0,j=E>0;if(P&&Re(a.current,{transition:`opacity ${ye.DURATION}s cubic-bezier(${ye.EASE.join(",")})`}),!f&&O>2&&!j){A?I():w(v[0]);return}if(!f&&O>2&&j&&v&&s){w(v[s.length-1]);return}const F=v?.reduce((k,L)=>typeof k!="number"||typeof L!="number"?k:Math.abs(L-M)<Math.abs(k-M)?L:k),D=Ie(l)?window.innerHeight:window.innerWidth;if(O>qu&&Math.abs(E)<D*.4){const k=j?1:-1;if(k>0&&x&&s){w(v[s.length-1]);return}if(R&&k<0&&A&&I(),p===null)return;w(v[p+k]);return}w(F)}function N({draggedDistance:E}){if(S===null)return;const I=l==="bottom"||l==="right"?S-E:S+E;(l==="bottom"||l==="right")&&I<v[v.length-1]||(l==="top"||l==="left")&&I>v[v.length-1]||Re(r.current,{transform:Ie(l)?`translate3d(0, ${I}px, 0)`:`translate3d(${I}px, 0, 0)`})}function C(E,I){if(!s||typeof p!="number"||!v||o===void 0)return null;const O=p===o-1;if(p>=o&&I)return 0;if(O&&!I)return 1;if(!b&&!O)return null;const M=O?p+1:p-1,P=O?v[M]-v[M-1]:v[M+1]-v[M],R=E/Math.abs(P);return O?1-R:R}return{isLastSnapPoint:x,activeSnapPoint:d,shouldFade:b,getPercentageDragged:C,setActiveSnapPoint:m,activeSnapPointIndex:p,onRelease:y,onDrag:N,snapPointsOffset:v}}const Ty=()=>()=>{};function Ry(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:r,noBodyStyles:a}=xn(),o=K.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-va)/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;ky(r&&!a?Zr(document.body,{background:"black"}):Ty,Zr(u,{transformOrigin:Ie(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${ye.DURATION}s`,transitionTimingFunction:`cubic-bezier(${ye.EASE.join(",")})`}));const f=Zr(u,{borderRadius:`${Hu}px`,overflow:"hidden",...Ie(e)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{f(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},ye.DURATION*1e3)}}},[t,s,i])}let Hs=null;function My({isOpen:e,modal:t,nested:s,hasBeenOpened:r,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=K.useState(()=>typeof window<"u"?window.location.href:""),u=K.useRef(0),f=K.useCallback(()=>{if(Gi()&&Hs===null&&e&&!o){Hs={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:m,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-m}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const g=h-window.innerHeight;g&&u.current>=h&&(document.body.style.top=`${-(u.current+g)}px`)}),300)}},[e]),d=K.useCallback(()=>{if(Gi()&&Hs!==null&&!o){const m=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Hs),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,m)}),Hs=null}},[i]);return K.useEffect(()=>{function m(){u.current=window.scrollY}return m(),window.addEventListener("scroll",m),()=>{window.removeEventListener("scroll",m)}},[]),K.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),K.useEffect(()=>{s||!r||(e?(!window.matchMedia("(display-mode: standalone)").matches&&f(),t||window.setTimeout(()=>{d()},500)):d())},[e,r,i,t,s,f,d]),{restorePositionSetting:d}}function Ay({open:e,onOpenChange:t,children:s,onDrag:r,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=Cy,scrollLockTimeout:f=Ny,dismissible:d=!0,handleOnly:m=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:g,setActiveSnapPoint:x,fixed:p,modal:b=!0,onClose:v,nested:S,noBodyStyles:w=!1,direction:y="bottom",defaultOpen:N=!1,disablePreventScroll:C=!0,snapToSequentialPoint:E=!1,preventScrollRestoration:I=!1,repositionInputs:O=!0,onAnimationEnd:A,container:M,autoFocus:P=!1}){var R,j;const[F=!1,D]=Vu({defaultProp:N,prop:e,onChange:X=>{t?.(X),!X&&!S&&fe(),setTimeout(()=>{A?.(X)},ye.DURATION*1e3),X&&!b&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),X||(document.body.style.pointerEvents="auto")}}),[k,L]=K.useState(!1),[T,$]=K.useState(!1),[V,ne]=K.useState(!1),re=K.useRef(null),q=K.useRef(null),Q=K.useRef(null),J=K.useRef(null),te=K.useRef(null),Z=K.useRef(!1),se=K.useRef(null),ce=K.useRef(0),xe=K.useRef(!1),Te=K.useRef(!N),Y=K.useRef(0),z=K.useRef(null),B=K.useRef(((R=z.current)==null?void 0:R.getBoundingClientRect().height)||0),le=K.useRef(((j=z.current)==null?void 0:j.getBoundingClientRect().width)||0),de=K.useRef(0),_e=K.useCallback(X=>{o&&X===U.length-1&&(q.current=new Date)},[]),{activeSnapPoint:ae,activeSnapPointIndex:Ce,setActiveSnapPoint:qe,onRelease:Me,snapPointsOffset:U,onDrag:Ut,shouldFade:He,getPercentageDragged:pe}=Iy({snapPoints:o,activeSnapPointProp:g,setActiveSnapPointProp:x,drawerRef:z,fadeFromIndex:h,overlayRef:re,onSnapPointChange:_e,direction:y,container:M,snapToSequentialPoint:E});xy({isDisabled:!F||T||!b||V||!k||!O||!C});const{restorePositionSetting:fe}=My({isOpen:F,modal:b,nested:S??!1,hasBeenOpened:k,preventScrollRestoration:I,noBodyStyles:w});function Ve(){return(window.innerWidth-va)/window.innerWidth}function dt(X){var ie,me;!d&&!o||z.current&&!z.current.contains(X.target)||(B.current=((ie=z.current)==null?void 0:ie.getBoundingClientRect().height)||0,le.current=((me=z.current)==null?void 0:me.getBoundingClientRect().width)||0,$(!0),Q.current=new Date,zu()&&window.addEventListener("touchend",()=>Z.current=!1,{once:!0}),X.target.setPointerCapture(X.pointerId),ce.current=Ie(y)?X.pageY:X.pageX)}function ft(X,ie){var me;let oe=X;const ge=(me=window.getSelection())==null?void 0:me.toString(),Se=z.current?Pn(z.current,y):null,Ee=new Date;if(oe.tagName==="SELECT"||oe.hasAttribute("data-vaul-no-drag")||oe.closest("[data-vaul-no-drag]"))return!1;if(y==="right"||y==="left")return!0;if(q.current&&Ee.getTime()-q.current.getTime()<500)return!1;if(Se!==null&&(y==="bottom"?Se>0:Se<0))return!0;if(ge&&ge.length>0)return!1;if(te.current&&Ee.getTime()-te.current.getTime()<f&&Se===0||ie)return te.current=Ee,!1;for(;oe;){if(oe.scrollHeight>oe.clientHeight){if(oe.scrollTop!==0)return te.current=new Date,!1;if(oe.getAttribute("role")==="dialog")return!0}oe=oe.parentNode}return!0}function Qe(X){if(z.current&&T){const ie=y==="bottom"||y==="right"?1:-1,me=(ce.current-(Ie(y)?X.pageY:X.pageX))*ie,oe=me>0,ge=o&&!d&&!oe;if(ge&&Ce===0)return;const Se=Math.abs(me),Ee=document.querySelector("[data-vaul-drawer-wrapper]"),be=y==="bottom"||y==="top"?B.current:le.current;let Be=Se/be;const ot=pe(Se,oe);if(ot!==null&&(Be=ot),ge&&Be>=1||!Z.current&&!ft(X.target,oe))return;if(z.current.classList.add(ea),Z.current=!0,Re(z.current,{transition:"none"}),Re(re.current,{transition:"none"}),o&&Ut({draggedDistance:me}),oe&&!o){const Fe=jy(me),st=Math.min(Fe*-1,0)*ie;Re(z.current,{transform:Ie(y)?`translate3d(0, ${st}px, 0)`:`translate3d(${st}px, 0, 0)`});return}const Le=1-Be;if((He||h&&Ce===h-1)&&(r?.(X,Be),Re(re.current,{opacity:`${Le}`,transition:"none"},!0)),Ee&&re.current&&i){const Fe=Math.min(Ve()+Be*(1-Ve()),1),st=8-Be*8,Ye=Math.max(0,14-Be*14);Re(Ee,{borderRadius:`${st}px`,transform:Ie(y)?`scale(${Fe}) translate3d(0, ${Ye}px, 0)`:`scale(${Fe}) translate3d(${Ye}px, 0, 0)`,transition:"none"},!0)}if(!o){const Fe=Se*ie;Re(z.current,{transform:Ie(y)?`translate3d(0, ${Fe}px, 0)`:`translate3d(${Fe}px, 0, 0)`})}}}K.useEffect(()=>{window.requestAnimationFrame(()=>{Te.current=!0})},[]),K.useEffect(()=>{var X;function ie(){if(!z.current||!O)return;const me=document.activeElement;if(ba(me)||xe.current){var oe;const ge=((oe=window.visualViewport)==null?void 0:oe.height)||0,Se=window.innerHeight;let Ee=Se-ge;const be=z.current.getBoundingClientRect().height||0,Be=be>Se*.8;de.current||(de.current=be);const ot=z.current.getBoundingClientRect().top;if(Math.abs(Y.current-Ee)>60&&(xe.current=!xe.current),o&&o.length>0&&U&&Ce){const Le=U[Ce]||0;Ee+=Le}if(Y.current=Ee,be>ge||xe.current){const Le=z.current.getBoundingClientRect().height;let Fe=Le;Le>ge&&(Fe=ge-(Be?ot:va)),p?z.current.style.height=`${Le-Math.max(Ee,0)}px`:z.current.style.height=`${Math.max(Fe,ge-ot)}px`}else uy()||(z.current.style.height=`${de.current}px`);o&&o.length>0&&!xe.current?z.current.style.bottom="0px":z.current.style.bottom=`${Math.max(Ee,0)}px`}}return(X=window.visualViewport)==null||X.addEventListener("resize",ie),()=>{var me;return(me=window.visualViewport)==null?void 0:me.removeEventListener("resize",ie)}},[Ce,o,U]);function De(X){ve(),v?.(),X||D(!1),setTimeout(()=>{o&&qe(o[0])},ye.DURATION*1e3)}function Ae(){if(!z.current)return;const X=document.querySelector("[data-vaul-drawer-wrapper]"),ie=Pn(z.current,y);Re(z.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${ye.DURATION}s cubic-bezier(${ye.EASE.join(",")})`}),Re(re.current,{transition:`opacity ${ye.DURATION}s cubic-bezier(${ye.EASE.join(",")})`,opacity:"1"}),i&&ie&&ie>0&&F&&Re(X,{borderRadius:`${Hu}px`,overflow:"hidden",...Ie(y)?{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:`${ye.DURATION}s`,transitionTimingFunction:`cubic-bezier(${ye.EASE.join(",")})`},!0)}function ve(){!T||!z.current||(z.current.classList.remove(ea),Z.current=!1,$(!1),J.current=new Date)}function ze(X){if(!T||!z.current)return;z.current.classList.remove(ea),Z.current=!1,$(!1),J.current=new Date;const ie=Pn(z.current,y);if(!X||!ft(X.target,!1)||!ie||Number.isNaN(ie)||Q.current===null)return;const me=J.current.getTime()-Q.current.getTime(),oe=ce.current-(Ie(y)?X.pageY:X.pageX),ge=Math.abs(oe)/me;if(ge>.05&&(ne(!0),setTimeout(()=>{ne(!1)},200)),o){Me({draggedDistance:oe*(y==="bottom"||y==="right"?1:-1),closeDrawer:De,velocity:ge,dismissible:d}),a?.(X,!0);return}if(y==="bottom"||y==="right"?oe>0:oe<0){Ae(),a?.(X,!0);return}if(ge>qu){De(),a?.(X,!1);return}var Se;const Ee=Math.min((Se=z.current.getBoundingClientRect().height)!=null?Se:0,window.innerHeight);var be;const Be=Math.min((be=z.current.getBoundingClientRect().width)!=null?be:0,window.innerWidth),ot=y==="left"||y==="right";if(Math.abs(ie)>=(ot?Be:Ee)*u){De(),a?.(X,!1);return}a?.(X,!0),Ae()}K.useEffect(()=>(F&&(Re(document.documentElement,{scrollBehavior:"auto"}),q.current=new Date),()=>{Sy(document.documentElement,"scrollBehavior")}),[F]);function is(X){const ie=X?(window.innerWidth-Yt)/window.innerWidth:1,me=X?-Yt:0;se.current&&window.clearTimeout(se.current),Re(z.current,{transition:`transform ${ye.DURATION}s cubic-bezier(${ye.EASE.join(",")})`,transform:Ie(y)?`scale(${ie}) translate3d(0, ${me}px, 0)`:`scale(${ie}) translate3d(${me}px, 0, 0)`}),!X&&z.current&&(se.current=setTimeout(()=>{const oe=Pn(z.current,y);Re(z.current,{transition:"none",transform:Ie(y)?`translate3d(0, ${oe}px, 0)`:`translate3d(${oe}px, 0, 0)`})},500))}function mt(X,ie){if(ie<0)return;const me=(window.innerWidth-Yt)/window.innerWidth,oe=me+ie*(1-me),ge=-Yt+ie*Yt;Re(z.current,{transform:Ie(y)?`scale(${oe}) translate3d(0, ${ge}px, 0)`:`scale(${oe}) translate3d(${ge}px, 0, 0)`,transition:"none"})}function Pe(X,ie){const me=Ie(y)?window.innerHeight:window.innerWidth,oe=ie?(me-Yt)/me:1,ge=ie?-Yt:0;ie&&Re(z.current,{transition:`transform ${ye.DURATION}s cubic-bezier(${ye.EASE.join(",")})`,transform:Ie(y)?`scale(${oe}) translate3d(0, ${ge}px, 0)`:`scale(${oe}) translate3d(${ge}px, 0, 0)`})}return K.useEffect(()=>{b||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[b]),K.createElement(Iu,{defaultOpen:N,onOpenChange:X=>{!d&&!X||(X?L(!0):De(!0),D(X))},open:F},K.createElement(_u.Provider,{value:{activeSnapPoint:ae,snapPoints:o,setActiveSnapPoint:qe,drawerRef:z,overlayRef:re,onOpenChange:t,onPress:dt,onRelease:ze,onDrag:Qe,dismissible:d,shouldAnimate:Te,handleOnly:m,isOpen:F,isDragging:T,shouldFade:He,closeDrawer:De,onNestedDrag:mt,onNestedOpenChange:is,onNestedRelease:Pe,keyboardIsOpen:xe,modal:b,snapPointsOffset:U,activeSnapPointIndex:Ce,direction:y,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:w,container:M,autoFocus:P}},s))}const Qu=K.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:r,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=xn(),f=Ku(t,s),d=r&&r.length>0;if(!l)return null;const m=K.useCallback(h=>a(h),[a]);return K.createElement(Au,{onMouseUp:m,ref:f,"data-vaul-overlay":"","data-vaul-snap-points":i&&d?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});Qu.displayName="Drawer.Overlay";const Yu=K.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...r},a){const{drawerRef:o,onPress:i,onRelease:l,onDrag:u,keyboardIsOpen:f,snapPointsOffset:d,activeSnapPointIndex:m,modal:h,isOpen:g,direction:x,snapPoints:p,container:b,handleOnly:v,shouldAnimate:S,autoFocus:w}=xn(),[y,N]=K.useState(!1),C=Ku(a,o),E=K.useRef(null),I=K.useRef(null),O=K.useRef(!1),A=p&&p.length>0;Ry();const M=(R,j,F=0)=>{if(O.current)return!0;const D=Math.abs(R.y),k=Math.abs(R.x),L=k>D,T=["bottom","right"].includes(j)?1:-1;if(j==="left"||j==="right"){if(!(R.x*T<0)&&k>=0&&k<=F)return L}else if(!(R.y*T<0)&&D>=0&&D<=F)return!L;return O.current=!0,!0};K.useEffect(()=>{A&&window.requestAnimationFrame(()=>{N(!0)})},[]);function P(R){E.current=null,O.current=!1,l(R)}return K.createElement(Ou,{"data-vaul-drawer-direction":x,"data-vaul-drawer":"","data-vaul-delayed-snap-points":y?"true":"false","data-vaul-snap-points":g&&A?"true":"false","data-vaul-custom-container":b?"true":"false","data-vaul-animate":S?.current?"true":"false",...r,ref:C,style:d&&d.length>0?{"--snap-point-height":`${d[m??0]}px`,...t}:t,onPointerDown:R=>{v||(r.onPointerDown==null||r.onPointerDown.call(r,R),E.current={x:R.pageX,y:R.pageY},i(R))},onOpenAutoFocus:R=>{s?.(R),w||R.preventDefault()},onPointerDownOutside:R=>{if(e?.(R),!h||R.defaultPrevented){R.preventDefault();return}f.current&&(f.current=!1)},onFocusOutside:R=>{if(!h){R.preventDefault();return}},onPointerMove:R=>{if(I.current=R,v||(r.onPointerMove==null||r.onPointerMove.call(r,R),!E.current))return;const j=R.pageY-E.current.y,F=R.pageX-E.current.x,D=R.pointerType==="touch"?10:2;M({x:F,y:j},x,D)?u(R):(Math.abs(F)>D||Math.abs(j)>D)&&(E.current=null)},onPointerUp:R=>{r.onPointerUp==null||r.onPointerUp.call(r,R),E.current=null,O.current=!1,l(R)},onPointerOut:R=>{r.onPointerOut==null||r.onPointerOut.call(r,R),P(I.current)},onContextMenu:R=>{r.onContextMenu==null||r.onContextMenu.call(r,R),I.current&&P(I.current)}})});Yu.displayName="Drawer.Content";const Oy=250,Dy=120,Gu=K.forwardRef(function({preventCycle:e=!1,children:t,...s},r){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:l,setActiveSnapPoint:u,dismissible:f,handleOnly:d,isOpen:m,onPress:h,onDrag:g}=xn(),x=K.useRef(null),p=K.useRef(!1);function b(){if(p.current){w();return}window.setTimeout(()=>{v()},Dy)}function v(){if(o||e||p.current){w();return}if(w(),!i||i.length===0){f||a();return}if(l===i[i.length-1]&&f){a();return}const N=i.findIndex(E=>E===l);if(N===-1)return;const C=i[N+1];u(C)}function S(){x.current=window.setTimeout(()=>{p.current=!0},Oy)}function w(){x.current&&window.clearTimeout(x.current),p.current=!1}return K.createElement("div",{onClick:b,onPointerCancel:w,onPointerDown:y=>{d&&h(y),S()},onPointerMove:y=>{d&&g(y)},ref:r,"data-vaul-drawer-visible":m?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},K.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});Gu.displayName="Drawer.Handle";function Py(e){const t=xn(),{container:s=t.container,...r}=e;return K.createElement(Mu,{container:s,...r})}const at={Root:Ay,Content:Yu,Overlay:Qu,Portal:Py,Handle:Gu,Title:Lu},Xu="inline-flex items-center justify-center transition-colors",Ly=Ne(Xu,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Fy=Ne(Xu,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),Ds=({accountId:e,currentMailboxId:t,onMove:s,disabled:r=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),f=_t(),d=c.useRef(null),m=i??"Move to folder",h=c.useId(),{t:g}=tr("mail",{useSuspense:!1}),x=c.useCallback((P,R)=>g(P,{defaultValue:R}),[g]),{data:p,isLoading:b,isError:v,error:S,refetch:w}=ue({...Ue({path:{accountId:e}}),staleTime:1/0,enabled:l}),y=Cu(e),{createFolder:N}=Yl(e),C=c.useMemo(()=>{const P=cn(p?.items??[],y),R=an(y);return P.map(j=>({id:j.mailboxId,label:js(j,R.get(j.mailboxId),x),searchValue:j.fullPath,isCurrent:j.mailboxId===t}))},[p?.items,y,t,x]),E=c.useCallback(P=>{u(!1),s(P)},[s]),I=c.useCallback(async(P,R)=>{const j=await N(P,R);return{id:j.id,label:j.label}},[N]);c.useEffect(()=>{if(!l||!f)return;const P=j=>{d.current&&!d.current.contains(j.target)&&u(!1)},R=j=>{j.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",P),document.addEventListener("keydown",R),()=>{document.removeEventListener("mousedown",P),document.removeEventListener("keydown",R)}},[l,f]);const O=r||!!a,A=n.jsxs("button",{type:"button",onClick:P=>{P.stopPropagation(),!O&&u(R=>!R)},"aria-label":m,"aria-haspopup":f?"listbox":"dialog","aria-expanded":l,"aria-controls":l?h:void 0,title:a,className:o==="icon-only"?Ly:Fy,children:[n.jsx(Ya,{className:"size-4"}),o==="compact"&&n.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),M=b?n.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):v?n.jsx("div",{className:"p-3",children:n.jsx(zt,{variant:"inline",title:"Couldn't load folders",error:S,onRetry:()=>w()})}):n.jsx(Gl,{mailboxes:C,onSelect:E,onCreateFolder:I,onCancel:()=>u(!1),autoFocus:!f,labels:{createLabel:P=>`Create "${P}"`,searchPlaceholder:g("move_picker_placeholder",{defaultValue:"Move to…"}),searchAriaLabel:g("move_picker_filter_label",{defaultValue:"Filter folders"}),optionLabel:P=>`Move to ${P}`,currentSuffix:"(current folder)",currentTag:"current",emptyMessage:P=>`No folders match "${P}"`}});return f?n.jsxs("div",{ref:d,className:"relative inline-block",children:[A,l&&n.jsx("div",{id:h,className:Ne("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:M})]}):n.jsxs(n.Fragment,{children:[A,n.jsx(at.Root,{open:l,onOpenChange:u,children:n.jsxs(at.Portal,{children:[n.jsx(at.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(at.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{maxHeight:"85dvh"},id:h,children:[n.jsx(at.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),n.jsx(at.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),n.jsx("div",{className:"flex-1 overflow-hidden",children:M})]})]})})]})},$y=({messageId:e,threadId:t,mailboxId:s,isRead:r,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const f=we(),d=$e(),{pushError:m}=tt(),{selectedMessageId:h}=Cs({strict:!1}),{mutate:g,isPending:x}=je({...or(),onMutate:async F=>{const D=F.body.isRead??!0,k=new Set(F.body.messageIds??[]),L=rs({path:{threadId:t}}),T=Ct([s]);await Promise.all([f.cancelQueries({queryKey:L}),fn(f,T)]);const $=f.getQueriesData({queryKey:L}).filter(ne=>ne[1]!==void 0).map(([ne,re])=>({queryKey:ne,data:re})),V=mn(f,T);return f.setQueriesData({queryKey:L},ne=>ne&&{...ne,items:Qn(ne.items,k,D)}),hn(f,T,ne=>Qn(ne,k,D)),{threadMessagesPrefix:L,listPrefixes:T,previousThreadMessages:$,previousThreadsList:V}},onError:(F,D,k)=>{if(k){for(const T of k.previousThreadMessages)f.setQueryData(T.queryKey,T.data);pn(f,k.previousThreadsList)}const L=D.body.isRead??!0;m({title:L?"Couldn't mark as read":"Couldn't mark as unread",detail:lt(F),error:F})},onSettled:(F,D,k,L)=>{L&&(f.invalidateQueries({queryKey:L.threadMessagesPrefix}),Nt(f,L.listPrefixes))}}),p=c.useCallback(F=>{h&&F.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:D=>({...D,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:b,isPending:v}=es({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:S,isPending:w}=Lt({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:y,isPending:N,error:C,reset:E}=bo({messageId:e}),I=()=>{g({body:{messageIds:[e],isRead:!1}})},O=()=>{b([e])},A=()=>{o&&y(o,i)},M=x||v||w||N,P=M||!o,R=c.useCallback(F=>{S([e],F)},[S,e]),j=o?void 0:"Sender has no parseable address";return n.jsxs("div",{className:"flex flex-col items-end gap-1",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[a&&n.jsx(Ds,{accountId:a,currentMailboxId:s,onMove:R,disabled:M,label:"Move this message"}),n.jsxs(tu,{trigger:n.jsx(fc,{className:"size-4"}),children:[n.jsxs(bs,{onClick:A,disabled:P,children:[i?n.jsx(dr,{className:"size-4 text-positive"}):n.jsx(nn,{className:"size-4 opacity-0"}),n.jsx("span",{title:j,children:"Trusted sender"})]}),r&&n.jsxs(bs,{onClick:I,disabled:M,children:[n.jsx(Rs,{className:"size-4"}),"Mark as unread"]}),u&&n.jsxs(bs,{onClick:u,children:[n.jsx(dc,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),n.jsx(pa,{}),n.jsxs(bs,{onClick:O,disabled:M,destructive:!0,children:[n.jsx(ct,{className:"size-4"}),"Delete"]})]})]}),C&&n.jsx("div",{className:"w-64",children:n.jsx(zt,{variant:"inline",title:"Couldn't update trust",error:C,onRetry:()=>{E(),A()}})})]})},_y=()=>{const[e,t]=c.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return c.useEffect(()=>{const s=document.documentElement,r=new MutationObserver(()=>{t(s.classList.contains("dark"))});return r.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>r.disconnect()},[]),e},zy=({blockedImageCount:e,canAlwaysTrust:t,isTrustPending:s,onLoadOnce:r,onAlwaysTrust:a})=>n.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-md bg-surface-sunken/50 px-3 py-2 text-sm",children:[n.jsxs("span",{className:"text-fg-muted",children:[e," image",e>1?"s":""," blocked for privacy"]}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:r,className:"text-accent hover:underline",children:"Load once"}),t&&n.jsx("button",{type:"button",onClick:a,"aria-busy":s,className:"text-accent hover:underline aria-busy:opacity-50",children:s?"Trusting…":"Always trust"})]})]}),By=(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}}},Ky=e=>e instanceof Gt?e.reason:"generic",Uy=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",qy=({error:e,onRetry:t})=>{const s=Ky(e),r=Uy(e),{title:a,detail:o}=By(s,r),[i,l]=c.useState(!1),{Account:u}=La();return i?null:n.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[n.jsx(ts,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"font-medium text-danger",children:a}),n.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&n.jsx(u,{children:({signOut:f})=>n.jsx("button",{type:"button",onClick:()=>f(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&n.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),n.jsx("button",{type:"button",onClick:()=>l(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:n.jsx(Ze,{className:"size-4","aria-hidden":"true"})})]})]})},Hy=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),el=()=>n.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Ju=({bodyParts:e,html:t,text:s,isTrusted:r=!1,messageId:a,fromAddressId:o,category:i,className:l})=>{const[u,f]=c.useState(!1),d=r||u,m=_y(),{toggleTrusted:h,isPending:g}=bo({messageId:a??""}),x=!!e&&e.length>0,{picked:p,data:b,isLoading:v,isError:S,error:w,refetch:y}=mu({messageId:a,bodyParts:e,enabled:x}),N=c.useMemo(()=>wp(e??[]),[e]),C=x&&b?.kind==="html"?b.body:t,E=x&&b?.kind==="text"?b.body:s;if(x){if(v)return n.jsx("div",{className:Ne("message-body",l),children:n.jsx(Hy,{})});if(S)return n.jsx("div",{className:Ne("message-body",l),children:n.jsx(qy,{error:w,onRetry:()=>y()})});if(!p)return n.jsx("div",{className:Ne("message-body",l),children:n.jsx(el,{})})}else if(!t&&!s)return n.jsx("div",{className:Ne("message-body",l),children:n.jsx(el,{})});const I=!!(o&&a),O=()=>{!o||g||(f(!0),h(o,!1))};return n.jsx(Tc,{className:l,html:C,text:E,isDark:m,category:i,allowImages:d,resolveCid:N,renderBlockedNotice:A=>n.jsx(zy,{blockedImageCount:A,canAlwaysTrust:I,isTrustPending:g,onLoadOnce:()=>f(!0),onAlwaysTrust:O})})},Wy=({messageId:e,threadId:t,mailboxId:s,accountId:r,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:l,isTrusted:u,showRaw:f,onToggleRaw:d,onReply:m,onReplyAll:h,onForward:g})=>{const x=we(),{deleteMessages:p}=es({mailboxId:s,threadId:t}),{moveMessages:b}=Lt({mailboxId:s,threadId:t,accountId:r}),{toggleTrusted:v}=bo({messageId:e}),{mutate:S}=je({...or(),onSettled:()=>{x.invalidateQueries({queryKey:rs({path:{threadId:t}})}),Nt(x,Ct([s]))}}),w=c.useCallback(E=>{b([e],E)},[b,e]),y=c.useCallback(()=>{p([e])},[p,e]),N=c.useCallback(()=>{S({body:{messageIds:[e],isRead:!a}})},[S,e,a]),C=[];return l&&C.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?n.jsx(dr,{className:"size-4 text-positive"}):n.jsx(nn,{className:"size-4"}),onSelect:()=>v(l,u)}),d&&C.push({key:"raw",label:f?"Show formatted":"Show raw email",icon:n.jsx(dc,{className:"size-4"}),onSelect:d}),n.jsx(Ic,{hasThread:!0,onReply:m,onReplyAll:h,onForward:g,isStarred:o,onToggleStar:i,onDelete:y,isRead:a,onToggleRead:N,overflowItems:C,moveSlot:r?n.jsx(Ds,{accountId:r,currentMailboxId:s,onMove:w,label:"Move this message"}):void 0})},Vy=()=>n.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading raw email",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"})]}),Qy=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:r,isError:a,error:o,refetch:i}=ue({...am({path:{messageId:e}}),enabled:t});if(r)return n.jsx("div",{className:"message-body",children:n.jsx(Vy,{})});if(a)return n.jsx("div",{className:"message-body",children:n.jsx(zt,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const l=s?.raw??"";return l===""?n.jsx("div",{className:"message-body",children:n.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):n.jsx("div",{className:"message-body",children:n.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:l})})},Yy=()=>n.jsx(dr,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),Zu=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),ed=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:r})=>n.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:Ne("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":Ne("text-fg-subtle hover:text-warning",r&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:n.jsx(Ft,{className:Ne("size-3.5",e&&"fill-current")})}),Gy=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:r,isStarPending:a})=>{const o=Vl(e.sentDate,"datetime"),i=Zu(e,o);return n.jsx(Rc,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:n.jsxs(n.Fragment,{children:[e.hasAttachment&&n.jsx(fr,{className:"size-3 shrink-0 text-fg-subtle"}),n.jsx(ed,{isStarred:e.hasStars,onToggleStar:r,isStarPending:a,hoverReveal:!0}),n.jsx("span",{"data-testid":"message-date",className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:o})]})})},Xy=({threadMessage:e,messageData:t,isLoading:s,isError:r,error:a,onRetry:o,isFocused:i,onToggle:l,onToggleStar:u,isStarPending:f,accountId:d,showRaw:m,onToggleRaw:h,mobile:g,onReply:x,onReplyAll:p,onForward:b})=>{const v=Vl(e.sentDate,"long"),S=!e.isRead,w=t?.envelope.from[0]?.flags?.trusted?.value===!0,y=t?.envelope.from[0]?.addressId,N=Zu(e,v),C=e.autoMoved?n.jsx(Gv,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved}):null;return n.jsx(Mc,{message:N,isFocused:g?!1:i,onHeaderClick:l,senderBadge:w?n.jsx(Yy,{}):void 0,trailing:n.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:v}),to:t?n.jsx(Hh,{label:"To",addresses:t.envelope.to}):null,indicators:C||!g?n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[C,!g&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n.jsx(ed,{isStarred:e.hasStars,onToggleStar:u,isStarPending:f}),e.hasAttachment&&n.jsx("span",{className:"text-fg-subtle p-0.5",children:n.jsx(fr,{className:"size-3.5"})})]}),S&&n.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:g?void 0:n.jsx($y,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:y,isTrusted:w,showRaw:m,onToggleRaw:h}),actionBar:g?n.jsx(Wy,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:y,isTrusted:w,showRaw:m,onToggleRaw:h,onReply:x,onReplyAll:p,onForward:b}):void 0,body:s?n.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):r&&om(a)?n.jsx("div",{className:"mt-3",children:n.jsx(vu,{message:"This message has been deleted"})}):r?n.jsx("div",{className:"mt-3",children:n.jsx(zt,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):m?n.jsx("div",{className:"mt-3",children:n.jsx(Qy,{messageId:e.messageId})}):n.jsx("div",{className:"mt-3",children:n.jsx(Ju,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:w,category:yr(e.category)})})})},Jy=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,mobile:l,onReply:u,onReplyAll:f,onForward:d})=>{const[m,h]=c.useState(!1),{data:g,isLoading:x,isError:p,error:b,refetch:v}=ue({...Ka({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?n.jsx(Xy,{threadMessage:e,messageData:g,isLoading:x,isError:p,error:b,onRetry:()=>v(),isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o,accountId:i,showRaw:m,onToggleRaw:()=>h(S=>!S),mobile:l,onReply:u,onReplyAll:f,onForward:d}):n.jsx(Gy,{threadMessage:e,isFocused:s,onToggle:r,onToggleStar:a,isStarPending:o})},Zy=()=>n.jsxs("div",{className:"animate-pulse p-4",children:[n.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),n.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>n.jsxs("div",{className:"flex gap-3 py-3",children:[n.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function tl({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?n.jsxs("div",{className:"flex items-start gap-2 rounded-none border-b border-danger/20 bg-danger-soft px-5 py-2.5 text-sm",children:[n.jsx(Ms,{className:"mt-0.5 size-4 shrink-0 text-danger"}),n.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",n.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&n.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const Ps=({threadId:e,mailboxId:t,subject:s,selectedMessageId:r,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:l,onComposeClose:u,onSwipeNext:f,onSwipePrevious:d,mobileIntelligenceOpen:m})=>{const h=_t(),{handlers:g}=zv({onSwipeLeft:f,onSwipeRight:d}),{accountId:x}=ho(t),{data:p,isLoading:b,isError:v,error:S,refetch:w}=ue({...im({path:{threadId:e}})}),y=c.useMemo(()=>p?.items??[],[p?.items]),N=y[y.length-1],C=c.useRef(new Map),[E,I]=c.useState(new Set),[O,A]=c.useState(null),[M,P]=c.useState(0);c.useEffect(()=>{if(y.length>0&&e!==O){A(e);const B=new Set([y[y.length-1].threadMessageId]);if(r){const le=y.find(de=>de.messageId===r);le&&B.add(le.threadMessageId)}I(B),P(y.length-1)}},[e,y,O,r]);const R=c.useCallback(B=>{I(le=>{const de=new Set(le);return de.has(B)?de.delete(B):de.add(B),de})},[]),j=c.useCallback(B=>{const le=y[B];if(!le)return;C.current.get(le.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[y]),F=c.useCallback(()=>{if(y.length===0)return;const B=Math.min(M+1,y.length-1);P(B),j(B)},[y.length,M,j]),D=c.useCallback(()=>{if(y.length===0)return;const B=Math.max(M-1,0);P(B),j(B)},[y.length,M,j]),k=c.useCallback(()=>{const B=y[M];B&&R(B.threadMessageId)},[y,M,R]),{data:L}=ue({...jt(),staleTime:1/0}),T=L?.accounts?.[0],$=!!T?.smtpHost;Lv({messages:y,expandedIds:E,threadId:e,mailboxId:t,accountId:T?.accountId});const{toggleStar:V,isPending:ne,pendingMessageId:re}=po({threadId:e,mailboxId:t,messages:y}),[q,Q]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(Q(l),u?.())},[l,u]);const{data:J}=ue({...Ka({path:{messageId:N?.messageId??""}}),enabled:!!N&&q!==null}),te=c.useCallback(()=>{Q("reply")},[]),Z=c.useCallback(()=>{Q("reply_all")},[]),se=c.useCallback(()=>{Q("forward")},[]),ce=c.useCallback(()=>{Q(null),u?.()},[u]);if(mo({enabled:!b&&y.length>0&&q===null,bindings:[{key:"j",handler:F,preventDefault:!0},{key:"ArrowDown",handler:F,preventDefault:!0},{key:"k",handler:D,preventDefault:!0},{key:"ArrowUp",handler:D,preventDefault:!0},{key:"Enter",handler:k,preventDefault:!0},{key:"o",handler:k,preventDefault:!0},...$?[{key:"r",handler:te,preventDefault:!0},{key:"R",handler:Z,noModifiers:!1,preventDefault:!0},{key:"f",handler:se,preventDefault:!0}]:[]]}),b)return n.jsx(Zy,{});if(v)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(zt,{title:"Couldn't load this conversation",error:S,onRetry:()=>w()})});if(y.length===0)return n.jsx("div",{className:"flex h-full items-center justify-center",children:n.jsx(vu,{message:"No messages in this thread"})});const xe=s||y[0]?.subject||"(No subject)",Te=y.length,Y=B=>n.jsx("div",{children:y.map((le,de)=>n.jsx("div",{ref:_e=>{_e&&C.current.set(le.threadMessageId,_e)},children:n.jsx(Jy,{threadMessage:le,isExpanded:E.has(le.threadMessageId),isFocused:de===M,onToggle:()=>R(le.threadMessageId),onToggleStar:()=>V(le.messageId,le.hasStars),isStarPending:ne&&re===le.messageId,accountId:x,mobile:B,onReply:B&&$?te:void 0,onReplyAll:B&&$?Z:void 0,onForward:B&&$?se:void 0})},le.threadMessageId))}),z=n.jsxs("header",{className:"border-b border-line px-5 pt-5 pb-3",children:[n.jsx("h1",{className:"max-w-2xl text-lg font-semibold leading-snug text-fg",children:xe}),n.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Te," ",Te===1?"message":"messages"]})]});return h?n.jsxs("article",{className:"h-full flex flex-col",children:[z,a?.dkimMismatch&&n.jsx(tl,{authenticity:a,onOpenIntelligence:o}),n.jsx("div",{className:"flex-1 overflow-auto",children:Y(!1)}),q!==null&&n.jsx(Wi,{mode:q,account:T,sourceMessage:J,onClose:ce})]}):n.jsxs(Wp,{thread:{subject:xe,messages:[]},onBack:i??(()=>{}),intelligenceOpen:m,onToggleIntelligence:o,touchHandlers:g,children:[a?.dkimMismatch&&n.jsx(tl,{authenticity:a,onOpenIntelligence:o}),Y(!0),q!==null&&n.jsx(Wi,{mode:q,account:T,sourceMessage:J,onClose:ce})]})},e0=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function td(e){return!!e&&e0.has(e)}const sd=3e3,t0=sd*2,sl={syncing:!1,resolved:!1,synced:0,total:0};function s0(e,t){const s=e.join(","),[r,a]=c.useState(!1),[o,i]=c.useState(!1);c.useEffect(()=>{a(!1),i(!1)},[s,t]),c.useEffect(()=>{if(!t)return;const x=setTimeout(()=>i(!0),t0);return()=>clearTimeout(x)},[s,t]);const l=vt({queries:e.map(x=>({...lm({path:{accountId:x}}),enabled:t&&!r,refetchInterval:sd,meta:{softError:!0}}))}),u=l.every(x=>x.isSuccess||x.isError),f=l.length===0||u||o;let d=!1,m=0,h=0;for(const x of l)if(td(x.data?.syncPhase)){d=!0;for(const p of x.data?.mailboxes??[])m+=p.messagesSynced,h+=p.messagesTotal}const g=t&&f&&!d;return c.useEffect(()=>{g&&a(!0)},[g]),!t||!f?sl:{syncing:d,resolved:!0,synced:m,total:h}}function os(){const{mailboxNameIndex:e,accountNameIndex:t}=ke();return{...St({select:r=>lu(r.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const So=e=>e.trim().toLocaleLowerCase(),nd={personal:"Personal",uncategorized:"Unclassified",transactional:"Transactional",newsletter:"Newsletter",marketing:"Marketing",social:"Social",automated:"Automated"},n0=Object.values(Je).map(e=>({value:e,label:nd[e]})),r0={unclassified:"uncategorized"},ya=[{name:"from",label:"Sender",values:"contact"},{name:"subject",label:"Subject",values:"text"},{name:"category",label:"Category",values:"fixed",options:n0},{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"}],a0=new Map(ya.map(e=>[e.name,e])),rd=e=>a0.get(e.toLowerCase()),o0=/^\d{4}-\d{2}-\d{2}$/,i0=e=>/[\s"]/.test(e),l0=e=>i0(e)?`"${e.replace(/"/g,"")}"`:e,ad=(e,t)=>`${e}:${l0(t)}`,c0=e=>{if(!e.startsWith('"'))return e;const t=e.slice(1);return t.endsWith('"')?t.slice(0,-1):t};function jo(e){const t=[];let s=-1,r=!1;for(let a=0;a<e.length;a++){const o=e[a];if(o==='"'){r=!r,s<0&&(s=a);continue}if(!r&&/\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 od(e){const t=e.indexOf(":");if(t<=0)return;const s=e.slice(t+1);return{name:e.slice(0,t).toLowerCase(),value:c0(s),rawValue:s}}function u0(e,t,s){if(!o0.test(s))return;const r=Date.parse(`${s}T00:00:00Z`);if(!Number.isNaN(r))return{type:e,raw:t,value:s,epochSeconds:Math.floor(r/1e3)}}function d0(e){const t=e.toLowerCase(),s=r0[t];return s||Object.values(Je).find(a=>a===t)}function f0(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 m0(e,t){const s=od(e);if(!s||s.value.length===0)return;const{name:r,value:a}=s;switch(r){case"from":return{type:"from",raw:e,value:a};case"subject":return{type:"subject",raw:e,value:a};case"category":{const o=d0(a);return o?{type:"category",raw:e,value:a,category:o}:void 0}case"is":return f0(e,a);case"has":return a.toLowerCase()==="attachment"?{type:"hasAttachment",raw:e}:void 0;case"before":case"after":return u0(r,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 Ls(e,t={}){const s=[],r=[];for(const a of jo(e)){const o=m0(a.raw,t);o?s.push(o):r.push(a.raw)}return{freeText:r.join(" "),tokens:s}}function h0(e,t){return jo(e).filter(s=>s.raw!==t.raw).map(s=>s.raw).join(" ")}function id(e){switch(e.type){case"from":return`From: ${e.value}`;case"subject":return`Subject: ${e.value}`;case"category":return`Category: ${nd[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 p0=20,g0=new Set(Object.values(Je)),x0=e=>e!==void 0&&g0.has(e)?e:void 0,b0=e=>{if(e.some(t=>t.type==="isUnread"))return!1;if(e.some(t=>t.type==="isRead"))return!0};function ld({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=ke(),r=os(),a=St({select:y=>y.matches}),o=So(s),{freeText:i,tokens:l}=Ls(o,r),u=i.length>0,f=l.find(y=>y.type==="category"),d=x0(t)??f?.category,m=l.some(y=>y.type==="hasAttachment")?!0:void 0,h=l.some(y=>y.type==="isStarred")?!0:void 0,g=b0(l),x=l.find(y=>y.type==="after"),p=l.find(y=>y.type==="before"),b=l.find(y=>y.type==="in"),v=Hb({matches:a,callerMailboxId:e,inTokenMailboxId:b?.mailboxId}),{data:S,isLoading:w}=ue({...Pl({query:{query:i,mailboxId:v,limit:p0,...d!==void 0?{category:d}:{},...m!==void 0?{hasAttachment:m}:{},...h!==void 0?{hasStars:h}:{},...g!==void 0?{isRead:g}:{},...x?{sentDateFrom:x.epochSeconds}:{},...p?{sentDateTo:p.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:S?.items??[],isLoading:u&&w}}const v0=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),y0=e=>[...e].sort(v0);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:Bt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:yr(e.category),suspicious:t}}function nl(e){return e.filter(t=>t.muted!==!0)}function w0(e,t){const s=new Set,r=[];for(const a of[...e,...t])s.has(a.id)||(s.add(a.id),r.push(a));return r.sort((a,o)=>(o.sentDate??0)-(a.sentDate??0))}const rl=[{id:"personal",label:"Personal",category:Je.personal},{id:"transactional",label:"Transactional",category:Je.transactional},{id:"newsletter",label:"Newsletter",category:Je.newsletter},{id:"marketing",label:"Marketing",category:Je.marketing},{id:"social",label:"Social",category:Je.social},{id:"automated",label:"Automated",category:Je.automated},{id:"uncategorized",label:"Unclassified",category:Je.uncategorized}];function S0(e){const t=new Map(rl.map(r=>[r.category,[]]));for(const r of e){const a=r.category??Je.uncategorized;(t.get(a)??t.get(Je.uncategorized))?.push(r)}const s=[];for(const r of rl){const a=t.get(r.category);a&&a.length>0&&s.push({id:r.id,label:r.label,threads:a})}return s}function cd(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function ko(e,t){return t.every(s=>{switch(s.type){case"from":{const r=s.value.toLowerCase();return e.fromEmail.toLowerCase().includes(r)||e.fromName.toLowerCase().includes(r)}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 j0={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function k0(e){return j0[e]??e}function C0(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:Bt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function ud(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 N0(e,t){const{mailboxId:s,folder:r}=Ua(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?Bt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:k0(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...r?{folder:r}:{}}}function dd(e,t,s){const r=new Set(t),a=[];for(const o of[...e].sort((i,l)=>l.score-i.score))r.has(o.threadId)||(r.add(o.threadId),a.push(N0(o,s)));return a}const E0=e=>e.isRunning?"running":e.isCounting?"counting":e.isEscalated?"escalated":"idle",I0=2,fd=(e,t,s=!1)=>e>=I0||t!=="idle"||s,T0=768,R0=1024,md=e=>e!=="desktop",jr=()=>{const e=Wo(`(min-width: ${T0}px)`);return Wo(`(min-width: ${R0}px)`)?"desktop":e?"tablet":"phone"},hd=8;function Co(e,t){const s=Math.max(0,Math.min(t,e.length)),r=jo(e).find(o=>s>=o.start&&s<=o.end);if(!r)return{start:s,end:s,raw:""};const a=od(r.raw);return a?{start:r.start,end:r.end,raw:r.raw,name:a.name,value:a.value}:{start:r.start,end:r.end,raw:r.raw}}function M0(e,t){const s=Co(e,t);if(s.name===void 0)return{kind:"token",query:s.raw};const r=rd(s.name);if(r)return{kind:"value",token:r.name,source:r.values,query:s.value??""}}const A0={mailbox:"mailboxes",account:"accounts",contact:"contacts"},O0=(e,t)=>{if(e.values==="fixed")return e.options??[];const s=A0[e.values];return s?t[s]??[]:[]},D0=(e,t)=>{if(t==="")return 1;const s=e.toLowerCase();return s.startsWith(t)?0:s.includes(t)?1:-1},wa=(e,...t)=>{let s=-1;for(const r of t){if(r===void 0)continue;const a=D0(r,e);a<0||(s<0||a<s)&&(s=a)}return s},pd=e=>{const t=new Set;return e.filter(s=>s.rank>=0).sort((s,r)=>s.rank-r.rank).filter(s=>{const r=s.suggestion.value.toLowerCase();return t.has(r)?!1:(t.add(r),!0)}).slice(0,hd).map(s=>s.suggestion)},al=e=>({value:`${e.name}:`,label:`${e.name}:`,hint:e.label});function P0(e){const t=e.trim().toLowerCase();if(t==="")return ya.map(al);const s=[];for(const r of ya)if(s.push({rank:wa(t,`${r.name}:`,r.label),suggestion:al(r)}),r.values==="fixed")for(const a of r.options??[]){const o=ad(r.name,a.value);s.push({rank:wa(t,o,a.label),suggestion:{value:o,label:a.label??o,hint:o}})}return pd(s)}function L0(e,t,s){const r=t.trim().toLowerCase(),a=O0(e,s).map(o=>({rank:wa(r,o.value,o.label),suggestion:{value:ad(e.name,o.value),label:o.label??o.value,...o.hint?{hint:o.hint}:{}}}));return pd(a)}function F0(e,t,s={}){const r=Co(e,t);if(r.name===void 0)return P0(r.raw);const a=rd(r.name);return a?L0(a,r.value??"",s):[]}function $0(e,t,s){const r=Co(e,t),a=!s.value.endsWith(":"),o=/\s/.test(e.slice(r.end,r.end+1)),i=a&&!o?`${s.value} `:s.value;return{query:e.slice(0,r.start)+i+e.slice(r.end),cursor:r.start+i.length+(a&&o?1:0)}}const _0=e=>({value:e.normalizedEmail,...e.displayName?{label:e.displayName,hint:e.normalizedEmail}:{}});function z0(e){const t=new Map;for(const s of e){const r=s.email.toLowerCase(),a=r.split("@")[0];a&&!t.has(a)&&t.set(a,s.accountId),t.has(r)||t.set(r,s.accountId)}return t}function B0(e){const t=new Map;for(const s of e)for(const r of s){const a=r.fullPath?.toLowerCase();if(!a)continue;const o=a.split("/").pop();t.has(a)||t.set(a,r.mailboxId),o&&!t.has(o)&&t.set(o,r.mailboxId)}return t}function K0(e,t=[]){const s=e.flat().filter(o=>o.fullPath),r=new Map;for(const o of s){const i=ks(o.fullPath).toLowerCase();r.set(i,(r.get(i)??0)+1)}const a=new Map(t.map(o=>[o.accountId,o.email]));return s.map(o=>{const i=ks(o.fullPath),l=r.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 U0(e){const t=new Map;for(const s of e){const r=s.email.toLowerCase().split("@")[0]??"";t.set(r,(t.get(r)??0)+1)}return e.map(s=>{const r=s.email.split("@")[0]??s.email,a=t.get(r.toLowerCase())===1,o=s.displayName?.trim();return{value:a?r:s.email,label:o||s.email,...o?{hint:s.email}:{}}})}const q0=250,H0=2;function W0({query:e,cursor:t,enabled:s}){const{accounts:r}=ke(),{mailboxesByName:a}=os(),o=a!==void 0,i=s?M0(e,t):void 0,l=i?.source==="contact"?i.query.trim():"",u=lr(l,q0),{data:f}=ue({...nr({query:{q:u,limit:hd}}),enabled:u.length>=H0}),d=vt({queries:r.map(x=>({...Ue({path:{accountId:x.accountId}}),staleTime:1/0}))}),m=c.useMemo(()=>o?K0(d.map(x=>x.data?.items??[]),r):[],[o,d,r]),h=c.useMemo(()=>U0(r),[r]),g=c.useMemo(()=>(f?.items??[]).map(_0),[f]);return c.useMemo(()=>{if(!s)return[];const x=F0(e,t,{mailboxes:m,accounts:h,contacts:g});return o?x:x.filter(p=>p.value!=="in:")},[s,e,t,m,h,g,o])}const V0=new Set(["hasAttachment","isUnread","isRead","isStarred","category","before","after"]),gd=(e,{searchHadSemanticReach:t})=>{const s=[],r=[];let a,o;for(const u of e.tokens){if(u.type==="from"){s.push({field:"From",value:u.value});continue}if(u.type==="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}V0.has(u.type)&&r.push({type:u.type,label:id(u)})}const i=e.freeText.trim(),l=i.length>0;return l&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:r,targetAccountId:o,keptTerms:l,droppedSemantic:l&&t}},Q0=e=>e.clauses.length>0,xd=(e,{scope:t="standing",moveMailboxId:s}={})=>({clauses:e.clauses.map((r,a)=>({id:`search-${a}`,field:r.field,value:r.value})),matchOperator:e.matchOperator,moveMailboxId:s,scope:t,name:""}),bd="remit.recentSearches",Y0=5;function Sa(){try{const e=localStorage.getItem(bd);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function ol(e){const t=e.trim();if(!t)return Sa();const s=[t,...Sa().filter(r=>r!==t)].slice(0,Y0);try{localStorage.setItem(bd,JSON.stringify(s))}catch{return s}return s}const G0=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function X0(e){const{spam:t}=Oc([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let r;for(const[a,o]of s)(!r||o>r.count)&&(r={mailboxId:a,count:o});return r}const J0=(e,t)=>{const s=je(Ll()),{mutate:r,reset:a}=s,o=Pm(t),i=c.useCallback(()=>{!e||!o||(a(),r({path:{accountId:e},body:la({matchOperator:t.matchOperator,literalClauses:t.literalClauses})}))},[e,o,t.matchOperator,t.literalClauses,r,a]);return c.useEffect(()=>{i()},[i]),{seedCount:s.data?.matchedCount,uncountable:!o,isPending:o&&(s.isPending||s.data===void 0),isError:o&&s.isError,error:s.error,retry:i}},vd=({initialRule:e,widenAnchorCount:t=1})=>{const[s,r]=c.useState(e),[a,o]=c.useState(),i=c.useRef(0);return{rule:s,setRule:C=>r(C),handlers:{clauseEdit:a,onStartAddClause:()=>o({mode:"add",draft:{field:Va[0],value:""}}),onStartEditClause:C=>{const E=s.clauses.find(I=>I.id===C);E&&o({mode:"edit",clauseId:C,draft:{field:E.field,value:E.value}})},onRemoveClause:C=>r(E=>({...E,clauses:E.clauses.filter(I=>I.id!==C)})),onChangeDraftField:C=>o(E=>E&&{...E,draft:{...E.draft,field:C}}),onChangeDraftValue:C=>o(E=>E&&{...E,draft:{...E.draft,value:C}}),onSubmitClause:()=>{if(!a)return;const C=a.draft.field,E=Lm(C,a.draft.value);E!==""&&(r(I=>a.mode==="edit"&&a.clauseId?{...I,clauses:I.clauses.map(O=>O.id===a.clauseId?{id:O.id,field:C,value:E}:O)}:(i.current+=1,{...I,clauses:[...I.clauses,{id:`clause-${i.current}`,field:C,value:E}]})),o(void 0))},onCancelClause:()=>o(void 0),onAddWiden:()=>r(C=>({...C,widen:{anchorCount:Math.max(t,1)}})),onRemoveWiden:()=>r(C=>({...C,widen:void 0})),onChangeMatchOperator:C=>r(E=>({...E,matchOperator:C})),onChangeMove:C=>r(E=>({...E,moveMailboxId:C||void 0})),onChangeLabel:C=>r(E=>({...E,labelId:C||void 0})),onChangeScope:C=>r(E=>({...E,scope:C})),onChangeName:C=>r(E=>({...E,name:C})),onChangeUntil:C=>r(E=>({...E,until:C}))}}};function yd({progress:e,isDone:t,runningLabel:s,onClose:r}){const a=e.state==="Failed";return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[t?a?n.jsx("span",{className:"text-sm font-semibold text-danger",children:"Organize failed"}):n.jsx(cr,{className:"size-8 text-positive"}):n.jsx(et,{className:"size-8 animate-spin text-accent-2"}),!t&&n.jsx("p",{className:"text-sm font-medium text-fg",children:s}),t&&!a&&n.jsxs("div",{className:"text-sm text-fg",children:[n.jsx("p",{className:"font-medium",children:"Done"}),n.jsxs("p",{className:"mt-1 text-xs text-fg-muted",children:[e.appliedCount," of ",e.matchedCount," moved",e.failedCount>0?` · ${e.failedCount} failed`:"","."]})]}),t&&a&&n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:e.errorMessage||"Something went wrong. Please try again."}),t&&n.jsx(W,{variant:"primary",onClick:r,className:"mt-2",children:"Done"})]})}function ja(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(et,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Saving rule…"})]})}function wd({onClose:e}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(cr,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Filter saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"You can see it, and when it expires, under Settings › Filters."}),n.jsx(W,{variant:"primary",onClick:e,className:"mt-2",children:"Done"})]})}function Z0({onRetry:e,onClose:t}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx(cr,{className:"size-8 text-positive"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Rule saved"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"New mail follows it automatically. Moving the mail already in your mailbox didn't run — try again?"}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(W,{variant:"primary",onClick:e,children:"Move existing mail"}),n.jsx(W,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function Sd({onRetry:e,onClose:t}){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't save the rule"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(W,{variant:"primary",onClick:e,children:"Try again"}),n.jsx(W,{variant:"ghost",onClick:t,children:"Not now"})]})]})}function ew({accountId:e,conversion:t,seedCount:s,onClose:r}){const[a]=c.useState(()=>xd(t)),{rule:o,handlers:i}=vd({initialRule:a}),{data:l}=ue({...Ue({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),u=c.useMemo(()=>cn(l?.items??[]).map(g=>({id:g.mailboxId,label:ks(g.fullPath)})),[l?.items]),f=Kl(e,Qa(o),s),d=Ul(e),m=ql(e),h=()=>{const g=Hl(o);if(o.scope==="once"){d.start(g);return}m.createFilter(g,o.scope==="standing"?"standing":"temporary",(o.name??"").trim())};return d.isStarting||d.isRunning||d.isDone?n.jsx(yd,{progress:d.progress,isDone:d.isDone,runningLabel:"Organizing your mail…",onClose:r}):m.isPending?n.jsx(ja,{}):m.isSuccess?n.jsx(wd,{onClose:r}):m.isError?n.jsx(Sd,{onRetry:m.reset,onClose:r}):n.jsx(Fl,{rule:o,folders:u,preview:f,notice:n.jsx(Vg,{notice:{scopedOutFolder:t.scopedOut?.label,droppedFacets:t.droppedFacets.map(g=>g.label),droppedSemantic:t.droppedSemantic}}),semanticAvailable:!1,clauseFields:Va,...i,onCommit:h,onCancel:r})}function tw({open:e,accountId:t,parsed:s,searchHadSemanticReach:r,onClose:a}){const o=c.useMemo(()=>gd(s,{searchHadSemanticReach:r}),[s,r]),i=c.useMemo(()=>Qa(xd(o)),[o]),{seedCount:l,isPending:u,isError:f,retry:d}=J0(e?t:void 0,i);return e?n.jsx(Ra,{open:e,onClose:a,title:"Filter rule",children:f?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't build the filter"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:"Please try again."}),n.jsxs("div",{className:"mt-2 flex gap-2",children:[n.jsx(W,{variant:"primary",onClick:d,children:"Try again"}),n.jsx(W,{variant:"ghost",onClick:a,children:"Not now"})]})]}):u?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(et,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Turning your search into a filter…"})]}):n.jsx(ew,{accountId:t,conversion:o,seedCount:l,onClose:a})}):null}function jd({title:e,unreadCount:t,children:s,selectionBar:r,selectionSheet:a,footer:o,searchFilter:i,searchResults:l,searchLoading:u,relatedResults:f,relatedLoading:d,onSelectSearchResult:m,searchResultsLabel:h="Top matches",relatedResultsLabel:g="Related",searchResultsInBody:x=!1}){const{accounts:p,resultFolderIndex:b,searchQuery:v,searchInput:S,onSearchChange:w,onSearchClear:y,searchViewKey:N}=ke(),C=os(),E=$e(),I=Is(),O=jr(),[A,M]=c.useState(!1),[P,R]=c.useState(Sa),[j,F]=c.useState(!1),D=c.useRef(N);c.useEffect(()=>{D.current!==N&&(D.current=N,M(!1))},[N]);const[k,L]=c.useState(0),[T,$]=c.useState(!1),[V,ne]=c.useState(void 0),re=W0({query:S,cursor:k,enabled:T&&S.trim().length>0}),q=c.useCallback(ve=>{const ze=$0(S,k,ve);w(ze.query),ne({cursor:ze.cursor})},[S,k,w]),Q=Ml({count:re.length,onAccept:ve=>{const ze=re[ve];ze&&q(ze)}}),J={comboboxProps:Q.comboboxProps,onKeyDown:Q.handleKeyDown,onCaretChange:L,onFocusChange:$,...V?{caret:V}:{}},te=Q.open?n.jsx(Al,{id:Q.listId,suggestions:re,activeIndex:Q.activeIndex,optionId:Q.optionId,onPick:q,onHighlight:Q.setActiveIndex,label:"Search suggestions",className:"mx-row-inset mt-1 shrink-0"}):null,Z=S.trim().length>0,{mailboxesByName:se,accountsByName:ce}=C,xe=c.useMemo(()=>Ls(S,{mailboxesByName:se,accountsByName:ce}),[S,se,ce]),Te=xe.tokens.map(ve=>({label:id(ve),onRemove:()=>w(h0(S,ve))})),Y=l??[],z=f??[],B=Z?[{id:"top",label:h,results:Y},{id:"related",label:g,results:z}]:[],de=!(Y.length+z.length>0)&&(u===!0||d===!0),{scope:_e}=du(p),ae=St({select:ve=>ve.matches}),Ce=cu(ae),qe=Vb(ae,_e,Ce?b.get(Ce)?.role:void 0),Me=qe.kind==="global"?X0([...Y,...z]):void 0,U=Me?{kind:"global",onScopeToSpam:()=>E({to:"/mail/$mailboxId",params:{mailboxId:Me.mailboxId},search:{q:v||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:qe,He=xe.tokens.find(ve=>ve.type==="account")?.accountId??p[0]?.accountId,pe=z.length>0,fe=Z&&He?{onClick:()=>F(!0),disabledReason:Q0(gd(xe,{searchHadSemanticReach:pe}))?void 0:"Add a sender or words to filter on"}:void 0,Ve=fe&&!r?n.jsx(Dc,{...fe}):null,dt=j&&He?n.jsx(tw,{open:j,accountId:He,parsed:xe,searchHadSemanticReach:pe,onClose:()=>F(!1)}):null;if(O==="phone"&&A){const ve=ze=>{R(ol(S)),M(!1),m?.(ze)};return n.jsxs(n.Fragment,{children:[n.jsx(jg,{value:S,onChange:w,onClear:y,onCancel:()=>{M(!1),y()},filter:i,recentSearches:P,onPickRecent:w,makeFilter:fe,sections:B,loading:de,onSelectResult:ve,tokens:Te,scope:U,suggest:J,suggestList:te}),dt]})}const ft=G0({tier:O,hasLiveInput:Z,hasCommittedQuery:v.trim().length>0,bodyRendersCommittedResults:x}),Qe=ve=>{R(ol(S)),m?.(ve)},De=n.jsx(Pc,{value:S,sections:B,loading:de,onSelectResult:Qe,tokens:Te,scope:U}),Ae=ft?n.jsx("div",{className:"h-full overflow-y-auto",children:De}):s;return n.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[r??n.jsx(mg,{title:e,unreadCount:t,isDesktop:!1,showSearch:md(O),onMenuClick:()=>I?.openNav(),searchValue:S,onSearchChange:w,onSearchClear:y,searchOpen:A,onSearchOpenChange:M,searchSuggest:J}),te,Ve,n.jsx("div",{className:"min-h-0 flex-1",children:Ae}),o,dt,a]})}const sw=120,kd=({keyboardFocusedMessageId:e,openMessageId:t,enabled:s,open:r,delayMs:a=sw})=>{const o=c.useRef(r);o.current=r;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])},nw=(e,t,s)=>{const r=e.indexOf(s);if(r===-1)return[];const a=t===void 0?-1:e.indexOf(t);if(a===-1)return[s];const o=Math.min(a,r),i=Math.max(a,r);return e.slice(o,i+1)},rw=(e,t,s,r)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:r,aw=(e,t)=>{const s=new Set(t),r=new Set;for(const a of e)s.has(a)&&r.add(a);return r},Cd=(e,t,s)=>{if(e.length===0)return;const r=t===void 0?-1:e.indexOf(t);if(r===-1)return s>0?e[0]:e[e.length-1];const a=Math.min(Math.max(r+s,0),e.length-1);return e[a]},Nd=e=>{const[t,s]=c.useState(new Set),[r,a]=c.useState(void 0),o=c.useCallback(p=>t.has(p),[t]),i=c.useCallback(p=>{a(p),s(b=>{const v=new Set(b);return v.has(p)?v.delete(p):v.add(p),v})},[]),l=c.useCallback(p=>{a(p),s(b=>{if(b.has(p))return b;const v=new Set(b);return v.add(p),v})},[]),u=c.useCallback(p=>{s(b=>{if(!b.has(p))return b;const v=new Set(b);return v.delete(p),v})},[]),f=c.useCallback(p=>{s(new Set(p))},[]),d=c.useCallback(()=>{a(void 0),s(new Set)},[]),m=c.useCallback(p=>{s(b=>p.every(S=>b.has(S))?new Set:new Set(p))},[]),h=c.useCallback(p=>{a(p)},[]),g=c.useCallback(p=>{s(b=>{if(b.size===0)return b;const v=aw(b,p);return v.size===b.size?b:v})},[]),x=c.useCallback((p,b,v)=>{const S=rw(p,r,v,b);s(w=>{const y=nw(p,S,b);if(y.length===0)return w;const N=new Set(w);for(const C of y)N.add(C);return N}),a(S)},[r]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:l,deselect:u,selectAll:f,clearSelection:d,toggleAll:m,selectRange:x,setAnchor:h,anchorId:r,intersectWith:g}},Ed=(e,t)=>!t&&e>0,ow=(e,t)=>e==="BACK"&&t,iw=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:r})=>{const[a,o]=c.useState(s),[i,l]=c.useState(),u=c.useCallback(D=>{l(k=>k===D?k:void 0),o(D)},[]),f=Nd(),{selectedCount:d,toggle:m,clearSelection:h,selectRange:g,setAnchor:x,selectAll:p}=f,b=Ed(d,t),v=c.useRef(null),S=c.useRef(!1),w=c.useCallback(()=>{r?.(),h()},[h,r]),y=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),N=c.useCallback(D=>{if(D<0||D>=e.length)return;const k=e[D];if(b){m(k);return}v.current=k,S.current=!1,l(k),o(k)},[e,b,m]),C=c.useCallback(()=>{e.length!==0&&N(y<0?0:Math.min(y+1,e.length-1))},[e.length,y,N]),E=c.useCallback(()=>{e.length!==0&&N(y<=0?0:y-1)},[e.length,y,N]),I=c.useCallback(()=>N(0),[N]),O=c.useCallback(()=>N(e.length-1),[N,e.length]),A=c.useCallback(()=>{a&&m(a)},[a,m]),M=c.useCallback((D,k)=>k.shiftKey?(g(e,D,a),!0):k.metaKey||k.ctrlKey?(m(D),!0):(w(),x(D),!1),[e,a,g,m,w,x]),P=c.useCallback(D=>{const k=Cd(e,a,D);k!==void 0&&(g(e,k),v.current=k,S.current=!1,l(void 0),o(k))},[e,a,g]),R=c.useCallback(()=>P(-1),[P]),j=c.useCallback(()=>P(1),[P]),F=c.useCallback(()=>{e.length>0&&p(e)},[e,p]);return{focusedMessageId:a,setFocusedMessageId:u,keyboardFocusedMessageId:i,focusIndex:y,pendingDomFocusRef:v,cursorMovedByPointerRef:S,selection:f,isMultiSelectMode:b,exitSelection:w,moveFocusToIndex:N,focusNext:C,focusPrevious:E,focusFirst:I,focusLast:O,toggleFocusedSelection:A,extendRangeUp:R,extendRangeDown:j,selectAllLoaded:F,handleRowSelect:M}};function Id(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const lw=e=>{const{mailboxId:t,messages:s}=e,r=we(),{pushError:a}=tt(),{mutateAsync:o,isPending:i}=je({...cm(),onError:(u,f)=>{a({title:f.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:lt(u),error:u})},onSettled:(u,f,d)=>{Nt(r,Ct(br(d.body.messageIds??[],s??[],t)))}});return{applyLabel:c.useCallback((u,f,d)=>{u.length!==0&&xr(u,m=>o({body:{messageIds:m,labelId:f,action:d}}))},[o]),isPending:i}};function cw({accountId:e,mailboxId:t,messageIds:s}){const{labels:r}=Xl(e),{applyLabel:a}=lw({mailboxId:t}),o=c.useMemo(()=>r.map(i=>({key:i.labelId,label:i.name,icon:n.jsx("span",{className:`size-2.5 rounded-full ${um(i.color)?Ho[i.color]:Ho.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[r,s,a]);return o.length===0?null:n.jsx(Ec,{triggerLabel:"Apply label to selected messages",triggerIcon:n.jsx(dm,{className:"size-4"}),items:o})}const No=({selectedCount:e,onDelete:t,onClearSelection:s,onMarkAsRead:r,onMove:a,onOrganize:o,isDeleting:i=!1,isMoving:l=!1,accountId:u,currentMailboxId:f,selectedMessageIds:d,moveDisabledHint:m,selectAll:h,statusLabel:g,isCounting:x=!1,progress:p,notice:b})=>{if(e===0)return null;const v=p!==void 0,S=i||l||v,w=!v&&!x,y=!!a&&!!u&&!!f,N=!!u&&!!f&&!!d?.length,C=!!o&&!!u&&!!f&&!m&&!g,E=h?.checked?`All ${e} loaded selected`:`${e} ${e===1?"message":"messages"} selected`;return n.jsxs("div",{className:"sticky top-0 z-10 flex flex-col bg-surface-sunken border-b border-line",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-2",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("button",{type:"button",onClick:s,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded hover:bg-surface-raised transition-colors","aria-label":"Clear selection",children:n.jsx(Ze,{className:"size-4 text-fg-muted"})}),h&&n.jsx("label",{className:"flex size-11 shrink-0 cursor-pointer items-center justify-center",children:n.jsx(un,{"aria-label":"Select all",checked:h.checked,indeterminate:h.indeterminate,onChange:h.onChange})}),n.jsx("span",{className:"text-sm font-medium",children:g??E}),m&&!b&&n.jsx("span",{className:"text-xs text-fg-muted",role:"status","aria-live":"polite",children:m})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[C&&o&&n.jsxs("button",{type:"button",onClick:S?void 0:o,className:"min-h-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Organize similar messages",children:[n.jsx(xt,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:"Organize"})]}),w&&r&&n.jsx("button",{type:"button",onClick:S?void 0:r,className:"min-h-11 min-w-11 inline-flex items-center justify-center rounded text-sm font-medium transition-colors hover:bg-surface-raised","aria-label":"Mark as read","aria-busy":S,children:n.jsx(Rs,{className:"size-4"})}),w&&y&&a&&u&&f&&n.jsx(Ds,{accountId:u,currentMailboxId:f,onMove:S?()=>{}:a,disabledHint:m,variant:"icon-only",label:"Move selected messages"}),w&&N&&u&&f&&d&&n.jsx(cw,{accountId:u,mailboxId:f,messageIds:d}),w&&n.jsxs("button",{type:"button",onClick:S?void 0:t,className:Ne("min-h-11 min-w-11 inline-flex items-center justify-center gap-1.5 px-3 rounded text-sm font-medium transition-colors","bg-danger text-canvas hover:bg-danger/90"),"aria-label":"Delete selected messages","aria-busy":i,children:[i?n.jsx(et,{className:"size-4 animate-spin"}):n.jsx(ct,{className:"size-4"}),n.jsx("span",{className:"hidden sm:inline",children:i?"Deleting...":"Delete"})]})]})]}),p&&n.jsx("div",{className:"px-3 pb-2",children:n.jsx(so,{value:p.value,max:p.max,tone:p.tone})}),b&&n.jsx(ss,{tone:b.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-3 mb-2",children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[b.text&&n.jsx("span",{children:b.text}),b.action&&n.jsx("button",{type:"button",onClick:b.action.onClick,className:"-my-1 min-h-11 shrink-0 inline-flex items-center px-3 rounded text-sm font-medium transition-colors hover:bg-surface-raised",children:b.action.label})]})})]})},Eo=c.createContext(null),uw=e=>{const t=c.useContext(Eo);return t?t.rowInteraction(e):null},Td=()=>{const e=c.useContext(Eo);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},dw="[data-message-id]",fw=e=>Array.from(e.querySelectorAll(dw)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),mw=(e,t)=>e.length===t.length&&e.every((s,r)=>s===t[r]),hw=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const r=e.current;if(!r)return;const a=()=>{const i=fw(r);s(l=>mw(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(r,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function Rd({selectedMessageId:e,onOpen:t,onDeleteMessages:s,isDeleting:r=!1,commandsRef:a,onTriageContextChange:o,children:i}){const l=_t(),u=c.useRef(null),f=hw(u),d=iw({orderedIds:f,isDesktop:l,initialFocusedId:e}),{focusedMessageId:m,setFocusedMessageId:h,pendingDomFocusRef:g,cursorMovedByPointerRef:x,selection:p,isMultiSelectMode:b,exitSelection:v,handleRowSelect:S}=d,{selectedIds:w,selectedCount:y,isSelected:N,toggle:C,select:E,toggleAll:I}=p,O=f.length>0&&f.every(se=>w.has(se)),A=c.useCallback(()=>{f.length>0&&I(f)},[f,I]),{intersectWith:M}=p;c.useEffect(()=>{M(f)},[M,f]),c.useEffect(()=>{const se=g.current;se!==null&&(g.current=null,u.current?.querySelector(`[data-message-id="${se}"]`)?.focus())});const P=c.useCallback(se=>{x.current=!0,h(se)},[x,h]),R=c.useCallback(se=>{l||E(se)},[l,E]),j=c.useCallback(()=>{m&&t(m)},[m,t]),F=c.useCallback(se=>t(se,{replace:!0}),[t]);kd({keyboardFocusedMessageId:d.keyboardFocusedMessageId,openMessageId:e,enabled:l&&y===0,open:F});const[D,k]=c.useState(null),L=c.useCallback(se=>!s||se.length===0?!1:(k(se),!0),[s]),T=c.useCallback(()=>{L(Array.from(w))},[L,w]),$=c.useCallback(()=>D!==null?!0:y>0?L(Array.from(w)):m?L([m]):!1,[D,y,w,m,L]),V=c.useCallback(()=>{D!==null&&(s?.(D),k(null),v())},[D,s,v]),ne=c.useCallback(()=>k(null),[]),re=c.useCallback(()=>y===0?!1:(v(),!0),[y,v]),q=f.length>0;c.useEffect(()=>{if(a){if(!q){a.current=null;return}return a.current={focusNext:d.focusNext,focusPrevious:d.focusPrevious,focusFirst:d.focusFirst,focusLast:d.focusLast,openFocused:j,toggleSelect:d.toggleFocusedSelection,extendSelectDown:d.extendRangeDown,extendSelectUp:d.extendRangeUp,selectAll:d.selectAllLoaded,clearSelection:re,requestDelete:$,toggleDensity:()=>{}},()=>{a.current=null}}},[a,q,d.focusNext,d.focusPrevious,d.focusFirst,d.focusLast,d.toggleFocusedSelection,d.extendRangeDown,d.extendRangeUp,d.selectAllLoaded,j,re,$]);const Q=c.useMemo(()=>Array.from(w),[w]),J=D!==null;c.useEffect(()=>{o?.({focusedMessageId:m,selectedIds:Q,orderedIds:f,hasList:q,blocksKeyboard:J})},[o,m,Q,f,q,J]);const te=Id(f,m),Z=c.useMemo(()=>({selectedIds:w,selectedCount:y,exitSelection:v,requestDeleteSelection:T,orderedIds:f,allSelected:O,toggleAllLoaded:A,rowInteraction:se=>({focused:se===m,isTabStop:se===te,isDesktop:l,onFocusRow:P,selection:{isChecked:N(se),onToggleCheck:C,onRowSelect:S,isMultiSelectMode:b,onLongPress:R}})}),[w,y,v,T,f,O,A,m,te,l,P,N,C,S,b,R]);return n.jsxs(Eo.Provider,{value:Z,children:[n.jsx("div",{ref:u,className:"contents",children:i}),n.jsx(Ga,{isOpen:J,title:Ql(D?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:r,onConfirm:V,onCancel:ne})]})}function pw({onMarkAsRead:e,isDeleting:t}){const{selectedIds:s,selectedCount:r,exitSelection:a,requestDeleteSelection:o}=Td(),i=c.useCallback(()=>{e?.(Array.from(s)),a()},[e,s,a]);return n.jsx(No,{selectedCount:r,onDelete:o,onClearSelection:a,onMarkAsRead:e?i:void 0,isDeleting:t})}const ka=e=>({shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey}),il=e=>e.shiftKey||e.metaKey||e.ctrlKey,ta=e=>{e.preventDefault(),e.stopPropagation()},Md=(e,t)=>{const s=c.useRef(!1),r=c.useCallback(i=>{if(s.current=!1,i.button!==0)return;const l=ka(i);il(l)&&t?.(e,l)&&(ta(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,ta(i),!0;const l=ka(i);return!il(l)||!t?.(e,l)?!1:(ta(i),l.shiftKey&&window.getSelection()?.removeAllRanges(),!0)},[t,e]);return{onMouseDown:r,onContextMenu:a,claimClick:o}},gw=({thread:e,active:t=!1,focused:s,isTabStop:r,density:a="comfortable",isDesktop:o,badge:i,selection:l,inListbox:u=!1,linkMailboxId:f,onClick:d,onFocusRow:m})=>{const h=we(),g=e.id,x=uw(g),p=s??x?.focused??!1,b=r??x?.isTabStop??!1,v=l??x?.selection,S=m??x?.onFocusRow,w=o??x?.isDesktop??!0,y=v?.isChecked??!1,N=v?.isMultiSelectMode??!1,C=v?.onToggleCheck,E=v?.onRowSelect,I=v?.onLongPress,O=c.useCallback(T=>{T.preventDefault(),T.stopPropagation(),C?.(g)},[C,g]),A=Md(g,E),M=c.useCallback(T=>{if(!A.claimClick(T)){if(!w){if(N){T.preventDefault(),T.stopPropagation(),C?.(g);return}d?.();return}E?.(g,ka(T)),d?.()}},[A,w,N,C,E,d,g]),P=c.useCallback(()=>{I?.(g)},[I,g]),{longPressProps:R}=kc({onLongPress:P,accessibilityDescription:y?"Deselect message":"Select message"}),j=c.useCallback(()=>{h.prefetchQuery(Ka({path:{messageId:g}}))},[h,g]),F=c.useCallback(()=>{j(),S?.(g)},[j,S,g]),D=Ts({"data-list-row":"","data-message-row":!0,"data-message-id":g,...u?{role:"option","aria-selected":y}:{},tabIndex:b?0:-1,onClick:M,onMouseDown:A.onMouseDown,onContextMenu:A.onContextMenu,onMouseEnter:j,onFocus:F},w||!v?{}:R),k=Ne(a==="compact"?wc({active:t,focused:p}):Ne("group",As({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",y&&"bg-accent-soft",!w&&"min-h-11 select-none [-webkit-touch-callout:none]"),L=a==="compact"?n.jsx(Sc,{thread:e}):n.jsx(to,{thread:e,badge:i,selection:v?{checked:y,alwaysVisible:N,onToggle:O}:void 0});return f===void 0?n.jsx("button",{type:"button",...D,className:k,children:L}):n.jsx(wt,{to:"/mail/$mailboxId",params:{mailboxId:f},search:T=>({...T,selectedMessageId:g}),...D,className:k,children:L})},Xn=c.memo(gw),Ad=(e,t,s)=>{const r=je(Ll()),{mutate:a,reset:o}=r,[i,l]=c.useState(!1),u=c.useMemo(()=>Fm(s),[s]),f=c.useCallback(()=>{!e||!t||(l(!1),a({path:{accountId:e},body:la({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=c.useCallback(()=>{l(!1),o()},[o]),m=r.data,h=m?.semanticUnavailable===!0&&!i&&u.length>0;c.useEffect(()=>{!h||!e||(l(!0),a({path:{accountId:e},body:la($m(u))}))},[h,e,u,a]);const g=i||(m?.semanticUnavailable??!1),x=r.isPending||h,p=i?{matchOperator:"Or",literalClauses:_m(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:f,reset:d,matchedCount:x?void 0:m?.matchedCount,messageIds:x?void 0:m?.messageIds,semanticUnavailable:g,senderFallback:i,senders:u,matchPredicate:p,isPending:x,isError:r.isError,error:r.error}},xw=({entry:e,hasSeed:t,previewStatus:s,matchedCount:r})=>{if(e==="something-else"&&!t)return{kind:"something-else"};if(s==="error")return{kind:"error"};if(s!=="success")return{kind:"widening"};const a=r??0;return{kind:"organize",matchedCount:a,fallback:a===0}},Od=8,Dd=e=>e==="From"||e==="FromDomain",bw=e=>({value:e.email,label:e.displayName??e.email,...e.displayName?{hint:e.email}:{},...e.fromSelection?{source:"selected"}:{}}),vw=e=>{const t=zm(e.email);if(t!==null)return{value:t,...e.fromSelection?{source:"selected"}:{}}},yw=(e,t)=>e.value.toLowerCase().includes(t)||(e.label??"").toLowerCase().includes(t),ww=(e,t,s)=>{if(!Dd(e))return[];const r=t.trim().toLowerCase(),a=new Set,o=[];for(const i of s){if(i.email.trim()==="")continue;const l=e==="From"?bw(i):vw(i);if(!l)continue;const u=l.value.toLowerCase();if(!(u===""||a.has(u))&&(a.add(u),u!==r&&!(r!==""&&!yw(l,r))&&(o.push(l),o.length===Od)))break}return o},Sw=250,jw=2,kw=(e,t,s)=>{const r=t.trim(),a=lr(r,Sw),o=e!==void 0&&Dd(e),{data:i}=ue({...nr({query:{q:a,limit:Od}}),enabled:o&&a.length>=jw});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 ww(e,r,l)},Cw=()=>[ar({path:{mailboxId:""}}),za({path:{mailboxId:""}}),Ba()].map(e=>[{_id:e[0]._id}]),Nw=e=>Su(e)?e.pages:ju(e)?[e]:[],Ew=e=>typeof e=="object"&&e!==null&&typeof e.messageId=="string",Iw=(e,t)=>{const s=new Set(t),r=new Map;for(const a of e)for(const o of Nw(a))for(const i of o.items){if(!Ew(i)||!s.has(i.messageId))continue;const l=i.subject?.trim();l&&r.set(i.messageId,l)}return t.map(a=>r.get(a)).filter(a=>a!==void 0)},Tw=e=>{const t=we(),s=e.join("\0");return c.useMemo(()=>{const r=Cw().flatMap(a=>t.getQueriesData({queryKey:a}).map(([,o])=>o));return Iw(r,e)},[t,s])};function Pd({accountId:e,selectedMessageIds:t,seedCount:s,semanticUnavailable:r=!1,senders:a=[],seedMatchMode:o,seedMailboxId:i,seedScope:l,onClose:u}){const f=t[0],d=r&&a.length>0,m=Tw(t),[h,g]=c.useState(()=>o??Bm(r)),[x]=c.useState(()=>Km({anchorMessageId:f,semanticUnavailable:r,matchMode:h,senders:a,subjects:m,selectionCount:t.length,seedMailboxId:i,seedScope:l})),{rule:p,setRule:b,handlers:v}=vd({initialRule:x,widenAnchorCount:t.length}),S=T=>{T!==h&&(g(T),b($=>({...$,...qm(T,{anchorMessageId:f,senders:a,subjects:m,selectionCount:t.length,keepClauses:$.clauses.filter(V=>!V.derived),currentOperator:$.matchOperator})})))},w=kw(v.clauseEdit?.draft.field,v.clauseEdit?.draft.value??"",a),{data:y}=ue({...Ue({path:{accountId:e}}),staleTime:Number.POSITIVE_INFINITY}),N=c.useMemo(()=>cn(y?.items??[]).map(T=>({id:T.mailboxId,label:ks(T.fullPath)})),[y?.items]),{labels:C}=Xl(e),E=c.useMemo(()=>C.map(T=>({id:T.labelId,name:T.name,color:T.color})),[C]),{createLabel:I}=Vm(e),O=async T=>{const $=await I(T);return{id:$.labelId,name:$.name,color:$.color}},A=Kl(e,Qa(p,f),s),M=Ul(e),P=ql(e),{createFolder:R}=Yl(e),[j,F]=c.useState(),D=c.useRef(!1),k=()=>{const T=Hl(p,f);if(p.scope==="once"){M.start(T);return}D.current=!1,F(Um(T)?T:void 0),P.createFilter(T,p.scope==="standing"?"standing":"temporary",(p.name??"").trim())};c.useEffect(()=>{!j||D.current||!P.isSuccess||(D.current=!0,M.start(j))},[j,P.isSuccess,M.start]);const L=()=>{j&&M.start(j)};return M.isStarting||M.isRunning||M.isDone?n.jsx(yd,{progress:M.progress,isDone:M.isDone,runningLabel:d?"Organizing mail from these senders…":h==="properties"?"Organizing matching mail…":"Organizing similar mail…",onClose:u}):P.isSuccess&&M.isError?n.jsx(Z0,{onRetry:L,onClose:u}):P.isPending?n.jsx(ja,{}):P.isSuccess?j?n.jsx(ja,{}):n.jsx(wd,{onClose:u}):P.isError?n.jsx(Sd,{onRetry:P.reset,onClose:u}):n.jsx(Fl,{rule:p,folders:N,labels:E,preview:A,semanticAvailable:!r,matchMode:r?void 0:h,onChangeMatchMode:S,clauseFields:Va,clauseSuggestions:w,...v,onCreateFolder:R,onCreateLabel:O,onCommit:k,onCancel:u})}const ll=(e,t)=>e.find(s=>s.label.toLowerCase()===t),Rw=(e,t)=>{const s=[],r=ll(e,"inbox");r&&s.push({id:"keep-inbox",label:"Always keep in Inbox",seed:{moveMailboxId:r.id,scope:"standing"}});const a=ll(e,"archive");a&&s.push({id:"file-archive",label:"File in Archive",seed:{moveMailboxId:a.id}});const o=t?e.find(i=>i.id===t):void 0;return o&&s.push({id:"move-junk",label:`Move to ${o.label}`,seed:{moveMailboxId:o.id}}),s},Mw=(e,t)=>{const s=e.toLowerCase(),r=t.find(o=>s.includes(o.label.toLowerCase())),a=/\b(always|keep|future|from now)\b/.test(s);return{moveMailboxId:r?.id,scope:a?"standing":void 0}};function Aw({folderOptions:e,junkMailboxId:t,onSeed:s}){const[r,a]=c.useState(""),o=c.useMemo(()=>Rw(e,t),[e,t]),i=()=>{const l=r.trim();l&&s(Mw(l,e))};return n.jsxs("div",{className:"flex min-h-0 flex-col",children:[n.jsxs("div",{className:"border-b border-line px-5 py-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-fg",children:"What should Remit do?"}),n.jsx("p",{className:"mt-0.5 text-xs text-fg-muted",children:"Pick a shortcut or say it in your own words."})]}),n.jsx("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto px-5 py-4",children:o.map(l=>n.jsx(W,{variant:"secondary",onClick:()=>s(l.seed),className:"h-12 w-full justify-start px-4",children:l.label},l.id))}),n.jsxs("div",{className:"flex items-center gap-2 border-t border-line px-5 py-3",children:[n.jsx(fm,{value:r,onChange:l=>a(l.target.value),onKeyDown:l=>l.key==="Enter"&&i(),placeholder:"Tell Remit what to do…","aria-label":"Tell Remit what to do",className:"flex-1"}),n.jsx(W,{variant:"primary","aria-label":"Send",onClick:i,disabled:!r.trim(),icon:n.jsx(Ah,{className:"size-4"}),className:"size-9 shrink-0 px-0"})]})]})}const Ow=e=>e?.scope==="standing"?"standing":void 0,Dw=(e,t,s)=>e?"error":t?"pending":s!==void 0?"success":"idle";function Ld({entry:e,accountId:t,selectedMessageIds:s,selectedSenders:r,junkMailboxId:a,onClose:o}){const i=s[0],[l,u]=c.useState(),{preview:f,matchedCount:d,semanticUnavailable:m,senders:h,isPending:g,isError:x,error:p}=Ad(t,i,r);c.useEffect(()=>{f()},[f]);const{data:b}=ue({...Ue({path:{accountId:t}}),staleTime:Number.POSITIVE_INFINITY}),v=c.useMemo(()=>cn(b?.items??[]).map(w=>({id:w.mailboxId,label:ks(w.fullPath)})),[b?.items]),S=xw({entry:e,hasSeed:l!==void 0,previewStatus:Dw(x,g,d),matchedCount:d});return n.jsxs(Bl,{open:!0,onClose:o,dismissLabel:"Dismiss organize",children:[S.kind==="something-else"&&n.jsx(Aw,{folderOptions:v,junkMailboxId:a,onSeed:u}),S.kind==="widening"&&n.jsx(Pw,{}),S.kind==="error"&&n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:p instanceof Error?p.message:"Please try again."}),n.jsx(W,{variant:"ghost",onClick:o,className:"mt-2",children:"Close"})]}),S.kind==="organize"&&n.jsx(Pd,{accountId:t,selectedMessageIds:s,seedCount:S.matchedCount,seedScope:Ow(l),seedMailboxId:l?.moveMailboxId,semanticUnavailable:m,senders:h,onClose:o})]})}function Pw(){return n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(et,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]})}function Fd({open:e,accountId:t,selectedMessageIds:s,selectedSenders:r,onClose:a}){const o=s[0],{preview:i,reset:l,matchedCount:u,semanticUnavailable:f,senders:d,isPending:m,isError:h,error:g}=Ad(t,o,r);c.useEffect(()=>{e&&i()},[e,i]);const x=()=>{l(),a()};return e?n.jsx(Ra,{open:e,onClose:x,title:"Filter rule",children:m||u===void 0?h?n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-8 text-center",children:[n.jsx("p",{className:"text-sm font-medium text-danger",children:"Couldn't find similar messages"}),n.jsx("p",{className:"max-w-xs text-xs text-fg-muted",children:g instanceof Error?g.message:"Please try again."}),n.jsx(W,{variant:"ghost",onClick:x,className:"mt-2",children:"Close"})]}):n.jsxs("div",{className:"flex flex-col items-center gap-3 px-5 py-10 text-center",children:[n.jsx(et,{className:"size-8 animate-spin text-accent-2"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"Finding similar messages…"})]}):n.jsx(Pd,{accountId:t,selectedMessageIds:s,seedCount:u,semanticUnavailable:f,senders:d,onClose:x})}):null}const Lw=200,Fw={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0,contacts:e=>e.trust==="vip"||e.trust==="wellknown",today:e=>e.sentDate!=null&&new Date(e.sentDate).toDateString()===new Date().toDateString()},cl=()=>n.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>n.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[n.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsxs("div",{className:"flex justify-between gap-2",children:[n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),n.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),n.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),$w=({accountEmail:e})=>{const t=$e();return n.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[n.jsx(ts,{className:"size-3.5 shrink-0"}),n.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),n.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})};function _w({sections:e,briefCategory:t,selectedThreadId:s,onSelectThread:r}){const a=t==="all",o=e.flatMap(l=>l.threads).filter(l=>l.category===t),i=a?e.length===0:o.length===0;return n.jsxs("div",{className:"h-full overflow-y-auto",children:[a?e.map(l=>n.jsx(mm,{section:l,Row:Xn,selectedThreadId:s,onSelectThread:r},l.id)):n.jsx("div",{className:"divide-y divide-line",children:o.map(l=>n.jsx(Xn,{thread:l,active:l.id===s,onClick:()=>r?.(l.id)},l.id))}),i&&n.jsx("div",{className:"px-row-inset py-6 text-center text-2xs text-fg-subtle",children:"No threads match these filters."})]})}const zw=(e,t)=>{if(t.size===0)return{};const s=new Set,r=new Set;for(const o of e)t.has(o.id)&&(o.accountId&&s.add(o.accountId),o.mailboxId&&r.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 r.size>1?{accountId:a,moveDisabledHint:`Move only works within one folder — this selection spans ${r.size} folders`}:{accountId:a,mailboxId:r.size===1?[...r][0]:void 0}};function Bw({header:e,rows:t,isDesktop:s,onMarkMessagesRead:r,children:a}){const{selectedIds:o,selectedCount:i,exitSelection:l,requestDeleteSelection:u,orderedIds:f,allSelected:d,toggleAllLoaded:m}=Td(),h=c.useMemo(()=>zw(t,o),[t,o]),{junkMailboxId:g}=gn(h.accountId),{moveMessages:x,isPending:p}=Lt({mailboxId:h.mailboxId??"",accountId:h.accountId}),[b,v]=c.useState(!1),[S,w]=c.useState(null);c.useEffect(()=>{i>0||(v(!1),w(null))},[i]);const y=c.useMemo(()=>Array.from(o),[o]),N=c.useMemo(()=>{const k=[];for(const L of t)o.has(L.id)&&L.fromEmail&&k.push(L.fromEmail);return k},[t,o]),C=c.useCallback(()=>{r?.(y),l()},[r,y,l]),E=c.useCallback(k=>{y.length!==0&&(x(y,k),l())},[x,y,l]),I=c.useCallback(()=>{g&&E(g)},[g,E]),O=!!h.accountId&&!!h.mailboxId,A=O&&!!g&&g!==h.mailboxId,M=c.useMemo(()=>f.length>0?{checked:d,indeterminate:i>0&&!d,onChange:m}:void 0,[f.length,d,i,m]),P=s&&i>0?n.jsx(No,{selectedCount:i,onDelete:u,onClearSelection:l,onMarkAsRead:r?C:void 0,onMove:O?E:void 0,onOrganize:()=>v(!0),isMoving:p,accountId:h.accountId,currentMailboxId:h.mailboxId,selectedMessageIds:y,moveDisabledHint:h.moveDisabledHint,selectAll:M}):void 0,R=h.moveDisabledHint?{tone:"warning",text:h.moveDisabledHint}:void 0,j=!s&&i>0&&fd(i,"idle",R!==void 0),F=S&&h.accountId&&!s&&i>0?n.jsx(Ld,{entry:S,accountId:h.accountId,selectedMessageIds:y,selectedSenders:N,junkMailboxId:g,onClose:()=>{w(null),l()}}):void 0,D=j||F?n.jsxs(n.Fragment,{children:[j&&n.jsx(Lc,{count:i,onCancel:l,onDelete:u,onJunk:A?I:void 0,onMarkRead:r?C:void 0,onSelectSimilar:O?()=>w("select-similar"):void 0,onSomethingElse:O?()=>w("something-else"):void 0,moveSlot:O&&h.accountId&&h.mailboxId?n.jsx(Ds,{accountId:h.accountId,currentMailboxId:h.mailboxId,onMove:p?()=>{}:E,label:"Move selected messages"}):void 0,isBusy:p,selectAll:M,notice:R}),F]}):void 0;return n.jsxs(n.Fragment,{children:[n.jsx(jd,{...e,selectionBar:P,selectionSheet:D,children:n.jsx("div",{className:"h-full",style:j?{paddingBottom:xs}:void 0,children:a})}),b&&h.accountId&&n.jsx(Fd,{open:b,accountId:h.accountId,selectedMessageIds:y,selectedSenders:N,onClose:()=>v(!1)})]})}function Kw({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:r,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i,onMarkMessagesRead:l}){const{searchQuery:u,resultFolderIndex:f}=ke(),d=os(),m=_t(),h=c.useMemo(()=>y0(e.filter(Y=>!Y.muted?.value)),[e]),[g,x]=c.useState("all"),[p,b]=c.useState("all"),[v,S]=c.useState(new Set),[w,y]=c.useState(!1),N=c.useCallback(Y=>{S(z=>{const B=new Set(z);return B.has(Y)?B.delete(Y):B.add(Y),B})},[]),{data:C,isLoading:E,isError:I,refetch:O}=ue({...oa(),staleTime:6e4}),A=vt({queries:h.map(Y=>({...Ue({path:{accountId:Y.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),M=c.useMemo(()=>{const Y=new Map;for(let z=0;z<h.length;z++){const B=h[z].accountId,de=(A[z]?.data?.items??[]).reduce((_e,ae)=>_e+(ae.unseenCount??0),0);Y.set(B,de)}return Y},[h,A]),P=c.useMemo(()=>h.filter((Y,z)=>{const B=A[z];return B?.isError?!ia(B.error):!1}),[h,A]),{freeText:R,tokens:j}=Ls(u.trim().toLowerCase(),d),{data:F,isFetching:D}=ue({...oa({query:{query:R,limit:Lw}}),enabled:R.length>0,staleTime:3e4}),k=c.useMemo(()=>{const Y=nl(C?.items??[]).map(Gn);return(R?w0(Y.filter(B=>cd(B,R)),nl(F?.items??[]).map(Gn)):Y).filter(B=>(g==="all"||B.accountId===g)&&ko(B,j))},[C,F,g,R,j]),L=c.useMemo(()=>S0(k),[k]),T=c.useMemo(()=>h.length<=1?[]:[{id:"all",label:"All",active:g==="all"},...h.map(Y=>({id:Y.accountId,label:Y.email.split("@")[0]??Y.email,count:M.get(Y.accountId),active:g===Y.accountId}))],[h,M,g]),$=c.useMemo(()=>e.filter(Y=>Y.muted?.value).length,[e]),V=c.useMemo(()=>Array.from(M.values()).reduce((Y,z)=>Y+z,0),[M]),ne=c.useMemo(()=>{const Y=Array.from(v).map(z=>Fw[z]).filter(z=>z!=null);return k.filter(z=>(p==="all"||z.category===p)&&Y.every(B=>B(z))).map(z=>ud(z,f))},[k,p,v,f]),{hits:re,isLoading:q}=ld(),Q=c.useMemo(()=>{const Y=new Map;for(const B of C?.items??[])Y.set(B.messageId,B.threadId);const z=ne.map(B=>Y.get(B.id)).filter(B=>B!=null);return dd(re,z,f)},[re,ne,C,f]),J=c.useMemo(()=>{const Y=sx(T.map(z=>({id:z.id,label:z.label,count:z.count,active:z.active})));return{categories:Y.categories,filters:Y.filters,sources:Y.sources,sourcesNote:$>0?`+${$} muted`:void 0,selectedCategory:p,activeFilters:v,expanded:w,onExpandedChange:y,onSelectCategory:z=>b(z),onSelectSource:x,onToggleFilter:N,onClear:()=>{b("all"),x("all"),S(new Set)}}},[T,$,p,v,w,N]),te=L.length===0&&g==="all"&&R.length===0,Z=c.useMemo(()=>h.map(Y=>Y.accountId),[h]),se=c.useMemo(()=>h.some(Y=>td(Y.syncPhase)),[h]),ce=s0(Z,te||se),xe=n.jsxs("div",{className:"h-full overflow-y-auto",children:[n.jsx(cl,{}),n.jsx(cl,{})]}),Te=E?xe:I?n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[n.jsx(ts,{className:"size-8 text-danger"}),n.jsx("p",{children:"Couldn't load your messages"}),n.jsxs("button",{type:"button",onClick:()=>O(),className:"flex items-center gap-1 text-accent underline text-xs",children:[n.jsx(pc,{className:"size-3.5"}),"Try again"]})]}):te?ce.resolved?n.jsx(ng,{sync:ce.syncing?{synced:ce.synced,total:ce.total}:void 0}):xe:n.jsx(_w,{sections:L,briefCategory:p,selectedThreadId:t,onSelectThread:s});return n.jsx(Rd,{selectedMessageId:t,onOpen:(Y,z)=>s?.(Y,z),onDeleteMessages:i,commandsRef:a,onTriageContextChange:o,children:n.jsx(Bw,{header:{title:"Daily brief",unreadCount:V,footer:m?n.jsx(vc,{}):void 0,searchFilter:J,searchResults:ne,searchLoading:E||D,relatedResults:Q,relatedLoading:q,onSelectSearchResult:r},rows:k,isDesktop:m,onMarkMessagesRead:l,children:n.jsxs("div",{className:"flex h-full flex-col",children:[P.map(Y=>n.jsx($w,{accountEmail:Y.email,accountId:Y.accountId},Y.accountId)),n.jsx("div",{className:"min-h-0 flex-1",children:Te})]})})})}const Uw=10,$d=e=>({q:e?.toLowerCase()??"",limit:Uw}),qw=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(r=>r.normalizedEmail===s)};function Hw(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":qn(t,{month:"short",year:"numeric"})}function _d(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const Ww="We can't verify the sender of this email, which could mean it's from an insecure source.",Vw="We couldn't read this sender's address, so we can't confirm who really sent this message.";function Qw(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?Hw(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:_d(e.fromEmail)}}function Yw(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 Gw(e,t){const s=t>0?t:void 0;if(_d(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:Vw,similarCount:s};const r=e.authenticity;if(!r)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:Ww};if(!r.dkimMismatch)return{verdict:"aligned",fromDomain:r.fromDomain,dkimDomain:r.dkimDomain,summary:r.dkimDomain?`We verified this message was really sent by ${r.fromDomain}.`:"Nothing looks unusual about this sender."};const a=r.fromDomain,o=r.dkimDomain,i=e.fromName&&e.fromName!==e.fromEmail?e.fromName:void 0,l=i?`The display name claims "${i}", but this message was actually sent from ${o??"another sender"} — not ${a}. Real senders use their own address.`:`This message claims to be from ${a}, but it was actually sent from ${o??"a different sender"}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:l,similarCount:s}}function zd(e,t){const s=e?.fromEmail??null,r=e?.subject??"",{data:a,error:o}=ue({...nr({query:$d(s??void 0)}),enabled:!!s,staleTime:3e4}),i=qw(a?.items,s??void 0),l=[r,s].filter(Boolean).join(" "),{data:u,isLoading:f,error:d}=ue({...Pl({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(v=>v.messageId!==e.messageId).map(v=>({id:v.messageId,mailboxId:t!=null&&v.mailboxIds.includes(t)?t:v.mailboxIds[0]??"",fromName:v.fromName??"",subject:v.subject??"(No subject)",timeLabel:v.sentDate!=null?Bt(v.sentDate*1e3):"",matched:v.matchedChunkType})),g=Qw(e,i),x=Gw(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},b=Yw(i);return{sender:g,authenticity:x,category:p,flags:b,similar:h}},[e,i,u,t]),isSimilarLoading:f,similarError:d,similarErrorIsFatal:ia(d),addressErrorIsFatal:ia(o),addressId:i?.addressId,address:i}}function Xw(e,t){const s={...e??{}};for(const[r,a]of Object.entries(t))a==null?delete s[r]:s[r]={...a,setAt:a.setAt??Date.now()};return s}function Bd({addressId:e,senderEmail:t}){const s=we(),{pushError:r}=tt(),a=hm({query:$d(t)}),{mutate:o,isPending:i}=je({...Dl(),onMutate:async u=>{const f=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,m=>m&&{...m,items:m.items.map(h=>h.addressId===u.path.addressId?{...h,flags:Xw(h.flags,f)}:h)}),{previous:d}},onError:(u,f,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),r({title:"Couldn't update sender preference",detail:lt(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){$l(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 Jw=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Kd=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function Zw(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function eS(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function tS(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Ud(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const sS=["personal","newsletter","marketing","automated","transactional","social"],nS=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:r}=e;return t?s&&t===s?r?"notSpam":null:s?"markSpam":null:null},rS=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:r}=e;return t&&!s?"error":r?"loading":"ready"};function aS(){return n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(xt,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),n.jsxs("div",{className:"flex-1 space-y-1.5",children:[n.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"h-8 rounded bg-surface"})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),n.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>n.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function oS({isOpen:e,current:t,onSelect:s,onCancel:r}){return e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:r,children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),n.jsx("div",{className:"mt-4 flex flex-col gap-1",children:sS.map(a=>n.jsxs("button",{type:"button",onClick:()=>s(a),className:`flex min-h-11 items-center justify-between rounded px-3 text-left text-sm capitalize transition-colors hover:bg-surface-raised ${a===t?"font-semibold text-accent":"text-fg"}`,children:[a,a===t&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"current"})]},a))}),n.jsx("div",{className:"mt-6 flex justify-end",children:n.jsx("button",{type:"button",onClick:r,className:"inline-flex min-h-11 items-center justify-center rounded border border-line px-4 text-sm font-medium transition-colors hover:bg-surface-raised",children:"Cancel"})})]})]}):null}function iS({thread:e,onClose:t,mailboxId:s,accountId:r,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:f}=zd(e,s),[d,m]=c.useState(!1),[h,g]=c.useState(!1),x=e.fromEmail??void 0,{updateFlags:p,isPending:b}=Bd({addressId:i,senderEmail:x}),{junkMailboxId:v}=gn(r),{inboxMailboxId:S}=xo(r),{moveMessages:w}=Lt({mailboxId:s??"",threadId:e.threadId,accountId:r}),y=on(),N=nS({mailboxId:s,junkMailboxId:v,inboxMailboxId:S}),C=c.useCallback(()=>{S&&w([e.messageId],S)},[S,w,e.messageId]),E=c.useCallback(()=>{v&&(Ud(y,{count:1,senderTrust:e.senderTrust,wasRescuable:Kd(e)}),w([e.messageId],v))},[v,w,e,y]),I=c.useCallback(()=>{},[]),O=c.useCallback(()=>{const T=o?.flags?.vip!==!0;p({vip:{value:T}})},[o?.flags?.vip,p]),A=c.useCallback(()=>{const T=o?.flags?.muted!==!0;p({muted:{value:T}})},[o?.flags?.muted,p]),M=c.useCallback(()=>{o?.flags?.blocked===!0?p({blocked:{value:!1}}):m(!0)},[o?.flags?.blocked,p]),P=c.useCallback(()=>{m(!1),p({blocked:{value:!0}})},[p]),R=c.useCallback(()=>{const T=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:T}})},[o?.flags?.unsubscribed,p]),j=c.useCallback(T=>{g(!1),p({category:{value:T}})},[p]),F=i!==void 0,D={onToggleVip:F?O:void 0,onToggleMute:F?A:void 0,onToggleBlock:F?M:void 0,onToggleUnsubscribe:F?R:void 0,onReclassify:F?()=>g(!0):void 0,onNotSpam:N==="notSpam"?C:void 0,onMarkSpam:N==="markSpam"?E:void 0},k=({mailboxId:T,messageId:$,className:V,ariaLabel:ne,children:re})=>n.jsx(wt,{to:"/mail/$mailboxId",params:{mailboxId:T},search:q=>({...q,selectedMessageId:$}),className:V,"aria-label":ne,children:re});if(!o)return n.jsx(aS,{});const L=rS({similarError:u,similarErrorIsFatal:f,isSimilarLoading:l});return n.jsxs(n.Fragment,{children:[n.jsx(bc,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:I,actions:D,similarState:L,similarLinkComponent:k,className:"border-l-0 h-full w-full"}),n.jsx(Ga,{isOpen:d,title:"Block this sender?",description:`Messages from ${x??"this sender"} will never load images and will be flagged. You can undo this in Settings → Senders.`,confirmLabel:"Block sender",destructive:!0,isBusy:b,onConfirm:P,onCancel:()=>m(!1)}),n.jsx(oS,{isOpen:h,current:o.category.value,onSelect:j,onCancel:()=>g(!1)})]})}const Fs=({onClose:e,thread:t,mailboxId:s,accountId:r,hideCloseButton:a})=>t?n.jsx(iS,{thread:t,onClose:e,mailboxId:s,accountId:r,hideCloseButton:a}):n.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[n.jsx(xt,{className:"size-3.5 text-fg-subtle"}),n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[n.jsx(xt,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),n.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),sa="Open a message first",Io=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:r,onReply:a,onReplyAll:o,onForward:i,onDelete:l,canDelete:u,onToggleStar:f,isStarred:d,moveContext:m})=>{const[h,g]=c.useState(null),x=u??e,p=b=>()=>g(b);return n.jsx(bp,{hasThread:e,isStarred:d,onUnavailable:b=>g(sa),unavailableHint:h,replyTitle:`Reply ${ps("reply")}`,replyAllTitle:`Reply all ${ps("replyAll")}`,forwardTitle:`Forward ${ps("forward")}`,deleteTitle:`Move to Trash ${ps("delete")}`,flagTitle:`Star ${ps("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:x?l:p(sa),onToggleStar:f,onMove:p(sa),moveSlot:m?n.jsx(Ds,{accountId:m.accountId,currentMailboxId:m.currentMailboxId,onMove:m.onMove,label:"Move to mailbox"}):void 0,children:n.jsx(xp,{open:t,enabled:s,onToggle:r})})},qd=()=>{const e=we();return c.useCallback(t=>{const s=rs({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])},sn=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:r})=>{const a=t??e?.mailboxId,o=s??e?.accountId,{accountId:i}=ho(o?void 0:a),l=o??i,u=qd(),{deleteMessages:f}=es({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:r}),{moveMessages:d}=Lt({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:r}),{toggleStar:m}=po({threadId:e?.threadId??"",mailboxId:a??""}),h=c.useCallback(()=>{e&&f(u(e))},[e,u,f]),g=c.useCallback(S=>{e&&d(u(e),S)},[e,u,d]),x=c.useCallback(()=>{e&&m(e.messageId,e.hasStars)},[e,m]),[p,b]=c.useState(null),v=c.useCallback(()=>b(null),[]);return{mailboxId:a,accountId:l,isStarred:e?.hasStars,deleteThread:h,moveThread:g,toggleStar:x,composeRequest:p,requestCompose:b,clearComposeRequest:v}},Ws={action:null,nextPrefix:null,preventDefault:!1},lS={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},cS={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 uS(e,t){const s=e.key.toLowerCase(),r=e.metaKey||e.ctrlKey;if(e.inEditable)return{...Ws,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...Ws,nextPrefix:t==="g"?null:t};if(r&&s==="n")return{action:"compose",nextPrefix:null,preventDefault:!0};if(r&&s==="a")return{action:"selectAll",nextPrefix:null,preventDefault:!0};if(r)return{...Ws,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=lS[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=cS[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?Ws:{action:a.action,nextPrefix:null,preventDefault:!0}}return Ws}function dS(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const fS="data-message-row",mS='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function hS(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(mS);return t?!t.hasAttribute(fS):!1}function pS({handlers:e,enabled:t=!0,sequenceTimeoutMs:s=1e3}){const r=c.useRef(e);r.current=e;const a=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{if(!t)return;const i=()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},l=u=>{const f=uS({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:dS(u.target),onControl:hS(u.target)},a.current);if(i(),a.current=f.nextPrefix,f.nextPrefix!==null&&(o.current=setTimeout(()=>{a.current=null,o.current=null},s)),f.action===null)return;const d=r.current[f.action];d&&(f.preventDefault&&u.preventDefault(),d())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l),i(),a.current=null}},[t,s])}const ul=(e,t,s)=>{if(!t)return null;const r=e.indexOf(t);if(r===-1)return null;const a=s==="next"?r+1:r-1;return a<0||a>=e.length?null:e[a]},To=()=>{const[e,t]=c.useState(void 0),[s,r]=c.useState([]),[a,o]=c.useState([]),i=c.useRef(null),[l,u]=c.useState(!1),[f,d]=c.useState(!1),m=c.useCallback(h=>{t(h.focusedMessageId),r(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:m,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:l,blocksKeyboard:f}},Ro=({context:e,orderedIds:t,selectedMessageId:s,enabled:r=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:l,blocksKeyboard:u}=e,f=c.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return pS({enabled:r&&!u,handlers:{...l?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:f,...o}}),{goBack:f,nextMessageId:ul(t,s,"next")??void 0,previousMessageId:ul(t,s,"previous")??void 0}};function gS(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function Hd(e,t){if(e)return gS(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const Wd=c.createContext(null);function kr(){const e=c.useContext(Wd);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function xS({selectedMessageId:e,children:t}){const s=$e(),{searchInput:r}=ke(),{selectedThreadId:a,selectedMailboxId:o}=Cs({strict:!1}),{data:i}=ue({...oa(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(A=>A.messageId===e)},[i,e]),u=c.useMemo(()=>Hd(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),f=c.useCallback((A,M)=>{s({to:"/mail",search:P=>({...P,selectedMessageId:A,selectedThreadId:void 0,selectedMailboxId:void 0}),replace:M?.replace})},[s]),d=c.useCallback(A=>{s({to:"/mail",search:M=>({...M,q:r||void 0,selectedMessageId:A.id,selectedThreadId:A.threadId,selectedMailboxId:A.mailboxId})})},[s,r]),m=c.useCallback(A=>{e&&A.includes(e)&&s({to:"/mail",search:M=>({...M,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=sn({thread:l,onAfterOptimisticRemove:m}),g=c.useCallback(()=>{s({to:"/mail",search:A=>({...A,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),x=To(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:b}=es({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:m}),{toggleReadFor:v}=vr({mailboxId:l?.mailboxId??"",messages:p}),S=c.useCallback(A=>v(A,!0),[v]),w=x.focusedMessageId,N=c.useMemo(()=>i?.items.find(A=>A.messageId===w),[i,w])??l,C=sn({thread:N}),{nextMessageId:E,previousMessageId:I}=Ro({context:x,orderedIds:x.orderedIds,selectedMessageId:e,onClose:g,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{x.listCommandsRef.current?.requestDelete()||C.deleteThread()},toggleStar:C.toggleStar,toggleRead:()=>{const A=x.selectedIds.length>0?x.selectedIds:N?[N.messageId]:[];A.length!==0&&v(A,!(N?.isRead??!1))},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),O={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:f,onSelectSearchResult:d,onCloseThread:g,actions:h,triage:x,onDeleteMessages:b,onMarkMessagesRead:S,nextMessageId:E,previousMessageId:I};return n.jsx(Wd.Provider,{value:O,children:t})}function Vd(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:r,onDeleteMessages:a,onMarkMessagesRead:o}=kr(),{accounts:i}=ke();return n.jsx(Kw,{accounts:i,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:r.listCommandsRef,onTriageContextChange:r.onTriageContextChange,onDeleteMessages:a,onMarkMessagesRead:o})}function bS(){const{conversation:e,actions:t}=kr(),{intelligenceOpen:s,onToggleIntelligence:r}=ke(),a=Is()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(Io,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Ps,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Os,{})})]})}function vS(){const{selectedThread:e}=kr(),{onToggleIntelligence:t}=ke();return n.jsx(Fs,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function yS(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:r,nextMessageId:a,previousMessageId:o}=kr(),{intelligenceOpen:i,onToggleIntelligence:l}=ke();return t?n.jsxs(n.Fragment,{children:[n.jsx(Ps,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:r,onOpenIntelligence:l,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:i}),n.jsx(uo,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:n.jsx(Fs,{onClose:l,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(Vd,{})})}const Vs=Object.assign(xS,{List:Vd,Reading:bS,Intelligence:vS,Phone:yS}),wS=()=>Ba({query:{starred:!0,order:"desc"}});function Qd(){const{data:e,isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=Zc({queryKey:wS(),queryFn:async({pageParam:f})=>{const{data:d}=await pm({query:{starred:!0,order:"desc",continuationToken:f},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:f=>f.continuationToken,staleTime:6e4});return{threads:c.useMemo(()=>(e?.pages??[]).flatMap(f=>f.items??[]),[e]),isLoading:t,isError:s,error:r,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}}const SS=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function Yd({title:e,unreadCount:t,preset:s,selectedCategory:r,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:l,onClearFilters:u,children:f,footer:d,searchResults:m,searchLoading:h,relatedResults:g,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:v,searchResultsInBody:S}){const[w,y]=c.useState(!1),{searchInput:N}=ke(),C=N.trim().length>0,E={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:r,activeFilters:a,expanded:w,onExpandedChange:y,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return n.jsx(jd,{title:e,unreadCount:t,footer:d,searchFilter:E,searchResults:m,searchLoading:h,relatedResults:g,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:v,searchResultsInBody:S,children:C?n.jsx("div",{className:"h-full overflow-y-auto",children:f}):n.jsx(Cl,{...E,children:f})})}const jS={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function kS({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:r,onDeleteMessages:a,onMarkMessagesRead:o}){const{searchQuery:i,resultFolderIndex:l}=ke(),u=os(),f=_t(),[d,m]=c.useState("all"),[h,g]=c.useState(new Set),x=c.useCallback(k=>{g(L=>{const T=new Set(L);return T.has(k)?T.delete(k):T.add(k),T})},[]),p=c.useCallback(()=>{m("all"),g(new Set)},[]),{threads:b,isLoading:v,isError:S,error:w,refetch:y,fetchNextPage:N,hasNextPage:C,isFetchingNextPage:E}=Qd(),{freeText:I,tokens:O}=Ls(i.trim().toLowerCase(),u),A=c.useMemo(()=>{const k=Array.from(h).map(L=>jS[L]).filter(L=>L!=null);return SS(b).map(Gn).filter(L=>(d==="all"||L.category===d)&&k.every(T=>T(L))&&(!I||cd(L,I))&&ko(L,O))},[b,d,h,I,O]),M=c.useMemo(()=>nx(),[]),P=c.useMemo(()=>A.map(k=>ud(k,l)),[A,l]),R=c.useMemo(()=>A.filter(k=>!k.isRead).length,[A]),j=v?"loading":S?"error":A.length===0?"empty":"ready",F=c.useCallback(()=>{const k=$a(Fa());window.open(k,"_blank","noopener,noreferrer")},[]),D=n.jsx(Rd,{selectedMessageId:e,onOpen:(k,L)=>t?.(k,L),onDeleteMessages:a,commandsRef:s,onTriageContextChange:r,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a?n.jsx(pw,{onMarkAsRead:o}):null,n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.jsx("div",{className:"divide-y divide-line",children:A.map(k=>n.jsx(Xn,{thread:k,active:k.id===e,onClick:()=>t?.(k.id)},k.id))}),C?n.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>N(),disabled:E,children:E?"Loading…":"Load more"}):null]})]})});return n.jsx(Yd,{title:"Starred",unreadCount:R,preset:M,selectedCategory:d,activeFilters:h,onSelectCategory:m,onToggleFilter:x,onClearFilters:p,searchResults:P,searchLoading:v,onSelectSearchResult:k=>t?.(k.id),children:n.jsx(Nc,{listTitle:"Starred",sections:[{id:"flagged",threads:A}],flatList:!0,hideHeader:!0,listState:j,searchQuery:I?i:void 0,errorMessage:S?Wl(w):void 0,onRetry:()=>y(),onReportError:F,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:f,listBody:j==="ready"?D:void 0})})}const Gd=c.createContext(null);function Cr(){const e=c.useContext(Gd);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function CS({selectedMessageId:e,children:t}){const s=$e(),{threads:r}=Qd(),a=c.useMemo(()=>{if(e)return r.find(y=>y.messageId===e)},[r,e]),o=c.useCallback((y,N)=>{s({to:"/mail/flagged",search:C=>({...C,selectedMessageId:y}),replace:N?.replace})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:y=>({...y,selectedMessageId:void 0})})},[s]),l=c.useCallback(y=>{e&&y.includes(e)&&i()},[e,i]),u=sn({thread:a,onAfterOptimisticRemove:l}),f=To(),{deleteMessages:d}=es({mailboxId:a?.mailboxId??"",messages:r,onAfterOptimisticRemove:l}),{toggleReadFor:m}=vr({mailboxId:a?.mailboxId??"",messages:r}),h=c.useCallback(y=>m(y,!0),[m]),g=f.focusedMessageId,p=c.useMemo(()=>r.find(y=>y.messageId===g),[r,g])??a,b=sn({thread:p}),{nextMessageId:v,previousMessageId:S}=Ro({context:f,orderedIds:f.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{f.listCommandsRef.current?.requestDelete()||b.deleteThread()},toggleStar:b.toggleStar,toggleRead:()=>{const y=f.selectedIds.length>0?f.selectedIds:p?[p.messageId]:[];y.length!==0&&m(y,!(p?.isRead??!1))},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),w={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:f,onDeleteMessages:d,onMarkMessagesRead:h,nextMessageId:v,previousMessageId:S};return n.jsx(Gd.Provider,{value:w,children:t})}function Xd(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:r,onMarkMessagesRead:a}=Cr();return n.jsx(kS,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:r,onMarkMessagesRead:a})}function NS(){const{selectedThread:e,actions:t}=Cr(),{intelligenceOpen:s,onToggleIntelligence:r}=ke(),a=Is()?.showIntelligencePane??!1,o=!!e,i=a&&o;return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(Io,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:r,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(Ps,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):n.jsx(Os,{})})]})}function ES(){const{selectedThread:e}=Cr(),{onToggleIntelligence:t}=ke();return n.jsx(Fs,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function IS(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:r,previousMessageId:a}=Cr(),{intelligenceOpen:o,onToggleIntelligence:i}=ke();return e?n.jsxs(n.Fragment,{children:[n.jsx(Ps,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:i,onSwipeNext:r?()=>s(r):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:o}),n.jsx(uo,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:n.jsx(Fs,{onClose:i,thread:e,hideCloseButton:!0})})]}):n.jsx("div",{className:"h-full",children:n.jsx(Xd,{})})}const Qs=Object.assign(CS,{List:Xd,Reading:NS,Intelligence:ES,Phone:IS}),TS={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},RS=()=>{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},[])},MS=()=>{const{state:e,closeCompose:t}=$t(),s=RS(),[r,a]=c.useState(!1),{isError:o,error:i,refetch:l}=ue({...jt(),staleTime:1/0}),u=c.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),f=c.useCallback(()=>{a(!1),t()},[t]),d=c.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const m=TS[e.mode]??"New Message";return n.jsxs(at.Root,{open:e.isOpen,onOpenChange:u,children:[n.jsxs(at.Portal,{children:[n.jsx(at.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),n.jsxs(at.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[n.jsx(at.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),n.jsx(at.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:m}),o?n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(zt,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):n.jsx("div",{className:"flex-1 overflow-hidden",children:n.jsx(fo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),r&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50",children:n.jsxs("div",{className:"mx-4 w-full max-w-sm rounded-xl bg-canvas p-6 shadow-xl",children:[n.jsx("h3",{className:"text-lg font-semibold",children:"Discard draft?"}),n.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Your message has unsaved content. Are you sure you want to discard it?"}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:d,className:"rounded-md px-4 py-2 text-sm font-medium hover:bg-surface-raised transition-colors",children:"Keep editing"}),n.jsx("button",{type:"button",onClick:f,className:"rounded-md bg-danger px-4 py-2 text-sm font-medium text-canvas hover:bg-danger/90 transition-colors",children:"Discard"})]})]})})]})},AS={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Jd=()=>{const{state:e,closeCompose:t}=$t(),s=_t(),{isError:r,error:a,refetch:o}=ue({...jt(),staleTime:1/0});if(!s)return n.jsx(MS,{});if(!e.isOpen)return null;const i=AS[e.mode]??"New Message",l=n.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[n.jsx("div",{className:"flex items-center gap-2 min-w-0",children:n.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),n.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:n.jsx(Ze,{className:"size-5"})})]});return r?n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[l,n.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:n.jsx(zt,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[l,n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:n.jsx(fo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function OS(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:Bt(e.updatedAt),isRead:!0}}function DS(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:Bt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function PS({outboxMessages:e,accountId:t,imapThreads:s}){const r=e.filter(i=>i.status==="draft"&&i.accountId===t).map(OS),a=s.map(DS),o=[];return r.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:r}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function Mo(){const e=Is();return!e||e.showNavPane?null:n.jsx(W,{variant:"ghost",size:"sm",icon:n.jsx(Ha,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const LS=({label:e,count:t})=>n.jsxs("div",{className:"sticky top-0 z-10 flex items-baseline justify-between border-b border-line bg-surface-sunken px-row-inset py-1",children:[n.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),n.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:t})]}),FS=({row:e,isSelected:t,onOpen:s,onDelete:r,isDeleting:a})=>n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:H("group",As({active:t})),children:[n.jsx(kl,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),n.jsx(Zs,{thread:e}),n.jsx("div",{className:"flex items-center gap-1 shrink-0",children:n.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),r(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:n.jsx(ct,{className:"size-3.5"})})})]}),$S=({row:e,isSelected:t,onOpen:s})=>{const r=!e.isRead;return n.jsxs("button",{type:"button",onClick:()=>s(e.id),className:H("group",As({active:t})),children:[r&&n.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),n.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"sm"}),n.jsx(Zs,{thread:e})]})};function _S({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:r,title:a,unreadCount:o}){const{openCompose:i,state:l}=$t(),u=$e(),f=we(),{data:d}=ue(sr()),m=c.useMemo(()=>PS({outboxMessages:d?.items??[],accountId:t,imapThreads:r}),[d?.items,t,r]),h=je({...rr(),onSuccess:()=>{f.invalidateQueries({queryKey:qa()})}}),g=v=>{h.mutate({path:{outboxMessageId:v}})},x=v=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:v})},p=v=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:v}})},b=m.length===0;return n.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(Mo,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:a}),(o??0)>0&&n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:[o," unread"]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto",children:b?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[n.jsx(Ta,{className:"size-8 text-fg-subtle"}),n.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),n.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):m.map(v=>n.jsxs("div",{children:[v.label&&n.jsx(LS,{label:v.label,count:v.threads.length}),n.jsx("div",{className:"divide-y divide-line",children:v.threads.map(S=>v.id==="remit-drafts"?n.jsx(FS,{row:S,isSelected:l.isOpen&&S.id===l.outboxMessageId,onOpen:x,onDelete:g,isDeleting:h.isPending},S.id):n.jsx($S,{row:S,isSelected:S.id===s,onOpen:p},S.id))})]},v.id))})]})}function zS(e,t,s){const r=new Array(e);return new Proxy(r,{get(a,o,i){if(typeof o=="string"){const l=o.charCodeAt(0);if(l>=48&&l<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let f=a[u];if(!f){const d=t[u*2];f=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return f}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function hs(e,t,s){let r=s.initialDeps??[],a,o=!0;function i(){const l=e();return(l.length!==r.length||l.some((f,d)=>r[d]!==f))&&(r=l,a=t(...l),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=l=>{r=l},i}function dl(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const BS=(e,t)=>Math.abs(e-t)<1.01,KS=(e,t,s)=>{let r;return function(...a){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,a),s)}};let Ys;const na=()=>{if(Ys!==void 0)return Ys;if(typeof navigator>"u")return Ys=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Ys=!0;const e=navigator.maxTouchPoints;return Ys=navigator.platform==="MacIntel"&&e!==void 0&&e>0},fl=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},US=e=>e,qS=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,a=new Array(r);for(let o=0;o<r;o++)a[o]=t+o;return a},HS=(e,t)=>{const s=e.scrollElement;if(!s)return;const r=e.targetWindow;if(!r)return;const a=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(a(fl(s)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u?.borderBoxSize){const f=u.borderBoxSize[0];if(f){a({width:f.inlineSize,height:f.blockSize});return}}a(fl(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},Jn={passive:!0},WS=typeof window>"u"?!0:"onscrollend"in window,VS=(e,t,s)=>{const r=e.scrollElement;if(!r)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&WS;let i=0;const l=o?null:KS(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=m=>()=>{i=s(r),l?.(),t(i,m)},f=u(!0),d=u(!1);return r.addEventListener("scroll",f,Jn),o&&r.addEventListener("scrollend",d,Jn),()=>{r.removeEventListener("scroll",f),o&&r.removeEventListener("scrollend",d)}},QS=(e,t)=>VS(e,t,s=>{const{horizontal:r,isRtl:a}=e.options;return r?s.scrollLeft*(a&&-1||1):s.scrollTop}),YS=(e,t,s)=>{if(s.options.useCachedMeasurements){const r=s.indexFromElement(e),a=s.options.getItemKey(r);return s.itemSizeCache.get(a)??s.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[s.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=s.indexFromElement(e),a=s.options.getItemKey(r),o=s.itemSizeCache.get(a);if(o!==void 0)return o}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},GS=(e,{adjustments:t=0,behavior:s},r)=>{var a,o;(o=(a=r.scrollElement)==null?void 0:a.scrollTo)==null||o.call(a,{[r.options.horizontal?"left":"top"]:e+t,behavior:s})},XS=GS;class JS{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,r,a;return((a=(r=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:r.now)==null?void 0:a.call(r))??Date.now()},this.observer=(()=>{let s=null;const r=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const l=o.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[f,d]of this.elementsCache)if(d===l){this.elementsCache.delete(f);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=r())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=r())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=r())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var r,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:US,rangeExtractor:qS,onChange:()=>{},measureElement:YS,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in s){const g=s[h];g!==void 0&&(o[h]=g)}const i=this.options;let l=null,u=null,f=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,g=o.count,x=this.getMeasurements(),p=h>0?((r=x[0])==null?void 0:r.key)??i.getItemKey(0):null,b=h>0?((a=x[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(g!==h||h>0&&g>0&&(o.getItemKey(0)!==p||o.getItemKey(g-1)!==b)){f=!0;const w=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??x[0]:null;w&&(l=[w.key,this.getScrollOffset()-w.start]);const y=o.followOnAppend===!0?"auto":o.followOnAppend||null;y&&g>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(g-1)!==b)&&(u=y)}}this.options=o,f&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,m=0;if(l&&this.scrollOffset!==null){const[h,g]=l,x=this.getMeasurements(),{count:p,getItemKey:b}=this.options;let v=0;for(;v<p&&b(v)!==h;)v++;if(v<p){const S=x[v];if(S){const w=S.start+g;w!==this.scrollOffset&&(m=w-this.scrollOffset,this.scrollOffset=w,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,u,m])},this.notify=s=>{var r,a;(a=(r=this.options).onChange)==null||a.call(r,this,s)},this.maybeNotify=hs(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===o?this.scrollDirection:l<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!na()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,Jn),o.addEventListener("touchend",l,Jn),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&&(na()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),r=this.getMaxScrollOffset();if(s<0||s>r)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=hs(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,r,a,o,i,l,u,f)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f}),{key:!1}),this.getMeasurements=hs(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:r,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:f},d)=>{const m=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const v of this.laneAssignments.keys())v>=s&&this.laneAssignments.delete(v);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(v=>{this.itemSizeCache.set(v.key,v.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 v=s*2;let S=this._flatMeasurements;if(!S||S.length<v){const N=new Float64Array(v);S&&h>0&&N.set(S.subarray(0,h*2)),S=N,this._flatMeasurements=S}let w;if(h===0)w=r+a;else{const N=h-1;w=S[N*2]+S[N*2+1]+f}for(let N=h;N<s;N++){const C=o(N),E=m.get(C),I=typeof E=="number"?E:this.options.estimateSize(N);S[N*2]=w,S[N*2+1]=I,w+=I+f}const y=zS(s,S,o);return this.measurementsCache=y,y}const g=this.measurementsCache.slice(0,h),x=new Array(l).fill(void 0),p=new Float64Array(l);let b=0;for(let v=0;v<h;v++){const S=g[v];S&&(x[S.lane]===void 0&&b++,x[S.lane]=v,p[S.lane]=S.end)}for(let v=h;v<s;v++){const S=o(v),w=this.laneAssignments.get(v);let y,N;const C=u==="estimate"||m.has(S);if(w!==void 0&&this.options.lanes>1){y=w;const A=x[y],M=A!==void 0?g[A]:void 0;N=M?M.end+f:r+a}else if(b===l){let A=0,M=p[0],P=x[0];for(let R=1;R<l;R++){const j=p[R];(j<M||j===M&&x[R]<P)&&(A=R,M=j,P=x[R])}y=A,N=M+f,C&&this.laneAssignments.set(v,y)}else y=v%this.options.lanes,N=r+a,C&&this.laneAssignments.set(v,y);const E=m.get(S),I=typeof E=="number"?E:this.options.estimateSize(v),O=N+I;g[v]={index:v,start:N,size:I,end:O,key:S,lane:y},x[y]===void 0&&b++,x[y]=v,p[y]=O}return this.measurementsCache=g,g},{key:!1,debug:()=>this.options.debug}),this.calculateRange=hs(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,r,a,o)=>s.length===0||r===0?(this.range=null,null):(this.range=ej(s,r,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=hs(()=>{let s=null,r=null;const a=this.calculateRange();return a&&(s=a.startIndex,r=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,r]},(s,r,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:r,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const r=this.options.indexAttribute,a=s.getAttribute(r);return a?parseInt(a,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),l=Math.min(this.options.count-1,a+o);return s>=i&&s<=l}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const r=this.indexFromElement(s),a=this.options.getItemKey(r),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,r)=>{var a,o;if(s<0||s>=this.options.count)return;let i,l,u;const f=this._flatMeasurements;if(this.options.lanes===1&&f!==null)u=this.options.getItemKey(s),l=f[s*2],i=f[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,l=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,m=r-d;if(m!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,g=h?this.getTotalSize():0,x=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:l,size:i,end:l+i,lane:0},m,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,r),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-g):x&&this.applyScrollAdjustment(m),this.notify(!1)}},this.getVirtualItems=hs(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,r)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const l=s[o],u=r[l];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const r=this.getMeasurements();if(r.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=Zd(0,r.length-1,o?l=>a[l*2]:l=>dl(r[l]).start,s);return dl(r[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,r,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=s>=i+o?"end":"start"),r==="center"?s+=(a-o)/2:r==="end"&&(s-=o);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,r="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(r==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)r="end";else if(i.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,i.size),r]},this.scrollToOffset=(s,{align:r="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,r),i=this.now();this.scrollState={index:null,align:r,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:r="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,r);if(!o)return;const[i,l]=o,u=this.now();this.scrollState={index:s,align:l,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:r="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const r=this.getMeasurements();let a;if(r.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=r[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&o.some(l=>l===null);){const l=r[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}a=Math.max(...o.filter(l=>l!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const r=this.getMeasurements();for(const a of r)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:r,behavior:a})=>{this._intendedScrollOffset=s+(r??0),this.options.scrollToFn(s,{behavior:a,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&(na()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=r?r[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&BS(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),f=this.scrollState.behavior==="smooth"&&u>l;this.scrollState.lastTargetOffset=a,f||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:f?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Zd=(e,t,s,r)=>{for(;e<=t;){const a=(e+t)/2|0,o=s(a);if(o<r)e=a+1;else if(o>r)t=a-1;else return a}return e>0?e-1:0};function ZS(e,t,s){let r=0;for(;r<=t;){const a=(r+t)/2|0,o=e[a*2];if(o<s)r=a+1;else if(o>s)t=a-1;else return a}return r>0?r-1:0}function ej(e,t,s,r,a){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&a!==null){const f=ZS(a,o,s);let d=f;const m=s+t;for(;d<o&&a[d*2]+a[d*2+1]<m;)d++;return{startIndex:f,endIndex:d}}let l=Zd(0,o,f=>e[f].start,s),u=l;if(r===1)for(;u<o&&e[u].end<s+t;)u++;else if(r>1){const f=Array(r).fill(0);for(;u<o&&f.some(m=>m<s+t);){const m=e[u];f[m.lane]=m.end,u++}const d=Array(r).fill(s+t);for(;l>=0&&d.some(m=>m>=s);){const m=e[l];d[m.lane]=m.start,l--}l=Math.max(0,l-l%r),u=Math.min(o,u+(r-1-u%r))}return{startIndex:l,endIndex:u}}const ra=typeof document<"u"?c.useLayoutEffect:c.useEffect;function tj({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...r}){const a=c.useReducer(f=>f+1,0)[1],o=c.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=f=>{const d=o.current;if(!d.enabled||!d.container)return;const m=f.getTotalSize();if(m!==d.lastSize){d.lastSize=m;const v=f.options.horizontal?"width":"height";d.container.style[v]=`${m}px`}const h=!!f.options.horizontal,g=d.mode==="transform",x=h?"left":"top",p=f.options.scrollMargin,b=f.getVirtualItems();for(const v of b){const S=v.start-p,w=f.elementsCache.get(v.key);w&&d.lastPositions.get(w)!==S&&(d.lastPositions.set(w,S),g?w.style.transform=h?`translate3d(${S}px, 0, 0)`:`translate3d(0, ${S}px, 0)`:w.style[x]=`${S}px`)}},l={...r,onChange:(f,d)=>{var m;const h=o.current;let g=!0;if(h.enabled){i(f);const x=f.range,p=h.prevRange;g=!p||p.isScrolling!==f.isScrolling||p.startIndex!==x?.startIndex||p.endIndex!==x?.endIndex,g&&(h.prevRange=x?{startIndex:x.startIndex,endIndex:x.endIndex,isScrolling:f.isScrolling}:null)}g&&(e&&d?Oa.flushSync(a):a()),(m=r.onChange)==null||m.call(r,f,d)}},[u]=c.useState(()=>{const f=new JS(l);return Object.assign(f,{containerRef:d=>{const m=o.current;if(m.container=d,m.lastSize=null,d&&m.enabled){const h=f.getTotalSize();m.lastSize=h;const g=f.options.horizontal?"width":"height";d.style[g]=`${h}px`}}})});return u.setOptions(l),ra(()=>u._didMount(),[]),ra(()=>u._willUpdate()),ra(()=>{i(u)}),u}function sj(e){return tj({observeElementRect:HS,observeElementOffset:QS,scrollToFn:XS,...e})}const nj={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},ef={delete:"moved to Trash",move:"moved",markRead:"marked as read"},tf={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},rj={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},aj={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},oj=(e,t,s)=>nj[e](gt(t),gt(s)),ml=(e,t)=>`${gt(t)} ${ef[e]}. Your mail server is still catching up.`,ij=(e,t,s)=>`${gt(t)} ${ef[e]}. ${gt(s)} ${tf[e]}.`,lj=(e,t)=>t>0?`Stopped after ${gt(t)} — some messages ${tf[e]}`:rj[e],cj=e=>aj[e],uj=e=>e==="delete"?"danger":"info",dj=100,fj=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],mj=({mailboxId:e,accountId:t,enabled:s,predicateKey:r,searchQuery:a})=>{const[o,i]=c.useState({kind:"idle"}),[l,u]=c.useState(void 0),[f,d]=c.useState(void 0),m=c.useRef(!1),h=we(),{pushError:g}=tt();c.useEffect(()=>{m.current=!0,i({kind:"idle"})},[s,r]);const x=c.useRef(a);x.current=a;const p=c.useCallback(async C=>{const{data:E}=await _l({path:{mailboxId:e},query:{...x.current,continuationToken:C,limit:dj},throwOnError:!0});return{ids:(E.items??[]).map(I=>I.messageId),continuationToken:E.continuationToken}},[e]),b=c.useCallback(C=>async E=>{if(C.kind==="move"){const{data:O}=await gm({body:{messageIds:E,destinationMailboxId:C.destinationMailboxId},throwOnError:!0});return O}if(C.kind==="markRead"){const{data:O}=await xm({body:{messageIds:E,isRead:!0},throwOnError:!0});return O}const{data:I}=await bm({body:{messageIds:E},throwOnError:!0});return I},[]),v=c.useCallback(C=>{Nt(h,Ct(fj(C,e))),t&&h.invalidateQueries({queryKey:ns({path:{accountId:t}})})},[h,e,t]),S=c.useCallback(()=>{m.current=!1,i({kind:"counting",countSoFar:0}),Mv(p,C=>i({kind:"counting",countSoFar:C}),()=>m.current).then(C=>{if(C.error){g(Jt("Couldn't count matching messages","The count didn't finish.",C.error)),i({kind:"idle"});return}if(C.cancelled){i({kind:"idle"});return}i({kind:"escalated",total:C.total})})},[p,g]),w=c.useCallback(()=>{m.current=!0},[]),y=c.useCallback(()=>{m.current=!0,i({kind:"idle"})},[]),N=c.useCallback(async(C,E)=>{m.current=!1,u(C);const I=M=>d(Rv(M)),O=b(C),A=E!==void 0?await wu(E,O,I,()=>m.current):await Tv(p,o.kind==="escalated"?o.total:0,O,I,()=>m.current);return u(void 0),d(void 0),i({kind:"idle"}),A.error&&g(Jt(lj(C.kind,A.done),cj(C.kind),A.error)),A.done>0&&v(C),A},[b,p,o,g,v]);return{phase:o,escalate:S,stop:w,clear:y,isRunning:l!==void 0,runningAction:l,progress:f,runAction:N}},sf=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",hj=e=>`Select all ${sf(e)}`,pj=(e,t)=>`All ${gt(t)} ${sf(e)} selected`,gj=(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:Bt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:yr(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),xj=({thread:e,mailboxId:t,isSelected:s,isFocused:r,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,messageCount:f,isMultiSelectMode:d,onLongPress:m,isDesktop:h,density:g})=>n.jsx(Xn,{thread:gj(e,f),linkMailboxId:t,inListbox:!0,active:s,focused:r,isTabStop:a,density:g,isDesktop:h,onFocusRow:o,selection:{isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:d,onLongPress:m}}),bj=c.memo(xj),vj=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:Bt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:yr(e.category),suspicious:t}},yj=({thread:e,mailboxId:t,isSelected:s,isFocused:r,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:f,onLongPress:d,isDesktop:m,onDelete:h,onToggleRead:g,density:x})=>{const[p,b]=c.useState("none"),v=c.useCallback(N=>{navigator.vibrate?.(10),N==="trailing"?h(e.messageId):g(e.messageId,e.isRead),b("none")},[h,g,e.messageId,e.isRead]),S=c.useCallback(()=>{d(e.messageId)},[d,e.messageId]),w=c.useCallback(()=>{l(e.messageId)},[l,e.messageId]),y=Md(e.messageId,u);return m||f?n.jsx(bj,{thread:e,mailboxId:t,isSelected:s,isFocused:r,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:f,onLongPress:d,isDesktop:m,density:x}):n.jsx(Cc,{thread:vj(e),selectionMode:!1,checked:!1,active:s,peek:p,onPeek:b,onToggleCheck:w,onLongPress:S,onOpen:()=>{},onAct:v,linkComponent:({onOpenClick:N,children:C,...E})=>n.jsx(wt,{...E,to:"/mail/$mailboxId",params:{mailboxId:t},search:I=>({...I,selectedMessageId:e.messageId}),"data-message-row":!0,onMouseDown:y.onMouseDown,onContextMenu:y.onContextMenu,onClick:I=>{y.claimClick(I)||N(I)},children:C})})},wj=72,Sj=32,jj=5,nf="remit:list-density",kj={kind:"delete"},hl={kind:"markRead"},Cj=()=>{try{const e=localStorage.getItem(nf);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},Nj=({query:e})=>n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[n.jsx(ir,{className:"size-4 text-fg-muted"}),n.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),Ej=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:r,isError:a=!1,error:o,onRetry:i,searchQuery:l,searchPredicate:u,onDeleteMessages:f,onMoveMessages:d,isDeleting:m=!1,isMoving:h=!1,onLoadMore:g,hasMore:x=!1,isLoadingMore:p=!1,accountId:b,listTitle:v,listMeta:S,listFilter:w,listScopeLabel:y,onTriageContextChange:N,commandsRef:C,hideHeader:E=!1})=>{const I=c.useRef(null),O=$e(),A=_t(),[M,P]=c.useState(!1),[R,j]=c.useState(null),F=!!l?.trim(),[D,k]=c.useState(s),[L,T]=c.useState(),$=c.useCallback(_=>{T(ee=>ee===_?ee:void 0),k(_)},[]),[V,ne]=c.useState(Cj),re=c.useCallback(()=>{ne(_=>{const ee=_==="comfortable"?"compact":"comfortable";try{localStorage.setItem(nf,ee)}catch{}return ee})},[]),{toggleReadFor:q}=vr({mailboxId:e}),{junkMailboxId:Q}=gn(b),{selectedIds:J,selectedCount:te,hasSelection:Z,isSelected:se,toggle:ce,select:xe,clearSelection:Te,selectRange:Y,setAnchor:z,selectAll:B,toggleAll:le,intersectWith:de}=Nd(),_e=Ed(te,A);c.useEffect(()=>{te===0&&j(null)},[te]);const[ae,Ce]=c.useState(null),qe=F&&!!u,Me=`${e}|${JSON.stringify(u??{})}`,U=mj({mailboxId:e,accountId:b,enabled:qe,predicateKey:Me,searchQuery:u??{}}),Ut=U.phase.kind,He=U.clear,pe=c.useCallback(()=>{Ut==="escalated"&&He(),Te()},[Te,He,Ut]),[fe,Ve]=c.useState(null),[dt,ft]=c.useState(null),Qe=c.useRef(null),De=c.useRef(!1),Ae=c.useRef(null),ve=!r&&t.length>0,ze=ae!==null,is=c.useCallback((_,ee)=>{const{exit:Et,retryIds:rt}=Av(ee);if(Et){ft(ml(_.kind,ee.done)),Ve(null),pe();return}if(rt.length>0){Ve({action:_,succeeded:ee.done}),B(rt);return}Ve(null)},[pe,B]),mt=sj({count:t.length,getScrollElement:()=>I.current,estimateSize:()=>V==="compact"?Sj:wj,overscan:jj}),Pe=s?t.findIndex(_=>_.messageId===s):-1,X=D?t.findIndex(_=>_.messageId===D):-1,ie=c.useCallback(_=>{if(_<0||_>=t.length)return;const ee=t[_];if(_e){ce(ee.messageId);return}Qe.current=ee.messageId,De.current=!1,T(ee.messageId),k(ee.messageId)},[t,_e,ce]),me=c.useCallback(()=>{if(t.length===0)return;const _=X<0?0:Math.min(X+1,t.length-1);ie(_)},[t.length,X,ie]),oe=c.useCallback(()=>{if(t.length===0)return;const _=X<=0?0:X-1;ie(_)},[t.length,X,ie]),ge=c.useCallback(()=>ie(0),[ie]),Se=c.useCallback(()=>ie(t.length-1),[ie,t.length]),Ee=c.useCallback(()=>{D&&ce(D)},[D,ce]),be=c.useMemo(()=>t.map(_=>_.messageId),[t]),Be=c.useMemo(()=>{const _=[];for(const ee of t)J.has(ee.messageId)&&ee.fromEmail&&_.push(ee.fromEmail);return _},[t,J]),ot=c.useCallback((_,ee)=>ee.shiftKey?(Y(be,_,D),!0):ee.metaKey||ee.ctrlKey?(ce(_),!0):(pe(),z(_),!1),[be,D,Y,ce,pe,z]),Le=c.useCallback(_=>{!f||_.length===0||(Ae.current=D??null,Ce({source:"ids",ids:_}))},[f,D]),Fe=c.useCallback(()=>{U.phase.kind==="escalated"&&(Ae.current=D??null,Ce({source:"predicate",total:U.phase.total}))},[U.phase,D]),st=c.useCallback(_=>{const ee=Cd(be,D,_);ee!==void 0&&(Y(be,ee),Qe.current=ee,De.current=!1,T(void 0),k(ee))},[be,D,Y]),Ye=c.useCallback(()=>st(-1),[st]),$s=c.useCallback(()=>st(1),[st]),bn=c.useCallback(()=>{be.length>0&&B(be)},[be,B]),_s=c.useCallback(()=>ae!==null?!0:f?te>0?(Le(Array.from(J)),!0):D?(Le([D]),!0):!1:!1,[ae,f,te,J,D,Le]),zs=c.useCallback(()=>{D&&O({to:"/mail/$mailboxId",params:{mailboxId:e},search:_=>({..._,selectedMessageId:D})})},[D,O,e]),qt=c.useCallback(_=>{O({to:"/mail/$mailboxId",params:{mailboxId:e},search:ee=>({...ee,selectedMessageId:_}),replace:!0})},[O,e]);kd({keyboardFocusedMessageId:L,openMessageId:s,enabled:A&&te===0,open:qt});const Ht=c.useCallback(()=>{te>0&&Le(Array.from(J))},[Le,te,J]),We=c.useCallback(async(_,ee)=>{const Et=await U.runAction(_,ee);is(_,Et)},[U,is]),nt=c.useCallback(async _=>{Ce(null),Ae.current=null,await We(kj,_)},[We]),Er=c.useCallback(()=>{if(!ae)return;if(ae.source==="predicate"){nt(void 0);return}const{ids:_}=ae;if(_.length===0){Ce(null);return}if(_.length>yu){nt(_);return}const ee=new Set(_),Et=t.findIndex(Ke=>ee.has(Ke.messageId));let rt;for(let Ke=Et+1;Ke<t.length;Ke++)if(!ee.has(t[Ke].messageId)){rt=t[Ke].messageId;break}if(rt===void 0){for(let Ke=Et-1;Ke>=0;Ke--)if(!ee.has(t[Ke].messageId)){rt=t[Ke].messageId;break}}f?.(_),pe(),Ae.current=null,Ce(null),rt!==void 0&&(Qe.current=rt,De.current=!1,$(rt),A&&O({to:"/mail/$mailboxId",params:{mailboxId:e},search:Ke=>({...Ke,selectedMessageId:rt}),replace:!0})),A||ft(ml("delete",_.length))},[ae,t,f,pe,O,e,A,nt,$]),Ir=c.useCallback(()=>{const _=Ae.current;Ae.current=null,Ce(null),_!==null&&(Qe.current=_,De.current=!1,$(_))},[$]),vn=c.useCallback(()=>{if(U.phase.kind==="escalated"){We(hl);return}te!==0&&We(hl,Array.from(J))},[U.phase,We,te,J]),it=c.useCallback(_=>{if(U.phase.kind==="escalated"){We({kind:"move",destinationMailboxId:_});return}!d||te===0||(d(Array.from(J),_),pe())},[U.phase,We,d,te,J,pe]),Tr=c.useCallback(()=>{Q&&it(Q)},[Q,it]),Wt=c.useMemo(()=>{if(te===0)return;const _=new Set;for(const ee of t)J.has(ee.messageId)&&_.add(ee.accountConfigId);if(_.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[te,J,t]),Rr=c.useCallback(_=>{f?.([_])},[f]),Mr=c.useCallback((_,ee)=>{q([_],!ee)},[q]),Ar=c.useCallback(_=>{A||xe(_)},[A,xe]),yn=c.useCallback(()=>{if(U.phase.kind==="escalated"){Fe();return}Ht()},[U.phase,Fe,Ht]),wn=c.useCallback(()=>{if(U.isRunning||U.phase.kind==="counting"){U.stop();return}pe()},[U,pe]),Vt=c.useCallback(()=>{U.clear()},[U]),Sn=c.useCallback(()=>{if(!fe)return;const _=Array.from(J);if(fe.action.kind==="delete"){nt(_);return}We(fe.action,_)},[fe,nt,We,J]);c.useEffect(()=>{if(De.current||!A&&s)return;const _=X>=0?X:Pe;_>=0&&mt.scrollToIndex(_,{align:"auto"})},[X,Pe,mt,A,s]),c.useEffect(()=>{s&&(De.current=!1,$(s))},[s,$]),c.useEffect(()=>{D&&(t.some(_=>_.messageId===D)||$(t[0]?.messageId))},[t,D,$]),c.useEffect(()=>{N?.({focusedMessageId:D,selectedIds:Array.from(J),hasList:ve,blocksKeyboard:ze})},[D,J,ve,ze,N]);const Bs=c.useRef(N);Bs.current=N,c.useEffect(()=>()=>Bs.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{U.phase.kind!=="idle"||U.isRunning||de(t.map(_=>_.messageId))},[t,de,U.phase,U.isRunning]);const jn=c.useRef(e);c.useEffect(()=>{jn.current!==e&&(jn.current=e,pe())},[e,pe]),Pb({shouldBlockFn:({action:_})=>ow(_,Z)?(pe(),!0):!1,enableBeforeUnload:!1,disabled:!Z}),c.useEffect(()=>{const _=I.current;if(!_||!x||!g)return;const ee=()=>{if(p)return;const{scrollTop:Et,scrollHeight:rt,clientHeight:Ke}=_;Et+Ke>=rt-200&&g()};return _.addEventListener("scroll",ee,{passive:!0}),ee(),()=>_.removeEventListener("scroll",ee)},[x,p,g]),c.useEffect(()=>{const _=Qe.current;if(!_)return;const ee=I.current?.querySelector(`[data-message-id="${_}"]`);ee&&(Qe.current=null,ee.focus({preventScroll:!0}))}),c.useEffect(()=>{if(C){if(!ve){C.current=null;return}return C.current={focusNext:me,focusPrevious:oe,focusFirst:ge,focusLast:Se,openFocused:zs,toggleSelect:Ee,extendSelectDown:$s,extendSelectUp:Ye,selectAll:bn,clearSelection:()=>Z?(pe(),!0):!1,requestDelete:_s,toggleDensity:re},()=>{C.current=null}}},[C,ve,me,oe,ge,Se,zs,Ee,$s,Ye,bn,Z,pe,_s,re]);const kn=r?"loading":a?"error":t.length===0?"empty":"ready",Or=a?Wl(o):void 0,Dr=c.useCallback(()=>{const _=$a(Fa());window.open(_,"_blank","noopener,noreferrer")},[]),Pr=[{id:"inbox",threads:[]}],G=be.length>0&&be.every(_=>J.has(_)),Ge=qe&&x&&G&&!m&&!h&&U.phase.kind==="idle"&&!U.isRunning,Xe=m||h||U.isRunning,Lr=U.phase.kind==="escalated"?U.phase.total:te,Do=U.runningAction?oj(U.runningAction.kind,U.progress?.done??0,U.progress?.total??0):U.phase.kind==="counting"?U.phase.countSoFar>=5e3?`Counting… ${gt(U.phase.countSoFar)} so far. This is a big result set.`:`Counting… ${gt(U.phase.countSoFar)} so far`:U.phase.kind==="escalated"?pj(u??{},U.phase.total):void 0,Po=U.phase.kind!=="escalated"&&be.length>0?{checked:G,indeterminate:te>0&&!G,onChange:()=>le(be)}:void 0,Lo=U.runningAction&&U.progress?{value:U.progress.done,max:U.progress.total,tone:uj(U.runningAction.kind)}:void 0,Fo=U.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:U.stop}}:U.phase.kind==="escalated"&&!U.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:Vt}}:Ge?{tone:"info",text:"",action:{label:hj(u??{}),onClick:U.escalate}}:fe!==null&&te>0?{tone:"danger",text:ij(fe.action.kind,fe.succeeded,te),action:{label:`Retry ${gt(te)}`,onClick:Sn}}:void 0,$o=Fo??(Wt?{tone:"warning",text:Wt}:void 0),_o=E0({isRunning:U.isRunning,isCounting:U.phase.kind==="counting",isEscalated:U.phase.kind==="escalated"}),zo=!A&&_e&&fd(Lr,_o,$o!==void 0),gf=(d||U.phase.kind==="escalated")&&b&&e?n.jsx(Ds,{accountId:b,currentMailboxId:e,onMove:m||h?()=>{}:it,disabledHint:Wt,label:"Move selected messages"}):void 0,Bo=R&&b&&!A&&te>0?n.jsx(Ld,{entry:R,accountId:b,selectedMessageIds:Array.from(J),selectedSenders:Be,junkMailboxId:Q,onClose:()=>{j(null),pe()}}):void 0,Ko=zo?n.jsx(Lc,{count:Lr,mode:_o,onCancel:wn,onDelete:yn,onJunk:Q&&Q!==e&&!Wt?Tr:void 0,onMarkRead:vn,onSelectSimilar:b?()=>j("select-similar"):void 0,onSomethingElse:b?()=>j("something-else"):void 0,moveSlot:gf,isBusy:Xe,selectAll:Po,statusLabel:Do,progress:Lo,notice:$o}):void 0,xf=Ko||Bo?n.jsxs(n.Fragment,{children:[Ko,Bo]}):void 0,bf=Z&&A?n.jsx(No,{selectedCount:Lr,onDelete:yn,onClearSelection:wn,onMarkAsRead:vn,onMove:d?it:void 0,onOrganize:()=>P(!0),isDeleting:m,isMoving:h,accountId:b,currentMailboxId:e,selectedMessageIds:Array.from(J),moveDisabledHint:Wt,selectAll:qe?Po:void 0,statusLabel:Do,isCounting:U.phase.kind==="counting",progress:Lo,notice:Fo}):void 0,vf=Id(be,D),yf=c.useCallback(_=>{De.current=!0,$(_)},[$]),wf=n.jsxs(n.Fragment,{children:[F&&l&&n.jsx(Nj,{query:l}),n.jsxs("div",{ref:I,role:"listbox","aria-multiselectable":!0,"aria-label":v,className:"flex-1 overflow-y-auto",style:zo?{paddingBottom:xs}:void 0,children:[n.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${mt.getTotalSize()}px`},children:mt.getVirtualItems().map(_=>{const ee=t[_.index];return n.jsx("div",{role:"presentation","data-index":_.index,ref:mt.measureElement,className:Ne("absolute left-0 top-0 w-full border-b border-line",U.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${_.start}px)`},children:n.jsx(yj,{thread:ee,mailboxId:e,isSelected:s===ee.messageId,isFocused:D===ee.messageId,isTabStop:vf===ee.messageId,onFocusRow:yf,isChecked:se(ee.messageId),onToggleCheck:ce,onRowSelect:ot,isMultiSelectMode:_e,onLongPress:Ar,isDesktop:A,onDelete:Rr,onToggleRead:Mr,density:V})},_.key)})}),p&&n.jsx(rp,{})]})]}),Sf=ae?ae.source==="ids"?ae.ids.length:ae.total:0,Uo=ae?.source==="predicate";return n.jsxs(n.Fragment,{children:[dt&&!A&&n.jsx(ss,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>ft(null),children:dt}),n.jsx(Nc,{listTitle:v,listMeta:S,sections:Pr,flatList:!0,listState:kn,searchQuery:F?l:void 0,listFilter:w,listScopeLabel:y,errorMessage:Or,onRetry:i,onReportError:Dr,density:V,selectedThreadId:s,onSelectThread:_=>O({to:"/mail/$mailboxId",params:{mailboxId:e},search:ee=>({...ee,selectedMessageId:_})}),onSelectBriefCategory:()=>{},isDesktop:A,hideHeader:E,selectionBar:bf,selectionSheet:xf,listBody:kn==="ready"?wf:void 0}),n.jsx(Ga,{isOpen:ae!==null,title:Ql(Sf,Uo),description:Uo?"This count is a snapshot — new mail arriving during the delete won't be included. You can restore what's deleted from Trash later.":"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:m,onConfirm:Er,onCancel:Ir}),M&&b&&n.jsx(Fd,{open:M,accountId:b,selectedMessageIds:Array.from(J),selectedSenders:Be,onClose:()=>P(!1)})]})},Ij=e=>ns({path:{accountId:e}}),Tj=e=>{const t=we(),s=on(),r=je({...vm(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:Ij(e)})}});return{trigger:()=>{r.mutate({path:{accountId:e}})},triggerAsync:()=>r.mutateAsync({path:{accountId:e}}),isPending:r.isPending,error:r.error,reset:r.reset}},Rj=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:r}=Tj(e);return n.jsx(Ig,{onRefresh:s,isRefreshing:r,children:t})};function Mj({accountId:e,currentMailboxId:t,candidates:s,onMove:r,children:a}){const[o,i]=c.useState(!1),l=on(),{t:u}=tr("mail",{useSuspense:!1}),f=c.useCallback((S,w)=>u(S,{defaultValue:w}),[u]),{inboxMailboxId:d}=xo(e),m=Cu(e),{data:h}=ue({...Ue({path:{accountId:e}}),staleTime:1/0}),g=c.useMemo(()=>{const S=cn(h?.items??[],m),w=an(m);return S.map(y=>({id:y.mailboxId,label:js(y,w.get(y.mailboxId),f),searchValue:y.fullPath,isCurrent:y.mailboxId===t}))},[h?.items,m,t,f]),x=c.useMemo(()=>d||(g.find(w=>w.label.toLowerCase()==="inbox")?.id??g.find(w=>!w.isCurrent)?.id??""),[d,g]),p=c.useRef(!1);c.useEffect(()=>{p.current||(p.current=!0,Zw(l,s.length))},[l,s.length]);const b=c.useCallback(()=>{eS(l,s.length),i(!0)},[l,s.length]),v=c.useCallback((S,w)=>{tS(l,{selected:S.length,total:s.length,toInbox:w===d}),r(S,w)},[l,s.length,d,r]);return n.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[n.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:n.jsx(Mg,{count:s.length,onReview:b})}),n.jsx("div",{className:"min-h-0 flex-1",children:a}),n.jsx(Bg,{open:o,candidates:s,defaultDestinationId:x,availableFolders:g,onConfirmMove:v,onCancel:()=>i(!1)})]})}const Aj="We can verify this sender";function Oj(e){const{data:t}=ue({...ym({path:{mailboxId:e??""},query:{senderTrust:["vip","wellknown"],dkimMismatch:!1,results:!0,limit:500}}),enabled:!!e,staleTime:6e4});return{candidates:(t?.items??[]).map(r=>({id:r.messageId,senderName:r.fromName||r.fromEmail||"Unknown sender",senderAddress:r.fromEmail??"",subject:r.subject||"(no subject)",snippet:r.snippet??"",trustReason:Aj,trustSubReason:Jw(r.senderTrust),senderTrust:r.senderTrust}))}}const Dj=e=>{const t=new Set,s=[];for(const r of e)t.has(r.threadMessageId)||(t.add(r.threadMessageId),s.push(r));return s},Pj={unread:"unread",flagged:"starred",attachment:"attachments"},Lj=new Set(Object.values(Je)),rf=e=>Lj.has(e),Fj=e=>rf(e.category)||e.attributes.size>0,$j=e=>{const t={};rf(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const r=Pj[s];r&&(t[r]=!0)}return t},_j=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",zj=["category","unread","starred","attachments"],pl=e=>JSON.stringify(zj.map(t=>e?.[t]??null)),Bj=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},Kj=(e,t)=>{const s=Bj(e);return s?pl(s)===pl(t):!1},af="remit:intelligence-open";function Uj(){try{return localStorage.getItem(af)!=="closed"}catch{return!0}}function gl(e){try{localStorage.setItem(af,e?"open":"closed")}catch{}}const qj=(e,t)=>e!==t,Hj=(e,t,s)=>{if(!(s||!t))return e.find(r=>r.messageId===t)},Wj=(e,t,s,r)=>{if(e)return e;if(!(r||!s))return t?.messageId===s?t:void 0},Ln=e=>e[0],Vj=e=>{const t=Ln(e.filter(l=>l.type==="from").map(l=>l.value)),s=Ln(e.filter(l=>l.type==="subject").map(l=>l.value)),r=Ln(e.filter(l=>l.type==="category").map(l=>l.category)),a=Ln(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}:{},...r!==void 0?{category:[r]}:{},...a!==void 0?{unread:a}:{},...o!==void 0?{starred:o}:{},...i!==void 0?{attachments:i}:{}}},Qj=(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 Yj(e,t={}){const s=Vj(e),r={...s,...t};return{params:s,residual:e.filter(a=>!Qj(r,a))}}function Gj(e,t,s){if(t.length===0)return e;const r=[...t];return e.filter(a=>{const o=Gn(a);return ko({...o,accountId:o.accountId??s},r)})}const Xj=50,Jj=new Map(_c().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),of=c.createContext(null);function Nr(){const e=c.useContext(of);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function Zj({mailboxId:e,selectedMessageId:t,children:s}){const r=$e(),o=jr()==="desktop",i=on(),{accounts:l,searchQuery:u,searchInput:f,intelligenceOpen:d,onToggleIntelligence:m,onSetIntelligenceOpen:h}=ke(),g=os(),x=So(u),p=x.length>0,{freeText:b,tokens:v}=Ls(x,g),[S,w]=c.useState("all"),[y,N]=c.useState(new Set),C=c.useMemo(()=>({category:S,attributes:y}),[S,y]),E=c.useMemo(()=>$j(C),[C]),I=p||Fj(C),{params:O,residual:A}=Yj(v,E),M={order:"desc",limit:Xj,...b?{query:b}:{},...O,...E},P={category:M.category,unread:M.unread,starred:M.starred,attachments:M.attachments},R=I?za({path:{mailboxId:e},query:M}):ar({path:{mailboxId:e},query:{order:"desc"}}),{data:j,isLoading:F,isError:D,error:k,refetch:L,fetchNextPage:T,hasNextPage:$,isFetchingNextPage:V}=Zc({queryKey:R,queryFn:async({pageParam:G})=>{if(I){const{data:Xe}=await _l({path:{mailboxId:e},query:{...M,continuationToken:G},throwOnError:!0});return Xe}const{data:Ge}=await wm({path:{mailboxId:e},query:{order:"desc",continuationToken:G},throwOnError:!0});return Ge},initialPageParam:void 0,getNextPageParam:G=>G.continuationToken,placeholderData:(G,Ge)=>Kj(Ge?.queryKey,P)?G:void 0}),ne=c.useCallback(G=>{t&&G.includes(t)&&r({to:"/mail/$mailboxId",params:{mailboxId:e},search:Ge=>({...Ge,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,r]),{deleteMessages:re,isPending:q}=es({mailboxId:e,onAfterOptimisticRemove:ne}),{accountId:Q}=ho(e),J=uu({accounts:l}),{moveMessages:te,isPending:Z}=Lt({mailboxId:e,accountId:Q,onAfterOptimisticRemove:ne}),se=Gj(Xv(Dj(j?.pages.flatMap(G=>G.items??[])??[])),A,Q),ce=c.useCallback(G=>{w(G)},[]),xe=c.useCallback(G=>{N(Ge=>{const Xe=new Set(Ge);return Xe.has(G)?Xe.delete(G):Xe.add(G),Xe})},[]),Te=c.useCallback(()=>{w("all"),N(new Set)},[]),Y=Jj.get(S),z=Y?{label:Y,reach:A.length>0?"loaded-pages":_j(M),onClear:Te}:void 0,B=qj(f,u),le=Hj(se,t,B),[de,_e]=c.useState(void 0);c.useEffect(()=>{le&&_e(le)},[le]);const ae=Wj(le,de,t,B),{selectedThreadId:Ce}=Cs({strict:!1}),qe=c.useMemo(()=>Hd(ae,{messageId:t,threadId:B?void 0:Ce,mailboxId:e}),[ae,t,Ce,B,e]),Me=To(),{listCommandsRef:U,onTriageContextChange:Ut,focusedMessageId:He,selectedIds:pe}=Me,fe=se.find(G=>G.messageId===He)??ae,Ve=c.useRef(null);c.useEffect(()=>{const G=ae?.messageId??null;G&&Ve.current!==G&&ae?.authenticity?.dkimMismatch&&(Ve.current=G,d||m())},[ae?.messageId,ae?.authenticity?.dkimMismatch,d,m]);const dt=c.useRef(!1);c.useEffect(()=>{dt.current||o&&ae?.messageId&&(dt.current=!0,Uj()&&!d&&h(!0))},[o,ae?.messageId,d,h]);const ft=Qb({accounts:l})??0,Qe=we(),{pushError:De}=tt(),Ae=sn({thread:ae,mailboxId:e,accountId:Q,onAfterOptimisticRemove:ne}),{draftsMailboxId:ve}=Qv(Q),ze=ve!==void 0&&ve===e,{archiveMailboxId:is}=Vv(Q),mt=qd(),{requestCompose:Pe}=Ae,X=c.useCallback(()=>{Pe("reply")},[Pe]),ie=c.useCallback(()=>{Pe("reply_all")},[Pe]),me=c.useCallback(()=>{Pe("forward")},[Pe]),{state:oe,openCompose:ge,closeCompose:Se}=$t(),Ee=c.useCallback(()=>{ge({mode:"new"})},[ge]),be=je({...rr(),onError:G=>{De(Jt("Couldn't discard draft","The draft wasn't deleted.",G))}}),Be=c.useCallback(()=>{const G=oe.outboxMessageId;G&&(be.mutate({path:{outboxMessageId:G}}),Qe.invalidateQueries({queryKey:qa()}),Se())},[oe.outboxMessageId,be,Qe,Se]),ot=c.useCallback(()=>{r({to:"/mail/$mailboxId",params:{mailboxId:e},search:G=>({...G,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,r]),Le=c.useCallback(G=>G?mt(G):[],[mt]),{toggleStar:Fe}=po({threadId:fe?.threadId??"",mailboxId:e}),{toggleReadFor:st}=vr({mailboxId:e,accountId:Q}),{junkMailboxId:Ye}=gn(Q),$s=Ye!=null&&Ye===e,{candidates:bn}=Oj($s?Ye:void 0),{moveMessages:_s}=Lt({mailboxId:e,threadId:fe?.threadId,accountId:Q,onAfterOptimisticRemove:ne}),{deleteMessages:zs}=es({mailboxId:e,threadId:fe?.threadId,onAfterOptimisticRemove:ne}),{addressId:qt,address:Ht}=zd(fe),{updateFlags:We}=Bd({addressId:qt,senderEmail:fe?.fromEmail??void 0}),nt=c.useCallback(()=>t||!He?!1:(r({to:"/mail/$mailboxId",params:{mailboxId:e},search:G=>({...G,selectedMessageId:He})}),!0),[t,He,e,r]),Er=c.useCallback(()=>{nt()||ae&&Pe("reply")},[nt,ae,Pe]),Ir=c.useCallback(()=>{nt()||ae&&Pe("reply_all")},[nt,ae,Pe]),vn=c.useCallback(()=>{nt()||ae&&Pe("forward")},[nt,ae,Pe]),it=c.useCallback(()=>pe.length>0?pe:Le(fe),[pe,Le,fe]),Tr=c.useCallback(()=>{if(U.current?.requestDelete())return;const G=it();G.length>0&&zs(G)},[U,it,zs]),Wt=c.useCallback(()=>{if(!Ye)return;const G=it();G.length!==0&&(Ud(i,{count:G.length,senderTrust:fe?.senderTrust??"unknown",wasRescuable:fe?Kd(fe):!1}),_s(G,Ye))},[Ye,it,_s,i,fe]),Rr=c.useCallback(()=>{if(pe.length>0){const G=!(fe?.hasStars??!1),Ge=new Set(pe);for(const Xe of se)Ge.has(Xe.messageId)&&Xe.hasStars!==G&&Fe(Xe.messageId,Xe.hasStars);return}fe&&Fe(fe.messageId,fe.hasStars)},[pe,se,fe,Fe]),Mr=c.useCallback(()=>{const G=it();if(G.length===0)return;const Ge=!(fe?.isRead??!1);st(G,Ge)},[it,fe,st]),Ar=c.useCallback(()=>{if(!qt)return;const G=Ht?.flags?.muted?.value!==!0;We({muted:{value:G}})},[qt,Ht,We]),yn=c.useCallback(()=>{if(!qt)return;const G=Ht?.flags?.vip?.value!==!0;We({vip:{value:G}})},[qt,Ht,We]),wn=c.useCallback(()=>{d||m()},[d,m]),Vt=c.useCallback(G=>{r({to:G})},[r]),Sn=ze?"drafts":is===e?"archive":Ye===e?"junk":"inbox",Bs=c.useRef("");c.useEffect(()=>{const G=Bs.current;Bs.current=x,x.length>0&&G.length===0&&i.recordEvent("search.submitted",{mailboxType:Sn})},[x,Sn,i]);const jn=ze&&oe.isOpen&&!!oe.outboxMessageId&&!ae,{goBack:kn,nextMessageId:Or,previousMessageId:Dr}=Ro({context:Me,orderedIds:se.map(G=>G.messageId),selectedMessageId:t,enabled:!oe.isOpen,onClose:ot,handlers:{reply:Er,replyAll:Ir,forward:vn,delete:Tr,toggleStar:Rr,toggleRead:Mr,muteSender:Ar,blockSender:wn,vipSender:yn,markJunk:Wt,toggleIntelligence:ae?m:void 0,compose:Ee,goBrief:()=>Vt("/mail"),goInbox:()=>Vt("/mail"),goSent:()=>Vt("/mail"),goFlagged:()=>Vt("/mail/flagged"),goSettings:()=>Vt("/settings")}});mo({enabled:oe.isOpen,bindings:[{key:"Escape",handler:Se,preventDefault:!0}]});const Pr={mailboxId:e,selectedMessageId:t,selectedThread:ae,conversation:qe,threads:se,isLoading:F,isError:D,error:k,mailboxAccountId:Q,mailboxName:J,unreadCount:ft,isDraftsMailbox:ze,isSpamFolder:$s,rescueCandidates:bn,filterCategory:S,filterAttributes:y,onSelectFilterCategory:ce,onToggleFilterAttribute:xe,onClearFilters:Te,listFilter:z,intelligenceOpen:d,onToggleIntelligence:m,searchPredicate:p&&A.length===0?M:void 0,onDeleteMessages:re,onMoveMessages:te,isDeleting:q,isMoving:Z,onLoadMore:T,hasMore:$,isLoadingMore:V,onTriageContextChange:Ut,listCommandsRef:U,onRetry:()=>L(),toolbarComposeRequest:Ae.composeRequest,onToolbarReply:X,onToolbarReplyAll:ie,onToolbarForward:me,onClearComposeRequest:Ae.clearComposeRequest,onToolbarDelete:Ae.deleteThread,onToolbarStar:Ae.toggleStar,onToolbarDiscardDraft:Be,onToolbarMove:Ae.moveThread,composeState:oe,closeCompose:Se,hasRemitDraftOpen:jn,onBack:kn,nextMessageId:Or,previousMessageId:Dr};return n.jsx(of.Provider,{value:Pr,children:s})}function lf(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:r,isError:a,error:o,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,mailboxAccountId:g,mailboxName:x,unreadCount:p,isDraftsMailbox:b,isSpamFolder:v,rescueCandidates:S,onTriageContextChange:w,listCommandsRef:y,onRetry:N,filterCategory:C,filterAttributes:E,onSelectFilterCategory:I,onToggleFilterAttribute:O,onClearFilters:A,listFilter:M,searchPredicate:P}=Nr(),{searchQuery:R,searchInput:j,accounts:F,resultFolderIndex:D}=ke(),k=jr(),L=$e(),T=x??"Inbox",$=c.useMemo(()=>_c(),[]),V=c.useMemo(()=>s.map(ce=>C0(ce,D)),[s,D]),{hits:ne,isLoading:re}=ld({mailboxId:e,filterCategory:C}),q=c.useMemo(()=>dd(ne,s.map(ce=>ce.threadId),D),[ne,s,D]),Q=c.useCallback(ce=>L({to:"/mail/$mailboxId",params:{mailboxId:ce.mailboxId??e},search:xe=>({...xe,q:j||void 0,selectedMessageId:ce.id,selectedThreadId:ce.threadId})}),[e,L,j]);if(b&&g)return n.jsx(_S,{mailboxId:e,accountId:g,selectedMessageId:t,imapThreads:s,title:x??"Drafts",unreadCount:p??void 0});const J=n.jsx(Ej,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:r,isError:a,error:o,onRetry:N,searchQuery:R,searchPredicate:P,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:f,onLoadMore:d,hasMore:m,isLoadingMore:h,accountId:g,listTitle:T,listFilter:M,listScopeLabel:T,hideHeader:!0,onTriageContextChange:w,commandsRef:y}),te=F[0]?.accountId,Z=k==="phone"&&te?n.jsx(Rj,{accountId:te,children:J}):J,se=v&&S.length>0&&g?n.jsx(Mj,{accountId:g,currentMailboxId:e,candidates:S,onMove:l,children:Z}):Z;return n.jsx(Yd,{title:T,unreadCount:p,preset:$,selectedCategory:C,activeFilters:E,onSelectCategory:I,onToggleFilter:O,onClearFilters:A,searchResults:V,searchLoading:r,relatedResults:q,relatedLoading:re,onSelectSearchResult:Q,searchResultsInBody:!0,children:se})}function ek(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:r,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:l,onToolbarReply:u,onToolbarReplyAll:f,onToolbarForward:d,onClearComposeRequest:m,onToolbarDelete:h,onToolbarStar:g,onToolbarDiscardDraft:x,onToolbarMove:p,composeState:b}=Nr(),v=Is()?.showIntelligencePane??!1,S=!!r,w=v&&S,y=b.isOpen&&!r?n.jsx(Jd,{}):r?n.jsx(Ps,{threadId:r.threadId,mailboxId:r.mailboxId,subject:r.subject,selectedMessageId:r.messageId,authenticity:r.authenticity,onOpenIntelligence:r.authenticity?.dkimMismatch?i:void 0,composeRequest:l,onComposeClose:m}):n.jsx(Os,{});return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx(Io,{hasThread:S,intelligenceOpen:w&&o,canToggleIntelligence:w,onToggleIntelligence:i,onReply:S?u:void 0,onReplyAll:S?f:void 0,onForward:S?d:void 0,canDelete:S||a,onDelete:S?h:a?x:void 0,onToggleStar:S?g:void 0,isStarred:s?.hasStars,moveContext:S&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:y})]})}function tk(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:r}=Nr();return n.jsx(Fs,{onClose:r,thread:s,mailboxId:e,accountId:t})}function sk(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:r,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=Nr(),f=$e();if(s){const d=m=>f({to:"/mail/$mailboxId",params:{mailboxId:e},search:h=>({...h,selectedMessageId:m,selectedThreadId:void 0})});return n.jsxs(n.Fragment,{children:[n.jsx(Ps,{threadId:s.threadId,mailboxId:s.mailboxId,subject:s.subject,selectedMessageId:s.messageId,authenticity:s.authenticity,onBack:o,onOpenIntelligence:a,onSwipeNext:i?()=>d(i):void 0,onSwipePrevious:l?()=>d(l):void 0,mobileIntelligenceOpen:r}),n.jsx(uo,{isOpen:r,onClose:a,ariaLabel:"Message details",side:"right",children:n.jsx(Fs,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?n.jsx("div",{className:"h-full",children:n.jsx(Jd,{})}):n.jsx(lf,{})}const Gs=Object.assign(Zj,{List:lf,Reading:ek,Intelligence:tk,Phone:sk}),cf=e=>e==="failed"||e==="blocked",uf=e=>e!=="draft"&&e!=="sent",Ao="remit.savedSearches",nk=25;function Zn(){try{const e=localStorage.getItem(Ao);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function rk(e){const t=e.trim();if(!t)return Zn();const s=[t,...Zn().filter(r=>r!==t)].slice(0,nk);try{localStorage.setItem(Ao,JSON.stringify(s))}catch{return s}return s}function ak(e){const t=Zn().filter(s=>s!==e);try{localStorage.setItem(Ao,JSON.stringify(t))}catch{return t}return t}const xl=e=>/^\d/.test(e),ok=(e,t)=>{const s=xl(e),r=xl(t);return s&&!r?-1:!s&&r?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function ik(e,t,s){const r=[],a=[];for(const o of e)t.has(o.mailboxId)?r.push(o):a.push(o);return a.sort((o,i)=>ok(js(o,void 0,s),js(i,void 0,s))),{system:r,labels:a}}function lk(e,t,s){const r=Sm(t)&&e.unseenCount>0;return{id:e.mailboxId,name:js(e,t,s),unseen:r?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function ck(){const e=pr(),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 bl({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const r=we(),a=$e(),o=ck(),{searchInput:i,onSearchChange:l}=ke(),[u,f]=c.useState(Zn),{t:d}=tr("mail",{useSuspense:!1}),m=c.useCallback((I,O)=>d(I,{defaultValue:O}),[d]),h=vt({queries:e.map(I=>({...Ue({path:{accountId:I.accountId}}),staleTime:1/0}))}),{data:g}=ue(sr()),x=c.useMemo(()=>(g?.items??[]).filter(I=>uf(I.status)).length,[g?.items]),p=c.useMemo(()=>e.map((I,O)=>{const A=h[O],M=A?.data?.items??[],P=an(I.folderAppointments),{system:R,labels:j}=ik(M,P,m),F=A?.isError?"error":A?.isLoading?"loading":"ready";return{id:I.accountId,label:I.email,email:I.email,muted:!!I.muted,outboxPending:x,status:F,onRetry:()=>A?.refetch(),mailboxes:[...R,...j].map(D=>lk(D,P.get(D.mailboxId),m))}}),[e,h,x,m]),b=I=>{r.invalidateQueries({queryKey:ar({path:{mailboxId:I},query:{order:"desc"}})})},v=({navId:I,className:O,ariaLabel:A,title:M,children:P,onClick:R})=>I==="brief"?n.jsx(wt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>R?.(),className:O,"aria-label":A,title:M,children:P}):I==="outbox"?n.jsx(wt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>R?.(),className:O,"aria-label":A,title:M,children:P}):I==="flagged"?n.jsx(wt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>R?.(),className:O,"aria-label":A,title:M,children:P}):I==="settings"?n.jsx(wt,{to:"/settings/accounts",onClick:()=>R?.(),className:O,"aria-label":A,title:M,children:P}):n.jsx(wt,{to:"/mail/$mailboxId",params:{mailboxId:I},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{b(I),R?.()},className:O,"aria-label":A,title:M,children:P}),S=()=>{l(""),t?.()},w=i.trim(),y=w.length>0&&!u.includes(w)?w:void 0,N=c.useCallback(()=>{y&&f(rk(y))},[y]),C=c.useCallback(I=>{f(ak(I))},[]),E=c.useCallback(I=>{l(I),a({to:"/mail",search:{q:I,selectedMessageId:void 0}}),t?.()},[l,a,t]);return n.jsx(eg,{accounts:p,selectedNavId:o,onSelectNav:S,linkComponent:v,variant:s,savedSearches:u,saveableQuery:y,onSaveCurrentSearch:N,onSelectSavedSearch:E,onRemoveSavedSearch:C})}function uk({accounts:e,onMailboxSelect:t}){return Is()?.showNavPane??!0?n.jsx(bl,{accounts:e}):n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsx("div",{className:"flex-1 overflow-y-auto",children:n.jsx(bl,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),n.jsxs("div",{className:"border-t border-line px-2 py-2",children:[n.jsxs(wt,{to:"/settings/accounts",onClick:t,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[n.jsx(eo,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),n.jsx(nu,{variant:"drawer"}),n.jsx(su,{children:({signOut:a})=>n.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[n.jsx(hc,{className:"size-4 shrink-0"}),n.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function dk(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const r=[e.subject,e.fromAddress,e.fromName,...e.toAddresses??[],...e.ccAddresses??[]].filter(a=>typeof a=="string").join(" ").toLowerCase();return s.split(/\s+/).every(a=>a.length===0||r.includes(a))}function fk(e){return e.tokens.length>0&&e.freeText.trim().length===0}const df={queued:{icon:Wa,label:"Queued",className:"text-warning"},sending:{icon:et,label:"Sending…",className:"text-accent-2"},sent:{icon:uc,label:"Sent",className:"text-positive"},failed:{icon:ts,label:"Failed",className:"text-danger"},blocked:{icon:Ma,label:"Blocked",className:"text-warning"}},mk=e=>Hm(e).toDateString()===new Date().toDateString()?qn(e,{hour:"numeric",minute:"2-digit"}):qn(e,{month:"short",day:"numeric"}),vl=e=>qn(e,{dateStyle:"medium",timeStyle:"short"}),hk=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},ff=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",mf=c.createContext(null);function Oo(){const e=c.useContext(mf);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function pk({children:e}){const t=$e(),{selectedOutboxMessageId:s}=Cs({strict:!1}),{data:r,isLoading:a}=ue(sr()),{searchQuery:o}=ke(),i=os(),l=So(o),u=Ls(l,i),f=l.length>0,d=fk(u),m=c.useMemo(()=>d?[]:(r?.items??[]).filter(p=>uf(p.status)).filter(p=>dk(p,u.freeText)),[r,u.freeText,d]),h=c.useMemo(()=>m.find(p=>p.outboxMessageId===s),[m,s]),g=c.useCallback(p=>{t({to:"/mail/outbox",search:b=>({...b,selectedOutboxMessageId:p})})},[t]),x={messages:m,hasQuery:f,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:g};return n.jsx(mf.Provider,{value:x,children:e})}function hf({message:e,isSelected:t,onSelect:s}){const r=we(),{openCompose:a}=$t(),{pushError:o}=tt(),i=c.useCallback(()=>{r.invalidateQueries({queryKey:qa()})},[r]),l=je({...Ol(),onSuccess:i,onError:m=>{o(Jt("Couldn't resend message","The message wasn't sent.",m))}}),u=je({...rr(),onSuccess:i,onError:m=>{o(Jt("Couldn't delete message","The message wasn't deleted.",m))}}),f=e.status;if(!df[f])return null;const d=cf(e.status);return n.jsx(Ng,{recipients:hk(e),subject:e.subject||"",time:mk(e.sentAt??e.updatedAt),status:f,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:f==="failed"?()=>l.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:l.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function pf({message:e,onBack:t}){const s=e.status,r=df[s],a=r?.icon??rn,o=e.sentAt?vl(e.sentAt):vl(e.updatedAt);return n.jsxs("div",{className:"h-full overflow-y-auto bg-canvas",children:[n.jsxs("div",{className:"border-b border-line p-4",children:[t&&n.jsxs("button",{type:"button",onClick:t,className:"mb-3 inline-flex items-center gap-1 text-sm text-fg-muted hover:text-fg",children:[n.jsx(lc,{className:"size-4"}),n.jsx("span",{children:"Back"})]}),n.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),n.jsxs("div",{className:"space-y-1 text-sm",children:[n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),n.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),n.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),n.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),n.jsx("span",{className:"text-fg",children:o})]}),r&&n.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[n.jsx(a,{className:Ne("size-4",r.className,s==="sending"&&"animate-spin")}),n.jsx("span",{className:Ne("text-xs font-medium",r.className),children:r.label}),cf(e.status)&&e.lastError&&n.jsxs("span",{className:"text-xs text-fg-muted",children:["— ",e.lastError]})]})]})]}),n.jsx("div",{className:"p-4",children:n.jsx(Ju,{html:e.htmlBody,text:e.textBody})})]})}function gk(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,onSelectMessage:o}=Oo(),i=c.useRef(null);return er({containerRef:i,itemSelector:Ea}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Os,{message:ff(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(Mo,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(l=>n.jsx(hf,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function xk(){const{selectedMessage:e}=Oo();return n.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[n.jsx("header",{className:"flex h-pane-header shrink-0 items-center border-b border-line px-3"}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?n.jsx(pf,{message:e}):n.jsx(Os,{message:"Select a message to read",showHints:!1})})]})}function bk(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:r,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=Oo(),l=c.useRef(null);return er({containerRef:l,itemSelector:Ea}),r?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:n.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?n.jsx(pf,{message:o,onBack:()=>i(void 0)}):e.length===0?n.jsx("div",{className:"flex h-full bg-surface",children:n.jsx(Os,{message:ff(t,s),showHints:!1})}):n.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[n.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[n.jsx(Mo,{}),n.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),n.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),n.jsx("div",{ref:l,className:"flex-1 overflow-y-auto",children:e.map(u=>n.jsx(hf,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const Fn=Object.assign(pk,{List:gk,Reading:xk,Phone:bk}),vk=({isOpen:e,onClose:t})=>{const s=c.useCallback(r=>{r.key==="Escape"&&(r.preventDefault(),t())},[t]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?n.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:t,onKeyDown:r=>r.key==="Escape"&&t(),children:[n.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),n.jsxs("div",{className:Ne("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),onClick:r=>r.stopPropagation(),onKeyDown:r=>{r.key!=="Escape"&&r.stopPropagation()},children:[n.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[n.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),n.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:n.jsx(Ze,{className:"size-5"})})]}),n.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:fu.map(r=>n.jsxs("div",{children:[n.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:r.title}),n.jsx("div",{className:"space-y-2",children:r.hints.map(a=>n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsx("span",{className:"text-sm",children:a.description}),n.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>n.jsxs(c.Fragment,{children:[i>0&&a.keys[0]==="g"&&n.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),n.jsx(vs,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},r.title))}),n.jsx("div",{className:"mt-6 border-t border-line pt-4",children:n.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",n.jsx(vs,{children:"Esc"})," to close"]})})]})]}):null};function yk(e){const t=vt({queries:e.map(s=>({...Ue({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>B0(t.map(s=>s.data?.items??[])),[t])}const wk=e=>e.map(t=>t.data?.items??[]);function Sk(e){const t=vt({queries:e.map(s=>({...Ue({path:{accountId:s.accountId}}),staleTime:1/0})),combine:wk});return c.useMemo(()=>jm(e.map((s,r)=>({folderAppointments:s.folderAppointments,mailboxes:t[r]??[]}))),[e,t])}var $n={exports:{}},yl;function jk(){if(yl)return $n.exports;yl=1;const e=(t,s,r)=>new Promise((a,o)=>{if(r=Object.assign({concurrency:1/0},r),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=r;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const l=[],u=t[Symbol.iterator]();let f=!1,d=!1,m=0,h=0;const g=()=>{if(f)return;const x=u.next(),p=h;if(h++,x.done){d=!0,m===0&&a(l);return}m++,Promise.resolve(x.value).then(b=>s(b,p)).then(b=>{l[p]=b,m--,g()},b=>{f=!0,o(b)})};for(let x=0;x<i&&(g(),!d);x++);});return $n.exports=e,$n.exports.default=e,$n.exports}var kk=jk();const Ck=km(kk),Nk=900*1e3,Ek=300,Ik=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},Tk=60*1e3,Rk=e=>Math.max(Ik(e,Ek)*1e3,Tk),Un=Rk(Em().mailboxPollIntervalSeconds),Mk=5,Ca=new Set,Ak=(e,t,s=Nk)=>e.filter(r=>{const a=r.lastSyncAt;return a==null?!0:t-a>s}).map(r=>r.accountId),Ok=(e,t,s=Un)=>e-t>=s,Dk=(e,t)=>e.filter(s=>!t.has(s)),wl=(e,t)=>{if(Ca.delete(e),Nm(t,{softError:!0})){$l(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},Sl=(e,t)=>Cm({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:ns({path:{accountId:e}})})}),Pk=e=>{const t=we(),s=c.useRef(e);s.current=e;const r=e.map(a=>a.accountId).join(",");c.useEffect(()=>{const a=Date.now(),i=Ak(s.current,a).filter(l=>!Ca.has(l));if(i.length!==0)for(const l of i)Ca.add(l),Sl(l,t).catch(u=>{wl(l,u)})},[r,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const d=Dk(s.current.map(m=>m.accountId),i);for(const m of d)i.add(m);Ck(d,m=>Sl(m,t).catch(h=>{wl(m,h)}).finally(()=>{i.delete(m)}),{concurrency:Mk})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,Un);return}},f=()=>{document.visibilityState==="visible"&&Ok(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,Un))};return o=setTimeout(u,Un),document.addEventListener("visibilitychange",f),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",f)}},[r,t])};function Lk(e,t,s){if(e!==t)return s}function Fk(e,t){return e===""?"":t}function $k(e,t,s){return t!==e?!1:t!==s}function _k(){const{q:e=""}=Cs({from:"/mail"}),t=$e(),s=jr(),r=md(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,f]=c.useState(!1),d=c.useCallback(Z=>{f(Z),gl(Z)},[]),[m,h]=c.useState(e),g=lr(m,200),x=Fk(m,g),p=c.useRef(e);p.current=e;const b=St({select:Z=>Ub(Z.matches)}),[v,S]=c.useState(b);if(v!==b){const Z=Lk(v,b,e);S(b),Z!==void 0&&h(Z)}c.useEffect(()=>{$k(m,x,p.current)&&t({to:".",search:Z=>{const se=Z.q===x;return{...Z,q:x||void 0,...x&&!se?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[m,x,t]);const{data:w,isLoading:y,isError:N,error:C,refetch:E}=ue({...jt(),staleTime:1/0}),I=!!(w&&(w.accounts?.length??0)===0);c.useEffect(()=>{I&&t({to:"/onboarding",replace:!0})},[I,t]),mo({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const O=c.useCallback(Z=>{h(Z)},[]),A=c.useCallback(()=>{h("")},[]),M=c.useCallback(()=>{h("")},[]),P=c.useCallback(()=>{f(Z=>{const se=!Z;return gl(se),se})},[]),R=w?.accounts??[],j=yk(R),F=Sk(R),D=c.useMemo(()=>z0(R),[R]),k=St({select:Z=>Z.matches.find(ce=>"mailboxId"in ce.params)?.params.mailboxId}),{selectedMessageId:L}=Cs({strict:!1}),T=St({select:Z=>co(Z.matches)}),$=St({select:Z=>dn(Z.matches)}),V=St({select:Z=>gr(Z.matches)});Pk(R);const ne=c.useCallback(()=>{l(!1)},[]),re={accounts:R,mailboxNameIndex:j,accountNameIndex:D,resultFolderIndex:F,searchQuery:x,searchInput:m,searchViewKey:b,onSearchChange:O,onSearchClear:A,onSearchClearQuery:M,intelligenceOpen:u,onToggleIntelligence:P,onSetIntelligenceOpen:d},q=n.jsx(uk,{accounts:R,onMailboxSelect:ne}),Q=r?n.jsx(zb,{accounts:R}):void 0,J=r?void 0:n.jsx(Xb,{accounts:R}),te={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return n.jsxs(Im.Provider,{value:re,children:[N?n.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:n.jsx(zt,{title:"Couldn't load your account",error:C,onRetry:()=>{E()}})}):T?n.jsx(Vs,{selectedMessageId:L,children:r?n.jsx(It,{nav:q,list:n.jsx(Vs.Phone,{}),intelligenceOpen:u,overlay:Q,skeleton:n.jsx(yt,{}),isLoading:y||I,...te}):n.jsx(It,{nav:q,topBar:J,list:n.jsx(Vs.List,{}),reading:n.jsx(Vs.Reading,{}),intelligence:n.jsx(Vs.Intelligence,{}),intelligenceOpen:u,hasThread:!!L,overlay:Q,skeleton:n.jsx(yt,{}),isLoading:y||I,...te})}):$?n.jsx(Qs,{selectedMessageId:L,children:r?n.jsx(It,{nav:q,list:n.jsx(Qs.Phone,{}),intelligenceOpen:u,overlay:Q,skeleton:n.jsx(yt,{}),isLoading:y||I,...te}):n.jsx(It,{nav:q,topBar:J,list:n.jsx(Qs.List,{}),reading:n.jsx(Qs.Reading,{}),intelligence:n.jsx(Qs.Intelligence,{}),intelligenceOpen:u,hasThread:!!L,overlay:Q,skeleton:n.jsx(yt,{}),isLoading:y||I,...te})}):k?n.jsx(Gs,{mailboxId:k,selectedMessageId:L,children:r?n.jsx(It,{nav:q,list:n.jsx(Gs.Phone,{}),intelligenceOpen:u,overlay:Q,skeleton:n.jsx(yt,{}),isLoading:y||I,...te}):n.jsx(It,{nav:q,topBar:J,list:n.jsx(Gs.List,{}),reading:n.jsx(Gs.Reading,{}),intelligence:n.jsx(Gs.Intelligence,{}),intelligenceOpen:u,hasThread:!!L,overlay:Q,skeleton:n.jsx(yt,{}),isLoading:y||I,...te})}):V?n.jsx(Fn,{children:r?n.jsx(It,{nav:q,list:n.jsx(Fn.Phone,{}),intelligenceOpen:!1,overlay:Q,skeleton:n.jsx(yt,{}),isLoading:y||I,...te}):n.jsx(It,{nav:q,topBar:J,list:n.jsx(Fn.List,{}),reading:n.jsx(Fn.Reading,{}),intelligenceOpen:!1,overlay:Q,skeleton:n.jsx(yt,{}),isLoading:y||I,...te})}):n.jsx(yt,{}),n.jsx(vk,{isOpen:a,onClose:()=>o(!1)}),n.jsx(Tm,{})]})}const aC=Object.freeze(Object.defineProperty({__proto__:null,component:_k,useMailContext:ke},Symbol.toStringTag,{value:"Module"}));export{rC as S,Uh as U,aC as m};