@remit/web-client-dist 0.0.212 → 0.0.214
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.
- package/assets/{ComposeBody-mpT1bIZQ.js → ComposeBody-DkVLvIk4.js} +1 -1
- package/assets/{ConfirmDialog-CizCth1u.js → ConfirmDialog-CaWe_jPn.js} +1 -1
- package/assets/{ErrorState-l4dEQFJg.js → ErrorState-CSSSJdRP.js} +1 -1
- package/assets/{OnboardingWizard-DnI61eV7.js → OnboardingWizard-DCY75WEk.js} +1 -1
- package/assets/{account-form-helpers-ij4HJuaw.js → account-form-helpers-CS_UR5Kq.js} +1 -1
- package/assets/{accounts-BrxGxap6.js → accounts-DwXZWgF9.js} +1 -1
- package/assets/{advanced-CwOWyvZb.js → advanced-dZ8mwYDB.js} +1 -1
- package/assets/{appearance-CL0imSlO.js → appearance-Ci7wCeom.js} +1 -1
- package/assets/{avatar-CW3rY9cf.js → avatar-C04VSX82.js} +1 -1
- package/assets/{browser-ponyfill-AB6DBGZ-.js → browser-ponyfill-DkeOSn-q.js} +2 -2
- package/assets/{circle-check-D_g0KGUi.js → circle-check-DGmBT3eM.js} +1 -1
- package/assets/{download-BKhHUxFd.js → download-YtVp0sfd.js} +1 -1
- package/assets/{filters-Bl1GaURK.js → filters-CgEbRI0k.js} +1 -1
- package/assets/{flagged-DHn95EmZ.js → flagged-Ci9217W2.js} +1 -1
- package/assets/{folder-DQu-y59S.js → folder-DwlTnoXO.js} +1 -1
- package/assets/{folders-BquYwbOJ.js → folders-DQpU4a1r.js} +1 -1
- package/assets/format-CKZmh-Ru.js +1 -0
- package/assets/{index-drg-6YVA.js → index-BeLT0qtF.js} +63 -63
- package/assets/index-DKrzsjB5.js +1 -0
- package/assets/{index-CmklEekM.js → index-hbDmGk_p.js} +1 -1
- package/assets/{kbd-B5onHXik.js → kbd-7fENS2_x.js} +1 -1
- package/assets/{labels-DpcwLPY0.js → labels-BDJo08qI.js} +1 -1
- package/assets/mail-CNQ-L3D0.js +118 -0
- package/assets/{move-targets-BS_XOOwJ.js → move-targets-Dp9SdWEz.js} +1 -1
- package/assets/{onboarding-CRU6eUno.js → onboarding-DO1FH8UD.js} +1 -1
- package/assets/{senders-DVtjOxF3.js → senders-BeEFZD50.js} +1 -1
- package/assets/settings-eagCqrYO.js +1 -0
- package/assets/{settings-screen-BSyM94jc.js → settings-screen-4siZ6QzX.js} +1 -1
- package/assets/{shield-check-CbmIhOop.js → shield-check-BbW2Nqyg.js} +1 -1
- package/assets/{suggested-vips-Dl1cpFXj.js → suggested-vips-BX4Wcd3Y.js} +1 -1
- package/assets/{useDebouncedValue-D6NiRiXv.js → useDebouncedValue-CSS-iY0_.js} +1 -1
- package/assets/{useLabels-DrMULqHs.js → useLabels-CI8QGXzQ.js} +1 -1
- package/assets/{useRulePreview-BRtFT-fi.js → useRulePreview-D30ZUBNx.js} +1 -1
- package/assets/{useSignature-BEsxeqJs.js → useSignature-CfcdQ5lE.js} +1 -1
- package/index.html +1 -1
- package/package.json +1 -1
- package/assets/format-BWvUVmUm.js +0 -1
- package/assets/index-BWSbUdc3.js +0 -1
- package/assets/mail-DmVUsxbA.js +0 -118
- package/assets/settings-CVPaGBD8.js +0 -1
package/assets/mail-DmVUsxbA.js
DELETED
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-mpT1bIZQ.js","assets/index-drg-6YVA.js","assets/index-AAKtgqZz.css","assets/avatar-CW3rY9cf.js","assets/kbd-B5onHXik.js","assets/shield-check-CbmIhOop.js","assets/account-form-helpers-ij4HJuaw.js","assets/useSignature-BEsxeqJs.js","assets/useDebouncedValue-D6NiRiXv.js","assets/useRulePreview-BRtFT-fi.js","assets/ErrorState-l4dEQFJg.js","assets/format-BWvUVmUm.js","assets/move-targets-BS_XOOwJ.js","assets/useLabels-DrMULqHs.js","assets/ConfirmDialog-CizCth1u.js","assets/circle-check-D_g0KGUi.js","assets/folder-DQu-y59S.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{R as q,c as bf,r as c,a as we,j as r,C as Ut,X as vt,b as Y,B as oe,d as gt,S as Ht,e as Nt,f as cs,L as Os,g as Ma,h as vf,i as yf,k as on,A as Aa,T as Et,F as Oa,P as wf,l as ln,u as Jn,m as Da,n as Sf,I as Il,p as Tl,o as Pa,q as kf,D as Cf,s as cn,t as Zn,O as jf,M as Nf,v as Ef,w as Rl,x as If,y as Tf,z as Rf,E as Mf,G as Af,H as Ml,J as La,K as Of,N as Al,Q as Df,U as Pf,V as Fa,W as $a,_ as _t,Y as Ol,Z as Lf,$ as _a,a0 as Ff,a1 as $f,a2 as _f,a3 as ua,a4 as zf,a5 as Bf,a6 as Ee,a7 as Kf,a8 as Uf,a9 as qf,aa as Hf,ab as Wf,ac as Vf,ad as Ko,ae as Qf,af as Gf,ag as Yf,ah as za,ai as Dl,aj as Pl,ak as Wt,al as He,am as ot,an as un,ao as Le,ap as Ba,aq as Ka,ar as Ua,as as qa,at as er,au as Ts,av as Ie,aw as dn,ax as xe,ay as Ll,az as Xf,aA as Oe,aB as Fl,aC as Jf,aD as tr,aE as sr,aF as $l,aG as _l,aH as Zf,aI as It,aJ as it,aK as em,aL as ft,aM as zl,aN as as,aO as nr,aP as tm,aQ as rr,aR as Ha,aS as Wa,aT as us,aU as ar,aV as ds,aW as sm,aX as nm,aY as Bn,aZ as rm,a_ as Bl,a$ as Rs,b0 as am,b1 as or,b2 as om,b3 as im,b4 as lm,b5 as Kl,b6 as Va,b7 as cm,b8 as Uo,b9 as um,ba as dm,bb as Ds,bc as Qa,bd as Ct,be as Ul,bf as fm,bg as mm,bh as hm,bi as pm,bj as gm,bk as xm,bl as bm,bm as qo,bn as vm,bo as ym,bp as wm,bq as Sm,br as da,bs as fa,bt as km,bu as Cm,bv as ql,bw as jm,bx as Ga,by as Nm,bz as Em,bA as Im,bB as Tm,bC as Rm,bD as Mm,bE as Am,bF as Om,bG as Dm,bH as Pm,bI as Lm,bJ as Lt,bK as kt,bL as Fm}from"./index-drg-6YVA.js";import{A as bt,M as Ya,C as $m}from"./avatar-CW3rY9cf.js";import{K as js}from"./kbd-B5onHXik.js";import{S as fn,C as Xa,R as _m}from"./shield-check-CbmIhOop.js";import{M as Hl,a as zm}from"./account-form-helpers-ij4HJuaw.js";import{R as Bm,u as Km}from"./useSignature-BEsxeqJs.js";import{u as ir}from"./useDebouncedValue-D6NiRiXv.js";import{B as Um,u as Vt,a as Ho,b as Wo,c as qm,d as Hm,e as Wm,n as Vm,o as Qm,f as Gm,g as Ym,S as Xm}from"./useRulePreview-BRtFT-fi.js";import{E as Qt,f as Wl}from"./ErrorState-l4dEQFJg.js";import{f as Vl,a as yt,b as Ql,c as xt,d as Kn,t as Jm}from"./format-BWvUVmUm.js";import{P as Vo,u as Gl,b as Ja,M as at}from"./move-targets-BS_XOOwJ.js";import{u as Za}from"./useLabels-DrMULqHs.js";import{C as eo}from"./ConfirmDialog-CizCth1u.js";import{C as Zm}from"./circle-check-D_g0KGUi.js";import{F as eh}from"./folder-DQu-y59S.js";function en(e){if(th())e.focus({preventScroll:!0});else{let t=sh(e);e.focus(),nh(t)}}let kn=null;function th(){if(kn==null){kn=!1;try{document.createElement("div").focus({get preventScroll(){return kn=!0,!0}})}catch{}}return kn}function sh(e){let t=e.parentNode,s=[],n=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==n;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return n instanceof HTMLElement&&s.push({element:n,scrollTop:n.scrollTop,scrollLeft:n.scrollLeft}),s}function nh(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const Bt=e=>e?.ownerDocument??document,qt=e=>e&&"window"in e&&e.window===e?e:Bt(e).defaultView||window;function rh(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function ah(e){return rh(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let oh=!1;function Yl(){return oh}function pt(e,t){if(!Yl())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:ah(s)?s=s.host:s=s.parentNode}return!1}function Ke(e){if(Yl()&&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 ih=typeof Element<"u"&&"checkVisibility"in Element.prototype;function lh(e){const t=qt(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:n}=e.style,a=s!=="none"&&n!=="hidden"&&n!=="collapse";if(a){const{getComputedStyle:o}=qt(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function ch(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 Xl(e,t){return ih?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&lh(e)&&ch(e,t)&&(!e.parentElement||Xl(e.parentElement,e))}const Jl=["input:not([disabled]):not([type=hidden])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable^="false"])',"permission"],uh=Jl.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";Jl.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function dh(e,t){return e.matches(uh)&&!fh(e)&&(t?.skipVisibilityCheck||Xl(e))}function fh(e){let t=e;for(;t!=null;){if(t instanceof qt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const to=typeof document<"u"?q.useLayoutEffect:()=>{};function mh(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function hh(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function ph(e){for(;e&&!dh(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=qt(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=d=>{(Ke(d)===s||n)&&d.stopImmediatePropagation()},o=d=>{(Ke(d)===s||n)&&(d.stopImmediatePropagation(),!e&&!n&&(n=!0,en(s),u()))},i=d=>{(Ke(d)===e||n)&&d.stopImmediatePropagation()},l=d=>{(Ke(d)===e||n)&&(d.stopImmediatePropagation(),n||(n=!0,en(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function lr(e){if(typeof window>"u"||window.navigator==null)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(s=>e.test(s.brand))||e.test(window.navigator.userAgent)}function so(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function Gt(e){let t=null;return()=>(t==null&&(t=e()),t)}const Un=Gt(function(){return so(/^Mac/i)}),gh=Gt(function(){return so(/^iPhone/i)}),Zl=Gt(function(){return so(/^iPad/i)||Un()&&navigator.maxTouchPoints>1}),ec=Gt(function(){return gh()||Zl()}),xh=Gt(function(){return lr(/AppleWebKit/i)&&!bh()}),bh=Gt(function(){return lr(/Chrome/i)}),tc=Gt(function(){return lr(/Android/i)}),vh=Gt(function(){return lr(/Firefox/i)});function yh(e){return e.pointerType===""&&e.isTrusted?!0:tc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function wh(e){return!tc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function tn(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;vh()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Un()?n=!0:a=!0);let l=xh()&&Un()&&!Zl()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});tn.isOpening=s,en(e),e.dispatchEvent(l),tn.isOpening=!1}tn.isOpening=!1;let zt=new Map,ma=new Set;function Qo(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=Ke(n);if(!e(n)||!a)return;let o=zt.get(a);o||(o=new Set,zt.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=Ke(n);if(!e(n)||!a)return;let o=zt.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),zt.delete(a)),zt.size===0)){for(let i of ma)i();ma.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?Qo():document.addEventListener("DOMContentLoaded",Qo));function Sh(){for(const[e]of zt)"isConnected"in e&&!e.isConnected&&zt.delete(e)}function kh(e){requestAnimationFrame(()=>{Sh(),zt.size===0?e():ma.add(e)})}function sc(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let ha=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{ha.delete(e)});function Ch(e,t){if(e===t)return e;let s=ha.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=ha.get(t);return n?(n.forEach(a=>a.current=e),e):t}function jh(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=Go(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():Go(e[o],null)})}}}function Go(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ps(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let n=e[s];for(let a in n){let o=t[a],i=n[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=sc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=bf(o,i):a==="id"&&o&&i?t.id=Ch(o,i):a==="ref"&&o&&i?t.ref=jh(o,i):t[a]=i!==void 0?i:o}}return t}function Nh(e,t){to(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const Eh=q.useInsertionEffect??to;function _r(e){const t=c.useRef(null);return Eh(()=>{t.current=e},[e]),c.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let ks="default",pa="",Ln=new WeakMap;function Ih(e){if(ec()){if(ks==="default"){const t=Bt(e);pa=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}ks="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Ln.set(e,e.style[t]),e.style[t]="none"}}function Yo(e){if(ec()){if(ks!=="disabled")return;ks="restoring",setTimeout(()=>{kh(()=>{if(ks==="restoring"){const t=Bt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=pa||""),pa="",ks="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Ln.has(e)){let t=Ln.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Ln.delete(e)}}function Xo(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let zr=new WeakMap;function Th(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return Xo(t);if(zr.has(t))return zr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof qt(s).HTMLMetaElement&&(s.nonce||s.content)||Xo(t)||void 0;return n!==void 0&&zr.set(t,n),n}const nc=q.createContext({register:()=>{}});nc.displayName="PressResponderContext";function rc(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),n=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function Rh(e){let t=c.useContext(nc);if(t){let{register:s,ref:n,...a}=t;e=Ps(a,e),s()}return Nh(t,e.ref),e}class Cn{#s;constructor(t,s,n,a){this.#s=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let l,u=0,m,d=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,d=n.clientY),i&&(m!=null&&d!=null?(l=m-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=n.currentTarget,this.shiftKey=n.shiftKey,this.metaKey=n.metaKey,this.ctrlKey=n.ctrlKey,this.altKey=n.altKey,this.x=l,this.y=u,this.key=n.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const Jo=Symbol("linkClicked"),Zo="react-aria-pressable-style",ei="data-react-aria-pressable";function Mh(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:f,ref:h,...g}=Rh(e),[y,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:x,removeAllGlobalListeners:S}=rc(),w=c.useCallback((k,P)=>{let F=b.current;if(l||F.didFirePressStart)return!1;let j=!0;if(F.isTriggeringEvent=!0,n){let R=new Cn("pressstart",P,k);n(R),j=R.shouldStopPropagation}return s&&s(!0),F.isTriggeringEvent=!1,F.didFirePressStart=!0,p(!0),j},[l,n,s]),v=c.useCallback((k,P,F=!0)=>{let j=b.current;if(!j.didFirePressStart)return!1;j.didFirePressStart=!1,j.isTriggeringEvent=!0;let R=!0;if(a){let T=new Cn("pressend",P,k);a(T),R=T.shouldStopPropagation}if(s&&s(!1),p(!1),t&&F&&!l){let T=new Cn("press",P,k);t(T),R&&=T.shouldStopPropagation}return j.isTriggeringEvent=!1,R},[l,a,s,t]),C=_r(v),E=c.useCallback((k,P)=>{let F=b.current;if(l)return!1;if(o){F.isTriggeringEvent=!0;let j=new Cn("pressup",P,k);return o(j),F.isTriggeringEvent=!1,j.shouldStopPropagation}return!0},[l,o]),I=_r(E),N=c.useCallback(k=>{let P=b.current;if(P.isPressed&&P.target){P.didFirePressStart&&P.pointerType!=null&&v(ts(P.target,k),P.pointerType,!1),P.isPressed=!1,P.isOverTarget=!1,P.activePointerId=null,P.pointerType=null,S(),f||Yo(P.target);for(let F of P.disposables)F();P.disposables=[]}},[f,S,v]),D=_r(N);c.useEffect(()=>{l&&b.current.isPressed&&D({currentTarget:b.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let A=c.useCallback(k=>{d&&N(k)},[d,N]),O=c.useCallback(k=>{l||i?.(k)},[l,i]),L=c.useCallback((k,P)=>{if(!l&&i){let F=new MouseEvent("click",k);hh(F,P),i(mh(F))}},[l,i]),M=c.useMemo(()=>{let k=b.current,P={onKeyDown(j){if(Br(j.nativeEvent,j.currentTarget)&&pt(j.currentTarget,Ke(j))){ti(Ke(j),j.key)&&j.preventDefault();let R=!0;!k.isPressed&&!j.repeat&&(k.target=j.currentTarget,k.isPressed=!0,k.pointerType="keyboard",R=w(j,"keyboard"));let T=j.currentTarget,V=Z=>{Br(Z,T)&&!Z.repeat&&pt(T,Ke(Z))&&k.target&&I(ts(k.target,Z),"keyboard")};x(Bt(j.currentTarget),"keyup",sc(V,F),!0),R&&j.stopPropagation(),j.metaKey&&Un()&&k.metaKeyEvents?.set(j.key,j.nativeEvent)}else j.key==="Meta"&&(k.metaKeyEvents=new Map)},onClick(j){if(!(j&&!pt(j.currentTarget,Ke(j)))&&j&&j.button===0&&!k.isTriggeringEvent&&!tn.isOpening){let R=!0;if(l&&j.preventDefault(),!k.ignoreEmulatedMouseEvents&&!k.isPressed&&(k.pointerType==="virtual"||yh(j.nativeEvent))){let T=w(j,"virtual"),V=I(j,"virtual"),Z=C(j,"virtual");O(j),R=T&&V&&Z}else if(k.isPressed&&k.pointerType!=="keyboard"){let T=k.pointerType||j.nativeEvent.pointerType||"virtual",V=I(ts(j.currentTarget,j),T),Z=C(ts(j.currentTarget,j),T,!0);R=V&&Z,k.isOverTarget=!1,O(j),D(j)}k.ignoreEmulatedMouseEvents=!1,R&&j.stopPropagation()}}},F=j=>{if(k.isPressed&&k.target&&Br(j,k.target)){ti(Ke(j),j.key)&&j.preventDefault();let R=Ke(j),T=pt(k.target,R);C(ts(k.target,j),"keyboard",T),T&&L(j,k.target),S(),j.key!=="Enter"&&no(k.target)&&pt(k.target,R)&&!j[Jo]&&(j[Jo]=!0,tn(k.target,j,!1)),k.isPressed=!1,k.metaKeyEvents?.delete(j.key)}else if(j.key==="Meta"&&k.metaKeyEvents?.size){let R=k.metaKeyEvents;k.metaKeyEvents=void 0;for(let T of R.values())k.target?.dispatchEvent(new KeyboardEvent("keyup",T))}};if(typeof PointerEvent<"u"){P.onPointerDown=T=>{if(T.button!==0||!pt(T.currentTarget,Ke(T)))return;if(wh(T.nativeEvent)){k.pointerType="virtual";return}k.pointerType=T.pointerType;let V=!0;if(!k.isPressed){k.isPressed=!0,k.isOverTarget=!0,k.activePointerId=T.pointerId,k.target=T.currentTarget,f||Ih(k.target),V=w(T,k.pointerType);let Z=Ke(T);"releasePointerCapture"in Z&&("hasPointerCapture"in Z?Z.hasPointerCapture(T.pointerId)&&Z.releasePointerCapture(T.pointerId):Z.releasePointerCapture(T.pointerId)),x(Bt(T.currentTarget),"pointerup",j,!1),x(Bt(T.currentTarget),"pointercancel",R,!1)}V&&T.stopPropagation()},P.onMouseDown=T=>{if(pt(T.currentTarget,Ke(T))&&T.button===0){if(m){let V=ph(T.target);V&&k.disposables.push(V)}T.stopPropagation()}},P.onPointerUp=T=>{!pt(T.currentTarget,Ke(T))||k.pointerType==="virtual"||T.button===0&&!k.isPressed&&I(T,k.pointerType||T.pointerType)},P.onPointerEnter=T=>{T.pointerId===k.activePointerId&&k.target&&!k.isOverTarget&&k.pointerType!=null&&(k.isOverTarget=!0,w(ts(k.target,T),k.pointerType))},P.onPointerLeave=T=>{T.pointerId===k.activePointerId&&k.target&&k.isOverTarget&&k.pointerType!=null&&(k.isOverTarget=!1,C(ts(k.target,T),k.pointerType,!1),A(T))};let j=T=>{if(T.pointerId===k.activePointerId&&k.isPressed&&T.button===0&&k.target){if(pt(k.target,Ke(T))&&k.pointerType!=null){let V=!1,Z=setTimeout(()=>{k.isPressed&&k.target instanceof HTMLElement&&(V?D(T):(en(k.target),k.target.click()))},80);x(T.currentTarget,"click",()=>V=!0,!0),k.disposables.push(()=>clearTimeout(Z))}else D(T);k.isOverTarget=!1}},R=T=>{D(T)};P.onDragStart=T=>{pt(T.currentTarget,Ke(T))&&D(T)}}return P},[x,l,m,S,f,A,w,O,L]);return c.useEffect(()=>{if(!h)return;const k=Bt(h.current);if(!k||!k.head||k.getElementById(Zo))return;const P=k.createElement("style");P.id=Zo;let F=Th(k);F&&(P.nonce=F),P.textContent=`
|
|
3
|
-
@layer {
|
|
4
|
-
[${ei}] {
|
|
5
|
-
touch-action: pan-x pan-y pinch-zoom;
|
|
6
|
-
}
|
|
7
|
-
}
|
|
8
|
-
`.trim(),k.head.prepend(P)},[h]),c.useEffect(()=>{let k=b.current;return()=>{f||Yo(k.target??void 0);for(let P of k.disposables)P();k.disposables=[]}},[f]),{isPressed:u||y,pressProps:Ps(g,M,{[ei]:!0})}}function no(e){return e.tagName==="A"&&e.hasAttribute("href")}function Br(e,t){const{key:s,code:n}=e,a=t,o=a.getAttribute("role");return(s==="Enter"||s===" "||s==="Spacebar"||n==="Space")&&!(a instanceof qt(a).HTMLInputElement&&!ac(a,s)||a instanceof qt(a).HTMLTextAreaElement||a.isContentEditable)&&!((o==="link"||!o&&no(a))&&s!=="Enter")}function ts(e,t){let s=t.clientX,n=t.clientY;return{currentTarget:e,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,altKey:t.altKey,clientX:s,clientY:n,key:t.key}}function Ah(e){return e instanceof HTMLInputElement?!1:e instanceof HTMLButtonElement?e.type!=="submit"&&e.type!=="reset":!no(e)}function ti(e,t){return e instanceof HTMLInputElement?!ac(e,t):Ah(e)}const Oh=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function ac(e,t){return e.type==="checkbox"||e.type==="radio"?t===" ":Oh.has(e.type)}let Dh=0;const Kr=new Map;function Ph(e){let[t,s]=c.useState();return to(()=>{if(!e)return;let n=Kr.get(e);if(n)s(n.element.id);else{let a=`react-aria-description-${Dh++}`;s(a);let o=document.createElement("div");o.id=a,o.style.display="none",o.textContent=e,document.body.appendChild(o),n={refCount:0,element:o},Kr.set(e,n)}return n.refCount++,()=>{n&&--n.refCount===0&&(n.element.remove(),Kr.delete(e))}},[e]),{"aria-describedby":e?t:void 0}}const Lh=500;function Fh(e){let{isDisabled:t,onLongPressStart:s,onLongPressEnd:n,onLongPress:a,threshold:o=Lh,accessibilityDescription:i}=e;const l=c.useRef(void 0);let{addGlobalListener:u,removeGlobalListener:m}=rc(),{pressProps:d}=Mh({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})),Bt(h.target).activeElement!==h.target&&en(h.target),a&&a({...h,type:"longpress"}),l.current=void 0},o),h.pointerType==="touch")){let g=p=>{p.preventDefault()},y=qt(h.target);u(h.target,"contextmenu",g,{once:!0}),u(y,"pointerup",()=>{setTimeout(()=>{m(h.target,"contextmenu",g)},30)},{once:!0})}},onPressEnd(h){l.current&&clearTimeout(l.current),n&&(h.pointerType==="mouse"||h.pointerType==="touch")&&n({...h,type:"longpressend"})}}),f=Ph(a&&!t?i:void 0);return{longPressProps:Ps(d,f)}}const cr=we("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 $h=we("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);const oc=we("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 _h=we("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=we("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 Ms=we("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const ic=we("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 lc=we("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);const cc=we("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 uc=we("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 dc=we("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 zh=we("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);const ur=we("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 Bh=we("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 Kh=we("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const dr=we("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 Uh=we("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 fc=we("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 mc=we("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 hc=we("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 ro=we("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const Ls=we("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 qh=we("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 Hh=we("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 Wh=we("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 Vh=we("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?r.jsx(cr,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}):null;return e.displayName?r.jsxs("span",{children:[r.jsx("span",{className:"text-fg",children:e.displayName}),r.jsxs("span",{className:"text-fg-muted",children:[" ","<",e.normalizedEmail,">"]}),s]}):r.jsxs("span",{className:"text-fg",children:[e.normalizedEmail,s]})},Gh=({label:e,addresses:t,showTrustedBadge:s=!1})=>{const[n,a]=c.useState(!1);if(t.length===0)return null;const o=t.length>3,i=l=>{const u=s&&l.flags?.trusted?.value===!0;return r.jsx(Qh,{address:l,showTrustedBadge:u})};return r.jsxs("div",{className:"flex gap-2 text-sm",children:[r.jsxs("span",{className:"text-fg-muted shrink-0 w-12",children:[e,":"]}),r.jsx("div",{className:"flex-1 min-w-0",children:n?r.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((l,u)=>r.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))}):r.jsx("div",{className:"truncate",children:t.map((l,u)=>r.jsxs("span",{children:[i(l),u<t.length-1&&", "]},u))})}),o&&r.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),a(!n)},className:"shrink-0 text-fg-muted hover:text-fg transition-colors","aria-label":n?"Collapse":"Expand",children:n?r.jsx(Ut,{className:"h-4 w-4"}):r.jsx(Ms,{className:"h-4 w-4"})})]})},Yh=({email:e,displayName:t,onRemove:s,className:n})=>r.jsxs("span",{className:Y("inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-accent-2-soft text-sm max-w-[200px]",n),children:[r.jsx("span",{className:"truncate",children:t||e}),r.jsx("button",{type:"button",onClick:s,className:"shrink-0 p-0.5 rounded-full hover:bg-fg-muted/20 transition-colors","aria-label":`Remove ${e}`,children:r.jsx(vt,{className:"size-3"})})]}),Xh={unknown:{label:"Unknown sender",tone:"neutral"},wellknown:{label:"Known sender",tone:"positive"},vip:{label:"VIP",tone:"accent"}};function ps({label:e,children:t,className:s}){return r.jsxs("section",{className:Y("border-b border-line px-row-inset py-3",s),children:[r.jsx("h3",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),r.jsx("div",{className:"mt-2",children:t})]})}function Jh({sender:e}){const t=Xh[e.trust],s=e.inboundCount==null?null:(e.replyCount??0)>0?`${e.inboundCount} received · you replied ${e.replyCount}×`:`${e.inboundCount} received · you've never replied`;return r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(bt,{name:e.name,email:e.email,size:"md"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"truncate text-sm font-semibold text-fg",children:e.name}),r.jsx("div",{className:"truncate text-2xs text-fg-subtle",children:e.email})]})]}),r.jsx("div",{className:"mt-2 flex items-center gap-2",children:e.addressUnverified?r.jsx(gt,{tone:"danger",dot:!0,children:"Address couldn't be verified"}):r.jsx(gt,{tone:t.tone,dot:!0,children:t.label})}),r.jsxs("p",{className:"mt-2 text-xs text-fg-muted",children:["First seen ",e.firstSeenLabel,s?` · ${s}`:""]})]})}function Zh({auth:e,onShowSimilar:t}){if(e.verdict==="aligned")return r.jsxs("div",{className:"flex items-start gap-2 text-xs text-fg-muted",children:[r.jsx(fn,{className:"mt-0.5 size-3.5 shrink-0 text-positive"}),r.jsx("span",{children:e.summary})]});if(e.verdict==="caution")return r.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-warning/10 p-3 text-warning",children:[r.jsx(qh,{className:"mt-0.5 size-4 shrink-0"}),r.jsx("p",{className:"text-xs leading-relaxed",children:e.summary})]});const s=e.addressUnreadable?"This sender can't be verified":"This message may be impersonating someone";return r.jsxs("div",{className:"rounded-md bg-danger-soft p-3",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(Ls,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm font-semibold text-danger",children:s}),r.jsx("p",{className:"mt-1 text-xs leading-relaxed text-fg",children:e.summary}),!e.addressUnreadable&&e.dkimDomain&&r.jsxs("p",{className:"mt-1 text-2xs text-fg-muted",children:["Sent from"," ",r.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.dkimDomain}),", claims to be"," ",r.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.fromDomain})]})]})]}),e.similarCount!=null&&e.similarCount>0&&r.jsxs(oe,{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 gs({icon:e,label:t,active:s,danger:n,onClick:a}){const o=a===void 0;return r.jsxs("button",{type:"button",onClick:a,disabled:o,className:Y("flex items-center gap-2 rounded-md border px-2 py-1 text-xs transition-colors",s?"border-accent-2 bg-accent-2-soft text-accent-2":"border-line text-fg-muted hover:border-line-strong hover:text-fg",n&&!s&&"text-danger hover:bg-danger-soft",o&&"cursor-not-allowed opacity-50 hover:border-line"),children:[e,t]})}const ep={sender:"matched: sender",recipient:"matched: recipient",subject:"matched: subject",attachment:"matched: attachment",body:"matched: body",entities:"matched: entities"};function pc({data:e,onClose:t,onShowSimilar:s,actions:n,similarState:a="ready",similarLinkComponent:o,className:i,hideCloseButton:l=!1}){const{sender:u,authenticity:m,category:d,flags:f={},similar:h}=e,g=m.verdict==="mismatch";return r.jsxs("aside",{className:Y("flex w-76 shrink-0 flex-col overflow-y-auto border-l border-line bg-surface",i),children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center justify-between border-b border-line px-row-inset",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"}),!l&&r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(vt,{className:"size-3.5"}),onClick:t,"aria-label":"Collapse intelligence sidebar"})]}),r.jsx(ps,{label:"Sender",children:r.jsx(Jh,{sender:u})}),r.jsx(ps,{label:"Authenticity",children:r.jsx(Zh,{auth:m,onShowSimilar:s})}),r.jsx(ps,{label:"Category",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(gt,{tone:g?"danger":"neutral",children:d.value}),d.overridden&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"your override"}),r.jsx("button",{type:"button",className:Y("ml-auto text-2xs text-accent hover:underline",!n?.onReclassify&&"cursor-not-allowed opacity-50 hover:no-underline"),disabled:!n?.onReclassify,onClick:n?.onReclassify,children:"reclassify"})]})}),r.jsx(ps,{label:"Quick actions",children:r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[r.jsx(gs,{icon:r.jsx(Ht,{className:"size-3.5"}),label:"VIP",active:f.vip,onClick:n?.onToggleVip}),r.jsx(gs,{icon:r.jsx(oc,{className:"size-3.5"}),label:"Mute",active:f.muted,onClick:n?.onToggleMute}),r.jsx(gs,{icon:r.jsx($h,{className:"size-3.5"}),label:"Block",active:f.blocked,danger:!0,onClick:n?.onToggleBlock}),r.jsx(gs,{icon:r.jsx(Bh,{className:"size-3.5"}),label:"Unsubscribe",active:f.unsubscribed,onClick:n?.onToggleUnsubscribe}),n?.onNotSpam&&r.jsx(gs,{icon:r.jsx(zh,{className:"size-3.5"}),label:"Not spam",onClick:n.onNotSpam}),n?.onMarkSpam&&r.jsx(gs,{icon:r.jsx(Hh,{className:"size-3.5"}),label:"Mark spam",danger:!0,onClick:n.onMarkSpam})]})}),(a!=="ready"||h.length>0)&&r.jsx(ps,{label:"Similar messages",children:a==="loading"?r.jsx("div",{className:"animate-pulse space-y-2",children:Array.from({length:3}).map((y,p)=>r.jsxs("div",{className:"space-y-1",children:[r.jsx("div",{className:"h-3 w-3/4 rounded bg-surface-sunken"}),r.jsx("div",{className:"h-2.5 w-1/2 rounded bg-surface-sunken"})]},p))}):a==="error"?r.jsx("p",{className:"text-xs text-fg-subtle",children:"Similarity search unavailable"}):r.jsx("ul",{className:"-mx-1 space-y-1",children:h.map(y=>{const p="block w-full rounded-md px-1 py-1 text-left hover:bg-surface-sunken",b=`Open message from ${y.fromName||"unknown sender"}: ${y.subject}`,x=r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[r.jsx("span",{className:"truncate text-xs font-medium text-fg",children:y.fromName}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:y.timeLabel})]}),r.jsx("div",{className:"truncate text-xs text-fg-muted",children:y.subject}),r.jsx("span",{className:"mt-1 inline-block rounded-full bg-surface-sunken px-1.5 py-px text-2xs text-fg-subtle",children:ep[y.matched]})]});return r.jsx("li",{children:o?o({mailboxId:y.mailboxId,messageId:y.id,className:p,ariaLabel:b,children:x}):r.jsx("div",{className:p,children:x})},y.id)})})}),r.jsx(ps,{label:"Coming soon",className:"border-b-0 opacity-70",children:r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[r.jsx(Nt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Suggested actions"}),r.jsx("div",{className:"text-2xs text-fg-subtle",children:'"Create a filter for messages like this" — on-device model'})]})]}),r.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[r.jsx(Nt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Thread summary"}),r.jsx("div",{className:"text-2xs text-fg-subtle",children:"One-paragraph digest — Bedrock"})]})]})]})})]})}const tp=[{keys:["j","k"],label:"navigate"},{keys:["m"],label:"mute"},{keys:["?"],label:"all shortcuts"}];function gc({hints:e=tp,className:t}){return r.jsx("footer",{className:Y("flex items-center gap-2 border-t border-line px-row-inset py-1 text-2xs text-fg-subtle",t),children:e.map(s=>r.jsx(sp,{hint:s},s.label))})}function sp({hint:e}){return r.jsxs("span",{className:"flex items-center gap-1",children:[e.keys.map(t=>r.jsx(js,{children:t},t)),r.jsx("span",{children:e.label})]})}function np(){return r.jsx("div",{className:"space-y-0",role:"status","aria-busy":"true","aria-label":"Loading messages",children:Array.from({length:8}).map((e,t)=>r.jsxs("div",{className:"animate-pulse border-b border-line px-3 py-2",children:[r.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[r.jsx("div",{className:"h-4 w-32 rounded bg-surface-sunken"}),r.jsx("div",{className:"h-3 w-16 rounded bg-surface-sunken"})]}),r.jsx("div",{className:"mb-2 h-4 w-48 rounded bg-surface-sunken"}),r.jsx("div",{className:"h-3 w-full rounded bg-surface-sunken"})]},t))})}function rp({filter:e,scopeLabel:t,searchQuery:s}){const n=s?.trim();return e?r.jsxs(ni,{children:[r.jsx("p",{className:"font-medium text-fg",children:ip(e.label,t,n)}),r.jsx("p",{className:"mt-1 text-sm text-fg-muted",children:ap[e.reach]}),r.jsx(oe,{variant:"secondary",size:"sm",className:"mt-4",onClick:e.onClear,children:"Clear filter"})]}):r.jsx(ni,{children:r.jsx("p",{className:"text-fg-muted",children:op(n,t)})})}const ap={"whole-folder":"Every message in this folder was checked.","loaded-pages":"Only the messages loaded so far were checked."};function op(e,t){return e?"No messages match your search":t?`No messages in ${t}`:"No messages in this mailbox"}function ip(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 r.jsx("div",{className:"flex h-full flex-1 items-center justify-center",children:r.jsx("div",{className:"flex max-w-sm flex-col items-center justify-center p-8 text-center",children:e})})}function lp(){return r.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-sm text-fg-muted",role:"status","aria-live":"polite",children:[r.jsx(Os,{className:"size-4 animate-spin","aria-hidden":"true"}),r.jsx("span",{children:"Loading more…"})]})}function cp({message:e="Something went wrong loading this mailbox.",onRetry:t,onReport:s}){return r.jsx("div",{className:"flex h-full flex-1 items-center justify-center p-4",children:r.jsxs("div",{role:"alert",className:"flex max-w-sm flex-col items-center justify-center gap-3 text-center",children:[r.jsx(cs,{className:"size-8 text-danger","aria-hidden":"true"}),r.jsxs("div",{children:[r.jsx("p",{className:"font-medium text-danger",children:"Couldn't load messages"}),r.jsx("p",{className:"mt-1 break-words text-sm text-fg-muted",children:e})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t&&r.jsx(oe,{variant:"secondary",size:"sm",onClick:t,children:"Retry"}),s&&r.jsx(oe,{variant:"ghost",size:"sm",onClick:s,children:"Report a problem"})]})]})})}const xc="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",bc=({active:e,focused:t})=>Y("relative flex h-8 w-full items-center gap-2 px-row-inset text-left",xc,e?"bg-accent-2-soft":t?"bg-surface-sunken":"hover:bg-surface-sunken",t&&!e&&"before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-accent-2"),Fs=({active:e,focused:t})=>Y("relative flex w-full items-start gap-3 py-2 pl-5 pr-row-inset text-left transition-colors",xc,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 vc({thread:e}){const t=!e.isRead;return r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"flex w-4 shrink-0 items-center justify-center",children:e.suspicious?r.jsx(Ls,{className:"size-3.5 text-danger"}):e.starred?r.jsx(Ht,{className:"size-3 fill-warning text-warning"}):t?r.jsx("span",{className:"size-1.5 rounded-full bg-accent"}):null}),r.jsx("span",{className:Y("w-36 shrink-0 truncate text-xs",t?"font-semibold text-fg":"text-fg-muted"),children:e.fromName}),r.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs",children:[r.jsx("span",{className:Y(t?"font-medium text-fg":"text-fg-muted"),children:e.subject}),r.jsxs("span",{className:"text-fg-subtle",children:[" — ",e.snippet]})]}),e.hasAttachment&&r.jsx(dr,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"w-11 shrink-0 text-right text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]})}function ri(e,t){const s=t?.trim();if(!s)return e;const n=e.toLowerCase(),a=s.toLowerCase(),o=[];let i=0,l=n.indexOf(a,i),u=0;for(;l!==-1;)l>i&&o.push(e.slice(i,l)),o.push(r.jsx("mark",{className:"bg-transparent font-semibold text-fg",children:e.slice(l,l+a.length)},u++)),i=l+a.length,l=n.indexOf(a,i);return i<e.length&&o.push(e.slice(i)),o}function sn({thread:e,badge:t,highlightQuery:s}){const n=!e.isRead;return r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsxs("span",{className:"flex items-baseline justify-between gap-2",children:[r.jsxs("span",{className:Y("flex min-w-0 items-center gap-1.5 truncate text-sm",n?"font-semibold text-fg":"font-medium text-fg-muted"),children:[e.trust==="vip"&&r.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-accent-2"}),r.jsx("span",{className:"truncate",children:e.fromName}),e.messageCount!=null&&e.messageCount>1&&r.jsx("span",{className:"shrink-0 text-2xs font-normal text-fg-subtle",children:e.messageCount})]}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:Y("truncate text-sm",n?"text-fg":"text-fg-muted"),children:ri(e.subject,s)}),e.suspicious&&r.jsx(Ls,{className:"size-3.5 shrink-0 text-danger"}),e.starred&&r.jsx(Ht,{className:"size-3 shrink-0 fill-warning text-warning"}),e.hasAttachment&&r.jsx(dr,{className:"size-3 shrink-0 text-fg-subtle"})]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"line-clamp-1 min-w-0 flex-1 text-xs text-fg-subtle",children:ri(e.snippet,s)}),e.category&&e.category!=="personal"&&r.jsx(gt,{tone:vf[e.category],className:"shrink-0",children:e.category}),e.labels?.map(a=>r.jsx(yf,{label:a,className:"max-w-20"},a.labelId)),t]})]})}function up({thread:e,selection:t}){if(!t)return r.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"sm"});const{checked:s,alwaysVisible:n}=t;return r.jsxs("span",{className:"relative size-7 shrink-0",children:[r.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"sm",className:Y("absolute inset-0 transition-opacity sm:group-hover:opacity-0",(s||n)&&"opacity-0")}),r.jsx("span",{role:"button",tabIndex:-1,onClick:t.onToggle,onKeyDown:a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),a.stopPropagation(),t.onToggle(a))},className:Y("absolute inset-0 size-7 items-center justify-center rounded-full border transition-opacity",n?"flex":"hidden sm:flex",s?"bg-accent border-accent text-accent-fg opacity-100":n?"border-fg-subtle/40 bg-canvas opacity-100":"border-fg-subtle/40 bg-canvas opacity-0 group-hover:opacity-100"),"aria-label":s?"Deselect message":"Select message",children:s&&r.jsx(on,{className:"size-3"})})]})}function ao({thread:e,selection:t,badge:s,highlightQuery:n}){const a=!e.isRead;return r.jsxs(r.Fragment,{children:[a&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx(up,{thread:e,selection:t}),r.jsx(sn,{thread:e,badge:s,highlightQuery:n})]})}function dp({thread:e,active:t,focused:s,onClick:n}){return r.jsx("button",{type:"button",...Ma,onClick:n,className:bc({active:t,focused:s}),children:r.jsx(vc,{thread:e})})}function fp({thread:e,active:t,focused:s,selection:n,onClick:a}){return r.jsx("button",{type:"button",...Ma,onClick:a,className:Y("group",Fs({active:t,focused:s})),children:r.jsx(ao,{thread:e,selection:n})})}const mp="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 oo({label:e,description:t,indeterminate:s=!1,checked:n,onChange:a,className:o,...i}){const l=c.useRef(null);c.useEffect(()=>{l.current&&(l.current.indeterminate=s)},[s]);const u=r.jsxs("span",{className:"relative inline-flex",children:[r.jsx("input",{ref:l,type:"checkbox",checked:n,onChange:a,className:mp,...i}),r.jsx(on,{className:Y(ai,"hidden peer-checked:block"),"aria-hidden":!0}),r.jsx(Kh,{className:Y(ai,"hidden peer-indeterminate:block"),"aria-hidden":!0})]});return e===void 0&&t===void 0?r.jsx("span",{className:o,children:u}):r.jsxs("label",{className:Y("flex min-h-11 cursor-pointer items-center gap-3 text-left",o),children:[u,r.jsxs("span",{className:"flex min-w-0 flex-col",children:[e!==void 0&&r.jsx("span",{className:"text-sm text-fg",children:e}),t!==void 0&&r.jsx("span",{className:"text-xs text-fg-subtle",children:t})]})]})}function io({triggerLabel:e,triggerIcon:t,triggerText:s,items:n,align:a="end",touch:o=!0,className:i,triggerClassName:l,nested:u=!1,children:m}){const[d,f]=c.useState(!1),h=c.useRef(null);return c.useEffect(()=>{if(!d)return;const g=p=>{h.current&&!h.current.contains(p.target)&&f(!1)},y=p=>{p.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y)}},[d]),n.length===0&&!m?null:r.jsxs("div",{ref:h,className:Y("relative",i),...u?{role:"none"}:{},children:[r.jsx(oe,{variant:"ghost",size:"sm",icon:t??r.jsx(cc,{className:"size-5"}),onClick:()=>f(g=>!g),"aria-label":e,"aria-haspopup":"menu","aria-expanded":d,...u?{role:"menuitem"}:{},className:Y(o&&"min-h-11 min-w-11 px-0",l),children:s}),d&&r.jsxs("div",{role:"menu",className:Y("absolute top-full z-50 mt-1 flex max-h-[60dvh] min-w-44 flex-col overflow-y-auto overscroll-contain rounded-md border border-line bg-surface py-1 shadow-lg",a==="end"?"right-0":"left-0"),children:[n.map(g=>r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{f(!1),g.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:[g.icon&&r.jsx("span",{className:"shrink-0 text-fg-subtle",children:g.icon}),g.label]},g.key)),m]})]})}const oi=e=>e.toLocaleString();function ii({selectAll:e,selecting:t,className:s}){return r.jsx(oo,{className:s,checked:e.checked,indeterminate:e.indeterminate,onChange:e.onChange,label:r.jsx("span",{className:"font-medium text-accent",children:e.checked&&t?"Deselect all":"Select all"})})}function fr({title:e,count:t,onCancel:s,onDelete:n,onMove:a,moveSlot:o,onOrganize:i,onJunk:l,onMarkRead:u,navSlot:m,titleMeta:d,searchSlot:f,searchField:h,idleSlot:g,overflowSlot:y,isBusy:p=!1,isCounting:b=!1,selectAll:x,statusLabel:S,progress:w,notice:v}){const C=t>0||b,E=x?.checked?`All ${oi(t)} loaded selected`:`${oi(t)} ${t===1?"message":"messages"} selected`,I=[];return l&&!p&&!b&&I.push({key:"junk",label:"Junk",icon:r.jsx(Ls,{className:"size-4"}),onSelect:l}),u&&!p&&!b&&I.push({key:"mark-read",label:"Mark read",icon:r.jsx(ur,{className:"size-4"}),onSelect:u}),r.jsxs("header",{"data-selection-bar":"",className:"flex shrink-0 flex-col border-b border-line bg-surface-sunken",children:[r.jsxs("div",{"data-selection-bar-row":"actions",className:"flex h-pane-header items-center gap-1 px-row-inset",children:[C?r.jsx(oe,{variant:"ghost",size:"touch",icon:r.jsx(Aa,{className:"size-5"}),onClick:s,"aria-label":"Cancel selection",className:"-ml-2 shrink-0"}):m,x&&r.jsx(ii,{selectAll:x,selecting:C,className:"hidden shrink-0 pr-2 md:flex"}),C?r.jsx("span",{"data-selection-count":"",className:"min-w-0 flex-1 truncate px-1 text-sm font-medium text-fg",role:"status","aria-live":"polite",children:S??E}):h?r.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:h}):r.jsxs(r.Fragment,{children:[r.jsx("h1",{className:"min-w-0 flex-1 truncate px-1 text-sm font-semibold text-fg",children:e}),d,f]}),C&&!b&&r.jsxs(r.Fragment,{children:[r.jsx(oe,{variant:"ghost",size:"touch",icon:p?r.jsx(Os,{className:"size-5 animate-spin"}):r.jsx(Et,{className:"size-5 text-danger"}),onClick:p?void 0:n,"aria-label":"Move selected messages to Trash","aria-busy":p||void 0,className:"shrink-0"}),!p&&(a?r.jsx(oe,{variant:"ghost",size:"touch",icon:r.jsx(Oa,{className:"size-5"}),onClick:a,"aria-label":"Move selected messages",className:"shrink-0"}):o),!p&&i&&r.jsx(oe,{variant:"ghost",size:"touch",icon:r.jsx(Nt,{className:"size-5"}),onClick:i,"aria-label":"Organize selected messages",className:"shrink-0"})]}),C&&r.jsx(io,{triggerLabel:"More actions",items:I,className:"shrink-0",children:!p&&!b&&y})]}),!C&&g,C&&x&&r.jsx("div",{"data-selection-bar-row":"select-all",className:"px-row-inset pb-2 md:hidden",children:r.jsx(ii,{selectAll:x,selecting:C,className:"w-full"})}),w&&r.jsx("div",{className:"px-row-inset pb-2",children:r.jsx(wf,{value:w.value,max:w.max,tone:w.tone})}),v&&r.jsx(ln,{"data-selection-notice":"",tone:v.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-row-inset mb-2",children:r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v.text&&r.jsx("span",{children:v.text}),v.action&&r.jsx(oe,{variant:"ghost",size:"md",onClick:v.action.onClick,className:"-my-1 min-h-11 shrink-0",children:v.action.label})]})})]})}let Ns;const hp=5e3;function yc(e){e.preventDefault(),qn()}function qn(){Ns!==void 0&&(clearTimeout(Ns),Ns=void 0,document.removeEventListener("contextmenu",yc,!0),document.removeEventListener("pointerup",qn,!0))}function pp(){Ns===void 0?(document.addEventListener("contextmenu",yc,!0),document.addEventListener("pointerup",qn,!0)):clearTimeout(Ns),Ns=setTimeout(qn,hp)}function wc({onLongPress:e,isDisabled:t,delayMs:s=500,accessibilityDescription:n}){const{longPressProps:a}=Fh({isDisabled:t,threshold:s,accessibilityDescription:n,onLongPress:e}),o=c.useCallback(i=>{i.pointerType!=="touch"&&i.pointerType!=="pen"||pp()},[]);return{longPressProps:Ps(a,{onPointerDown:o})}}const os=72,li=10,gp=os/2,ci="__swipeableRowAxisCancel";function ui(e){return e==="leading"?os:e==="trailing"?-os:0}function xp(e){return e>=os/2?"leading":e<=-os/2?"trailing":"none"}function Sc({thread:e,selectionMode:t,checked:s,active:n,peek:a,onPeek:o,onToggleCheck:i,onLongPress:l,onOpen:u,onAct:m,linkComponent:d}){const f=c.useRef(null),[h,g]=c.useState(null),{longPressProps:y}=wc({onLongPress:l,isDisabled:t,accessibilityDescription:"Select message"}),p=M=>{const k=new PointerEvent("pointercancel",{bubbles:!0});k[ci]=!0,M.currentTarget.dispatchEvent(k)},v=Ps(y,{onPointerDown:M=>{f.current={startX:M.clientX,startY:M.clientY,axis:"none",escaped:!1}},onPointerMove:M=>{if(t)return;const k=f.current;if(!k)return;const P=M.clientX-k.startX,F=M.clientY-k.startY;if(k.axis==="none"&&(Math.abs(F)>li&&Math.abs(F)>Math.abs(P)?k.axis="vertical":Math.abs(P)>li&&Math.abs(P)>Math.abs(F)&&(k.axis="horizontal",M.currentTarget.setPointerCapture(M.pointerId))),k.axis==="none")return;const j=k.axis==="horizontal"?Math.abs(P):Math.abs(F);if(!k.escaped&&j>gp&&(k.escaped=!0,p(M)),k.axis!=="horizontal")return;const R=ui(a),T=Math.max(-os,Math.min(os,R+P));g(T)},onPointerUp:M=>{const k=f.current;f.current=null;const P=h;if(g(null),!!k){if(k.axis!=="none"&&!k.escaped&&p(M),k.axis==="horizontal"){P!==null&&o(xp(P));return}if(k.axis!=="vertical"){if(t){i();return}if(a!=="none"){o("none");return}d||u()}}},onPointerCancel:M=>{M.nativeEvent[ci]||(f.current=null,g(null))}}),C=M=>{a!=="none"&&M.preventDefault()},E=h??ui(a),I=E>0?"leading":E<0?"trailing":"none",N=Y("relative touch-pan-y bg-surface","select-none [-webkit-touch-callout:none]",Fs({active:s||n})),D={transform:E!==0?`translateX(${E}px)`:void 0,transition:h===null?"transform 150ms ease":"none",minHeight:44},A=!e.isRead,O=M=>M.stopPropagation(),L=t?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:Y("inline-flex size-7 shrink-0 items-center justify-center rounded-full border",s?"border-accent bg-accent text-accent-fg":"border-line-strong bg-canvas"),children:s&&r.jsx(on,{className:"size-3.5"})}),r.jsx(sn,{thread:e})]}):r.jsxs(r.Fragment,{children:[A&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx("button",{type:"button",role:"checkbox","aria-checked":s,"aria-label":`Select message from ${e.fromName}`,onPointerDown:O,onPointerMove:O,onPointerUp:O,onClick:M=>{M.preventDefault(),M.stopPropagation(),l()},className:"-m-2 inline-flex size-11 shrink-0 items-center justify-center rounded-full",children:r.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"sm"})}),r.jsx(sn,{thread:e})]});return r.jsxs("div",{className:"relative overflow-hidden",children:[I==="leading"&&r.jsx("button",{type:"button",onClick:()=>m("leading"),"aria-label":e.isRead?"Mark as unread":"Mark as read",className:"absolute inset-y-0 left-0 flex items-center justify-start bg-accent-2 px-6 text-accent-fg",children:e.isRead?r.jsx(Hl,{className:"size-6"}):r.jsx(ur,{className:"size-6"})}),I==="trailing"&&r.jsx("button",{type:"button",onClick:()=>m("trailing"),"aria-label":"Delete message",className:"absolute inset-y-0 right-0 flex items-center justify-end bg-danger px-6 text-canvas",children:r.jsx(Et,{className:"size-6"})}),d&&!t?d({...v,className:N,style:D,onOpenClick:C,children:L}):r.jsx("button",{type:"button",role:t?"checkbox":void 0,"aria-checked":t?s:void 0,...v,className:N,style:D,children:L})]})}function bp({sections:e,selectedThreadId:t,selectionMode:s,checkedIds:n,initialPeek:a,onToggleCheck:o,onEnterSelection:i,onOpenThread:l,onRefresh:u,refreshing:m,busy:d=!1}){const[f,h]=c.useState(()=>e.flatMap(b=>b.threads)),[g,y]=c.useState(a&&a!=="none"&&f[1]?{id:f[1].id,side:a}:null),p=(b,x)=>{h(x==="trailing"?S=>S.filter(w=>w.id!==b):S=>S.map(w=>w.id===b?{...w,isRead:!w.isRead}:w)),y(null)};return r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[m&&r.jsxs("div",{className:"flex items-center justify-center gap-2 border-b border-line py-3 text-fg-muted",children:[r.jsx(fc,{className:"size-4 animate-spin"}),r.jsx("span",{className:"text-xs",children:"Checking for new mail…"})]}),r.jsx("div",{className:"divide-y divide-line",children:f.map(b=>r.jsx("div",{className:d?"pointer-events-none opacity-50":void 0,children:r.jsx(Sc,{thread:b,selectionMode:s,checked:n.has(b.id),active:b.id===t,peek:g?.id===b.id?g.side:"none",onPeek:x=>y(x==="none"?null:{id:b.id,side:x}),onToggleCheck:()=>o(b.id),onLongPress:()=>i(b.id),onOpen:()=>l(b.id),onAct:x=>p(b.id,x)})},b.id))}),!s&&!m&&!d&&r.jsx("button",{type:"button",onClick:u,className:"w-full border-t border-line py-2 text-center text-2xs text-fg-subtle transition-colors hover:bg-surface-sunken",children:"Pull to refresh"})]})}function kc({listTitle:e,listMeta:t,sections:s,briefFilters:n,flatList:a,listState:o="ready",searchQuery:i,listFilter:l,listScopeLabel:u,errorMessage:m,onRetry:d,onReportError:f,briefCategory:h,selectedThreadId:g,density:y="comfortable",onSelectThread:p,onSelectBriefCategory:b,onOpenNav:x,isDesktop:S,initialTouchState:w,selectionBar:v,paneOverlay:C,listBody:E,hideHeader:I=!1}){const N=y==="compact"?dp:fp,D=c.useRef(null);Jn({containerRef:D,itemSelector:Da});const A=!S&&!n&&o==="ready",O=s.flatMap(W=>W.threads),[L,M]=c.useState(w==="selection"),[k,P]=c.useState(()=>w==="selection"?new Set(O.slice(0,2).map(W=>W.id)):new Set),[F,j]=c.useState(!1),R=w==="peek-trailing"?"trailing":w==="peek-leading"?"leading":void 0,T=W=>{P(te=>{const ce=new Set(te);return ce.has(W)?ce.delete(W):ce.add(W),ce.size===0&&M(!1),ce})},V=W=>{M(!0),P(new Set([W]))},Z=()=>{M(!1),P(new Set)},ee=()=>{j(!0),setTimeout(()=>j(!1),1400)},fe=!v&&A&&L&&k.size>0;return r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[v??(fe?r.jsx(fr,{title:e,count:k.size,onCancel:Z,onMarkRead:Z,onDelete:Z}):I?null:r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[x&&r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Ya,{className:"size-4"}),onClick:x,"aria-label":"Open folders",className:"-ml-1 shrink-0"}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),t&&r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:t})]})),o==="loading"?r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(np,{})}):o==="empty"?r.jsx(rp,{filter:l,scopeLabel:u,searchQuery:i}):o==="error"?r.jsx(cp,{message:m,onRetry:d,onReport:f}):n?r.jsx(Sf,{sections:s,briefCategory:h,selectedThreadId:g,Row:N,onSelectThread:p,onSelectBriefCategory:b}):E??(A?r.jsx(bp,{sections:s,selectedThreadId:g,selectionMode:L,checkedIds:k,initialPeek:R,onToggleCheck:T,onEnterSelection:V,onOpenThread:W=>p?.(W),onRefresh:ee,refreshing:F}):r.jsx("div",{ref:D,className:"flex-1 overflow-y-auto",children:s.map(W=>r.jsxs("div",{children:[!a&&W.label&&r.jsxs("div",{className:"sticky top-0 flex h-section-row items-center justify-between border-b border-line bg-surface-sunken px-row-inset",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:W.label}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:W.threads.length})]}),r.jsx("div",{className:"divide-y divide-line",children:W.threads.map(te=>r.jsx(N,{thread:te,active:te.id===g,onClick:()=>p?.(te.id)},te.id))})]},W.id))})),S&&r.jsx(gc,{}),C]})}const qs="min-h-11 min-w-11 px-0";function Cc({hasThread:e,onReply:t,onReplyAll:s,onForward:n,isStarred:a,onToggleStar:o,onDelete:i,isRead:l,onToggleRead:u,moveSlot:m,overflowItems:d=[],onUnavailable:f,unavailableHint:h,className:g}){const y=(b,x)=>()=>{if(!e){f?.(b);return}x?.()},p=u?[{key:"toggle-read",label:l?"Mark as unread":"Mark as read",icon:l?r.jsx(Hl,{className:"size-4"}):r.jsx(ur,{className:"size-4"}),onSelect:y("toggleRead",u)}]:[];return r.jsxs("div",{className:Y("relative",g),children:[r.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-0.5 bg-canvas px-1",children:[r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(hc,{className:"size-5"}),onClick:y("reply",t),"aria-label":"Reply",title:"Reply",className:qs}),r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(mc,{className:"size-5"}),onClick:y("replyAll",s),"aria-label":"Reply all",title:"Reply all",className:qs}),r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(uc,{className:"size-5"}),onClick:y("forward",n),"aria-label":"Forward",title:"Forward",className:qs}),r.jsx("div",{className:"flex-1"}),r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Ht,{className:Y("size-5",a&&"fill-warning text-warning")}),onClick:y("star",o),"aria-label":a?"Unstar":"Star","aria-pressed":a,title:a?"Unstar":"Star",className:qs}),m,r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Et,{className:"size-5"}),onClick:y("delete",i),"aria-label":"Move to Trash",title:"Move to Trash",className:qs}),r.jsx(io,{triggerLabel:"More actions",items:[...p,...d]})]}),!e&&h&&r.jsx("p",{role:"status",className:"bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:h})]})}function vp({open:e=!1,enabled:t=!0,onToggle:s,className:n}){return r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Il,{className:"size-4"}),title:"Intelligence","aria-label":e?"Hide intelligence sidebar":"Show intelligence sidebar","aria-pressed":e,disabled:!t,onClick:s,className:Y(e&&"bg-accent-2-soft text-accent-2",n)})}function yp({hasThread:e,onUnavailable:t,unavailableHint:s,isStarred:n,showTriage:a=!0,onReply:o,onReplyAll:i,onForward:l,onDelete:u,onToggleStar:m,moveSlot:d,onMove:f,replyTitle:h="Reply (r)",replyAllTitle:g="Reply all (a)",forwardTitle:y="Forward (f)",deleteTitle:p="Move to Trash (#)",flagTitle:b="Star (s)",children:x,className:S}){const w=(v,C)=>()=>{if(!e){t?.(v);return}C?.()};return r.jsxs("div",{className:"relative",children:[r.jsxs("header",{className:Y("flex h-pane-header shrink-0 items-center gap-1 border-b border-line bg-surface px-3",S),children:[r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(hc,{className:"size-4"}),title:h,"aria-label":"Reply",onClick:w("reply",o)}),r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(mc,{className:"size-4"}),title:g,"aria-label":"Reply all",onClick:w("replyAll",i)}),r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(uc,{className:"size-4"}),title:y,"aria-label":"Forward",onClick:w("forward",l)}),a&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"mx-1 h-4 w-px bg-line","aria-hidden":!0}),r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Et,{className:"size-4"}),title:p,"aria-label":"Move to Trash",onClick:w("delete",u)}),d??r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Oa,{className:"size-4"}),title:"Move to mailbox","aria-label":"Move to mailbox",onClick:w("move",f)}),r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Ht,{className:Y("size-4",n&&"fill-warning text-warning")}),title:b,"aria-label":"Star",onClick:w("flag",m)})]}),r.jsx("div",{className:"flex-1"}),x]}),!e&&s&&r.jsx("p",{role:"status",className:"border-b border-line bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:s})]})}const wp=(e,t)=>{const n=e==="newsletter"||e==="marketing"||t;return{framed:n,isPlain:!n}},Sp=()=>`
|
|
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
|
-
`,kp=e=>{const t=new Map;for(const s of e){if(!s.contentId||s.contentUrl.length===0)continue;const n=s.contentId.replace(/^<|>$/g,"");t.set(n,s.contentUrl)}return s=>t.get(s.replace(/^<|>$/g,""))},Cp=/^(none|transparent|inherit|initial|unset)\s*$/i,jp=e=>{const t=[],s=/<style[^>]*>([\s\S]*?)<\/style>/gi;let n;for(n=s.exec(e);n!==null;)t.push(n[1]),n=s.exec(e);return t},Np=e=>{const t=/background(?:-color)?\s*:\s*([^;}\n]+)/gi;let s;for(s=t.exec(e);s!==null;){const n=s[1].trim();if(!Cp.test(n))return!0;s=t.exec(e)}return!1},Ep=e=>{if(/\bstyle\s*=\s*["'][^"']*background/i.test(e)||/\bbgcolor\s*=/i.test(e))return!0;for(const t of jp(e))if(Np(t))return!0;return!1},Ip=["script","iframe","object","embed","form","input","button","textarea","select","meta","link","base"],Tp=["onerror","onload","onclick","onmouseover","onmouseout","onfocus","onblur","onsubmit","onkeydown","onkeyup","formaction","xlink:href","data-bind"],Rp="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
|
-
`),Mp=e=>e.replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Ap=e=>e.replace(/@import[^;]*;/gi,"/* @import blocked */").replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Op=(e={})=>{const t=Tl(),s={FORBID_TAGS:Ip,FORBID_ATTR:Tp,ALLOW_DATA_ATTR:!1,ALLOW_UNKNOWN_PROTOCOLS:!1};return t.addHook("afterSanitizeAttributes",n=>{if(n.tagName==="IMG"){const a=n.getAttribute("src")||"";if(a.startsWith("data:"))return;if(a.startsWith("cid:")){const i=a.slice(4).replace(/^<|>$/g,""),l=e.resolveCid?.(i);l&&(n.setAttribute("src",l),n.classList.add("inline-content"));return}e.allowExternalImages||(n.setAttribute("data-blocked-src",a),n.setAttribute("src",Rp),n.setAttribute("alt","[Blocked image]"),n.classList.add("blocked-image"))}if(n.tagName==="A"){const a=n.getAttribute("href")||"";if(/^(javascript|data):/i.test(a)){n.removeAttribute("href");return}n.setAttribute("target","_blank"),n.setAttribute("rel","noopener noreferrer nofollow"),n.classList.add("external-link")}if(n.hasAttribute("style")){const a=n.getAttribute("style")||"";n.setAttribute("style",Mp(a))}}),t.addHook("uponSanitizeElement",(n,a)=>{if(a.tagName==="style"){const o=n.textContent||"";n.textContent=Ap(o)}}),n=>{const a=Ep(n),o=t.sanitize(n,s);return{html:`<style>${Sp()}</style>${o}`,hasAuthorBackground:a}}},Dp='"Geist Variable", "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',di={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)"}},Pp=/prefers-color-scheme\s*:\s*dark|color-scheme\s*:\s*[^;}"']*\bdark\b/i,fi='<meta name="viewport" content="width=device-width, initial-scale=1">',Lp=e=>{const t=e?di.dark:di.light;return`
|
|
54
|
-
/* Plain-email base: UI font-stack + theme-aware colors (#424) */
|
|
55
|
-
html, body {
|
|
56
|
-
font-family: ${Dp};
|
|
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
|
-
`},Fp=(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}",$p=(e,t,s)=>{if(t==="plain")return`${fi}<style>${Lp(s)}</style>${e}`;const n=Pp.test(e);return`${fi}<style>${Fp(s,n)}</style>${e}`},_p=5e4,zp=1e4,Bp="(max-width: 640px)",Kp=.4,Up="allow-same-origin allow-popups allow-popups-to-escape-sandbox",mi=(e,t,s)=>Math.min(Math.ceil(Math.max(e,t)),s),qp=(e,t)=>e<=0||t<=0||e<=t?1:Math.max(Kp,t/e),Hp=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Wp=new Set(["Enter","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"]),Vp=e=>e===" "?!1:e.length===1?!0:Wp.has(e),hi=e=>{if(e.metaKey||e.ctrlKey||e.altKey||!Vp(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}))},pi=({html:e,variant:t="framed",isDark:s=!1,className:n})=>{const a=c.useRef(null),o=c.useRef(null),[i,l]=c.useState(0),[u,m]=c.useState(0),[d,f]=c.useState(0),h=Hp(Bp),g=c.useMemo(()=>$p(e,t,s),[e,t,s]);c.useEffect(()=>{const w=a.current;if(!w)return;const v=()=>f(E=>E===w.clientWidth?E:w.clientWidth);v();const C=new ResizeObserver(v);return C.observe(w),()=>C.disconnect()},[]),c.useEffect(()=>{const w=o.current;if(!w)return;const v=()=>{const N=w.contentDocument;if(!N?.body)return;const D=N.documentElement,A=mi(N.body.scrollHeight,D?.scrollHeight??0,_p);l(L=>L===A?L:A);const O=mi(N.body.scrollWidth,D?.scrollWidth??0,zp);m(L=>L===O?L:O)};let C,E;const I=()=>{v();const N=w.contentDocument;N?.body&&(C=new ResizeObserver(v),C.observe(N.body),N.documentElement&&C.observe(N.documentElement),N.addEventListener("keydown",hi),E=N)};return w.addEventListener("load",I),()=>{w.removeEventListener("load",I),E?.removeEventListener("keydown",hi),C?.disconnect()}},[]);const y=h?qp(u,d):1,p=y<1,b=p?`${u}px`:h?"100%":t==="framed"&&u>0?`max(100%, ${u}px)`:u===0?"100%":`${u}px`,x=i===0?"1px":`${i}px`,S=r.jsx("iframe",{ref:o,title:"Email content",sandbox:Up,srcDoc:g,className:p?void 0:n,scrolling:"no",style:{width:b,maxWidth:p?"none":void 0,border:"none",display:"block",height:x,overflow:"hidden",transform:p?`scale(${y})`:void 0,transformOrigin:p?"top left":void 0,colorScheme:"normal"}});return r.jsx("div",{ref:a,className:p?n:void 0,children:p?r.jsx("div",{style:{width:"100%",height:`${Math.ceil(i*y)}px`,overflow:"hidden"},children:S}):S})},gi=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),jc=({html:e,text:t,isDark:s=!1,category:n,allowImages:a=!1,resolveCid:o,className:i,renderBlockedNotice:l})=>{const u=c.useMemo(()=>!e||typeof document>"u"?null:Op({allowExternalImages:a,resolveCid:o})(e),[e,a,o]),m=u?.html??null,{framed:d,isPlain:f}=wp(n,u?.hasAuthorBackground??!1),h=c.useMemo(()=>!m||a?0:(m.match(/data-blocked-src/g)||[]).length,[m,a]);return!m&&!t?r.jsx("div",{className:Y("message-body",i),children:r.jsx(gi,{})}):r.jsxs("div",{className:Y("message-body",i),children:[h>0&&r.jsx("div",{className:"message-body-notice",children:l?.(h)}),m?d?r.jsx("div",{className:"w-full max-w-full overflow-x-auto",children:r.jsx(pi,{html:m,variant:"framed",isDark:s})}):r.jsx("div",{className:"max-w-full overflow-x-auto lg:max-w-2xl",children:r.jsx(pi,{html:m,variant:f?"plain":"framed",isDark:s})}):t?r.jsx("pre",{className:"email-text whitespace-pre-wrap text-sm leading-relaxed",children:t}):r.jsx(gi,{})]})};function $s({message:e="Select a thread to read",icon:t,showHints:s=!0,className:n}){return r.jsxs("div",{className:Y("flex flex-1 flex-col items-center justify-center text-center",n),children:[t??r.jsx(Pa,{className:"size-10 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:e}),s&&r.jsxs("p",{className:"text-2xs text-fg-subtle",children:[r.jsx(js,{children:"j"})," / ",r.jsx(js,{children:"k"})," to move, ",r.jsx(js,{children:"Enter"})," to open"]})]})}function Nc({message:e,onClick:t,isFocused:s,isUnread:n,trailing:a}){const o=r.jsxs(r.Fragment,{children:[r.jsx(Ms,{className:"size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{className:"relative shrink-0",children:[r.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"md"}),n&&r.jsx("span",{className:"absolute -top-0.5 -right-0.5 size-2 rounded-full border border-canvas bg-accent"})]}),r.jsx("span",{className:Y("w-36 shrink-0 truncate text-sm",n?"font-semibold text-fg":"font-medium text-fg-muted"),children:e.fromName}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-fg-subtle",children:e.snippet}),a??r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.dateLabel})]}),i=Y("group flex h-section-row w-full items-center gap-3 border-b border-line px-2 text-left transition-colors hover:bg-surface-sunken lg:px-4",s&&"bg-surface-sunken ring-1 ring-inset ring-accent/30");return t?r.jsx("div",{role:"button",tabIndex:0,"aria-expanded":!1,onClick:t,onKeyDown:l=>{kf(l)&&(l.preventDefault(),t())},className:Y(i,"cursor-pointer"),children:o}):r.jsx("div",{className:i,children:o})}function Ec({message:e,warning:t,onHeaderClick:s,isFocused:n,senderBadge:a,trailing:o,to:i,indicators:l,actionMenu:u,actionBar:m,body:d}){const f=r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[r.jsxs("span",{className:"text-sm font-semibold text-fg",children:[e.fromName,a]}),o??r.jsx("span",{className:"text-2xs text-fg-subtle",children:e.dateLabel})]}),r.jsx("div",{className:"text-xs text-fg-subtle",children:e.fromEmail}),i!==null&&r.jsx("div",{className:"text-xs text-fg-subtle",children:i??r.jsxs(r.Fragment,{children:["to ",e.toLabel]})})]});return r.jsxs("div",{className:Y("px-2 py-3 lg:px-4",n&&"ring-1 ring-inset ring-accent/30"),children:[r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(Ut,{className:"mt-1 size-3.5 shrink-0 text-fg-subtle"}),r.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"md"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[s?r.jsx("button",{type:"button",onClick:s,className:"w-full text-left",children:f}):f,l]}),u&&r.jsx("div",{className:"shrink-0",children:u})]}),t&&r.jsxs("div",{className:"mt-3 flex items-start gap-3 rounded-md bg-danger-soft p-3",children:[r.jsx(Ls,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("div",{className:"text-sm text-fg",children:[r.jsx("span",{className:"font-semibold text-danger",children:"Caution: "}),t," ",r.jsx("button",{type:"button",className:"text-accent underline",children:"Why?"})]})]}),m&&r.jsx("div",{className:"mt-3 -mx-2 lg:-mx-4",children:m}),r.jsx("div",{className:"-mx-2 [&_.message-body-notice]:px-2 lg:mx-0 lg:[&_.message-body-notice]:px-0",children:d??r.jsx(jc,{className:"mt-3",html:e.bodyHtml,category:e.framed?"newsletter":"personal",allowImages:!0})})]})}function Qp({thread:e,onBack:t,intelligence:s,intelligenceOpen:n,onToggleIntelligence:a,actions:o,children:i,touchHandlers:l}){const[u,m]=c.useState(!1),d=a!==void 0,f=d?n??!1:u,h=!!s||d,g=()=>{if(d){a?.();return}m(p=>!p)},y=()=>{if(d){f&&a?.();return}m(!1)};return r.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Aa,{className:"size-4"}),onClick:t,"aria-label":"Back to messages",className:"-ml-1 shrink-0"}),r.jsx("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e.subject}),h&&r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Il,{className:"size-4"}),onClick:g,"aria-label":f?"Hide intelligence panel":"Show intelligence panel","aria-pressed":f,title:"Intelligence",className:Y("shrink-0",f&&"bg-accent-2-soft text-accent-2")})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",style:l?{touchAction:"pan-y"}:void 0,...l,children:i??e.messages.map(p=>{const b=x=>x?()=>x(p.id):void 0;return p.expanded?r.jsx(Ec,{message:p,warning:e.warning,onHeaderClick:b(o?.onToggleExpand),actionBar:r.jsx(Cc,{hasThread:!0,onReply:b(o?.onReply),onReplyAll:b(o?.onReplyAll),onForward:b(o?.onForward),onToggleStar:b(o?.onToggleStar),onDelete:b(o?.onDelete),onToggleRead:b(o?.onToggleRead),moveSlot:o?.moveSlot?.(p.id)})},p.id):r.jsx(Nc,{message:p,onClick:b(o?.onToggleExpand)},p.id)})}),s&&!d&&r.jsx(Cf,{open:f,onClose:y,title:"Intelligence",anchor:"right",className:"p-0",children:r.jsx(pc,{data:s,onClose:y,className:"h-full w-full border-l-0"})})]})}const Gp="button:not([disabled]), a[href]",rs="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface-sunken";function Yp({active:e,dimmed:t,indent:s}){return Y("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors",rs,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 Xp({icon:e,label:t,count:s,active:n}){return r.jsxs(r.Fragment,{children:[e&&r.jsx("span",{className:Y("shrink-0",n?"text-accent-2":"text-fg-subtle"),children:e}),r.jsx("span",{className:"flex-1 truncate",children:t}),s!=null&&s>0&&r.jsx("span",{className:Y("text-2xs tabular-nums",n?"text-accent-2":"text-fg-subtle"),children:s})]})}function Es({icon:e,label:t,count:s,active:n,dimmed:a,indent:o,navId:i,linkComponent:l,ariaLabel:u,title:m,onClick:d}){const f=Yp({active:n,dimmed:a,indent:o}),h=r.jsx(Xp,{icon:e,label:t,count:s,active:n});return i&&l?l({navId:i,className:f,ariaLabel:u??t,title:m,onClick:d,children:h}):r.jsx("button",{type:"button",onClick:d,className:f,"aria-label":u,title:m,children:h})}const xi={inbox:0,flagged:1,drafts:2,sent:3,archive:4,all:5,junk:6,trash:7};function Jp(e){switch(e){case"inbox":return r.jsx(Pa,{className:"size-4"});case"flagged":return r.jsx(Ht,{className:"size-4"});case"drafts":return r.jsx(Rl,{className:"size-4"});case"sent":return r.jsx(cn,{className:"size-4"});case"archive":return r.jsx(Ef,{className:"size-4"});case"all":return r.jsx(Nf,{className:"size-4"});case"junk":return r.jsx(jf,{className:"size-4"});case"trash":return r.jsx(Et,{className:"size-4"})}}const bi=e=>e.role!=null,Ur=8,vi="remit.nav.folders.open.",yi="remit.nav.account.open.";function wi(e,t,s){if(typeof localStorage>"u")return s;const n=localStorage.getItem(e+t);return n===null?s:n!=="0"}function Si(e,t,s){typeof localStorage>"u"||localStorage.setItem(e+t,s?"1":"0")}function Zp({query:e,onSelect:t,onRemove:s}){return r.jsxs("div",{className:"group flex w-full items-center gap-1 rounded-md pr-1 hover:bg-surface",children:[r.jsxs("button",{type:"button",onClick:t,className:Y("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",rs),children:[r.jsx(Zn,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate",children:e})]}),s&&r.jsx("button",{type:"button",onClick:s,"aria-label":`Remove saved search: ${e}`,className:Y("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",rs),children:r.jsx(vt,{className:"size-3.5"})})]})}function eg({savedSearches:e,saveableQuery:t,onSelectSavedSearch:s,onRemoveSavedSearch:n,onSaveCurrentSearch:a}){return e.length===0&&!t?null:r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:"px-2 pb-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Saved searches"}),t&&r.jsxs("button",{type:"button",onClick:a,className:Y("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-accent transition-colors hover:bg-surface",rs),children:[r.jsx(_h,{className:"size-4 shrink-0"}),r.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Save “",t,"”"]})]}),e.map(o=>r.jsx(Zp,{query:o,onSelect:()=>s?.(o),onRemove:n?()=>n(o):void 0},o))]})}function tg({account:e,selectedNavId:t,onSelectNav:s,linkComponent:n}){const[a,o]=c.useState(()=>wi(yi,e.id,!0)),[i,l]=c.useState(()=>wi(vi,e.id,!0)),[u,m]=c.useState(!1),d=()=>{o(S=>{const w=!S;return Si(yi,e.id,w),w})},f=()=>{l(S=>{const w=!S;return Si(vi,e.id,w),w})},h=e.mailboxes.filter(bi).sort((S,w)=>xi[S.role]-xi[w.role]),g=e.mailboxes.filter(S=>!bi(S)),y=u||g.length<=Ur?g:g.slice(0,Ur),p=g.length-y.length,b=e.status??"ready",x=b==="ready"&&h.length===0&&g.length===0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("button",{type:"button",onClick:d,"aria-expanded":a,className:Y("flex w-full items-center gap-1.5 px-2 pb-1 text-left transition-colors hover:text-fg",rs,e.muted&&"opacity-55"),children:[a?r.jsx(Ut,{className:"size-3 shrink-0 text-fg-subtle"}):r.jsx(Ms,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"truncate text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),e.muted&&r.jsxs(r.Fragment,{children:[r.jsx(oc,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:"muted"})]})]}),a&&r.jsxs(r.Fragment,{children:[b==="loading"&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"Loading…"}),b==="error"&&r.jsxs("div",{role:"alert",className:"mx-2 my-1 flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-2 py-1.5 text-sm",children:[r.jsx(cs,{className:"mt-0.5 size-4 shrink-0 text-danger","aria-hidden":"true"}),r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx("p",{className:"font-medium text-danger",children:"Couldn't load mailboxes"})}),e.onRetry&&r.jsx("button",{type:"button",onClick:e.onRetry,className:"shrink-0 text-sm font-medium text-accent hover:underline",children:"Retry"})]}),x&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"No mailboxes"}),b==="ready"&&r.jsxs(r.Fragment,{children:[h.map(S=>r.jsx(Es,{navId:S.id,linkComponent:n,icon:Jp(S.role),label:S.name,ariaLabel:S.name,title:S.fullPath??S.name,count:S.unseen,active:t===S.id,dimmed:e.muted,onClick:()=>s?.(S.id)},S.id)),e.outboxPending!==void 0&&r.jsx(Es,{navId:"outbox",linkComponent:n,icon:r.jsx(cn,{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&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",onClick:f,"aria-expanded":i,className:Y("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",rs),children:[i?r.jsx(Ut,{className:"size-3 shrink-0"}):r.jsx(Ms,{className:"size-3 shrink-0"}),r.jsx("span",{className:"flex-1",children:"Folders"}),r.jsx("span",{className:"tabular-nums opacity-70",children:g.length})]}),i&&r.jsxs(r.Fragment,{children:[y.map(S=>r.jsx(Es,{navId:S.id,linkComponent:n,icon:r.jsx(eh,{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>Ur&&r.jsx("button",{type:"button",onClick:()=>m(S=>!S),className:Y("ml-7 flex items-center px-2 py-1 text-2xs font-medium text-accent transition-colors hover:underline",rs),children:u?"Show less":`Show all (${g.length})`})]})]})]})]})]})}function sg({accounts:e,selectedNavId:t,briefUnseen:s,onSelectNav:n,variant:a="desktop",linkComponent:o,savedSearches:i=[],saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:d}){const f=c.useRef(null);Jn({containerRef:f,itemSelector:Gp});const h=a==="drawer",g=r.jsxs("nav",{ref:h?f:void 0,className:h?"px-2 py-2":"flex-1 overflow-y-auto px-2 py-2","aria-label":"Mailboxes",children:[r.jsx(Es,{navId:"brief",linkComponent:o,icon:r.jsx(Nt,{className:"size-4"}),label:"Daily brief",ariaLabel:"Daily brief",count:s,active:t==="brief",onClick:()=>n?.("brief")}),r.jsx(Es,{navId:"flagged",linkComponent:o,icon:r.jsx(Ht,{className:"size-4"}),label:"Starred",ariaLabel:"Starred",active:t==="flagged",onClick:()=>n?.("flagged")}),r.jsx(eg,{savedSearches:i,saveableQuery:l,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:d}),e.length===0?r.jsx("div",{className:"px-2 py-4 text-center text-sm text-fg-muted",children:"No accounts configured"}):e.map(y=>r.jsx(tg,{account:y,selectedNavId:t,onSelectNav:n,linkComponent:o},y.id))]});return h?g:r.jsxs("aside",{ref:f,className:"flex h-full w-full flex-col bg-surface-sunken",children:[g,r.jsx("div",{className:"border-t border-line px-2 py-2",children:r.jsx(Es,{navId:"settings",linkComponent:o,icon:r.jsx(ro,{className:"size-4"}),label:"Settings",ariaLabel:"Settings",active:t==="settings",onClick:()=>n?.("settings")})})]})}function ng({search:e,actions:t,className:s}){return r.jsxs("header",{className:Y("flex min-h-16 w-full shrink-0 items-center gap-3 border-b border-line bg-canvas px-3 py-2",s),children:[r.jsx("div",{className:"flex min-w-0 flex-1 justify-start",children:r.jsx("div",{className:"w-full max-w-2xl",children:e})}),t&&r.jsx("div",{className:"flex shrink-0 items-center gap-1",children:t})]})}function rg({label:e,onUndo:t,undoLabel:s="Undo",filtersHref:n,manageLabel:a="Manage filter",className:o}){return r.jsxs(gt,{tone:"accent",className:Y("py-1 text-xs",o),children:[r.jsx(Vh,{className:"size-3.5 shrink-0","aria-hidden":!0}),r.jsx("span",{children:e}),t&&r.jsx("button",{type:"button",onClick:i=>{i.stopPropagation(),t()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:s}),n&&r.jsx("a",{href:n,onClick:i=>{i.stopPropagation()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:a})]})}function ag({sync:e}){return e?r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",role:"status","aria-live":"polite",children:[r.jsx(Os,{className:"size-8 animate-spin text-fg-subtle","aria-hidden":"true"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"Still syncing your mail"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:og(e)})]}):r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[r.jsx(Nt,{className:"size-8 text-fg-subtle","aria-hidden":"true"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"You're caught up"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Nothing needs attention."})]})}function og({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 ig=({status:e})=>e==="saving"?r.jsx("span",{className:"animate-pulse text-xs text-fg-muted",children:"Saving..."}):e==="saved"?r.jsx("span",{className:"text-xs text-fg-muted",children:"Draft saved"}):e==="error"?r.jsx("span",{className:"text-xs text-danger",children:"Save failed"}):null;function lg({onSend:e,onDiscard:t,sending:s,canSend:n,saveStatus:a="idle",unavailableReason:o,onUnavailable:i}){return r.jsxs("div",{className:"flex items-center justify-between border-t border-line px-3 py-2",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(oe,{variant:"primary",size:"md","aria-busy":s,title:n?void 0:o,className:"min-h-11 rounded-full px-4",icon:s?r.jsx(Os,{className:"size-4 animate-spin"}):r.jsx(cn,{className:"size-4"}),onClick:()=>{if(!s){if(!n){o&&i?.(o);return}e()}},children:"Send"}),r.jsx(ig,{status:a})]}),r.jsx(oe,{variant:"ghost",size:"md","aria-busy":s,"aria-label":"Discard",className:"min-h-11 min-w-11 px-2 hover:text-danger",icon:r.jsx(Et,{className:"size-4"}),onClick:()=>{s||t()}})]})}function cg({banner:e,header:t,children:s,quoted:n,actionBar:a}){return r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e,t,r.jsxs("div",{className:"min-h-0 flex-1 overflow-auto",children:[s,n&&r.jsx("div",{className:"px-3 pb-2",children:n})]}),a]})}function ug({key:e,shiftKey:t=!1,repeat:s=!1,caretAtStart:n,hasValue:a,chipCount:o}){const i=o-1;return e==="Escape"?a?{type:"clearQuery"}:{type:"blur"}:e==="Tab"&&t?o===0?{type:"none"}:{type:"focusChip",index:i}:e==="Backspace"||e==="ArrowLeft"?!n||o===0?{type:"none"}:s?{type:"none"}:{type:"focusChip",index:i}:{type:"none"}}function dg({key:e,repeat:t=!1,index:s,chipCount:n}){return e==="Backspace"||e==="Delete"?t?{type:"none"}:{type:"removeChip",index:s}:e==="ArrowLeft"?s===0?{type:"none"}:{type:"focusChip",index:s-1}:e==="ArrowRight"?s>=n-1?{type:"focusInput"}:{type:"focusChip",index:s+1}:e==="Enter"||e===" "?{type:"activateChip",index:s}:e==="Escape"?{type:"focusInput"}:{type:"none"}}function fg(e,t){const s=t-1;return s<=0?null:e<s?e:s-1}const mg=e=>e instanceof HTMLElement?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable:!1,hg=({chips:e=[],onRemoveChip:t,onActivateChip:s,value:n,onChange:a,onClear:o,onClearQuery:i,placeholder:l="Search mail...",globalFocusKey:u=!0,showClearButton:m=!0,size:d="sm",inputId:f,chipsLabel:h="Search filters",suggest:g,className:y})=>{const p=c.useId(),b=f??p,x=c.useRef(null),S=c.useRef([]),w=i??o,[v,C]=c.useState(null),E=c.useRef(void 0),[I,N]=c.useState(""),D=e.length>0;c.useEffect(()=>{C(j=>j!==null&&j>=e.length?null:j)},[e.length]),c.useEffect(()=>{const j=E.current;if(j!==void 0){if(E.current=void 0,j===null){x.current?.focus();return}S.current[j]?.focus()}});const A=c.useRef(void 0);c.useEffect(()=>{const j=g?.caret;if(!j||j===A.current)return;A.current=j;const R=x.current;!R||R.ownerDocument.activeElement!==R||(R.setSelectionRange(j.cursor,j.cursor),g?.onCaretChange(j.cursor))});const O=j=>{g?.onCaretChange(j.selectionStart??j.value.length)},L=c.useCallback(j=>{C(j),E.current=j},[]),M=c.useCallback(j=>{const R=e[j];R&&t&&(L(fg(j,e.length)),N(`${R.label} removed`),t(R.id))},[e,t,L]),k=c.useCallback(()=>{L(null),o()},[o,L]),P=c.useCallback(j=>{const R=j.currentTarget;if(g?.onKeyDown(j))return;const T=ug({key:j.key,shiftKey:j.shiftKey,repeat:j.repeat,caretAtStart:R.selectionStart===0&&R.selectionEnd===0,hasValue:n.length>0,chipCount:e.length});switch(T.type){case"focusChip":j.preventDefault(),L(T.index);return;case"clearQuery":w();return;case"blur":R.blur();return;case"none":return}},[e.length,n,w,L,g]),F=c.useCallback(j=>R=>{const T=dg({key:R.key,repeat:R.repeat,index:j,chipCount:e.length});switch(T.type!=="none"&&R.preventDefault(),T.type){case"removeChip":M(T.index);return;case"focusChip":L(T.index);return;case"focusInput":L(null);return;case"activateChip":{const V=e[T.index];V&&s&&s(V.id);return}case"none":return}},[e,M,L,s]);return c.useEffect(()=>{if(!u)return;const j=R=>{R.key!=="/"||R.metaKey||R.ctrlKey||R.altKey||mg(R.target)||(R.preventDefault(),x.current?.focus())};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[u]),r.jsxs("label",{htmlFor:b,className:Y("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",y),children:[r.jsx(Zn,{className:Y("shrink-0 text-fg-muted pointer-events-none",d==="lg"?"size-5":"size-4")}),r.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1",children:[D&&r.jsx("div",{role:"grid","aria-label":h,className:"flex min-w-0 flex-wrap items-center gap-1",children:e.map((j,R)=>r.jsx(If,{ref:T=>{S.current[R]=T},label:j.label,tone:j.tone,focused:v===R,onFocusLabel:()=>C(R),onKeyDown:F(R),onRemove:()=>M(R),onActivate:s?()=>s(j.id):void 0},j.id))}),r.jsx("input",{ref:x,id:b,name:"q",type:"text","aria-label":"Search mail",autoComplete:"off",value:n,tabIndex:v===null?0:-1,onChange:j=>{a(j.target.value),O(j.target)},onKeyDown:P,onKeyUp:j=>O(j.currentTarget),onClick:j=>O(j.currentTarget),onFocus:j=>{C(null),g?.onFocusChange?.(!0),O(j.currentTarget)},onBlur:()=>g?.onFocusChange?.(!1),...g?.comboboxProps,placeholder:D?void 0:l,className:"min-w-24 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted"})]}),(n||D)&&m&&r.jsx("button",{type:"button",onClick:k,className:"shrink-0 rounded p-0.5 hover:bg-surface-raised transition-colors","aria-label":"Clear search",children:r.jsx(vt,{className:Y("text-fg-muted",d==="lg"?"size-5":"size-4")})}),r.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:I})]})},lo=({value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i="Search mail...",globalFocusKey:l=!0,showClearButton:u=!0,size:m,inputId:d,suggest:f,className:h})=>r.jsx(hg,{value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i,globalFocusKey:l,showClearButton:u,size:m,inputId:d,suggest:f,className:h}),pg=(e,t)=>e==="vip"?"vip":e==="unknown"&&t==="md"?"unknown-pill":"hidden",Ic=({senderTrust:e,size:t="sm",className:s})=>{const n=pg(e,t);return n==="vip"?r.jsx(Nt,{className:Y("text-warning shrink-0",t==="sm"&&"size-3.5",t==="md"&&"size-4",s),"aria-label":"VIP sender","data-testid":"sender-trust-vip"}):n==="unknown-pill"?r.jsx("span",{className:Y("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 gg(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 xg({result:e,onClick:t,query:s,showFolder:n=!0}){const a=n&&e.folder?Tf(e.folder):void 0;return r.jsx("button",{type:"button",onClick:t,className:Y("group",Fs({}),"border-b border-line"),children:r.jsx(ao,{thread:gg(e),highlightQuery:s,badge:r.jsxs(r.Fragment,{children:[a&&r.jsx(gt,{tone:"neutral",className:"shrink-0",children:a}),e.category&&r.jsx(gt,{tone:e.category.tone??"neutral",className:"shrink-0",children:e.category.label}),e.matchedChunkLabel&&r.jsx(gt,{tone:"neutral",className:"shrink-0",children:`matched: ${e.matchedChunkLabel}`}),e.score!=null&&r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.score.toFixed(2)})]})})})}const bg=e=>e===1?"result":"results";function vg({count:e,onScopeToSpam:t}){return r.jsx(ln,{tone:"info",variant:"soft",className:"items-center justify-between gap-3 rounded-none border-b border-line",children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("p",{className:"min-w-0 text-xs text-fg-muted",children:[r.jsx("span",{className:"font-semibold text-fg tabular-nums",children:e})," ",`${bg(e)} from Spam`]}),r.jsx(oe,{variant:"ghost",size:"sm",onClick:t,className:"shrink-0 text-accent",children:"Go to Spam"})]})})}const ki=6,yg={kind:"global"},wg=e=>e.kind==="folder"&&e.role==="junk",Sg=e=>e.folder?.role==="junk";function Tc(e){const t=[],s=[];for(const n of e)Sg(n)?s.push(n):t.push(n);return{kept:t,spam:s}}function Rc({onClick:e,blockedReason:t}){const s=c.useId(),[n,a]=c.useState(!1);return r.jsxs("div",{className:"border-b border-line px-row-inset py-1.5",children:[r.jsxs("button",{type:"button",onClick:()=>{if(t){a(!0);return}e()},"aria-describedby":t?s:void 0,className:Y("flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs font-medium transition-colors",t?"text-fg-subtle opacity-55":"text-accent hover:bg-surface-sunken"),children:[r.jsx(Rf,{className:"size-3.5 shrink-0","aria-hidden":"true"}),r.jsx("span",{children:"Make this a filter"})]}),t&&r.jsx(Mf,{id:s,reason:t,nudged:n,className:"px-2 pt-1 text-2xs text-warning"})]})}function kg({section:e,query:t,onSelectResult:s,showFolder:n}){const[a,o]=c.useState(e.initialCollapsed??!1),[i,l]=c.useState(!1),u=e.results.length>ki,d=!i&&u?e.results.slice(0,ki):e.results,f=e.results.length-d.length;return r.jsxs("div",{children:[r.jsxs("button",{type:"button","aria-expanded":!a,onClick:()=>o(h=>!h),className:"sticky top-0 z-10 flex h-section-row w-full items-center gap-1.5 border-b border-line bg-surface-sunken px-row-inset text-left transition-colors hover:bg-surface",children:[r.jsx("span",{className:"flex-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e.label}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:e.results.length}),r.jsx(Ut,{className:Y("size-3 shrink-0 text-fg-subtle transition-transform duration-200",a?"rotate-0":"rotate-180")})]}),!a&&r.jsxs(r.Fragment,{children:[d.map(h=>r.jsx(xg,{result:h,query:t,showFolder:n,onClick:s?()=>s(h):void 0},h.id)),u&&r.jsxs("button",{type:"button",onClick:()=>l(h=>!h),className:"flex w-full items-center justify-center border-b border-line px-row-inset py-1.5 text-2xs font-medium text-accent transition-colors hover:bg-surface",children:[i?"Show less":`Show ${f} more`,!i&&r.jsx(Ut,{className:"ml-1 size-3"})]})]})]})}function Mc({value:e,recentSearches:t,onPickRecent:s,sections:n,loading:a,onSelectResult:o,tokens:i,scope:l=yg,makeFilter:u}){if(!(e.trim().length>0))return t&&t.length>0?r.jsxs("div",{className:"flex flex-col",children:[r.jsx("h3",{className:"px-row-inset pb-1 pt-3 text-2xs font-semibold uppercase tracking-wide text-fg-subtle",children:"Recent searches"}),t.map(v=>r.jsxs("button",{type:"button",onClick:()=>s?.(v),className:"flex w-full items-center gap-2.5 border-b border-line px-row-inset py-2.5 text-left transition-colors hover:bg-surface-sunken",children:[r.jsx(Xa,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-fg-muted",children:v})]},v))]}):r.jsx("p",{className:"px-row-inset py-6 text-center text-sm text-fg-subtle",children:"Search across your mail by sender, subject or words in the message."});const d=i&&i.length>0&&r.jsx(Af,{tokens:i}),f=u&&r.jsx(Rc,{...u});if(a)return r.jsxs("div",{className:"flex flex-col",children:[f,d,r.jsx("div",{className:"flex flex-col gap-3 px-row-inset py-4",children:[0,1,2,3].map(v=>r.jsxs("div",{className:"flex flex-col gap-1.5",children:[r.jsx("div",{className:"h-3 w-1/3 animate-pulse rounded bg-surface-sunken"}),r.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-surface-sunken"}),r.jsx("div",{className:"h-2.5 w-1/2 animate-pulse rounded bg-surface-sunken"})]},v))})]});const h=l.kind==="global",g=wg(l)||l.kind==="collection",y=h||l.kind==="collection",p=(n??[]).map(v=>{if(g)return{section:v,spam:[]};const{kept:C,spam:E}=Tc(v.results);return{section:{...v,results:C},spam:E}}),b=p.map(v=>v.section),x=p.reduce((v,C)=>v+C.spam.length,0),S=l.kind==="global"&&x>0&&l.onScopeToSpam!==void 0?r.jsx(vg,{count:x,onScopeToSpam:l.onScopeToSpam}):void 0;return b.some(v=>v.results.length>0)?r.jsxs("div",{className:"flex flex-col",children:[f,d,S,b.filter(v=>v.results.length>0).map(v=>r.jsx(kg,{section:v,query:e,showFolder:y,onSelectResult:o},v.id))]}):r.jsxs("div",{className:"flex flex-col",children:[f,d,S,r.jsxs("div",{className:"px-row-inset py-10 text-center",children:[r.jsxs("p",{className:"text-sm font-medium text-fg",children:["No matches for “",e,"”"]}),r.jsx("p",{className:"mt-1 text-xs text-fg-subtle",children:"Try a different word, or adjust the filters above."})]})]})}function Cg({value:e,onChange:t,onClear:s,onCancel:n,filter:a,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:m,tokens:d,chips:f,onRemoveChip:h,scope:g,makeFilter:y,suggest:p,suggestList:b}){const x=r.jsx(Mc,{value:e,recentSearches:o,onPickRecent:i,sections:l,loading:u,onSelectResult:m,tokens:d,scope:g,makeFilter:y});return r.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(lo,{value:e,onChange:t,onClear:s,chips:f,onRemoveChip:h,globalFocusKey:!1,showClearButton:!1,suggest:p})}),r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(vt,{className:"size-4"}),onClick:n,"aria-label":"Clear and close search",className:"-mr-1 shrink-0"})]}),b,a&&e.trim().length===0?r.jsx(Ml,{...a,children:x}):r.jsx("div",{className:"flex-1 overflow-y-auto",children:x})]})}const jg={queued:{icon:Xa,label:"Queued",className:"text-warning"},sending:{icon:Os,label:"Sending…",className:"text-accent-2",spin:!0},sent:{icon:ic,label:"Sent",className:"text-positive"},failed:{icon:cs,label:"Failed",className:"text-danger"},blocked:{icon:La,label:"Blocked",className:"text-warning"}};function Ci({status:e,iconOnly:t,className:s}){const n=jg[e],a=n.icon;return r.jsxs("span",{className:Y("inline-flex items-center gap-1.5 text-xs font-medium",n.className,s),children:[r.jsx(a,{className:Y("size-4",n.spin&&"animate-spin")}),!t&&n.label]})}const Ng=(e,t)=>t?"bg-accent-2-soft":e==="failed"?"bg-danger-soft":e==="blocked"?"bg-warning/10":"";function Eg({recipients:e,subject:t,time:s,status:n,error:a,selected:o,onSelect:i,onRetry:l,retrying:u,onEdit:m,onDelete:d,deleting:f}){const h=n==="failed"||n==="blocked";return r.jsxs("div",{className:Y("flex items-start gap-3 border-b border-line px-4 py-3 transition-colors hover:bg-surface-raised",Ng(n,o)),children:[r.jsxs("button",{type:"button",...Ma,onClick:i,className:"flex flex-1 min-w-0 items-start gap-3 text-left",children:[r.jsx("div",{className:"mt-0.5 shrink-0",children:r.jsx(Ci,{status:n,iconOnly:!0})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"truncate text-sm font-medium",children:e}),r.jsx("span",{className:"shrink-0 text-xs text-fg-muted",children:s})]}),r.jsx("div",{className:"truncate text-sm",children:t||"No subject"}),r.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[r.jsx(Ci,{status:n}),a&&r.jsxs("span",{className:"truncate text-xs text-fg-muted",children:["— ",a]})]})]})]}),h&&r.jsx("div",{className:"shrink-0",children:r.jsx(Bm,{actions:[...n==="failed"&&l?[{label:"Retry sending",iconOnly:!0,icon:r.jsx(_m,{className:"size-3.5"}),busy:u,onClick:l}]:[],{label:"Edit as draft",iconOnly:!0,icon:r.jsx(cn,{className:"size-3.5"}),onClick:m}],destructive:{label:"Delete message",iconOnly:!0,icon:r.jsx(Et,{className:"size-3.5"}),busy:f,confirm:{prompt:"Delete this message?",confirmLabel:"Delete"},onClick:d}})})]})}const Ig=e=>{const[t,s]=c.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return c.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Tg=({children:e,onRefresh:t,isRefreshing:s})=>Ig("(min-width: 1024px)")?e:r.jsx(Of,{onRefresh:t,isPullable:!s,children:e}),Rg=({text:e,html:t,senderName:s,date:n})=>{const[a,o]=c.useState(!1);if(!e&&!t)return null;const i=[s,n].filter(Boolean).join(" on ");return r.jsxs("div",{className:"mt-2 px-3 pb-2",children:[r.jsxs("button",{type:"button",onClick:()=>o(!a),"aria-expanded":a,className:"flex items-center gap-1 text-xs text-fg-muted hover:text-fg transition-colors",children:[a?r.jsx(Ut,{className:"size-3"}):r.jsx(Ms,{className:"size-3"}),i?`${i} wrote:`:"Show quoted text"]}),a&&r.jsx("blockquote",{className:"mt-2 pl-3 border-l-2 border-fg-subtle/30 text-sm text-fg-muted [&_a]:text-accent [&_a]:underline [&_blockquote]:pl-3 [&_blockquote]:border-l-2 [&_blockquote]:border-fg-subtle/30",children:t?r.jsx("div",{dangerouslySetInnerHTML:{__html:t}}):e.split(`
|
|
75
|
-
`).map((l,u)=>r.jsx("p",{className:"min-h-[1.2em]",children:l},u))})]})},Mg=e=>e===1?"message":"messages";function Ag({count:e,onReview:t,onDismiss:s,actionLabel:n="Review & rescue"}){return r.jsx(ln,{tone:"info",variant:"soft",onDismiss:s,children:r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsxs("p",{className:"flex items-start gap-2 text-sm text-fg",children:[r.jsx(fn,{className:"mt-0.5 size-4 shrink-0 text-positive","aria-hidden":!0}),r.jsxs("span",{children:[r.jsx("span",{className:"font-semibold text-fg",children:`${e} ${Mg(e)} here`})," ","may not be spam — they're from senders we can verify."]})]}),r.jsx(oe,{variant:"primary",size:"sm",onClick:t,className:"self-start",children:n})]})})}function Og({candidate:e,selected:t,onToggle:s,hideSender:n=!1}){const{senderName:a,senderAddress:o,subject:i,snippet:l,trustReason:u,trustSubReason:m,senderTrust:d}=e;return r.jsxs("label",{className:Y("flex w-full cursor-pointer items-start gap-3 px-3 py-2.5 text-left transition-colors",n&&"pl-11",t?"bg-positive/10":"bg-surface hover:bg-surface-sunken"),children:[r.jsx(oo,{className:"mt-0.5",checked:t,onChange:s,"aria-label":`${t?"Deselect":"Select"} ${n?i:`message from ${a}`}`}),!n&&r.jsx(bt,{name:a,email:o,size:"sm"}),r.jsxs("span",{className:"min-w-0 flex-1",children:[!n&&r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"truncate text-sm font-medium text-fg",children:a}),d&&r.jsx(Ic,{senderTrust:d,size:"sm"}),r.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:o})]}),r.jsx("span",{className:"block truncate text-sm text-fg-muted",children:i}),r.jsx("span",{className:"block line-clamp-1 text-xs text-fg-subtle",children:l}),!n&&r.jsxs("span",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[r.jsxs(gt,{tone:"positive",children:[r.jsx(fn,{className:"size-3","aria-hidden":!0}),u]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:m})]})]})]})}const Dg=e=>{const t=new Map,s=[];for(const n of e){const a=(n.senderAddress||n.senderName).toLowerCase(),o=t.get(a);if(o){o.messages.push(n);continue}t.set(a,{key:a,senderName:n.senderName,senderAddress:n.senderAddress,trustReason:n.trustReason,trustSubReason:n.trustSubReason,senderTrust:n.senderTrust,messages:[n]}),s.push(a)}return s.map(n=>t.get(n)).sort((n,a)=>a.messages.length-n.messages.length)},Pg=(e,t)=>{const s=e.messages.filter(n=>t.has(n.id)).length;return s===0?"none":s===e.messages.length?"all":"some"},ji=e=>e===1?"message":"messages";function Lg({group:e,selected:t,onToggleGroup:s,onToggleMessage:n}){const[a,o]=c.useState(!1),i=Pg(e,t),l=e.messages.length,u=a?Ut:Ms;return r.jsxs("div",{className:Y(i!=="none"?"bg-positive/10":"bg-surface"),children:[r.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-2.5",children:[r.jsx(oo,{className:"mt-0.5",checked:i==="all",indeterminate:i==="some",onChange:()=>s(e,i!=="all"),"aria-label":`${i==="all"?"Deselect":"Select"} all ${l} ${ji(l)} from ${e.senderName}`}),r.jsx(bt,{name:e.senderName,email:e.senderAddress,size:"sm"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"truncate text-sm font-medium text-fg",children:e.senderName}),e.senderTrust&&r.jsx(Ic,{senderTrust:e.senderTrust,size:"sm"}),r.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:e.senderAddress})]}),r.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[r.jsxs(gt,{tone:"positive",children:[r.jsx(fn,{className:"size-3","aria-hidden":!0}),e.trustReason]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:e.trustSubReason})]})]}),r.jsxs("button",{type:"button",onClick:()=>o(m=>!m),"aria-expanded":a,className:"flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-2xs text-fg-muted transition-colors hover:bg-surface-sunken hover:text-fg",children:[`${l} ${ji(l)}`,r.jsx(u,{className:"size-3.5","aria-hidden":!0})]})]}),a&&r.jsx("div",{className:"divide-y divide-line border-t border-line",children:e.messages.map(m=>r.jsx(Og,{candidate:m,selected:t.has(m.id),onToggle:()=>n(m.id),hideSender:!0},m.id))})]})}const co=e=>e===1?"message":"messages",Fg=(e,t)=>`Moves ${e===1?"this message":`these ${e} ${co(e)}`} out of Spam to ${t} now. Nothing later.`,ga=(e,t)=>e.find(s=>s.id===t)?.label??"Inbox";function $g(){return r.jsx(ln,{tone:"info",variant:"soft",children:r.jsx("p",{className:"text-2xs text-fg-muted",children:"We list a message here only when we can confirm the sender is who they say — usually someone you've emailed before, write to often, or a service that consistently checks out. We never guess from words in the subject. Anything we can't confirm stays in Spam."})})}function _g({candidates:e,selected:t,onToggle:s,onToggleGroup:n,onSelectAll:a,onSelectNone:o,onContinue:i,onCancel:l}){const[u,m]=c.useState(!1),d=t.size,f=c.useMemo(()=>Dg(e),[e]);return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("h2",{className:"flex items-center gap-2 text-sm font-semibold text-fg",children:[r.jsx(fn,{className:"size-4 text-positive","aria-hidden":!0}),"Rescue from Spam"]}),r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx($m,{className:"size-3.5"}),onClick:()=>m(h=>!h),className:"-mr-1.5 -mt-0.5",children:"Why these?"})]}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"These look safe — from senders we can verify. Uncheck any sender that belongs in Spam, or open a sender to pick individual messages."}),u&&r.jsx("div",{className:"mt-2",children:r.jsx($g,{})})]}),r.jsxs("div",{className:"flex items-center justify-between px-row-inset pb-1.5",children:[r.jsx("span",{className:"text-2xs font-medium text-fg-muted",children:`${d} of ${e.length} selected · ${f.length} ${f.length===1?"sender":"senders"}`}),r.jsxs("span",{className:"flex gap-1",children:[r.jsx(oe,{variant:"ghost",size:"sm",onClick:a,children:"Select all"}),r.jsx(oe,{variant:"ghost",size:"sm",onClick:o,children:"Select none"})]})]}),r.jsx("div",{className:"min-h-0 flex-1 divide-y divide-line overflow-y-auto border-y border-line",children:f.map(h=>r.jsx(Lg,{group:h,selected:t,onToggleGroup:n,onToggleMessage:s},h.key))}),r.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[r.jsx(oe,{variant:"primary",onClick:i,className:"h-11 w-full font-semibold",children:`Continue with ${d} ${co(d)}`}),r.jsx(oe,{variant:"ghost",onClick:l,className:"h-11 w-full",children:"Cancel"})]})]})}function zg({count:e,folders:t,destination:s,onPick:n,onMove:a,onBack:o}){const[i,l]=c.useState(!1);return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[r.jsx("h2",{className:"text-sm font-semibold text-fg",children:"Where should they go?"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Pick a folder, then we move them out of Spam."})]}),r.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-row-inset py-2",children:i?r.jsx("div",{className:"overflow-hidden rounded-xl border border-line bg-surface",children:r.jsx(Al,{mailboxes:t,autoFocus:!0,onSelect:u=>{n(u),l(!1)},onCancel:()=>l(!1)})}):r.jsxs("div",{className:"rounded-xl border border-line bg-surface-sunken p-3",children:[r.jsx("p",{className:"text-2xs text-fg-subtle",children:"Destination"}),r.jsx("p",{className:"mt-0.5 text-sm font-medium text-fg",children:ga(t,s)}),r.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>l(!0),className:"mt-2 px-0",children:"Move to a different folder"})]})}),r.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[r.jsx("p",{className:"text-2xs text-fg-subtle",children:Fg(e,ga(t,s))}),r.jsx(oe,{variant:"primary",onClick:a,className:"h-11 w-full font-semibold",children:`Move ${e} out of Spam`}),r.jsx(oe,{variant:"ghost",onClick:o,className:"h-11 w-full",children:"Back"})]})]})}function Bg({count:e,destinationLabel:t,onClose:s}){return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 px-row-inset py-10 text-center",children:[r.jsx(Zm,{className:"size-10 text-positive","aria-hidden":!0}),r.jsx("p",{className:"text-base font-semibold text-fg",children:`Moved ${e} ${co(e)} out of Spam.`}),r.jsx("p",{className:"text-2xs text-fg-subtle",children:`You'll find them in ${t}.`})]}),r.jsx("div",{className:"border-t border-line bg-surface px-row-inset py-3",children:r.jsx(oe,{variant:"primary",onClick:s,className:"h-11 w-full font-semibold",children:"Done"})})]})}function Kg({open:e,candidates:t,defaultDestinationId:s,availableFolders:n,onConfirmMove:a,onCancel:o}){const[i,l]=c.useState("review"),[u,m]=c.useState(()=>e?new Set(t.map(w=>w.id)):new Set),[d,f]=c.useState(s),[h,g]=c.useState(0),y=c.useRef(!1);c.useEffect(()=>{e&&!y.current&&(l("review"),m(new Set(t.map(w=>w.id))),f(s),g(0)),y.current=e},[e,t,s]);const p=u.size,b=w=>{m(v=>{const C=new Set(v);return C.has(w)?C.delete(w):C.add(w),C})},x=(w,v)=>{m(C=>{const E=new Set(C);for(const I of w.messages)v?E.add(I.id):E.delete(I.id);return E})},S=()=>{const w=Array.from(u);g(w.length),a(w,d),l("done")};return r.jsxs(Um,{open:e,onClose:o,dismissLabel:"Close rescue",children:[i==="review"&&r.jsx(_g,{candidates:t,selected:u,onToggle:b,onToggleGroup:x,onSelectAll:()=>m(new Set(t.map(w=>w.id))),onSelectNone:()=>m(new Set),onContinue:()=>l("destination"),onCancel:o}),i==="destination"&&r.jsx(zg,{count:p,folders:n,destination:d,onPick:f,onMove:S,onBack:()=>l("review")}),i==="done"&&r.jsx(Bg,{count:h,destinationLabel:ga(n,d),onClose:o})]})}const uo=[{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"}],Ac={id:"unread",label:"Unread"},Ug={id:"flagged",label:"Starred"},Oc={id:"attachment",label:"Has attachment"};function qg(e){if(!(e.length<=1))return e.map(t=>({id:t.id,label:t.label,count:t.count,active:t.active}))}function Hg(e=[]){return{categories:[...uo],filters:Df,sources:qg(e)}}function Dc(){return{categories:[...uo],filters:[Ac,Ug,Oc]}}function Wg(){return{categories:[...uo],filters:[Ac,Oc]}}function Vg(e,t){return e.endsWith(t)?e.length===t.length||e[e.length-t.length-1]===".":!1}function Qg(e,t){const s=e.length-t.length-2,n=e.lastIndexOf(".",s);return n===-1?e:e.slice(n+1)}function Gg(e,t,s){if(s.validHosts!==null){const a=s.validHosts;for(const o of a)if(Vg(t,o))return o}let n=0;if(t.startsWith("."))for(;n<t.length&&t[n]===".";)n+=1;return e.length===t.length-n?null:Qg(t,e)}const qr=/[\t\n\r]/g;let xa=!1;function Ni(e){return e>=97&&e<=122||e>=48&&e<=57||e>127||e>=65&&e<=90||e===45||e===95}function Ei(e,t,s){const n=s-t,a=e.charCodeAt(t)|32;if(n===2)return a===119&&(e.charCodeAt(t+1)|32)===115?1:0;if(n===3){const o=e.charCodeAt(t+1)|32,i=e.charCodeAt(t+2)|32;return a===119&&o===115&&i===115||a===102&&o===116&&i===112?1:0}else if(n===4){const o=e.charCodeAt(t+1)|32,i=e.charCodeAt(t+2)|32,l=e.charCodeAt(t+3)|32;return a===104&&o===116&&i===116&&l===112?1:a===102&&o===105&&i===108&&l===101?2:0}else if(n===5)return a===104&&(e.charCodeAt(t+1)|32)===116&&(e.charCodeAt(t+2)|32)===116&&(e.charCodeAt(t+3)|32)===112&&(e.charCodeAt(t+4)|32)===115?1:0;return 0}function Zs(e,t,s=!1){let n=0,a=e.length,o=!1,i=!1;if(xa=!1,!t){if(e.startsWith("data:"))return null;for(;n<e.length&&e.charCodeAt(n)<=32;)n+=1;for(;a>n+1&&e.charCodeAt(a-1)<=32;)a-=1;if(e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47)n+=2;else{const b=e.indexOf(":/",n);if(b!==-1){const x=Ei(e,n,b);if(x===1)for(i=!0,n=b+2;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1;else if(x===2){i=!0,n=b+1;let S=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&S<2;)n+=1,S+=1;if(S<2)return null}else{for(let S=n;S<b;S+=1){const w=e.charCodeAt(S)|32;if(!(w>=97&&w<=122||w>=48&&w<=57||w===46||w===45||w===43)){const v=e.charCodeAt(S);return v===9||v===10||v===13?Zs(e.replace(qr,""),t,s):null}}if(e.charCodeAt(b+2)===47)n=b+3;else return null}}else if(e.charCodeAt(n)!==91){let x=-1;for(let S=n;S<a;S+=1){const w=e.charCodeAt(S);if(w===9||w===10||w===13)return Zs(e.replace(qr,""),t,s);if(w===58){x=S;break}if(w===47||w===92||w===63||w===35)break}if(x!==-1){let S=!1;for(let w=x+1;w<a;w+=1){const v=e.charCodeAt(w);if(v===47||v===92||v===63||v===35)break;if(v===64){S=!0;break}}if(!S){let w=!0,v=x+1;for(;v<a;v+=1){const C=e.charCodeAt(v);if(C===47||C===92||C===63||C===35)break;if(C<48||C>57){w=!1;break}}if(v===x+1&&(w=!1),!w){const C=Ei(e,n,x);if(C===0){let E=!1;for(let I=x+1;I<a;I+=1){const N=e.charCodeAt(I);if(N===47||N===92||N===63||N===35)break;if(N===58){E=!0;break}}if(!E)return null}else if(i=!0,n=x+1,C===2){let E=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&E<2;)n+=1,E+=1;if(E<2)return null}else for(;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1}}}}}let u=-1,m=-1,d=-1,f=-1,h=!1,g=s,y=n-1,p=-1;if(s&&n<a){const b=e.charCodeAt(n);(!(Ni(b)||b===46||b===95)||b===45)&&(g=!1)}for(let b=n;b<a;b+=1){const x=e.charCodeAt(b);if(x<64)if(x===47||x===35||x===63){a=b;break}else x===58?(f===-1&&(f=b),d=b):x===9||x===10||x===13?h=!0:s&&(x===46?((b-y>64||p===46||p===45)&&(g=!1),y=b):(x<48||x>57)&&(x!==45||p===46)&&(g=!1));else if(i&&x===92){a=b;break}else x===64?(u=b,f=-1):x===93?m=b:x>=65&&x<=90?o=!0:s&&!Ni(x)&&(g=!1);s&&(p=x)}if(h)return Zs(e.replace(qr,""),t,s);if(u!==-1&&u>=n&&u<a&&(n=u+1),e.charCodeAt(n)===91)return m!==-1?e.slice(n+1,m).toLowerCase():null;if(d!==-1&&d>n&&d<a&&f===d&&(a=d),n>=a)return null;s&&g&&u===-1&&d===-1&&m===-1&&e.charCodeAt(a-1)!==46&&a-n<=255&&a-y-1<=63&&p!==45&&(xa=!0)}for(;a>n+1&&e.charCodeAt(a-1)===46;)a-=1;const l=n!==0||a!==e.length?e.slice(n,a):e;return o?l.toLowerCase():l}function Yg(e){if(e.length<7||e.length>15)return!1;let t=0;for(let s=0;s<e.length;s+=1){const n=e.charCodeAt(s);if(n===46)t+=1;else if(n<48||n>57)return!1}return t===3&&e.charCodeAt(0)!==46&&e.charCodeAt(e.length-1)!==46}function Xg(e){if(e.length<3)return!1;let t=e.startsWith("[")?1:0,s=e.length;if(e[s-1]==="]"&&(s-=1),s-t>39)return!1;let n=!1;for(;t<s;t+=1){const a=e.charCodeAt(t);if(a===58)n=!0;else if(!(a>=48&&a<=57||a>=97&&a<=102||a>=65&&a<=70))return!1}return n}function Jg(e){return Xg(e)||Yg(e)}function Ii(e){return e>=97&&e<=122||e>=48&&e<=57||e>127}function Ti(e){if(e.length>255||e.length===0||!Ii(e.charCodeAt(0))&&e.charCodeAt(0)!==46&&e.charCodeAt(0)!==95)return!1;let t=-1,s=-1;const n=e.length;for(let a=0;a<n;a+=1){const o=e.charCodeAt(a);if(o===46){if(a-t>64||s===46||s===45)return!1;t=a}else if(!(Ii(o)||o===45||o===95)||o===45&&s===46)return!1;s=o}return n-t-1<=63&&s!==45}function Zg({allowIcannDomains:e=!0,allowPrivateDomains:t=!1,detectIp:s=!0,detectSpecialUse:n=!1,extractHostname:a=!0,mixedInputs:o=!0,validHosts:i=null,validateHostname:l=!0}){return{allowIcannDomains:e,allowPrivateDomains:t,detectIp:s,detectSpecialUse:n,extractHostname:a,mixedInputs:o,validHosts:i,validateHostname:l}}const ex=Zg({});function tx(e){return ex}function sx(){return{domain:null,domainWithoutSuffix:null,hostname:null,isIcann:null,isIp:null,isPrivate:null,isSpecialUse:null,publicSuffix:null,subdomain:null}}function nx(e){e.domain=null,e.domainWithoutSuffix=null,e.hostname=null,e.isIcann=null,e.isIp=null,e.isPrivate=null,e.isSpecialUse=null,e.publicSuffix=null,e.subdomain=null}function rx(e,t,s,n,a){const o=tx();if(typeof e!="string")return a;let i=!1;return o.extractHostname?o.mixedInputs?(i=Ti(e),a.hostname=Zs(e,i,o.validateHostname)):a.hostname=Zs(e,!1,o.validateHostname):a.hostname=e,o.detectIp&&a.hostname!==null&&(a.isIp=Jg(a.hostname),a.isIp)?a:o.validateHostname&&o.extractHostname&&a.hostname!==null&&!(i&&a.hostname===e)&&!xa&&!Ti(a.hostname)?(a.hostname=null,a):(a.hostname===null||(s(a.hostname,o,a),a.publicSuffix===null)||(a.domain=Gg(a.publicSuffix,a.hostname,o)),a)}const Ri=sx();function ax(e,t){return nx(Ri),rx(e,3,Pf,t,Ri).domain}const mr=e=>{const t=new Set,s=[];for(const n of e){const a=n.trim();if(a==="")continue;const o=a.toLowerCase();t.has(o)||(t.add(o),s.push(a))}return s},ox=e=>{const t=e.lastIndexOf("@");return t>=0?e.slice(t+1):e},Pc=e=>ax(ox(e.trim())),ix=e=>{const t=mr(e);if(t.length<2)return null;let s=null;for(const n of t){const a=Pc(n);if(a===null)return null;if(s===null)s=a;else if(s!==a)return null}return s},hr=e=>{const t=ix(e);return t!==null?[{field:"FromDomain",value:t}]:mr(e).map(s=>({field:"From",value:s}))},lx=e=>{const t=new Map;for(const a of e){const o=a.normalizedEmail.trim().toLowerCase();if(o==="")continue;const i=t.get(o);i?i.count+=1:t.set(o,{sender:a,count:1})}let s,n=0;for(const{sender:a,count:o}of t.values())o<=n||(s=a,n=o);return s},Lc=e=>e.displayName?.trim()||e.normalizedEmail,cx=/^\s*(?:(?:re|aw|fwd?|vs|sv|antw|res|enc|tr)\s*(?:\[\d+\])?\s*:|\[[^\]]{1,32}\])\s*/i,ux=e=>{let t=e.replace(/\s+/g," ").trim();for(;;){const s=t.replace(cx,"");if(s===t)return t.trim();t=s}},dx=new Set(["a","an","and","are","as","at","be","by","for","from","has","have","in","is","it","me","my","new","of","on","or","our","the","this","to","was","we","with","you","your"]),fx=3,Hr=e=>e.split(" ").filter(t=>t!==""),Mi=e=>e.length===0||e.join(" ").length<fx?!1:e.some(t=>!dx.has(t.toLowerCase())),mx=(e,t)=>e.findIndex((s,n)=>t.every((a,o)=>e[n+o]?.toLowerCase()===a.toLowerCase())),hx=e=>{const t=e.map(ux).filter(o=>o!=="");if(t.length===0)return;const[s,...n]=t;if(n.length===0)return Mi(Hr(s))?s:void 0;const a=Hr(s);for(let o=a.length;o>0;o-=1)for(let i=0;i+o<=a.length;i+=1){const l=a.slice(i,i+o);if(Mi(l)&&n.every(u=>mx(Hr(u),l)>=0))return l.join(" ")}},px=(e,t)=>{const s=hr(e);if(mr(e).length===1||s.length===1&&s[0].field==="FromDomain")return s;const n=hx(t);return n!==void 0?[{field:"Subject",value:n}]:s},gx=({match:e,sender:t,folder:s})=>{const n=e??t;return n?s?`${n} → ${s}`:e?`Mail matching ${e}`:`Mail from ${n}`:s?`Mail to ${s}`:""},xx=e=>e.clauses.length>0,bx=e=>({scopedOutFolder:e.scopedOut?.label,droppedFacets:e.droppedFacets.map(t=>t.label),droppedSemantic:e.droppedSemantic});function Kt(e,t,{checkForDefaultPrevented:s=!0}={}){return function(a){if(e?.(a),s===!1||!a||!a.defaultPrevented)return t?.(a)}}function Ai(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function vx(...e){return t=>{let s=!1;const n=e.map(a=>{const o=Ai(a,t);return!s&&typeof o=="function"&&(s=!0),o});if(s)return()=>{for(let a=0;a<n.length;a++){const o=n[a];typeof o=="function"?o():Ai(e[a],null)}}}}function fs(...e){return c.useCallback(vx(...e),e)}function yx(e,t=[]){let s=[];function n(o,i){const l=c.createContext(i);l.displayName=o+"Context";const u=s.length;s=[...s,i];const m=f=>{const{scope:h,children:g,...y}=f,p=h?.[e]?.[u]||l,b=c.useMemo(()=>y,Object.values(y));return r.jsx(p.Provider,{value:b,children:g})};m.displayName=o+"Provider";function d(f,h,g={}){const{optional:y=!1}=g,p=h?.[e]?.[u]||l,b=c.useContext(p);if(b)return b;if(i!==void 0)return i;if(!y)throw new Error(`\`${f}\` must be used within \`${o}\``)}return[m,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,[n,wx(a,...t)]}function wx(...e){const t=e[0];if(e.length===1)return t;const s=()=>{const n=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(o){const i=n.reduce((l,{useScope:u,scopeName:m})=>{const f=u(o)[`__scope${m}`];return{...l,...f}},{});return c.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return s.scopeName=t.scopeName,s}var nn=globalThis?.document?c.useLayoutEffect:()=>{},Sx=Fa[" useInsertionEffect ".trim().toString()]||nn;function kx({prop:e,defaultProp:t,onChange:s=()=>{},caller:n}){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 f=d.current;f!==l&&console.warn(`${n} is changing from ${f?"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,n])}const m=c.useCallback(d=>{if(l){const f=jx(d)?d(e):d;f!==e&&i.current?.(f)}else o(d)},[l,e,o,i]);return[u,m]}function Cx({defaultProp:e,onChange:t}){const[s,n]=c.useState(e),a=c.useRef(s),o=c.useRef(t);return Sx(()=>{o.current=t},[t]),c.useEffect(()=>{a.current!==s&&(o.current?.(s),a.current=s)},[s,a]),[s,n,o]}function jx(e){return typeof e=="function"}function fo(e){const t=c.forwardRef((s,n)=>{let{children:a,...o}=s,i=null,l=!1;const u=[];Oi(a)&&typeof jn=="function"&&(a=jn(a._payload)),c.Children.forEach(a,h=>{if(Rx(h)){l=!0;const g=h;let y="child"in g.props?g.props.child:g.props.children;Oi(y)&&typeof jn=="function"&&(y=jn(y._payload)),i=Ex(g,y),u.push(i?.props?.children)}else u.push(h)}),i?i=c.cloneElement(i,void 0,u):!l&&c.Children.count(a)===1&&c.isValidElement(a)&&(i=a);const m=i?Tx(i):void 0,d=fs(n,m);if(!i){if(a||a===0)throw new Error(l?Dx(e):Ox(e));return a}const f=Ix(o,i.props??{});return i.type!==c.Fragment&&(f.ref=n?d:m),c.cloneElement(i,f)});return t.displayName=`${e}.Slot`,t}var hj=fo("Slot"),Nx=Symbol.for("radix.slottable"),Ex=(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 Ix(e,t){const s={...t};for(const n in t){const a=e[n],o=t[n];/^on[A-Z]/.test(n)?a&&o?s[n]=(...l)=>{const u=o(...l);return a(...l),u}:a&&(s[n]=a):n==="style"?s[n]={...a,...o}:n==="className"&&(s[n]=[a,o].filter(Boolean).join(" "))}return{...e,...s}}function Tx(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 Rx(e){return c.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Nx}var Mx=Symbol.for("react.lazy");function Oi(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Mx&&"_payload"in e&&Ax(e._payload)}function Ax(e){return typeof e=="object"&&e!==null&&"then"in e}var Ox=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,Dx=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,jn=Fa[" use ".trim().toString()],Px=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Tt=Px.reduce((e,t)=>{const s=fo(`Primitive.${t}`),n=c.forwardRef((a,o)=>{const{asChild:i,...l}=a,u=i?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),r.jsx(u,{...l,ref:o})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function Lx(e,t){e&&$a.flushSync(()=>e.dispatchEvent(t))}function rn(e){const t=c.useRef(e);return c.useEffect(()=>{t.current=e}),c.useMemo(()=>((...s)=>t.current?.(...s)),[])}var Fx="DismissableLayer",ba="dismissableLayer.update",$x="dismissableLayer.pointerDownOutside",_x="dismissableLayer.focusOutside",Di,mo=c.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Fc=c.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:n=!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:l,onDismiss:u,...m}=e,d=c.useContext(mo),[f,h]=c.useState(null),g=f?.ownerDocument??globalThis?.document,[,y]=c.useState({}),p=fs(t,h),b=Array.from(d.layers),[x]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),S=x?b.indexOf(x):-1,w=f?b.indexOf(f):-1,v=d.layersWithOutsidePointerEventsDisabled.size>0,C=w>=S,E=c.useRef(!1),I=qx(O=>{o?.(O),l?.(O),O.defaultPrevented||u?.()},{ownerDocument:g,deferPointerDownOutside:n,isDeferredPointerDownOutsideRef:E,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:c.useCallback(O=>{if(!(O instanceof Node))return!1;const L=[...d.branches].some(M=>M.contains(O));return C&&!L},[d.branches,C])}),N=Hx(O=>{if(n&&E.current)return;const L=O.target;[...d.branches].some(k=>k.contains(L))||(i?.(O),l?.(O),O.defaultPrevented||u?.())},g),D=f?w===b.length-1:!1,A=rn(O=>{O.key==="Escape"&&(a?.(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))});return c.useEffect(()=>{if(D)return g.addEventListener("keydown",A,{capture:!0}),()=>g.removeEventListener("keydown",A,{capture:!0})},[g,D,A]),c.useEffect(()=>{if(f)return s&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Di=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(f)),d.layers.add(f),Pi(),()=>{s&&(d.layersWithOutsidePointerEventsDisabled.delete(f),d.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=Di))}},[f,g,s,d]),c.useEffect(()=>()=>{f&&(d.layers.delete(f),d.layersWithOutsidePointerEventsDisabled.delete(f),Pi())},[f,d]),c.useEffect(()=>{const O=()=>y({});return document.addEventListener(ba,O),()=>document.removeEventListener(ba,O)},[]),r.jsx(Tt.div,{...m,ref:p,style:{pointerEvents:v?C?"auto":"none":void 0,...e.style},onFocusCapture:Kt(e.onFocusCapture,N.onFocusCapture),onBlurCapture:Kt(e.onBlurCapture,N.onBlurCapture),onPointerDownCapture:Kt(e.onPointerDownCapture,I.onPointerDownCapture)})});Fc.displayName=Fx;var zx="DismissableLayerBranch",Bx=c.forwardRef((e,t)=>{const s=c.useContext(mo),n=c.useRef(null),a=fs(t,n);return c.useEffect(()=>{const o=n.current;if(o)return s.branches.add(o),()=>{s.branches.delete(o)}},[s.branches]),r.jsx(Tt.div,{...e,ref:a})});Bx.displayName=zx;function Kx(){const e=c.useContext(mo),[t,s]=c.useState(null);return c.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),s}var Ux=()=>!0;function qx(e,t){const{ownerDocument:s=globalThis?.document,deferPointerDownOutside:n=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:o,shouldHandlePointerDownOutside:i=Ux}=t,l=rn(e),u=c.useRef(!1),m=c.useRef(!1),d=c.useRef(new Map),f=c.useRef(()=>{});return c.useEffect(()=>{function h(){m.current=!1,a.current=!1,d.current.clear()}function g(){return Array.from(d.current.values()).some(Boolean)}function y(w){if(!m.current)return;const v=w.target;v instanceof Node&&[...o].some(E=>E.contains(v))||d.current.set(w.type,!0),w.type==="click"&&window.setTimeout(()=>{m.current&&f.current()},0)}function p(w){m.current&&d.current.set(w.type,!1)}const b=w=>{if(w.target&&!u.current){let v=function(){s.removeEventListener("click",f.current);const E=g();h(),E||$c($x,l,C,{discrete:!0})};if(!i(w.target)){s.removeEventListener("click",f.current),h(),u.current=!1;return}const C={originalEvent:w};m.current=!0,a.current=n&&w.button===0,d.current.clear(),!n||w.button!==0?v():(s.removeEventListener("click",f.current),f.current=v,s.addEventListener("click",f.current,{once:!0}))}else s.removeEventListener("click",f.current),h();u.current=!1},x=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const w of x)s.addEventListener(w,y,!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",f.current);for(const w of x)s.removeEventListener(w,y,!0),s.removeEventListener(w,p)}},[s,l,n,a,o,i]),{onPointerDownCapture:()=>u.current=!0}}function Hx(e,t=globalThis?.document){const s=rn(e),n=c.useRef(!1);return c.useEffect(()=>{const a=o=>{o.target&&!n.current&&$c(_x,s,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,s]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function Pi(){const e=new CustomEvent(ba);document.dispatchEvent(e)}function $c(e,t,s,{discrete:n}){const a=s.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:s});t&&a.addEventListener(e,t,{once:!0}),n?Lx(a,o):a.dispatchEvent(o)}var Nn=0,xs=null;function Wx(){c.useEffect(()=>{xs||(xs={start:Li(),end:Li()});const{start:e,end:t}=xs;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Nn++,()=>{Nn===1&&(xs?.start.remove(),xs?.end.remove(),xs=null),Nn=Math.max(0,Nn-1)}},[])}function Li(){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 Wr="focusScope.autoFocusOnMount",Vr="focusScope.autoFocusOnUnmount",Fi={bubbles:!1,cancelable:!0},Vx="FocusScope",_c=c.forwardRef((e,t)=>{const{loop:s=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[l,u]=c.useState(null),m=rn(a),d=rn(o),f=c.useRef(null),h=fs(t,u),g=c.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;c.useEffect(()=>{if(n){let p=function(w){if(g.paused||!l)return;const v=w.target;l.contains(v)?f.current=v:$t(f.current,{select:!0})},b=function(w){if(g.paused||!l)return;const v=w.relatedTarget;v!==null&&(l.contains(v)||$t(f.current,{select:!0}))},x=function(w){if(document.activeElement===document.body)for(const C of w)C.removedNodes.length>0&&$t(l)};document.addEventListener("focusin",p),document.addEventListener("focusout",b);const S=new MutationObserver(x);return l&&S.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",b),S.disconnect()}}},[n,l,g.paused]),c.useEffect(()=>{if(l){_i.add(g);const p=document.activeElement;if(!l.contains(p)){const x=new CustomEvent(Wr,Fi);l.addEventListener(Wr,m),l.dispatchEvent(x),x.defaultPrevented||(Qx(Zx(zc(l)),{select:!0}),document.activeElement===p&&$t(l))}return()=>{l.removeEventListener(Wr,m),setTimeout(()=>{const x=new CustomEvent(Vr,Fi);l.addEventListener(Vr,d),l.dispatchEvent(x),x.defaultPrevented||$t(p??document.body,{select:!0}),l.removeEventListener(Vr,d),_i.remove(g)},0)}}},[l,m,d,g]);const y=c.useCallback(p=>{if(!s&&!n||g.paused)return;const b=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,x=document.activeElement;if(b&&x){const S=p.currentTarget,[w,v]=Gx(S);w&&v?!p.shiftKey&&x===v?(p.preventDefault(),s&&$t(w,{select:!0})):p.shiftKey&&x===w&&(p.preventDefault(),s&&$t(v,{select:!0})):x===S&&p.preventDefault()}},[s,n,g.paused]);return r.jsx(Tt.div,{tabIndex:-1,...i,ref:h,onKeyDown:y})});_c.displayName=Vx;function Qx(e,{select:t=!1}={}){const s=document.activeElement;for(const n of e)if($t(n,{select:t}),document.activeElement!==s)return}function Gx(e){const t=zc(e),s=$i(t,e),n=$i(t.reverse(),e);return[s,n]}function zc(e){const t=[],s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const a=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||a?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)t.push(s.currentNode);return t}function $i(e,t){const s=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const n of e)if(!(s?!n.checkVisibility({checkVisibilityCSS:!0}):Yx(n,{upTo:t})))return n}function Yx(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 Xx(e){return e instanceof HTMLInputElement&&"select"in e}function $t(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&Xx(e)&&t&&e.select()}}var _i=Jx();function Jx(){let e=[];return{add(t){const s=e[0];t!==s&&s?.pause(),e=zi(e,t),e.unshift(t)},remove(t){e=zi(e,t),e[0]?.resume()}}}function zi(e,t){const s=[...e],n=s.indexOf(t);return n!==-1&&s.splice(n,1),s}function Zx(e){return e.filter(t=>t.tagName!=="A")}var eb=Fa[" useId ".trim().toString()]||(()=>{}),tb=0;function Qr(e){const[t,s]=c.useState(eb());return nn(()=>{s(n=>n??String(tb++))},[e]),e||(t?`radix-${t}`:"")}var sb="Portal",Bc=c.forwardRef((e,t)=>{const{container:s,...n}=e,[a,o]=c.useState(!1);nn(()=>o(!0),[]);const i=s||a&&globalThis?.document?.body;return i?$a.createPortal(r.jsx(Tt.div,{...n,ref:t}),i):null});Bc.displayName=sb;function nb(e,t){return c.useReducer((s,n)=>t[s][n]??s,e)}var pr=e=>{const{present:t,children:s}=e,n=rb(t),a=typeof s=="function"?s({present:n.isPresent}):c.Children.only(s),o=ab(n.ref,ob(a));return typeof s=="function"||n.isPresent?c.cloneElement(a,{ref:o}):null};pr.displayName="Presence";function rb(e){const[t,s]=c.useState(),n=c.useRef(null),a=c.useRef(e),o=c.useRef("none"),i=c.useRef(void 0),l=e?"mounted":"unmounted",[u,m]=nb(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??Hs(n.current),i.current=void 0):o.current="none"},[u]),nn(()=>{const d=n.current,f=a.current;if(f!==e){const g=o.current,y=Hs(d);e?(i.current=y,m("MOUNT")):y==="none"||d?.display==="none"?m("UNMOUNT"):m(f&&g!==y?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,m]),nn(()=>{if(t){let d;const f=t.ownerDocument.defaultView??window,h=y=>{const b=Hs(n.current).includes(CSS.escape(y.animationName));if(y.target===t&&b&&(m("ANIMATION_END"),!a.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",d=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},g=y=>{y.target===t&&(o.current=Hs(n.current))};return t.addEventListener("animationstart",g),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{f.clearTimeout(d),t.removeEventListener("animationstart",g),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:c.useCallback(d=>{if(d){const f=getComputedStyle(d);n.current=f,i.current=Hs(f)}else n.current=null;s(d)},[])}}function Bi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ab(...e){const t=c.useRef(e);return t.current=e,c.useCallback(s=>{const n=t.current;let a=!1;const o=n.map(i=>{const l=Bi(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():Bi(n[i],null)}}},[])}function Hs(e){return e?.animationName||"none"}function ob(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 ib=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},bs=new WeakMap,En=new WeakMap,In={},Gr=0,Kc=function(e){return e&&(e.host||Kc(e.parentNode))},lb=function(e,t){return t.map(function(s){if(e.contains(s))return s;var n=Kc(s);return n&&e.contains(n)?n:(console.error("aria-hidden",s,"in not contained inside",e,". Doing nothing"),null)}).filter(function(s){return!!s})},cb=function(e,t,s,n){var a=lb(t,Array.isArray(e)?e:[e]);In[s]||(In[s]=new WeakMap);var o=In[s],i=[],l=new Set,u=new Set(a),m=function(f){!f||l.has(f)||(l.add(f),m(f.parentNode))};a.forEach(m);var d=function(f){!f||u.has(f)||Array.prototype.forEach.call(f.children,function(h){if(l.has(h))d(h);else try{var g=h.getAttribute(n),y=g!==null&&g!=="false",p=(bs.get(h)||0)+1,b=(o.get(h)||0)+1;bs.set(h,p),o.set(h,b),i.push(h),p===1&&y&&En.set(h,!0),b===1&&h.setAttribute(s,"true"),y||h.setAttribute(n,"true")}catch(x){console.error("aria-hidden: cannot operate on ",h,x)}})};return d(t),l.clear(),Gr++,function(){i.forEach(function(f){var h=bs.get(f)-1,g=o.get(f)-1;bs.set(f,h),o.set(f,g),h||(En.has(f)||f.removeAttribute(n),En.delete(f)),g||f.removeAttribute(s)}),Gr--,Gr||(bs=new WeakMap,bs=new WeakMap,En=new WeakMap,In={})}},ub=function(e,t,s){s===void 0&&(s="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),a=ib(e);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live], script"))),cb(n,a,s,"aria-hidden")):function(){return null}},Fn="right-scroll-bar-position",$n="width-before-scroll-bar",db="with-scroll-bars-hidden",fb="--removed-body-scroll-bar-size";function Yr(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function mb(e,t){var s=c.useState(function(){return{value:e,callback:t,facade:{get current(){return s.value},set current(n){var a=s.value;a!==n&&(s.value=n,s.callback(n,a))}}}})[0];return s.callback=t,s.facade}var hb=typeof window<"u"?c.useLayoutEffect:c.useEffect,Ki=new WeakMap;function pb(e,t){var s=mb(null,function(n){return e.forEach(function(a){return Yr(a,n)})});return hb(function(){var n=Ki.get(s);if(n){var a=new Set(n),o=new Set(e),i=s.current;a.forEach(function(l){o.has(l)||Yr(l,null)}),o.forEach(function(l){a.has(l)||Yr(l,i)})}Ki.set(s,e)},[e]),s}function gb(e){return e}function xb(e,t){t===void 0&&(t=gb);var s=[],n=!1,a={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return s.length?s[s.length-1]:e},useMedium:function(o){var i=t(o,n);return s.push(i),function(){s=s.filter(function(l){return l!==i})}},assignSyncMedium:function(o){for(n=!0;s.length;){var i=s;s=[],i.forEach(o)}s={push:function(l){return o(l)},filter:function(){return s}}},assignMedium:function(o){n=!0;var i=[];if(s.length){var l=s;s=[],l.forEach(o),i=s}var u=function(){var d=i;i=[],d.forEach(o)},m=function(){return Promise.resolve().then(u)};m(),s={push:function(d){i.push(d),m()},filter:function(d){return i=i.filter(d),s}}}};return a}function bb(e){e===void 0&&(e={});var t=xb(null);return t.options=_t({async:!0,ssr:!1},e),t}var Uc=function(e){var t=e.sideCar,s=Ol(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return c.createElement(n,_t({},s))};Uc.isSideCarExport=!0;function vb(e,t){return e.useMedium(t),Uc}var qc=bb(),Xr=function(){},gr=c.forwardRef(function(e,t){var s=c.useRef(null),n=c.useState({onScrollCapture:Xr,onWheelCapture:Xr,onTouchMoveCapture:Xr}),a=n[0],o=n[1],i=e.forwardProps,l=e.children,u=e.className,m=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,g=e.noRelative,y=e.noIsolation,p=e.inert,b=e.allowPinchZoom,x=e.as,S=x===void 0?"div":x,w=e.gapMode,v=Ol(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=h,E=pb([s,t]),I=_t(_t({},v),a);return c.createElement(c.Fragment,null,d&&c.createElement(C,{sideCar:qc,removeScrollBar:m,shards:f,noRelative:g,noIsolation:y,inert:p,setCallbacks:o,allowPinchZoom:!!b,lockRef:s,gapMode:w}),i?c.cloneElement(c.Children.only(l),_t(_t({},I),{ref:E})):c.createElement(S,_t({},I,{className:u,ref:E}),l))});gr.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};gr.classNames={fullWidth:$n,zeroRight:Fn};var yb=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function wb(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=yb();return t&&e.setAttribute("nonce",t),e}function Sb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function kb(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=wb())&&(Sb(t,s),kb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},jb=function(){var e=Cb();return function(t,s){c.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},Hc=function(){var e=jb(),t=function(s){var n=s.styles,a=s.dynamic;return e(n,a),null};return t},Nb={left:0,top:0,right:0,gap:0},Jr=function(e){return parseInt(e||"",10)||0},Eb=function(e){var t=window.getComputedStyle(document.body),s=t[e==="padding"?"paddingLeft":"marginLeft"],n=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return[Jr(s),Jr(n),Jr(a)]},Ib=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Nb;var t=Eb(e),s=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-s+t[2]-t[0])}},Tb=Hc(),Is="data-scroll-locked",Rb=function(e,t,s,n){var a=e.left,o=e.top,i=e.right,l=e.gap;return s===void 0&&(s="margin"),`
|
|
76
|
-
.`.concat(db,` {
|
|
77
|
-
overflow: hidden `).concat(n,`;
|
|
78
|
-
padding-right: `).concat(l,"px ").concat(n,`;
|
|
79
|
-
}
|
|
80
|
-
body[`).concat(Is,`] {
|
|
81
|
-
overflow: hidden `).concat(n,`;
|
|
82
|
-
overscroll-behavior: contain;
|
|
83
|
-
`).concat([t&&"position: relative ".concat(n,";"),s==="margin"&&`
|
|
84
|
-
padding-left: `.concat(a,`px;
|
|
85
|
-
padding-top: `).concat(o,`px;
|
|
86
|
-
padding-right: `).concat(i,`px;
|
|
87
|
-
margin-left:0;
|
|
88
|
-
margin-top:0;
|
|
89
|
-
margin-right: `).concat(l,"px ").concat(n,`;
|
|
90
|
-
`),s==="padding"&&"padding-right: ".concat(l,"px ").concat(n,";")].filter(Boolean).join(""),`
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
.`).concat(Fn,` {
|
|
94
|
-
right: `).concat(l,"px ").concat(n,`;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
.`).concat($n,` {
|
|
98
|
-
margin-right: `).concat(l,"px ").concat(n,`;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
.`).concat(Fn," .").concat(Fn,` {
|
|
102
|
-
right: 0 `).concat(n,`;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
.`).concat($n," .").concat($n,` {
|
|
106
|
-
margin-right: 0 `).concat(n,`;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
body[`).concat(Is,`] {
|
|
110
|
-
`).concat(fb,": ").concat(l,`px;
|
|
111
|
-
}
|
|
112
|
-
`)},Ui=function(){var e=parseInt(document.body.getAttribute(Is)||"0",10);return isFinite(e)?e:0},Mb=function(){c.useEffect(function(){return document.body.setAttribute(Is,(Ui()+1).toString()),function(){var e=Ui()-1;e<=0?document.body.removeAttribute(Is):document.body.setAttribute(Is,e.toString())}},[])},Ab=function(e){var t=e.noRelative,s=e.noImportant,n=e.gapMode,a=n===void 0?"margin":n;Mb();var o=c.useMemo(function(){return Ib(a)},[a]);return c.createElement(Tb,{styles:Rb(o,!t,a,s?"":"!important")})},va=!1;if(typeof window<"u")try{var Tn=Object.defineProperty({},"passive",{get:function(){return va=!0,!0}});window.addEventListener("test",Tn,Tn),window.removeEventListener("test",Tn,Tn)}catch{va=!1}var vs=va?{passive:!1}:!1,Ob=function(e){return e.tagName==="TEXTAREA"},Wc=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!Ob(e)&&s[t]==="visible")},Db=function(e){return Wc(e,"overflowY")},Pb=function(e){return Wc(e,"overflowX")},qi=function(e,t){var s=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=Vc(e,n);if(a){var o=Qc(e,n),i=o[1],l=o[2];if(i>l)return!0}n=n.parentNode}while(n&&n!==s.body);return!1},Lb=function(e){var t=e.scrollTop,s=e.scrollHeight,n=e.clientHeight;return[t,s,n]},Fb=function(e){var t=e.scrollLeft,s=e.scrollWidth,n=e.clientWidth;return[t,s,n]},Vc=function(e,t){return e==="v"?Db(t):Pb(t)},Qc=function(e,t){return e==="v"?Lb(t):Fb(t)},$b=function(e,t){return e==="h"&&t==="rtl"?-1:1},_b=function(e,t,s,n,a){var o=$b(e,window.getComputedStyle(t).direction),i=o*n,l=s.target,u=t.contains(l),m=!1,d=i>0,f=0,h=0;do{if(!l)break;var g=Qc(e,l),y=g[0],p=g[1],b=g[2],x=p-b-o*y;(y||x)&&Vc(e,l)&&(f+=x,h+=y);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(f)<1||!d&&Math.abs(h)<1)&&(m=!0),m},Rn=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Hi=function(e){return[e.deltaX,e.deltaY]},Wi=function(e){return e&&"current"in e?e.current:e},zb=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Bb=function(e){return`
|
|
113
|
-
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
114
|
-
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
115
|
-
`)},Kb=0,ys=[];function Ub(e){var t=c.useRef([]),s=c.useRef([0,0]),n=c.useRef(),a=c.useState(Kb++)[0],o=c.useState(Hc)[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=Lf([e.lockRef.current],(e.shards||[]).map(Wi),!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 x=Rn(p),S=s.current,w="deltaX"in p?p.deltaX:S[0]-x[0],v="deltaY"in p?p.deltaY:S[1]-x[1],C,E=p.target,I=Math.abs(w)>Math.abs(v)?"h":"v";if("touches"in p&&I==="h"&&E.type==="range")return!1;var N=window.getSelection(),D=N&&N.anchorNode,A=D?D===E||D.contains(E):!1;if(A)return!1;var O=qi(I,E);if(!O)return!0;if(O?C=I:(C=I==="v"?"h":"v",O=qi(I,E)),!O)return!1;if(!n.current&&"changedTouches"in p&&(w||v)&&(n.current=C),!C)return!0;var L=n.current||C;return _b(L,b,p,L==="h"?w:v)},[]),u=c.useCallback(function(p){var b=p;if(!(!ys.length||ys[ys.length-1]!==o)){var x="deltaY"in b?Hi(b):Rn(b),S=t.current.filter(function(C){return C.name===b.type&&(C.target===b.target||b.target===C.shadowParent)&&zb(C.delta,x)})[0];if(S&&S.should){b.cancelable&&b.preventDefault();return}if(!S){var w=(i.current.shards||[]).map(Wi).filter(Boolean).filter(function(C){return C.contains(b.target)}),v=w.length>0?l(b,w[0]):!i.current.noIsolation;v&&b.cancelable&&b.preventDefault()}}},[]),m=c.useCallback(function(p,b,x,S){var w={name:p,delta:b,target:x,should:S,shadowParent:qb(x)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(v){return v!==w})},1)},[]),d=c.useCallback(function(p){s.current=Rn(p),n.current=void 0},[]),f=c.useCallback(function(p){m(p.type,Hi(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){m(p.type,Rn(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return ys.push(o),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",u,vs),document.addEventListener("touchmove",u,vs),document.addEventListener("touchstart",d,vs),function(){ys=ys.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,vs),document.removeEventListener("touchmove",u,vs),document.removeEventListener("touchstart",d,vs)}},[]);var g=e.removeScrollBar,y=e.inert;return c.createElement(c.Fragment,null,y?c.createElement(o,{styles:Bb(a)}):null,g?c.createElement(Ab,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function qb(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Hb=vb(qc,Ub);var Gc=c.forwardRef(function(e,t){return c.createElement(gr,_t({},e,{ref:t,sideCar:Hb}))});Gc.classNames=gr.classNames;var Wb=class extends _a{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,n=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:l}=n,u=s.fetchMeta?.fetchMore?.direction,m=i&&u==="forward",d=a&&u==="forward",f=i&&u==="backward",h=a&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:$f(t,s.data),hasPreviousPage:Ff(t,s.data),isFetchNextPageError:m,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:l&&!m&&!f,isRefetching:o&&!d&&!h}}};function Vi(e,t){const s=new Set(t);return e.filter(n=>!s.has(n))}function Vb(e,t,s){const n=e.slice(0);return n[t]=s,n}var Qb=class extends _f{#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,ua.batch(()=>{const s=this.#t,n=this.#f(this.#a);n.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=n.map(d=>d.observer),o=a.map(d=>d.getCurrentResult()),i=s.length!==a.length,l=a.some((d,f)=>d!==s[f]),u=i||l,m=u?!0:o.some((d,f)=>{const h=this.#e[f];return!h||!zf(d,h)});!u&&!m||(u&&(this.#c=n,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(Vi(s,a).forEach(d=>{d.destroy()}),Vi(a,s).forEach(d=>{d.subscribe(f=>{this.#m(d,f)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const s=this.#f(e),n=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[n,o=>this.#d(o??n,t,a),()=>this.#u(n,s)]}#u(e,t){return t.map((s,n)=>{const a=e[n];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const n=this.#l,a=s!==void 0&&n!==void 0&&(n.length!==s.length||s.some((o,i)=>o!==n[i]));return(!this.#n||this.#e!==this.#i||a||t!==this.#o)&&(this.#o=t,this.#i=this.#e,s!==void 0&&(this.#l=s),this.#n=Bf(this.#n,t(e))),this.#n}return e}#p(){return this.#r?.combine!==void 0&&this.#t.some((e,t)=>e.options.suspense&&this.#e[t]?.data===void 0)}#f(e){const t=new Map;this.#t.forEach(n=>{const a=n.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(n):t.set(a,[n])});const s=[];return e.forEach(n=>{const a=this.#s.defaultQueryOptions(n),i=t.get(a.queryHash)?.shift()??new _a(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=Vb(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,n=t?s:this.#d(e,this.#r?.combine);(t||s!==n)&&ua.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function mt({queries:e,...t},s){const n=Ee(),a=Kf(),o=Uf(),i=c.useMemo(()=>e.map(p=>{const b=n.defaultQueryOptions(p);return b._optimisticResults=a?"isRestoring":"optimistic",b}),[e,n,a]);i.forEach(p=>{qf(p);const b=n.getQueryCache().get(p.queryHash);Hf(p,o,b)}),Wf(o);const[l]=c.useState(()=>new Qb(n,i,t)),[u,m,d]=l.getOptimisticResult(i,t.combine),f=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>f?l.subscribe(ua.batchCalls(p)):Vf,[l,f]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const g=u.some((p,b)=>Ko(i[b],p))?u.flatMap((p,b)=>{const x=i[b];if(x&&Ko(x,p)){const S=new _a(n,x);return Qf(x,S,o)}return[]}):[];if(g.length>0)throw Promise.all(g);const y=u.find((p,b)=>{const x=i[b];return x&&Gf({result:p,errorResetBoundary:o,throwOnError:x.throwOnError,query:n.getQueryCache().get(x.queryHash),suspense:x.suspense})});if(y?.error)throw y.error;return m(d())}function Yc(e,t){return Yf(e,Wb)}function Gb(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const s=!!(e.condition??!0),n=e.blockerFn;return{shouldBlockFn:async()=>s&&n!==void 0?await n():s,enableBeforeUnload:s,withResolver:n===void 0}}function Xc(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:a=!1,withResolver:o=!1}=Gb(e),i=za(),{history:l}=i,[u,m]=c.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return c.useEffect(()=>{const d=async f=>{function h(x){const S=i.parseLocation(x),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(x.search)}:{routeId:w.foundRoute.id,fullPath:w.foundRoute.fullPath,pathname:S.pathname,params:w.routeParams,search:i.options.parseSearch(x.search)}}const g=h(f.currentLocation),y=h(f.nextLocation);if(g.routeId==="__notFound__"&&y.routeId!=="__notFound__")return!1;const p=await s({action:f.action,current:g,next:y});if(!o)return p;if(!p)return!1;const b=await new Promise(x=>{m({status:"blocked",current:g,next:y,action:f.action,proceed:()=>x(!1),reset:()=>x(!0)})});return m({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),b};return a?void 0:l.block({blockerFn:d,enableBeforeUnload:n})},[s,n,a,o,l,i]),u}function jt(e){const t=za({warn:e?.router===void 0}),s=e?.router||t;return Dl(s.stores.__store,Pl(e,s))}function xr(e){const t=za();return Dl(t.stores.location,Pl(e,t))}const Yb=new Set(["outbox","flagged"]),Xb=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!Yb.has(s)};function Jb(e){const t=mt({queries:e.map(s=>({...ot({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,n]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=un(n.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function Jc(e){const{openCompose:t}=Wt(),s=He(),n=xr(),a=Jb(e);return c.useCallback(()=>{if(Xb(n.pathname)){c.startTransition(()=>{t({mode:"new"})});return}a&&(c.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,n.pathname,a])}const Zb=e=>e.startsWith("/mail")||e.startsWith("/settings"),ev=({accounts:e})=>{const{state:t}=Wt(),s=xr(),n=Jc(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!Zb(s.pathname)||t.isOpen||o?null:r.jsx("button",{type:"button",onClick:n,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:r.jsx(Uh,{className:"size-6"})})},Zc=({trigger:e,children:t,align:s="right"})=>{const[n,a]=c.useState(!1),o=c.useRef(null),i=c.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),l=c.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return c.useEffect(()=>(n&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",l)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",l)}),[n,i,l]),r.jsxs("div",{ref:o,className:"relative",children:[r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!n)},className:Le("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),n&&r.jsx("div",{className:Le("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})]})},Cs=({onClick:e,disabled:t,destructive:s,children:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:Le("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:n}),ya=()=>r.jsx("div",{className:"my-1 h-px bg-line"}),eu=({children:e})=>{const{Account:t}=Ba();return r.jsx(t,{children:e})},tv=({email:e,onSignOut:t})=>{const s=He(),n=e??"Account";return r.jsxs(Zc,{trigger:r.jsx(bt,{name:n,email:e??void 0,size:"sm"}),align:"right",children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),r.jsx(ya,{})]}),r.jsxs(Cs,{onClick:()=>s({to:"/settings/accounts"}),children:[r.jsx(ro,{className:"size-4"}),"Settings"]}),r.jsx(ya,{}),r.jsxs(Cs,{onClick:t,children:[r.jsx(dc,{className:"size-4"}),"Sign out"]})]})},sv=()=>r.jsx(eu,{children:({email:e,signOut:t})=>r.jsx(tv,{email:e,onSignOut:t})}),Qi=()=>{const e=Ka(),t=Ua(e);window.open(t,"_blank","noopener,noreferrer")};function tu({variant:e="icon"}){return e==="drawer"?r.jsxs("button",{type:"button",onClick:Qi,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[r.jsx(si,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]}):r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(si,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:Qi})}const su="/mail/",ho="/mail/$mailboxId",nu="/mail/outbox",ru="/mail/flagged";function po(e){return e.some(t=>t.routeId===su)}function mn(e){return e.some(t=>t.routeId===ru)}function br(e){return e.some(t=>t.routeId===nu)}function au(e){return e.some(t=>t.routeId===ho)}function nv(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${ho}:${t}`:mn(e)?ru:br(e)?nu:po(e)?su:""}const _n="search-scope";function rv(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function ou(e){return mn(e)||br(e)||au(e)}function iu(e){return e.find(t=>t.routeId===ho)?.params?.mailboxId}function av(e){const t=iu(e.matches);return t||(ou(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function ov(e,t){return po(e)?{kind:"global"}:mn(e)?{kind:"scoped",chip:{id:_n,label:"is:starred"}}:br(e)?{kind:"scoped",chip:{id:_n,label:"in:outbox"}}:au(e)?t?{kind:"scoped",chip:{id:_n,label:rv(t)}}:{kind:"pending"}:{kind:"global"}}function iv(e,t,s){return t.kind==="global"?{kind:"global"}:mn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const lu=({accounts:e})=>{const t=qa({strict:!1}),s=xr(),n=t.mailboxId,{t:a}=er("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=mt({queries:e.map(l=>({...ot({path:{accountId:l.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!n)return null;for(let l=0;l<e.length;l++){const u=i[l]?.data?.items;if(!u)continue;const m=u.find(f=>f.mailboxId===n);if(!m)continue;const d=un(e[l].folderAppointments);return Ts(m,d.get(n),o)}return null},lv=({accounts:e})=>{const s=qa({strict:!1}).mailboxId,n=mt({queries:e.map(a=>({...ot({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of n){const o=a.data?.items;if(!o)continue;const i=o.find(l=>l.mailboxId===s);if(i)return i.unseenCount}return null};function cu(e){const t=He(),{searchInput:s}=Ie(),n=lu({accounts:e}),a=jt({select:l=>l.matches}),o=ov(a,n),i=c.useCallback(l=>{l===_n&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const uu=[{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 cv(e){for(const t of uu){const s=t.hints.find(n=>n.action===e);if(s)return s.keys}}function Ss(e){const t=cv(e);return!t||t.length===0?"":t.length===1?`(${t[0]})`:t[0]==="g"?`(${t.join(" then ")})`:`(${t.join("")})`}const uv={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function dv({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:n,onSearchClearQuery:a}=Ie(),o=Jc(e),{scope:i,clearScope:l}=cu(e),u=i.kind==="scoped"?[{id:i.chip.id,label:i.chip.label,tone:"scope"}]:void 0,m=uv[i.kind];return r.jsx(ng,{search:r.jsx(lo,{value:t,onChange:s,onClear:n,onClearQuery:a,chips:u,onRemoveChip:l,placeholder:m,size:"lg"}),actions:r.jsxs(r.Fragment,{children:[r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Wh,{className:"size-4"}),title:`Compose ${Ss("compose")}`,"aria-label":"Compose",onClick:o}),r.jsx(tu,{}),r.jsx(sv,{})]})})}const go=({isOpen:e,onClose:t,children:s,ariaLabel:n="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=c.useRef(null),l=c.useRef(null);if(c.useEffect(()=>{if(!e)return;l.current=document.activeElement;const m=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",m),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=f,l.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return r.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":n,children:[r.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),r.jsxs("div",{ref:i,className:Le("absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[r.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:r.jsx(vt,{className:"size-5"})})}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},fv=e=>{const t=e.filter(a=>!a.isMultipart&&a.disposition!=="attachment"&&a.mediaType==="TEXT"&&a.contentUrl.length>0),s=t.find(a=>a.mediaSubtype.toUpperCase()==="HTML");if(s)return{kind:"html",contentUrl:s.contentUrl};const n=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return n?{kind:"text",contentUrl:n.contentUrl}:null},wa={all:["messages"],detail:e=>[...wa.all,"detail",e],body:e=>[...wa.detail(e),"body"]};class ns extends Error{reason;status;retryAfterSeconds;constructor(t,s,n,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=n,this.retryAfterSeconds=a}}const mv=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},hv=8,pv="x-remit-403-reason",gv=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},xv=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,bv=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},vv=async(e,t,s=async()=>null)=>{const n={},a=await s();a&&(n.Authorization=`Bearer ${a}`);const o=await Xf(e,{headers:n});if(o.status===202)throw new ns("not-ready","Message body is still syncing",202,mv(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(pv),m=gv(o.status,u);throw new ns(m,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(bv(t,i))throw new ns("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(xv(l,i))throw new ns("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},yv=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),du=({messageId:e,bodyParts:t,enabled:s=!0})=>{const n=t?fv(t):null,a=dn(),{getToken:o}=Ba(),i=c.useRef(null),l=Ee(),u=c.useRef(!1),m=c.useRef(null),d=e&&n?`${e}:${n.contentUrl}`:null;m.current!==d&&(m.current=d,u.current=!1);const f=xe({queryKey:e?[...wa.body(e),n?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!n)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const y=u.current;return u.current=!1,yv({fetchContent:(p,b)=>vv(p,b,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:Ll({path:{messageId:e}})})},{contentUrl:n.contentUrl,kind:n.kind,isRetryAfterNotReady:y})},enabled:s&&!!e&&!!n,staleTime:300*1e3,gcTime:1800*1e3,retry:(y,p)=>p instanceof ns&&p.reason==="not-ready"?y<hv:y<1,retryDelay:(y,p)=>p instanceof ns&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=f.isLoading&&!!n;c.useEffect(()=>{h&&(i.current=performance.now())},[h]),c.useEffect(()=>{f.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[f.isSuccess,a]);const g=f.data&&n?{kind:n.kind,body:f.data}:void 0;return{picked:n,data:g,isLoading:h,isError:f.isError,error:f.error,refetch:f.refetch}},wv=({outboxMessageId:e,onDraftCreated:t})=>{const[s,n]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=Ee(),u=Oe(Fl()),m=Oe(Jf()),d=c.useCallback(async y=>{if(n("saving"),o(null),e){const b=await m.mutateAsync({path:{outboxMessageId:e},body:{toAddresses:y.toAddresses,ccAddresses:y.ccAddresses,bccAddresses:y.bccAddresses,subject:y.subject,textBody:y.textBody,htmlBody:y.htmlBody,inReplyTo:y.inReplyTo,references:y.references}});return n("saved"),b}const p=await u.mutateAsync({body:{...y,sendImmediately:!1}});return t(p.outboxMessageId),n("saved"),l.invalidateQueries({queryKey:tr().queryKey}),p},[e,u,m,t,l]),f=c.useCallback(y=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{d(y).catch(p=>{o(p),n("error")})},2e3)},[d]),h=c.useCallback(y=>(i.current&&clearTimeout(i.current),d(y)),[d]),g=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:f,saveImmediately:h,cancelAutoSave:g}},fu=e=>"text"in e&&!("children"in e),mu=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Sv=e=>{let t=mu(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},hu=e=>{const t=e.children.map(s=>fu(s)?Sv(s):hu(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${mu(s)}">${t}</a>`}default:return`<p>${t}</p>`}},Gi=e=>e.map(hu).join(""),pu=e=>fu(e)?e.text:e.children.map(pu).join(""),Sa=e=>e.map(pu).join(`
|
|
116
|
-
`),kv=["Tab",","],Yi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),Cv=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const n=s[1].trim(),a=s[2].trim();if(Yi(a))return{email:a,displayName:n}}if(Yi(t))return{email:t}},Zr=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=c.useState(""),i=c.useRef(null),l=ir(a,200),{data:u}=xe({...sr({query:{q:l,limit:8}}),enabled:l.length>=2}),m=u?.items??[],d=new Set(t.map(v=>v.email.toLowerCase())),f=a.length>=2?m.filter(v=>!d.has(v.normalizedEmail.toLowerCase())):[],h=c.useCallback(v=>{d.has(v.email.toLowerCase())||(s([...t,v]),o(""))},[t,d,s]),g=c.useCallback(v=>{s(t.filter((C,E)=>E!==v))},[t,s]),y=c.useCallback(v=>{h({email:v.normalizedEmail,displayName:v.displayName}),i.current?.focus()},[h]),p=c.useCallback(()=>{const v=Cv(a);v&&h(v)},[a,h]),b=$l({count:f.length,acceptKeys:kv,onAccept:v=>y(f[v])}),x=c.useMemo(()=>f.map(v=>({value:v.normalizedEmail,label:v.displayName??v.normalizedEmail,...v.displayName?{hint:v.normalizedEmail}:{}})),[f]),S=c.useCallback(v=>{if(v.key==="Backspace"&&a===""&&t.length>0){g(t.length-1);return}b.handleKeyDown(v)||(v.key==="Enter"||v.key==="Tab"||v.key===",")&&a.trim()&&(v.preventDefault(),p())},[a,t.length,g,b.handleKeyDown,p]),w=c.useCallback(()=>{setTimeout(()=>{p(),b.dismiss()},150)},[p,b.dismiss]);return r.jsxs("div",{className:"relative",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),r.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>i.current?.focus(),onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&i.current?.focus()},children:[t.map((v,C)=>r.jsx(Yh,{email:v.email,displayName:v.displayName,onRemove:()=>g(C)},v.email)),r.jsx("input",{ref:i,id:`address-field-${e}`,type:"text",value:a,onChange:v=>{b.reopen(),o(v.target.value)},onKeyDown:S,onBlur:w,placeholder:t.length===0?n:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5",autoComplete:"off",...b.comboboxProps})]})]}),b.open&&r.jsx(_l,{id:b.listId,suggestions:x,activeIndex:b.activeIndex,optionId:b.optionId,onPick:v=>{const C=f.find(E=>E.normalizedEmail===v.value);C&&y(C)},onHighlight:b.setActiveIndex,label:`${e} suggestions`,className:"absolute left-12 right-0 z-50 mt-1 max-h-[200px] shadow-lg"})]})},jv=({accountId:e})=>{const t=He();return r.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[r.jsx(La,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),r.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",r.jsx(Zf,{className:"size-3","aria-hidden":"true"})]})]})]})},Xi=150,Nv=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>Xi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>Xi})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},Ev=({selectedAccountId:e,onSelect:t})=>{const{data:s}=xe({...It(),staleTime:1/0}),n=s?.accounts??[];if(c.useEffect(()=>{!e&&n.length===1&&n[0]&&t(n[0])},[e,n,t]),n.length<=1){const a=n[0];return a?r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=n.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:n.map(a=>r.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},Iv=({value:e,onChange:t})=>r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),r.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),Tv=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],Rv=["href"],Mv=e=>Tl.sanitize(e,{ALLOWED_TAGS:Tv,ALLOWED_ATTR:Rv}),Av=c.lazy(()=>tm(()=>import("./ComposeBody-mpT1bIZQ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.ComposeBody}))),Ov=()=>r.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[r.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),r.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),gu=[{type:"p",children:[{text:""}]}],Dv=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],Pv=e=>e?[...Dv,{type:"p",children:[{text:e}]}]:gu,Lv=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",Fv=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",$v=(e,t,s)=>{const{envelope:n}=e,o=(n.replyTo.length>0?n.replyTo:n.from).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(m=>m.email.toLowerCase())),u=[...n.to,...n.cc].filter(m=>m.normalizedEmail.toLowerCase()!==i&&!l.has(m.normalizedEmail.toLowerCase())).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));return{to:o,cc:u}},_v=e=>{const t=e.envelope.messageIdValue,n=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!n.includes(t)&&n.push(t),{inReplyTo:t,references:n}},zv=(e,t,s,n,a)=>e.length===0&&t.length===0&&s.length===0&&n.trim()===""&&Sa(a).trim()==="",Bv=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:n,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:m,showBcc:d,setShowBcc:f,subject:h,setSubject:g})=>{const y=Vt(),{isKeyboardOpen:p}=Nv();if(!y&&p){const x=[];return s.length>0&&x.push(`To: ${s.map(S=>S.displayName??S.email).join(", ")}`),a.length>0&&x.push(`Cc: ${a.length}`),i.length>0&&x.push(`Bcc: ${i.length}`),h&&x.push(h),r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[r.jsx("span",{className:"truncate text-xs text-fg-muted",children:x.length>0?x.join(" · "):"…"}),r.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return r.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[r.jsx(Ev,{selectedAccountId:e,onSelect:t}),r.jsx(Zr,{label:"To",addresses:s,onChange:n,placeholder:"Recipients"}),u?r.jsx(Zr,{label:"Cc",addresses:a,onChange:o}):r.jsxs("div",{className:"flex gap-2 pl-14",children:[r.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),r.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&r.jsx("div",{className:"pl-14",children:r.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&r.jsx(Zr,{label:"Bcc",addresses:i,onChange:l}),r.jsx(Iv,{value:h,onChange:g})]})},xo=({mode:e,account:t,sourceMessage:s,onClose:n,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Wt(),{pushError:u}=it(),{outboxMessageId:m}=o,[d,f]=c.useState([]),[h,g]=c.useState([]),[y,p]=c.useState([]),[b,x]=c.useState(""),[S,w]=c.useState(!1),[v,C]=c.useState(!1),[E,I]=c.useState(t?.accountId),[N,D]=c.useState(!1),A=c.useRef(m);c.useEffect(()=>{A.current!==m&&(A.current=m,m&&(f([]),g([]),p([]),x(""),w(!1),C(!1),M(gu),D(!1)))},[m]);const{signature:O}=Km(E),[L,M]=c.useState(()=>Pv(O.plainText)),{data:k}=xe({...em({path:{outboxMessageId:m??""}}),enabled:!!m&&!N});c.useEffect(()=>{!k||N||(f(k.toAddresses.map($=>({email:$,displayName:void 0}))),k.ccAddresses&&k.ccAddresses.length>0&&(g(k.ccAddresses.map($=>({email:$,displayName:void 0}))),w(!0)),k.bccAddresses&&k.bccAddresses.length>0&&(p(k.bccAddresses.map($=>({email:$,displayName:void 0}))),C(!0)),k.subject&&x(k.subject),k.textBody&&M([{type:"p",children:[{text:k.textBody}]}]),I(k.accountId),D(!0))},[k,N]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:$,cc:le}=$v(s,e,t?.email);f($),g(le),le.length>0&&w(!0),x(Lv(s.envelope.subject))}e==="forward"&&x(Fv(s.envelope.subject))}},[e,s,t?.email]);const P=e==="reply"||e==="reply_all"||e==="forward",{data:F}=du({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:P&&!!s}),j=F?.kind==="text"?F.body:"",R=F?.kind==="html"?Mv(F.body):void 0,T=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:V,saveError:Z,saveDraft:ee,cancelAutoSave:fe}=wv({outboxMessageId:m,onDraftCreated:i});c.useEffect(()=>{Z&&u({title:"Couldn't save draft",detail:ft(Z)??"Saving the draft failed.",error:Z})},[Z,u]);const W=Oe(Fl()),te=Oe(zl()),ce=Oe({...nr(),onError:$=>{u(as("Couldn't discard draft","The draft wasn't discarded.",$))}}),{data:ie}=xe({...It(),staleTime:1/0}),U=ie?.accounts.find($=>$.accountId===E),K=U?zm(U):!1,he=W.isPending||te.isPending,Se=d.length>0&&!!E&&!K;c.useEffect(()=>{if(!E||m&&!N||zv(d,h,y,b,L))return;const $=Sa(L),le=Gi(L);ee({accountId:E,toAddresses:d.map(ue=>ue.email),ccAddresses:h.length>0?h.map(ue=>ue.email):void 0,bccAddresses:y.length>0?y.map(ue=>ue.email):void 0,subject:b||void 0,textBody:$||void 0,htmlBody:le||void 0})},[E,m,N,d,h,y,b,L,ee]);const ye=c.useCallback(async()=>{if(!E||d.length===0)return;fe();const $=s&&(e==="reply"||e==="reply_all")?_v(s):{};let le=m,ue=!1;if(!le){const me=Sa(L),Me=Gi(L),pe=await W.mutateAsync({body:{accountId:E,toAddresses:d.map(de=>de.email),ccAddresses:h.length>0?h.map(de=>de.email):void 0,bccAddresses:y.length>0?y.map(de=>de.email):void 0,subject:b||void 0,textBody:me||void 0,htmlBody:Me||void 0,sendImmediately:!0,...$}}).catch(de=>(u({title:"Couldn't send message",detail:ft(de)??"Saving the draft failed.",error:de}),null));if(pe===null)return;le=pe.outboxMessageId,ue=!0,i(le)}await te.mutateAsync({path:{outboxMessageId:le}}).catch(me=>(u({title:"Couldn't send message",detail:ft(me)??(ue?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:me}),null))!==null&&(l(le),n())},[E,d,h,y,b,L,e,s,m,W,te,fe,l,i,u,n]),G=c.useCallback(()=>{fe(),m&&ce.mutate({path:{outboxMessageId:m}}),n()},[fe,m,ce,n]),B=c.useCallback($=>{I($.accountId),a?.($)},[a]);return r.jsx(cg,{banner:U&&K?r.jsx(jv,{accountId:U.accountId}):void 0,header:r.jsx(Bv,{selectedAccountId:E,onAccountChange:B,toAddresses:d,setToAddresses:f,ccAddresses:h,setCcAddresses:g,bccAddresses:y,setBccAddresses:p,showCc:S,setShowCc:w,showBcc:v,setShowBcc:C,subject:b,setSubject:x}),quoted:j||R?r.jsx(Rg,{text:j,html:R,senderName:T}):void 0,actionBar:r.jsx(lg,{onSend:ye,onDiscard:G,sending:he,canSend:Se,saveStatus:V,unavailableReason:K?"SMTP not configured":void 0,onUnavailable:$=>u({title:"Can't send yet",detail:$})}),children:r.jsx(c.Suspense,{fallback:r.jsx(Ov,{}),children:r.jsx(Av,{value:L,onChange:M,onSubmit:ye,autoFocus:e==="new"})})})},Ji=({mode:e,account:t,sourceMessage:s,onClose:n})=>r.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:r.jsx(xo,{mode:e,account:t,sourceMessage:s,onClose:n})}),xu=({message:e,icon:t})=>r.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&r.jsx("div",{className:"mb-4 text-fg-muted",children:t}),r.jsx("p",{className:"text-fg-muted",children:e})]}),bo=({enabled:e=!0,bindings:t,capture:s=!1})=>{const n=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const m=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(m&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",n,s),()=>window.removeEventListener("keydown",n,s)},[e,n,s])},vo=e=>{const{data:t,isLoading:s}=xe({...It(),staleTime:1/0}),n=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=mt({queries:n.map(l=>({...ot({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<n.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return n[l]}},[e,n,a]),isLoading:o}},bu=100,Hn=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),Kv=(e,t=bu)=>{if(e.length===0)return[];const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s},vu=async(e,t,s,n)=>{const a=Kv(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(n())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const m=a[u],d=await Hn(t(m));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+=m.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},vr=async(e,t)=>{await vu(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},Uv=async(e,t,s,n,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await Hn(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const m=u.value;if(m.ids.length>0){const d=await Hn(s(m.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=m.ids.length,n({done:o,total:t})}l=m.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},qv=e=>({done:e.done,total:Math.max(e.total,e.done)}),Hv=async(e,t,s)=>{let n=0,a;do{if(s())return{total:n,cancelled:!0};const o=await Hn(e(a));if(!o.ok)return{total:n,cancelled:!1,error:o.error};const i=o.value;n+=i.ids.length,t(n),a=i.continuationToken}while(a);return{total:n,cancelled:!1}},Wv=e=>e.failedIds.length>0?{exit:!1,retryIds:e.failedIds}:e.cancelled||e.error?{exit:!1,retryIds:[]}:{exit:!0,retryIds:[]},yu=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),wu=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),Su=(e,t)=>e===void 0?e:yu(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:wu(e)?{...e,items:t(e.items)}:e,Rt=e=>{const t=[];for(const s of new Set(e))t.push(rr({path:{mailboxId:s}})),t.push(Ha({path:{mailboxId:s}}));return t.push(Wa()),t},hn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),pn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,n])=>({queryKey:s,data:n})),gn=(e,t,s)=>{const n=a=>Su(a,s);for(const a of t)e.setQueriesData({queryKey:a},n)},xn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},Mt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Vv=3e3,Qv=(e,t,s)=>{if(e.length===0)return()=>{};const n=setTimeout(()=>s(e),t);return()=>clearTimeout(n)},yr=(e,t,s)=>{const n=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(n.get(o)??s);return[...a]},Wn=(e,t,s)=>e.map(n=>t.has(n.messageId)?{...n,isRead:s}:n),Gv=(e,t,s,n)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!n.has(a.messageId)).map(a=>a.messageId),Yv=({messages:e,expandedIds:t,threadId:s,mailboxId:n,accountId:a})=>{const o=Ee(),{pushError:i}=it(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:m}=Oe({...ar(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),y=h.body.isRead??!0,p=ds({path:{threadId:s}}),b=Rt(yr(g,e,n));await Promise.all([o.cancelQueries({queryKey:p}),hn(o,b)]);const x=o.getQueriesData({queryKey:p}).filter(w=>w[1]!==void 0).map(([w,v])=>({queryKey:w,data:v})),S=pn(o,b);return o.setQueriesData({queryKey:p},w=>w&&{...w,items:Wn(w.items,g,y)}),gn(o,b,w=>Wn(w,g,y)),{threadMessagesPrefix:p,listPrefixes:b,previousThreadMessages:x,previousThreadsList:S}},onSuccess:(h,g)=>{const y=g.body.messageIds??[];for(const p of y)l.current.add(p),u.current.delete(p)},onError:(h,g,y)=>{const p=g.body.messageIds??[];for(const x of p)u.current.delete(x);if(y){for(const x of y.previousThreadMessages)o.setQueryData(x.queryKey,x.data);xn(o,y.previousThreadsList)}const b=g.body.isRead??!0;i({title:b?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(h),error:h})},onSettled:(h,g,y,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),Mt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:us({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(y=>!l.current.has(y)&&!u.current.has(y));if(g.length!==0){for(const y of g)u.current.add(y);m({body:{messageIds:g,isRead:!0}})}},[m]),f=c.useMemo(()=>Gv(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Qv(f,Vv,d),[f,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},wr=e=>{const{mailboxId:t,accountId:s,messages:n}=e,a=Ee(),{pushError:o}=it(),{mutateAsync:i,isPending:l}=Oe({...ar(),onError:(m,d)=>{const f=d.body.isRead??!0;o({title:f?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(m),error:m})},onSettled:(m,d,f)=>{Mt(a,Rt(yr(f.body.messageIds??[],n??[],t))),s&&a.invalidateQueries({queryKey:us({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((m,d)=>{m.length!==0&&vr(m,f=>i({body:{messageIds:f,isRead:d}}))},[i]),isPending:l}},Xv=60,Jv=1.5,Zv=(e,t,s)=>{const n=Math.abs(e),a=Math.abs(t);return n<s?{direction:null}:n<a*Jv?{direction:null}:{direction:e<0?"left":"right"}},ey=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Xv})=>{const n=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){n.current=null;return}n.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const m=n.current;if(n.current=null,!m)return;const{direction:d}=Zv(u.clientX-m.x,u.clientY-m.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{n.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},ty=(e,t,s)=>t?.find(n=>n.messageId===e)?.mailboxId??s,Zi=(e,t,s)=>e.map(n=>n.messageId===t?{...n,hasStars:s}:n),yo=({threadId:e,mailboxId:t,messages:s})=>{const n=Ee(),{pushError:a}=it(),{mutate:o,isPending:i,variables:l}=Oe({...sm(),onMutate:async m=>{const d=m.path.messageId,f=m.body.isStarred??!1,h=ds({path:{threadId:e}}),g=Rt([ty(d,s,t)]);await Promise.all([n.cancelQueries({queryKey:h}),hn(n,g)]);const y=n.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,x])=>({queryKey:b,data:x})),p=pn(n,g);return n.setQueriesData({queryKey:h},b=>Su(b,x=>Zi(x,d,f))),gn(n,g,b=>Zi(b,d,f)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:y,previousThreadsList:p}},onError:(m,d,f)=>{if(f){for(const g of f.previousThreadMessages)n.setQueryData(g.queryKey,g.data);xn(n,f.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:ft(m),error:m})},onSettled:(m,d,f,h)=>{h&&(n.invalidateQueries({queryKey:h.threadMessagesPrefix}),Mt(n,h.listPrefixes))}});return{toggleStar:(m,d)=>{o({path:{messageId:m},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function Sr(e){return e===void 0?"uncategorized":e}const sy={inbox:"Inbox",junk:"Junk"},wo=e=>e.destinationMailboxId!==void 0,ny=(e,t)=>{if(wo(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${sy[s]??"another folder"} by Remit`},ry=(e,t)=>{if(e===Vo.MoveToInbox)return t.inboxMailboxId;if(e===Vo.MoveToJunk)return t.junkMailboxId},ay=(e,t,s)=>{if(!e||!t)return!1;const n=wo(e)?e.destinationMailboxId:ry(e.action,s);return n!==void 0&&n===t},oy=(e,t)=>{if(e){if(wo(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},kr=(e,t)=>{const{data:s,isLoading:n}=xe({...It(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:n}},iy=e=>{const{mailboxId:t,isLoading:s}=kr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},ly=e=>{const{mailboxId:t,isLoading:s}=kr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},So=e=>{const{mailboxId:t,isLoading:s}=kr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},_s=e=>{const{mailboxId:t,isLoading:s}=kr(e,"Junk");return{junkMailboxId:t,isLoading:s}},ko=e=>{const{data:t}=xe({...It(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},el=(e,t)=>e.filter(s=>!t.has(s.messageId)),is=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=Ee(),{pushError:o}=it(),{mutateAsync:i,isPending:l}=Oe({...nm(),onMutate:async m=>{const d=new Set(m.body.messageIds??[]),f=t?ds({path:{threadId:t}}):[],h=Rt([e,m.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:f})]:[],hn(a,h)]);const g=t?a.getQueriesData({queryKey:f}).filter(p=>p[1]!==void 0).map(([p,b])=>({queryKey:p,data:b})):[],y=pn(a,h);return t&&a.setQueriesData({queryKey:f},p=>p&&{...p,items:el(p.items,d)}),gn(a,h,p=>el(p,d)),n?.(Array.from(d)),{threadMessagesPrefix:f,listPrefixes:h,previousThreadMessages:g,previousThreadsList:y}},onError:(m,d,f)=>{if(f){for(const g of f.previousThreadMessages)a.setQueryData(g.queryKey,g.data);xn(a,f.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:ft(m),error:m})},onSettled:(m,d,f,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),Mt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:us({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((m,d)=>{m.length!==0&&vr(m,f=>i({body:{messageIds:f,destinationMailboxId:d}}))},[i]),isPending:l}},cy=({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a})=>{const{inboxMailboxId:o}=So(e),{junkMailboxId:i}=_s(e),{moveMessages:l,isPending:u}=is({mailboxId:n,threadId:s,accountId:e}),{data:m}=xe({...ot({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},f=ay(a,n,d),h=oy(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!f||!a)return{show:!1,label:"",isUndoing:!1};const y=a.fromMailboxId?m?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>Bn(p.fullPath))[0]:void 0;return{show:!0,label:ny(a,y),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function uy({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a}){const o=cy({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a});return o.show?r.jsx(rg,{label:o.label,onUndo:o.onUndo,undoLabel:o.isUndoing?"Undoing…":"Undo",filtersHref:o.filtersHref}):null}const tl=(e,t)=>e.filter(s=>!t.has(s.messageId)),dy=e=>e.filter(t=>t.isDeleted!==!0),ls=({mailboxId:e,threadId:t,accountId:s,messages:n,onAfterOptimisticRemove:a})=>{const o=Ee(),{pushError:i}=it(),{mutateAsync:l,isPending:u}=Oe({...rm(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?ds({path:{threadId:t}}):[],g=Rt(yr(f,n??[],e));await Promise.all([o.cancelQueries({queryKey:h}),hn(o,g)]);const y=t?o.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,x])=>({queryKey:b,data:x})):[],p=pn(o,g);return t&&o.setQueriesData({queryKey:h},b=>b&&{...b,items:tl(b.items,f)}),gn(o,g,b=>tl(b,f)),a?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:y,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const y of h.previousThreadMessages)o.setQueryData(y.queryKey,y.data);xn(o,h.previousThreadsList)}const g=f.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:ft(d),error:d})},onSettled:(d,f,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),Mt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:us({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&vr(d,f=>l({body:{messageIds:f}}))},[l]),isPending:u}},ku=(e,t=Date.now())=>({value:e,setAt:t}),fy=(e,t,s,n)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=ku(!0,n):delete a.trusted,{...e,flags:a}},my=(e,t,s,n)=>{const a=o=>o.map(i=>fy(i,t,s,n));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},Co=({messageId:e})=>{const t=Ee(),{pushError:s}=it(),{mutate:n,isPending:a,error:o,reset:i}=Oe({...Bl(),onMutate:async u=>{const m=u.path.addressId,f=u.body.flags?.trusted?.value===!0,h=Ll({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(y=>y[1]!==void 0).map(([y,p])=>({queryKey:y,data:p}));return t.setQueriesData({queryKey:h},y=>y&&my(y,m,f)),{describePrefix:h,previous:g}},onError:(u,m,d)=>{if(d)for(const f of d.previous)t.setQueryData(f.queryKey,f.data);s(as("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,m,d,f)=>{f&&t.invalidateQueries({queryKey:f.describePrefix})}});return{toggleTrusted:(u,m)=>{n({path:{addressId:u},body:{flags:{trusted:ku(!m)}}})},isPending:a,error:o,reset:i}};var Cr="Dialog",[Cu]=yx(Cr),[hy,ht]=Cu(Cr),ju=e=>{const{__scopeDialog:t,children:s,open:n,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[m,d]=kx({prop:n,defaultProp:a??!1,onChange:o,caller:Cr});return r.jsx(hy,{scope:t,triggerRef:l,contentRef:u,contentId:Qr(),titleId:Qr(),descriptionId:Qr(),open:m,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(f=>!f),[d]),modal:i,children:s})};ju.displayName=Cr;var Nu="DialogTrigger",py=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=ht(Nu,s),o=fs(t,a.triggerRef);return r.jsx(Tt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":No(a.open),...n,ref:o,onClick:Kt(e.onClick,a.onOpenToggle)})});py.displayName=Nu;var jo="DialogPortal",[gy,Eu]=Cu(jo,{forceMount:void 0}),Iu=e=>{const{__scopeDialog:t,forceMount:s,children:n,container:a}=e,o=ht(jo,t);return r.jsx(gy,{scope:t,forceMount:s,children:c.Children.map(n,i=>r.jsx(pr,{present:s||o.open,children:r.jsx(Bc,{asChild:!0,container:a,children:i})}))})};Iu.displayName=jo;var Vn="DialogOverlay",Tu=c.forwardRef((e,t)=>{const s=Eu(Vn,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=ht(Vn,e.__scopeDialog);return o.modal?r.jsx(pr,{present:n||o.open,children:r.jsx(by,{...a,ref:t})}):null});Tu.displayName=Vn;var xy=fo("DialogOverlay.RemoveScroll"),by=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=ht(Vn,s),o=Kx(),i=fs(t,o);return r.jsx(Gc,{as:xy,allowPinchZoom:!0,shards:[a.contentRef],children:r.jsx(Tt.div,{"data-state":No(a.open),...n,ref:i,style:{pointerEvents:"auto",...n.style}})})}),As="DialogContent",Ru=c.forwardRef((e,t)=>{const s=Eu(As,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=ht(As,e.__scopeDialog);return r.jsx(pr,{present:n||o.open,children:o.modal?r.jsx(vy,{...a,ref:t}):r.jsx(yy,{...a,ref:t})})});Ru.displayName=As;var vy=c.forwardRef((e,t)=>{const s=ht(As,e.__scopeDialog),n=c.useRef(null),a=fs(t,s.contentRef,n);return c.useEffect(()=>{const o=n.current;if(o)return ub(o)},[]),r.jsx(Mu,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Kt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Kt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Kt(e.onFocusOutside,o=>o.preventDefault())})}),yy=c.forwardRef((e,t)=>{const s=ht(As,e.__scopeDialog),n=c.useRef(!1),a=c.useRef(!1);return r.jsx(Mu,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(n.current||s.triggerRef.current?.focus(),o.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),Mu=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=ht(As,s);return Wx(),r.jsx(r.Fragment,{children:r.jsx(_c,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:r.jsx(Fc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":No(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),Au="DialogTitle",Ou=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=ht(Au,s);return r.jsx(Tt.h2,{id:a.titleId,...n,ref:t})});Ou.displayName=Au;var Du="DialogDescription",wy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=ht(Du,s);return r.jsx(Tt.p,{id:a.descriptionId,...n,ref:t})});wy.displayName=Du;var Pu="DialogClose",Sy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=ht(Pu,s);return r.jsx(Tt.button,{type:"button",...n,ref:t,onClick:Kt(e.onClick,()=>a.onOpenChange(!1))})});Sy.displayName=Pu;function No(e){return e?"open":"closed"}function ky(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}const Lu=q.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),bn=()=>{const e=q.useContext(Lu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};ky(`[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 Cy(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function jy(){return Eo(/^Mac/)}function Ny(){return Eo(/^iPhone/)}function sl(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Ey(){return Eo(/^iPad/)||jy()&&navigator.maxTouchPoints>1}function Fu(){return Ny()||Ey()}function Eo(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const Iy=24,Ty=typeof window<"u"?c.useLayoutEffect:c.useEffect;function nl(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const ea=typeof document<"u"&&window.visualViewport;function rl(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function $u(e){for(rl(e)&&(e=e.parentElement);e&&!rl(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Ry=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Mn=0,ta;function My(e={}){let{isDisabled:t}=e;Ty(()=>{if(!t)return Mn++,Mn===1&&Fu()&&(ta=Ay()),()=>{Mn--,Mn===0&&ta?.()}},[t])}function Ay(){let e,t=0,s=f=>{e=$u(f.target),!(e===document.documentElement&&e===document.body)&&(t=f.changedTouches[0].pageY)},n=f=>{if(!e||e===document.documentElement||e===document.body){f.preventDefault();return}let h=f.changedTouches[0].pageY,g=e.scrollTop,y=e.scrollHeight-e.clientHeight;y!==0&&((g<=0&&h>t||g>=y&&h<t)&&f.preventDefault(),t=h)},a=f=>{let h=f.target;ka(h)&&h!==document.activeElement&&(f.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=f=>{let h=f.target;ka(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",ea&&(ea.height<window.innerHeight?requestAnimationFrame(()=>{al(h)}):ea.addEventListener("resize",()=>al(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,m=nl(Oy(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=nl(Ws(document,"touchstart",s,{passive:!1,capture:!0}),Ws(document,"touchmove",n,{passive:!1,capture:!0}),Ws(document,"touchend",a,{passive:!1,capture:!0}),Ws(document,"focus",o,!0),Ws(window,"scroll",i));return()=>{m(),d(),window.scrollTo(l,u)}}function Oy(e,t,s){let n=e.style[t];return e.style[t]=s,()=>{e.style[t]=n}}function Ws(e,t,s,n){return e.addEventListener(t,s,n),()=>{e.removeEventListener(t,s,n)}}function al(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=$u(e);if(s!==document.documentElement&&s!==document.body&&s!==e){let n=s.getBoundingClientRect().top,a=e.getBoundingClientRect().top,o=e.getBoundingClientRect().bottom;const i=s.getBoundingClientRect().bottom+Iy;o>i&&(s.scrollTop+=a-n)}e=s.parentElement}}function ka(e){return e instanceof HTMLInputElement&&!Ry.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function Dy(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function Py(...e){return t=>e.forEach(s=>Dy(s,t))}function _u(...e){return c.useCallback(Py(...e),e)}const zu=new WeakMap;function _e(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let n={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}n[a]=e.style[a],e.style[a]=o}),!s&&zu.set(e,n)}function Ly(e,t){if(!e||!(e instanceof HTMLElement))return;let s=zu.get(e);s&&(e.style[t]=s[t])}const Pe=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function An(e,t){if(!e)return null;const s=window.getComputedStyle(e),n=s.transform||s.webkitTransform||s.mozTransform;let a=n.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[Pe(t)?13:12]):(a=n.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[Pe(t)?5:4]):null)}function Fy(e){return 8*(Math.log(e+1)-2)}function sa(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function $y(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const Ne={DURATION:.5,EASE:[.32,.72,0,1]},Bu=.4,_y=.25,zy=100,Ku=8,ss=16,Ca=26,na="vaul-dragging";function Uu(e){const t=q.useRef(e);return q.useEffect(()=>{t.current=e}),q.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function By({defaultProp:e,onChange:t}){const s=q.useState(e),[n]=s,a=q.useRef(n),o=Uu(t);return q.useEffect(()=>{a.current!==n&&(o(n),a.current=n)},[n,a,o]),s}function qu({prop:e,defaultProp:t,onChange:s=()=>{}}){const[n,a]=By({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:n,l=Uu(s),u=q.useCallback(m=>{if(o){const f=typeof m=="function"?m(e):m;f!==e&&l(f)}else a(m)},[o,e,a,l]);return[i,u]}function Ky({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:n,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:m}){const[d,f]=qu({prop:e,defaultProp:s?.[0],onChange:t}),[h,g]=q.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);q.useEffect(()=>{function I(){g({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[]);const y=q.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=q.useMemo(()=>{var I;return(I=s?.findIndex(N=>N===d))!=null?I:null},[s,d]),b=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,x=q.useMemo(()=>{const I=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var N;return(N=s?.map(D=>{const A=typeof D=="string";let O=0;if(A&&(O=parseInt(D,10)),Pe(l)){const M=A?O:h?D*I.height:0;return h?l==="bottom"?I.height-M:-I.height+M:M}const L=A?O:h?D*I.width:0;return h?l==="right"?I.width-L:-I.width+L:L}))!=null?N:[]},[s,h,u]),S=q.useMemo(()=>p!==null?x?.[p]:null,[x,p]),w=q.useCallback(I=>{var N;const D=(N=x?.findIndex(A=>A===I))!=null?N:null;i(D),_e(n.current,{transition:`transform ${Ne.DURATION}s cubic-bezier(${Ne.EASE.join(",")})`,transform:Pe(l)?`translate3d(0, ${I}px, 0)`:`translate3d(${I}px, 0, 0)`}),x&&D!==x.length-1&&o!==void 0&&D!==o&&D<o?_e(a.current,{transition:`opacity ${Ne.DURATION}s cubic-bezier(${Ne.EASE.join(",")})`,opacity:"0"}):_e(a.current,{transition:`opacity ${Ne.DURATION}s cubic-bezier(${Ne.EASE.join(",")})`,opacity:"1"}),f(s?.[Math.max(D,0)])},[n.current,s,x,o,a,f]);q.useEffect(()=>{if(d||e){var I;const N=(I=s?.findIndex(D=>D===e||D===d))!=null?I:-1;x&&N!==-1&&typeof x[N]=="number"&&w(x[N])}},[d,e,s,x,w]);function v({draggedDistance:I,closeDrawer:N,velocity:D,dismissible:A}){if(o===void 0)return;const O=l==="bottom"||l==="right"?(S??0)-I:(S??0)+I,L=p===o-1,M=p===0,k=I>0;if(L&&_e(a.current,{transition:`opacity ${Ne.DURATION}s cubic-bezier(${Ne.EASE.join(",")})`}),!m&&D>2&&!k){A?N():w(x[0]);return}if(!m&&D>2&&k&&x&&s){w(x[s.length-1]);return}const P=x?.reduce((j,R)=>typeof j!="number"||typeof R!="number"?j:Math.abs(R-O)<Math.abs(j-O)?R:j),F=Pe(l)?window.innerHeight:window.innerWidth;if(D>Bu&&Math.abs(I)<F*.4){const j=k?1:-1;if(j>0&&y&&s){w(x[s.length-1]);return}if(M&&j<0&&A&&N(),p===null)return;w(x[p+j]);return}w(P)}function C({draggedDistance:I}){if(S===null)return;const N=l==="bottom"||l==="right"?S-I:S+I;(l==="bottom"||l==="right")&&N<x[x.length-1]||(l==="top"||l==="left")&&N>x[x.length-1]||_e(n.current,{transform:Pe(l)?`translate3d(0, ${N}px, 0)`:`translate3d(${N}px, 0, 0)`})}function E(I,N){if(!s||typeof p!="number"||!x||o===void 0)return null;const D=p===o-1;if(p>=o&&N)return 0;if(D&&!N)return 1;if(!b&&!D)return null;const O=D?p+1:p-1,L=D?x[O]-x[O-1]:x[O+1]-x[O],M=I/Math.abs(L);return D?1-M:M}return{isLastSnapPoint:y,activeSnapPoint:d,shouldFade:b,getPercentageDragged:E,setActiveSnapPoint:f,activeSnapPointIndex:p,onRelease:v,onDrag:C,snapPointsOffset:x}}const Uy=()=>()=>{};function qy(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:n,noBodyStyles:a}=bn(),o=q.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-Ca)/window.innerWidth}q.useEffect(()=>{if(t&&s){o.current&&clearTimeout(o.current);const u=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!u)return;$y(n&&!a?sa(document.body,{background:"black"}):Uy,sa(u,{transformOrigin:Pe(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Ne.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Ne.EASE.join(",")})`}));const m=sa(u,{borderRadius:`${Ku}px`,overflow:"hidden",...Pe(e)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{m(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},Ne.DURATION*1e3)}}},[t,s,i])}let Vs=null;function Hy({isOpen:e,modal:t,nested:s,hasBeenOpened:n,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=q.useState(()=>typeof window<"u"?window.location.href:""),u=q.useRef(0),m=q.useCallback(()=>{if(sl()&&Vs===null&&e&&!o){Vs={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:f,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-f}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const g=h-window.innerHeight;g&&u.current>=h&&(document.body.style.top=`${-(u.current+g)}px`)}),300)}},[e]),d=q.useCallback(()=>{if(sl()&&Vs!==null&&!o){const f=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Vs),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,f)}),Vs=null}},[i]);return q.useEffect(()=>{function f(){u.current=window.scrollY}return f(),window.addEventListener("scroll",f),()=>{window.removeEventListener("scroll",f)}},[]),q.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),q.useEffect(()=>{s||!n||(e?(!window.matchMedia("(display-mode: standalone)").matches&&m(),t||window.setTimeout(()=>{d()},500)):d())},[e,n,i,t,s,m,d]),{restorePositionSetting:d}}function Wy({open:e,onOpenChange:t,children:s,onDrag:n,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=_y,scrollLockTimeout:m=zy,dismissible:d=!0,handleOnly:f=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:g,setActiveSnapPoint:y,fixed:p,modal:b=!0,onClose:x,nested:S,noBodyStyles:w=!1,direction:v="bottom",defaultOpen:C=!1,disablePreventScroll:E=!0,snapToSequentialPoint:I=!1,preventScrollRestoration:N=!1,repositionInputs:D=!0,onAnimationEnd:A,container:O,autoFocus:L=!1}){var M,k;const[P=!1,F]=qu({defaultProp:C,prop:e,onChange:Q=>{t?.(Q),!Q&&!S&&ge(),setTimeout(()=>{A?.(Q)},Ne.DURATION*1e3),Q&&!b&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),Q||(document.body.style.pointerEvents="auto")}}),[j,R]=q.useState(!1),[T,V]=q.useState(!1),[Z,ee]=q.useState(!1),fe=q.useRef(null),W=q.useRef(null),te=q.useRef(null),ce=q.useRef(null),ie=q.useRef(null),U=q.useRef(!1),K=q.useRef(null),he=q.useRef(0),Se=q.useRef(!1),ye=q.useRef(!C),G=q.useRef(0),B=q.useRef(null),$=q.useRef(((M=B.current)==null?void 0:M.getBoundingClientRect().height)||0),le=q.useRef(((k=B.current)==null?void 0:k.getBoundingClientRect().width)||0),ue=q.useRef(0),De=q.useCallback(Q=>{o&&Q===ze.length-1&&(W.current=new Date)},[]),{activeSnapPoint:me,activeSnapPointIndex:Me,setActiveSnapPoint:pe,onRelease:de,snapPointsOffset:ze,onDrag:ut,shouldFade:H,getPercentageDragged:Ge}=Ky({snapPoints:o,activeSnapPointProp:g,setActiveSnapPointProp:y,drawerRef:B,fadeFromIndex:h,overlayRef:fe,onSnapPointChange:De,direction:v,container:O,snapToSequentialPoint:I});My({isDisabled:!P||T||!b||Z||!j||!D||!E});const{restorePositionSetting:ge}=Hy({isOpen:P,modal:b,nested:S??!1,hasBeenOpened:j,preventScrollRestoration:N,noBodyStyles:w});function be(){return(window.innerWidth-Ca)/window.innerWidth}function Ue(Q){var ae,ne;!d&&!o||B.current&&!B.current.contains(Q.target)||($.current=((ae=B.current)==null?void 0:ae.getBoundingClientRect().height)||0,le.current=((ne=B.current)==null?void 0:ne.getBoundingClientRect().width)||0,V(!0),te.current=new Date,Fu()&&window.addEventListener("touchend",()=>U.current=!1,{once:!0}),Q.target.setPointerCapture(Q.pointerId),he.current=Pe(v)?Q.pageY:Q.pageX)}function Ze(Q,ae){var ne;let re=Q;const ve=(ne=window.getSelection())==null?void 0:ne.toString(),Ce=B.current?An(B.current,v):null,Te=new Date;if(re.tagName==="SELECT"||re.hasAttribute("data-vaul-no-drag")||re.closest("[data-vaul-no-drag]"))return!1;if(v==="right"||v==="left")return!0;if(W.current&&Te.getTime()-W.current.getTime()<500)return!1;if(Ce!==null&&(v==="bottom"?Ce>0:Ce<0))return!0;if(ve&&ve.length>0)return!1;if(ie.current&&Te.getTime()-ie.current.getTime()<m&&Ce===0||ae)return ie.current=Te,!1;for(;re;){if(re.scrollHeight>re.clientHeight){if(re.scrollTop!==0)return ie.current=new Date,!1;if(re.getAttribute("role")==="dialog")return!0}re=re.parentNode}return!0}function et(Q){if(B.current&&T){const ae=v==="bottom"||v==="right"?1:-1,ne=(he.current-(Pe(v)?Q.pageY:Q.pageX))*ae,re=ne>0,ve=o&&!d&&!re;if(ve&&Me===0)return;const Ce=Math.abs(ne),Te=document.querySelector("[data-vaul-drawer-wrapper]"),Ve=v==="bottom"||v==="top"?$.current:le.current;let Be=Ce/Ve;const je=Ge(Ce,re);if(je!==null&&(Be=je),ve&&Be>=1||!U.current&&!Ze(Q.target,re))return;if(B.current.classList.add(na),U.current=!0,_e(B.current,{transition:"none"}),_e(fe.current,{transition:"none"}),o&&ut({draggedDistance:ne}),re&&!o){const Re=Fy(ne),qe=Math.min(Re*-1,0)*ae;_e(B.current,{transform:Pe(v)?`translate3d(0, ${qe}px, 0)`:`translate3d(${qe}px, 0, 0)`});return}const Qe=1-Be;if((H||h&&Me===h-1)&&(n?.(Q,Be),_e(fe.current,{opacity:`${Qe}`,transition:"none"},!0)),Te&&fe.current&&i){const Re=Math.min(be()+Be*(1-be()),1),qe=8-Be*8,z=Math.max(0,14-Be*14);_e(Te,{borderRadius:`${qe}px`,transform:Pe(v)?`scale(${Re}) translate3d(0, ${z}px, 0)`:`scale(${Re}) translate3d(${z}px, 0, 0)`,transition:"none"},!0)}if(!o){const Re=Ce*ae;_e(B.current,{transform:Pe(v)?`translate3d(0, ${Re}px, 0)`:`translate3d(${Re}px, 0, 0)`})}}}q.useEffect(()=>{window.requestAnimationFrame(()=>{ye.current=!0})},[]),q.useEffect(()=>{var Q;function ae(){if(!B.current||!D)return;const ne=document.activeElement;if(ka(ne)||Se.current){var re;const ve=((re=window.visualViewport)==null?void 0:re.height)||0,Ce=window.innerHeight;let Te=Ce-ve;const Ve=B.current.getBoundingClientRect().height||0,Be=Ve>Ce*.8;ue.current||(ue.current=Ve);const je=B.current.getBoundingClientRect().top;if(Math.abs(G.current-Te)>60&&(Se.current=!Se.current),o&&o.length>0&&ze&&Me){const Qe=ze[Me]||0;Te+=Qe}if(G.current=Te,Ve>ve||Se.current){const Qe=B.current.getBoundingClientRect().height;let Re=Qe;Qe>ve&&(Re=ve-(Be?je:Ca)),p?B.current.style.height=`${Qe-Math.max(Te,0)}px`:B.current.style.height=`${Math.max(Re,ve-je)}px`}else Cy()||(B.current.style.height=`${ue.current}px`);o&&o.length>0&&!Se.current?B.current.style.bottom="0px":B.current.style.bottom=`${Math.max(Te,0)}px`}}return(Q=window.visualViewport)==null||Q.addEventListener("resize",ae),()=>{var ne;return(ne=window.visualViewport)==null?void 0:ne.removeEventListener("resize",ae)}},[Me,o,ze]);function Ye(Q){Fe(),x?.(),Q||F(!1),setTimeout(()=>{o&&pe(o[0])},Ne.DURATION*1e3)}function Ae(){if(!B.current)return;const Q=document.querySelector("[data-vaul-drawer-wrapper]"),ae=An(B.current,v);_e(B.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${Ne.DURATION}s cubic-bezier(${Ne.EASE.join(",")})`}),_e(fe.current,{transition:`opacity ${Ne.DURATION}s cubic-bezier(${Ne.EASE.join(",")})`,opacity:"1"}),i&&ae&&ae>0&&P&&_e(Q,{borderRadius:`${Ku}px`,overflow:"hidden",...Pe(v)?{transform:`scale(${be()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${be()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${Ne.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Ne.EASE.join(",")})`},!0)}function Fe(){!T||!B.current||(B.current.classList.remove(na),U.current=!1,V(!1),ce.current=new Date)}function We(Q){if(!T||!B.current)return;B.current.classList.remove(na),U.current=!1,V(!1),ce.current=new Date;const ae=An(B.current,v);if(!Q||!Ze(Q.target,!1)||!ae||Number.isNaN(ae)||te.current===null)return;const ne=ce.current.getTime()-te.current.getTime(),re=he.current-(Pe(v)?Q.pageY:Q.pageX),ve=Math.abs(re)/ne;if(ve>.05&&(ee(!0),setTimeout(()=>{ee(!1)},200)),o){de({draggedDistance:re*(v==="bottom"||v==="right"?1:-1),closeDrawer:Ye,velocity:ve,dismissible:d}),a?.(Q,!0);return}if(v==="bottom"||v==="right"?re>0:re<0){Ae(),a?.(Q,!0);return}if(ve>Bu){Ye(),a?.(Q,!1);return}var Ce;const Te=Math.min((Ce=B.current.getBoundingClientRect().height)!=null?Ce:0,window.innerHeight);var Ve;const Be=Math.min((Ve=B.current.getBoundingClientRect().width)!=null?Ve:0,window.innerWidth),je=v==="left"||v==="right";if(Math.abs(ae)>=(je?Be:Te)*u){Ye(),a?.(Q,!1);return}a?.(Q,!0),Ae()}q.useEffect(()=>(P&&(_e(document.documentElement,{scrollBehavior:"auto"}),W.current=new Date),()=>{Ly(document.documentElement,"scrollBehavior")}),[P]);function tt(Q){const ae=Q?(window.innerWidth-ss)/window.innerWidth:1,ne=Q?-ss:0;K.current&&window.clearTimeout(K.current),_e(B.current,{transition:`transform ${Ne.DURATION}s cubic-bezier(${Ne.EASE.join(",")})`,transform:Pe(v)?`scale(${ae}) translate3d(0, ${ne}px, 0)`:`scale(${ae}) translate3d(${ne}px, 0, 0)`}),!Q&&B.current&&(K.current=setTimeout(()=>{const re=An(B.current,v);_e(B.current,{transition:"none",transform:Pe(v)?`translate3d(0, ${re}px, 0)`:`translate3d(${re}px, 0, 0)`})},500))}function st(Q,ae){if(ae<0)return;const ne=(window.innerWidth-ss)/window.innerWidth,re=ne+ae*(1-ne),ve=-ss+ae*ss;_e(B.current,{transform:Pe(v)?`scale(${re}) translate3d(0, ${ve}px, 0)`:`scale(${re}) translate3d(${ve}px, 0, 0)`,transition:"none"})}function ke(Q,ae){const ne=Pe(v)?window.innerHeight:window.innerWidth,re=ae?(ne-ss)/ne:1,ve=ae?-ss:0;ae&&_e(B.current,{transition:`transform ${Ne.DURATION}s cubic-bezier(${Ne.EASE.join(",")})`,transform:Pe(v)?`scale(${re}) translate3d(0, ${ve}px, 0)`:`scale(${re}) translate3d(${ve}px, 0, 0)`})}return q.useEffect(()=>{b||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[b]),q.createElement(ju,{defaultOpen:C,onOpenChange:Q=>{!d&&!Q||(Q?R(!0):Ye(!0),F(Q))},open:P},q.createElement(Lu.Provider,{value:{activeSnapPoint:me,snapPoints:o,setActiveSnapPoint:pe,drawerRef:B,overlayRef:fe,onOpenChange:t,onPress:Ue,onRelease:We,onDrag:et,dismissible:d,shouldAnimate:ye,handleOnly:f,isOpen:P,isDragging:T,shouldFade:H,closeDrawer:Ye,onNestedDrag:st,onNestedOpenChange:tt,onNestedRelease:ke,keyboardIsOpen:Se,modal:b,snapPointsOffset:ze,activeSnapPointIndex:Me,direction:v,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:w,container:O,autoFocus:L}},s))}const Hu=q.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:n,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=bn(),m=_u(t,s),d=n&&n.length>0;if(!l)return null;const f=q.useCallback(h=>a(h),[a]);return q.createElement(Tu,{onMouseUp:f,ref:m,"data-vaul-overlay":"","data-vaul-snap-points":i&&d?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});Hu.displayName="Drawer.Overlay";const Wu=q.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...n},a){const{drawerRef:o,onPress:i,onRelease:l,onDrag:u,keyboardIsOpen:m,snapPointsOffset:d,activeSnapPointIndex:f,modal:h,isOpen:g,direction:y,snapPoints:p,container:b,handleOnly:x,shouldAnimate:S,autoFocus:w}=bn(),[v,C]=q.useState(!1),E=_u(a,o),I=q.useRef(null),N=q.useRef(null),D=q.useRef(!1),A=p&&p.length>0;qy();const O=(M,k,P=0)=>{if(D.current)return!0;const F=Math.abs(M.y),j=Math.abs(M.x),R=j>F,T=["bottom","right"].includes(k)?1:-1;if(k==="left"||k==="right"){if(!(M.x*T<0)&&j>=0&&j<=P)return R}else if(!(M.y*T<0)&&F>=0&&F<=P)return!R;return D.current=!0,!0};q.useEffect(()=>{A&&window.requestAnimationFrame(()=>{C(!0)})},[]);function L(M){I.current=null,D.current=!1,l(M)}return q.createElement(Ru,{"data-vaul-drawer-direction":y,"data-vaul-drawer":"","data-vaul-delayed-snap-points":v?"true":"false","data-vaul-snap-points":g&&A?"true":"false","data-vaul-custom-container":b?"true":"false","data-vaul-animate":S?.current?"true":"false",...n,ref:E,style:d&&d.length>0?{"--snap-point-height":`${d[f??0]}px`,...t}:t,onPointerDown:M=>{x||(n.onPointerDown==null||n.onPointerDown.call(n,M),I.current={x:M.pageX,y:M.pageY},i(M))},onOpenAutoFocus:M=>{s?.(M),w||M.preventDefault()},onPointerDownOutside:M=>{if(e?.(M),!h||M.defaultPrevented){M.preventDefault();return}m.current&&(m.current=!1)},onFocusOutside:M=>{if(!h){M.preventDefault();return}},onPointerMove:M=>{if(N.current=M,x||(n.onPointerMove==null||n.onPointerMove.call(n,M),!I.current))return;const k=M.pageY-I.current.y,P=M.pageX-I.current.x,F=M.pointerType==="touch"?10:2;O({x:P,y:k},y,F)?u(M):(Math.abs(P)>F||Math.abs(k)>F)&&(I.current=null)},onPointerUp:M=>{n.onPointerUp==null||n.onPointerUp.call(n,M),I.current=null,D.current=!1,l(M)},onPointerOut:M=>{n.onPointerOut==null||n.onPointerOut.call(n,M),L(N.current)},onContextMenu:M=>{n.onContextMenu==null||n.onContextMenu.call(n,M),N.current&&L(N.current)}})});Wu.displayName="Drawer.Content";const Vy=250,Qy=120,Vu=q.forwardRef(function({preventCycle:e=!1,children:t,...s},n){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:l,setActiveSnapPoint:u,dismissible:m,handleOnly:d,isOpen:f,onPress:h,onDrag:g}=bn(),y=q.useRef(null),p=q.useRef(!1);function b(){if(p.current){w();return}window.setTimeout(()=>{x()},Qy)}function x(){if(o||e||p.current){w();return}if(w(),!i||i.length===0){m||a();return}if(l===i[i.length-1]&&m){a();return}const C=i.findIndex(I=>I===l);if(C===-1)return;const E=i[C+1];u(E)}function S(){y.current=window.setTimeout(()=>{p.current=!0},Vy)}function w(){y.current&&window.clearTimeout(y.current),p.current=!1}return q.createElement("div",{onClick:b,onPointerCancel:w,onPointerDown:v=>{d&&h(v),S()},onPointerMove:v=>{d&&g(v)},ref:n,"data-vaul-drawer-visible":f?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},q.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});Vu.displayName="Drawer.Handle";function Gy(e){const t=bn(),{container:s=t.container,...n}=e;return q.createElement(Iu,{container:s,...n})}const ct={Root:Wy,Content:Wu,Overlay:Hu,Portal:Gy,Handle:Vu,Title:Ou},Qu="inline-flex items-center justify-center transition-colors",Yy=Le(Qu,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Xy=Le(Qu,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),jr=({accountId:e,currentMailboxId:t,onMove:s,disabled:n=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),m=Vt(),d=c.useRef(null),f=i??"Move to folder",h=c.useId(),{t:g}=er("mail",{useSuspense:!1}),y=c.useCallback((L,M)=>g(L,{defaultValue:M}),[g]),{data:p,isLoading:b,isError:x,error:S,refetch:w}=xe({...ot({path:{accountId:e}}),staleTime:1/0,enabled:l}),v=ko(e),{createFolder:C}=Gl(e),E=c.useMemo(()=>{const L=Ja(p?.items??[],v),M=un(v);return L.map(k=>({id:k.mailboxId,label:Ts(k,M.get(k.mailboxId),y),searchValue:k.fullPath,isCurrent:k.mailboxId===t}))},[p?.items,v,t,y]),I=c.useCallback(L=>{u(!1),s(L)},[s]),N=c.useCallback(async(L,M)=>{const k=await C(L,M);return{id:k.id,label:k.label}},[C]);c.useEffect(()=>{if(!l||!m)return;const L=k=>{d.current&&!d.current.contains(k.target)&&u(!1)},M=k=>{k.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",L),document.addEventListener("keydown",M),()=>{document.removeEventListener("mousedown",L),document.removeEventListener("keydown",M)}},[l,m]);const D=n||!!a,A=r.jsxs("button",{type:"button",onClick:L=>{L.stopPropagation(),!D&&u(M=>!M)},"aria-label":f,"aria-haspopup":m?"listbox":"dialog","aria-expanded":l,"aria-controls":l?h:void 0,title:a,className:o==="icon-only"?Yy:Xy,children:[r.jsx(Oa,{className:o==="icon-only"?"size-5":"size-4"}),o==="compact"&&r.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),O=b?r.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):x?r.jsx("div",{className:"p-3",children:r.jsx(Qt,{variant:"inline",title:"Couldn't load folders",error:S,onRetry:()=>w()})}):r.jsx(Al,{mailboxes:E,onSelect:I,onCreateFolder:N,onCancel:()=>u(!1),autoFocus:!m,labels:{createLabel:L=>`Create "${L}"`,searchPlaceholder:g("move_picker_placeholder",{defaultValue:"Move to…"}),searchAriaLabel:g("move_picker_filter_label",{defaultValue:"Filter folders"}),optionLabel:L=>`Move to ${L}`,currentSuffix:"(current folder)",currentTag:"current",emptyMessage:L=>`No folders match "${L}"`}});return m?r.jsxs("div",{ref:d,className:"relative inline-block",children:[A,l&&r.jsx("div",{id:h,className:Le("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:O})]}):r.jsxs(r.Fragment,{children:[A,r.jsx(ct.Root,{open:l,onOpenChange:u,children:r.jsxs(ct.Portal,{children:[r.jsx(ct.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(ct.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{maxHeight:"85dvh"},id:h,children:[r.jsx(ct.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),r.jsx(ct.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),r.jsx("div",{className:"flex-1 overflow-hidden",children:O})]})]})})]})},Jy=({messageId:e,threadId:t,mailboxId:s,isRead:n,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const m=Ee(),d=He(),{pushError:f}=it(),{selectedMessageId:h}=Rs({strict:!1}),{mutate:g,isPending:y}=Oe({...ar(),onMutate:async P=>{const F=P.body.isRead??!0,j=new Set(P.body.messageIds??[]),R=ds({path:{threadId:t}}),T=Rt([s]);await Promise.all([m.cancelQueries({queryKey:R}),hn(m,T)]);const V=m.getQueriesData({queryKey:R}).filter(ee=>ee[1]!==void 0).map(([ee,fe])=>({queryKey:ee,data:fe})),Z=pn(m,T);return m.setQueriesData({queryKey:R},ee=>ee&&{...ee,items:Wn(ee.items,j,F)}),gn(m,T,ee=>Wn(ee,j,F)),{threadMessagesPrefix:R,listPrefixes:T,previousThreadMessages:V,previousThreadsList:Z}},onError:(P,F,j)=>{if(j){for(const T of j.previousThreadMessages)m.setQueryData(T.queryKey,T.data);xn(m,j.previousThreadsList)}const R=F.body.isRead??!0;f({title:R?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(P),error:P})},onSettled:(P,F,j,R)=>{R&&(m.invalidateQueries({queryKey:R.threadMessagesPrefix}),Mt(m,R.listPrefixes))}}),p=c.useCallback(P=>{h&&P.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:F=>({...F,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:b,isPending:x}=ls({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:S,isPending:w}=is({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:v,isPending:C,error:E,reset:I}=Co({messageId:e}),N=()=>{g({body:{messageIds:[e],isRead:!1}})},D=()=>{b([e])},A=()=>{o&&v(o,i)},O=y||x||w||C,L=O||!o,M=c.useCallback(P=>{S([e],P)},[S,e]),k=o?void 0:"Sender has no parseable address";return r.jsxs("div",{className:"flex flex-col items-end gap-1",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[a&&r.jsx(jr,{accountId:a,currentMailboxId:s,onMove:M,disabled:O,label:"Move this message"}),r.jsxs(Zc,{trigger:r.jsx(cc,{className:"size-4"}),children:[r.jsxs(Cs,{onClick:A,disabled:L,children:[i?r.jsx(cr,{className:"size-4 text-positive"}):r.jsx(on,{className:"size-4 opacity-0"}),r.jsx("span",{title:k,children:"Trusted sender"})]}),n&&r.jsxs(Cs,{onClick:N,disabled:O,children:[r.jsx(ur,{className:"size-4"}),"Mark as unread"]}),u&&r.jsxs(Cs,{onClick:u,children:[r.jsx(lc,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),r.jsx(ya,{}),r.jsxs(Cs,{onClick:D,disabled:O,destructive:!0,children:[r.jsx(Et,{className:"size-4"}),"Delete"]})]})]}),E&&r.jsx("div",{className:"w-64",children:r.jsx(Qt,{variant:"inline",title:"Couldn't update trust",error:E,onRetry:()=>{I(),A()}})})]})},Zy=()=>{const[e,t]=c.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return c.useEffect(()=>{const s=document.documentElement,n=new MutationObserver(()=>{t(s.classList.contains("dark"))});return n.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e},e0=({blockedImageCount:e,canAlwaysTrust:t,isTrustPending:s,onLoadOnce:n,onAlwaysTrust:a})=>r.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-md bg-surface-sunken/50 px-3 py-2 text-sm",children:[r.jsxs("span",{className:"text-fg-muted",children:[e," image",e>1?"s":""," blocked for privacy"]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("button",{type:"button",onClick:n,className:"text-accent hover:underline",children:"Load once"}),t&&r.jsx("button",{type:"button",onClick:a,"aria-busy":s,className:"text-accent hover:underline aria-busy:opacity-50",children:s?"Trusting…":"Always trust"})]})]}),t0=(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}}},s0=e=>e instanceof ns?e.reason:"generic",n0=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",r0=({error:e,onRetry:t})=>{const s=s0(e),n=n0(e),{title:a,detail:o}=t0(s,n),[i,l]=c.useState(!1),{Account:u}=Ba();return i?null:r.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[r.jsx(cs,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"font-medium text-danger",children:a}),r.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&r.jsx(u,{children:({signOut:m})=>r.jsx("button",{type:"button",onClick:()=>m(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&r.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),r.jsx("button",{type:"button",onClick:()=>l(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:r.jsx(vt,{className:"size-4","aria-hidden":"true"})})]})]})},a0=()=>r.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),ol=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Gu=({bodyParts:e,html:t,text:s,isTrusted:n=!1,messageId:a,fromAddressId:o,category:i,className:l})=>{const[u,m]=c.useState(!1),d=n||u,f=Zy(),{toggleTrusted:h,isPending:g}=Co({messageId:a??""}),y=!!e&&e.length>0,{picked:p,data:b,isLoading:x,isError:S,error:w,refetch:v}=du({messageId:a,bodyParts:e,enabled:y}),C=c.useMemo(()=>kp(e??[]),[e]),E=y&&b?.kind==="html"?b.body:t,I=y&&b?.kind==="text"?b.body:s;if(y){if(x)return r.jsx("div",{className:Le("message-body",l),children:r.jsx(a0,{})});if(S)return r.jsx("div",{className:Le("message-body",l),children:r.jsx(r0,{error:w,onRetry:()=>v()})});if(!p)return r.jsx("div",{className:Le("message-body",l),children:r.jsx(ol,{})})}else if(!t&&!s)return r.jsx("div",{className:Le("message-body",l),children:r.jsx(ol,{})});const N=!!(o&&a),D=()=>{!o||g||(m(!0),h(o,!1))};return r.jsx(jc,{className:l,html:E,text:I,isDark:f,category:i,allowImages:d,resolveCid:C,renderBlockedNotice:A=>r.jsx(e0,{blockedImageCount:A,canAlwaysTrust:N,isTrustPending:g,onLoadOnce:()=>m(!0),onAlwaysTrust:D})})},o0=({messageId:e,threadId:t,mailboxId:s,accountId:n,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:l,isTrusted:u,showRaw:m,onToggleRaw:d,onReply:f,onReplyAll:h,onForward:g})=>{const y=Ee(),{deleteMessages:p}=ls({mailboxId:s,threadId:t}),{moveMessages:b}=is({mailboxId:s,threadId:t,accountId:n}),{toggleTrusted:x}=Co({messageId:e}),{mutate:S}=Oe({...ar(),onSettled:()=>{y.invalidateQueries({queryKey:ds({path:{threadId:t}})}),Mt(y,Rt([s]))}}),w=c.useCallback(I=>{b([e],I)},[b,e]),v=c.useCallback(()=>{p([e])},[p,e]),C=c.useCallback(()=>{S({body:{messageIds:[e],isRead:!a}})},[S,e,a]),E=[];return l&&E.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?r.jsx(cr,{className:"size-4 text-positive"}):r.jsx(on,{className:"size-4"}),onSelect:()=>x(l,u)}),d&&E.push({key:"raw",label:m?"Show formatted":"Show raw email",icon:r.jsx(lc,{className:"size-4"}),onSelect:d}),r.jsx(Cc,{hasThread:!0,onReply:f,onReplyAll:h,onForward:g,isStarred:o,onToggleStar:i,onDelete:v,isRead:a,onToggleRead:C,overflowItems:E,moveSlot:n?r.jsx(jr,{accountId:n,currentMailboxId:s,onMove:w,label:"Move this message"}):void 0})},i0=()=>r.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading raw email",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"})]}),l0=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:n,isError:a,error:o,refetch:i}=xe({...am({path:{messageId:e}}),enabled:t});if(n)return r.jsx("div",{className:"message-body",children:r.jsx(i0,{})});if(a)return r.jsx("div",{className:"message-body",children:r.jsx(Qt,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const l=s?.raw??"";return l===""?r.jsx("div",{className:"message-body",children:r.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):r.jsx("div",{className:"message-body",children:r.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:l})})},c0=()=>r.jsx(cr,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),Yu=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),Xu=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:Le("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":Le("text-fg-subtle hover:text-warning",n&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:r.jsx(Ht,{className:Le("size-3.5",e&&"fill-current")})}),u0=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:n,isStarPending:a})=>{const o=Vl(e.sentDate,"datetime"),i=Yu(e,o);return r.jsx(Nc,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:r.jsxs(r.Fragment,{children:[e.hasAttachment&&r.jsx(dr,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx(Xu,{isStarred:e.hasStars,onToggleStar:n,isStarPending:a,hoverReveal:!0}),r.jsx("span",{"data-testid":"message-date",className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:o})]})})},d0=({threadMessage:e,messageData:t,isLoading:s,isError:n,error:a,onRetry:o,isFocused:i,onToggle:l,onToggleStar:u,isStarPending:m,accountId:d,showRaw:f,onToggleRaw:h,mobile:g,onReply:y,onReplyAll:p,onForward:b})=>{const x=Vl(e.sentDate,"long"),S=!e.isRead,w=t?.envelope.from[0]?.flags?.trusted?.value===!0,v=t?.envelope.from[0]?.addressId,C=Yu(e,x),E=e.autoMoved?r.jsx(uy,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved}):null;return r.jsx(Ec,{message:C,isFocused:g?!1:i,onHeaderClick:l,senderBadge:w?r.jsx(c0,{}):void 0,trailing:r.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:x}),to:t?r.jsx(Gh,{label:"To",addresses:t.envelope.to}):null,indicators:E||!g?r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[E,!g&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[r.jsx(Xu,{isStarred:e.hasStars,onToggleStar:u,isStarPending:m}),e.hasAttachment&&r.jsx("span",{className:"text-fg-subtle p-0.5",children:r.jsx(dr,{className:"size-3.5"})})]}),S&&r.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:g?void 0:r.jsx(Jy,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:v,isTrusted:w,showRaw:f,onToggleRaw:h}),actionBar:g?r.jsx(o0,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:v,isTrusted:w,showRaw:f,onToggleRaw:h,onReply:y,onReplyAll:p,onForward:b}):void 0,body:s?r.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):n&&om(a)?r.jsx("div",{className:"mt-3",children:r.jsx(xu,{message:"This message has been deleted"})}):n?r.jsx("div",{className:"mt-3",children:r.jsx(Qt,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):f?r.jsx("div",{className:"mt-3",children:r.jsx(l0,{messageId:e.messageId})}):r.jsx("div",{className:"mt-3",children:r.jsx(Gu,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:w,category:Sr(e.category)})})})},f0=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,mobile:l,onReply:u,onReplyAll:m,onForward:d})=>{const[f,h]=c.useState(!1),{data:g,isLoading:y,isError:p,error:b,refetch:x}=xe({...or({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?r.jsx(d0,{threadMessage:e,messageData:g,isLoading:y,isError:p,error:b,onRetry:()=>x(),isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,showRaw:f,onToggleRaw:()=>h(S=>!S),mobile:l,onReply:u,onReplyAll:m,onForward:d}):r.jsx(u0,{threadMessage:e,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o})},m0=()=>r.jsxs("div",{className:"animate-pulse p-4",children:[r.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),r.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>r.jsxs("div",{className:"flex gap-3 py-3",children:[r.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function il({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?r.jsxs("div",{className:"flex items-start gap-2 rounded-none border-b border-danger/20 bg-danger-soft px-5 py-2.5 text-sm",children:[r.jsx(Ls,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",r.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&r.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const zs=({threadId:e,mailboxId:t,subject:s,selectedMessageId:n,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:l,onComposeClose:u,onSwipeNext:m,onSwipePrevious:d,mobileIntelligenceOpen:f})=>{const h=Vt(),{handlers:g}=ey({onSwipeLeft:m,onSwipeRight:d}),{accountId:y}=vo(t),{data:p,isLoading:b,isError:x,error:S,refetch:w}=xe({...im({path:{threadId:e}})}),v=c.useMemo(()=>p?.items??[],[p?.items]),C=v[v.length-1],E=c.useRef(new Map),[I,N]=c.useState(new Set),[D,A]=c.useState(null),[O,L]=c.useState(0);c.useEffect(()=>{if(v.length>0&&e!==D){A(e);const $=new Set([v[v.length-1].threadMessageId]);if(n){const le=v.find(ue=>ue.messageId===n);le&&$.add(le.threadMessageId)}N($),L(v.length-1)}},[e,v,D,n]);const M=c.useCallback($=>{N(le=>{const ue=new Set(le);return ue.has($)?ue.delete($):ue.add($),ue})},[]),k=c.useCallback($=>{const le=v[$];if(!le)return;E.current.get(le.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[v]),P=c.useCallback(()=>{if(v.length===0)return;const $=Math.min(O+1,v.length-1);L($),k($)},[v.length,O,k]),F=c.useCallback(()=>{if(v.length===0)return;const $=Math.max(O-1,0);L($),k($)},[v.length,O,k]),j=c.useCallback(()=>{const $=v[O];$&&M($.threadMessageId)},[v,O,M]),{data:R}=xe({...It(),staleTime:1/0}),T=R?.accounts?.[0],V=!!T?.smtpHost;Yv({messages:v,expandedIds:I,threadId:e,mailboxId:t,accountId:T?.accountId});const{toggleStar:Z,isPending:ee,pendingMessageId:fe}=yo({threadId:e,mailboxId:t,messages:v}),[W,te]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(te(l),u?.())},[l,u]);const{data:ce}=xe({...or({path:{messageId:C?.messageId??""}}),enabled:!!C&&W!==null}),ie=c.useCallback(()=>{te("reply")},[]),U=c.useCallback(()=>{te("reply_all")},[]),K=c.useCallback(()=>{te("forward")},[]),he=c.useCallback(()=>{te(null),u?.()},[u]);if(bo({enabled:!b&&v.length>0&&W===null,bindings:[{key:"j",handler:P,preventDefault:!0},{key:"ArrowDown",handler:P,preventDefault:!0},{key:"k",handler:F,preventDefault:!0},{key:"ArrowUp",handler:F,preventDefault:!0},{key:"Enter",handler:j,preventDefault:!0},{key:"o",handler:j,preventDefault:!0},...V?[{key:"r",handler:ie,preventDefault:!0},{key:"R",handler:U,noModifiers:!1,preventDefault:!0},{key:"f",handler:K,preventDefault:!0}]:[]]}),b)return r.jsx(m0,{});if(x)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(Qt,{title:"Couldn't load this conversation",error:S,onRetry:()=>w()})});if(v.length===0)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(xu,{message:"No messages in this thread"})});const Se=s||v[0]?.subject||"(No subject)",ye=v.length,G=$=>r.jsx("div",{children:v.map((le,ue)=>r.jsx("div",{ref:De=>{De&&E.current.set(le.threadMessageId,De)},children:r.jsx(f0,{threadMessage:le,isExpanded:I.has(le.threadMessageId),isFocused:ue===O,onToggle:()=>M(le.threadMessageId),onToggleStar:()=>Z(le.messageId,le.hasStars),isStarPending:ee&&fe===le.messageId,accountId:y,mobile:$,onReply:$&&V?ie:void 0,onReplyAll:$&&V?U:void 0,onForward:$&&V?K:void 0})},le.threadMessageId))}),B=r.jsxs("header",{className:"border-b border-line px-5 pt-5 pb-3",children:[r.jsx("h1",{className:"max-w-2xl text-lg font-semibold leading-snug text-fg",children:Se}),r.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[ye," ",ye===1?"message":"messages"]})]});return h?r.jsxs("article",{className:"h-full flex flex-col",children:[B,a?.dkimMismatch&&r.jsx(il,{authenticity:a,onOpenIntelligence:o}),r.jsx("div",{className:"flex-1 overflow-auto",children:G(!1)}),W!==null&&r.jsx(Ji,{mode:W,account:T,sourceMessage:ce,onClose:he})]}):r.jsxs(Qp,{thread:{subject:Se,messages:[]},onBack:i??(()=>{}),intelligenceOpen:f,onToggleIntelligence:o,touchHandlers:g,children:[a?.dkimMismatch&&r.jsx(il,{authenticity:a,onOpenIntelligence:o}),G(!0),W!==null&&r.jsx(Ji,{mode:W,account:T,sourceMessage:ce,onClose:he})]})},h0=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function Ju(e){return!!e&&h0.has(e)}const Zu=3e3,p0=Zu*2,ll={syncing:!1,resolved:!1,synced:0,total:0};function g0(e,t){const s=e.join(","),[n,a]=c.useState(!1),[o,i]=c.useState(!1);c.useEffect(()=>{a(!1),i(!1)},[s,t]),c.useEffect(()=>{if(!t)return;const y=setTimeout(()=>i(!0),p0);return()=>clearTimeout(y)},[s,t]);const l=mt({queries:e.map(y=>({...lm({path:{accountId:y}}),enabled:t&&!n,refetchInterval:Zu,meta:{softError:!0}}))}),u=l.every(y=>y.isSuccess||y.isError),m=l.length===0||u||o;let d=!1,f=0,h=0;for(const y of l)if(Ju(y.data?.syncPhase)){d=!0;for(const p of y.data?.mailboxes??[])f+=p.messagesSynced,h+=p.messagesTotal}const g=t&&m&&!d;return c.useEffect(()=>{g&&a(!0)},[g]),!t||!m?ll:{syncing:d,resolved:!0,synced:f,total:h}}function ms(){const{mailboxNameIndex:e,accountNameIndex:t}=Ie();return{...jt({select:n=>ou(n.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Io=e=>e.trim().toLocaleLowerCase(),ed={personal:"Personal",uncategorized:"Unclassified",transactional:"Transactional",newsletter:"Newsletter",marketing:"Marketing",social:"Social",automated:"Automated"},x0=Object.values(at).map(e=>({value:e,label:ed[e]})),b0={unclassified:"uncategorized"},ja=[{name:"from",label:"Sender",values:"contact"},{name:"subject",label:"Subject",values:"text"},{name:"category",label:"Category",values:"fixed",options:x0},{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"}],v0=new Map(ja.map(e=>[e.name,e])),td=e=>v0.get(e.toLowerCase()),y0=/^\d{4}-\d{2}-\d{2}$/,w0=e=>/[\s"]/.test(e),S0=e=>w0(e)?`"${e.replace(/"/g,"")}"`:e,sd=(e,t)=>`${e}:${S0(t)}`,k0=e=>{if(!e.startsWith('"'))return e;const t=e.slice(1);return t.endsWith('"')?t.slice(0,-1):t};function To(e){const t=[];let s=-1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];if(o==='"'){n=!n,s<0&&(s=a);continue}if(!n&&/\s/.test(o)){s>=0&&t.push({raw:e.slice(s,a),start:s,end:a}),s=-1;continue}s<0&&(s=a)}return s>=0&&t.push({raw:e.slice(s),start:s,end:e.length}),t}function nd(e){const t=e.indexOf(":");if(t<=0)return;const s=e.slice(t+1);return{name:e.slice(0,t).toLowerCase(),value:k0(s),rawValue:s}}function C0(e,t,s){if(!y0.test(s))return;const n=Date.parse(`${s}T00:00:00Z`);if(!Number.isNaN(n))return{type:e,raw:t,value:s,epochSeconds:Math.floor(n/1e3)}}function j0(e){const t=e.toLowerCase(),s=b0[t];return s||Object.values(at).find(a=>a===t)}function N0(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 E0(e,t){const s=nd(e);if(!s||s.value.length===0)return;const{name:n,value:a}=s;switch(n){case"from":return{type:"from",raw:e,value:a};case"subject":return{type:"subject",raw:e,value:a};case"category":{const o=j0(a);return o?{type:"category",raw:e,value:a,category:o}:void 0}case"is":return N0(e,a);case"has":return a.toLowerCase()==="attachment"?{type:"hasAttachment",raw:e}:void 0;case"before":case"after":return C0(n,e,a);case"in":{const o=t.mailboxesByName?.get(a.toLowerCase());return o?{type:"in",raw:e,value:a,mailboxId:o}:void 0}case"account":{const o=t.accountsByName?.get(a.toLowerCase());return o?{type:"account",raw:e,value:a,accountId:o}:void 0}default:return}}function Bs(e,t={}){const s=[],n=[];for(const a of To(e)){const o=E0(a.raw,t);o?s.push(o):n.push(a.raw)}return{freeText:n.join(" "),tokens:s}}function I0(e,t){return To(e).filter(s=>s.raw!==t.raw).map(s=>s.raw).join(" ")}function rd(e){switch(e.type){case"from":return`From: ${e.value}`;case"subject":return`Subject: ${e.value}`;case"category":return`Category: ${ed[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 T0=20,R0=new Set(Object.values(at)),M0=e=>e!==void 0&&R0.has(e)?e:void 0,A0=e=>{if(e.some(t=>t.type==="isUnread"))return!1;if(e.some(t=>t.type==="isRead"))return!0};function ad({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Ie(),n=ms(),a=jt({select:v=>v.matches}),o=Io(s),{freeText:i,tokens:l}=Bs(o,n),u=i.length>0,m=l.find(v=>v.type==="category"),d=M0(t)??m?.category,f=l.some(v=>v.type==="hasAttachment")?!0:void 0,h=l.some(v=>v.type==="isStarred")?!0:void 0,g=A0(l),y=l.find(v=>v.type==="after"),p=l.find(v=>v.type==="before"),b=l.find(v=>v.type==="in"),x=av({matches:a,callerMailboxId:e,inTokenMailboxId:b?.mailboxId}),{data:S,isLoading:w}=xe({...Kl({query:{query:i,mailboxId:x,limit:T0,...d!==void 0?{category:d}:{},...f!==void 0?{hasAttachment:f}:{},...h!==void 0?{hasStars:h}:{},...g!==void 0?{isRead:g}:{},...y?{sentDateFrom:y.epochSeconds}:{},...p?{sentDateTo:p.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:S?.items??[],isLoading:u&&w}}const O0=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),D0=e=>[...e].sort(O0);function Qn(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:yt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Sr(e.category),suspicious:t}}function cl(e){return e.filter(t=>t.muted!==!0)}function P0(e,t){const s=new Set,n=[];for(const a of[...e,...t])s.has(a.id)||(s.add(a.id),n.push(a));return n.sort((a,o)=>(o.sentDate??0)-(a.sentDate??0))}const ul=[{id:"personal",label:"Personal",category:at.personal},{id:"transactional",label:"Transactional",category:at.transactional},{id:"newsletter",label:"Newsletter",category:at.newsletter},{id:"marketing",label:"Marketing",category:at.marketing},{id:"social",label:"Social",category:at.social},{id:"automated",label:"Automated",category:at.automated},{id:"uncategorized",label:"Unclassified",category:at.uncategorized}];function L0(e){const t=new Map(ul.map(n=>[n.category,[]]));for(const n of e){const a=n.category??at.uncategorized;(t.get(a)??t.get(at.uncategorized))?.push(n)}const s=[];for(const n of ul){const a=t.get(n.category);a&&a.length>0&&s.push({id:n.id,label:n.label,threads:a})}return s}function od(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Ro(e,t){return t.every(s=>{switch(s.type){case"from":{const n=s.value.toLowerCase();return e.fromEmail.toLowerCase().includes(n)||e.fromName.toLowerCase().includes(n)}case"subject":return e.subject.toLowerCase().includes(s.value.toLowerCase());case"category":return(e.category??"uncategorized")===s.category;case"hasAttachment":return e.hasAttachment===!0;case"isUnread":return!e.isRead;case"isRead":return e.isRead===!0;case"isStarred":return e.starred===!0;case"after":return e.sentDate!=null&&e.sentDate>=s.epochSeconds*1e3;case"before":return e.sentDate!=null&&e.sentDate<s.epochSeconds*1e3;case"in":return e.mailboxId===s.mailboxId;case"account":return e.accountId===s.accountId;default:return!1}})}const F0={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function $0(e){return F0[e]??e}function _0(e,t){const{folder:s}=Va(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:yt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function id(e,t){const{folder:s}=Va(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 z0(e,t){const{mailboxId:s,folder:n}=Va(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?yt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:$0(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...n?{folder:n}:{}}}function ld(e,t,s){const n=new Set(t),a=[];for(const o of[...e].sort((i,l)=>l.score-i.score))n.has(o.threadId)||(n.add(o.threadId),a.push(z0(o,s)));return a}const B0=e=>{const{mailboxId:t,messages:s}=e,n=Ee(),{pushError:a}=it(),{mutateAsync:o,isPending:i}=Oe({...cm(),onError:(u,m)=>{a({title:m.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:ft(u),error:u})},onSettled:(u,m,d)=>{Mt(n,Rt(yr(d.body.messageIds??[],s??[],t)))}});return{applyLabel:c.useCallback((u,m,d)=>{u.length!==0&&vr(u,f=>o({body:{messageIds:f,labelId:m,action:d}}))},[o]),isPending:i}};function cd({accountId:e,mailboxId:t,messageIds:s}){const{labels:n}=Za(e),{applyLabel:a}=B0({mailboxId:t}),o=c.useMemo(()=>n.map(i=>({key:i.labelId,label:i.name,icon:r.jsx("span",{className:`size-2.5 rounded-full ${um(i.color)?Uo[i.color]:Uo.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[n,s,a]);return o.length===0?null:r.jsx(io,{triggerLabel:"Apply label to selected messages",triggerIcon:r.jsx(dm,{className:"size-4 text-fg-subtle"}),triggerText:"Apply label",items:o,align:"start",nested:!0,touch:!1,triggerClassName:"min-h-11 w-full justify-start gap-3 px-4 py-2.5 text-sm font-normal text-fg"})}const K0=768,U0=1024,ud=e=>e!=="desktop",Nr=()=>{const e=Ho(`(min-width: ${K0}px)`);return Ho(`(min-width: ${U0}px)`)?"desktop":e?"tablet":"phone"},dd=8;function Mo(e,t){const s=Math.max(0,Math.min(t,e.length)),n=To(e).find(o=>s>=o.start&&s<=o.end);if(!n)return{start:s,end:s,raw:""};const a=nd(n.raw);return a?{start:n.start,end:n.end,raw:n.raw,name:a.name,value:a.value}:{start:n.start,end:n.end,raw:n.raw}}function q0(e,t){const s=Mo(e,t);if(s.name===void 0)return{kind:"token",query:s.raw};const n=td(s.name);if(n)return{kind:"value",token:n.name,source:n.values,query:s.value??""}}const H0={mailbox:"mailboxes",account:"accounts",contact:"contacts"},W0=(e,t)=>{if(e.values==="fixed")return e.options??[];const s=H0[e.values];return s?t[s]??[]:[]},V0=(e,t)=>{if(t==="")return 1;const s=e.toLowerCase();return s.startsWith(t)?0:s.includes(t)?1:-1},Na=(e,...t)=>{let s=-1;for(const n of t){if(n===void 0)continue;const a=V0(n,e);a<0||(s<0||a<s)&&(s=a)}return s},fd=e=>{const t=new Set;return e.filter(s=>s.rank>=0).sort((s,n)=>s.rank-n.rank).filter(s=>{const n=s.suggestion.value.toLowerCase();return t.has(n)?!1:(t.add(n),!0)}).slice(0,dd).map(s=>s.suggestion)},dl=e=>({value:`${e.name}:`,label:`${e.name}:`,hint:e.label});function Q0(e){const t=e.trim().toLowerCase();if(t==="")return ja.map(dl);const s=[];for(const n of ja)if(s.push({rank:Na(t,`${n.name}:`,n.label),suggestion:dl(n)}),n.values==="fixed")for(const a of n.options??[]){const o=sd(n.name,a.value);s.push({rank:Na(t,o,a.label),suggestion:{value:o,label:a.label??o,hint:o}})}return fd(s)}function G0(e,t,s){const n=t.trim().toLowerCase(),a=W0(e,s).map(o=>({rank:Na(n,o.value,o.label),suggestion:{value:sd(e.name,o.value),label:o.label??o.value,...o.hint?{hint:o.hint}:{}}}));return fd(a)}function Y0(e,t,s={}){const n=Mo(e,t);if(n.name===void 0)return Q0(n.raw);const a=td(n.name);return a?G0(a,n.value??"",s):[]}function X0(e,t,s){const n=Mo(e,t),a=!s.value.endsWith(":"),o=/\s/.test(e.slice(n.end,n.end+1)),i=a&&!o?`${s.value} `:s.value;return{query:e.slice(0,n.start)+i+e.slice(n.end),cursor:n.start+i.length+(a&&o?1:0)}}const J0=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 n=s.email.toLowerCase(),a=n.split("@")[0];a&&!t.has(a)&&t.set(a,s.accountId),t.has(n)||t.set(n,s.accountId)}return t}function ew(e){const t=new Map;for(const s of e)for(const n of s){const a=n.fullPath?.toLowerCase();if(!a)continue;const o=a.split("/").pop();t.has(a)||t.set(a,n.mailboxId),o&&!t.has(o)&&t.set(o,n.mailboxId)}return t}function tw(e,t=[]){const s=e.flat().filter(o=>o.fullPath),n=new Map;for(const o of s){const i=Bn(o.fullPath).toLowerCase();n.set(i,(n.get(i)??0)+1)}const a=new Map(t.map(o=>[o.accountId,o.email]));return s.map(o=>{const i=Bn(o.fullPath),l=n.get(i.toLowerCase())===1,u=t.length>1?a.get(o.accountId):void 0;return{value:l?i:o.fullPath,label:o.displayNameOverride?.trim()||i,...u?{hint:u}:{}}})}function sw(e){const t=new Map;for(const s of e){const n=s.email.toLowerCase().split("@")[0]??"";t.set(n,(t.get(n)??0)+1)}return e.map(s=>{const n=s.email.split("@")[0]??s.email,a=t.get(n.toLowerCase())===1,o=s.displayName?.trim();return{value:a?n:s.email,label:o||s.email,...o?{hint:s.email}:{}}})}const nw=250,rw=2;function aw({query:e,cursor:t,enabled:s}){const{accounts:n}=Ie(),{mailboxesByName:a}=ms(),o=a!==void 0,i=s?q0(e,t):void 0,l=i?.source==="contact"?i.query.trim():"",u=ir(l,nw),{data:m}=xe({...sr({query:{q:u,limit:dd}}),enabled:u.length>=rw}),d=mt({queries:n.map(y=>({...ot({path:{accountId:y.accountId}}),staleTime:1/0}))}),f=c.useMemo(()=>o?tw(d.map(y=>y.data?.items??[]),n):[],[o,d,n]),h=c.useMemo(()=>sw(n),[n]),g=c.useMemo(()=>(m?.items??[]).map(J0),[m]);return c.useMemo(()=>{if(!s)return[];const y=Y0(e,t,{mailboxes:f,accounts:h,contacts:g});return o?y:y.filter(p=>p.value!=="in:")},[s,e,t,f,h,g,o])}const ow={title:"",navSlot:null,titleMeta:null,searchSlot:null,searchField:null,searchResults:null,makeFilterSlot:null},Ea=c.createContext(ow),Er=()=>c.useContext(Ea),iw=new Set(["hasAttachment","isUnread","isRead","isStarred","category","before","after"]),lw=e=>iw.has(e),cw=(e,{searchHadSemanticReach:t})=>{const s=[],n=[];let a,o;for(const u of e.tokens){if(u.type==="from"){s.push({field:"From",value:u.value});continue}if(u.type==="subject"){s.push({field:"Subject",value:u.value});continue}if(u.type==="in"){a={mailboxId:u.mailboxId,label:u.value};continue}if(u.type==="account"){o=u.accountId;continue}lw(u.type)&&n.push({type:u.type,label:rd(u)})}const i=e.freeText.trim(),l=i.length>0;return l&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:n,targetAccountId:o,keptTerms:l,droppedSemantic:l&&t}},md="remit.recentSearches",uw=5;function Ia(){try{const e=localStorage.getItem(md);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function fl(e){const t=e.trim();if(!t)return Ia();const s=[t,...Ia().filter(n=>n!==t)].slice(0,uw);try{localStorage.setItem(md,JSON.stringify(s))}catch{return s}return s}const dw=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function fw(e){const{spam:t}=Tc([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let n;for(const[a,o]of s)(!n||o>n.count)&&(n={mailboxId:a,count:o});return n}function hd({title:e,unreadCount:t,children:s,selectionBar:n,paneOverlay:a,footer:o,searchFilter:i,searchResults:l,searchLoading:u,relatedResults:m,relatedLoading:d,onSelectSearchResult:f,searchResultsLabel:h="Top matches",relatedResultsLabel:g="Related",searchResultsInBody:y=!1}){const{accounts:p,resultFolderIndex:b,searchQuery:x,searchInput:S,onSearchChange:w,onSearchClear:v,searchViewKey:C}=Ie(),E=ms(),I=He(),N=Ds(),D=Nr(),[A,O]=c.useState(!1),[L,M]=c.useState(Ia),k=Qa(),P=c.useRef(C);c.useEffect(()=>{P.current!==C&&(P.current=C,O(!1))},[C]);const[F,j]=c.useState(0),[R,T]=c.useState(!1),[V,Z]=c.useState(void 0),ee=aw({query:S,cursor:F,enabled:R&&S.trim().length>0}),fe=c.useCallback(ae=>{const ne=X0(S,F,ae);w(ne.query),Z({cursor:ne.cursor})},[S,F,w]),W=$l({count:ee.length,onAccept:ae=>{const ne=ee[ae];ne&&fe(ne)}}),{comboboxProps:te,handleKeyDown:ce}=W,ie=c.useMemo(()=>({comboboxProps:te,onKeyDown:ce,onCaretChange:j,onFocusChange:T,...V?{caret:V}:{}}),[te,ce,V]),U=W.open?r.jsx(_l,{id:W.listId,suggestions:ee,activeIndex:W.activeIndex,optionId:W.optionId,onPick:fe,onHighlight:W.setActiveIndex,label:"Search suggestions",className:"mx-row-inset mt-1 shrink-0"}):null,K=S.trim().length>0,{mailboxesByName:he,accountsByName:Se}=E,ye=c.useMemo(()=>Bs(S,{mailboxesByName:he,accountsByName:Se}),[S,he,Se]),G=ye.tokens.map(ae=>({label:rd(ae),onRemove:()=>w(I0(S,ae))})),B=l??[],$=m??[],le=K?[{id:"top",label:h,results:B},{id:"related",label:g,results:$}]:[],De=!(B.length+$.length>0)&&(u===!0||d===!0),{scope:me}=cu(p),Me=jt({select:ae=>ae.matches}),pe=iu(Me),de=iv(Me,me,pe?b.get(pe)?.role:void 0),ze=de.kind==="global"?fw([...B,...$]):void 0,ut=ze?{kind:"global",onScopeToSpam:()=>I({to:"/mail/$mailboxId",params:{mailboxId:ze.mailboxId},search:{q:x||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:de,H=$.length>0,Ge=c.useMemo(()=>cw(ye,{searchHadSemanticReach:H}),[ye,H]),ge=K?Ge:void 0,be=K?{onClick:()=>{O(!1),k("properties","search")},blockedReason:xx(Ge)?void 0:"Add a sender or words to filter on"}:void 0,Ue=be?r.jsx(Rc,{...be}):null,Ze=dw({tier:D,hasLiveInput:K,hasCommittedQuery:x.trim().length>0,bodyRendersCommittedResults:y}),et=ae=>{M(fl(S)),f?.(ae)},Ye=r.jsx(Mc,{value:S,sections:le,loading:De,onSelectResult:et,tokens:G,scope:ut}),Ae=n===void 0,Fe=Ze?r.jsx("div",{className:"h-full overflow-y-auto",children:Ye}):null,We=Fe&&!Ae?Fe:s,tt=Fe&&Ae?Fe:null,st=ud(D),ke=st&&(A||K),Q=c.useMemo(()=>({title:e,searchResults:tt,makeFilterSlot:Ue,searchConversion:ge,navSlot:N&&!N.showNavPane&&r.jsx(oe,{variant:"ghost",size:"touch",icon:r.jsx(Ya,{className:"size-5"}),onClick:()=>N.openNav(),"aria-label":"Menu",className:"-ml-2 shrink-0"}),titleMeta:r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[t.toLocaleString()," unread"]}),searchSlot:st&&!ke&&r.jsx(oe,{variant:"ghost",size:"touch",icon:r.jsx(Zn,{className:"size-5"}),onClick:()=>O(!0),"aria-label":"Search",className:"shrink-0"}),searchField:ke&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(lo,{value:S,onChange:w,onClear:v,globalFocusKey:!1,showClearButton:!1,suggest:ie})}),r.jsx(oe,{variant:"ghost",size:"touch",icon:r.jsx(vt,{className:"size-5"}),onClick:()=>{v(),O(!1)},"aria-label":"Close search",className:"shrink-0"})]})}),[e,t,N,st,ke,S,w,v,ie,tt,Ue,ge]);if(D==="phone"&&A){const ae=ne=>{M(fl(S)),O(!1),f?.(ne)};return r.jsxs(Ea.Provider,{value:Q,children:[r.jsx(Cg,{value:S,onChange:w,onClear:v,onCancel:()=>{O(!1),v()},filter:i,recentSearches:L,onPickRecent:w,makeFilter:be,sections:le,loading:De,onSelectResult:ae,tokens:G,scope:ut,suggest:ie,suggestList:U}),a]})}return r.jsx(Ea.Provider,{value:Q,children:r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[n?.(Q),U,r.jsx("div",{className:"min-h-0 flex-1",children:We}),o,a]})})}const mw=120,pd=({keyboardFocusedMessageId:e,openMessageId:t,enabled:s,open:n,delayMs:a=mw})=>{const o=c.useRef(n);o.current=n;const i=c.useRef(void 0);c.useEffect(()=>{const l=e;if(!s){i.current=l;return}if(l===void 0||l===t)return;if(l===i.current){i.current=void 0;return}const u=setTimeout(()=>o.current(l),a);return()=>clearTimeout(u)},[s,e,t,a])},hw=(e,t,s)=>{const n=e.indexOf(s);if(n===-1)return[];const a=t===void 0?-1:e.indexOf(t);if(a===-1)return[s];const o=Math.min(a,n),i=Math.max(a,n);return e.slice(o,i+1)},pw=(e,t,s,n)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:n,gw=(e,t)=>{const s=new Set(t),n=new Set;for(const a of e)s.has(a)&&n.add(a);return n},gd=(e,t,s)=>{if(e.length===0)return;const n=t===void 0?-1:e.indexOf(t);if(n===-1)return s>0?e[0]:e[e.length-1];const a=Math.min(Math.max(n+s,0),e.length-1);return e[a]},xd=e=>{const[t,s]=c.useState(new Set),[n,a]=c.useState(void 0),o=c.useCallback(p=>t.has(p),[t]),i=c.useCallback(p=>{a(p),s(b=>{const x=new Set(b);return x.has(p)?x.delete(p):x.add(p),x})},[]),l=c.useCallback(p=>{a(p),s(b=>{if(b.has(p))return b;const x=new Set(b);return x.add(p),x})},[]),u=c.useCallback(p=>{s(b=>{if(!b.has(p))return b;const x=new Set(b);return x.delete(p),x})},[]),m=c.useCallback(p=>{s(new Set(p))},[]),d=c.useCallback(()=>{a(void 0),s(new Set)},[]),f=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 x=gw(b,p);return x.size===b.size?b:x})},[]),y=c.useCallback((p,b,x)=>{const S=pw(p,n,x,b);s(w=>{const v=hw(p,S,b);if(v.length===0)return w;const C=new Set(w);for(const E of v)C.add(E);return C}),a(S)},[n]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:l,deselect:u,selectAll:m,clearSelection:d,toggleAll:f,selectRange:y,setAnchor:h,anchorId:n,intersectWith:g}},bd=(e,t)=>!t&&e>0,xw=(e,t,s)=>e==="BACK"&&t&&s===void 0,bw=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:n})=>{const[a,o]=c.useState(s),[i,l]=c.useState(),u=c.useCallback(F=>{l(j=>j===F?j:void 0),o(F)},[]),m=xd(),{selectedCount:d,toggle:f,clearSelection:h,selectRange:g,setAnchor:y,selectAll:p}=m,b=bd(d,t),x=c.useRef(null),S=c.useRef(!1),w=c.useCallback(()=>{n?.(),h()},[h,n]),v=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),C=c.useCallback(F=>{if(F<0||F>=e.length)return;const j=e[F];if(b){f(j);return}x.current=j,S.current=!1,l(j),o(j)},[e,b,f]),E=c.useCallback(()=>{e.length!==0&&C(v<0?0:Math.min(v+1,e.length-1))},[e.length,v,C]),I=c.useCallback(()=>{e.length!==0&&C(v<=0?0:v-1)},[e.length,v,C]),N=c.useCallback(()=>C(0),[C]),D=c.useCallback(()=>C(e.length-1),[C,e.length]),A=c.useCallback(()=>{a&&f(a)},[a,f]),O=c.useCallback((F,j)=>j.shiftKey?(g(e,F,a),!0):j.metaKey||j.ctrlKey?(f(F),!0):(w(),y(F),!1),[e,a,g,f,w,y]),L=c.useCallback(F=>{const j=gd(e,a,F);j!==void 0&&(g(e,j),x.current=j,S.current=!1,l(void 0),o(j))},[e,a,g]),M=c.useCallback(()=>L(-1),[L]),k=c.useCallback(()=>L(1),[L]),P=c.useCallback(()=>{e.length>0&&p(e)},[e,p]);return{focusedMessageId:a,setFocusedMessageId:u,keyboardFocusedMessageId:i,focusIndex:v,pendingDomFocusRef:x,cursorMovedByPointerRef:S,selection:m,isMultiSelectMode:b,exitSelection:w,moveFocusToIndex:C,focusNext:E,focusPrevious:I,focusFirst:N,focusLast:D,toggleFocusedSelection:A,extendRangeUp:M,extendRangeDown:k,selectAllLoaded:P,handleRowSelect:O}};function vd(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Ao=c.createContext(null),vw=e=>{const t=c.useContext(Ao);return t?t.rowInteraction(e):null},Oo=()=>{const e=c.useContext(Ao);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},yw="[data-message-id]",ww=e=>Array.from(e.querySelectorAll(yw)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),Sw=(e,t)=>e.length===t.length&&e.every((s,n)=>s===t[n]),kw=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const n=e.current;if(!n)return;const a=()=>{const i=ww(n);s(l=>Sw(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(n,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function yd({selectedMessageId:e,onOpen:t,onDeleteMessages:s,isDeleting:n=!1,commandsRef:a,onTriageContextChange:o,children:i}){const l=Vt(),u=c.useRef(null),m=kw(u),d=bw({orderedIds:m,isDesktop:l,initialFocusedId:e}),{focusedMessageId:f,setFocusedMessageId:h,pendingDomFocusRef:g,cursorMovedByPointerRef:y,selection:p,isMultiSelectMode:b,exitSelection:x,handleRowSelect:S}=d,{selectedIds:w,selectedCount:v,isSelected:C,toggle:E,select:I,toggleAll:N}=p,D=m.length>0&&m.every(K=>w.has(K)),A=c.useCallback(()=>{m.length>0&&N(m)},[m,N]),{intersectWith:O}=p;c.useEffect(()=>{O(m)},[O,m]),c.useEffect(()=>{const K=g.current;K!==null&&(g.current=null,u.current?.querySelector(`[data-message-id="${K}"]`)?.focus())});const L=c.useCallback(K=>{y.current=!0,h(K)},[y,h]),M=c.useCallback(K=>{l||I(K)},[l,I]),k=c.useCallback(()=>{f&&t(f)},[f,t]),P=c.useCallback(K=>t(K,{replace:!0}),[t]);pd({keyboardFocusedMessageId:d.keyboardFocusedMessageId,openMessageId:e,enabled:l&&v===0,open:P});const[F,j]=c.useState(null),R=c.useCallback(K=>K.length===0?!1:(j(K),!0),[]),T=c.useCallback(()=>{R(Array.from(w))},[R,w]),V=c.useCallback(()=>F!==null?!0:v>0?R(Array.from(w)):f?R([f]):!1,[F,v,w,f,R]),Z=c.useCallback(()=>{F!==null&&(s(F),j(null),x())},[F,s,x]),ee=c.useCallback(()=>j(null),[]),fe=c.useCallback(()=>v===0?!1:(x(),!0),[v,x]),W=m.length>0;c.useEffect(()=>{if(a){if(!W){a.current=null;return}return a.current={focusNext:d.focusNext,focusPrevious:d.focusPrevious,focusFirst:d.focusFirst,focusLast:d.focusLast,openFocused:k,toggleSelect:d.toggleFocusedSelection,extendSelectDown:d.extendRangeDown,extendSelectUp:d.extendRangeUp,selectAll:d.selectAllLoaded,clearSelection:fe,requestDelete:V,toggleDensity:()=>{}},()=>{a.current=null}}},[a,W,d.focusNext,d.focusPrevious,d.focusFirst,d.focusLast,d.toggleFocusedSelection,d.extendRangeDown,d.extendRangeUp,d.selectAllLoaded,k,fe,V]);const te=c.useMemo(()=>Array.from(w),[w]),ce=F!==null;c.useEffect(()=>{o?.({focusedMessageId:f,selectedIds:te,orderedIds:m,hasList:W,blocksKeyboard:ce})},[o,f,te,m,W,ce]);const ie=vd(m,f),U=c.useMemo(()=>({selectedIds:w,selectedCount:v,exitSelection:x,requestDeleteSelection:T,orderedIds:m,allSelected:D,toggleAllLoaded:A,rowInteraction:K=>({focused:K===f,isTabStop:K===ie,isDesktop:l,onFocusRow:L,selection:{isChecked:C(K),onToggleCheck:E,onRowSelect:S,isMultiSelectMode:b,onLongPress:M}})}),[w,v,x,T,m,D,A,f,ie,l,L,C,E,S,b,M]);return r.jsxs(Ao.Provider,{value:U,children:[r.jsx("div",{ref:u,className:"contents",children:i}),r.jsx(eo,{isOpen:ce,title:Ql(F?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:n,onConfirm:Z,onCancel:ee})]})}function Cw({title:e,onMarkAsRead:t,isDeleting:s}){const n=Er(),{selectedIds:a,selectedCount:o,exitSelection:i,requestDeleteSelection:l,orderedIds:u,allSelected:m,toggleAllLoaded:d}=Oo(),f=c.useCallback(()=>{t?.(Array.from(a)),i()},[t,a,i]);return r.jsx(fr,{title:n.title||e,navSlot:n.navSlot,titleMeta:n.titleMeta,searchSlot:n.searchSlot,searchField:n.searchField,idleSlot:n.makeFilterSlot,count:o,onCancel:i,onDelete:l,onMarkRead:t?f:void 0,isBusy:s,selectAll:u.length>0?{checked:m,indeterminate:o>0&&!m,onChange:d}:void 0})}const Ta=e=>({shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey}),ml=e=>e.shiftKey||e.metaKey||e.ctrlKey,ra=e=>{e.preventDefault(),e.stopPropagation()},wd=(e,t)=>{const s=c.useRef(!1),n=c.useCallback(i=>{if(s.current=!1,i.button!==0)return;const l=Ta(i);ml(l)&&t?.(e,l)&&(ra(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,ra(i),!0;const l=Ta(i);return!ml(l)||!t?.(e,l)?!1:(ra(i),l.shiftKey&&window.getSelection()?.removeAllRanges(),!0)},[t,e]);return{onMouseDown:n,onContextMenu:a,claimClick:o}},jw=({thread:e,active:t=!1,focused:s,isTabStop:n,density:a="comfortable",isDesktop:o,badge:i,selection:l,inListbox:u=!1,linkMailboxId:m,onClick:d,onFocusRow:f})=>{const h=Ee(),g=e.id,y=vw(g),p=s??y?.focused??!1,b=n??y?.isTabStop??!1,x=l??y?.selection,S=f??y?.onFocusRow,w=o??y?.isDesktop??!0,v=x?.isChecked??!1,C=x?.isMultiSelectMode??!1,E=x?.onToggleCheck,I=x?.onRowSelect,N=x?.onLongPress,D=c.useCallback(T=>{T.preventDefault(),T.stopPropagation(),E?.(g)},[E,g]),A=wd(g,I),O=c.useCallback(T=>{if(!A.claimClick(T)){if(!w){if(C){T.preventDefault(),T.stopPropagation(),E?.(g);return}d?.();return}I?.(g,Ta(T)),d?.()}},[A,w,C,E,I,d,g]),L=c.useCallback(()=>{N?.(g)},[N,g]),{longPressProps:M}=wc({onLongPress:L,accessibilityDescription:v?"Deselect message":"Select message"}),k=c.useCallback(()=>{h.prefetchQuery(or({path:{messageId:g}}))},[h,g]),P=c.useCallback(()=>{k(),S?.(g)},[k,S,g]),F=Ps({"data-list-row":"","data-message-row":!0,"data-message-id":g,...u?{role:"option","aria-selected":v}:{},tabIndex:b?0:-1,onClick:O,onMouseDown:A.onMouseDown,onContextMenu:A.onContextMenu,onMouseEnter:k,onFocus:P},w||!x?{}:M),j=Le(a==="compact"?bc({active:t,focused:p}):Le("group",Fs({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",v&&"bg-accent-soft",!w&&"min-h-11 select-none [-webkit-touch-callout:none]"),R=a==="compact"?r.jsx(vc,{thread:e}):r.jsx(ao,{thread:e,badge:i,selection:x?{checked:v,alwaysVisible:C,onToggle:D}:void 0});return m===void 0?r.jsx("button",{type:"button",...F,className:j,children:R}):r.jsx(Ct,{to:"/mail/$mailboxId",params:{mailboxId:m},search:T=>({...T,selectedMessageId:g}),...F,className:j,children:R})},Gn=c.memo(jw),Sd=8,kd=e=>e==="From"||e==="FromDomain",Nw=e=>({value:e.email,label:e.displayName??e.email,...e.displayName?{hint:e.email}:{},...e.fromSelection?{source:"selected"}:{}}),Ew=e=>{const t=Pc(e.email);if(t!==null)return{value:t,...e.fromSelection?{source:"selected"}:{}}},Iw=(e,t)=>e.value.toLowerCase().includes(t)||(e.label??"").toLowerCase().includes(t),Tw=(e,t,s)=>{if(!kd(e))return[];const n=t.trim().toLowerCase(),a=new Set,o=[];for(const i of s){if(i.email.trim()==="")continue;const l=e==="From"?Nw(i):Ew(i);if(!l)continue;const u=l.value.toLowerCase();if(!(u===""||a.has(u))&&(a.add(u),u!==n&&!(n!==""&&!Iw(l,n))&&(o.push(l),o.length===Sd)))break}return o},Rw=250,Mw=2,Aw=(e,t,s)=>{const n=t.trim(),a=ir(n,Rw),o=e!==void 0&&kd(e),{data:i}=xe({...sr({query:{q:a,limit:Sd}}),enabled:o&&a.length>=Mw});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 Tw(e,n,l)},Ow={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},Cd={delete:"moved to Trash",move:"moved",markRead:"marked as read"},jd={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},Dw={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},Pw={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},Lw=(e,t,s)=>Ow[e](xt(t),xt(s)),hl=(e,t)=>`${xt(t)} ${Cd[e]}. Your mail server is still catching up.`,Fw=(e,t,s)=>`${xt(t)} ${Cd[e]}. ${xt(s)} ${jd[e]}.`,$w=(e,t)=>t>0?`Stopped after ${xt(t)} — some messages ${jd[e]}`:Dw[e],_w=e=>Pw[e],zw=e=>e==="delete"?"danger":"info",Bw=100,Kw=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],Nd=({mailboxId:e,accountId:t,enabled:s,predicateKey:n,searchQuery:a})=>{const[o,i]=c.useState({kind:"idle"}),[l,u]=c.useState(void 0),[m,d]=c.useState(void 0),f=c.useRef(!1),h=Ee(),{pushError:g}=it();c.useEffect(()=>{f.current=!0,i({kind:"idle"})},[s,n]);const y=c.useRef(a);y.current=a;const p=c.useCallback(async E=>{const{data:I}=await Ul({path:{mailboxId:e},query:{...y.current,continuationToken:E,limit:Bw},throwOnError:!0});return{ids:(I.items??[]).map(N=>N.messageId),continuationToken:I.continuationToken}},[e]),b=c.useCallback(E=>async I=>{if(E.kind==="move"){const{data:D}=await fm({body:{messageIds:I,destinationMailboxId:E.destinationMailboxId},throwOnError:!0});return D}if(E.kind==="markRead"){const{data:D}=await mm({body:{messageIds:I,isRead:!0},throwOnError:!0});return D}const{data:N}=await hm({body:{messageIds:I},throwOnError:!0});return N},[]),x=c.useCallback(E=>{Mt(h,Rt(Kw(E,e))),t&&h.invalidateQueries({queryKey:us({path:{accountId:t}})})},[h,e,t]),S=c.useCallback(()=>{f.current=!1,i({kind:"counting",countSoFar:0}),Hv(p,E=>i({kind:"counting",countSoFar:E}),()=>f.current).then(E=>{if(E.error){g(as("Couldn't count matching messages","The count didn't finish.",E.error)),i({kind:"idle"});return}if(E.cancelled){i({kind:"idle"});return}i({kind:"escalated",total:E.total})})},[p,g]),w=c.useCallback(()=>{f.current=!0},[]),v=c.useCallback(()=>{f.current=!0,i({kind:"idle"})},[]),C=c.useCallback(async(E,I)=>{f.current=!1,u(E);const N=O=>d(qv(O)),D=b(E),A=I!==void 0?await vu(I,D,N,()=>f.current):await Uv(p,o.kind==="escalated"?o.total:0,D,N,()=>f.current);return u(void 0),d(void 0),i({kind:"idle"}),A.error&&g(as($w(E.kind,A.done),_w(E.kind),A.error)),A.done>0&&x(E),A},[b,p,o,g,x]);return{phase:o,escalate:S,stop:w,clear:v,isRunning:l!==void 0,runningAction:l,progress:m,runAction:C}},Uw=12,qw=e=>{const{envelope:t}=e,s=t.from[0];return{id:t.messageId,sender:s?Lc({normalizedEmail:s.normalizedEmail,displayName:s.displayName}):"Unknown",subject:t.subject??"(No subject)",date:yt(t.date)}},Hw=e=>mt({queries:e.slice(0,Uw).map(t=>({...or({path:{messageId:t}}),staleTime:Number.POSITIVE_INFINITY})),combine:t=>({messages:t.map(s=>s.data).filter(s=>s!==void 0).map(qw),isPending:t.some(s=>s.isPending)})}),Ww=e=>({matchOperator:"Or",literalClauses:hr(e)}),Vw=(e,t,s)=>{const n=Oe(pm()),{mutate:a,reset:o}=n,[i,l]=c.useState(!1),u=c.useMemo(()=>mr(s),[s]),m=c.useCallback(()=>{!e||!t||(l(!1),a({path:{accountId:e},body:Wo({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=c.useCallback(()=>{l(!1),o()},[o]),f=n.data,h=f?.semanticUnavailable===!0&&!i&&u.length>0;c.useEffect(()=>{!h||!e||(l(!0),a({path:{accountId:e},body:Wo(Ww(u))}))},[h,e,u,a]);const g=i||(f?.semanticUnavailable??!1),y=n.isPending||h,p=i?{matchOperator:"Or",literalClauses:hr(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:m,reset:d,matchedCount:y?void 0:f?.matchedCount,messageIds:y?void 0:f?.messageIds,semanticUnavailable:g,senderFallback:i,senders:u,matchPredicate:p,isPending:y,isError:n.isError,error:n.error}},Qw=()=>[rr({path:{mailboxId:""}}),Ha({path:{mailboxId:""}}),Wa()].map(e=>[{_id:e[0]._id}]),Gw=e=>yu(e)?e.pages:wu(e)?[e]:[],Yw=e=>typeof e=="object"&&e!==null&&typeof e.messageId=="string",Xw=(e,t)=>{const s=new Set(t),n=new Map;for(const a of e)for(const o of Gw(a))for(const i of o.items){if(!Yw(i)||!s.has(i.messageId))continue;const l=i.subject?.trim();l&&n.set(i.messageId,l)}return t.map(a=>n.get(a)).filter(a=>a!==void 0)},Jw=e=>{const t=Ee(),s=e.join("\0");return c.useMemo(()=>{const n=Qw().flatMap(a=>t.getQueriesData({queryKey:a}).map(([,o])=>o));return Xw(n,e)},[t,s])},Zw={clauses:[],matchOperator:"any"},eS={clauses:[],matchOperator:"all",droppedFacets:[],keptTerms:!1,droppedSemantic:!1},tS=[],Ft={state:"saving",matched:0,applied:0,failed:0,failures:[]},aa=(e,t)=>e.map((s,n)=>({...s,id:`${t}-${n}`})),sS=(e,t,s)=>{if(e==="delete")return{kind:"delete"};if(e==="markRead")return{kind:"markRead"};const n=e==="junk"?s:t;return n?{kind:"move",destinationMailboxId:n}:void 0},oa=e=>e==="move"||e==="junk"||e==="organize";function nS({verb:e,accountId:t,mailboxId:s,selection:n,crossAccount:a=!1,searchConversion:o,onFinished:i,step:l,goToStep:u,goBack:m,closeWizard:d}){const[f]=c.useState(()=>o),h=f!==void 0,[g,y]=c.useState(h?"properties":"selected"),[p,b]=c.useState(()=>f?{clauses:aa(f.clauses,"search"),matchOperator:f.matchOperator}:Zw),[x,S]=c.useState(void 0),[w,v]=c.useState(void 0),[C,E]=c.useState(!1),[I,N]=c.useState(void 0),[D,A]=c.useState(void 0),[O,L]=c.useState(),M=c.useRef(!1),k=c.useMemo(()=>n.map(z=>z.id),[n]),P=c.useMemo(()=>n.map(z=>z.email).filter(Boolean),[n]),F=k[0],j=Jw(k),{junkMailboxId:R}=_s(t),T=Vw(t,F,P),{preview:V}=T;c.useEffect(()=>{V()},[V]);const Z=g!=="selected",ee=c.useMemo(()=>({matchOperator:p.matchOperator==="all"?"And":"Or",literalClauses:p.clauses.map(z=>({field:z.field,value:z.value}))}),[p.clauses,p.matchOperator]),fe=g==="similar"?T.matchPredicate:ee,{count:W,matchedIds:te}=qm(Z?t:void 0,fe),ce=Hw(Z?te:[]),ie=Z?W:{status:"ready",count:n.length},{data:U}=xe({...ot({path:{accountId:t??""}}),enabled:!!t,staleTime:Number.POSITIVE_INFINITY}),K=ko(t),he=c.useMemo(()=>Ja(U?.items??[],K).map(z=>({id:z.mailboxId,label:Bn(z.fullPath),searchValue:z.fullPath,isCurrent:z.mailboxId===s})),[U?.items,K,s]),{createFolder:Se}=Gl(t),ye=he.find(z=>z.id===p.moveMailboxId)?.label,G=lx(n.map(z=>({normalizedEmail:z.email,displayName:z.sender}))),B=gx({match:g==="properties"&&p.clauses[0]?.value.trim()||void 0,sender:G?Lc(G):void 0,folder:ye}),$=c.useMemo(()=>({...p,name:p.name??B}),[p,B]),le=Aw(x?.draft.field,x?.draft.value??"",P),ue=Hm(t),De=Wm(t),me=Nd({mailboxId:s??"",accountId:t,enabled:!1,predicateKey:"selection-wizard",searchQuery:{}}),{runAction:Me}=me,pe=bm({verb:e,mode:g,scope:p.scope,fromSearch:h}),de=pe[qo(pe,l)],ze=!a&&!!t,ut=ze?void 0:wm,H=ze?void 0:Sm,ge=(z=>{if(z==="folder")return H;if(z==="rule")return $.scope==="standing"||$.scope==="until"?ut:void 0})(de)??vm(de,$,ie),be=c.useCallback(()=>aa(px(P,j),"seed"),[P,j]),Ue=c.useCallback(z=>{y(z),b(se=>({...se,widen:z==="similar"&&F?{anchorCount:Math.max(n.length,1)}:void 0,...z==="properties"&&se.clauses.length===0?{clauses:be()}:{}}))},[F,n.length,be]),Ze=c.useCallback(()=>{E(!0),y("properties"),b(z=>({...z,widen:void 0,clauses:aa(hr(P),"sender"),matchOperator:"any"})),u("properties")},[P,u]),et=T.semanticUnavailable||T.isError;c.useEffect(()=>{de==="match"&&(g!=="similar"||!et||C||Ze())},[de,g,et,C,Ze]);const Ye=c.useCallback(()=>{S({mode:"add",draft:{field:"From",value:""}})},[]),Ae=c.useCallback(z=>{const se=p.clauses.find($e=>$e.id===z);se&&S({mode:"edit",clauseId:z,draft:{field:se.field,value:se.value}})},[p.clauses]),Fe=c.useCallback(z=>{b(se=>({...se,clauses:se.clauses.filter($e=>$e.id!==z)}))},[]),We=c.useCallback(z=>{S(se=>se&&{...se,draft:z})},[]),tt=c.useCallback(()=>{S(z=>{if(!z)return;const se=Vm(z.draft.field,z.draft.value),$e={...z.draft,value:se};b(Xe=>({...Xe,clauses:z.clauseId?Xe.clauses.map(wt=>wt.id===z.clauseId?{...wt,...$e}:wt):[...Xe.clauses,{id:crypto.randomUUID(),...$e}]}))})},[]),st=c.useCallback(()=>{if(ge){v(de);return}v(void 0);const z=pe[qo(pe,de)+1];z&&u(z)},[ge,de,pe,u]),ke=c.useCallback(async z=>{const se=sS(e,$.moveMailboxId,R);if(!se){A({matched:z.length,outcome:{done:0,failedIds:[...z],cancelled:!1,error:new Error(e==="junk"?"This account has no Junk folder appointed, so there is nowhere to file these. Appoint one under Settings › Folders.":"No destination was chosen, so there is nowhere to file these. Go back and pick a folder.")}});return}A({matched:z.length});const $e=await Me(se,[...z]);A({matched:z.length,outcome:$e})},[e,$.moveMailboxId,R,Me]),{start:Q}=ue,{createFilterAsync:ae}=De,ne=c.useCallback(()=>{const z=Qm({mode:g,ruleScope:$.scope}),se=Gm({mode:g,ruleScope:$.scope,anchorMessageId:F,clauses:$.clauses,matchOperator:$.matchOperator,moveMailboxId:$.moveMailboxId,until:$.until});if(N(z),z==="standing"||z==="temporary"){const $e=Ym(se)?se:void 0;L($e),ae(se,z,($.name??"").trim()).then(Xe=>{Xe&&$e&&Q($e)});return}if(z==="all-like-these"&&oa(e)){Q(se);return}ke(z==="just-these"?k:te)},[g,$,F,e,k,te,ae,Q,ke]),re=c.useCallback(()=>{if(ge){v(de);return}M.current||(M.current=!0,u("run"),ne())},[ge,de,u,ne]),ve=c.useCallback(()=>{const z=ue.progress,se={matched:z.matchedCount,applied:z.appliedCount,failures:[]};return ue.isError?{...Ft,state:"commitFailed"}:ue.isDone?{...se,state:z.failedCount>0?"backApplyFailed":"backApplyComplete",failed:z.failedCount}:ue.isStarting||ue.isRunning?{...se,state:"backApplyRunning",failed:0}:Ft},[ue]),Ce=c.useMemo(()=>{const z=new Map;for(const se of[...n,...ce.messages])z.set(se.id,se);return z},[n,ce.messages]),Te=c.useCallback(()=>{if(!D)return Ft;const{matched:z,outcome:se}=D;if(!se)return{state:"backApplyRunning",matched:z,applied:me.progress?.done??0,failed:0,failures:[]};if(se.done===0&&(se.error||se.failedIds.length>0))return{...Ft,state:"commitFailed"};const $e=se.failedIds.map(Xe=>Ce.get(Xe)).filter(Xe=>Xe!==void 0);return{state:se.failedIds.length>0?"backApplyFailed":"backApplyComplete",matched:z,applied:se.done,failed:se.failedIds.length,failures:$e}},[D,me.progress,Ce]),Ve=()=>I==="standing"||I==="temporary"?De.isError?{...Ft,state:"commitFailed"}:De.isSuccess?O?ue.isError?{...Ft,state:"backApplyStartFailed"}:ve():{...Ft,state:"filterSaved"}:Ft:I==="all-like-these"&&oa(e)?ve():Te(),Be=()=>{if(I==="standing"||I==="temporary"){if(De.isError){De.reset(),ne();return}O&&Q(O);return}if(I==="all-like-these"&&oa(e)){ne();return}const z=D?.outcome?.failedIds??[];ke(z.length>0?z:k)},je=c.useCallback(()=>{d(pe,de)},[d,pe,de]),Qe=c.useCallback(()=>{d(pe,de),i()},[d,pe,de,i]);Xc({shouldBlockFn:({action:z})=>z!=="BACK"?!1:(Qe(),!0),enableBeforeUnload:!1,disabled:de!=="run"});const Re=Ve(),qe={messages:Z?ce.messages:n,count:ie,label:Z?"A sample of what matches":"Your selection",emptyReason:g==="similar"&&et?"notIndexed":"noMatch",loading:Z&&(ie.status==="loading"||ce.isPending)};return r.jsx(ym,{verb:e,steps:pe,step:de,blockedReason:ge,nudged:w===de,onBack:m,onExit:je,onContinue:st,onCommit:re,match:{selectedCount:n.length,mode:g,onModeChange:Ue,semanticUnavailable:et,semanticErrorDetail:T.error instanceof Error?T.error.message:void 0,semanticFallbackTaken:C,onSemanticFallback:Ze,sample:qe},properties:{clauses:$.clauses,matchOperator:$.matchOperator,onMatchOperatorChange:z=>b(se=>({...se,matchOperator:z})),clauseEdit:x,onStartAddClause:Ye,onStartEditClause:Ae,onRemoveClause:Fe,onChangeDraft:We,onSubmitClause:tt,onCancelClause:()=>S(void 0),clauseFields:Xm,clauseSuggestions:le,conversionNotice:f?bx(f):void 0,semanticFallbackTaken:C,sample:{...qe,label:"What this matches"}},folder:{mailboxes:he,mailboxId:$.moveMailboxId,onSelect:z=>b(se=>({...se,moveMailboxId:z})),onCreateFolder:t?Se:void 0,restriction:H},rule:{draft:$,onScopeChange:z=>b(se=>({...se,scope:z})),onUntilChange:z=>b(se=>({...se,until:z})),restriction:ut},name:{name:$.name??"",onNameChange:z=>b(se=>({...se,name:z})),nudged:w===de},review:{verb:e,mode:g,selectedCount:n.length,clauses:$.clauses,matchOperator:$.matchOperator,folder:ye,scope:$.scope,until:$.until,ruleName:pe.includes("name")?$.name:void 0,sample:qe},run:{state:Re.state,verb:e,scope:$.scope,matched:Re.matched,applied:Re.applied,failedCount:Re.failed,failures:Re.failures,onRetry:Be,onDismiss:Qe}})}function Do(e){const t=gm()==="search",{searchConversion:s}=Er(),{accounts:n}=Ie(),{step:a,goToStep:o,goBack:i,closeWizard:l}=xm(t?"properties":"match");if(!a)return null;const u=t?s??eS:void 0;return r.jsx(nS,{...e,...u?{verb:"organize",accountId:u.targetAccountId??n[0]?.accountId,selection:tS,crossAccount:!1,searchConversion:u}:{},step:a,goToStep:o,goBack:i,closeWizard:l})}const rS=200,aS={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()},pl=()=>r.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>r.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[r.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsxs("div",{className:"flex justify-between gap-2",children:[r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),oS=({accountEmail:e})=>{const t=He();return r.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[r.jsx(cs,{className:"size-3.5 shrink-0"}),r.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),r.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})};function iS({sections:e,briefCategory:t,selectedThreadId:s,onSelectThread:n}){const a=t==="all",o=e.flatMap(l=>l.threads).filter(l=>l.category===t),i=a?e.length===0:o.length===0;return r.jsxs("div",{className:"h-full overflow-y-auto",children:[a?e.map(l=>r.jsx(km,{section:l,Row:Gn,selectedThreadId:s,onSelectThread:n},l.id)):r.jsx("div",{className:"divide-y divide-line",children:o.map(l=>r.jsx(Gn,{thread:l,active:l.id===s,onClick:()=>n?.(l.id)},l.id))}),i&&r.jsx("div",{className:"px-row-inset py-6 text-center text-2xs text-fg-subtle",children:"No threads match these filters."})]})}const lS=(e,t)=>{if(t.size===0)return{};const s=new Set,n=new Set;for(const o of e)t.has(o.id)&&(o.accountId&&s.add(o.accountId),o.mailboxId&&n.add(o.mailboxId));if(s.size>1)return{moveDisabledHint:"Move only works within one account — clear selection or pick messages from a single account"};const a=s.size===1?[...s][0]:void 0;return n.size>1?{accountId:a,moveDisabledHint:`Move only works within one folder — this selection spans ${n.size} folders`}:{accountId:a,mailboxId:n.size===1?[...n][0]:void 0}};function cS({header:e,rows:t,onMarkMessagesRead:s,children:n}){const{selectedIds:a,selectedCount:o,exitSelection:i,orderedIds:l,allSelected:u,toggleAllLoaded:m}=Oo(),d=c.useMemo(()=>lS(t,a),[t,a]),{junkMailboxId:f}=_s(d.accountId),{labels:h}=Za(d.accountId),g=Qa(),[y,p]=c.useState("organize"),b=c.useCallback(I=>{p(I),g("match")},[g]),x=c.useMemo(()=>Array.from(a),[a]),S=c.useMemo(()=>t.filter(I=>a.has(I.id)).map(I=>({id:I.id,sender:I.fromName,email:I.fromEmail,subject:I.subject,date:I.timeLabel})),[t,a]),w=!!f&&f!==d.mailboxId,v=c.useMemo(()=>l.length>0?{checked:u,indeterminate:o>0&&!u,onChange:m}:void 0,[l.length,u,o,m]),C=d.moveDisabledHint?{tone:"warning",text:d.moveDisabledHint}:void 0,E=I=>r.jsx(fr,{title:I.title,navSlot:I.navSlot,titleMeta:I.titleMeta,searchSlot:I.searchSlot,searchField:I.searchField,idleSlot:I.makeFilterSlot,count:o,onCancel:i,onDelete:()=>b("delete"),onMove:()=>b("move"),onOrganize:()=>b("organize"),onJunk:w?()=>b("junk"):void 0,onMarkRead:s?()=>b("markRead"):void 0,overflowSlot:d.accountId&&d.mailboxId&&o>0&&h.length>0?r.jsx(cd,{accountId:d.accountId,mailboxId:d.mailboxId,messageIds:x}):void 0,selectAll:v,notice:C});return r.jsx(hd,{...e,selectionBar:E,paneOverlay:r.jsx(Do,{verb:y,accountId:d.accountId,mailboxId:d.mailboxId,selection:S,crossAccount:d.moveDisabledHint!==void 0,onFinished:i}),children:n})}function uS({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:n,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i,onMarkMessagesRead:l}){const{searchQuery:u,resultFolderIndex:m}=Ie(),d=ms(),f=Vt(),h=c.useMemo(()=>D0(e.filter(G=>!G.muted?.value)),[e]),[g,y]=c.useState("all"),[p,b]=c.useState("all"),[x,S]=c.useState(new Set),[w,v]=c.useState(!1),C=c.useCallback(G=>{S(B=>{const $=new Set(B);return $.has(G)?$.delete(G):$.add(G),$})},[]),{data:E,isLoading:I,isError:N,refetch:D}=xe({...da(),staleTime:6e4}),A=mt({queries:h.map(G=>({...ot({path:{accountId:G.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),O=c.useMemo(()=>{const G=new Map;for(let B=0;B<h.length;B++){const $=h[B].accountId,ue=(A[B]?.data?.items??[]).reduce((De,me)=>De+(me.unseenCount??0),0);G.set($,ue)}return G},[h,A]),L=c.useMemo(()=>h.filter((G,B)=>{const $=A[B];return $?.isError?!fa($.error):!1}),[h,A]),{freeText:M,tokens:k}=Bs(u.trim().toLowerCase(),d),{data:P,isFetching:F}=xe({...da({query:{query:M,limit:rS}}),enabled:M.length>0,staleTime:3e4}),j=c.useMemo(()=>{const G=cl(E?.items??[]).map(Qn);return(M?P0(G.filter($=>od($,M)),cl(P?.items??[]).map(Qn)):G).filter($=>(g==="all"||$.accountId===g)&&Ro($,k))},[E,P,g,M,k]),R=c.useMemo(()=>L0(j),[j]),T=c.useMemo(()=>h.length<=1?[]:[{id:"all",label:"All",active:g==="all"},...h.map(G=>({id:G.accountId,label:G.email.split("@")[0]??G.email,count:O.get(G.accountId),active:g===G.accountId}))],[h,O,g]),V=c.useMemo(()=>e.filter(G=>G.muted?.value).length,[e]),Z=c.useMemo(()=>Array.from(O.values()).reduce((G,B)=>G+B,0),[O]),ee=c.useMemo(()=>{const G=Array.from(x).map(B=>aS[B]).filter(B=>B!=null);return j.filter(B=>(p==="all"||B.category===p)&&G.every($=>$(B))).map(B=>id(B,m))},[j,p,x,m]),{hits:fe,isLoading:W}=ad(),te=c.useMemo(()=>{const G=new Map;for(const $ of E?.items??[])G.set($.messageId,$.threadId);const B=ee.map($=>G.get($.id)).filter($=>$!=null);return ld(fe,B,m)},[fe,ee,E,m]),ce=c.useMemo(()=>{const G=Hg(T.map(B=>({id:B.id,label:B.label,count:B.count,active:B.active})));return{categories:G.categories,filters:G.filters,sources:G.sources,sourcesNote:V>0?`+${V} muted`:void 0,selectedCategory:p,activeFilters:x,expanded:w,onExpandedChange:v,onSelectCategory:B=>b(B),onSelectSource:y,onToggleFilter:C,onClear:()=>{b("all"),y("all"),S(new Set)}}},[T,V,p,x,w,C]),ie=R.length===0&&g==="all"&&M.length===0,U=c.useMemo(()=>h.map(G=>G.accountId),[h]),K=c.useMemo(()=>h.some(G=>Ju(G.syncPhase)),[h]),he=g0(U,ie||K),Se=r.jsxs("div",{className:"h-full overflow-y-auto",children:[r.jsx(pl,{}),r.jsx(pl,{})]}),ye=I?Se:N?r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[r.jsx(cs,{className:"size-8 text-danger"}),r.jsx("p",{children:"Couldn't load your messages"}),r.jsxs("button",{type:"button",onClick:()=>D(),className:"flex items-center gap-1 text-accent underline text-xs",children:[r.jsx(fc,{className:"size-3.5"}),"Try again"]})]}):ie?he.resolved?r.jsx(ag,{sync:he.syncing?{synced:he.synced,total:he.total}:void 0}):Se:r.jsx(iS,{sections:R,briefCategory:p,selectedThreadId:t,onSelectThread:s});return r.jsx(yd,{selectedMessageId:t,onOpen:(G,B)=>s?.(G,B),onDeleteMessages:i,commandsRef:a,onTriageContextChange:o,children:r.jsx(cS,{header:{title:"Daily brief",unreadCount:Z,footer:f?r.jsx(gc,{}):void 0,searchFilter:ce,searchResults:ee,searchLoading:I||F,relatedResults:te,relatedLoading:W,onSelectSearchResult:n},rows:j,onMarkMessagesRead:l,children:r.jsxs("div",{className:"flex h-full flex-col",children:[L.map(G=>r.jsx(oS,{accountEmail:G.email,accountId:G.accountId},G.accountId)),r.jsx("div",{className:"min-h-0 flex-1",children:ye})]})})})}const dS=10,Ed=e=>({q:e?.toLowerCase()??"",limit:dS}),fS=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(n=>n.normalizedEmail===s)};function mS(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Kn(t,{month:"short",year:"numeric"})}function Id(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const hS="We can't verify the sender of this email, which could mean it's from an insecure source.",pS="We couldn't read this sender's address, so we can't confirm who really sent this message.";function gS(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?mS(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Id(e.fromEmail)}}function xS(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 bS(e,t){const s=t>0?t:void 0;if(Id(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:pS,similarCount:s};const n=e.authenticity;if(!n)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:hS};if(!n.dkimMismatch)return{verdict:"aligned",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,summary:n.dkimDomain?`We verified this message was really sent by ${n.fromDomain}.`:"Nothing looks unusual about this sender."};const a=n.fromDomain,o=n.dkimDomain,i=e.fromName&&e.fromName!==e.fromEmail?e.fromName:void 0,l=i?`The display name claims "${i}", but this message was actually sent from ${o??"another sender"} — not ${a}. Real senders use their own address.`:`This message claims to be from ${a}, but it was actually sent from ${o??"a different sender"}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:l,similarCount:s}}function Td(e,t){const s=e?.fromEmail??null,n=e?.subject??"",{data:a,error:o}=xe({...sr({query:Ed(s??void 0)}),enabled:!!s,staleTime:3e4}),i=fS(a?.items,s??void 0),l=[n,s].filter(Boolean).join(" "),{data:u,isLoading:m,error:d}=xe({...Kl({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(x=>x.messageId!==e.messageId).map(x=>({id:x.messageId,mailboxId:t!=null&&x.mailboxIds.includes(t)?t:x.mailboxIds[0]??"",fromName:x.fromName??"",subject:x.subject??"(No subject)",timeLabel:x.sentDate!=null?yt(x.sentDate*1e3):"",matched:x.matchedChunkType})),g=gS(e,i),y=bS(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},b=xS(i);return{sender:g,authenticity:y,category:p,flags:b,similar:h}},[e,i,u,t]),isSimilarLoading:m,similarError:d,similarErrorIsFatal:fa(d),addressErrorIsFatal:fa(o),addressId:i?.addressId,address:i}}function vS(e,t){const s={...e??{}};for(const[n,a]of Object.entries(t))a==null?delete s[n]:s[n]={...a,setAt:a.setAt??Date.now()};return s}function Rd({addressId:e,senderEmail:t}){const s=Ee(),{pushError:n}=it(),a=Cm({query:Ed(t)}),{mutate:o,isPending:i}=Oe({...Bl(),onMutate:async u=>{const m=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,f=>f&&{...f,items:f.items.map(h=>h.addressId===u.path.addressId?{...h,flags:vS(h.flags,m)}:h)}),{previous:d}},onError:(u,m,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),n({title:"Couldn't update sender preference",detail:ft(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){ql(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 yS=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Md=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function wS(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function SS(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function kS(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Ad(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const CS=["personal","newsletter","marketing","automated","transactional","social"],jS=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:n}=e;return t?s&&t===s?n?"notSpam":null:s?"markSpam":null:null},NS=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:n}=e;return t&&!s?"error":n?"loading":"ready"};function ES(){return r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Nt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"h-8 rounded bg-surface"})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>r.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function IS({isOpen:e,current:t,onSelect:s,onCancel:n}){return e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:n,children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),r.jsx("div",{className:"mt-4 flex flex-col gap-1",children:CS.map(a=>r.jsxs("button",{type:"button",onClick:()=>s(a),className:`flex min-h-11 items-center justify-between rounded px-3 text-left text-sm capitalize transition-colors hover:bg-surface-raised ${a===t?"font-semibold text-accent":"text-fg"}`,children:[a,a===t&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"current"})]},a))}),r.jsx("div",{className:"mt-6 flex justify-end",children:r.jsx("button",{type:"button",onClick:n,className:"inline-flex min-h-11 items-center justify-center rounded border border-line px-4 text-sm font-medium transition-colors hover:bg-surface-raised",children:"Cancel"})})]})]}):null}function TS({thread:e,onClose:t,mailboxId:s,accountId:n,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:m}=Td(e,s),[d,f]=c.useState(!1),[h,g]=c.useState(!1),y=e.fromEmail??void 0,{updateFlags:p,isPending:b}=Rd({addressId:i,senderEmail:y}),{junkMailboxId:x}=_s(n),{inboxMailboxId:S}=So(n),{moveMessages:w}=is({mailboxId:s??"",threadId:e.threadId,accountId:n}),v=dn(),C=jS({mailboxId:s,junkMailboxId:x,inboxMailboxId:S}),E=c.useCallback(()=>{S&&w([e.messageId],S)},[S,w,e.messageId]),I=c.useCallback(()=>{x&&(Ad(v,{count:1,senderTrust:e.senderTrust,wasRescuable:Md(e)}),w([e.messageId],x))},[x,w,e,v]),N=c.useCallback(()=>{},[]),D=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]),O=c.useCallback(()=>{o?.flags?.blocked===!0?p({blocked:{value:!1}}):f(!0)},[o?.flags?.blocked,p]),L=c.useCallback(()=>{f(!1),p({blocked:{value:!0}})},[p]),M=c.useCallback(()=>{const T=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:T}})},[o?.flags?.unsubscribed,p]),k=c.useCallback(T=>{g(!1),p({category:{value:T}})},[p]),P=i!==void 0,F={onToggleVip:P?D:void 0,onToggleMute:P?A:void 0,onToggleBlock:P?O:void 0,onToggleUnsubscribe:P?M:void 0,onReclassify:P?()=>g(!0):void 0,onNotSpam:C==="notSpam"?E:void 0,onMarkSpam:C==="markSpam"?I:void 0},j=({mailboxId:T,messageId:V,className:Z,ariaLabel:ee,children:fe})=>r.jsx(Ct,{to:"/mail/$mailboxId",params:{mailboxId:T},search:W=>({...W,selectedMessageId:V}),className:Z,"aria-label":ee,children:fe});if(!o)return r.jsx(ES,{});const R=NS({similarError:u,similarErrorIsFatal:m,isSimilarLoading:l});return r.jsxs(r.Fragment,{children:[r.jsx(pc,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:N,actions:F,similarState:R,similarLinkComponent:j,className:"border-l-0 h-full w-full"}),r.jsx(eo,{isOpen:d,title:"Block this sender?",description:`Messages from ${y??"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:L,onCancel:()=>f(!1)}),r.jsx(IS,{isOpen:h,current:o.category.value,onSelect:k,onCancel:()=>g(!1)})]})}const Ks=({onClose:e,thread:t,mailboxId:s,accountId:n,hideCloseButton:a})=>t?r.jsx(TS,{thread:t,onClose:e,mailboxId:s,accountId:n,hideCloseButton:a}):r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Nt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[r.jsx(Nt,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),ia="Open a message first",Po=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:n,onReply:a,onReplyAll:o,onForward:i,onDelete:l,canDelete:u,onToggleStar:m,isStarred:d,moveContext:f})=>{const[h,g]=c.useState(null),y=u??e,p=b=>()=>g(b);return r.jsx(yp,{hasThread:e,isStarred:d,onUnavailable:b=>g(ia),unavailableHint:h,replyTitle:`Reply ${Ss("reply")}`,replyAllTitle:`Reply all ${Ss("replyAll")}`,forwardTitle:`Forward ${Ss("forward")}`,deleteTitle:`Move to Trash ${Ss("delete")}`,flagTitle:`Star ${Ss("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:y?l:p(ia),onToggleStar:m,onMove:p(ia),moveSlot:f?r.jsx(jr,{accountId:f.accountId,currentMailboxId:f.currentMailboxId,onMove:f.onMove,label:"Move to mailbox"}):void 0,children:r.jsx(vp,{open:t,enabled:s,onToggle:n})})},Od=()=>{const e=Ee();return c.useCallback(t=>{const s=ds({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])},an=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=t??e?.mailboxId,o=s??e?.accountId,{accountId:i}=vo(o?void 0:a),l=o??i,u=Od(),{deleteMessages:m}=ls({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:n}),{moveMessages:d}=is({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:n}),{toggleStar:f}=yo({threadId:e?.threadId??"",mailboxId:a??""}),h=c.useCallback(()=>{e&&m(u(e))},[e,u,m]),g=c.useCallback(S=>{e&&d(u(e),S)},[e,u,d]),y=c.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[p,b]=c.useState(null),x=c.useCallback(()=>b(null),[]);return{mailboxId:a,accountId:l,isStarred:e?.hasStars,deleteThread:h,moveThread:g,toggleStar:y,composeRequest:p,requestCompose:b,clearComposeRequest:x}},Qs={action:null,nextPrefix:null,preventDefault:!1},RS={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},MS={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 AS(e,t){const s=e.key.toLowerCase(),n=e.metaKey||e.ctrlKey;if(e.inEditable)return{...Qs,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...Qs,nextPrefix:t==="g"?null:t};if(n&&s==="n")return{action:"compose",nextPrefix:null,preventDefault:!0};if(n&&s==="a")return{action:"selectAll",nextPrefix:null,preventDefault:!0};if(n)return{...Qs,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=RS[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=MS[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?Qs:{action:a.action,nextPrefix:null,preventDefault:!0}}return Qs}function OS(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const DS="data-message-row",PS='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function LS(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(PS);return t?!t.hasAttribute(DS):!1}function FS({handlers:e,enabled:t=!0,sequenceTimeoutMs:s=1e3}){const n=c.useRef(e);n.current=e;const a=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{if(!t)return;const i=()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},l=u=>{const m=AS({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:OS(u.target),onControl:LS(u.target)},a.current);if(i(),a.current=m.nextPrefix,m.nextPrefix!==null&&(o.current=setTimeout(()=>{a.current=null,o.current=null},s)),m.action===null)return;const d=n.current[m.action];d&&(m.preventDefault&&u.preventDefault(),d())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l),i(),a.current=null}},[t,s])}const gl=(e,t,s)=>{if(!t)return null;const n=e.indexOf(t);if(n===-1)return null;const a=s==="next"?n+1:n-1;return a<0||a>=e.length?null:e[a]},Lo=()=>{const[e,t]=c.useState(void 0),[s,n]=c.useState([]),[a,o]=c.useState([]),i=c.useRef(null),[l,u]=c.useState(!1),[m,d]=c.useState(!1),f=c.useCallback(h=>{t(h.focusedMessageId),n(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:f,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:l,blocksKeyboard:m}},Fo=({context:e,orderedIds:t,selectedMessageId:s,enabled:n=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:l,blocksKeyboard:u}=e,m=c.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return FS({enabled:n&&!u,handlers:{...l?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:m,...o}}),{goBack:m,nextMessageId:gl(t,s,"next")??void 0,previousMessageId:gl(t,s,"previous")??void 0}};function $S(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function Dd(e,t){if(e)return $S(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const Pd=c.createContext(null);function Ir(){const e=c.useContext(Pd);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function _S({selectedMessageId:e,children:t}){const s=He(),{searchInput:n}=Ie(),{selectedThreadId:a,selectedMailboxId:o}=Rs({strict:!1}),{data:i}=xe({...da(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(A=>A.messageId===e)},[i,e]),u=c.useMemo(()=>Dd(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),m=c.useCallback((A,O)=>{s({to:"/mail",search:L=>({...L,selectedMessageId:A,selectedThreadId:void 0,selectedMailboxId:void 0}),replace:O?.replace})},[s]),d=c.useCallback(A=>{s({to:"/mail",search:O=>({...O,q:n||void 0,selectedMessageId:A.id,selectedThreadId:A.threadId,selectedMailboxId:A.mailboxId})})},[s,n]),f=c.useCallback(A=>{e&&A.includes(e)&&s({to:"/mail",search:O=>({...O,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=an({thread:l,onAfterOptimisticRemove:f}),g=c.useCallback(()=>{s({to:"/mail",search:A=>({...A,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),y=Lo(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:b}=ls({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:f}),{toggleReadFor:x}=wr({mailboxId:l?.mailboxId??"",messages:p}),S=c.useCallback(A=>x(A,!0),[x]),w=y.focusedMessageId,C=c.useMemo(()=>i?.items.find(A=>A.messageId===w),[i,w])??l,E=an({thread:C}),{nextMessageId:I,previousMessageId:N}=Fo({context:y,orderedIds:y.orderedIds,selectedMessageId:e,onClose:g,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{y.listCommandsRef.current?.requestDelete()||E.deleteThread()},toggleStar:E.toggleStar,toggleRead:()=>{const A=y.selectedIds.length>0?y.selectedIds:C?[C.messageId]:[];A.length!==0&&x(A,!(C?.isRead??!1))},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),D={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:m,onSelectSearchResult:d,onCloseThread:g,actions:h,triage:y,onDeleteMessages:b,onMarkMessagesRead:S,nextMessageId:I,previousMessageId:N};return r.jsx(Pd.Provider,{value:D,children:t})}function Ld(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:n,onDeleteMessages:a,onMarkMessagesRead:o}=Ir(),{accounts:i}=Ie();return r.jsx(uS,{accounts:i,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:n.listCommandsRef,onTriageContextChange:n.onTriageContextChange,onDeleteMessages:a,onMarkMessagesRead:o})}function zS(){const{conversation:e,actions:t}=Ir(),{intelligenceOpen:s,onToggleIntelligence:n}=Ie(),a=Ds()?.showIntelligencePane??!1,o=!!e,i=a&&o;return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Po,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(zs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx($s,{})})]})}function BS(){const{selectedThread:e}=Ir(),{onToggleIntelligence:t}=Ie();return r.jsx(Ks,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function KS(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:n,nextMessageId:a,previousMessageId:o}=Ir(),{intelligenceOpen:i,onToggleIntelligence:l}=Ie();return t?r.jsxs(r.Fragment,{children:[r.jsx(zs,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:n,onOpenIntelligence:l,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:i}),r.jsx(go,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:l,thread:e,hideCloseButton:!0})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Ld,{})})}const Gs=Object.assign(_S,{List:Ld,Reading:zS,Intelligence:BS,Phone:KS}),US=()=>Wa({query:{starred:!0,order:"desc"}});function Fd(){const{data:e,isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=Yc({queryKey:US(),queryFn:async({pageParam:m})=>{const{data:d}=await jm({query:{starred:!0,order:"desc",continuationToken:m},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:m=>m.continuationToken,staleTime:6e4});return{threads:c.useMemo(()=>(e?.pages??[]).flatMap(m=>m.items??[]),[e]),isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}}const qS=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function $d({title:e,unreadCount:t,preset:s,selectedCategory:n,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:l,onClearFilters:u,children:m,footer:d,searchResults:f,searchLoading:h,relatedResults:g,relatedLoading:y,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:x,searchResultsInBody:S}){const[w,v]=c.useState(!1),{searchInput:C}=Ie(),E=C.trim().length>0,I={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:n,activeFilters:a,expanded:w,onExpandedChange:v,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return r.jsx(hd,{title:e,unreadCount:t,footer:d,searchFilter:I,searchResults:f,searchLoading:h,relatedResults:g,relatedLoading:y,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:x,searchResultsInBody:S,children:r.jsx(Ml,{...I,hideChrome:E,children:m})})}const HS={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function WS({rows:e}){const{selectedIds:t,exitSelection:s}=Oo(),n=c.useMemo(()=>e.filter(a=>t.has(a.id)).map(a=>({id:a.id,sender:a.fromName,email:a.fromEmail,subject:a.subject,date:a.timeLabel})),[e,t]);return r.jsx(Do,{verb:"organize",selection:n,crossAccount:!0,onFinished:s})}function VS({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:n,onDeleteMessages:a,onMarkMessagesRead:o}){const{searchQuery:i,resultFolderIndex:l}=Ie(),u=ms(),m=Vt(),[d,f]=c.useState("all"),[h,g]=c.useState(new Set),y=c.useCallback(R=>{g(T=>{const V=new Set(T);return V.has(R)?V.delete(R):V.add(R),V})},[]),p=c.useCallback(()=>{f("all"),g(new Set)},[]),{threads:b,isLoading:x,isError:S,error:w,refetch:v,fetchNextPage:C,hasNextPage:E,isFetchingNextPage:I}=Fd(),{freeText:N,tokens:D}=Bs(i.trim().toLowerCase(),u),A=c.useMemo(()=>{const R=Array.from(h).map(T=>HS[T]).filter(T=>T!=null);return qS(b).map(Qn).filter(T=>(d==="all"||T.category===d)&&R.every(V=>V(T))&&(!N||od(T,N))&&Ro(T,D))},[b,d,h,N,D]),O=c.useMemo(()=>Wg(),[]),L=c.useMemo(()=>A.map(R=>id(R,l)),[A,l]),M=c.useMemo(()=>A.filter(R=>!R.isRead).length,[A]),k=x?"loading":S?"error":A.length===0?"empty":"ready",P=c.useCallback(()=>{const R=Ua(Ka());window.open(R,"_blank","noopener,noreferrer")},[]),F=Er(),j=r.jsx("div",{className:"flex h-full min-h-0 flex-col",children:r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r.jsx("div",{className:"divide-y divide-line",children:A.map(R=>r.jsx(Gn,{thread:R,active:R.id===e,onClick:()=>t?.(R.id)},R.id))}),E?r.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>C(),disabled:I,children:I?"Loading…":"Load more"}):null]})});return r.jsx($d,{title:"Starred",unreadCount:M,preset:O,selectedCategory:d,activeFilters:h,onSelectCategory:f,onToggleFilter:y,onClearFilters:p,searchResults:L,searchLoading:x,onSelectSearchResult:R=>t?.(R.id),children:r.jsxs(yd,{selectedMessageId:e,onOpen:(R,T)=>t?.(R,T),onDeleteMessages:a,commandsRef:s,onTriageContextChange:n,children:[r.jsx(kc,{listTitle:"Starred",sections:[{id:"flagged",threads:A}],flatList:!0,hideHeader:!0,listState:F.searchResults?"ready":k,searchQuery:N?i:void 0,errorMessage:S?Wl(w):void 0,onRetry:()=>v(),onReportError:P,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:m,selectionBar:r.jsx(Cw,{title:"Starred",onMarkAsRead:o}),listBody:F.searchResults??(k==="ready"?j:void 0)}),r.jsx(WS,{rows:A})]})})}const _d=c.createContext(null);function Tr(){const e=c.useContext(_d);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function QS({selectedMessageId:e,children:t}){const s=He(),{threads:n}=Fd(),a=c.useMemo(()=>{if(e)return n.find(v=>v.messageId===e)},[n,e]),o=c.useCallback((v,C)=>{s({to:"/mail/flagged",search:E=>({...E,selectedMessageId:v}),replace:C?.replace})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:v=>({...v,selectedMessageId:void 0})})},[s]),l=c.useCallback(v=>{e&&v.includes(e)&&i()},[e,i]),u=an({thread:a,onAfterOptimisticRemove:l}),m=Lo(),{deleteMessages:d}=ls({mailboxId:a?.mailboxId??"",messages:n,onAfterOptimisticRemove:l}),{toggleReadFor:f}=wr({mailboxId:a?.mailboxId??"",messages:n}),h=c.useCallback(v=>f(v,!0),[f]),g=m.focusedMessageId,p=c.useMemo(()=>n.find(v=>v.messageId===g),[n,g])??a,b=an({thread:p}),{nextMessageId:x,previousMessageId:S}=Fo({context:m,orderedIds:m.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{m.listCommandsRef.current?.requestDelete()||b.deleteThread()},toggleStar:b.toggleStar,toggleRead:()=>{const v=m.selectedIds.length>0?m.selectedIds:p?[p.messageId]:[];v.length!==0&&f(v,!(p?.isRead??!1))},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),w={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:m,onDeleteMessages:d,onMarkMessagesRead:h,nextMessageId:x,previousMessageId:S};return r.jsx(_d.Provider,{value:w,children:t})}function zd(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:n,onMarkMessagesRead:a}=Tr();return r.jsx(VS,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:n,onMarkMessagesRead:a})}function GS(){const{selectedThread:e,actions:t}=Tr(),{intelligenceOpen:s,onToggleIntelligence:n}=Ie(),a=Ds()?.showIntelligencePane??!1,o=!!e,i=a&&o;return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Po,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(zs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx($s,{})})]})}function YS(){const{selectedThread:e}=Tr(),{onToggleIntelligence:t}=Ie();return r.jsx(Ks,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function XS(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:n,previousMessageId:a}=Tr(),{intelligenceOpen:o,onToggleIntelligence:i}=Ie();return e?r.jsxs(r.Fragment,{children:[r.jsx(zs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:i,onSwipeNext:n?()=>s(n):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:o}),r.jsx(go,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:i,thread:e,hideCloseButton:!0})})]}):r.jsx("div",{className:"h-full",children:r.jsx(zd,{})})}const Ys=Object.assign(QS,{List:zd,Reading:GS,Intelligence:YS,Phone:XS}),JS={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},ZS=()=>{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},[])},ek=()=>{const{state:e,closeCompose:t}=Wt(),s=ZS(),[n,a]=c.useState(!1),{isError:o,error:i,refetch:l}=xe({...It(),staleTime:1/0}),u=c.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),m=c.useCallback(()=>{a(!1),t()},[t]),d=c.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const f=JS[e.mode]??"New Message";return r.jsxs(ct.Root,{open:e.isOpen,onOpenChange:u,children:[r.jsxs(ct.Portal,{children:[r.jsx(ct.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(ct.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[r.jsx(ct.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),r.jsx(ct.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:f}),o?r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(Qt,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):r.jsx("div",{className:"flex-1 overflow-hidden",children:r.jsx(xo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),n&&r.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50",children:r.jsxs("div",{className:"mx-4 w-full max-w-sm rounded-xl bg-canvas p-6 shadow-xl",children:[r.jsx("h3",{className:"text-lg font-semibold",children:"Discard draft?"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Your message has unsaved content. Are you sure you want to discard it?"}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx("button",{type:"button",onClick:d,className:"rounded-md px-4 py-2 text-sm font-medium hover:bg-surface-raised transition-colors",children:"Keep editing"}),r.jsx("button",{type:"button",onClick:m,className:"rounded-md bg-danger px-4 py-2 text-sm font-medium text-canvas hover:bg-danger/90 transition-colors",children:"Discard"})]})]})})]})},tk={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Bd=()=>{const{state:e,closeCompose:t}=Wt(),s=Vt(),{isError:n,error:a,refetch:o}=xe({...It(),staleTime:1/0});if(!s)return r.jsx(ek,{});if(!e.isOpen)return null;const i=tk[e.mode]??"New Message",l=r.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[r.jsx("div",{className:"flex items-center gap-2 min-w-0",children:r.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:r.jsx(vt,{className:"size-5"})})]});return n?r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[l,r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(Qt,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):r.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[l,r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:r.jsx(xo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function sk(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:yt(e.updatedAt),isRead:!0}}function nk(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:yt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function rk({outboxMessages:e,accountId:t,imapThreads:s}){const n=e.filter(i=>i.status==="draft"&&i.accountId===t).map(sk),a=s.map(nk),o=[];return n.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:n}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function $o(){const e=Ds();return!e||e.showNavPane?null:r.jsx(oe,{variant:"ghost",size:"sm",icon:r.jsx(Ya,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const ak=({label:e,count:t})=>r.jsxs("div",{className:"sticky top-0 z-10 flex items-baseline justify-between border-b border-line bg-surface-sunken px-row-inset py-1",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:t})]}),ok=({row:e,isSelected:t,onOpen:s,onDelete:n,isDeleting:a})=>r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:Y("group",Fs({active:t})),children:[r.jsx(Rl,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),r.jsx(sn,{thread:e}),r.jsx("div",{className:"flex items-center gap-1 shrink-0",children:r.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),n(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:r.jsx(Et,{className:"size-3.5"})})})]}),ik=({row:e,isSelected:t,onOpen:s})=>{const n=!e.isRead;return r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:Y("group",Fs({active:t})),children:[n&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx(bt,{name:e.fromName,email:e.fromEmail,size:"sm"}),r.jsx(sn,{thread:e})]})};function lk({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:n,title:a,unreadCount:o}){const{openCompose:i,state:l}=Wt(),u=He(),m=Ee(),{data:d}=xe(tr()),f=c.useMemo(()=>rk({outboxMessages:d?.items??[],accountId:t,imapThreads:n}),[d?.items,t,n]),h=Oe({...nr(),onSuccess:()=>{m.invalidateQueries({queryKey:Ga()})}}),g=x=>{h.mutate({path:{outboxMessageId:x}})},y=x=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:x})},p=x=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:x}})},b=f.length===0;return r.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx($o,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:a}),(o??0)>0&&r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:[o," unread"]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:b?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[r.jsx(Pa,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):f.map(x=>r.jsxs("div",{children:[x.label&&r.jsx(ak,{label:x.label,count:x.threads.length}),r.jsx("div",{className:"divide-y divide-line",children:x.threads.map(S=>x.id==="remit-drafts"?r.jsx(ok,{row:S,isSelected:l.isOpen&&S.id===l.outboxMessageId,onOpen:y,onDelete:g,isDeleting:h.isPending},S.id):r.jsx(ik,{row:S,isSelected:S.id===s,onOpen:p},S.id))})]},x.id))})]})}function ck(e,t,s){const n=new Array(e);return new Proxy(n,{get(a,o,i){if(typeof o=="string"){const l=o.charCodeAt(0);if(l>=48&&l<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let m=a[u];if(!m){const d=t[u*2];m=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return m}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function ws(e,t,s){let n=s.initialDeps??[],a,o=!0;function i(){const l=e();return(l.length!==n.length||l.some((m,d)=>n[d]!==m))&&(n=l,a=t(...l),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=l=>{n=l},i}function xl(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const uk=(e,t)=>Math.abs(e-t)<1.01,dk=(e,t,s)=>{let n;return function(...a){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,a),s)}};let Xs;const la=()=>{if(Xs!==void 0)return Xs;if(typeof navigator>"u")return Xs=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Xs=!0;const e=navigator.maxTouchPoints;return Xs=navigator.platform==="MacIntel"&&e!==void 0&&e>0},bl=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},fk=e=>e,mk=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,a=new Array(n);for(let o=0;o<n;o++)a[o]=t+o;return a},hk=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const a=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(a(bl(s)),!n.ResizeObserver)return()=>{};const o=new n.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u?.borderBoxSize){const m=u.borderBoxSize[0];if(m){a({width:m.inlineSize,height:m.blockSize});return}}a(bl(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},Yn={passive:!0},pk=typeof window>"u"?!0:"onscrollend"in window,gk=(e,t,s)=>{const n=e.scrollElement;if(!n)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&pk;let i=0;const l=o?null:dk(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=f=>()=>{i=s(n),l?.(),t(i,f)},m=u(!0),d=u(!1);return n.addEventListener("scroll",m,Yn),o&&n.addEventListener("scrollend",d,Yn),()=>{n.removeEventListener("scroll",m),o&&n.removeEventListener("scrollend",d)}},xk=(e,t)=>gk(e,t,s=>{const{horizontal:n,isRtl:a}=e.options;return n?s.scrollLeft*(a&&-1||1):s.scrollTop}),bk=(e,t,s)=>{if(s.options.useCachedMeasurements){const n=s.indexFromElement(e),a=s.options.getItemKey(n);return s.itemSizeCache.get(a)??s.options.estimateSize(n)}if(t?.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}if(!t){const n=s.indexFromElement(e),a=s.options.getItemKey(n),o=s.itemSizeCache.get(a);if(o!==void 0)return o}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},vk=(e,{adjustments:t=0,behavior:s},n)=>{var a,o;(o=(a=n.scrollElement)==null?void 0:a.scrollTo)==null||o.call(a,{[n.options.horizontal?"left":"top"]:e+t,behavior:s})},yk=vk;class wk{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,n,a;return((a=(n=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:n.now)==null?void 0:a.call(n))??Date.now()},this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const l=o.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[m,d]of this.elementsCache)if(d===l){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=n())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=n())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=n())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var n,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:fk,rangeExtractor:mk,onChange:()=>{},measureElement:bk,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,m=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,g=o.count,y=this.getMeasurements(),p=h>0?((n=y[0])==null?void 0:n.key)??i.getItemKey(0):null,b=h>0?((a=y[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)){m=!0;const w=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??y[0]:null;w&&(l=[w.key,this.getScrollOffset()-w.start]);const v=o.followOnAppend===!0?"auto":o.followOnAppend||null;v&&g>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(g-1)!==b)&&(u=v)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(l&&this.scrollOffset!==null){const[h,g]=l,y=this.getMeasurements(),{count:p,getItemKey:b}=this.options;let x=0;for(;x<p&&b(x)!==h;)x++;if(x<p){const S=y[x];if(S){const w=S.start+g;w!==this.scrollOffset&&(f=w-this.scrollOffset,this.scrollOffset=w,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,u,f])},this.notify=s=>{var n,a;(a=(n=this.options).onChange)==null||a.call(n,this,s)},this.maybeNotify=ws(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}if(this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===o?this.scrollDirection:l<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!la()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,Yn),o.addEventListener("touchend",l,Yn),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,l,u]=a;o!==null&&!l&&(la()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),n=this.getMaxScrollOffset();if(s<0||s>n)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=ws(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,n,a,o,i,l,u,m)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:m}),{key:!1}),this.getMeasurements=ws(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:m},d)=>{const f=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const x of this.laneAssignments.keys())x>=s&&this.laneAssignments.delete(x);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(x=>{this.itemSizeCache.set(x.key,x.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 x=s*2;let S=this._flatMeasurements;if(!S||S.length<x){const C=new Float64Array(x);S&&h>0&&C.set(S.subarray(0,h*2)),S=C,this._flatMeasurements=S}let w;if(h===0)w=n+a;else{const C=h-1;w=S[C*2]+S[C*2+1]+m}for(let C=h;C<s;C++){const E=o(C),I=f.get(E),N=typeof I=="number"?I:this.options.estimateSize(C);S[C*2]=w,S[C*2+1]=N,w+=N+m}const v=ck(s,S,o);return this.measurementsCache=v,v}const g=this.measurementsCache.slice(0,h),y=new Array(l).fill(void 0),p=new Float64Array(l);let b=0;for(let x=0;x<h;x++){const S=g[x];S&&(y[S.lane]===void 0&&b++,y[S.lane]=x,p[S.lane]=S.end)}for(let x=h;x<s;x++){const S=o(x),w=this.laneAssignments.get(x);let v,C;const E=u==="estimate"||f.has(S);if(w!==void 0&&this.options.lanes>1){v=w;const A=y[v],O=A!==void 0?g[A]:void 0;C=O?O.end+m:n+a}else if(b===l){let A=0,O=p[0],L=y[0];for(let M=1;M<l;M++){const k=p[M];(k<O||k===O&&y[M]<L)&&(A=M,O=k,L=y[M])}v=A,C=O+m,E&&this.laneAssignments.set(x,v)}else v=x%this.options.lanes,C=n+a,E&&this.laneAssignments.set(x,v);const I=f.get(S),N=typeof I=="number"?I:this.options.estimateSize(x),D=C+N;g[x]={index:x,start:C,size:N,end:D,key:S,lane:v},y[v]===void 0&&b++,y[v]=x,p[v]=D}return this.measurementsCache=g,g},{key:!1,debug:()=>this.options.debug}),this.calculateRange=ws(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,a,o)=>s.length===0||n===0?(this.range=null,null):(this.range=kk(s,n,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ws(()=>{let s=null,n=null;const a=this.calculateRange();return a&&(s=a.startIndex,n=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:n,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,a=s.getAttribute(n);return a?parseInt(a,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),l=Math.min(this.options.count-1,a+o);return s>=i&&s<=l}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const n=this.indexFromElement(s),a=this.options.getItemKey(n),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,n)=>{var a,o;if(s<0||s>=this.options.count)return;let i,l,u;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)u=this.options.getItemKey(s),l=m[s*2],i=m[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,l=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,f=n-d;if(f!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,g=h?this.getTotalSize():0,y=((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},f,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,n),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-g):y&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=ws(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const l=s[o],u=n[l];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=Kd(0,n.length-1,o?l=>a[l*2]:l=>xl(n[l]).start,s);return xl(n[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,n,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+o?"end":"start"),n==="center"?s+=(a-o)/2:n==="end"&&(s-=o);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(n==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)n="end";else if(i.start<=o+this.options.scrollPaddingStart)n="start";else return[o,n];if(n==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),n];const l=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,n,i.size),n]},this.scrollToOffset=(s,{align:n="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,n),i=this.now();this.scrollState={index:null,align:n,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:n="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,n);if(!o)return;const[i,l]=o,u=this.now();this.scrollState={index:s,align:l,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:n="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let a;if(n.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=n.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=n[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&o.some(l=>l===null);){const l=n[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}a=Math.max(...o.filter(l=>l!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const n=this.getMeasurements();for(const a of n)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:n,behavior:a})=>{this._intendedScrollOffset=s+(n??0),this.options.scrollToFn(s,{behavior:a,adjustments:n},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&(la()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const n=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=n?n[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&uk(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&u>l;this.scrollState.lastTargetOffset=a,m||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Kd=(e,t,s,n)=>{for(;e<=t;){const a=(e+t)/2|0,o=s(a);if(o<n)e=a+1;else if(o>n)t=a-1;else return a}return e>0?e-1:0};function Sk(e,t,s){let n=0;for(;n<=t;){const a=(n+t)/2|0,o=e[a*2];if(o<s)n=a+1;else if(o>s)t=a-1;else return a}return n>0?n-1:0}function kk(e,t,s,n,a){const o=e.length-1;if(e.length<=n)return{startIndex:0,endIndex:o};if(n===1&&a!==null){const m=Sk(a,o,s);let d=m;const f=s+t;for(;d<o&&a[d*2]+a[d*2+1]<f;)d++;return{startIndex:m,endIndex:d}}let l=Kd(0,o,m=>e[m].start,s),u=l;if(n===1)for(;u<o&&e[u].end<s+t;)u++;else if(n>1){const m=Array(n).fill(0);for(;u<o&&m.some(f=>f<s+t);){const f=e[u];m[f.lane]=f.end,u++}const d=Array(n).fill(s+t);for(;l>=0&&d.some(f=>f>=s);){const f=e[l];d[f.lane]=f.start,l--}l=Math.max(0,l-l%n),u=Math.min(o,u+(n-1-u%n))}return{startIndex:l,endIndex:u}}const ca=typeof document<"u"?c.useLayoutEffect:c.useEffect;function Ck({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...n}){const a=c.useReducer(m=>m+1,0)[1],o=c.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=m=>{const d=o.current;if(!d.enabled||!d.container)return;const f=m.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const x=m.options.horizontal?"width":"height";d.container.style[x]=`${f}px`}const h=!!m.options.horizontal,g=d.mode==="transform",y=h?"left":"top",p=m.options.scrollMargin,b=m.getVirtualItems();for(const x of b){const S=x.start-p,w=m.elementsCache.get(x.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[y]=`${S}px`)}},l={...n,onChange:(m,d)=>{var f;const h=o.current;let g=!0;if(h.enabled){i(m);const y=m.range,p=h.prevRange;g=!p||p.isScrolling!==m.isScrolling||p.startIndex!==y?.startIndex||p.endIndex!==y?.endIndex,g&&(h.prevRange=y?{startIndex:y.startIndex,endIndex:y.endIndex,isScrolling:m.isScrolling}:null)}g&&(e&&d?$a.flushSync(a):a()),(f=n.onChange)==null||f.call(n,m,d)}},[u]=c.useState(()=>{const m=new wk(l);return Object.assign(m,{containerRef:d=>{const f=o.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const h=m.getTotalSize();f.lastSize=h;const g=m.options.horizontal?"width":"height";d.style[g]=`${h}px`}}})});return u.setOptions(l),ca(()=>u._didMount(),[]),ca(()=>u._willUpdate()),ca(()=>{i(u)}),u}function jk(e){return Ck({observeElementRect:hk,observeElementOffset:xk,scrollToFn:yk,...e})}const Ud=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",Nk=e=>`Select all ${Ud(e)}`,Ek=(e,t)=>`All ${xt(t)} ${Ud(e)} selected`,Ik=(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:yt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Sr(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),Tk=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,messageCount:m,isMultiSelectMode:d,onLongPress:f,isDesktop:h,density:g})=>r.jsx(Gn,{thread:Ik(e,m),linkMailboxId:t,inListbox:!0,active:s,focused:n,isTabStop:a,density:g,isDesktop:h,onFocusRow:o,selection:{isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:d,onLongPress:f}}),Rk=c.memo(Tk),Mk=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:yt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Sr(e.category),suspicious:t}},Ak=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,onDelete:h,onToggleRead:g,density:y})=>{const[p,b]=c.useState("none"),x=c.useCallback(C=>{navigator.vibrate?.(10),C==="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]),v=wd(e.messageId,u);return f||m?r.jsx(Rk,{thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,density:y}):r.jsx(Sc,{thread:Mk(e),selectionMode:!1,checked:!1,active:s,peek:p,onPeek:b,onToggleCheck:w,onLongPress:S,onOpen:()=>{},onAct:x,linkComponent:({onOpenClick:C,children:E,...I})=>r.jsx(Ct,{...I,to:"/mail/$mailboxId",params:{mailboxId:t},search:N=>({...N,selectedMessageId:e.messageId}),"data-message-row":!0,onMouseDown:v.onMouseDown,onContextMenu:v.onContextMenu,onClick:N=>{v.claimClick(N)||C(N)},children:E})})},Ok=72,Dk=32,Pk=5,qd="remit:list-density",Lk={kind:"delete"},vl={kind:"markRead"},Fk=()=>{try{const e=localStorage.getItem(qd);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},$k=({query:e})=>r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[r.jsx(Zn,{className:"size-4 text-fg-muted"}),r.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),_k=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:n,isError:a=!1,error:o,onRetry:i,searchQuery:l,searchPredicate:u,onDeleteMessages:m,onMoveMessages:d,isDeleting:f=!1,isMoving:h=!1,onLoadMore:g,hasMore:y=!1,isLoadingMore:p=!1,accountId:b,listTitle:x,listMeta:S,listFilter:w,listScopeLabel:v,onTriageContextChange:C,commandsRef:E,hideHeader:I=!1})=>{const N=c.useRef(null),D=He(),A=Vt(),O=Nm(),L=Qa(),[M,k]=c.useState("organize"),P=!!l?.trim(),F=Er(),{labels:j}=Za(b),[R,T]=c.useState(s),[V,Z]=c.useState(),ee=c.useCallback(_=>{Z(J=>J===_?J:void 0),T(_)},[]),[fe,W]=c.useState(Fk),te=c.useCallback(()=>{W(_=>{const J=_==="comfortable"?"compact":"comfortable";try{localStorage.setItem(qd,J)}catch{}return J})},[]),{toggleReadFor:ce}=wr({mailboxId:e}),{junkMailboxId:ie}=_s(b),{selectedIds:U,selectedCount:K,hasSelection:he,isSelected:Se,toggle:ye,select:G,clearSelection:B,selectRange:$,setAnchor:le,selectAll:ue,toggleAll:De,intersectWith:me}=xd(),Me=bd(K,A),[pe,de]=c.useState(null),ze=P&&!!u,ut=`${e}|${JSON.stringify(u??{})}`,H=Nd({mailboxId:e,accountId:b,enabled:ze,predicateKey:ut,searchQuery:u??{}}),Ge=H.phase.kind,ge=H.clear,be=c.useCallback(()=>{Ge==="escalated"&&ge(),B()},[B,ge,Ge]),[Ue,Ze]=c.useState(null),[et,Ye]=c.useState(null),Ae=c.useRef(null),Fe=c.useRef(!1),We=c.useRef(null),tt=!n&&t.length>0,st=pe!==null,ke=c.useCallback((_,J)=>{const{exit:Pt,retryIds:lt}=Wv(J);if(Pt){Ye(hl(_.kind,J.done)),Ze(null),be();return}if(lt.length>0){Ze({action:_,succeeded:J.done}),ue(lt);return}Ze(null)},[be,ue]),Q=jk({count:t.length,getScrollElement:()=>N.current,estimateSize:()=>fe==="compact"?Dk:Ok,overscan:Pk}),ae=s?t.findIndex(_=>_.messageId===s):-1,ne=R?t.findIndex(_=>_.messageId===R):-1,re=c.useCallback(_=>{if(_<0||_>=t.length)return;const J=t[_];if(Me){ye(J.messageId);return}Ae.current=J.messageId,Fe.current=!1,Z(J.messageId),T(J.messageId)},[t,Me,ye]),ve=c.useCallback(()=>{if(t.length===0)return;const _=ne<0?0:Math.min(ne+1,t.length-1);re(_)},[t.length,ne,re]),Ce=c.useCallback(()=>{if(t.length===0)return;const _=ne<=0?0:ne-1;re(_)},[t.length,ne,re]),Te=c.useCallback(()=>re(0),[re]),Ve=c.useCallback(()=>re(t.length-1),[re,t.length]),Be=c.useCallback(()=>{R&&ye(R)},[R,ye]),je=c.useMemo(()=>t.map(_=>_.messageId),[t]),Qe=c.useMemo(()=>{const _=[];for(const J of t)U.has(J.messageId)&&_.push({id:J.messageId,sender:J.fromName??J.fromEmail??"Unknown",email:J.fromEmail??"",subject:J.subject??"(No subject)",date:yt(J.sentDate)});return _},[t,U]),Re=c.useCallback((_,J)=>J.shiftKey?($(je,_,R),!0):J.metaKey||J.ctrlKey?(ye(_),!0):(be(),le(_),!1),[je,R,$,ye,be,le]),qe=c.useCallback(_=>{!m||_.length===0||(We.current=R??null,de({source:"ids",ids:_}))},[m,R]),z=c.useCallback(()=>{H.phase.kind==="escalated"&&(We.current=R??null,de({source:"predicate",total:H.phase.total}))},[H.phase,R]),se=c.useCallback(_=>{const J=gd(je,R,_);J!==void 0&&($(je,J),Ae.current=J,Fe.current=!1,Z(void 0),T(J))},[je,R,$]),$e=c.useCallback(()=>se(-1),[se]),Xe=c.useCallback(()=>se(1),[se]),wt=c.useCallback(()=>{je.length>0&&ue(je)},[je,ue]),At=c.useCallback(()=>pe!==null?!0:m?K>0?(qe(Array.from(U)),!0):R?(qe([R]),!0):!1:!1,[pe,m,K,U,R,qe]),Yt=c.useCallback(()=>{R&&D({to:"/mail/$mailboxId",params:{mailboxId:e},search:_=>({..._,selectedMessageId:R})})},[R,D,e]),hs=c.useCallback(_=>{D({to:"/mail/$mailboxId",params:{mailboxId:e},search:J=>({...J,selectedMessageId:_}),replace:!0})},[D,e]);pd({keyboardFocusedMessageId:V,openMessageId:s,enabled:A&&K===0,open:hs});const St=c.useCallback(()=>{K>0&&qe(Array.from(U))},[qe,K,U]),dt=c.useCallback(async(_,J)=>{const Pt=await H.runAction(_,J);ke(_,Pt)},[H,ke]),Xt=c.useCallback(async _=>{de(null),We.current=null,await dt(Lk,_)},[dt]),Mr=c.useCallback(()=>{if(!pe)return;if(pe.source==="predicate"){Xt(void 0);return}const{ids:_}=pe;if(_.length===0){de(null);return}if(_.length>bu){Xt(_);return}const J=new Set(_),Pt=t.findIndex(Je=>J.has(Je.messageId));let lt;for(let Je=Pt+1;Je<t.length;Je++)if(!J.has(t[Je].messageId)){lt=t[Je].messageId;break}if(lt===void 0){for(let Je=Pt-1;Je>=0;Je--)if(!J.has(t[Je].messageId)){lt=t[Je].messageId;break}}m?.(_),be(),We.current=null,de(null),lt!==void 0&&(Ae.current=lt,Fe.current=!1,ee(lt),A&&D({to:"/mail/$mailboxId",params:{mailboxId:e},search:Je=>({...Je,selectedMessageId:lt}),replace:!0})),A||Ye(hl("delete",_.length))},[pe,t,m,be,D,e,A,Xt,ee]),Ot=c.useCallback(()=>{const _=We.current;We.current=null,de(null),_!==null&&(Ae.current=_,Fe.current=!1,ee(_))},[ee]),Ar=c.useCallback(()=>{if(H.phase.kind==="escalated"){dt(vl);return}K!==0&&dt(vl,Array.from(U))},[H.phase,dt,K,U]),Us=c.useCallback(_=>{if(H.phase.kind==="escalated"){dt({kind:"move",destinationMailboxId:_});return}!d||K===0||(d(Array.from(U),_),be())},[H.phase,dt,d,K,U,be]),Or=c.useCallback(()=>{ie&&Us(ie)},[ie,Us]),Jt=c.useMemo(()=>{if(K===0)return;const _=new Set;for(const J of t)U.has(J.messageId)&&_.add(J.accountConfigId);if(_.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[K,U,t]),Dt=H.phase.kind==="idle"&&!H.isRunning,Zt=c.useCallback(_=>{k(_),L("match")},[L]),Dr=c.useCallback(_=>{m?.([_])},[m]),es=c.useCallback((_,J)=>{ce([_],!J)},[ce]),vn=c.useCallback(_=>{A||G(_)},[A,G]),yn=c.useCallback(()=>{if(H.phase.kind==="escalated"){z();return}St()},[H.phase,z,St]),Pr=c.useCallback(()=>{if(H.isRunning||H.phase.kind==="counting"){H.stop();return}be()},[H,be]),Lr=c.useCallback(()=>{H.clear()},[H]),Fr=c.useCallback(()=>{if(!Ue)return;const _=Array.from(U);if(Ue.action.kind==="delete"){Xt(_);return}dt(Ue.action,_)},[Ue,Xt,dt,U]);c.useEffect(()=>{if(Fe.current||!A&&s)return;const _=ne>=0?ne:ae;_>=0&&Q.scrollToIndex(_,{align:"auto"})},[ne,ae,Q,A,s]),c.useEffect(()=>{s&&(Fe.current=!1,ee(s))},[s,ee]),c.useEffect(()=>{R&&(t.some(_=>_.messageId===R)||ee(t[0]?.messageId))},[t,R,ee]),c.useEffect(()=>{C?.({focusedMessageId:R,selectedIds:Array.from(U),hasList:tt,blocksKeyboard:st})},[R,U,tt,st,C]);const wn=c.useRef(C);wn.current=C,c.useEffect(()=>()=>wn.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{H.phase.kind!=="idle"||H.isRunning||me(t.map(_=>_.messageId))},[t,me,H.phase,H.isRunning]);const Sn=c.useRef(e);c.useEffect(()=>{Sn.current!==e&&(Sn.current=e,be())},[e,be]),Xc({shouldBlockFn:({action:_})=>xw(_,he,O)?(be(),!0):!1,enableBeforeUnload:!1,disabled:!he||O!==void 0}),c.useEffect(()=>{const _=N.current;if(!_||!y||!g)return;const J=()=>{if(p)return;const{scrollTop:Pt,scrollHeight:lt,clientHeight:Je}=_;Pt+Je>=lt-200&&g()};return _.addEventListener("scroll",J,{passive:!0}),J(),()=>_.removeEventListener("scroll",J)},[y,p,g]),c.useEffect(()=>{const _=Ae.current;if(!_)return;const J=N.current?.querySelector(`[data-message-id="${_}"]`);J&&(Ae.current=null,J.focus({preventScroll:!0}))}),c.useEffect(()=>{if(E){if(!tt){E.current=null;return}return E.current={focusNext:ve,focusPrevious:Ce,focusFirst:Te,focusLast:Ve,openFocused:Yt,toggleSelect:Be,extendSelectDown:Xe,extendSelectUp:$e,selectAll:wt,clearSelection:()=>he?(be(),!0):!1,requestDelete:At,toggleDensity:te},()=>{E.current=null}}},[E,tt,ve,Ce,Te,Ve,Yt,Be,Xe,$e,wt,he,be,At,te]);const X=n?"loading":a?"error":t.length===0?"empty":"ready",nt=a?Wl(o):void 0,rt=c.useCallback(()=>{const _=Ua(Ka());window.open(_,"_blank","noopener,noreferrer")},[]),sf=[{id:"inbox",threads:[]}],$r=je.length>0&&je.every(_=>U.has(_)),nf=ze&&y&&$r&&!f&&!h&&H.phase.kind==="idle"&&!H.isRunning,rf=f||h||H.isRunning,af=H.phase.kind==="escalated"?H.phase.total:K,of=H.runningAction?Lw(H.runningAction.kind,H.progress?.done??0,H.progress?.total??0):H.phase.kind==="counting"?H.phase.countSoFar>=5e3?`Counting… ${xt(H.phase.countSoFar)} so far. This is a big result set.`:`Counting… ${xt(H.phase.countSoFar)} so far`:H.phase.kind==="escalated"?Ek(u??{},H.phase.total):void 0,lf=H.phase.kind!=="escalated"&&je.length>0?{checked:$r,indeterminate:K>0&&!$r,onChange:()=>De(je)}:void 0,cf=H.runningAction&&H.progress?{value:H.progress.done,max:H.progress.total,tone:zw(H.runningAction.kind)}:void 0,uf=H.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:H.stop}}:H.phase.kind==="escalated"&&!H.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:Lr}}:nf?{tone:"info",text:"",action:{label:Nk(u??{}),onClick:H.escalate}}:Ue!==null&&K>0?{tone:"danger",text:Fw(Ue.action.kind,Ue.succeeded,K),action:{label:`Retry ${xt(K)}`,onClick:Fr}}:void 0,df=!Dt&&(d||H.phase.kind==="escalated")&&b&&e?r.jsx(jr,{accountId:b,currentMailboxId:e,onMove:f||h?()=>{}:Us,disabledHint:Jt,label:"Move selected messages"}):void 0,ff=uf??(Jt?{tone:"warning",text:Jt}:void 0),mf=r.jsx(fr,{title:F.title||x,navSlot:F.navSlot,titleMeta:F.titleMeta,searchSlot:F.searchSlot,searchField:F.searchField,idleSlot:F.makeFilterSlot,count:af,onCancel:Pr,onDelete:Dt?()=>Zt("delete"):yn,onMove:Dt?()=>Zt("move"):void 0,moveSlot:df,onOrganize:Dt?()=>Zt("organize"):void 0,onJunk:ie&&ie!==e?Dt?()=>Zt("junk"):Jt?void 0:Or:void 0,onMarkRead:Dt?()=>Zt("markRead"):Ar,overflowSlot:b&&e&&K>0&&j.length>0?r.jsx(cd,{accountId:b,mailboxId:e,messageIds:Array.from(U)}):void 0,isBusy:rf,isCounting:H.phase.kind==="counting",selectAll:lf,statusLabel:of,progress:cf,notice:ff}),hf=vd(je,R),pf=c.useCallback(_=>{Fe.current=!0,ee(_)},[ee]),gf=r.jsxs(r.Fragment,{children:[P&&l&&r.jsx($k,{query:l}),r.jsxs("div",{ref:N,role:"listbox","aria-multiselectable":!0,"aria-label":x,className:"flex-1 overflow-y-auto",children:[r.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${Q.getTotalSize()}px`},children:Q.getVirtualItems().map(_=>{const J=t[_.index];return r.jsx("div",{role:"presentation","data-index":_.index,ref:Q.measureElement,className:Le("absolute left-0 top-0 w-full border-b border-line",H.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${_.start}px)`},children:r.jsx(Ak,{thread:J,mailboxId:e,isSelected:s===J.messageId,isFocused:R===J.messageId,isTabStop:hf===J.messageId,onFocusRow:pf,isChecked:Se(J.messageId),onToggleCheck:ye,onRowSelect:Re,isMultiSelectMode:Me,onLongPress:vn,isDesktop:A,onDelete:Dr,onToggleRead:es,density:fe})},_.key)})}),p&&r.jsx(lp,{})]})]}),xf=pe?pe.source==="ids"?pe.ids.length:pe.total:0,Bo=pe?.source==="predicate";return r.jsxs(r.Fragment,{children:[et&&!A&&r.jsx(ln,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>Ye(null),children:et}),r.jsx(kc,{listTitle:x,listMeta:S,sections:sf,flatList:!0,listState:F.searchResults?"ready":X,searchQuery:P?l:void 0,listFilter:w,listScopeLabel:v,errorMessage:nt,onRetry:i,onReportError:rt,density:fe,selectedThreadId:s,onSelectThread:_=>D({to:"/mail/$mailboxId",params:{mailboxId:e},search:J=>({...J,selectedMessageId:_})}),onSelectBriefCategory:()=>{},isDesktop:A,hideHeader:I,selectionBar:mf,listBody:F.searchResults??(X==="ready"?gf:void 0)}),r.jsx(eo,{isOpen:pe!==null,title:Ql(xf,Bo),description:Bo?"This count is a snapshot — new mail arriving during the delete won't be included. You can restore what's deleted from Trash later.":"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:f,onConfirm:Mr,onCancel:Ot}),r.jsx(Do,{verb:M,accountId:b,mailboxId:e,selection:Qe,crossAccount:Jt!==void 0,onFinished:be})]})},zk=e=>us({path:{accountId:e}}),Bk=e=>{const t=Ee(),s=dn(),n=Oe({...Em(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:zk(e)})}});return{trigger:()=>{n.mutate({path:{accountId:e}})},triggerAsync:()=>n.mutateAsync({path:{accountId:e}}),isPending:n.isPending,error:n.error,reset:n.reset}},Kk=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:n}=Bk(e);return r.jsx(Tg,{onRefresh:s,isRefreshing:n,children:t})};function Uk({accountId:e,currentMailboxId:t,candidates:s,onMove:n,children:a}){const[o,i]=c.useState(!1),l=dn(),{t:u}=er("mail",{useSuspense:!1}),m=c.useCallback((S,w)=>u(S,{defaultValue:w}),[u]),{inboxMailboxId:d}=So(e),f=ko(e),{data:h}=xe({...ot({path:{accountId:e}}),staleTime:1/0}),g=c.useMemo(()=>{const S=Ja(h?.items??[],f),w=un(f);return S.map(v=>({id:v.mailboxId,label:Ts(v,w.get(v.mailboxId),m),searchValue:v.fullPath,isCurrent:v.mailboxId===t}))},[h?.items,f,t,m]),y=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,wS(l,s.length))},[l,s.length]);const b=c.useCallback(()=>{SS(l,s.length),i(!0)},[l,s.length]),x=c.useCallback((S,w)=>{kS(l,{selected:S.length,total:s.length,toInbox:w===d}),n(S,w)},[l,s.length,d,n]);return r.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[r.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:r.jsx(Ag,{count:s.length,onReview:b})}),r.jsx("div",{className:"min-h-0 flex-1",children:a}),r.jsx(Kg,{open:o,candidates:s,defaultDestinationId:y,availableFolders:g,onConfirmMove:x,onCancel:()=>i(!1)})]})}const qk="We can verify this sender";function Hk(e){const{data:t}=xe({...Im({path:{mailboxId:e??""},query:{senderTrust:["vip","wellknown"],dkimMismatch:!1,results:!0,limit:500}}),enabled:!!e,staleTime:6e4});return{candidates:(t?.items??[]).map(n=>({id:n.messageId,senderName:n.fromName||n.fromEmail||"Unknown sender",senderAddress:n.fromEmail??"",subject:n.subject||"(no subject)",snippet:n.snippet??"",trustReason:qk,trustSubReason:yS(n.senderTrust),senderTrust:n.senderTrust}))}}const Wk=e=>{const t=new Set,s=[];for(const n of e)t.has(n.threadMessageId)||(t.add(n.threadMessageId),s.push(n));return s},Vk={unread:"unread",flagged:"starred",attachment:"attachments"},Qk=new Set(Object.values(at)),Hd=e=>Qk.has(e),Gk=e=>Hd(e.category)||e.attributes.size>0,Yk=e=>{const t={};Hd(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const n=Vk[s];n&&(t[n]=!0)}return t},Xk=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",Jk=["category","unread","starred","attachments"],yl=e=>JSON.stringify(Jk.map(t=>e?.[t]??null)),Zk=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},eC=(e,t)=>{const s=Zk(e);return s?yl(s)===yl(t):!1},Wd="remit:intelligence-open";function tC(){try{return localStorage.getItem(Wd)!=="closed"}catch{return!0}}function wl(e){try{localStorage.setItem(Wd,e?"open":"closed")}catch{}}const sC=(e,t)=>e!==t,nC=(e,t,s)=>{if(!(s||!t))return e.find(n=>n.messageId===t)},rC=(e,t,s,n)=>{if(e)return e;if(!(n||!s))return t?.messageId===s?t:void 0},On=e=>e[0],aC=e=>{const t=On(e.filter(l=>l.type==="from").map(l=>l.value)),s=On(e.filter(l=>l.type==="subject").map(l=>l.value)),n=On(e.filter(l=>l.type==="category").map(l=>l.category)),a=On(e.filter(l=>l.type==="isUnread"||l.type==="isRead").map(l=>l.type==="isUnread")),o=e.some(l=>l.type==="isStarred")?!0:void 0,i=e.some(l=>l.type==="hasAttachment")?!0:void 0;return{...t!==void 0?{from:t}:{},...s!==void 0?{subject:s}:{},...n!==void 0?{category:[n]}:{},...a!==void 0?{unread:a}:{},...o!==void 0?{starred:o}:{},...i!==void 0?{attachments:i}:{}}},oC=(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 iC(e,t={}){const s=aC(e),n={...s,...t};return{params:s,residual:e.filter(a=>!oC(n,a))}}function lC(e,t,s){if(t.length===0)return e;const n=[...t];return e.filter(a=>{const o=Qn(a);return Ro({...o,accountId:o.accountId??s},n)})}const cC=50,uC=new Map(Dc().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),Vd=c.createContext(null);function Rr(){const e=c.useContext(Vd);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function dC({mailboxId:e,selectedMessageId:t,children:s}){const n=He(),o=Nr()==="desktop",i=dn(),{accounts:l,searchQuery:u,searchInput:m,intelligenceOpen:d,onToggleIntelligence:f,onSetIntelligenceOpen:h}=Ie(),g=ms(),y=Io(u),p=y.length>0,{freeText:b,tokens:x}=Bs(y,g),[S,w]=c.useState("all"),[v,C]=c.useState(new Set),E=c.useMemo(()=>({category:S,attributes:v}),[S,v]),I=c.useMemo(()=>Yk(E),[E]),N=p||Gk(E),{params:D,residual:A}=iC(x,I),O={order:"desc",limit:cC,...b?{query:b}:{},...D,...I},L={category:O.category,unread:O.unread,starred:O.starred,attachments:O.attachments},M=N?Ha({path:{mailboxId:e},query:O}):rr({path:{mailboxId:e},query:{order:"desc"}}),{data:k,isLoading:P,isError:F,error:j,refetch:R,fetchNextPage:T,hasNextPage:V,isFetchingNextPage:Z}=Yc({queryKey:M,queryFn:async({pageParam:X})=>{if(N){const{data:rt}=await Ul({path:{mailboxId:e},query:{...O,continuationToken:X},throwOnError:!0});return rt}const{data:nt}=await Tm({path:{mailboxId:e},query:{order:"desc",continuationToken:X},throwOnError:!0});return nt},initialPageParam:void 0,getNextPageParam:X=>X.continuationToken,placeholderData:(X,nt)=>eC(nt?.queryKey,L)?X:void 0}),ee=c.useCallback(X=>{t&&X.includes(t)&&n({to:"/mail/$mailboxId",params:{mailboxId:e},search:nt=>({...nt,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,n]),{deleteMessages:fe,isPending:W}=ls({mailboxId:e,onAfterOptimisticRemove:ee}),{accountId:te}=vo(e),ce=lu({accounts:l}),{moveMessages:ie,isPending:U}=is({mailboxId:e,accountId:te,onAfterOptimisticRemove:ee}),K=lC(dy(Wk(k?.pages.flatMap(X=>X.items??[])??[])),A,te),he=c.useCallback(X=>{w(X)},[]),Se=c.useCallback(X=>{C(nt=>{const rt=new Set(nt);return rt.has(X)?rt.delete(X):rt.add(X),rt})},[]),ye=c.useCallback(()=>{w("all"),C(new Set)},[]),G=uC.get(S),B=G?{label:G,reach:A.length>0?"loaded-pages":Xk(O),onClear:ye}:void 0,$=sC(m,u),le=nC(K,t,$),[ue,De]=c.useState(void 0);c.useEffect(()=>{le&&De(le)},[le]);const me=rC(le,ue,t,$),{selectedThreadId:Me}=Rs({strict:!1}),pe=c.useMemo(()=>Dd(me,{messageId:t,threadId:$?void 0:Me,mailboxId:e}),[me,t,Me,$,e]),de=Lo(),{listCommandsRef:ze,onTriageContextChange:ut,focusedMessageId:H,selectedIds:Ge}=de,ge=K.find(X=>X.messageId===H)??me,be=c.useRef(null);c.useEffect(()=>{const X=me?.messageId??null;X&&be.current!==X&&me?.authenticity?.dkimMismatch&&(be.current=X,d||f())},[me?.messageId,me?.authenticity?.dkimMismatch,d,f]);const Ue=c.useRef(!1);c.useEffect(()=>{Ue.current||o&&me?.messageId&&(Ue.current=!0,tC()&&!d&&h(!0))},[o,me?.messageId,d,h]);const Ze=lv({accounts:l})??0,et=Ee(),{pushError:Ye}=it(),Ae=an({thread:me,mailboxId:e,accountId:te,onAfterOptimisticRemove:ee}),{draftsMailboxId:Fe}=ly(te),We=Fe!==void 0&&Fe===e,{archiveMailboxId:tt}=iy(te),st=Od(),{requestCompose:ke}=Ae,Q=c.useCallback(()=>{ke("reply")},[ke]),ae=c.useCallback(()=>{ke("reply_all")},[ke]),ne=c.useCallback(()=>{ke("forward")},[ke]),{state:re,openCompose:ve,closeCompose:Ce}=Wt(),Te=c.useCallback(()=>{ve({mode:"new"})},[ve]),Ve=Oe({...nr(),onError:X=>{Ye(as("Couldn't discard draft","The draft wasn't deleted.",X))}}),Be=c.useCallback(()=>{const X=re.outboxMessageId;X&&(Ve.mutate({path:{outboxMessageId:X}}),et.invalidateQueries({queryKey:Ga()}),Ce())},[re.outboxMessageId,Ve,et,Ce]),je=c.useCallback(()=>{n({to:"/mail/$mailboxId",params:{mailboxId:e},search:X=>({...X,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,n]),Qe=c.useCallback(X=>X?st(X):[],[st]),{toggleStar:Re}=yo({threadId:ge?.threadId??"",mailboxId:e}),{toggleReadFor:qe}=wr({mailboxId:e,accountId:te}),{junkMailboxId:z}=_s(te),se=z!=null&&z===e,{candidates:$e}=Hk(se?z:void 0),{moveMessages:Xe}=is({mailboxId:e,threadId:ge?.threadId,accountId:te,onAfterOptimisticRemove:ee}),{deleteMessages:wt}=ls({mailboxId:e,threadId:ge?.threadId,onAfterOptimisticRemove:ee}),{addressId:At,address:Yt}=Td(ge),{updateFlags:hs}=Rd({addressId:At,senderEmail:ge?.fromEmail??void 0}),St=c.useCallback(()=>t||!H?!1:(n({to:"/mail/$mailboxId",params:{mailboxId:e},search:X=>({...X,selectedMessageId:H})}),!0),[t,H,e,n]),dt=c.useCallback(()=>{St()||me&&ke("reply")},[St,me,ke]),Xt=c.useCallback(()=>{St()||me&&ke("reply_all")},[St,me,ke]),Mr=c.useCallback(()=>{St()||me&&ke("forward")},[St,me,ke]),Ot=c.useCallback(()=>Ge.length>0?Ge:Qe(ge),[Ge,Qe,ge]),Ar=c.useCallback(()=>{if(ze.current?.requestDelete())return;const X=Ot();X.length>0&&wt(X)},[ze,Ot,wt]),Us=c.useCallback(()=>{if(!z)return;const X=Ot();X.length!==0&&(Ad(i,{count:X.length,senderTrust:ge?.senderTrust??"unknown",wasRescuable:ge?Md(ge):!1}),Xe(X,z))},[z,Ot,Xe,i,ge]),Or=c.useCallback(()=>{if(Ge.length>0){const X=!(ge?.hasStars??!1),nt=new Set(Ge);for(const rt of K)nt.has(rt.messageId)&&rt.hasStars!==X&&Re(rt.messageId,rt.hasStars);return}ge&&Re(ge.messageId,ge.hasStars)},[Ge,K,ge,Re]),Jt=c.useCallback(()=>{const X=Ot();if(X.length===0)return;const nt=!(ge?.isRead??!1);qe(X,nt)},[Ot,ge,qe]),Dt=c.useCallback(()=>{if(!At)return;const X=Yt?.flags?.muted?.value!==!0;hs({muted:{value:X}})},[At,Yt,hs]),Zt=c.useCallback(()=>{if(!At)return;const X=Yt?.flags?.vip?.value!==!0;hs({vip:{value:X}})},[At,Yt,hs]),Dr=c.useCallback(()=>{d||f()},[d,f]),es=c.useCallback(X=>{n({to:X})},[n]),vn=We?"drafts":tt===e?"archive":z===e?"junk":"inbox",yn=c.useRef("");c.useEffect(()=>{const X=yn.current;yn.current=y,y.length>0&&X.length===0&&i.recordEvent("search.submitted",{mailboxType:vn})},[y,vn,i]);const Pr=We&&re.isOpen&&!!re.outboxMessageId&&!me,{goBack:Lr,nextMessageId:Fr,previousMessageId:wn}=Fo({context:de,orderedIds:K.map(X=>X.messageId),selectedMessageId:t,enabled:!re.isOpen,onClose:je,handlers:{reply:dt,replyAll:Xt,forward:Mr,delete:Ar,toggleStar:Or,toggleRead:Jt,muteSender:Dt,blockSender:Dr,vipSender:Zt,markJunk:Us,toggleIntelligence:me?f:void 0,compose:Te,goBrief:()=>es("/mail"),goInbox:()=>es("/mail"),goSent:()=>es("/mail"),goFlagged:()=>es("/mail/flagged"),goSettings:()=>es("/settings")}});bo({enabled:re.isOpen,bindings:[{key:"Escape",handler:Ce,preventDefault:!0}]});const Sn={mailboxId:e,selectedMessageId:t,selectedThread:me,conversation:pe,threads:K,isLoading:P,isError:F,error:j,mailboxAccountId:te,mailboxName:ce,unreadCount:Ze,isDraftsMailbox:We,isSpamFolder:se,rescueCandidates:$e,filterCategory:S,filterAttributes:v,onSelectFilterCategory:he,onToggleFilterAttribute:Se,onClearFilters:ye,listFilter:B,intelligenceOpen:d,onToggleIntelligence:f,searchPredicate:p&&A.length===0?O:void 0,onDeleteMessages:fe,onMoveMessages:ie,isDeleting:W,isMoving:U,onLoadMore:T,hasMore:V,isLoadingMore:Z,onTriageContextChange:ut,listCommandsRef:ze,onRetry:()=>R(),toolbarComposeRequest:Ae.composeRequest,onToolbarReply:Q,onToolbarReplyAll:ae,onToolbarForward:ne,onClearComposeRequest:Ae.clearComposeRequest,onToolbarDelete:Ae.deleteThread,onToolbarStar:Ae.toggleStar,onToolbarDiscardDraft:Be,onToolbarMove:Ae.moveThread,composeState:re,closeCompose:Ce,hasRemitDraftOpen:Pr,onBack:Lr,nextMessageId:Fr,previousMessageId:wn};return r.jsx(Vd.Provider,{value:Sn,children:s})}function Qd(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:n,isError:a,error:o,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,mailboxAccountId:g,mailboxName:y,unreadCount:p,isDraftsMailbox:b,isSpamFolder:x,rescueCandidates:S,onTriageContextChange:w,listCommandsRef:v,onRetry:C,filterCategory:E,filterAttributes:I,onSelectFilterCategory:N,onToggleFilterAttribute:D,onClearFilters:A,listFilter:O,searchPredicate:L}=Rr(),{searchQuery:M,searchInput:k,accounts:P,resultFolderIndex:F}=Ie(),j=Nr(),R=He(),T=y??"Inbox",V=c.useMemo(()=>Dc(),[]),Z=c.useMemo(()=>s.map(he=>_0(he,F)),[s,F]),{hits:ee,isLoading:fe}=ad({mailboxId:e,filterCategory:E}),W=c.useMemo(()=>ld(ee,s.map(he=>he.threadId),F),[ee,s,F]),te=c.useCallback(he=>R({to:"/mail/$mailboxId",params:{mailboxId:he.mailboxId??e},search:Se=>({...Se,q:k||void 0,selectedMessageId:he.id,selectedThreadId:he.threadId})}),[e,R,k]);if(b&&g)return r.jsx(lk,{mailboxId:e,accountId:g,selectedMessageId:t,imapThreads:s,title:y??"Drafts",unreadCount:p??void 0});const ce=r.jsx(_k,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:n,isError:a,error:o,onRetry:C,searchQuery:M,searchPredicate:L,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,accountId:g,listTitle:T,listFilter:O,listScopeLabel:T,hideHeader:!0,onTriageContextChange:w,commandsRef:v}),ie=P[0]?.accountId,U=j==="phone"&&ie?r.jsx(Kk,{accountId:ie,children:ce}):ce,K=x&&S.length>0&&g?r.jsx(Uk,{accountId:g,currentMailboxId:e,candidates:S,onMove:l,children:U}):U;return r.jsx($d,{title:T,unreadCount:p,preset:V,selectedCategory:E,activeFilters:I,onSelectCategory:N,onToggleFilter:D,onClearFilters:A,searchResults:Z,searchLoading:n,relatedResults:W,relatedLoading:fe,onSelectSearchResult:te,searchResultsInBody:!0,children:K})}function fC(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:l,onToolbarReply:u,onToolbarReplyAll:m,onToolbarForward:d,onClearComposeRequest:f,onToolbarDelete:h,onToolbarStar:g,onToolbarDiscardDraft:y,onToolbarMove:p,composeState:b}=Rr(),x=Ds()?.showIntelligencePane??!1,S=!!n,w=x&&S,v=b.isOpen&&!n?r.jsx(Bd,{}):n?r.jsx(zs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onOpenIntelligence:n.authenticity?.dkimMismatch?i:void 0,composeRequest:l,onComposeClose:f}):r.jsx($s,{});return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Po,{hasThread:S,intelligenceOpen:w&&o,canToggleIntelligence:w,onToggleIntelligence:i,onReply:S?u:void 0,onReplyAll:S?m:void 0,onForward:S?d:void 0,canDelete:S||a,onDelete:S?h:a?y:void 0,onToggleStar:S?g:void 0,isStarred:s?.hasStars,moveContext:S&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:v})]})}function mC(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:n}=Rr();return r.jsx(Ks,{onClose:n,thread:s,mailboxId:e,accountId:t})}function hC(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:n,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=Rr(),m=He();if(s){const d=f=>m({to:"/mail/$mailboxId",params:{mailboxId:e},search:h=>({...h,selectedMessageId:f,selectedThreadId:void 0})});return r.jsxs(r.Fragment,{children:[r.jsx(zs,{threadId:s.threadId,mailboxId:s.mailboxId,subject:s.subject,selectedMessageId:s.messageId,authenticity:s.authenticity,onBack:o,onOpenIntelligence:a,onSwipeNext:i?()=>d(i):void 0,onSwipePrevious:l?()=>d(l):void 0,mobileIntelligenceOpen:n}),r.jsx(go,{isOpen:n,onClose:a,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?r.jsx("div",{className:"h-full",children:r.jsx(Bd,{})}):r.jsx(Qd,{})}const Js=Object.assign(dC,{List:Qd,Reading:fC,Intelligence:mC,Phone:hC}),Gd=e=>e==="failed"||e==="blocked",Yd=e=>e!=="draft"&&e!=="sent",_o="remit.savedSearches",pC=25;function Xn(){try{const e=localStorage.getItem(_o);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function gC(e){const t=e.trim();if(!t)return Xn();const s=[t,...Xn().filter(n=>n!==t)].slice(0,pC);try{localStorage.setItem(_o,JSON.stringify(s))}catch{return s}return s}function xC(e){const t=Xn().filter(s=>s!==e);try{localStorage.setItem(_o,JSON.stringify(t))}catch{return t}return t}const Sl=e=>/^\d/.test(e),bC=(e,t)=>{const s=Sl(e),n=Sl(t);return s&&!n?-1:!s&&n?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function vC(e,t,s){const n=[],a=[];for(const o of e)t.has(o.mailboxId)?n.push(o):a.push(o);return a.sort((o,i)=>bC(Ts(o,void 0,s),Ts(i,void 0,s))),{system:n,labels:a}}function yC(e,t,s){const n=Rm(t)&&e.unseenCount>0;return{id:e.mailboxId,name:Ts(e,t,s),unseen:n?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function wC(){const e=xr(),t=qa({strict:!1});return e.pathname.startsWith("/settings")?"settings":e.pathname.startsWith("/mail/outbox")?"outbox":e.pathname.startsWith("/mail/flagged")?"flagged":t.mailboxId?t.mailboxId:e.pathname==="/mail"||e.pathname==="/mail/"?"brief":""}function kl({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const n=Ee(),a=He(),o=wC(),{searchInput:i,onSearchChange:l}=Ie(),[u,m]=c.useState(Xn),{t:d}=er("mail",{useSuspense:!1}),f=c.useCallback((N,D)=>d(N,{defaultValue:D}),[d]),h=mt({queries:e.map(N=>({...ot({path:{accountId:N.accountId}}),staleTime:1/0}))}),{data:g}=xe(tr()),y=c.useMemo(()=>(g?.items??[]).filter(N=>Yd(N.status)).length,[g?.items]),p=c.useMemo(()=>e.map((N,D)=>{const A=h[D],O=A?.data?.items??[],L=un(N.folderAppointments),{system:M,labels:k}=vC(O,L,f),P=A?.isError?"error":A?.isLoading?"loading":"ready";return{id:N.accountId,label:N.email,email:N.email,muted:!!N.muted,outboxPending:y,status:P,onRetry:()=>A?.refetch(),mailboxes:[...M,...k].map(F=>yC(F,L.get(F.mailboxId),f))}}),[e,h,y,f]),b=N=>{n.invalidateQueries({queryKey:rr({path:{mailboxId:N},query:{order:"desc"}})})},x=({navId:N,className:D,ariaLabel:A,title:O,children:L,onClick:M})=>N==="brief"?r.jsx(Ct,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>M?.(),className:D,"aria-label":A,title:O,children:L}):N==="outbox"?r.jsx(Ct,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>M?.(),className:D,"aria-label":A,title:O,children:L}):N==="flagged"?r.jsx(Ct,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>M?.(),className:D,"aria-label":A,title:O,children:L}):N==="settings"?r.jsx(Ct,{to:"/settings/accounts",onClick:()=>M?.(),className:D,"aria-label":A,title:O,children:L}):r.jsx(Ct,{to:"/mail/$mailboxId",params:{mailboxId:N},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{b(N),M?.()},className:D,"aria-label":A,title:O,children:L}),S=()=>{l(""),t?.()},w=i.trim(),v=w.length>0&&!u.includes(w)?w:void 0,C=c.useCallback(()=>{v&&m(gC(v))},[v]),E=c.useCallback(N=>{m(xC(N))},[]),I=c.useCallback(N=>{l(N),a({to:"/mail",search:{q:N,selectedMessageId:void 0}}),t?.()},[l,a,t]);return r.jsx(sg,{accounts:p,selectedNavId:o,onSelectNav:S,linkComponent:x,variant:s,savedSearches:u,saveableQuery:v,onSaveCurrentSearch:C,onSelectSavedSearch:I,onRemoveSavedSearch:E})}function SC({accounts:e,onMailboxSelect:t}){return Ds()?.showNavPane??!0?r.jsx(kl,{accounts:e}):r.jsxs("div",{className:"flex h-full flex-col",children:[r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(kl,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),r.jsxs("div",{className:"border-t border-line px-2 py-2",children:[r.jsxs(Ct,{to:"/settings/accounts",onClick:t,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[r.jsx(ro,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),r.jsx(tu,{variant:"drawer"}),r.jsx(eu,{children:({signOut:a})=>r.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[r.jsx(dc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function kC(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const n=[e.subject,e.fromAddress,e.fromName,...e.toAddresses??[],...e.ccAddresses??[]].filter(a=>typeof a=="string").join(" ").toLowerCase();return s.split(/\s+/).every(a=>a.length===0||n.includes(a))}function CC(e){return e.tokens.length>0&&e.freeText.trim().length===0}const Xd={queued:{icon:Xa,label:"Queued",className:"text-warning"},sending:{icon:Os,label:"Sending…",className:"text-accent-2"},sent:{icon:ic,label:"Sent",className:"text-positive"},failed:{icon:cs,label:"Failed",className:"text-danger"},blocked:{icon:La,label:"Blocked",className:"text-warning"}},jC=e=>Jm(e).toDateString()===new Date().toDateString()?Kn(e,{hour:"numeric",minute:"2-digit"}):Kn(e,{month:"short",day:"numeric"}),Cl=e=>Kn(e,{dateStyle:"medium",timeStyle:"short"}),NC=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},Jd=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",Zd=c.createContext(null);function zo(){const e=c.useContext(Zd);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function EC({children:e}){const t=He(),{selectedOutboxMessageId:s}=Rs({strict:!1}),{data:n,isLoading:a}=xe(tr()),{searchQuery:o}=Ie(),i=ms(),l=Io(o),u=Bs(l,i),m=l.length>0,d=CC(u),f=c.useMemo(()=>d?[]:(n?.items??[]).filter(p=>Yd(p.status)).filter(p=>kC(p,u.freeText)),[n,u.freeText,d]),h=c.useMemo(()=>f.find(p=>p.outboxMessageId===s),[f,s]),g=c.useCallback(p=>{t({to:"/mail/outbox",search:b=>({...b,selectedOutboxMessageId:p})})},[t]),y={messages:f,hasQuery:m,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:g};return r.jsx(Zd.Provider,{value:y,children:e})}function ef({message:e,isSelected:t,onSelect:s}){const n=Ee(),{openCompose:a}=Wt(),{pushError:o}=it(),i=c.useCallback(()=>{n.invalidateQueries({queryKey:Ga()})},[n]),l=Oe({...zl(),onSuccess:i,onError:f=>{o(as("Couldn't resend message","The message wasn't sent.",f))}}),u=Oe({...nr(),onSuccess:i,onError:f=>{o(as("Couldn't delete message","The message wasn't deleted.",f))}}),m=e.status;if(!Xd[m])return null;const d=Gd(e.status);return r.jsx(Eg,{recipients:NC(e),subject:e.subject||"",time:jC(e.sentAt??e.updatedAt),status:m,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:m==="failed"?()=>l.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:l.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function tf({message:e,onBack:t}){const s=e.status,n=Xd[s],a=n?.icon??cn,o=e.sentAt?Cl(e.sentAt):Cl(e.updatedAt);return r.jsxs("div",{className:"h-full overflow-y-auto bg-canvas",children:[r.jsxs("div",{className:"border-b border-line p-4",children:[t&&r.jsxs("button",{type:"button",onClick:t,className:"mb-3 inline-flex items-center gap-1 text-sm text-fg-muted hover:text-fg",children:[r.jsx(Aa,{className:"size-4"}),r.jsx("span",{children:"Back"})]}),r.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),r.jsxs("div",{className:"space-y-1 text-sm",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),r.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),r.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),r.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),r.jsx("span",{className:"text-fg",children:o})]}),n&&r.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[r.jsx(a,{className:Le("size-4",n.className,s==="sending"&&"animate-spin")}),r.jsx("span",{className:Le("text-xs font-medium",n.className),children:n.label}),Gd(e.status)&&e.lastError&&r.jsxs("span",{className:"text-xs text-fg-muted",children:["— ",e.lastError]})]})]})]}),r.jsx("div",{className:"p-4",children:r.jsx(Gu,{html:e.htmlBody,text:e.textBody})})]})}function IC(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,onSelectMessage:o}=zo(),i=c.useRef(null);return Jn({containerRef:i,itemSelector:Da}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx($s,{message:Jd(t,s),showHints:!1})}):r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx($o,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(l=>r.jsx(ef,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function TC(){const{selectedMessage:e}=zo();return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx("header",{className:"flex h-pane-header shrink-0 items-center border-b border-line px-3"}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(tf,{message:e}):r.jsx($s,{message:"Select a message to read",showHints:!1})})]})}function RC(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=zo(),l=c.useRef(null);return Jn({containerRef:l,itemSelector:Da}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?r.jsx(tf,{message:o,onBack:()=>i(void 0)}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx($s,{message:Jd(t,s),showHints:!1})}):r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx($o,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:l,className:"flex-1 overflow-y-auto",children:e.map(u=>r.jsx(ef,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const Dn=Object.assign(EC,{List:IC,Reading:TC,Phone:RC}),MC=({isOpen:e,onClose:t})=>{const s=c.useCallback(n=>{n.key==="Escape"&&(n.preventDefault(),t())},[t]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:t,onKeyDown:n=>n.key==="Escape"&&t(),children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.jsxs("div",{className:Le("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),onClick:n=>n.stopPropagation(),onKeyDown:n=>{n.key!=="Escape"&&n.stopPropagation()},children:[r.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),r.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:r.jsx(vt,{className:"size-5"})})]}),r.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:uu.map(n=>r.jsxs("div",{children:[r.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:n.title}),r.jsx("div",{className:"space-y-2",children:n.hints.map(a=>r.jsxs("div",{className:"flex items-center justify-between gap-4",children:[r.jsx("span",{className:"text-sm",children:a.description}),r.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>r.jsxs(c.Fragment,{children:[i>0&&a.keys[0]==="g"&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),r.jsx(js,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},n.title))}),r.jsx("div",{className:"mt-6 border-t border-line pt-4",children:r.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",r.jsx(js,{children:"Esc"})," to close"]})})]})]}):null};function AC(e){const t=mt({queries:e.map(s=>({...ot({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>ew(t.map(s=>s.data?.items??[])),[t])}const OC=e=>e.map(t=>t.data?.items??[]);function DC(e){const t=mt({queries:e.map(s=>({...ot({path:{accountId:s.accountId}}),staleTime:1/0})),combine:OC});return c.useMemo(()=>Mm(e.map((s,n)=>({folderAppointments:s.folderAppointments,mailboxes:t[n]??[]}))),[e,t])}var Pn={exports:{}},jl;function PC(){if(jl)return Pn.exports;jl=1;const e=(t,s,n)=>new Promise((a,o)=>{if(n=Object.assign({concurrency:1/0},n),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=n;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const l=[],u=t[Symbol.iterator]();let m=!1,d=!1,f=0,h=0;const g=()=>{if(m)return;const y=u.next(),p=h;if(h++,y.done){d=!0,f===0&&a(l);return}f++,Promise.resolve(y.value).then(b=>s(b,p)).then(b=>{l[p]=b,f--,g()},b=>{m=!0,o(b)})};for(let y=0;y<i&&(g(),!d);y++);});return Pn.exports=e,Pn.exports.default=e,Pn.exports}var LC=PC();const FC=Am(LC),$C=900*1e3,_C=300,zC=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},BC=60*1e3,KC=e=>Math.max(zC(e,_C)*1e3,BC),zn=KC(Pm().mailboxPollIntervalSeconds),UC=5,Ra=new Set,qC=(e,t,s=$C)=>e.filter(n=>{const a=n.lastSyncAt;return a==null?!0:t-a>s}).map(n=>n.accountId),HC=(e,t,s=zn)=>e-t>=s,WC=(e,t)=>e.filter(s=>!t.has(s)),Nl=(e,t)=>{if(Ra.delete(e),Dm(t,{softError:!0})){ql(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},El=(e,t)=>Om({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:us({path:{accountId:e}})})}),VC=e=>{const t=Ee(),s=c.useRef(e);s.current=e;const n=e.map(a=>a.accountId).join(",");c.useEffect(()=>{const a=Date.now(),i=qC(s.current,a).filter(l=>!Ra.has(l));if(i.length!==0)for(const l of i)Ra.add(l),El(l,t).catch(u=>{Nl(l,u)})},[n,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const d=WC(s.current.map(f=>f.accountId),i);for(const f of d)i.add(f);FC(d,f=>El(f,t).catch(h=>{Nl(f,h)}).finally(()=>{i.delete(f)}),{concurrency:UC})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,zn);return}},m=()=>{document.visibilityState==="visible"&&HC(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,zn))};return o=setTimeout(u,zn),document.addEventListener("visibilitychange",m),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",m)}},[n,t])};function QC(e,t,s){if(e!==t)return s}function GC(e,t){return e===""?"":t}function YC(e,t,s){return t!==e?!1:t!==s}function XC(){const{q:e=""}=Rs({from:"/mail"}),t=He(),s=Nr(),n=ud(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,m]=c.useState(!1),d=c.useCallback(U=>{m(U),wl(U)},[]),[f,h]=c.useState(e),g=ir(f,200),y=GC(f,g),p=c.useRef(e);p.current=e;const b=jt({select:U=>nv(U.matches)}),[x,S]=c.useState(b);if(x!==b){const U=QC(x,b,e);S(b),U!==void 0&&h(U)}c.useEffect(()=>{YC(f,y,p.current)&&t({to:".",search:U=>{const K=U.q===y;return{...U,q:y||void 0,...y&&!K?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[f,y,t]);const{data:w,isLoading:v,isError:C,error:E,refetch:I}=xe({...It(),staleTime:1/0}),N=!!(w&&(w.accounts?.length??0)===0);c.useEffect(()=>{N&&t({to:"/onboarding",replace:!0})},[N,t]),bo({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const D=c.useCallback(U=>{h(U)},[]),A=c.useCallback(()=>{h("")},[]),O=c.useCallback(()=>{h("")},[]),L=c.useCallback(()=>{m(U=>{const K=!U;return wl(K),K})},[]),M=w?.accounts??[],k=AC(M),P=DC(M),F=c.useMemo(()=>Z0(M),[M]),j=jt({select:U=>U.matches.find(he=>"mailboxId"in he.params)?.params.mailboxId}),{selectedMessageId:R}=Rs({strict:!1}),T=jt({select:U=>po(U.matches)}),V=jt({select:U=>mn(U.matches)}),Z=jt({select:U=>br(U.matches)});VC(M);const ee=c.useCallback(()=>{l(!1)},[]),fe={accounts:M,mailboxNameIndex:k,accountNameIndex:F,resultFolderIndex:P,searchQuery:y,searchInput:f,searchViewKey:b,onSearchChange:D,onSearchClear:A,onSearchClearQuery:O,intelligenceOpen:u,onToggleIntelligence:L,onSetIntelligenceOpen:d},W=r.jsx(SC,{accounts:M,onMailboxSelect:ee}),te=n?r.jsx(ev,{accounts:M}):void 0,ce=n?void 0:r.jsx(dv,{accounts:M}),ie={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return r.jsxs(Lm.Provider,{value:fe,children:[C?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:r.jsx(Qt,{title:"Couldn't load your account",error:E,onRetry:()=>{I()}})}):T?r.jsx(Gs,{selectedMessageId:R,children:n?r.jsx(Lt,{nav:W,list:r.jsx(Gs.Phone,{}),intelligenceOpen:u,overlay:te,skeleton:r.jsx(kt,{}),isLoading:v||N,...ie}):r.jsx(Lt,{nav:W,topBar:ce,list:r.jsx(Gs.List,{}),reading:r.jsx(Gs.Reading,{}),intelligence:r.jsx(Gs.Intelligence,{}),intelligenceOpen:u,hasThread:!!R,overlay:te,skeleton:r.jsx(kt,{}),isLoading:v||N,...ie})}):V?r.jsx(Ys,{selectedMessageId:R,children:n?r.jsx(Lt,{nav:W,list:r.jsx(Ys.Phone,{}),intelligenceOpen:u,overlay:te,skeleton:r.jsx(kt,{}),isLoading:v||N,...ie}):r.jsx(Lt,{nav:W,topBar:ce,list:r.jsx(Ys.List,{}),reading:r.jsx(Ys.Reading,{}),intelligence:r.jsx(Ys.Intelligence,{}),intelligenceOpen:u,hasThread:!!R,overlay:te,skeleton:r.jsx(kt,{}),isLoading:v||N,...ie})}):j?r.jsx(Js,{mailboxId:j,selectedMessageId:R,children:n?r.jsx(Lt,{nav:W,list:r.jsx(Js.Phone,{}),intelligenceOpen:u,overlay:te,skeleton:r.jsx(kt,{}),isLoading:v||N,...ie}):r.jsx(Lt,{nav:W,topBar:ce,list:r.jsx(Js.List,{}),reading:r.jsx(Js.Reading,{}),intelligence:r.jsx(Js.Intelligence,{}),intelligenceOpen:u,hasThread:!!R,overlay:te,skeleton:r.jsx(kt,{}),isLoading:v||N,...ie})}):Z?r.jsx(Dn,{children:n?r.jsx(Lt,{nav:W,list:r.jsx(Dn.Phone,{}),intelligenceOpen:!1,overlay:te,skeleton:r.jsx(kt,{}),isLoading:v||N,...ie}):r.jsx(Lt,{nav:W,topBar:ce,list:r.jsx(Dn.List,{}),reading:r.jsx(Dn.Reading,{}),intelligenceOpen:!1,overlay:te,skeleton:r.jsx(kt,{}),isLoading:v||N,...ie})}):r.jsx(kt,{}),r.jsx(MC,{isOpen:a,onClose:()=>o(!1)}),r.jsx(Fm,{})]})}const pj=Object.freeze(Object.defineProperty({__proto__:null,component:XC,useMailContext:Ie},Symbol.toStringTag,{value:"Module"}));export{hj as S,Vh as U,pj as m};
|