@remit/web-client-dist 0.0.309 → 0.0.310
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/{ErrorState-CoYNTNJq.js → ErrorState-DiX_zNTK.js} +1 -1
- package/assets/{OnboardingWizard-C6uaYNpR.js → OnboardingWizard-r-N3eGPg.js} +1 -1
- package/assets/{account-form-helpers-BqRAFw9h.js → account-form-helpers-BHUowns0.js} +1 -1
- package/assets/{accounts-D4OtZ41r.js → accounts-B4-7wVt4.js} +1 -1
- package/assets/{advanced-CLPJC7oW.js → advanced-Dlyjnb6l.js} +1 -1
- package/assets/{appearance-D9JbZ1CF.js → appearance-Drfetqy5.js} +1 -1
- package/assets/{avatar-no7z5maH.js → avatar-Ci3CMhdo.js} +1 -1
- package/assets/{browser-ponyfill-ClKzhM_I.js → browser-ponyfill-BhnZT7aq.js} +2 -2
- package/assets/{circle-check-BwajEOAH.js → circle-check-BM6iE_RP.js} +1 -1
- package/assets/{confirm-dialog-DPRgwpsP.js → confirm-dialog-F7nDmx5t.js} +1 -1
- package/assets/{download-C4twhQsf.js → download-Bg6cLSAV.js} +1 -1
- package/assets/{filters-BBCPnnZ1.js → filters-CsWlycJW.js} +1 -1
- package/assets/{flagged-Cujm8pvv.js → flagged-CuV2oZw_.js} +1 -1
- package/assets/{folders-BzM2UocM.js → folders-Dg7RilCS.js} +1 -1
- package/assets/{index-BLRngKEP.js → index-BSJKHoKS.js} +1 -1
- package/assets/index-dsr8I39S.js +1 -0
- package/assets/{index-DAzmnDmQ.js → index-xOALrEh8.js} +59 -59
- package/assets/{kbd-CJO6TTXi.js → kbd-C00o9L4B.js} +1 -1
- package/assets/{labels-DzYgbLjQ.js → labels-pEUVx_Ue.js} +1 -1
- package/assets/{mail-DWCiR4Nu.js → mail-Chm12_Xz.js} +14 -14
- package/assets/{move-options-peU5H7WV.js → move-options-B2c-WWEl.js} +1 -1
- package/assets/{onboarding-Cj7kSn2_.js → onboarding-DKy8Q5MV.js} +1 -1
- package/assets/{pencil-BYhgO1mk.js → pencil-CZK87pI9.js} +1 -1
- package/assets/{rich-text-DUirdWcq.js → rich-text-CoTs3nIc.js} +1 -1
- package/assets/{senders-Bf6ohezs.js → senders-p6LBrcYb.js} +1 -1
- package/assets/settings-C2TANSwS.js +1 -0
- package/assets/{settings-screen-BukG_Ts5.js → settings-screen-C7xmJsXG.js} +1 -1
- package/assets/{shield-check-AWXIQWep.js → shield-check-CdES_QdC.js} +1 -1
- package/assets/{suggested-vips-DxCcVYyq.js → suggested-vips-BQoY6-Yl.js} +1 -1
- package/assets/{useDebouncedValue-DY8PZXql.js → useDebouncedValue-Ck8McJvG.js} +1 -1
- package/assets/{useFilters-BmXXLu1U.js → useFilters-DMt8Gx-P.js} +1 -1
- package/assets/{useLabels-CnYv6kWo.js → useLabels-oSXOt6KZ.js} +1 -1
- package/assets/{useSignature-BZ6jdf71.js → useSignature-BQN3IL24.js} +1 -1
- package/index.html +1 -1
- package/package.json +1 -1
- package/assets/index-B9LE6IYn.js +0 -1
- package/assets/settings-Dr2CVHK2.js +0 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/rich-text-
|
|
2
|
-
import{R as W,c as em,r as l,a as _e,j as r,C as Qt,b as Ms,X as Nt,d as Q,B as ce,e as kt,S as Xt,f as Dt,g as Pt,L as hs,h as tm,i as sm,k as lc,l as hn,T as Lt,m as nm,u as or,n as Qn,o as cc,I as uc,F as za,p as dc,q as Ba,s as rm,A as Ua,D as am,t as pn,v as om,w as ir,O as im,M as lm,x as cm,y as fc,z as mc,E as hc,G as Ka,H as um,J as dm,K as fm,N as gn,P as mm,Q as hm,U as pm,V as gm,W as pc,Y as ps,Z as xm,_ as gc,$ as bm,a0 as vm,a1 as ym,a2 as wm,a3 as qa,a4 as Ha,a5 as Kt,a6 as xc,a7 as Sm,a8 as Wa,a9 as Cm,aa as km,ab as jm,ac as xa,ad as Nm,ae as Em,af as De,ag as Im,ah as Rm,ai as Tm,aj as Mm,ak as Am,al as Om,am as li,an as Dm,ao as Pm,ap as Lm,aq as Va,ar as bc,as as vc,at as Jt,au as Ye,av as it,aw as Qa,ax as Ve,ay as lr,az as Gn,aA as Fe,aB as Ls,aC as Ft,aD as yc,aE as wc,aF as Ga,aG as Ya,aH as Xa,aI as Yn,aJ as Sc,aK as we,aL as Ja,aM as Cc,aN as Ue,aO as Fm,aP as $m,aQ as cr,aR as ur,aS as $t,aT as nt,aU as _m,aV as zm,aW as ft,aX as kc,aY as ds,aZ as dr,a_ as Bm,a$ as Um,b0 as Km,b1 as fr,b2 as Za,b3 as eo,b4 as mr,b5 as Zt,b6 as qm,b7 as Hm,b8 as Wm,b9 as Vm,ba as Qm,bb as ba,bc as Gm,bd as jc,be as As,bf as to,bg as so,bh as Ym,bi as hr,bj as Xm,bk as Jm,bl as Nc,bm as no,bn as Zm,bo as ci,bp as eh,bq as th,br as sh,bs as nh,bt as ui,bu as qt,bv as va,bw as rh,bx as ah,by as oh,bz as Ec,bA as ih,bB as lh,bC as ch,bD as uh,bE as di,bF as dh,bG as fh,bH as mh,bI as hh,bJ as ro,bK as ya,bL as wa,bM as ph,bN as Ic,bO as gh,bP as Rc,bQ as xh,bR as ao,bS as bh,bT as vh,bU as yh,bV as wh,bW as Sh,bX as Ch,bY as kh,bZ as jh,b_ as Bt,b$ as At,c0 as Nh}from"./index-DAzmnDmQ.js";import{P as Eh}from"./pencil-BYhgO1mk.js";import{A as jt,M as pr,C as Ih}from"./avatar-no7z5maH.js";import{K as Is}from"./kbd-CJO6TTXi.js";import{S as xn,C as oo,R as Rh}from"./shield-check-AWXIQWep.js";import{M as Tc,a as Th}from"./account-form-helpers-BqRAFw9h.js";import{R as Mh,u as Ah}from"./useSignature-BZ6jdf71.js";import{u as gr}from"./useDebouncedValue-DY8PZXql.js";import{D as Mc,B as Oh,u as es,a as fi,b as mi,c as Dh,d as Ph,e as Lh,n as Fh,o as $h,f as _h,g as zh,S as Bh}from"./useFilters-BmXXLu1U.js";import{E as ts,f as Ac}from"./ErrorState-CoYNTNJq.js";import{f as Oc,a as gt,b as Dc,c as Gt,d as Xn,t as Uh}from"./format-CKZmh-Ru.js";import{P as hi,u as io,a as Pc,b as lo,f as co,C as Kh,M as ot,D as pi}from"./move-options-peU5H7WV.js";import{D as qh}from"./download-C4twhQsf.js";import{u as uo}from"./useLabels-CnYv6kWo.js";import{C as fo}from"./confirm-dialog-DPRgwpsP.js";import{C as Hh}from"./circle-check-BwajEOAH.js";function on(e){if(Wh())e.focus({preventScroll:!0});else{let t=Vh(e);e.focus(),Qh(t)}}let Rn=null;function Wh(){if(Rn==null){Rn=!1;try{document.createElement("div").focus({get preventScroll(){return Rn=!0,!0}})}catch{}}return Rn}function Vh(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 Qh(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const Wt=e=>e?.ownerDocument??document,Yt=e=>e&&"window"in e&&e.window===e?e:Wt(e).defaultView||window;function Gh(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function Yh(e){return Gh(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let Xh=!1;function Lc(){return Xh}function Ct(e,t){if(!Lc())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:Yh(s)?s=s.host:s=s.parentNode}return!1}function Je(e){if(Lc()&&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 Jh=typeof Element<"u"&&"checkVisibility"in Element.prototype;function Zh(e){const t=Yt(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}=Yt(e);let{display:i,visibility:c}=o(e);a=i!=="none"&&c!=="hidden"&&c!=="collapse"}return a}function ep(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 Fc(e,t){return Jh?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&Zh(e)&&ep(e,t)&&(!e.parentElement||Fc(e.parentElement,e))}const $c=["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"],tp=$c.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";$c.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function sp(e,t){return e.matches(tp)&&!np(e)&&(t?.skipVisibilityCheck||Fc(e))}function np(e){let t=e;for(;t!=null;){if(t instanceof Yt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const mo=typeof document<"u"?W.useLayoutEffect:()=>{};function rp(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function ap(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function op(e){for(;e&&!sp(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Yt(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=d=>{(Je(d)===s||n)&&d.stopImmediatePropagation()},o=d=>{(Je(d)===s||n)&&(d.stopImmediatePropagation(),!e&&!n&&(n=!0,on(s),u()))},i=d=>{(Je(d)===e||n)&&d.stopImmediatePropagation()},c=d=>{(Je(d)===e||n)&&(d.stopImmediatePropagation(),n||(n=!0,on(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",c,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",c,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function xr(e){if(typeof window>"u"||window.navigator==null)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(s=>e.test(s.brand))||e.test(window.navigator.userAgent)}function ho(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function ss(e){let t=null;return()=>(t==null&&(t=e()),t)}const Jn=ss(function(){return ho(/^Mac/i)}),ip=ss(function(){return ho(/^iPhone/i)}),_c=ss(function(){return ho(/^iPad/i)||Jn()&&navigator.maxTouchPoints>1}),zc=ss(function(){return ip()||_c()}),lp=ss(function(){return xr(/AppleWebKit/i)&&!cp()}),cp=ss(function(){return xr(/Chrome/i)}),Bc=ss(function(){return xr(/Android/i)}),up=ss(function(){return xr(/Firefox/i)});function dp(e){return e.pointerType===""&&e.isTrusted?!0:Bc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function fp(e){return!Bc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function ln(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;up()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Jn()?n=!0:a=!0);let c=lp()&&Jn()&&!_c()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});ln.isOpening=s,on(e),e.dispatchEvent(c),ln.isOpening=!1}ln.isOpening=!1;let Ht=new Map,Sa=new Set;function gi(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=Je(n);if(!e(n)||!a)return;let o=Ht.get(a);o||(o=new Set,Ht.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=Je(n);if(!e(n)||!a)return;let o=Ht.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),Ht.delete(a)),Ht.size===0)){for(let i of Sa)i();Sa.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?gi():document.addEventListener("DOMContentLoaded",gi));function mp(){for(const[e]of Ht)"isConnected"in e&&!e.isConnected&&Ht.delete(e)}function hp(e){requestAnimationFrame(()=>{mp(),Ht.size===0?e():Sa.add(e)})}function Uc(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let Ca=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{Ca.delete(e)});function pp(e,t){if(e===t)return e;let s=Ca.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=Ca.get(t);return n?(n.forEach(a=>a.current=e),e):t}function gp(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=xi(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():xi(e[o],null)})}}}function xi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Fs(...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]=Uc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=em(o,i):a==="id"&&o&&i?t.id=pp(o,i):a==="ref"&&o&&i?t.ref=gp(o,i):t[a]=i!==void 0?i:o}}return t}function xp(e,t){mo(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const bp=W.useInsertionEffect??mo;function Hr(e){const t=l.useRef(null);return bp(()=>{t.current=e},[e]),l.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let Es="default",ka="",Un=new WeakMap;function vp(e){if(zc()){if(Es==="default"){const t=Wt(e);ka=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}Es="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Un.set(e,e.style[t]),e.style[t]="none"}}function bi(e){if(zc()){if(Es!=="disabled")return;Es="restoring",setTimeout(()=>{hp(()=>{if(Es==="restoring"){const t=Wt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=ka||""),ka="",Es="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Un.has(e)){let t=Un.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Un.delete(e)}}function vi(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Wr=new WeakMap;function yp(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return vi(t);if(Wr.has(t))return Wr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof Yt(s).HTMLMetaElement&&(s.nonce||s.content)||vi(t)||void 0;return n!==void 0&&Wr.set(t,n),n}const Kc=W.createContext({register:()=>{}});Kc.displayName="PressResponderContext";function qc(){let e=l.useRef(new Map),t=l.useCallback((a,o,i,c)=>{let u=c?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:c}),a.addEventListener(o,u,c)},[]),s=l.useCallback((a,o,i,c)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,c),e.current.delete(i)},[]),n=l.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return l.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function wp(e){let t=l.useContext(Kc);if(t){let{register:s,ref:n,...a}=t;e=Fs(a,e),s()}return xp(t,e.ref),e}class Tn{#s;constructor(t,s,n,a){this.#s=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let c,u=0,m,d=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,d=n.clientY),i&&(m!=null&&d!=null?(c=m-i.left,u=d-i.top):(c=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=n.currentTarget,this.shiftKey=n.shiftKey,this.metaKey=n.metaKey,this.ctrlKey=n.ctrlKey,this.altKey=n.altKey,this.x=c,this.y=u,this.key=n.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const yi=Symbol("linkClicked"),wi="react-aria-pressable-style",Si="data-react-aria-pressable";function Sp(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:c,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:f,ref:h,...v}=wp(e),[x,p]=l.useState(!1),b=l.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:y,removeAllGlobalListeners:S}=qc(),g=l.useCallback((j,I)=>{let D=b.current;if(c||D.didFirePressStart)return!1;let T=!0;if(D.isTriggeringEvent=!0,n){let F=new Tn("pressstart",I,j);n(F),T=F.shouldStopPropagation}return s&&s(!0),D.isTriggeringEvent=!1,D.didFirePressStart=!0,p(!0),T},[c,n,s]),w=l.useCallback((j,I,D=!0)=>{let T=b.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let F=!0;if(a){let N=new Tn("pressend",I,j);a(N),F=N.shouldStopPropagation}if(s&&s(!1),p(!1),t&&D&&!c){let N=new Tn("press",I,j);t(N),F&&=N.shouldStopPropagation}return T.isTriggeringEvent=!1,F},[c,a,s,t]),C=Hr(w),R=l.useCallback((j,I)=>{let D=b.current;if(c)return!1;if(o){D.isTriggeringEvent=!0;let T=new Tn("pressup",I,j);return o(T),D.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[c,o]),O=Hr(R),k=l.useCallback(j=>{let I=b.current;if(I.isPressed&&I.target){I.didFirePressStart&&I.pointerType!=null&&w(os(I.target,j),I.pointerType,!1),I.isPressed=!1,I.isOverTarget=!1,I.activePointerId=null,I.pointerType=null,S(),f||bi(I.target);for(let D of I.disposables)D();I.disposables=[]}},[f,S,w]),M=Hr(k);l.useEffect(()=>{c&&b.current.isPressed&&M({currentTarget:b.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[c]);let P=l.useCallback(j=>{d&&k(j)},[d,k]),E=l.useCallback(j=>{c||i?.(j)},[c,i]),L=l.useCallback((j,I)=>{if(!c&&i){let D=new MouseEvent("click",j);ap(D,I),i(rp(D))}},[c,i]),A=l.useMemo(()=>{let j=b.current,I={onKeyDown(T){if(Vr(T.nativeEvent,T.currentTarget)&&Ct(T.currentTarget,Je(T))){Ci(Je(T),T.key)&&T.preventDefault();let F=!0;!j.isPressed&&!T.repeat&&(j.target=T.currentTarget,j.isPressed=!0,j.pointerType="keyboard",F=g(T,"keyboard"));let N=T.currentTarget,V=J=>{Vr(J,N)&&!J.repeat&&Ct(N,Je(J))&&j.target&&O(os(j.target,J),"keyboard")};y(Wt(T.currentTarget),"keyup",Uc(V,D),!0),F&&T.stopPropagation(),T.metaKey&&Jn()&&j.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(j.metaKeyEvents=new Map)},onClick(T){if(!(T&&!Ct(T.currentTarget,Je(T)))&&T&&T.button===0&&!j.isTriggeringEvent&&!ln.isOpening){let F=!0;if(c&&T.preventDefault(),!j.ignoreEmulatedMouseEvents&&!j.isPressed&&(j.pointerType==="virtual"||dp(T.nativeEvent))){let N=g(T,"virtual"),V=O(T,"virtual"),J=C(T,"virtual");E(T),F=N&&V&&J}else if(j.isPressed&&j.pointerType!=="keyboard"){let N=j.pointerType||T.nativeEvent.pointerType||"virtual",V=O(os(T.currentTarget,T),N),J=C(os(T.currentTarget,T),N,!0);F=V&&J,j.isOverTarget=!1,E(T),M(T)}j.ignoreEmulatedMouseEvents=!1,F&&T.stopPropagation()}}},D=T=>{if(j.isPressed&&j.target&&Vr(T,j.target)){Ci(Je(T),T.key)&&T.preventDefault();let F=Je(T),N=Ct(j.target,F);C(os(j.target,T),"keyboard",N),N&&L(T,j.target),S(),T.key!=="Enter"&&po(j.target)&&Ct(j.target,F)&&!T[yi]&&(T[yi]=!0,ln(j.target,T,!1)),j.isPressed=!1,j.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&j.metaKeyEvents?.size){let F=j.metaKeyEvents;j.metaKeyEvents=void 0;for(let N of F.values())j.target?.dispatchEvent(new KeyboardEvent("keyup",N))}};if(typeof PointerEvent<"u"){I.onPointerDown=N=>{if(N.button!==0||!Ct(N.currentTarget,Je(N)))return;if(fp(N.nativeEvent)){j.pointerType="virtual";return}j.pointerType=N.pointerType;let V=!0;if(!j.isPressed){j.isPressed=!0,j.isOverTarget=!0,j.activePointerId=N.pointerId,j.target=N.currentTarget,f||vp(j.target),V=g(N,j.pointerType);let J=Je(N);"releasePointerCapture"in J&&("hasPointerCapture"in J?J.hasPointerCapture(N.pointerId)&&J.releasePointerCapture(N.pointerId):J.releasePointerCapture(N.pointerId)),y(Wt(N.currentTarget),"pointerup",T,!1),y(Wt(N.currentTarget),"pointercancel",F,!1)}V&&N.stopPropagation()},I.onMouseDown=N=>{if(Ct(N.currentTarget,Je(N))&&N.button===0){if(m){let V=op(N.target);V&&j.disposables.push(V)}N.stopPropagation()}},I.onPointerUp=N=>{!Ct(N.currentTarget,Je(N))||j.pointerType==="virtual"||N.button===0&&!j.isPressed&&O(N,j.pointerType||N.pointerType)},I.onPointerEnter=N=>{N.pointerId===j.activePointerId&&j.target&&!j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!0,g(os(j.target,N),j.pointerType))},I.onPointerLeave=N=>{N.pointerId===j.activePointerId&&j.target&&j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!1,C(os(j.target,N),j.pointerType,!1),P(N))};let T=N=>{if(N.pointerId===j.activePointerId&&j.isPressed&&N.button===0&&j.target){if(Ct(j.target,Je(N))&&j.pointerType!=null){let V=!1,J=setTimeout(()=>{j.isPressed&&j.target instanceof HTMLElement&&(V?M(N):(on(j.target),j.target.click()))},80);y(N.currentTarget,"click",()=>V=!0,!0),j.disposables.push(()=>clearTimeout(J))}else M(N);j.isOverTarget=!1}},F=N=>{M(N)};I.onDragStart=N=>{Ct(N.currentTarget,Je(N))&&M(N)}}return I},[y,c,m,S,f,P,g,E,L]);return l.useEffect(()=>{if(!h)return;const j=Wt(h.current);if(!j||!j.head||j.getElementById(wi))return;const I=j.createElement("style");I.id=wi;let D=yp(j);D&&(I.nonce=D),I.textContent=`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/rich-text-CoTs3nIc.js","assets/index-xOALrEh8.js","assets/index-C2fo0j9f.css","assets/confirm-dialog-F7nDmx5t.js","assets/pencil-CZK87pI9.js","assets/avatar-Ci3CMhdo.js","assets/kbd-C00o9L4B.js","assets/shield-check-CdES_QdC.js","assets/account-form-helpers-BHUowns0.js","assets/useSignature-BQN3IL24.js","assets/useDebouncedValue-Ck8McJvG.js","assets/useFilters-DMt8Gx-P.js","assets/ErrorState-DiX_zNTK.js","assets/format-CKZmh-Ru.js","assets/move-options-B2c-WWEl.js","assets/download-Bg6cLSAV.js","assets/useLabels-oSXOt6KZ.js","assets/circle-check-BM6iE_RP.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{R as W,c as em,r as l,a as _e,j as r,C as Qt,b as Ms,X as Nt,d as Q,B as ce,e as kt,S as Xt,f as Dt,g as Pt,L as hs,h as tm,i as sm,k as lc,l as hn,T as Lt,m as nm,u as or,n as Qn,o as cc,I as uc,F as za,p as dc,q as Ba,s as rm,A as Ua,D as am,t as pn,v as om,w as ir,O as im,M as lm,x as cm,y as fc,z as mc,E as hc,G as Ka,H as um,J as dm,K as fm,N as gn,P as mm,Q as hm,U as pm,V as gm,W as pc,Y as ps,Z as xm,_ as gc,$ as bm,a0 as vm,a1 as ym,a2 as wm,a3 as qa,a4 as Ha,a5 as Kt,a6 as xc,a7 as Sm,a8 as Wa,a9 as Cm,aa as km,ab as jm,ac as xa,ad as Nm,ae as Em,af as De,ag as Im,ah as Rm,ai as Tm,aj as Mm,ak as Am,al as Om,am as li,an as Dm,ao as Pm,ap as Lm,aq as Va,ar as bc,as as vc,at as Jt,au as Ye,av as it,aw as Qa,ax as Ve,ay as lr,az as Gn,aA as Fe,aB as Ls,aC as Ft,aD as yc,aE as wc,aF as Ga,aG as Ya,aH as Xa,aI as Yn,aJ as Sc,aK as we,aL as Ja,aM as Cc,aN as Ue,aO as Fm,aP as $m,aQ as cr,aR as ur,aS as $t,aT as nt,aU as _m,aV as zm,aW as ft,aX as kc,aY as ds,aZ as dr,a_ as Bm,a$ as Um,b0 as Km,b1 as fr,b2 as Za,b3 as eo,b4 as mr,b5 as Zt,b6 as qm,b7 as Hm,b8 as Wm,b9 as Vm,ba as Qm,bb as ba,bc as Gm,bd as jc,be as As,bf as to,bg as so,bh as Ym,bi as hr,bj as Xm,bk as Jm,bl as Nc,bm as no,bn as Zm,bo as ci,bp as eh,bq as th,br as sh,bs as nh,bt as ui,bu as rh,bv as ah,bw as oh,bx as va,by as ih,bz as lh,bA as ch,bB as Ec,bC as uh,bD as dh,bE as fh,bF as mh,bG as di,bH as hh,bI as ph,bJ as gh,bK as xh,bL as ro,bM as ya,bN as wa,bO as bh,bP as Ic,bQ as vh,bR as Rc,bS as yh,bT as ao,bU as wh,bV as Sh,bW as Ch,bX as kh,bY as jh,bZ as Nh,b_ as Eh,b$ as Ih,c0 as Bt,c1 as At,c2 as Rh}from"./index-xOALrEh8.js";import{P as Th}from"./pencil-CZK87pI9.js";import{A as jt,M as pr,C as Mh}from"./avatar-Ci3CMhdo.js";import{K as Is}from"./kbd-C00o9L4B.js";import{S as xn,C as oo,R as Ah}from"./shield-check-CdES_QdC.js";import{M as Tc,a as Oh}from"./account-form-helpers-BHUowns0.js";import{R as Dh,u as Ph}from"./useSignature-BQN3IL24.js";import{u as gr}from"./useDebouncedValue-Ck8McJvG.js";import{D as Mc,B as Lh,u as es,a as fi,b as mi,c as Fh,d as $h,e as _h,n as zh,o as Bh,f as Uh,g as Kh,S as qh}from"./useFilters-DMt8Gx-P.js";import{E as ts,f as Ac}from"./ErrorState-DiX_zNTK.js";import{f as Oc,a as gt,b as Dc,c as Gt,d as Xn,t as Hh}from"./format-CKZmh-Ru.js";import{P as hi,u as io,a as Pc,b as lo,f as co,C as Wh,M as ot,D as pi}from"./move-options-B2c-WWEl.js";import{D as Vh}from"./download-Bg6cLSAV.js";import{u as uo}from"./useLabels-oSXOt6KZ.js";import{C as fo}from"./confirm-dialog-F7nDmx5t.js";import{C as Qh}from"./circle-check-BM6iE_RP.js";function on(e){if(Gh())e.focus({preventScroll:!0});else{let t=Yh(e);e.focus(),Xh(t)}}let Rn=null;function Gh(){if(Rn==null){Rn=!1;try{document.createElement("div").focus({get preventScroll(){return Rn=!0,!0}})}catch{}}return Rn}function Yh(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 Xh(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const Wt=e=>e?.ownerDocument??document,Yt=e=>e&&"window"in e&&e.window===e?e:Wt(e).defaultView||window;function Jh(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function Zh(e){return Jh(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let ep=!1;function Lc(){return ep}function Ct(e,t){if(!Lc())return t&&e?e.contains(t):!1;if(!e||!t)return!1;let s=t;for(;s!==null;){if(s===e)return!0;s.tagName==="SLOT"&&s.assignedSlot?s=s.assignedSlot.parentNode:Zh(s)?s=s.host:s=s.parentNode}return!1}function Je(e){if(Lc()&&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 tp=typeof Element<"u"&&"checkVisibility"in Element.prototype;function sp(e){const t=Yt(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}=Yt(e);let{display:i,visibility:c}=o(e);a=i!=="none"&&c!=="hidden"&&c!=="collapse"}return a}function np(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 Fc(e,t){return tp?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&sp(e)&&np(e,t)&&(!e.parentElement||Fc(e.parentElement,e))}const $c=["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"],rp=$c.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";$c.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function ap(e,t){return e.matches(rp)&&!op(e)&&(t?.skipVisibilityCheck||Fc(e))}function op(e){let t=e;for(;t!=null;){if(t instanceof Yt(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const mo=typeof document<"u"?W.useLayoutEffect:()=>{};function ip(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function lp(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function cp(e){for(;e&&!ap(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Yt(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=d=>{(Je(d)===s||n)&&d.stopImmediatePropagation()},o=d=>{(Je(d)===s||n)&&(d.stopImmediatePropagation(),!e&&!n&&(n=!0,on(s),u()))},i=d=>{(Je(d)===e||n)&&d.stopImmediatePropagation()},c=d=>{(Je(d)===e||n)&&(d.stopImmediatePropagation(),n||(n=!0,on(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",c,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",c,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function xr(e){if(typeof window>"u"||window.navigator==null)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(s=>e.test(s.brand))||e.test(window.navigator.userAgent)}function ho(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function ss(e){let t=null;return()=>(t==null&&(t=e()),t)}const Jn=ss(function(){return ho(/^Mac/i)}),up=ss(function(){return ho(/^iPhone/i)}),_c=ss(function(){return ho(/^iPad/i)||Jn()&&navigator.maxTouchPoints>1}),zc=ss(function(){return up()||_c()}),dp=ss(function(){return xr(/AppleWebKit/i)&&!fp()}),fp=ss(function(){return xr(/Chrome/i)}),Bc=ss(function(){return xr(/Android/i)}),mp=ss(function(){return xr(/Firefox/i)});function hp(e){return e.pointerType===""&&e.isTrusted?!0:Bc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function pp(e){return!Bc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function ln(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;mp()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Jn()?n=!0:a=!0);let c=dp()&&Jn()&&!_c()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});ln.isOpening=s,on(e),e.dispatchEvent(c),ln.isOpening=!1}ln.isOpening=!1;let qt=new Map,Sa=new Set;function gi(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=Je(n);if(!e(n)||!a)return;let o=qt.get(a);o||(o=new Set,qt.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=Je(n);if(!e(n)||!a)return;let o=qt.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),qt.delete(a)),qt.size===0)){for(let i of Sa)i();Sa.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?gi():document.addEventListener("DOMContentLoaded",gi));function gp(){for(const[e]of qt)"isConnected"in e&&!e.isConnected&&qt.delete(e)}function xp(e){requestAnimationFrame(()=>{gp(),qt.size===0?e():Sa.add(e)})}function Uc(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let Ca=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{Ca.delete(e)});function bp(e,t){if(e===t)return e;let s=Ca.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=Ca.get(t);return n?(n.forEach(a=>a.current=e),e):t}function vp(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=xi(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():xi(e[o],null)})}}}function xi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Fs(...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]=Uc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=em(o,i):a==="id"&&o&&i?t.id=bp(o,i):a==="ref"&&o&&i?t.ref=vp(o,i):t[a]=i!==void 0?i:o}}return t}function yp(e,t){mo(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const wp=W.useInsertionEffect??mo;function Hr(e){const t=l.useRef(null);return wp(()=>{t.current=e},[e]),l.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let Es="default",ka="",Un=new WeakMap;function Sp(e){if(zc()){if(Es==="default"){const t=Wt(e);ka=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}Es="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Un.set(e,e.style[t]),e.style[t]="none"}}function bi(e){if(zc()){if(Es!=="disabled")return;Es="restoring",setTimeout(()=>{xp(()=>{if(Es==="restoring"){const t=Wt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=ka||""),ka="",Es="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Un.has(e)){let t=Un.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Un.delete(e)}}function vi(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Wr=new WeakMap;function Cp(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return vi(t);if(Wr.has(t))return Wr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof Yt(s).HTMLMetaElement&&(s.nonce||s.content)||vi(t)||void 0;return n!==void 0&&Wr.set(t,n),n}const Kc=W.createContext({register:()=>{}});Kc.displayName="PressResponderContext";function qc(){let e=l.useRef(new Map),t=l.useCallback((a,o,i,c)=>{let u=c?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:c}),a.addEventListener(o,u,c)},[]),s=l.useCallback((a,o,i,c)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,c),e.current.delete(i)},[]),n=l.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return l.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function kp(e){let t=l.useContext(Kc);if(t){let{register:s,ref:n,...a}=t;e=Fs(a,e),s()}return yp(t,e.ref),e}class Tn{#s;constructor(t,s,n,a){this.#s=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let c,u=0,m,d=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,d=n.clientY),i&&(m!=null&&d!=null?(c=m-i.left,u=d-i.top):(c=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=n.currentTarget,this.shiftKey=n.shiftKey,this.metaKey=n.metaKey,this.ctrlKey=n.ctrlKey,this.altKey=n.altKey,this.x=c,this.y=u,this.key=n.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const yi=Symbol("linkClicked"),wi="react-aria-pressable-style",Si="data-react-aria-pressable";function jp(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:c,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:f,ref:h,...v}=kp(e),[x,p]=l.useState(!1),b=l.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:y,removeAllGlobalListeners:S}=qc(),g=l.useCallback((j,I)=>{let D=b.current;if(c||D.didFirePressStart)return!1;let T=!0;if(D.isTriggeringEvent=!0,n){let F=new Tn("pressstart",I,j);n(F),T=F.shouldStopPropagation}return s&&s(!0),D.isTriggeringEvent=!1,D.didFirePressStart=!0,p(!0),T},[c,n,s]),w=l.useCallback((j,I,D=!0)=>{let T=b.current;if(!T.didFirePressStart)return!1;T.didFirePressStart=!1,T.isTriggeringEvent=!0;let F=!0;if(a){let N=new Tn("pressend",I,j);a(N),F=N.shouldStopPropagation}if(s&&s(!1),p(!1),t&&D&&!c){let N=new Tn("press",I,j);t(N),F&&=N.shouldStopPropagation}return T.isTriggeringEvent=!1,F},[c,a,s,t]),C=Hr(w),R=l.useCallback((j,I)=>{let D=b.current;if(c)return!1;if(o){D.isTriggeringEvent=!0;let T=new Tn("pressup",I,j);return o(T),D.isTriggeringEvent=!1,T.shouldStopPropagation}return!0},[c,o]),O=Hr(R),k=l.useCallback(j=>{let I=b.current;if(I.isPressed&&I.target){I.didFirePressStart&&I.pointerType!=null&&w(os(I.target,j),I.pointerType,!1),I.isPressed=!1,I.isOverTarget=!1,I.activePointerId=null,I.pointerType=null,S(),f||bi(I.target);for(let D of I.disposables)D();I.disposables=[]}},[f,S,w]),M=Hr(k);l.useEffect(()=>{c&&b.current.isPressed&&M({currentTarget:b.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[c]);let P=l.useCallback(j=>{d&&k(j)},[d,k]),E=l.useCallback(j=>{c||i?.(j)},[c,i]),L=l.useCallback((j,I)=>{if(!c&&i){let D=new MouseEvent("click",j);lp(D,I),i(ip(D))}},[c,i]),A=l.useMemo(()=>{let j=b.current,I={onKeyDown(T){if(Vr(T.nativeEvent,T.currentTarget)&&Ct(T.currentTarget,Je(T))){Ci(Je(T),T.key)&&T.preventDefault();let F=!0;!j.isPressed&&!T.repeat&&(j.target=T.currentTarget,j.isPressed=!0,j.pointerType="keyboard",F=g(T,"keyboard"));let N=T.currentTarget,V=J=>{Vr(J,N)&&!J.repeat&&Ct(N,Je(J))&&j.target&&O(os(j.target,J),"keyboard")};y(Wt(T.currentTarget),"keyup",Uc(V,D),!0),F&&T.stopPropagation(),T.metaKey&&Jn()&&j.metaKeyEvents?.set(T.key,T.nativeEvent)}else T.key==="Meta"&&(j.metaKeyEvents=new Map)},onClick(T){if(!(T&&!Ct(T.currentTarget,Je(T)))&&T&&T.button===0&&!j.isTriggeringEvent&&!ln.isOpening){let F=!0;if(c&&T.preventDefault(),!j.ignoreEmulatedMouseEvents&&!j.isPressed&&(j.pointerType==="virtual"||hp(T.nativeEvent))){let N=g(T,"virtual"),V=O(T,"virtual"),J=C(T,"virtual");E(T),F=N&&V&&J}else if(j.isPressed&&j.pointerType!=="keyboard"){let N=j.pointerType||T.nativeEvent.pointerType||"virtual",V=O(os(T.currentTarget,T),N),J=C(os(T.currentTarget,T),N,!0);F=V&&J,j.isOverTarget=!1,E(T),M(T)}j.ignoreEmulatedMouseEvents=!1,F&&T.stopPropagation()}}},D=T=>{if(j.isPressed&&j.target&&Vr(T,j.target)){Ci(Je(T),T.key)&&T.preventDefault();let F=Je(T),N=Ct(j.target,F);C(os(j.target,T),"keyboard",N),N&&L(T,j.target),S(),T.key!=="Enter"&&po(j.target)&&Ct(j.target,F)&&!T[yi]&&(T[yi]=!0,ln(j.target,T,!1)),j.isPressed=!1,j.metaKeyEvents?.delete(T.key)}else if(T.key==="Meta"&&j.metaKeyEvents?.size){let F=j.metaKeyEvents;j.metaKeyEvents=void 0;for(let N of F.values())j.target?.dispatchEvent(new KeyboardEvent("keyup",N))}};if(typeof PointerEvent<"u"){I.onPointerDown=N=>{if(N.button!==0||!Ct(N.currentTarget,Je(N)))return;if(pp(N.nativeEvent)){j.pointerType="virtual";return}j.pointerType=N.pointerType;let V=!0;if(!j.isPressed){j.isPressed=!0,j.isOverTarget=!0,j.activePointerId=N.pointerId,j.target=N.currentTarget,f||Sp(j.target),V=g(N,j.pointerType);let J=Je(N);"releasePointerCapture"in J&&("hasPointerCapture"in J?J.hasPointerCapture(N.pointerId)&&J.releasePointerCapture(N.pointerId):J.releasePointerCapture(N.pointerId)),y(Wt(N.currentTarget),"pointerup",T,!1),y(Wt(N.currentTarget),"pointercancel",F,!1)}V&&N.stopPropagation()},I.onMouseDown=N=>{if(Ct(N.currentTarget,Je(N))&&N.button===0){if(m){let V=cp(N.target);V&&j.disposables.push(V)}N.stopPropagation()}},I.onPointerUp=N=>{!Ct(N.currentTarget,Je(N))||j.pointerType==="virtual"||N.button===0&&!j.isPressed&&O(N,j.pointerType||N.pointerType)},I.onPointerEnter=N=>{N.pointerId===j.activePointerId&&j.target&&!j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!0,g(os(j.target,N),j.pointerType))},I.onPointerLeave=N=>{N.pointerId===j.activePointerId&&j.target&&j.isOverTarget&&j.pointerType!=null&&(j.isOverTarget=!1,C(os(j.target,N),j.pointerType,!1),P(N))};let T=N=>{if(N.pointerId===j.activePointerId&&j.isPressed&&N.button===0&&j.target){if(Ct(j.target,Je(N))&&j.pointerType!=null){let V=!1,J=setTimeout(()=>{j.isPressed&&j.target instanceof HTMLElement&&(V?M(N):(on(j.target),j.target.click()))},80);y(N.currentTarget,"click",()=>V=!0,!0),j.disposables.push(()=>clearTimeout(J))}else M(N);j.isOverTarget=!1}},F=N=>{M(N)};I.onDragStart=N=>{Ct(N.currentTarget,Je(N))&&M(N)}}return I},[y,c,m,S,f,P,g,E,L]);return l.useEffect(()=>{if(!h)return;const j=Wt(h.current);if(!j||!j.head||j.getElementById(wi))return;const I=j.createElement("style");I.id=wi;let D=Cp(j);D&&(I.nonce=D),I.textContent=`
|
|
3
3
|
@layer {
|
|
4
4
|
[${Si}] {
|
|
5
5
|
touch-action: pan-x pan-y pinch-zoom;
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
|
-
`.trim(),j.head.prepend(I)},[h]),l.useEffect(()=>{let j=b.current;return()=>{f||bi(j.target??void 0);for(let I of j.disposables)I();j.disposables=[]}},[f]),{isPressed:u||x,pressProps:Fs(v,A,{[Si]:!0})}}function po(e){return e.tagName==="A"&&e.hasAttribute("href")}function Vr(e,t){const{key:s,code:n}=e,a=t,o=a.getAttribute("role");return(s==="Enter"||s===" "||s==="Spacebar"||n==="Space")&&!(a instanceof Yt(a).HTMLInputElement&&!Hc(a,s)||a instanceof Yt(a).HTMLTextAreaElement||a.isContentEditable)&&!((o==="link"||!o&&po(a))&&s!=="Enter")}function os(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 Cp(e){return e instanceof HTMLInputElement?!1:e instanceof HTMLButtonElement?e.type!=="submit"&&e.type!=="reset":!po(e)}function Ci(e,t){return e instanceof HTMLInputElement?!Hc(e,t):Cp(e)}const kp=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function Hc(e,t){return e.type==="checkbox"||e.type==="radio"?t===" ":kp.has(e.type)}let jp=0;const Qr=new Map;function Np(e){let[t,s]=l.useState();return mo(()=>{if(!e)return;let n=Qr.get(e);if(n)s(n.element.id);else{let a=`react-aria-description-${jp++}`;s(a);let o=document.createElement("div");o.id=a,o.style.display="none",o.textContent=e,document.body.appendChild(o),n={refCount:0,element:o},Qr.set(e,n)}return n.refCount++,()=>{n&&--n.refCount===0&&(n.element.remove(),Qr.delete(e))}},[e]),{"aria-describedby":e?t:void 0}}const Ep=500;function Ip(e){let{isDisabled:t,onLongPressStart:s,onLongPressEnd:n,onLongPress:a,threshold:o=Ep,accessibilityDescription:i}=e;const c=l.useRef(void 0);let{addGlobalListener:u,removeGlobalListener:m}=qc(),{pressProps:d}=Sp({isDisabled:t,onPressStart(h){if(h.continuePropagation(),(h.pointerType==="mouse"||h.pointerType==="touch")&&(s&&s({...h,type:"longpressstart"}),c.current=setTimeout(()=>{h.target.dispatchEvent(new PointerEvent("pointercancel",{bubbles:!0})),Wt(h.target).activeElement!==h.target&&on(h.target),a&&a({...h,type:"longpress"}),c.current=void 0},o),h.pointerType==="touch")){let v=p=>{p.preventDefault()},x=Yt(h.target);u(h.target,"contextmenu",v,{once:!0}),u(x,"pointerup",()=>{setTimeout(()=>{m(h.target,"contextmenu",v)},30)},{once:!0})}},onPressEnd(h){c.current&&clearTimeout(c.current),n&&(h.pointerType==="mouse"||h.pointerType==="touch")&&n({...h,type:"longpressend"})}}),f=Np(a&&!t?i:void 0);return{longPressProps:Fs(d,f)}}const br=_e("BadgeCheck",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Wc=_e("BellOff",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]]);const Rp=_e("BookmarkPlus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"12",x2:"12",y1:"7",y2:"13",key:"1cppfj"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);const Vc=_e("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]);const go=_e("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);const Qc=_e("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);const Gc=_e("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);const Yc=_e("Forward",[["polyline",{points:"15 17 20 12 15 7",key:"1w3sku"}],["path",{d:"M4 18v-2a4 4 0 0 1 4-4h12",key:"jmiej9"}]]);const Xc=_e("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);const Tp=_e("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);const vr=_e("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);const Mp=_e("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);const Ap=_e("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const yr=_e("Paperclip",[["path",{d:"M13.234 20.252 21 12.3",key:"1cbrk9"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486",key:"1pkts6"}]]);const xo=_e("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);const Jc=_e("ReplyAll",[["polyline",{points:"7 17 2 12 7 7",key:"t83bqg"}],["polyline",{points:"12 17 7 12 12 7",key:"1g4ajm"}],["path",{d:"M22 18v-2a4 4 0 0 0-4-4H7",key:"1fcyog"}]]);const Zc=_e("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);const eu=_e("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const $s=_e("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);const Op=_e("ShieldQuestion",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const Dp=_e("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);const Pp=_e("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);const Lp=_e("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]),Fp=({address:e,showTrustedBadge:t=!1})=>{const s=t?r.jsx(br,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}):null;return e.displayName?r.jsxs("span",{children:[r.jsx("span",{className:"text-fg",children:e.displayName}),r.jsxs("span",{className:"text-fg-muted",children:[" ","<",e.normalizedEmail,">"]}),s]}):r.jsxs("span",{className:"text-fg",children:[e.normalizedEmail,s]})},$p=({label:e,addresses:t,showTrustedBadge:s=!1})=>{const[n,a]=l.useState(!1);if(t.length===0)return null;const o=t.length>3,i=c=>{const u=s&&c.flags?.trusted?.value===!0;return r.jsx(Fp,{address:c,showTrustedBadge:u})};return r.jsxs("div",{className:"flex gap-2 text-sm",children:[r.jsxs("span",{className:"text-fg-muted shrink-0 w-12",children:[e,":"]}),r.jsx("div",{className:"flex-1 min-w-0",children:n?r.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((c,u)=>r.jsxs("span",{children:[i(c),u<t.length-1&&", "]},u))}):r.jsx("div",{className:"truncate",children:t.map((c,u)=>r.jsxs("span",{children:[i(c),u<t.length-1&&", "]},u))})}),o&&r.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),a(!n)},className:"shrink-0 text-fg-muted hover:text-fg transition-colors","aria-label":n?"Collapse":"Expand",children:n?r.jsx(Qt,{className:"h-4 w-4"}):r.jsx(Ms,{className:"h-4 w-4"})})]})},_p=({email:e,displayName:t,onRemove:s,className:n})=>r.jsxs("span",{className:Q("inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-accent-2-soft text-sm max-w-[200px]",n),children:[r.jsx("span",{className:"truncate",children:t||e}),r.jsx("button",{type:"button",onClick:s,className:"shrink-0 p-0.5 rounded-full hover:bg-fg-muted/20 transition-colors","aria-label":`Remove ${e}`,children:r.jsx(Nt,{className:"size-3"})})]}),zp={unknown:{label:"Unknown sender",tone:"neutral"},wellknown:{label:"Known sender",tone:"positive"},vip:{label:"VIP",tone:"accent"}};function ws({label:e,children:t,className:s}){return r.jsxs("section",{className:Q("border-b border-line px-row-inset py-3",s),children:[r.jsx("h3",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),r.jsx("div",{className:"mt-2",children:t})]})}function Bp({sender:e}){const t=zp[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(jt,{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(kt,{tone:"danger",dot:!0,children:"Address couldn't be verified"}):r.jsx(kt,{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 Up({auth:e,onShowSimilar:t}){if(e.verdict==="aligned")return r.jsxs("div",{className:"flex items-start gap-2 text-xs text-fg-muted",children:[r.jsx(xn,{className:"mt-0.5 size-3.5 shrink-0 text-positive"}),r.jsx("span",{children:e.summary})]});if(e.verdict==="caution")return r.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-warning/10 p-3 text-warning",children:[r.jsx(Op,{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($s,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm font-semibold text-danger",children:s}),r.jsx("p",{className:"mt-1 text-xs leading-relaxed text-fg",children:e.summary}),!e.addressUnreadable&&e.dkimDomain&&r.jsxs("p",{className:"mt-1 text-2xs text-fg-muted",children:["Sent from"," ",r.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.dkimDomain}),", claims to be"," ",r.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.fromDomain})]})]})]}),e.similarCount!=null&&e.similarCount>0&&r.jsxs(ce,{variant:"secondary",size:"sm",className:"mt-2 w-full border-danger/30 text-danger hover:bg-danger-soft",onClick:t,children:[e.similarCount," similar messages"]})]})}function Ws({icon:e,label:t,active:s,danger:n,onClick:a,pending:o}){const i=a===void 0||o===!0;return r.jsxs("button",{type:"button",onClick:a,disabled:i,className:Q("flex items-center gap-2 rounded-md border px-2 py-1 text-xs transition-colors",s?"border-accent-2 bg-accent-2-soft text-accent-2":"border-line text-fg-muted hover:border-line-strong hover:text-fg",n&&!s&&"text-danger hover:bg-danger-soft",i&&"cursor-not-allowed opacity-50 hover:border-line"),children:[e,t]})}const Kp={sender:"matched: sender",recipient:"matched: recipient",subject:"matched: subject",attachment:"matched: attachment",body:"matched: body",entities:"matched: entities"};function tu({data:e,onClose:t,onShowSimilar:s,actions:n,similarState:a="ready",similarLinkComponent:o,className:i,hideCloseButton:c=!1,reportSpamPending:u=!1,notSpamPending:m=!1}){const{sender:d,authenticity:f,category:h,flags:v={},similar:x}=e,p=f.verdict==="mismatch";return r.jsxs("aside",{className:Q("flex w-76 shrink-0 flex-col overflow-y-auto border-l border-line bg-surface",i),children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center justify-between border-b border-line px-row-inset",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"}),!c&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Nt,{className:"size-3.5"}),onClick:t,"aria-label":"Collapse intelligence sidebar"})]}),r.jsx(ws,{label:"Sender",children:r.jsx(Bp,{sender:d})}),r.jsx(ws,{label:"Authenticity",children:r.jsx(Up,{auth:f,onShowSimilar:s})}),r.jsx(ws,{label:"Category",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(kt,{tone:p?"danger":"neutral",children:h.value}),h.overridden&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"your override"}),r.jsx("button",{type:"button",className:Q("ml-auto text-2xs text-accent hover:underline",!n?.onReclassify&&"cursor-not-allowed opacity-50 hover:no-underline"),disabled:!n?.onReclassify,onClick:n?.onReclassify,children:"reclassify"})]})}),r.jsxs(ws,{label:"Quick actions",children:[r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[r.jsx(Ws,{icon:r.jsx(Xt,{className:"size-3.5"}),label:"VIP",active:v.vip,onClick:n?.onToggleVip}),r.jsx(Ws,{icon:r.jsx(Wc,{className:"size-3.5"}),label:"Mute",active:v.muted,onClick:n?.onToggleMute}),n?.onNotSpam&&r.jsx(Ws,{icon:r.jsx(Tp,{className:"size-3.5"}),label:m?"Undoing…":"Not spam",active:!0,onClick:n.onNotSpam,pending:m}),n?.onReportSpam&&r.jsx(Ws,{icon:r.jsx(Dp,{className:"size-3.5"}),label:u?"Reporting…":"Report spam",danger:!0,onClick:n.onReportSpam,pending:u}),r.jsx(Ws,{icon:r.jsx(Mp,{className:"size-3.5"}),label:"Unsubscribe",active:v.unsubscribed,onClick:n?.onToggleUnsubscribe})]}),n?.onNotSpam&&r.jsx("p",{className:"mt-1.5 text-2xs text-fg-subtle",children:"You reported this message as spam"})]}),(a!=="ready"||x.length>0)&&r.jsx(ws,{label:"Similar messages",children:a==="loading"?r.jsx("div",{className:"animate-pulse space-y-2",children:Array.from({length:3}).map((b,y)=>r.jsxs("div",{className:"space-y-1",children:[r.jsx("div",{className:"h-3 w-3/4 rounded bg-surface-sunken"}),r.jsx("div",{className:"h-2.5 w-1/2 rounded bg-surface-sunken"})]},y))}):a==="error"?r.jsx("p",{className:"text-xs text-fg-subtle",children:"Similarity search unavailable"}):r.jsx("ul",{className:"-mx-1 space-y-1",children:x.map(b=>{const y="block w-full rounded-md px-1 py-1 text-left hover:bg-surface-sunken",S=`Open message from ${b.fromName||"unknown sender"}: ${b.subject}`,g=r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[r.jsx("span",{className:"truncate text-xs font-medium text-fg",children:b.fromName}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:b.timeLabel})]}),r.jsx("div",{className:"truncate text-xs text-fg-muted",children:b.subject}),r.jsx("span",{className:"mt-1 inline-block rounded-full bg-surface-sunken px-1.5 py-px text-2xs text-fg-subtle",children:Kp[b.matched]})]});return r.jsx("li",{children:o?o({mailboxId:b.mailboxId,messageId:b.id,className:y,ariaLabel:S,children:g}):r.jsx("div",{className:y,children:g})},b.id)})})}),r.jsx(ws,{label:"Coming soon",className:"border-b-0 opacity-70",children:r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[r.jsx(Dt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Suggested actions"}),r.jsx("div",{className:"text-2xs text-fg-subtle",children:'"Create a filter for messages like this" — on-device model'})]})]}),r.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[r.jsx(Dt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Thread summary"}),r.jsx("div",{className:"text-2xs text-fg-subtle",children:"One-paragraph digest — Bedrock"})]})]})]})})]})}const bo=[{action:"focusNext",keys:["j","k"],label:"navigate"},{action:"muteSender",keys:["m"],label:"mute"},{action:"help",keys:["?"],label:"all shortcuts"}];function qp(e){return bo.filter(t=>e[t.action]!==void 0)}const su=[{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 Hp(e){for(const t of su){const s=t.hints.find(n=>n.action===e);if(s)return s.keys}}function nu(e){const t=Hp(e);return!t||t.length===0?"":t.length===1?t[0]??"":t[0]==="g"?t.join(" then "):t.join("")}function Vs(e){const t=nu(e);return t===""?"":`(${t})`}const Zn=e=>({shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey}),ki=e=>e.shiftKey||e.metaKey||e.ctrlKey,Wp=e=>e.shiftKey?"range":e.metaKey||e.ctrlKey?"toggle":"open",vo=(e,t)=>!t&&e>0,Vp=(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)},Qp=(e,t,s,n)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:n,Gp=(e,t)=>{const s=new Set(t),n=new Set;for(const a of e)s.has(a)&&n.add(a);return n},ru=(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]},au=e=>{const[t,s]=l.useState(()=>new Set(e?.initialSelectedIds)),[n,a]=l.useState(void 0),o=l.useCallback(p=>t.has(p),[t]),i=l.useCallback(p=>{a(p),s(b=>{const y=new Set(b);return y.has(p)?y.delete(p):y.add(p),y})},[]),c=l.useCallback(p=>{a(p),s(b=>{if(b.has(p))return b;const y=new Set(b);return y.add(p),y})},[]),u=l.useCallback(p=>{s(b=>{if(!b.has(p))return b;const y=new Set(b);return y.delete(p),y})},[]),m=l.useCallback(p=>{s(new Set(p))},[]),d=l.useCallback(()=>{a(void 0),s(new Set)},[]),f=l.useCallback(p=>{s(b=>p.every(S=>b.has(S))?new Set:new Set(p))},[]),h=l.useCallback(p=>{a(p)},[]),v=l.useCallback(p=>{s(b=>{if(b.size===0)return b;const y=Gp(b,p);return y.size===b.size?b:y})},[]),x=l.useCallback((p,b,y)=>{const S=Qp(p,n,y,b);s(g=>{const w=Vp(p,S,b);if(w.length===0)return g;const C=new Set(g);for(const R of w)C.add(R);return C}),a(S)},[n]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:c,deselect:u,selectAll:m,clearSelection:d,toggleAll:f,selectRange:x,setAnchor:h,anchorId:n,intersectWith:v}};function ou({hints:e=bo,className:t}){return e.length===0?null:r.jsx("footer",{className:Q("flex items-center gap-2 border-t border-line px-row-inset py-1 text-2xs text-fg-subtle",t),children:e.map(s=>r.jsx(Yp,{hint:s},s.label))})}function Yp({hint:e}){return r.jsxs("span",{className:"flex items-center gap-1",children:[e.keys.map(t=>r.jsx(Is,{children:t},t)),r.jsx("span",{children:e.label})]})}function Xp(){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 Jp({filter:e,scopeLabel:t,searchQuery:s}){const n=s?.trim();return e?r.jsxs(ji,{children:[r.jsx("p",{className:"font-medium text-fg",children:tg(e.label,t,n)}),r.jsx("p",{className:"mt-1 text-sm text-fg-muted",children:Zp[e.reach]}),r.jsx(ce,{variant:"secondary",size:"sm",className:"mt-4",onClick:e.onClear,children:"Clear filter"})]}):r.jsx(ji,{children:r.jsx("p",{className:"text-fg-muted",children:eg(n,t)})})}const Zp={"whole-folder":"Every message in this folder was checked.","loaded-pages":"Only the messages loaded so far were checked."};function eg(e,t){return e?"No messages match your search":t?`No messages in ${t}`:"No messages in this mailbox"}function tg(e,t,s){return s?`No results for “${s}” in ${e}`:t?`No ${e} mail in ${t}`:`No ${e} mail`}function ji({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 sg(){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(hs,{className:"size-4 animate-spin","aria-hidden":"true"}),r.jsx("span",{children:"Loading more…"})]})}function ng({message:e="Something went wrong loading this mailbox.",onRetry:t,onReport:s}){return r.jsx("div",{className:"flex h-full flex-1 items-center justify-center p-4",children:r.jsxs("div",{role:"alert",className:"flex max-w-sm flex-col items-center justify-center gap-3 text-center",children:[r.jsx(Pt,{className:"size-8 text-danger","aria-hidden":"true"}),r.jsxs("div",{children:[r.jsx("p",{className:"font-medium text-danger",children:"Couldn't load messages"}),r.jsx("p",{className:"mt-1 break-words text-sm text-fg-muted",children:e})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t&&r.jsx(ce,{variant:"secondary",size:"sm",onClick:t,children:"Retry"}),s&&r.jsx(ce,{variant:"ghost",size:"sm",onClick:s,children:"Report a problem"})]})]})})}const Qs={action:null,nextPrefix:null,preventDefault:!1},rg={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},ag={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 og(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=rg[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=ag[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 ig(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const iu="data-message-row",lg='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function cg(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(lg);return t?!t.hasAttribute(iu):!1}const lu="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",cu=({active:e,focused:t})=>Q("relative flex h-8 w-full items-center gap-2 px-row-inset text-left",lu,e?"bg-accent-2-soft":t?"bg-surface-sunken":"hover:bg-surface-sunken",t&&!e&&"before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-accent-2"),_s=({active:e,focused:t})=>Q("relative flex w-full items-start gap-3 py-2 pl-5 pr-row-inset text-left transition-colors",lu,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 uu({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($s,{className:"size-3.5 text-danger"}):e.starred?r.jsx(Xt,{className:"size-3 fill-warning text-warning"}):t?r.jsx("span",{className:"size-1.5 rounded-full bg-accent"}):null}),r.jsx("span",{className:Q("w-36 shrink-0 truncate text-xs",t?"font-semibold text-fg":"text-fg-muted"),children:e.fromName}),r.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs",children:[r.jsx("span",{className:Q(t?"font-medium text-fg":"text-fg-muted"),children:e.subject}),r.jsxs("span",{className:"text-fg-subtle",children:[" — ",e.snippet]})]}),e.hasAttachment&&r.jsx(yr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"}),r.jsx("span",{className:"w-11 shrink-0 text-right text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]})}function Ni(e,t){const s=t?.trim();if(!s)return e;const n=e.toLowerCase(),a=s.toLowerCase(),o=[];let i=0,c=n.indexOf(a,i),u=0;for(;c!==-1;)c>i&&o.push(e.slice(i,c)),o.push(r.jsx("mark",{className:"bg-transparent font-semibold text-fg",children:e.slice(c,c+a.length)},u++)),i=c+a.length,c=n.indexOf(a,i);return i<e.length&&o.push(e.slice(i)),o}function cn({thread:e,badge:t,highlightQuery:s}){const n=!e.isRead;return r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsxs("span",{className:"flex items-baseline justify-between gap-2",children:[r.jsxs("span",{className:Q("flex min-w-0 items-center gap-1.5 truncate text-sm",n?"font-semibold text-fg":"font-medium text-fg-muted"),children:[e.trust==="vip"&&r.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-accent-2"}),r.jsx("span",{className:"truncate",children:e.fromName}),e.messageCount!=null&&e.messageCount>1&&r.jsx("span",{className:"shrink-0 text-2xs font-normal text-fg-subtle",children:e.messageCount})]}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:Q("truncate text-sm",n?"text-fg":"text-fg-muted"),children:Ni(e.subject,s)}),e.suspicious&&r.jsx($s,{className:"size-3.5 shrink-0 text-danger"}),e.starred&&r.jsx(Xt,{className:"size-3 shrink-0 fill-warning text-warning"}),e.hasAttachment&&r.jsx(yr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"})]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"line-clamp-1 min-w-0 flex-1 text-xs text-fg-subtle",children:Ni(e.snippet,s)}),e.category&&e.category!=="personal"&&r.jsx(kt,{tone:tm[e.category],className:"shrink-0",children:e.category}),e.labels?.map(a=>r.jsx(sm,{label:a,className:"max-w-20"},a.labelId)),t]})]})}function ug({thread:e,selection:t}){if(!t)return r.jsx(jt,{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(jt,{name:e.fromName,email:e.fromEmail,size:"sm",className:Q("absolute inset-0 transition-opacity sm:group-hover:opacity-0",(s||n)&&"opacity-0")}),r.jsx("span",{role:"button",tabIndex:-1,onClick:t.onToggle,onKeyDown:a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),a.stopPropagation(),t.onToggle(a))},className:Q("absolute inset-0 size-7 items-center justify-center rounded-full border transition-opacity",n?"flex":"hidden sm:flex",s?"bg-accent border-accent text-accent-fg opacity-100":n?"border-fg-subtle/40 bg-canvas opacity-100":"border-fg-subtle/40 bg-canvas opacity-0 group-hover:opacity-100"),"aria-label":s?"Deselect message":"Select message",children:s&&r.jsx(hn,{className:"size-3"})})]})}function yo({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(ug,{thread:e,selection:t}),r.jsx(cn,{thread:e,badge:s,highlightQuery:n})]})}const du=e=>({...lc,[iu]:"","data-message-id":e.id});function dg({thread:e,active:t,focused:s,tabIndex:n,onClick:a}){return r.jsx("button",{type:"button",...du(e),tabIndex:n,onClick:a,className:cu({active:t,focused:s}),children:r.jsx(uu,{thread:e})})}function fg({thread:e,active:t,focused:s,tabIndex:n,selection:a,onClick:o}){return r.jsx("button",{type:"button",...du(e),tabIndex:n,onClick:o,className:Q("group",_s({active:t,focused:s})),children:r.jsx(yo,{thread:e,selection:a})})}let Rs;const mg=5e3;function fu(e){e.preventDefault(),er()}function er(){Rs!==void 0&&(clearTimeout(Rs),Rs=void 0,document.removeEventListener("contextmenu",fu,!0),document.removeEventListener("pointerup",er,!0))}function hg(){Rs===void 0?(document.addEventListener("contextmenu",fu,!0),document.addEventListener("pointerup",er,!0)):clearTimeout(Rs),Rs=setTimeout(er,mg)}function mu({onLongPress:e,isDisabled:t,delayMs:s=500,accessibilityDescription:n}){const{longPressProps:a}=Ip({isDisabled:t,threshold:s,accessibilityDescription:n,onLongPress:e}),o=l.useCallback(i=>{i.pointerType!=="touch"&&i.pointerType!=="pen"||hg()},[]);return{longPressProps:Fs(a,{onPointerDown:o})}}const fs=72,Ei=10,pg=fs/2,Ii="__swipeableRowAxisCancel";function Ri(e){return e==="leading"?fs:e==="trailing"?-fs:0}function gg(e){return e>=fs/2?"leading":e<=-fs/2?"trailing":"none"}function hu({thread:e,selectionMode:t,checked:s,active:n,peek:a,onPeek:o,onToggleCheck:i,onLongPress:c,onOpen:u,onAct:m}){const d=l.useRef(null),[f,h]=l.useState(null),{longPressProps:v}=mu({onLongPress:c,isDisabled:t,accessibilityDescription:"Select message"}),x=E=>{const L=new PointerEvent("pointercancel",{bubbles:!0});L[Ii]=!0,E.currentTarget.dispatchEvent(L)},g=Fs(v,{onPointerDown:E=>{d.current={startX:E.clientX,startY:E.clientY,axis:"none",escaped:!1}},onPointerMove:E=>{if(t)return;const L=d.current;if(!L)return;const A=E.clientX-L.startX,j=E.clientY-L.startY;if(L.axis==="none"&&(Math.abs(j)>Ei&&Math.abs(j)>Math.abs(A)?L.axis="vertical":Math.abs(A)>Ei&&Math.abs(A)>Math.abs(j)&&(L.axis="horizontal",E.currentTarget.setPointerCapture(E.pointerId))),L.axis==="none")return;const I=L.axis==="horizontal"?Math.abs(A):Math.abs(j);if(!L.escaped&&I>pg&&(L.escaped=!0,x(E)),L.axis!=="horizontal")return;const D=Ri(a),T=Math.max(-fs,Math.min(fs,D+A));h(T)},onPointerUp:E=>{const L=d.current;d.current=null;const A=f;if(h(null),!!L){if(L.axis!=="none"&&!L.escaped&&x(E),L.axis==="horizontal"){A!==null&&o(gg(A));return}if(L.axis!=="vertical"){if(t){i();return}if(a!=="none"){o("none");return}u()}}},onPointerCancel:E=>{E.nativeEvent[Ii]||(d.current=null,h(null))}}),w=f??Ri(a),C=w>0?"leading":w<0?"trailing":"none",R=Q("relative touch-pan-y bg-surface","select-none",_s({active:s||n})),O={transform:w!==0?`translateX(${w}px)`:void 0,transition:f===null?"transform 150ms ease":"none",minHeight:44},k=!e.isRead,M=E=>E.stopPropagation(),P=t?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:Q("inline-flex size-7 shrink-0 items-center justify-center rounded-full border",s?"border-accent bg-accent text-accent-fg":"border-line-strong bg-canvas"),children:s&&r.jsx(hn,{className:"size-3.5"})}),r.jsx(cn,{thread:e})]}):r.jsxs(r.Fragment,{children:[k&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx("span",{role:"checkbox",tabIndex:0,"aria-checked":s,"aria-label":`Select message from ${e.fromName}`,onPointerDown:M,onPointerMove:M,onPointerUp:M,onClick:E=>{E.preventDefault(),E.stopPropagation(),c()},onKeyDown:E=>{E.key!=="Enter"&&E.key!==" "||(E.preventDefault(),E.stopPropagation(),c())},className:"-m-2 inline-flex size-11 shrink-0 items-center justify-center rounded-full",children:r.jsx(jt,{name:e.fromName,email:e.fromEmail,size:"sm"})}),r.jsx(cn,{thread:e})]});return r.jsxs("div",{className:"relative overflow-hidden",children:[C==="leading"&&r.jsx("button",{type:"button",onClick:()=>m("leading"),"aria-label":e.isRead?"Mark as unread":"Mark as read",className:"absolute inset-y-0 left-0 flex items-center justify-start bg-accent-2 px-6 text-accent-fg",children:e.isRead?r.jsx(Tc,{className:"size-6"}):r.jsx(vr,{className:"size-6"})}),C==="trailing"&&r.jsx("button",{type:"button",onClick:()=>m("trailing"),"aria-label":"Delete message",className:"absolute inset-y-0 right-0 flex items-center justify-end bg-danger px-6 text-canvas",children:r.jsx(Lt,{className:"size-6"})}),r.jsx("button",{type:"button",role:t?"checkbox":void 0,"aria-checked":t?s:void 0,"data-message-row":!0,"data-message-id":e.id,...g,className:R,style:O,children:P})]})}function xg({sections:e,selectedThreadId:t,selectionMode:s,checkedIds:n,initialPeek:a,onToggleCheck:o,onEnterSelection:i,onOpenThread:c,onRefresh:u,refreshing:m,busy:d=!1}){const[f,h]=l.useState(new Set),[v,x]=l.useState(new Map),p=e.flatMap(g=>g.threads).filter(g=>!f.has(g.id)).map(g=>{const w=v.get(g.id);return w===void 0?g:{...g,isRead:w}}),[b,y]=l.useState(a&&a!=="none"&&p[1]?{id:p[1].id,side:a}:null),S=(g,w)=>{if(w==="trailing")h(C=>new Set(C).add(g));else{const C=p.find(R=>R.id===g);x(R=>new Map(R).set(g,!C?.isRead))}y(null)};return r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[m&&r.jsxs("div",{className:"flex items-center justify-center gap-2 border-b border-line py-3 text-fg-muted",children:[r.jsx(xo,{className:"size-4 animate-spin"}),r.jsx("span",{className:"text-xs",children:"Checking for new mail…"})]}),r.jsx("div",{className:"divide-y divide-line",children:p.map(g=>r.jsx("div",{className:d?"pointer-events-none opacity-50":void 0,children:r.jsx(hu,{thread:g,selectionMode:s,checked:n.has(g.id),active:g.id===t,peek:b?.id===g.id?b.side:"none",onPeek:w=>y(w==="none"?null:{id:g.id,side:w}),onToggleCheck:()=>o(g.id),onLongPress:()=>i(g.id),onOpen:()=>c(g.id),onAct:w=>S(g.id,w)})},g.id))}),!s&&!m&&!d&&r.jsx("button",{type:"button",onClick:u,className:"w-full border-t border-line py-2 text-center text-2xs text-fg-subtle transition-colors hover:bg-surface-sunken",children:"Pull to refresh"})]})}const bg=new Set;function pu({listTitle:e,listMeta:t,sections:s,briefFilters:n,flatList:a,listState:o="ready",searchQuery:i,listFilter:c,listScopeLabel:u,errorMessage:m,onRetry:d,onReportError:f,briefFilter:h,selectedThreadId:v,density:x="comfortable",onSelectThread:p,onOpenNav:b,isDesktop:y,initialTouchState:S,selection:g,keyboard:w,selectionBar:C,paneOverlay:R,listBody:O,hideHeader:k=!1}){const M=x==="compact"?dg:fg,P=l.useRef(null),E=l.useRef(null),L=nm(w);or({containerRef:P,itemSelector:Qn,enabled:!L});const A=L?w.focusedId:void 0,j=L?A??s[0]?.threads[0]?.id:void 0,I=l.useCallback(B=>j===void 0?void 0:B===j?0:-1,[j]);l.useEffect(()=>{if(A===void 0)return;const B=E.current;if(!B)return;const $=B.querySelector(`${Qn}[data-message-id="${A}"]`);!$||$===B.ownerDocument.activeElement||$.focus({preventScroll:!1})},[A]),l.useEffect(()=>{if(!L)return;const B=E.current;if(!B)return;const $=B.ownerDocument.activeElement;$!==null&&$!==B.ownerDocument.body||B.focus({preventScroll:!0})},[L]);const D=!y&&!n&&o==="ready",[T,F]=l.useState(!1),N=S==="peek-trailing"?"trailing":S==="peek-leading"?"leading":void 0,V=()=>{F(!0),setTimeout(()=>F(!1),1400)},J=g?.selectedIds??bg,re=g?.onToggle,oe=g?.onRowSelect,ie=vo(J.size,y),Z=l.useCallback(B=>{if(re)return{checked:J.has(B),onToggle:$=>{$.preventDefault(),$.stopPropagation(),re(B)}}},[J,re]),ae=l.useCallback((B,$)=>oe?.(B,Zn($))?($.preventDefault(),$.shiftKey&&window.getSelection()?.removeAllRanges(),!0):!1,[oe]),fe=l.useCallback(({thread:B,active:$,onClick:me})=>r.jsx(M,{thread:B,active:$,focused:B.id===A,tabIndex:I(B.id),selection:Z(B.id),onClick:ge=>{ae(B.id,ge)||me?.()}}),[M,Z,ae,A,I]);return r.jsxs("section",{ref:B=>{E.current=B,w?.ref(B)},tabIndex:L?-1:void 0,className:"relative flex h-full w-full flex-col bg-surface outline-none",children:[C??(k?null:r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[b&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(pr,{className:"size-4"}),onClick:b,"aria-label":"Open folders",className:"-ml-1 shrink-0"}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),t&&r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:t})]})),o==="loading"?r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(Xp,{})}):o==="empty"?r.jsx(Jp,{filter:c,scopeLabel:u,searchQuery:i}):o==="error"?r.jsx(ng,{message:m,onRetry:d,onReport:f}):n?r.jsx(cc,{...h??{},sections:s,selectedThreadId:v,Row:fe,keyboard:w,onSelectThread:p}):O??(D?r.jsx(xg,{sections:s,selectedThreadId:v,selectionMode:ie,checkedIds:J,initialPeek:N,onToggleCheck:B=>re?.(B),onEnterSelection:B=>re?.(B),onOpenThread:B=>p?.(B),onRefresh:V,refreshing:T}):r.jsx("div",{ref:P,className:"flex-1 overflow-y-auto",children:s.map(B=>r.jsxs("div",{children:[!a&&B.label&&r.jsxs("div",{className:"sticky top-0 flex h-section-row items-center justify-between border-b border-line bg-surface-sunken px-row-inset",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:B.label}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:B.threads.length})]}),r.jsx("div",{className:"divide-y divide-line",children:B.threads.map($=>r.jsx(M,{thread:$,active:$.id===v,focused:$.id===A,tabIndex:I($.id),selection:Z($.id),onClick:me=>{ae($.id,me)||p?.($.id)}},$.id))})]},B.id))})),y&&r.jsx(ou,{hints:w?qp(w.handlers):bo}),R]})}function wo({triggerLabel:e,triggerIcon:t,triggerText:s,items:n,align:a="end",touch:o=!0,className:i,triggerClassName:c,nested:u=!1,children:m}){const[d,f]=l.useState(!1),h=l.useRef(null);return l.useEffect(()=>{if(!d)return;const v=p=>{h.current&&!h.current.contains(p.target)&&f(!1)},x=p=>{p.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",x),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",x)}},[d]),n.length===0&&!m?null:r.jsxs("div",{ref:h,className:Q("relative",i),...u?{role:"none"}:{},children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:t??r.jsx(Gc,{className:"size-5"}),onClick:()=>f(v=>!v),"aria-label":e,"aria-haspopup":"menu","aria-expanded":d,...u?{role:"menuitem"}:{},className:Q(o&&"min-h-11 min-w-11 px-0",c),children:s}),d&&r.jsxs("div",{role:"menu",className:Q("absolute top-full z-50 mt-1 flex max-h-[60dvh] min-w-44 flex-col overflow-y-auto overscroll-contain rounded-md border border-line bg-surface py-1 shadow-lg",a==="end"?"right-0":"left-0"),children:[n.map(v=>r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{f(!1),v.onSelect()},className:"flex min-h-11 items-center gap-3 px-4 py-2.5 text-left text-sm text-fg transition-colors hover:bg-surface-sunken",children:[v.icon&&r.jsx("span",{className:"shrink-0 text-fg-subtle",children:v.icon}),v.label]},v.key)),m]})]})}const Gs="min-h-11 min-w-11 px-0";function gu({hasThread:e,onReply:t,onReplyAll:s,onForward:n,isStarred:a,onToggleStar:o,onDelete:i,isRead:c,onToggleRead:u,moveSlot:m,overflowItems:d=[],onUnavailable:f,unavailableHint:h,className:v}){const x=(b,y)=>()=>{if(!e){f?.(b);return}y?.()},p=u?[{key:"toggle-read",label:c?"Mark as unread":"Mark as read",icon:c?r.jsx(Tc,{className:"size-4"}):r.jsx(vr,{className:"size-4"}),onSelect:x("toggleRead",u)}]:[];return r.jsxs("div",{className:Q("relative",v),children:[r.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-0.5 bg-canvas px-1",children:[t&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Zc,{className:"size-5"}),onClick:x("reply",t),"aria-label":"Reply",title:"Reply",className:Gs}),s&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Jc,{className:"size-5"}),onClick:x("replyAll",s),"aria-label":"Reply all",title:"Reply all",className:Gs}),n&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Yc,{className:"size-5"}),onClick:x("forward",n),"aria-label":"Forward",title:"Forward",className:Gs}),r.jsx("div",{className:"flex-1"}),o&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Xt,{className:Q("size-5",a&&"fill-warning text-warning")}),onClick:x("star",o),"aria-label":a?"Unstar":"Star","aria-pressed":a,title:a?"Unstar":"Star",className:Gs}),m,i&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Lt,{className:"size-5"}),onClick:x("delete",i),"aria-label":"Move to Trash",title:"Move to Trash",className:Gs}),r.jsx(wo,{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 vg({open:e=!1,enabled:t=!0,onToggle:s,className:n}){return r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(uc,{className:"size-4"}),title:"Intelligence","aria-label":e?"Hide intelligence sidebar":"Show intelligence sidebar","aria-pressed":e,disabled:!t,onClick:s,className:Q(e&&"bg-accent-2-soft text-accent-2",n)})}function yg({hasThread:e,onUnavailable:t,unavailableHint:s,isStarred:n,showTriage:a=!0,onReply:o,onReplyAll:i,onForward:c,onDelete:u,onToggleStar:m,moveSlot:d,onMove:f,replyTitle:h="Reply (r)",replyAllTitle:v="Reply all (a)",forwardTitle:x="Forward (f)",deleteTitle:p="Move to Trash (#)",flagTitle:b="Star (s)",children:y,className:S}){const g=(w,C)=>()=>{if(!e){t?.(w);return}C?.()};return r.jsxs("div",{className:"relative",children:[r.jsxs("header",{className:Q("flex h-pane-header shrink-0 items-center gap-1 border-b border-line bg-surface px-3",S),children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Zc,{className:"size-4"}),title:h,"aria-label":"Reply",onClick:g("reply",o)}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Jc,{className:"size-4"}),title:v,"aria-label":"Reply all",onClick:g("replyAll",i)}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Yc,{className:"size-4"}),title:x,"aria-label":"Forward",onClick:g("forward",c)}),a&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"mx-1 h-4 w-px bg-line","aria-hidden":!0}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Lt,{className:"size-4"}),title:p,"aria-label":"Move to Trash",onClick:g("delete",u)}),d??r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(za,{className:"size-4"}),title:"Move to mailbox","aria-label":"Move to mailbox",onClick:g("move",f)}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Xt,{className:Q("size-4",n&&"fill-warning text-warning")}),title:b,"aria-label":"Star",onClick:g("flag",m)})]}),r.jsx("div",{className:"flex-1"}),y]}),!e&&s&&r.jsx("p",{role:"status",className:"border-b border-line bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:s})]})}const wg=(e,t)=>{const n=e==="newsletter"||e==="marketing"||t;return{framed:n,isPlain:!n}},Sg=()=>`
|
|
8
|
+
`.trim(),j.head.prepend(I)},[h]),l.useEffect(()=>{let j=b.current;return()=>{f||bi(j.target??void 0);for(let I of j.disposables)I();j.disposables=[]}},[f]),{isPressed:u||x,pressProps:Fs(v,A,{[Si]:!0})}}function po(e){return e.tagName==="A"&&e.hasAttribute("href")}function Vr(e,t){const{key:s,code:n}=e,a=t,o=a.getAttribute("role");return(s==="Enter"||s===" "||s==="Spacebar"||n==="Space")&&!(a instanceof Yt(a).HTMLInputElement&&!Hc(a,s)||a instanceof Yt(a).HTMLTextAreaElement||a.isContentEditable)&&!((o==="link"||!o&&po(a))&&s!=="Enter")}function os(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 Np(e){return e instanceof HTMLInputElement?!1:e instanceof HTMLButtonElement?e.type!=="submit"&&e.type!=="reset":!po(e)}function Ci(e,t){return e instanceof HTMLInputElement?!Hc(e,t):Np(e)}const Ep=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function Hc(e,t){return e.type==="checkbox"||e.type==="radio"?t===" ":Ep.has(e.type)}let Ip=0;const Qr=new Map;function Rp(e){let[t,s]=l.useState();return mo(()=>{if(!e)return;let n=Qr.get(e);if(n)s(n.element.id);else{let a=`react-aria-description-${Ip++}`;s(a);let o=document.createElement("div");o.id=a,o.style.display="none",o.textContent=e,document.body.appendChild(o),n={refCount:0,element:o},Qr.set(e,n)}return n.refCount++,()=>{n&&--n.refCount===0&&(n.element.remove(),Qr.delete(e))}},[e]),{"aria-describedby":e?t:void 0}}const Tp=500;function Mp(e){let{isDisabled:t,onLongPressStart:s,onLongPressEnd:n,onLongPress:a,threshold:o=Tp,accessibilityDescription:i}=e;const c=l.useRef(void 0);let{addGlobalListener:u,removeGlobalListener:m}=qc(),{pressProps:d}=jp({isDisabled:t,onPressStart(h){if(h.continuePropagation(),(h.pointerType==="mouse"||h.pointerType==="touch")&&(s&&s({...h,type:"longpressstart"}),c.current=setTimeout(()=>{h.target.dispatchEvent(new PointerEvent("pointercancel",{bubbles:!0})),Wt(h.target).activeElement!==h.target&&on(h.target),a&&a({...h,type:"longpress"}),c.current=void 0},o),h.pointerType==="touch")){let v=p=>{p.preventDefault()},x=Yt(h.target);u(h.target,"contextmenu",v,{once:!0}),u(x,"pointerup",()=>{setTimeout(()=>{m(h.target,"contextmenu",v)},30)},{once:!0})}},onPressEnd(h){c.current&&clearTimeout(c.current),n&&(h.pointerType==="mouse"||h.pointerType==="touch")&&n({...h,type:"longpressend"})}}),f=Rp(a&&!t?i:void 0);return{longPressProps:Fs(d,f)}}const br=_e("BadgeCheck",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Wc=_e("BellOff",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]]);const Ap=_e("BookmarkPlus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"12",x2:"12",y1:"7",y2:"13",key:"1cppfj"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);const Vc=_e("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]);const go=_e("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);const Qc=_e("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);const Gc=_e("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);const Yc=_e("Forward",[["polyline",{points:"15 17 20 12 15 7",key:"1w3sku"}],["path",{d:"M4 18v-2a4 4 0 0 1 4-4h12",key:"jmiej9"}]]);const Xc=_e("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);const Op=_e("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);const vr=_e("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);const Dp=_e("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);const Pp=_e("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const yr=_e("Paperclip",[["path",{d:"M13.234 20.252 21 12.3",key:"1cbrk9"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486",key:"1pkts6"}]]);const xo=_e("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);const Jc=_e("ReplyAll",[["polyline",{points:"7 17 2 12 7 7",key:"t83bqg"}],["polyline",{points:"12 17 7 12 12 7",key:"1g4ajm"}],["path",{d:"M22 18v-2a4 4 0 0 0-4-4H7",key:"1fcyog"}]]);const Zc=_e("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);const eu=_e("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const $s=_e("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);const Lp=_e("ShieldQuestion",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const Fp=_e("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);const $p=_e("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);const _p=_e("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]),zp=({address:e,showTrustedBadge:t=!1})=>{const s=t?r.jsx(br,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}):null;return e.displayName?r.jsxs("span",{children:[r.jsx("span",{className:"text-fg",children:e.displayName}),r.jsxs("span",{className:"text-fg-muted",children:[" ","<",e.normalizedEmail,">"]}),s]}):r.jsxs("span",{className:"text-fg",children:[e.normalizedEmail,s]})},Bp=({label:e,addresses:t,showTrustedBadge:s=!1})=>{const[n,a]=l.useState(!1);if(t.length===0)return null;const o=t.length>3,i=c=>{const u=s&&c.flags?.trusted?.value===!0;return r.jsx(zp,{address:c,showTrustedBadge:u})};return r.jsxs("div",{className:"flex gap-2 text-sm",children:[r.jsxs("span",{className:"text-fg-muted shrink-0 w-12",children:[e,":"]}),r.jsx("div",{className:"flex-1 min-w-0",children:n?r.jsx("div",{className:"flex flex-wrap gap-1",children:t.map((c,u)=>r.jsxs("span",{children:[i(c),u<t.length-1&&", "]},u))}):r.jsx("div",{className:"truncate",children:t.map((c,u)=>r.jsxs("span",{children:[i(c),u<t.length-1&&", "]},u))})}),o&&r.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),a(!n)},className:"shrink-0 text-fg-muted hover:text-fg transition-colors","aria-label":n?"Collapse":"Expand",children:n?r.jsx(Qt,{className:"h-4 w-4"}):r.jsx(Ms,{className:"h-4 w-4"})})]})},Up=({email:e,displayName:t,onRemove:s,className:n})=>r.jsxs("span",{className:Q("inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-accent-2-soft text-sm max-w-[200px]",n),children:[r.jsx("span",{className:"truncate",children:t||e}),r.jsx("button",{type:"button",onClick:s,className:"shrink-0 p-0.5 rounded-full hover:bg-fg-muted/20 transition-colors","aria-label":`Remove ${e}`,children:r.jsx(Nt,{className:"size-3"})})]}),Kp={unknown:{label:"Unknown sender",tone:"neutral"},wellknown:{label:"Known sender",tone:"positive"},vip:{label:"VIP",tone:"accent"}};function ws({label:e,children:t,className:s}){return r.jsxs("section",{className:Q("border-b border-line px-row-inset py-3",s),children:[r.jsx("h3",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),r.jsx("div",{className:"mt-2",children:t})]})}function qp({sender:e}){const t=Kp[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(jt,{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(kt,{tone:"danger",dot:!0,children:"Address couldn't be verified"}):r.jsx(kt,{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 Hp({auth:e,onShowSimilar:t}){if(e.verdict==="aligned")return r.jsxs("div",{className:"flex items-start gap-2 text-xs text-fg-muted",children:[r.jsx(xn,{className:"mt-0.5 size-3.5 shrink-0 text-positive"}),r.jsx("span",{children:e.summary})]});if(e.verdict==="caution")return r.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-warning/10 p-3 text-warning",children:[r.jsx(Lp,{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($s,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm font-semibold text-danger",children:s}),r.jsx("p",{className:"mt-1 text-xs leading-relaxed text-fg",children:e.summary}),!e.addressUnreadable&&e.dkimDomain&&r.jsxs("p",{className:"mt-1 text-2xs text-fg-muted",children:["Sent from"," ",r.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.dkimDomain}),", claims to be"," ",r.jsx("code",{className:"rounded bg-surface px-1 py-0.5",children:e.fromDomain})]})]})]}),e.similarCount!=null&&e.similarCount>0&&r.jsxs(ce,{variant:"secondary",size:"sm",className:"mt-2 w-full border-danger/30 text-danger hover:bg-danger-soft",onClick:t,children:[e.similarCount," similar messages"]})]})}function Ws({icon:e,label:t,active:s,danger:n,onClick:a,pending:o}){const i=a===void 0||o===!0;return r.jsxs("button",{type:"button",onClick:a,disabled:i,className:Q("flex items-center gap-2 rounded-md border px-2 py-1 text-xs transition-colors",s?"border-accent-2 bg-accent-2-soft text-accent-2":"border-line text-fg-muted hover:border-line-strong hover:text-fg",n&&!s&&"text-danger hover:bg-danger-soft",i&&"cursor-not-allowed opacity-50 hover:border-line"),children:[e,t]})}const Wp={sender:"matched: sender",recipient:"matched: recipient",subject:"matched: subject",attachment:"matched: attachment",body:"matched: body",entities:"matched: entities"};function tu({data:e,onClose:t,onShowSimilar:s,actions:n,similarState:a="ready",similarLinkComponent:o,className:i,hideCloseButton:c=!1,reportSpamPending:u=!1,notSpamPending:m=!1}){const{sender:d,authenticity:f,category:h,flags:v={},similar:x}=e,p=f.verdict==="mismatch";return r.jsxs("aside",{className:Q("flex w-76 shrink-0 flex-col overflow-y-auto border-l border-line bg-surface",i),children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center justify-between border-b border-line px-row-inset",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"}),!c&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Nt,{className:"size-3.5"}),onClick:t,"aria-label":"Collapse intelligence sidebar"})]}),r.jsx(ws,{label:"Sender",children:r.jsx(qp,{sender:d})}),r.jsx(ws,{label:"Authenticity",children:r.jsx(Hp,{auth:f,onShowSimilar:s})}),r.jsx(ws,{label:"Category",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(kt,{tone:p?"danger":"neutral",children:h.value}),h.overridden&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"your override"}),r.jsx("button",{type:"button",className:Q("ml-auto text-2xs text-accent hover:underline",!n?.onReclassify&&"cursor-not-allowed opacity-50 hover:no-underline"),disabled:!n?.onReclassify,onClick:n?.onReclassify,children:"reclassify"})]})}),r.jsxs(ws,{label:"Quick actions",children:[r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[r.jsx(Ws,{icon:r.jsx(Xt,{className:"size-3.5"}),label:"VIP",active:v.vip,onClick:n?.onToggleVip}),r.jsx(Ws,{icon:r.jsx(Wc,{className:"size-3.5"}),label:"Mute",active:v.muted,onClick:n?.onToggleMute}),n?.onNotSpam&&r.jsx(Ws,{icon:r.jsx(Op,{className:"size-3.5"}),label:m?"Undoing…":"Not spam",active:!0,onClick:n.onNotSpam,pending:m}),n?.onReportSpam&&r.jsx(Ws,{icon:r.jsx(Fp,{className:"size-3.5"}),label:u?"Reporting…":"Report spam",danger:!0,onClick:n.onReportSpam,pending:u}),r.jsx(Ws,{icon:r.jsx(Dp,{className:"size-3.5"}),label:"Unsubscribe",active:v.unsubscribed,onClick:n?.onToggleUnsubscribe})]}),n?.onNotSpam&&r.jsx("p",{className:"mt-1.5 text-2xs text-fg-subtle",children:"You reported this message as spam"})]}),(a!=="ready"||x.length>0)&&r.jsx(ws,{label:"Similar messages",children:a==="loading"?r.jsx("div",{className:"animate-pulse space-y-2",children:Array.from({length:3}).map((b,y)=>r.jsxs("div",{className:"space-y-1",children:[r.jsx("div",{className:"h-3 w-3/4 rounded bg-surface-sunken"}),r.jsx("div",{className:"h-2.5 w-1/2 rounded bg-surface-sunken"})]},y))}):a==="error"?r.jsx("p",{className:"text-xs text-fg-subtle",children:"Similarity search unavailable"}):r.jsx("ul",{className:"-mx-1 space-y-1",children:x.map(b=>{const y="block w-full rounded-md px-1 py-1 text-left hover:bg-surface-sunken",S=`Open message from ${b.fromName||"unknown sender"}: ${b.subject}`,g=r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[r.jsx("span",{className:"truncate text-xs font-medium text-fg",children:b.fromName}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:b.timeLabel})]}),r.jsx("div",{className:"truncate text-xs text-fg-muted",children:b.subject}),r.jsx("span",{className:"mt-1 inline-block rounded-full bg-surface-sunken px-1.5 py-px text-2xs text-fg-subtle",children:Wp[b.matched]})]});return r.jsx("li",{children:o?o({mailboxId:b.mailboxId,messageId:b.id,className:y,ariaLabel:S,children:g}):r.jsx("div",{className:y,children:g})},b.id)})})}),r.jsx(ws,{label:"Coming soon",className:"border-b-0 opacity-70",children:r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[r.jsx(Dt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Suggested actions"}),r.jsx("div",{className:"text-2xs text-fg-subtle",children:'"Create a filter for messages like this" — on-device model'})]})]}),r.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-line p-2",children:[r.jsx(Dt,{className:"mt-0.5 size-3.5 shrink-0 text-fg-subtle"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-xs font-medium text-fg-muted",children:"Thread summary"}),r.jsx("div",{className:"text-2xs text-fg-subtle",children:"One-paragraph digest — Bedrock"})]})]})]})})]})}const bo=[{action:"focusNext",keys:["j","k"],label:"navigate"},{action:"muteSender",keys:["m"],label:"mute"},{action:"help",keys:["?"],label:"all shortcuts"}];function Vp(e){return bo.filter(t=>e[t.action]!==void 0)}const su=[{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 Qp(e){for(const t of su){const s=t.hints.find(n=>n.action===e);if(s)return s.keys}}function nu(e){const t=Qp(e);return!t||t.length===0?"":t.length===1?t[0]??"":t[0]==="g"?t.join(" then "):t.join("")}function Vs(e){const t=nu(e);return t===""?"":`(${t})`}const Zn=e=>({shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey}),ki=e=>e.shiftKey||e.metaKey||e.ctrlKey,Gp=e=>e.shiftKey?"range":e.metaKey||e.ctrlKey?"toggle":"open",vo=(e,t)=>!t&&e>0,Yp=(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)},Xp=(e,t,s,n)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:n,Jp=(e,t)=>{const s=new Set(t),n=new Set;for(const a of e)s.has(a)&&n.add(a);return n},ru=(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]},au=e=>{const[t,s]=l.useState(()=>new Set(e?.initialSelectedIds)),[n,a]=l.useState(void 0),o=l.useCallback(p=>t.has(p),[t]),i=l.useCallback(p=>{a(p),s(b=>{const y=new Set(b);return y.has(p)?y.delete(p):y.add(p),y})},[]),c=l.useCallback(p=>{a(p),s(b=>{if(b.has(p))return b;const y=new Set(b);return y.add(p),y})},[]),u=l.useCallback(p=>{s(b=>{if(!b.has(p))return b;const y=new Set(b);return y.delete(p),y})},[]),m=l.useCallback(p=>{s(new Set(p))},[]),d=l.useCallback(()=>{a(void 0),s(new Set)},[]),f=l.useCallback(p=>{s(b=>p.every(S=>b.has(S))?new Set:new Set(p))},[]),h=l.useCallback(p=>{a(p)},[]),v=l.useCallback(p=>{s(b=>{if(b.size===0)return b;const y=Jp(b,p);return y.size===b.size?b:y})},[]),x=l.useCallback((p,b,y)=>{const S=Xp(p,n,y,b);s(g=>{const w=Yp(p,S,b);if(w.length===0)return g;const C=new Set(g);for(const R of w)C.add(R);return C}),a(S)},[n]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:c,deselect:u,selectAll:m,clearSelection:d,toggleAll:f,selectRange:x,setAnchor:h,anchorId:n,intersectWith:v}};function ou({hints:e=bo,className:t}){return e.length===0?null:r.jsx("footer",{className:Q("flex items-center gap-2 border-t border-line px-row-inset py-1 text-2xs text-fg-subtle",t),children:e.map(s=>r.jsx(Zp,{hint:s},s.label))})}function Zp({hint:e}){return r.jsxs("span",{className:"flex items-center gap-1",children:[e.keys.map(t=>r.jsx(Is,{children:t},t)),r.jsx("span",{children:e.label})]})}function eg(){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 tg({filter:e,scopeLabel:t,searchQuery:s}){const n=s?.trim();return e?r.jsxs(ji,{children:[r.jsx("p",{className:"font-medium text-fg",children:rg(e.label,t,n)}),r.jsx("p",{className:"mt-1 text-sm text-fg-muted",children:sg[e.reach]}),r.jsx(ce,{variant:"secondary",size:"sm",className:"mt-4",onClick:e.onClear,children:"Clear filter"})]}):r.jsx(ji,{children:r.jsx("p",{className:"text-fg-muted",children:ng(n,t)})})}const sg={"whole-folder":"Every message in this folder was checked.","loaded-pages":"Only the messages loaded so far were checked."};function ng(e,t){return e?"No messages match your search":t?`No messages in ${t}`:"No messages in this mailbox"}function rg(e,t,s){return s?`No results for “${s}” in ${e}`:t?`No ${e} mail in ${t}`:`No ${e} mail`}function ji({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 ag(){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(hs,{className:"size-4 animate-spin","aria-hidden":"true"}),r.jsx("span",{children:"Loading more…"})]})}function og({message:e="Something went wrong loading this mailbox.",onRetry:t,onReport:s}){return r.jsx("div",{className:"flex h-full flex-1 items-center justify-center p-4",children:r.jsxs("div",{role:"alert",className:"flex max-w-sm flex-col items-center justify-center gap-3 text-center",children:[r.jsx(Pt,{className:"size-8 text-danger","aria-hidden":"true"}),r.jsxs("div",{children:[r.jsx("p",{className:"font-medium text-danger",children:"Couldn't load messages"}),r.jsx("p",{className:"mt-1 break-words text-sm text-fg-muted",children:e})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t&&r.jsx(ce,{variant:"secondary",size:"sm",onClick:t,children:"Retry"}),s&&r.jsx(ce,{variant:"ghost",size:"sm",onClick:s,children:"Report a problem"})]})]})})}const Qs={action:null,nextPrefix:null,preventDefault:!1},ig={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},lg={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 cg(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=ig[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=lg[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 ug(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const iu="data-message-row",dg='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function fg(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(dg);return t?!t.hasAttribute(iu):!1}const lu="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",cu=({active:e,focused:t})=>Q("relative flex h-8 w-full items-center gap-2 px-row-inset text-left",lu,e?"bg-accent-2-soft":t?"bg-surface-sunken":"hover:bg-surface-sunken",t&&!e&&"before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-accent-2"),_s=({active:e,focused:t})=>Q("relative flex w-full items-start gap-3 py-2 pl-5 pr-row-inset text-left transition-colors",lu,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 uu({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($s,{className:"size-3.5 text-danger"}):e.starred?r.jsx(Xt,{className:"size-3 fill-warning text-warning"}):t?r.jsx("span",{className:"size-1.5 rounded-full bg-accent"}):null}),r.jsx("span",{className:Q("w-36 shrink-0 truncate text-xs",t?"font-semibold text-fg":"text-fg-muted"),children:e.fromName}),r.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs",children:[r.jsx("span",{className:Q(t?"font-medium text-fg":"text-fg-muted"),children:e.subject}),r.jsxs("span",{className:"text-fg-subtle",children:[" — ",e.snippet]})]}),e.hasAttachment&&r.jsx(yr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"}),r.jsx("span",{className:"w-11 shrink-0 text-right text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]})}function Ni(e,t){const s=t?.trim();if(!s)return e;const n=e.toLowerCase(),a=s.toLowerCase(),o=[];let i=0,c=n.indexOf(a,i),u=0;for(;c!==-1;)c>i&&o.push(e.slice(i,c)),o.push(r.jsx("mark",{className:"bg-transparent font-semibold text-fg",children:e.slice(c,c+a.length)},u++)),i=c+a.length,c=n.indexOf(a,i);return i<e.length&&o.push(e.slice(i)),o}function cn({thread:e,badge:t,highlightQuery:s}){const n=!e.isRead;return r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsxs("span",{className:"flex items-baseline justify-between gap-2",children:[r.jsxs("span",{className:Q("flex min-w-0 items-center gap-1.5 truncate text-sm",n?"font-semibold text-fg":"font-medium text-fg-muted"),children:[e.trust==="vip"&&r.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-accent-2"}),r.jsx("span",{className:"truncate",children:e.fromName}),e.messageCount!=null&&e.messageCount>1&&r.jsx("span",{className:"shrink-0 text-2xs font-normal text-fg-subtle",children:e.messageCount})]}),r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.timeLabel})]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:Q("truncate text-sm",n?"text-fg":"text-fg-muted"),children:Ni(e.subject,s)}),e.suspicious&&r.jsx($s,{className:"size-3.5 shrink-0 text-danger"}),e.starred&&r.jsx(Xt,{className:"size-3 shrink-0 fill-warning text-warning"}),e.hasAttachment&&r.jsx(yr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"})]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"line-clamp-1 min-w-0 flex-1 text-xs text-fg-subtle",children:Ni(e.snippet,s)}),e.category&&e.category!=="personal"&&r.jsx(kt,{tone:tm[e.category],className:"shrink-0",children:e.category}),e.labels?.map(a=>r.jsx(sm,{label:a,className:"max-w-20"},a.labelId)),t]})]})}function mg({thread:e,selection:t}){if(!t)return r.jsx(jt,{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(jt,{name:e.fromName,email:e.fromEmail,size:"sm",className:Q("absolute inset-0 transition-opacity sm:group-hover:opacity-0",(s||n)&&"opacity-0")}),r.jsx("span",{role:"button",tabIndex:-1,onClick:t.onToggle,onKeyDown:a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),a.stopPropagation(),t.onToggle(a))},className:Q("absolute inset-0 size-7 items-center justify-center rounded-full border transition-opacity",n?"flex":"hidden sm:flex",s?"bg-accent border-accent text-accent-fg opacity-100":n?"border-fg-subtle/40 bg-canvas opacity-100":"border-fg-subtle/40 bg-canvas opacity-0 group-hover:opacity-100"),"aria-label":s?"Deselect message":"Select message",children:s&&r.jsx(hn,{className:"size-3"})})]})}function yo({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(mg,{thread:e,selection:t}),r.jsx(cn,{thread:e,badge:s,highlightQuery:n})]})}const du=e=>({...lc,[iu]:"","data-message-id":e.id});function hg({thread:e,active:t,focused:s,tabIndex:n,onClick:a}){return r.jsx("button",{type:"button",...du(e),tabIndex:n,onClick:a,className:cu({active:t,focused:s}),children:r.jsx(uu,{thread:e})})}function pg({thread:e,active:t,focused:s,tabIndex:n,selection:a,onClick:o}){return r.jsx("button",{type:"button",...du(e),tabIndex:n,onClick:o,className:Q("group",_s({active:t,focused:s})),children:r.jsx(yo,{thread:e,selection:a})})}let Rs;const gg=5e3;function fu(e){e.preventDefault(),er()}function er(){Rs!==void 0&&(clearTimeout(Rs),Rs=void 0,document.removeEventListener("contextmenu",fu,!0),document.removeEventListener("pointerup",er,!0))}function xg(){Rs===void 0?(document.addEventListener("contextmenu",fu,!0),document.addEventListener("pointerup",er,!0)):clearTimeout(Rs),Rs=setTimeout(er,gg)}function mu({onLongPress:e,isDisabled:t,delayMs:s=500,accessibilityDescription:n}){const{longPressProps:a}=Mp({isDisabled:t,threshold:s,accessibilityDescription:n,onLongPress:e}),o=l.useCallback(i=>{i.pointerType!=="touch"&&i.pointerType!=="pen"||xg()},[]);return{longPressProps:Fs(a,{onPointerDown:o})}}const fs=72,Ei=10,bg=fs/2,Ii="__swipeableRowAxisCancel";function Ri(e){return e==="leading"?fs:e==="trailing"?-fs:0}function vg(e){return e>=fs/2?"leading":e<=-fs/2?"trailing":"none"}function hu({thread:e,selectionMode:t,checked:s,active:n,peek:a,onPeek:o,onToggleCheck:i,onLongPress:c,onOpen:u,onAct:m}){const d=l.useRef(null),[f,h]=l.useState(null),{longPressProps:v}=mu({onLongPress:c,isDisabled:t,accessibilityDescription:"Select message"}),x=E=>{const L=new PointerEvent("pointercancel",{bubbles:!0});L[Ii]=!0,E.currentTarget.dispatchEvent(L)},g=Fs(v,{onPointerDown:E=>{d.current={startX:E.clientX,startY:E.clientY,axis:"none",escaped:!1}},onPointerMove:E=>{if(t)return;const L=d.current;if(!L)return;const A=E.clientX-L.startX,j=E.clientY-L.startY;if(L.axis==="none"&&(Math.abs(j)>Ei&&Math.abs(j)>Math.abs(A)?L.axis="vertical":Math.abs(A)>Ei&&Math.abs(A)>Math.abs(j)&&(L.axis="horizontal",E.currentTarget.setPointerCapture(E.pointerId))),L.axis==="none")return;const I=L.axis==="horizontal"?Math.abs(A):Math.abs(j);if(!L.escaped&&I>bg&&(L.escaped=!0,x(E)),L.axis!=="horizontal")return;const D=Ri(a),T=Math.max(-fs,Math.min(fs,D+A));h(T)},onPointerUp:E=>{const L=d.current;d.current=null;const A=f;if(h(null),!!L){if(L.axis!=="none"&&!L.escaped&&x(E),L.axis==="horizontal"){A!==null&&o(vg(A));return}if(L.axis!=="vertical"){if(t){i();return}if(a!=="none"){o("none");return}u()}}},onPointerCancel:E=>{E.nativeEvent[Ii]||(d.current=null,h(null))}}),w=f??Ri(a),C=w>0?"leading":w<0?"trailing":"none",R=Q("relative touch-pan-y bg-surface","select-none",_s({active:s||n})),O={transform:w!==0?`translateX(${w}px)`:void 0,transition:f===null?"transform 150ms ease":"none",minHeight:44},k=!e.isRead,M=E=>E.stopPropagation(),P=t?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:Q("inline-flex size-7 shrink-0 items-center justify-center rounded-full border",s?"border-accent bg-accent text-accent-fg":"border-line-strong bg-canvas"),children:s&&r.jsx(hn,{className:"size-3.5"})}),r.jsx(cn,{thread:e})]}):r.jsxs(r.Fragment,{children:[k&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx("span",{role:"checkbox",tabIndex:0,"aria-checked":s,"aria-label":`Select message from ${e.fromName}`,onPointerDown:M,onPointerMove:M,onPointerUp:M,onClick:E=>{E.preventDefault(),E.stopPropagation(),c()},onKeyDown:E=>{E.key!=="Enter"&&E.key!==" "||(E.preventDefault(),E.stopPropagation(),c())},className:"-m-2 inline-flex size-11 shrink-0 items-center justify-center rounded-full",children:r.jsx(jt,{name:e.fromName,email:e.fromEmail,size:"sm"})}),r.jsx(cn,{thread:e})]});return r.jsxs("div",{className:"relative overflow-hidden",children:[C==="leading"&&r.jsx("button",{type:"button",onClick:()=>m("leading"),"aria-label":e.isRead?"Mark as unread":"Mark as read",className:"absolute inset-y-0 left-0 flex items-center justify-start bg-accent-2 px-6 text-accent-fg",children:e.isRead?r.jsx(Tc,{className:"size-6"}):r.jsx(vr,{className:"size-6"})}),C==="trailing"&&r.jsx("button",{type:"button",onClick:()=>m("trailing"),"aria-label":"Delete message",className:"absolute inset-y-0 right-0 flex items-center justify-end bg-danger px-6 text-canvas",children:r.jsx(Lt,{className:"size-6"})}),r.jsx("button",{type:"button",role:t?"checkbox":void 0,"aria-checked":t?s:void 0,"data-message-row":!0,"data-message-id":e.id,...g,className:R,style:O,children:P})]})}function yg({sections:e,selectedThreadId:t,selectionMode:s,checkedIds:n,initialPeek:a,onToggleCheck:o,onEnterSelection:i,onOpenThread:c,onRefresh:u,refreshing:m,busy:d=!1}){const[f,h]=l.useState(new Set),[v,x]=l.useState(new Map),p=e.flatMap(g=>g.threads).filter(g=>!f.has(g.id)).map(g=>{const w=v.get(g.id);return w===void 0?g:{...g,isRead:w}}),[b,y]=l.useState(a&&a!=="none"&&p[1]?{id:p[1].id,side:a}:null),S=(g,w)=>{if(w==="trailing")h(C=>new Set(C).add(g));else{const C=p.find(R=>R.id===g);x(R=>new Map(R).set(g,!C?.isRead))}y(null)};return r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[m&&r.jsxs("div",{className:"flex items-center justify-center gap-2 border-b border-line py-3 text-fg-muted",children:[r.jsx(xo,{className:"size-4 animate-spin"}),r.jsx("span",{className:"text-xs",children:"Checking for new mail…"})]}),r.jsx("div",{className:"divide-y divide-line",children:p.map(g=>r.jsx("div",{className:d?"pointer-events-none opacity-50":void 0,children:r.jsx(hu,{thread:g,selectionMode:s,checked:n.has(g.id),active:g.id===t,peek:b?.id===g.id?b.side:"none",onPeek:w=>y(w==="none"?null:{id:g.id,side:w}),onToggleCheck:()=>o(g.id),onLongPress:()=>i(g.id),onOpen:()=>c(g.id),onAct:w=>S(g.id,w)})},g.id))}),!s&&!m&&!d&&r.jsx("button",{type:"button",onClick:u,className:"w-full border-t border-line py-2 text-center text-2xs text-fg-subtle transition-colors hover:bg-surface-sunken",children:"Pull to refresh"})]})}const wg=new Set;function pu({listTitle:e,listMeta:t,sections:s,briefFilters:n,flatList:a,listState:o="ready",searchQuery:i,listFilter:c,listScopeLabel:u,errorMessage:m,onRetry:d,onReportError:f,briefFilter:h,selectedThreadId:v,density:x="comfortable",onSelectThread:p,onOpenNav:b,isDesktop:y,initialTouchState:S,selection:g,keyboard:w,selectionBar:C,paneOverlay:R,listBody:O,hideHeader:k=!1}){const M=x==="compact"?hg:pg,P=l.useRef(null),E=l.useRef(null),L=nm(w);or({containerRef:P,itemSelector:Qn,enabled:!L});const A=L?w.focusedId:void 0,j=L?A??s[0]?.threads[0]?.id:void 0,I=l.useCallback(B=>j===void 0?void 0:B===j?0:-1,[j]);l.useEffect(()=>{if(A===void 0)return;const B=E.current;if(!B)return;const $=B.querySelector(`${Qn}[data-message-id="${A}"]`);!$||$===B.ownerDocument.activeElement||$.focus({preventScroll:!1})},[A]),l.useEffect(()=>{if(!L)return;const B=E.current;if(!B)return;const $=B.ownerDocument.activeElement;$!==null&&$!==B.ownerDocument.body||B.focus({preventScroll:!0})},[L]);const D=!y&&!n&&o==="ready",[T,F]=l.useState(!1),N=S==="peek-trailing"?"trailing":S==="peek-leading"?"leading":void 0,V=()=>{F(!0),setTimeout(()=>F(!1),1400)},J=g?.selectedIds??wg,re=g?.onToggle,oe=g?.onRowSelect,ie=vo(J.size,y),Z=l.useCallback(B=>{if(re)return{checked:J.has(B),onToggle:$=>{$.preventDefault(),$.stopPropagation(),re(B)}}},[J,re]),ae=l.useCallback((B,$)=>oe?.(B,Zn($))?($.preventDefault(),$.shiftKey&&window.getSelection()?.removeAllRanges(),!0):!1,[oe]),fe=l.useCallback(({thread:B,active:$,onClick:me})=>r.jsx(M,{thread:B,active:$,focused:B.id===A,tabIndex:I(B.id),selection:Z(B.id),onClick:ge=>{ae(B.id,ge)||me?.()}}),[M,Z,ae,A,I]);return r.jsxs("section",{ref:B=>{E.current=B,w?.ref(B)},tabIndex:L?-1:void 0,className:"relative flex h-full w-full flex-col bg-surface outline-none",children:[C??(k?null:r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[b&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(pr,{className:"size-4"}),onClick:b,"aria-label":"Open folders",className:"-ml-1 shrink-0"}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e}),t&&r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle",children:t})]})),o==="loading"?r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(eg,{})}):o==="empty"?r.jsx(tg,{filter:c,scopeLabel:u,searchQuery:i}):o==="error"?r.jsx(og,{message:m,onRetry:d,onReport:f}):n?r.jsx(cc,{...h??{},sections:s,selectedThreadId:v,Row:fe,keyboard:w,onSelectThread:p}):O??(D?r.jsx(yg,{sections:s,selectedThreadId:v,selectionMode:ie,checkedIds:J,initialPeek:N,onToggleCheck:B=>re?.(B),onEnterSelection:B=>re?.(B),onOpenThread:B=>p?.(B),onRefresh:V,refreshing:T}):r.jsx("div",{ref:P,className:"flex-1 overflow-y-auto",children:s.map(B=>r.jsxs("div",{children:[!a&&B.label&&r.jsxs("div",{className:"sticky top-0 flex h-section-row items-center justify-between border-b border-line bg-surface-sunken px-row-inset",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:B.label}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:B.threads.length})]}),r.jsx("div",{className:"divide-y divide-line",children:B.threads.map($=>r.jsx(M,{thread:$,active:$.id===v,focused:$.id===A,tabIndex:I($.id),selection:Z($.id),onClick:me=>{ae($.id,me)||p?.($.id)}},$.id))})]},B.id))})),y&&r.jsx(ou,{hints:w?Vp(w.handlers):bo}),R]})}function wo({triggerLabel:e,triggerIcon:t,triggerText:s,items:n,align:a="end",touch:o=!0,className:i,triggerClassName:c,nested:u=!1,children:m}){const[d,f]=l.useState(!1),h=l.useRef(null);return l.useEffect(()=>{if(!d)return;const v=p=>{h.current&&!h.current.contains(p.target)&&f(!1)},x=p=>{p.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",x),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",x)}},[d]),n.length===0&&!m?null:r.jsxs("div",{ref:h,className:Q("relative",i),...u?{role:"none"}:{},children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:t??r.jsx(Gc,{className:"size-5"}),onClick:()=>f(v=>!v),"aria-label":e,"aria-haspopup":"menu","aria-expanded":d,...u?{role:"menuitem"}:{},className:Q(o&&"min-h-11 min-w-11 px-0",c),children:s}),d&&r.jsxs("div",{role:"menu",className:Q("absolute top-full z-50 mt-1 flex max-h-[60dvh] min-w-44 flex-col overflow-y-auto overscroll-contain rounded-md border border-line bg-surface py-1 shadow-lg",a==="end"?"right-0":"left-0"),children:[n.map(v=>r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{f(!1),v.onSelect()},className:"flex min-h-11 items-center gap-3 px-4 py-2.5 text-left text-sm text-fg transition-colors hover:bg-surface-sunken",children:[v.icon&&r.jsx("span",{className:"shrink-0 text-fg-subtle",children:v.icon}),v.label]},v.key)),m]})]})}const Gs="min-h-11 min-w-11 px-0";function gu({hasThread:e,onReply:t,onReplyAll:s,onForward:n,isStarred:a,onToggleStar:o,onDelete:i,isRead:c,onToggleRead:u,moveSlot:m,overflowItems:d=[],onUnavailable:f,unavailableHint:h,className:v}){const x=(b,y)=>()=>{if(!e){f?.(b);return}y?.()},p=u?[{key:"toggle-read",label:c?"Mark as unread":"Mark as read",icon:c?r.jsx(Tc,{className:"size-4"}):r.jsx(vr,{className:"size-4"}),onSelect:x("toggleRead",u)}]:[];return r.jsxs("div",{className:Q("relative",v),children:[r.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-0.5 bg-canvas px-1",children:[t&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Zc,{className:"size-5"}),onClick:x("reply",t),"aria-label":"Reply",title:"Reply",className:Gs}),s&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Jc,{className:"size-5"}),onClick:x("replyAll",s),"aria-label":"Reply all",title:"Reply all",className:Gs}),n&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Yc,{className:"size-5"}),onClick:x("forward",n),"aria-label":"Forward",title:"Forward",className:Gs}),r.jsx("div",{className:"flex-1"}),o&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Xt,{className:Q("size-5",a&&"fill-warning text-warning")}),onClick:x("star",o),"aria-label":a?"Unstar":"Star","aria-pressed":a,title:a?"Unstar":"Star",className:Gs}),m,i&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Lt,{className:"size-5"}),onClick:x("delete",i),"aria-label":"Move to Trash",title:"Move to Trash",className:Gs}),r.jsx(wo,{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 Sg({open:e=!1,enabled:t=!0,onToggle:s,className:n}){return r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(uc,{className:"size-4"}),title:"Intelligence","aria-label":e?"Hide intelligence sidebar":"Show intelligence sidebar","aria-pressed":e,disabled:!t,onClick:s,className:Q(e&&"bg-accent-2-soft text-accent-2",n)})}function Cg({hasThread:e,onUnavailable:t,unavailableHint:s,isStarred:n,showTriage:a=!0,onReply:o,onReplyAll:i,onForward:c,onDelete:u,onToggleStar:m,moveSlot:d,onMove:f,replyTitle:h="Reply (r)",replyAllTitle:v="Reply all (a)",forwardTitle:x="Forward (f)",deleteTitle:p="Move to Trash (#)",flagTitle:b="Star (s)",children:y,className:S}){const g=(w,C)=>()=>{if(!e){t?.(w);return}C?.()};return r.jsxs("div",{className:"relative",children:[r.jsxs("header",{className:Q("flex h-pane-header shrink-0 items-center gap-1 border-b border-line bg-surface px-3",S),children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Zc,{className:"size-4"}),title:h,"aria-label":"Reply",onClick:g("reply",o)}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Jc,{className:"size-4"}),title:v,"aria-label":"Reply all",onClick:g("replyAll",i)}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Yc,{className:"size-4"}),title:x,"aria-label":"Forward",onClick:g("forward",c)}),a&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"mx-1 h-4 w-px bg-line","aria-hidden":!0}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Lt,{className:"size-4"}),title:p,"aria-label":"Move to Trash",onClick:g("delete",u)}),d??r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(za,{className:"size-4"}),title:"Move to mailbox","aria-label":"Move to mailbox",onClick:g("move",f)}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Xt,{className:Q("size-4",n&&"fill-warning text-warning")}),title:b,"aria-label":"Star",onClick:g("flag",m)})]}),r.jsx("div",{className:"flex-1"}),y]}),!e&&s&&r.jsx("p",{role:"status",className:"border-b border-line bg-surface-sunken px-3 py-1 text-2xs text-fg-subtle",children:s})]})}const kg=(e,t)=>{const n=e==="newsletter"||e==="marketing"||t;return{framed:n,isPlain:!n}},jg=()=>`
|
|
9
9
|
/* Zero the UA default body margin and clamp the document to the iframe width so
|
|
10
10
|
wide author markup can't push the body (and the page) past the viewport. */
|
|
11
11
|
html, body {
|
|
@@ -43,17 +43,17 @@ pre, code {
|
|
|
43
43
|
overflow-wrap: anywhere;
|
|
44
44
|
word-break: break-word;
|
|
45
45
|
}
|
|
46
|
-
`,
|
|
46
|
+
`,Ng=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,""))},Eg=/^(none|transparent|inherit|initial|unset)\s*$/i,Ig=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},Rg=e=>{const t=/background(?:-color)?\s*:\s*([^;}\n]+)/gi;let s;for(s=t.exec(e);s!==null;){const n=s[1].trim();if(!Eg.test(n))return!0;s=t.exec(e)}return!1},Tg=e=>{if(/\bstyle\s*=\s*["'][^"']*background/i.test(e)||/\bbgcolor\s*=/i.test(e))return!0;for(const t of Ig(e))if(Rg(t))return!0;return!1},Mg=["script","iframe","object","embed","form","input","button","textarea","select","meta","link","base"],Ag=["onerror","onload","onclick","onmouseover","onmouseout","onfocus","onblur","onsubmit","onkeydown","onkeyup","formaction","xlink:href","data-bind"],Og="data:image/svg+xml,"+encodeURIComponent(`
|
|
47
47
|
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
|
|
48
48
|
<rect fill="#f0f0f0" width="100" height="100"/>
|
|
49
49
|
<text x="50" y="50" text-anchor="middle" dy=".3em" fill="#999" font-size="12">
|
|
50
50
|
Image blocked
|
|
51
51
|
</text>
|
|
52
52
|
</svg>
|
|
53
|
-
`),
|
|
53
|
+
`),Dg=e=>e.replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Pg=e=>e.replace(/@import[^;]*;/gi,"/* @import blocked */").replace(/url\s*\([^)]*\)/gi,"none").replace(/expression\s*\([^)]*\)/gi,"").replace(/-moz-binding\s*:[^;]*/gi,""),Lg=(e={})=>{const t=dc(),s={FORBID_TAGS:Mg,FORBID_ATTR:Ag,ALLOW_DATA_ATTR:!1,ALLOW_UNKNOWN_PROTOCOLS:!1};return t.addHook("afterSanitizeAttributes",n=>{if(n.tagName==="IMG"){const a=n.getAttribute("src")||"";if(a.startsWith("data:"))return;if(a.startsWith("cid:")){const i=a.slice(4).replace(/^<|>$/g,""),c=e.resolveCid?.(i);c&&(n.setAttribute("src",c),n.classList.add("inline-content"));return}e.allowExternalImages||(n.setAttribute("data-blocked-src",a),n.setAttribute("src",Og),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",Dg(a))}}),t.addHook("uponSanitizeElement",(n,a)=>{if(a.tagName==="style"){const o=n.textContent||"";n.textContent=Pg(o)}}),n=>{const a=Tg(n),o=t.sanitize(n,s);return{html:`<style>${jg()}</style>${o}`,hasAuthorBackground:a}}},Fg='"Geist Variable", "Geist", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',Ti={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)"}},$g=/prefers-color-scheme\s*:\s*dark|color-scheme\s*:\s*[^;}"']*\bdark\b/i,Mi='<meta name="viewport" content="width=device-width, initial-scale=1">',_g=e=>{const t=e?Ti.dark:Ti.light;return`
|
|
54
54
|
/* Plain-email base: UI font-stack + theme-aware colors (#424) */
|
|
55
55
|
html, body {
|
|
56
|
-
font-family: ${
|
|
56
|
+
font-family: ${Fg};
|
|
57
57
|
font-size: 14px;
|
|
58
58
|
line-height: 1.6;
|
|
59
59
|
color: ${t.fg};
|
|
@@ -71,9 +71,9 @@ a, a:visited {
|
|
|
71
71
|
color: ${t.accent} !important;
|
|
72
72
|
text-decoration: underline;
|
|
73
73
|
}
|
|
74
|
-
`},Fg=(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}",$g=(e,t,s)=>{if(t==="plain")return`${Mi}<style>${Lg(s)}</style>${e}`;const n=Pg.test(e);return`${Mi}<style>${Fg(s,n)}</style>${e}`},_g=5e4,zg=1e4,Bg="(max-width: 640px)",Ug=.4,Kg="allow-same-origin allow-popups allow-popups-to-escape-sandbox",Ai=(e,t,s)=>Math.min(Math.ceil(Math.max(e,t)),s),qg=(e,t)=>e<=0||t<=0||e<=t?1:Math.max(Ug,t/e),Hg=e=>{const[t,s]=l.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return l.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Wg=new Set(["Enter","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"]),Vg=e=>e===" "?!1:e.length===1?!0:Wg.has(e),Oi=e=>{if(e.metaKey||e.ctrlKey||e.altKey||!Vg(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}))},Di=({html:e,variant:t="framed",isDark:s=!1,className:n})=>{const a=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(0),[u,m]=l.useState(0),[d,f]=l.useState(0),h=Hg(Bg),v=l.useMemo(()=>$g(e,t,s),[e,t,s]);l.useEffect(()=>{const g=a.current;if(!g)return;const w=()=>f(R=>R===g.clientWidth?R:g.clientWidth);w();const C=new ResizeObserver(w);return C.observe(g),()=>C.disconnect()},[]),l.useEffect(()=>{const g=o.current;if(!g)return;const w=()=>{const k=g.contentDocument;if(!k?.body)return;const M=k.documentElement,P=Ai(k.body.scrollHeight,M?.scrollHeight??0,_g);c(L=>L===P?L:P);const E=Ai(k.body.scrollWidth,M?.scrollWidth??0,zg);m(L=>L===E?L:E)};let C,R;const O=()=>{w();const k=g.contentDocument;k?.body&&(C=new ResizeObserver(w),C.observe(k.body),k.documentElement&&C.observe(k.documentElement),k.addEventListener("keydown",Oi),R=k)};return g.addEventListener("load",O),()=>{g.removeEventListener("load",O),R?.removeEventListener("keydown",Oi),C?.disconnect()}},[]);const x=h?qg(u,d):1,p=x<1,b=p?`${u}px`:h?"100%":t==="framed"&&u>0?`max(100%, ${u}px)`:u===0?"100%":`${u}px`,y=i===0?"1px":`${i}px`,S=r.jsx("iframe",{ref:o,title:"Email content",sandbox:Kg,srcDoc:v,className:p?void 0:n,scrolling:"no",style:{width:b,maxWidth:p?"none":void 0,border:"none",display:"block",height:y,overflow:"hidden",transform:p?`scale(${x})`:void 0,transformOrigin:p?"top left":void 0,colorScheme:"normal"}});return r.jsx("div",{ref:a,className:p?n:void 0,children:p?r.jsx("div",{style:{width:"100%",height:`${Math.ceil(i*x)}px`,overflow:"hidden"},children:S}):S})},Pi=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),xu=({html:e,text:t,isDark:s=!1,category:n,allowImages:a=!1,resolveCid:o,className:i,renderBlockedNotice:c})=>{const u=l.useMemo(()=>!e||typeof document>"u"?null:Og({allowExternalImages:a,resolveCid:o})(e),[e,a,o]),m=u?.html??null,{framed:d,isPlain:f}=wg(n,u?.hasAuthorBackground??!1),h=l.useMemo(()=>!m||a?0:(m.match(/data-blocked-src/g)||[]).length,[m,a]);return!m&&!t?r.jsx("div",{className:Q("message-body",i),children:r.jsx(Pi,{})}):r.jsxs("div",{className:Q("message-body",i),children:[h>0&&r.jsx("div",{className:"message-body-notice",children:c?.(h)}),m?d?r.jsx("div",{className:"w-full max-w-full overflow-x-auto",children:r.jsx(Di,{html:m,variant:"framed",isDark:s})}):r.jsx("div",{className:"max-w-full overflow-x-auto lg:max-w-2xl",children:r.jsx(Di,{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(Pi,{})]})};function zs({message:e="Select a thread to read",icon:t,showHints:s=!0,className:n}){return r.jsxs("div",{className:Q("flex flex-1 flex-col items-center justify-center text-center",n),children:[t??r.jsx(Ba,{className:"size-10 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:e}),s&&r.jsxs("p",{className:"text-2xs text-fg-subtle",children:[r.jsx(Is,{children:"j"})," / ",r.jsx(Is,{children:"k"})," to move, ",r.jsx(Is,{children:"Enter"})," to open"]})]})}function bu({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(jt,{name:e.fromName,email:e.fromEmail,size:"md"}),n&&r.jsx("span",{className:"absolute -top-0.5 -right-0.5 size-2 rounded-full border border-canvas bg-accent"})]}),r.jsx("span",{className:Q("w-36 shrink-0 truncate text-sm",n?"font-semibold text-fg":"font-medium text-fg-muted"),children:e.fromName}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-fg-subtle",children:e.snippet}),a??r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.dateLabel})]}),i=Q("group flex h-section-row w-full items-center gap-3 border-b border-line px-2 text-left transition-colors hover:bg-surface-sunken lg:px-4",s&&"bg-surface-sunken ring-1 ring-inset ring-accent/30");return t?r.jsx("div",{role:"button",tabIndex:0,"aria-expanded":!1,onClick:t,onKeyDown:c=>{rm(c)&&(c.preventDefault(),t())},className:Q(i,"cursor-pointer"),children:o}):r.jsx("div",{className:i,children:o})}function vu({message:e,warning:t,onHeaderClick:s,isFocused:n,senderBadge:a,trailing:o,to:i,indicators:c,actionMenu:u,actionBar:m,body:d}){const f=r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[r.jsxs("span",{className:"text-sm font-semibold text-fg",children:[e.fromName,a]}),o??r.jsx("span",{className:"text-2xs text-fg-subtle",children:e.dateLabel})]}),r.jsx("div",{className:"text-xs text-fg-subtle",children:e.fromEmail}),i!==null&&r.jsx("div",{className:"text-xs text-fg-subtle",children:i??r.jsxs(r.Fragment,{children:["to ",e.toLabel]})})]});return r.jsxs("div",{className:Q("px-2 py-3 lg:px-4",n&&"ring-1 ring-inset ring-accent/30"),children:[r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(Qt,{className:"mt-1 size-3.5 shrink-0 text-fg-subtle"}),r.jsx(jt,{name:e.fromName,email:e.fromEmail,size:"md"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[s?r.jsx("button",{type:"button",onClick:s,className:"w-full text-left",children:f}):f,c]}),u&&r.jsx("div",{className:"shrink-0",children:u})]}),t&&r.jsxs("div",{className:"mt-3 flex items-start gap-3 rounded-md bg-danger-soft p-3",children:[r.jsx($s,{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(xu,{className:"mt-3",html:e.bodyHtml,category:e.framed?"newsletter":"personal",allowImages:!0})})]})}function Qg({thread:e,onBack:t,intelligence:s,intelligenceOpen:n,onToggleIntelligence:a,actions:o,children:i,touchHandlers:c}){const[u,m]=l.useState(!1),d=a!==void 0,f=d?n??!1:u,h=!!s||d,v=()=>{if(d){a?.();return}m(p=>!p)},x=()=>{if(d){f&&a?.();return}m(!1)};return r.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Ua,{className:"size-4"}),onClick:t,"aria-label":"Back to messages",className:"-ml-1 shrink-0"}),r.jsx("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e.subject}),h&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(uc,{className:"size-4"}),onClick:v,"aria-label":f?"Hide intelligence panel":"Show intelligence panel","aria-pressed":f,title:"Intelligence",className:Q("shrink-0",f&&"bg-accent-2-soft text-accent-2")})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",style:c?{touchAction:"pan-y"}:void 0,...c,children:i??e.messages.map(p=>{const b=y=>y?()=>y(p.id):void 0;return p.expanded?r.jsx(vu,{message:p,warning:e.warning,onHeaderClick:b(o?.onToggleExpand),actionBar:r.jsx(gu,{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(bu,{message:p,onClick:b(o?.onToggleExpand)},p.id)})}),s&&!d&&r.jsx(am,{open:f,onClose:x,title:"Intelligence",anchor:"right",className:"p-0",children:r.jsx(tu,{data:s,onClose:x,className:"h-full w-full border-l-0"})})]})}const Gg="button:not([disabled]), a[href]",us="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface-sunken";function Yg({active:e,dimmed:t,indent:s}){return Q("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors",us,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 Xg({icon:e,label:t,count:s,active:n}){return r.jsxs(r.Fragment,{children:[e&&r.jsx("span",{className:Q("shrink-0",n?"text-accent-2":"text-fg-subtle"),children:e}),r.jsx("span",{className:"flex-1 truncate",children:t}),s!=null&&s>0&&r.jsx("span",{className:Q("text-2xs tabular-nums",n?"text-accent-2":"text-fg-subtle"),children:s})]})}function rn({icon:e,label:t,count:s,active:n,dimmed:a,indent:o,navId:i,linkComponent:c,ariaLabel:u,title:m,onClick:d}){const f=Yg({active:n,dimmed:a,indent:o}),h=r.jsx(Xg,{icon:e,label:t,count:s,active:n});return i&&c?c({navId:i,className:f,ariaLabel:u??t,title:m,onClick:d,children:h}):r.jsx("button",{type:"button",onClick:d,className:f,"aria-label":u,title:m,children:h})}const Li={inbox:0,flagged:1,drafts:2,sent:3,archive:4,all:5,junk:6,trash:7};function Jg(e){switch(e){case"inbox":return r.jsx(Ba,{className:"size-4"});case"flagged":return r.jsx(Xt,{className:"size-4"});case"drafts":return r.jsx(fc,{className:"size-4"});case"sent":return r.jsx(pn,{className:"size-4"});case"archive":return r.jsx(cm,{className:"size-4"});case"all":return r.jsx(lm,{className:"size-4"});case"junk":return r.jsx(im,{className:"size-4"});case"trash":return r.jsx(Lt,{className:"size-4"})}}const Fi=e=>e.role!=null,Gr=8,$i="remit.nav.folders.open.",_i="remit.nav.account.open.";function zi(e,t,s){if(typeof localStorage>"u")return s;const n=localStorage.getItem(e+t);return n===null?s:n!=="0"}function Bi(e,t,s){typeof localStorage>"u"||localStorage.setItem(e+t,s?"1":"0")}function Zg({query:e,onSelect:t,onRemove:s}){return r.jsxs("div",{className:"group flex w-full items-center gap-1 rounded-md pr-1 hover:bg-surface",children:[r.jsxs("button",{type:"button",onClick:t,className:Q("flex min-w-0 flex-1 items-center gap-2 px-2 py-1 text-left text-sm text-fg-muted transition-colors hover:text-fg",us),children:[r.jsx(ir,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate",children:e})]}),s&&r.jsx("button",{type:"button",onClick:s,"aria-label":`Remove saved search: ${e}`,className:Q("shrink-0 rounded-full p-1 text-fg-subtle opacity-0 transition-opacity hover:bg-surface-sunken hover:text-fg group-hover:opacity-100 focus-visible:opacity-100",us),children:r.jsx(Nt,{className:"size-3.5"})})]})}function ex({savedSearches:e,saveableQuery:t,onSelectSavedSearch:s,onRemoveSavedSearch:n,onSaveCurrentSearch:a}){return e.length===0&&!t?null:r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:"px-2 pb-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Saved searches"}),t&&r.jsxs("button",{type:"button",onClick:a,className:Q("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-accent transition-colors hover:bg-surface",us),children:[r.jsx(Rp,{className:"size-4 shrink-0"}),r.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Save “",t,"”"]})]}),e.map(o=>r.jsx(Zg,{query:o,onSelect:()=>s?.(o),onRemove:n?()=>n(o):void 0},o))]})}function tx({account:e,selectedNavId:t,onSelectNav:s,linkComponent:n}){const[a,o]=l.useState(()=>zi(_i,e.id,!0)),[i,c]=l.useState(()=>zi($i,e.id,!0)),[u,m]=l.useState(!1),d=()=>{o(S=>{const g=!S;return Bi(_i,e.id,g),g})},f=()=>{c(S=>{const g=!S;return Bi($i,e.id,g),g})},h=e.mailboxes.filter(Fi).sort((S,g)=>Li[S.role]-Li[g.role]),v=e.mailboxes.filter(S=>!Fi(S)),x=u||v.length<=Gr?v:v.slice(0,Gr),p=v.length-x.length,b=e.status??"ready",y=b==="ready"&&h.length===0&&v.length===0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("button",{type:"button",onClick:d,"aria-expanded":a,className:Q("flex w-full items-center gap-1.5 px-2 pb-1 text-left transition-colors hover:text-fg",us,e.muted&&"opacity-55"),children:[a?r.jsx(Qt,{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(Wc,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:"muted"})]})]}),a&&r.jsxs(r.Fragment,{children:[b==="loading"&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"Loading…"}),b==="error"&&r.jsxs("div",{role:"alert",className:"mx-2 my-1 flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-2 py-1.5 text-sm",children:[r.jsx(Pt,{className:"mt-0.5 size-4 shrink-0 text-danger","aria-hidden":"true"}),r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx("p",{className:"font-medium text-danger",children:"Couldn't load mailboxes"})}),e.onRetry&&r.jsx("button",{type:"button",onClick:e.onRetry,className:"shrink-0 text-sm font-medium text-accent hover:underline",children:"Retry"})]}),y&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"No mailboxes"}),b==="ready"&&r.jsxs(r.Fragment,{children:[h.map(S=>r.jsx(rn,{navId:S.id,linkComponent:n,icon:Jg(S.role),label:S.name,ariaLabel:S.name,title:S.fullPath??S.name,count:S.unseen,active:t===S.id,dimmed:e.muted,onClick:()=>s?.(S.id)},S.id)),e.outboxPending!==void 0&&r.jsx(rn,{navId:"outbox",linkComponent:n,icon:r.jsx(pn,{className:"size-4"}),label:"Outbox",ariaLabel:"Outbox",count:e.outboxPending>0?e.outboxPending:void 0,active:t==="outbox",dimmed:e.muted,onClick:()=>s?.("outbox")}),v.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",onClick:f,"aria-expanded":i,className:Q("mt-1 flex w-full items-center gap-1 px-2 py-1 text-left text-2xs font-semibold uppercase tracking-wider text-fg-subtle transition-colors hover:text-fg",us),children:[i?r.jsx(Qt,{className:"size-3 shrink-0"}):r.jsx(Ms,{className:"size-3 shrink-0"}),r.jsx("span",{className:"flex-1",children:"Folders"}),r.jsx("span",{className:"tabular-nums opacity-70",children:v.length})]}),i&&r.jsxs(r.Fragment,{children:[x.map(S=>r.jsx(rn,{navId:S.id,linkComponent:n,icon:r.jsx(om,{className:"size-4"}),label:S.name,ariaLabel:S.name,title:S.fullPath??S.name,count:S.unseen,active:t===S.id,dimmed:e.muted,onClick:()=>s?.(S.id)},S.id)),(p>0||u)&&v.length>Gr&&r.jsx("button",{type:"button",onClick:()=>m(S=>!S),className:Q("ml-7 flex items-center px-2 py-1 text-2xs font-medium text-accent transition-colors hover:underline",us),children:u?"Show less":`Show all (${v.length})`})]})]})]})]})]})}function sx({accounts:e,selectedNavId:t,briefUnseen:s,onSelectNav:n,variant:a="desktop",linkComponent:o,savedSearches:i=[],saveableQuery:c,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:d}){const f=l.useRef(null);or({containerRef:f,itemSelector:Gg});const h=a==="drawer",v=r.jsxs("nav",{ref:h?f:void 0,className:h?"px-2 py-2":"flex-1 overflow-y-auto px-2 py-2","aria-label":"Mailboxes",children:[r.jsx(rn,{navId:"brief",linkComponent:o,icon:r.jsx(Dt,{className:"size-4"}),label:"Daily brief",ariaLabel:"Daily brief",count:s,active:t==="brief",onClick:()=>n?.("brief")}),r.jsx(rn,{navId:"flagged",linkComponent:o,icon:r.jsx(Xt,{className:"size-4"}),label:"Starred",ariaLabel:"Starred",active:t==="flagged",onClick:()=>n?.("flagged")}),r.jsx(ex,{savedSearches:i,saveableQuery:c,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:d}),e.length===0?r.jsx("div",{className:"px-2 py-4 text-center text-sm text-fg-muted",children:"No accounts configured"}):e.map(x=>r.jsx(tx,{account:x,selectedNavId:t,onSelectNav:n,linkComponent:o},x.id))]});return h?v:r.jsx("aside",{ref:f,className:"flex h-full w-full flex-col bg-surface-sunken",children:v})}function nx({leading:e,search:t,actions:s,className:n}){return r.jsxs("header",{className:Q("flex min-h-pane-header w-full shrink-0 items-center gap-2 border-b border-line bg-canvas px-row-inset py-1",n),children:[e&&r.jsx("div",{className:"flex shrink-0 items-center gap-1",children:e}),r.jsx("div",{className:"flex min-w-0 flex-1 justify-start",children:r.jsx("div",{className:"w-full max-w-xs transition-[max-width] duration-150 ease-out focus-within:max-w-lg",children:t})}),s&&r.jsx("div",{className:"flex shrink-0 items-center gap-1",children:s})]})}const rx=/[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069\ufeff]/g,ax=/[<>:"|?*]/g,ox=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,Ui=120,ix=12,lx="attachment",Ki=e=>{const t=[...e];if(t.length<=Ui)return e;const s=e.lastIndexOf("."),n=s>0&&[...e.slice(s)].length<=ix?e.slice(s):"",a=Ui-[...n].length;return t.slice(0,a).join("")+n},cx=(e,t=lx)=>{const n=e.replace(rx,"").split(/[/\\]/),o=(n[n.length-1]??"").replace(ax,"_").replace(/^[.\s]+/,"").replace(/[.\s]+$/,"");if(o.length===0)return Ki(t);const i=ox.test(o)?`_${o}`:o;return Ki(i)},qi=["KB","MB","GB","TB"],ux=e=>{if(!Number.isFinite(e)||e<0)return"unknown size";const t=Math.round(e);if(t<1024)return t===1?"1 byte":`${t} bytes`;const s=1023.95;let n=t/1024,a=0;for(;n>=s&&a<qi.length-1;)n/=1024,a+=1;return`${n.toFixed(1).replace(/\.0$/,"")} ${qi[a]}`};function dx({state:e,onRetry:t}){return r.jsxs("div",{role:"alert","data-testid":"attachment-error",className:"flex items-start gap-2 border-t border-danger/30 bg-danger-soft px-2 py-2 text-xs",children:[r.jsx(Pt,{className:"mt-0.5 size-3.5 shrink-0 text-danger","aria-hidden":!0}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"font-medium text-danger",children:e.title}),r.jsx("p",{className:"mt-0.5 text-fg-muted",children:e.detail})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[r.jsx("button",{type:"button",onClick:t,className:"font-medium text-accent hover:underline",children:"Try again"}),e.reportUrl&&r.jsx("a",{href:e.reportUrl,target:"_blank",rel:"noreferrer",className:"font-medium text-accent hover:underline",children:"Report this"})]})]})}function fx({attachments:e,onDownload:t,hasUnlistedAttachment:s=!1,className:n}){return e.length===0&&!s?null:r.jsxs("section",{"aria-label":"Attachments","data-testid":"attachment-list",className:Q("space-y-1.5",n),children:[r.jsxs("h3",{className:"flex items-center gap-1.5 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:[r.jsx(yr,{className:"size-3","aria-hidden":!0}),e.length===0?"Attachment":e.length===1?"1 attachment":`${e.length} attachments`]}),e.length>0&&r.jsx("ul",{className:"overflow-hidden rounded-sm border border-line bg-surface",children:e.map(a=>{const o=a.download.status==="downloading";return r.jsxs("li",{className:"border-t border-line first:border-t-0",children:[r.jsxs("button",{type:"button",onClick:()=>t(a.attachmentId),disabled:o,"data-testid":"attachment-download","aria-label":`Download ${a.filename}`,className:"flex w-full items-center gap-2 px-2 py-2 text-left transition-colors hover:bg-surface-sunken disabled:cursor-progress disabled:opacity-60",children:[r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsx("bdi",{className:"block truncate text-sm text-fg",title:a.filename,children:a.filename}),r.jsxs("span",{className:"block truncate text-2xs text-fg-subtle",children:[a.typeLabel," ·"," ",ux(a.sizeOctets)]})]}),o?r.jsx(hs,{className:"size-4 shrink-0 animate-spin text-fg-subtle","aria-hidden":!0}):r.jsx(qh,{className:"size-4 shrink-0 text-fg-subtle","aria-hidden":!0})]}),a.download.status==="failed"&&r.jsx(dx,{state:a.download,onRetry:()=>t(a.attachmentId)})]},a.attachmentId)})}),s&&r.jsx("p",{role:"alert","data-testid":"attachment-unlisted",className:"rounded-sm border border-line bg-surface px-2 py-2 text-xs text-fg-muted",children:"The mail server says this message carries an attachment, but none of its parts describe one. Re-sync the account from Settings; if the attachment still does not appear, the message is worth reporting."})]})}function mx({label:e,onUndo:t,undoLabel:s="Undo",filtersHref:n,className:a}){return r.jsxs(kt,{tone:"accent",className:Q("py-1 text-xs",a),children:[r.jsx(Lp,{className:"size-3.5 shrink-0","aria-hidden":!0}),r.jsx("span",{children:e}),t&&r.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),t()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:s}),n&&r.jsx("a",{href:n,onClick:o=>{o.stopPropagation()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:"Manage filter"})]})}function hx({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(hs,{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:px(e)})]}):r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[r.jsx(Dt,{className:"size-8 text-fg-subtle","aria-hidden":"true"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"You're caught up"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Nothing needs attention."})]})}function px({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 gx="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",Hi="pointer-events-none absolute inset-0 m-auto size-3.5 text-accent-fg";function So({label:e,description:t,indeterminate:s=!1,checked:n,onChange:a,className:o,...i}){const c=l.useRef(null);l.useEffect(()=>{c.current&&(c.current.indeterminate=s)},[s]);const u=r.jsxs("span",{className:"relative inline-flex",children:[r.jsx("input",{ref:c,type:"checkbox",checked:n,onChange:a,className:gx,...i}),r.jsx(hn,{className:Q(Hi,"hidden peer-checked:block"),"aria-hidden":!0}),r.jsx(Ap,{className:Q(Hi,"hidden peer-indeterminate:block"),"aria-hidden":!0})]});return e===void 0&&t===void 0?r.jsx("span",{className:o,children:u}):r.jsxs("label",{className:Q("flex min-h-11 cursor-pointer items-center gap-3 text-left",o),children:[u,r.jsxs("span",{className:"flex min-w-0 flex-col",children:[e!==void 0&&r.jsx("span",{className:"text-sm text-fg",children:e}),t!==void 0&&r.jsx("span",{className:"text-xs text-fg-subtle",children:t})]})]})}const xx=({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 bx({onSend:e,onDiscard:t,sending:s,canSend:n,saveStatus:a="idle",unavailableReason:o,onUnavailable:i}){return r.jsxs("div",{className:"flex items-center justify-between border-t border-line px-3 py-2",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(ce,{variant:"primary",size:"md","aria-busy":s,title:n?void 0:o,className:"min-h-11 rounded-full px-4",icon:s?r.jsx(hs,{className:"size-4 animate-spin"}):r.jsx(pn,{className:"size-4"}),onClick:()=>{if(!s){if(!n){o&&i?.(o);return}e()}},children:"Send"}),r.jsx(xx,{status:a})]}),r.jsx(ce,{variant:"ghost",size:"md","aria-busy":s,"aria-label":"Discard",className:"min-h-11 min-w-11 px-2 hover:text-danger",icon:r.jsx(Lt,{className:"size-4"}),onClick:()=>{s||t()}})]})}const vx=["Tab",","],Wi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),yx=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(Wi(a))return{email:a,displayName:n}}if(Wi(t))return{email:t}},wx=({label:e,addresses:t,onChange:s,placeholder:n,suggestions:a=[],onQueryChange:o})=>{const[i,c]=l.useState(""),u=l.useRef(null),m=new Set(t.map(g=>g.email.toLowerCase())),d=i.length>=2?a.filter(g=>!m.has(g.email.toLowerCase())):[],f=l.useCallback(g=>{m.has(g.email.toLowerCase())||(s([...t,g]),c(""),o?.(""))},[t,m,s,o]),h=l.useCallback(g=>{s(t.filter((w,C)=>C!==g))},[t,s]),v=l.useCallback(g=>{f(g),u.current?.focus()},[f]),x=l.useCallback(()=>{const g=yx(i);g&&f(g)},[i,f]),p=mc({count:d.length,acceptKeys:vx,onAccept:g=>v(d[g])}),b=l.useMemo(()=>d.map(g=>({value:g.email,label:g.displayName??g.email,...g.displayName?{hint:g.email}:{}})),[d]),y=l.useCallback(g=>{if(g.key==="Backspace"&&i===""&&t.length>0){h(t.length-1);return}p.handleKeyDown(g)||(g.key==="Enter"||g.key==="Tab"||g.key===",")&&i.trim()&&(g.preventDefault(),x())},[i,t.length,h,p.handleKeyDown,x]),S=l.useCallback(()=>{setTimeout(()=>{x(),p.dismiss()},150)},[x,p.dismiss]);return r.jsxs("div",{className:"relative",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),r.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>u.current?.focus(),onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&u.current?.focus()},children:[t.map((g,w)=>r.jsx(_p,{email:g.email,displayName:g.displayName,onRemove:()=>h(w)},g.email)),r.jsx("input",{ref:u,id:`address-field-${e}`,type:"text",value:i,onChange:g=>{p.reopen(),c(g.target.value),o?.(g.target.value)},onKeyDown:y,onBlur:S,placeholder:t.length===0?n:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5",autoComplete:"off",...p.comboboxProps})]})]}),p.open&&r.jsx(hc,{id:p.listId,suggestions:b,activeIndex:p.activeIndex,optionId:p.optionId,onPick:g=>{const w=d.find(C=>C.email===g.value);w&&v(w)},onHighlight:p.setActiveIndex,label:`${e} suggestions`,className:"absolute left-12 right-0 z-50 mt-1 max-h-[200px] shadow-lg"})]})};function Sx({banner:e,header:t,children:s,quoted:n,actionBar:a}){return r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e,t,r.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-auto","data-testid":"compose-body-area",children:[s,n&&r.jsx("div",{className:"shrink-0 px-3 pb-2",children:n})]}),a]})}const Yr=({label:e,onClick:t})=>r.jsx("button",{type:"button",onClick:t,className:"text-xs text-fg-muted hover:text-fg transition-colors",children:e}),Cx=({to:e,cc:t,bcc:s,subject:n})=>{const a=[];return e.length>0&&a.push(`To: ${e.map(o=>o.displayName??o.email).join(", ")}`),t.length>0&&a.push(`Cc: ${t.length}`),s.length>0&&a.push(`Bcc: ${s.length}`),n&&a.push(n),a.join(" · ")},kx=({collapsed:e=!1,summary:t="",from:s,to:n,cc:a,bcc:o,subject:i,onShowCc:c,onShowBcc:u})=>e?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[r.jsx("span",{className:"truncate text-xs text-fg-muted",children:t||"…"}),r.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]}):r.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[s,n,a??r.jsxs("div",{className:"flex gap-2 pl-14",children:[r.jsx(Yr,{label:"Cc",onClick:c}),r.jsx(Yr,{label:"Bcc",onClick:u})]}),a&&!o&&r.jsx("div",{className:"pl-14",children:r.jsx(Yr,{label:"Bcc",onClick:u})}),o,i]}),jx=({onConfigure:e})=>r.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[r.jsx(Ka,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),r.jsxs("button",{type:"button",onClick:e,className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",r.jsx(um,{className:"size-3","aria-hidden":"true"})]})]})]}),Nx=({value:e,onChange:t})=>r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),r.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]});function Ex({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 Ix({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 Rx(e,t){const s=t-1;return s<=0?null:e<s?e:s-1}const Tx=e=>e instanceof HTMLElement?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable:!1,Mx=({chips:e=[],onRemoveChip:t,value:s,onChange:n,onClear:a,onClearQuery:o,placeholder:i="Search mail...",globalFocusKey:c=!0,showClearButton:u=!0,size:m="sm",inputId:d,suggest:f,className:h})=>{const v=l.useId(),x=d??v,p=l.useRef(null),b=l.useRef([]),y=o??a,[S,g]=l.useState(null),w=l.useRef(void 0),[C,R]=l.useState(""),O=e.length>0;l.useEffect(()=>{g(I=>I!==null&&I>=e.length?null:I)},[e.length]),l.useEffect(()=>{const I=w.current;if(I!==void 0){if(w.current=void 0,I===null){p.current?.focus();return}b.current[I]?.focus()}});const k=l.useRef(void 0);l.useEffect(()=>{const I=f?.caret;if(!I||I===k.current)return;k.current=I;const D=p.current;!D||D.ownerDocument.activeElement!==D||(D.setSelectionRange(I.cursor,I.cursor),f?.onCaretChange(I.cursor))});const M=I=>{f?.onCaretChange(I.selectionStart??I.value.length)},P=l.useCallback(I=>{g(I),w.current=I},[]),E=l.useCallback(I=>{const D=e[I];D&&t&&(P(Rx(I,e.length)),R(`${D.label} removed`),t(D.id))},[e,t,P]),L=l.useCallback(()=>{P(null),a()},[a,P]),A=l.useCallback(I=>{const D=I.currentTarget;if(f?.onKeyDown(I))return;const T=Ex({key:I.key,shiftKey:I.shiftKey,repeat:I.repeat,caretAtStart:D.selectionStart===0&&D.selectionEnd===0,hasValue:s.length>0,chipCount:e.length});switch(T.type){case"focusChip":I.preventDefault(),P(T.index);return;case"clearQuery":y();return;case"blur":D.blur();return;case"none":return}},[e.length,s,y,P,f]),j=l.useCallback(I=>D=>{const T=Ix({key:D.key,repeat:D.repeat,index:I,chipCount:e.length});switch(T.type!=="none"&&D.preventDefault(),T.type){case"removeChip":E(T.index);return;case"focusChip":P(T.index);return;case"focusInput":P(null);return;case"activateChip":return;case"none":return}},[e,E,P]);return l.useEffect(()=>{if(!c)return;const I=D=>{D.key!=="/"||D.metaKey||D.ctrlKey||D.altKey||Tx(D.target)||(D.preventDefault(),p.current?.focus())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[c]),r.jsxs("label",{htmlFor:x,className:Q("flex w-full items-center gap-1.5 text-sm","bg-surface-sunken/50 border border-transparent","focus-within:bg-canvas focus-within:border-line focus-within:ring-2 focus-within:ring-ring","transition-colors",m==="lg"?"rounded-xl px-4 py-2":"rounded-md px-2.5 py-1",h),children:[r.jsx(ir,{className:Q("shrink-0 text-fg-muted pointer-events-none",m==="lg"?"size-5":"size-4")}),r.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1",children:[O&&r.jsx("div",{role:"grid","aria-label":"Search filters",className:"flex min-w-0 flex-wrap items-center gap-1",children:e.map((I,D)=>r.jsx(dm,{ref:T=>{b.current[D]=T},label:I.label,tone:I.tone,focused:S===D,onFocusLabel:()=>g(D),onKeyDown:j(D),onRemove:()=>E(D)},I.id))}),r.jsx("input",{ref:p,id:x,name:"q",type:"text","aria-label":"Search mail",autoComplete:"off",value:s,tabIndex:S===null?0:-1,onChange:I=>{n(I.target.value),M(I.target)},onKeyDown:A,onKeyUp:I=>M(I.currentTarget),onClick:I=>M(I.currentTarget),onFocus:I=>{g(null),f?.onFocusChange?.(!0),M(I.currentTarget)},onBlur:()=>f?.onFocusChange?.(!1),...f?.comboboxProps,placeholder:O?void 0:i,className:"min-w-24 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted"})]}),(s||O)&&u&&r.jsx("button",{type:"button",onClick:L,className:"shrink-0 rounded p-0.5 hover:bg-surface-raised transition-colors","aria-label":"Clear search",children:r.jsx(Nt,{className:Q("text-fg-muted",m==="lg"?"size-5":"size-4")})}),r.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:C})]})},Co=({value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i="Search mail...",globalFocusKey:c=!0,showClearButton:u=!0,size:m,inputId:d,suggest:f,className:h})=>r.jsx(Mx,{value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i,globalFocusKey:c,showClearButton:u,size:m,inputId:d,suggest:f,className:h});function Ax(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 Ox({result:e,onClick:t,query:s,showFolder:n=!0}){const a=n&&e.folder?fm(e.folder):void 0;return r.jsx("button",{type:"button",onClick:t,className:Q("group",_s({}),"border-b border-line"),children:r.jsx(yo,{thread:Ax(e),highlightQuery:s,badge:r.jsxs(r.Fragment,{children:[a&&r.jsx(kt,{tone:"neutral",className:"shrink-0",children:a}),e.category&&r.jsx(kt,{tone:e.category.tone??"neutral",className:"shrink-0",children:e.category.label}),e.matchedChunkLabel&&r.jsx(kt,{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 Dx=e=>e===1?"result":"results";function yu({count:e,onScopeToSpam:t}){return r.jsx(gn,{tone:"info",variant:"soft",className:"items-center justify-between gap-3 rounded-none border-b border-line",children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("p",{className:"min-w-0 text-xs text-fg-muted",children:[r.jsx("span",{className:"font-semibold text-fg tabular-nums",children:e})," ",`${Dx(e)} from Spam`]}),r.jsx(ce,{variant:"ghost",size:"sm",onClick:t,className:"shrink-0 text-accent",children:"Go to Spam"})]})})}const Vi=6,Px={kind:"global"},Lx=e=>e.kind==="folder"&&e.role==="junk",Fx=e=>e.folder?.role==="junk";function ko(e){const t=[],s=[];for(const n of e)Fx(n)?s.push(n):t.push(n);return{kept:t,spam:s}}function wu({onClick:e,blockedReason:t}){const s=l.useId(),[n,a]=l.useState(!1);return r.jsxs("div",{className:"border-b border-line px-row-inset py-1.5",children:[r.jsxs("button",{type:"button",onClick:()=>{if(t){a(!0);return}e()},"aria-describedby":t?s:void 0,className:Q("flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs font-medium transition-colors",t?"text-fg-subtle opacity-55":"text-accent hover:bg-surface-sunken"),children:[r.jsx(mm,{className:"size-3.5 shrink-0","aria-hidden":"true"}),r.jsx("span",{children:"Make this a filter"})]}),t&&r.jsx(hm,{id:s,reason:t,nudged:n,className:"px-2 pt-1 text-2xs text-warning"})]})}function $x({section:e,query:t,onSelectResult:s,showFolder:n}){const[a,o]=l.useState(e.initialCollapsed??!1),[i,c]=l.useState(!1),u=e.results.length>Vi,d=!i&&u?e.results.slice(0,Vi):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(Qt,{className:Q("size-3 shrink-0 text-fg-subtle transition-transform duration-200",a?"rotate-0":"rotate-180")})]}),!a&&r.jsxs(r.Fragment,{children:[d.map(h=>r.jsx(Ox,{result:h,query:t,showFolder:n,onClick:s?()=>s(h):void 0},h.id)),u&&r.jsxs("button",{type:"button",onClick:()=>c(h=>!h),className:"flex w-full items-center justify-center border-b border-line px-row-inset py-1.5 text-2xs font-medium text-accent transition-colors hover:bg-surface",children:[i?"Show less":`Show ${f} more`,!i&&r.jsx(Qt,{className:"ml-1 size-3"})]})]})]})}function Su({value:e,recentSearches:t,onPickRecent:s,sections:n,loading:a,onSelectResult:o,tokens:i,scope:c=Px,makeFilter:u}){if(!(e.trim().length>0))return t&&t.length>0?r.jsxs("div",{className:"flex flex-col",children:[r.jsx("h3",{className:"px-row-inset pb-1 pt-3 text-2xs font-semibold uppercase tracking-wide text-fg-subtle",children:"Recent searches"}),t.map(w=>r.jsxs("button",{type:"button",onClick:()=>s?.(w),className:"flex w-full items-center gap-2.5 border-b border-line px-row-inset py-2.5 text-left transition-colors hover:bg-surface-sunken",children:[r.jsx(oo,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-fg-muted",children:w})]},w))]}):r.jsx("p",{className:"px-row-inset py-6 text-center text-sm text-fg-subtle",children:"Search across your mail by sender, subject or words in the message."});const d=i&&i.length>0&&r.jsx(pm,{tokens:i}),f=u&&r.jsx(wu,{...u});if(a)return r.jsxs("div",{className:"flex flex-col",children:[f,d,r.jsx("div",{className:"flex flex-col gap-3 px-row-inset py-4",children:[0,1,2,3].map(w=>r.jsxs("div",{className:"flex flex-col gap-1.5",children:[r.jsx("div",{className:"h-3 w-1/3 animate-pulse rounded bg-surface-sunken"}),r.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-surface-sunken"}),r.jsx("div",{className:"h-2.5 w-1/2 animate-pulse rounded bg-surface-sunken"})]},w))})]});const h=c.kind==="global",v=Lx(c)||c.kind==="collection",x=h||c.kind==="collection",p=(n??[]).map(w=>{if(v)return{section:w,spam:[]};const{kept:C,spam:R}=ko(w.results);return{section:{...w,results:C},spam:R}}),b=p.map(w=>w.section),y=p.reduce((w,C)=>w+C.spam.length,0),S=c.kind==="global"&&y>0&&c.onScopeToSpam!==void 0?r.jsx(yu,{count:y,onScopeToSpam:c.onScopeToSpam}):void 0;return b.some(w=>w.results.length>0)?r.jsxs("div",{className:"flex flex-col",children:[f,d,S,b.filter(w=>w.results.length>0).map(w=>r.jsx($x,{section:w,query:e,showFolder:x,onSelectResult:o},w.id))]}):r.jsxs("div",{className:"flex flex-col",children:[f,d,S,r.jsxs("div",{className:"px-row-inset py-10 text-center",children:[r.jsxs("p",{className:"text-sm font-medium text-fg",children:["No matches for “",e,"”"]}),r.jsx("p",{className:"mt-1 text-xs text-fg-subtle",children:"Try a different word, or adjust the filters above."})]})]})}function _x({value:e,onChange:t,onClear:s,onCancel:n,filter:a,recentSearches:o,onPickRecent:i,sections:c,loading:u,onSelectResult:m,tokens:d,chips:f,onRemoveChip:h,scope:v,makeFilter:x,suggest:p,suggestList:b}){const y=r.jsx(Su,{value:e,recentSearches:o,onPickRecent:i,sections:c,loading:u,onSelectResult:m,tokens:d,scope:v,makeFilter:x});return r.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(Co,{value:e,onChange:t,onClear:s,chips:f,onRemoveChip:h,globalFocusKey:!1,showClearButton:!1,suggest:p})}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Nt,{className:"size-4"}),onClick:n,"aria-label":"Clear and close search",className:"-mr-1 shrink-0"})]}),b,a&&e.trim().length===0?r.jsx(gm,{children:r.jsx(pc,{...a,children:y})}):r.jsx("div",{className:"flex-1 overflow-y-auto",children:y})]})}function zx(){const e=ps();if(!e)return null;const t=e.showNavPane?!e.navCollapsed:!1;return r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(pr,{className:"size-4"}),onClick:e.toggleNav,"aria-label":t?"Hide folders":"Show folders","aria-expanded":t,title:"Folders",className:"shrink-0"})}const Bx={queued:{icon:oo,label:"Queued",className:"text-warning"},sending:{icon:hs,label:"Sending…",className:"text-accent-2",spin:!0},sent:{icon:go,label:"Sent",className:"text-positive"},failed:{icon:Pt,label:"Failed",className:"text-danger"},blocked:{icon:Ka,label:"Blocked",className:"text-warning"}};function Qi({status:e,iconOnly:t,className:s}){const n=Bx[e],a=n.icon;return r.jsxs("span",{className:Q("inline-flex items-center gap-1.5 text-xs font-medium",n.className,s),children:[r.jsx(a,{className:Q("size-4",n.spin&&"animate-spin")}),!t&&n.label]})}const Ux=(e,t)=>t?"bg-accent-2-soft":e==="failed"?"bg-danger-soft":e==="blocked"?"bg-warning/10":"";function Kx({recipients:e,subject:t,time:s,status:n,error:a,selected:o,onSelect:i,onRetry:c,retrying:u,onEdit:m,onDelete:d,deleting:f}){const h=n==="failed"||n==="blocked";return r.jsxs("div",{className:Q("flex items-start gap-3 border-b border-line px-4 py-3 transition-colors hover:bg-surface-raised",Ux(n,o)),children:[r.jsxs("button",{type:"button",...lc,onClick:i,className:"flex flex-1 min-w-0 items-start gap-3 text-left",children:[r.jsx("div",{className:"mt-0.5 shrink-0",children:r.jsx(Qi,{status:n,iconOnly:!0})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"truncate text-sm font-medium",children:e}),r.jsx("span",{className:"shrink-0 text-xs text-fg-muted",children:s})]}),r.jsx("div",{className:"truncate text-sm",children:t||"No subject"}),r.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[r.jsx(Qi,{status:n}),a&&r.jsxs("span",{className:"truncate text-xs text-fg-muted",children:["— ",a]})]})]})]}),h&&r.jsx("div",{className:"shrink-0",children:r.jsx(Mh,{actions:[...n==="failed"&&c?[{label:"Retry sending",iconOnly:!0,icon:r.jsx(Rh,{className:"size-3.5"}),busy:u,onClick:c}]:[],{label:"Edit as draft",iconOnly:!0,icon:r.jsx(pn,{className:"size-3.5"}),onClick:m}],destructive:{label:"Delete message",iconOnly:!0,icon:r.jsx(Lt,{className:"size-3.5"}),busy:f,confirm:{prompt:"Delete this message?",confirmLabel:"Delete"},onClick:d}})})]})}const qx=e=>{const[t,s]=l.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return l.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Hx=({children:e,onRefresh:t,isRefreshing:s})=>qx(Mc)?e:r.jsx(xm,{onRefresh:t,isPullable:!s,children:e}),Wx=({text:e,html:t,senderName:s,date:n})=>{const[a,o]=l.useState(!1);if(!e&&!t)return null;const i=[s,n].filter(Boolean).join(" on ");return r.jsxs("div",{className:"mt-2 px-3 pb-2",children:[r.jsxs("button",{type:"button",onClick:()=>o(!a),"aria-expanded":a,className:"flex items-center gap-1 text-xs text-fg-muted hover:text-fg transition-colors",children:[a?r.jsx(Qt,{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((c,u)=>r.jsx("p",{className:"min-h-[1.2em]",children:c},u))})]})};function jo({state:e,onRefresh:t,label:s,errorMessage:n,hasUpdate:a,size:o="sm",className:i}){const c=e==="refreshing",u=e==="error",m=e==="success",d=u?r.jsx(Pt,{className:"size-4 text-danger"}):m?r.jsx(go,{className:"size-4 text-positive"}):r.jsx(xo,{className:Q("size-4",c&&"animate-spin")}),f=u?`${s} — failed: ${n??"try again"}`:c?`${s} — refreshing`:m?`${s} — up to date`:a?`${s} — new mail`:s;return r.jsxs("div",{className:"relative inline-flex",children:[r.jsx(ce,{variant:"ghost",size:o,icon:d,onClick:t,disabled:c,"aria-label":f,"aria-busy":c||void 0,title:u?n:s,className:i}),e==="idle"&&a&&r.jsx("span",{"aria-hidden":"true",className:"absolute right-1 top-1 size-1.5 rounded-full bg-accent-2"})]})}const Vx=e=>e===1?"message":"messages";function Qx({count:e,onReview:t,onDismiss:s,actionLabel:n="Review & rescue"}){return r.jsx(gn,{tone:"info",variant:"soft",onDismiss:s,children:r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsxs("p",{className:"flex items-start gap-2 text-sm text-fg",children:[r.jsx(xn,{className:"mt-0.5 size-4 shrink-0 text-positive","aria-hidden":!0}),r.jsxs("span",{children:[r.jsx("span",{className:"font-semibold text-fg",children:`${e} ${Vx(e)} here`})," ","may not be spam — they're from senders we can verify."]})]}),r.jsx(ce,{variant:"primary",size:"sm",onClick:t,className:"self-start",children:n})]})})}const Gx=(e,t)=>e==="vip"?"vip":e==="unknown"&&t==="md"?"unknown-pill":"hidden",Cu=({senderTrust:e,size:t="sm",className:s})=>{const n=Gx(e,t);return n==="vip"?r.jsx(Dt,{className:Q("text-warning shrink-0",t==="sm"&&"size-3.5",t==="md"&&"size-4",s),"aria-label":"VIP sender","data-testid":"sender-trust-vip"}):n==="unknown-pill"?r.jsx("span",{className:Q("inline-flex items-center rounded border border-dashed border-fg-subtle/40 font-medium uppercase tracking-wide text-fg-muted/80 shrink-0","px-2 py-0.5 text-xs",s),title:"First message from this sender","aria-label":"First message from this sender","data-testid":"sender-trust-unknown",children:"new"}):null};function Yx({candidate:e,selected:t,onToggle:s,hideSender:n=!1}){const{senderName:a,senderAddress:o,subject:i,snippet:c,trustReason:u,trustSubReason:m,senderTrust:d}=e;return r.jsxs("label",{className:Q("flex w-full cursor-pointer items-start gap-3 px-3 py-2.5 text-left transition-colors",n&&"pl-11",t?"bg-positive/10":"bg-surface hover:bg-surface-sunken"),children:[r.jsx(So,{className:"mt-0.5",checked:t,onChange:s,"aria-label":`${t?"Deselect":"Select"} ${n?i:`message from ${a}`}`}),!n&&r.jsx(jt,{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(Cu,{senderTrust:d,size:"sm"}),r.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:o})]}),r.jsx("span",{className:"block truncate text-sm text-fg-muted",children:i}),r.jsx("span",{className:"block line-clamp-1 text-xs text-fg-subtle",children:c}),!n&&r.jsxs("span",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[r.jsxs(kt,{tone:"positive",children:[r.jsx(xn,{className:"size-3","aria-hidden":!0}),u]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:m})]})]})]})}const Xx=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)},Jx=(e,t)=>{const s=e.messages.filter(n=>t.has(n.id)).length;return s===0?"none":s===e.messages.length?"all":"some"},Gi=e=>e===1?"message":"messages";function Zx({group:e,selected:t,onToggleGroup:s,onToggleMessage:n}){const[a,o]=l.useState(!1),i=Jx(e,t),c=e.messages.length,u=a?Qt:Ms;return r.jsxs("div",{className:Q(i!=="none"?"bg-positive/10":"bg-surface"),children:[r.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-2.5",children:[r.jsx(So,{className:"mt-0.5",checked:i==="all",indeterminate:i==="some",onChange:()=>s(e,i!=="all"),"aria-label":`${i==="all"?"Deselect":"Select"} all ${c} ${Gi(c)} from ${e.senderName}`}),r.jsx(jt,{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(Cu,{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(kt,{tone:"positive",children:[r.jsx(xn,{className:"size-3","aria-hidden":!0}),e.trustReason]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:e.trustSubReason})]})]}),r.jsxs("button",{type:"button",onClick:()=>o(m=>!m),"aria-expanded":a,className:"flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-2xs text-fg-muted transition-colors hover:bg-surface-sunken hover:text-fg",children:[`${c} ${Gi(c)}`,r.jsx(u,{className:"size-3.5","aria-hidden":!0})]})]}),a&&r.jsx("div",{className:"divide-y divide-line border-t border-line",children:e.messages.map(m=>r.jsx(Yx,{candidate:m,selected:t.has(m.id),onToggle:()=>n(m.id),hideSender:!0},m.id))})]})}const No=e=>e===1?"message":"messages",eb=(e,t)=>`Moves ${e===1?"this message":`these ${e} ${No(e)}`} out of Spam to ${t} now. Nothing later.`,ja=(e,t)=>e.find(s=>s.id===t)?.label??"Inbox";function tb(){return r.jsx(gn,{tone:"info",variant:"soft",children:r.jsx("p",{className:"text-2xs text-fg-muted",children:"We list a message here only when we can confirm the sender is who they say — usually someone you've emailed before, write to often, or a service that consistently checks out. We never guess from words in the subject. Anything we can't confirm stays in Spam."})})}function sb({candidates:e,selected:t,onToggle:s,onToggleGroup:n,onSelectAll:a,onSelectNone:o,onContinue:i,onCancel:c}){const[u,m]=l.useState(!1),d=t.size,f=l.useMemo(()=>Xx(e),[e]);return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("h2",{className:"flex items-center gap-2 text-sm font-semibold text-fg",children:[r.jsx(xn,{className:"size-4 text-positive","aria-hidden":!0}),"Rescue from Spam"]}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Ih,{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(tb,{})})]}),r.jsxs("div",{className:"flex items-center justify-between px-row-inset pb-1.5",children:[r.jsx("span",{className:"text-2xs font-medium text-fg-muted",children:`${d} of ${e.length} selected · ${f.length} ${f.length===1?"sender":"senders"}`}),r.jsxs("span",{className:"flex gap-1",children:[r.jsx(ce,{variant:"ghost",size:"sm",onClick:a,children:"Select all"}),r.jsx(ce,{variant:"ghost",size:"sm",onClick:o,children:"Select none"})]})]}),r.jsx("div",{className:"min-h-0 flex-1 divide-y divide-line overflow-y-auto border-y border-line",children:f.map(h=>r.jsx(Zx,{group:h,selected:t,onToggleGroup:n,onToggleMessage:s},h.key))}),r.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[r.jsx(ce,{variant:"primary",onClick:i,className:"h-11 w-full font-semibold",children:`Continue with ${d} ${No(d)}`}),r.jsx(ce,{variant:"ghost",onClick:c,className:"h-11 w-full",children:"Cancel"})]})]})}function nb({count:e,folders:t,delimiter:s,destination:n,onPick:a,onMove:o,onBack:i}){const[c,u]=l.useState(!1);return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[r.jsx("h2",{className:"text-sm font-semibold text-fg",children:"Where should they go?"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Pick a folder, then we move them out of Spam."})]}),r.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-row-inset py-2",children:c?r.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden rounded-xl border border-line bg-surface",children:r.jsx(gc,{folders:t,selectedId:n,delimiter:s,onSelect:a,onCancel:()=>u(!1)})}):r.jsxs("div",{className:"rounded-xl border border-line bg-surface-sunken p-3",children:[r.jsx("p",{className:"text-2xs text-fg-subtle",children:"Destination"}),r.jsx("p",{className:"mt-0.5 text-sm font-medium text-fg",children:ja(t,n)}),r.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"mt-2 px-0",children:"Move to a different folder"})]})}),r.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[r.jsx("p",{className:"text-2xs text-fg-subtle",children:eb(e,ja(t,n))}),r.jsx(ce,{variant:"primary",onClick:o,className:"h-11 w-full font-semibold",children:`Move ${e} out of Spam`}),r.jsx(ce,{variant:"ghost",onClick:i,className:"h-11 w-full",children:"Back"})]})]})}function rb({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(Hh,{className:"size-10 text-positive","aria-hidden":!0}),r.jsx("p",{className:"text-base font-semibold text-fg",children:`Moved ${e} ${No(e)} out of Spam.`}),r.jsx("p",{className:"text-2xs text-fg-subtle",children:`You'll find them in ${t}.`})]}),r.jsx("div",{className:"border-t border-line bg-surface px-row-inset py-3",children:r.jsx(ce,{variant:"primary",onClick:s,className:"h-11 w-full font-semibold",children:"Done"})})]})}function ab({open:e,candidates:t,defaultDestinationId:s,availableFolders:n,delimiter:a,onConfirmMove:o,onCancel:i}){const[c,u]=l.useState("review"),[m,d]=l.useState(()=>e?new Set(t.map(w=>w.id)):new Set),[f,h]=l.useState(s),[v,x]=l.useState(0),p=l.useRef(!1);l.useEffect(()=>{e&&!p.current&&(u("review"),d(new Set(t.map(w=>w.id))),h(s),x(0)),p.current=e},[e,t,s]);const b=m.size,y=w=>{d(C=>{const R=new Set(C);return R.has(w)?R.delete(w):R.add(w),R})},S=(w,C)=>{d(R=>{const O=new Set(R);for(const k of w.messages)C?O.add(k.id):O.delete(k.id);return O})},g=()=>{const w=Array.from(m);x(w.length),o(w,f),u("done")};return r.jsxs(Oh,{open:e,onClose:i,dismissLabel:"Close rescue",children:[c==="review"&&r.jsx(sb,{candidates:t,selected:m,onToggle:y,onToggleGroup:S,onSelectAll:()=>d(new Set(t.map(w=>w.id))),onSelectNone:()=>d(new Set),onContinue:()=>u("destination"),onCancel:i}),c==="destination"&&r.jsx(nb,{count:b,folders:n,delimiter:a,destination:f,onPick:h,onMove:g,onBack:()=>u("review")}),c==="done"&&r.jsx(rb,{count:v,destinationLabel:ja(n,f),onClose:i})]})}const ob={html:"",text:"",formatting:[]},Yi=e=>e.toLocaleString();function Xi({selectAll:e,selecting:t,className:s}){return r.jsx(So,{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 Eo({title:e,count:t,onCancel:s,onDelete:n,onMove:a,onOrganize:o,onJunk:i,onMarkRead:c,navSlot:u,titleMeta:m,searchSlot:d,searchField:f,idleSlot:h,overflowSlot:v,isBusy:x=!1,isCounting:p=!1,selectAll:b,statusLabel:y,progress:S,notice:g}){const w=t>0||p,C=b?.checked?`All ${Yi(t)} loaded selected`:`${Yi(t)} ${t===1?"message":"messages"} selected`,R=[];return i&&!x&&!p&&R.push({key:"junk",label:"Junk",icon:r.jsx($s,{className:"size-4"}),onSelect:i}),c&&!x&&!p&&R.push({key:"mark-read",label:"Mark read",icon:r.jsx(vr,{className:"size-4"}),onSelect:c}),r.jsxs("header",{"data-selection-bar":"",className:"flex shrink-0 flex-col border-b border-line bg-surface-sunken",children:[r.jsxs("div",{"data-selection-bar-row":"actions",className:"flex h-pane-header items-center gap-1 px-row-inset",children:[w?r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(Ua,{className:"size-5"}),onClick:s,"aria-label":"Cancel selection",className:"-ml-2 shrink-0"}):u,b&&r.jsx(Xi,{selectAll:b,selecting:w,className:"hidden shrink-0 pr-2 md:flex"}),w?r.jsx("span",{"data-selection-count":"",className:"min-w-0 flex-1 truncate px-1 text-sm font-medium text-fg",role:"status","aria-live":"polite",children:y??C}):f?r.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:f}):r.jsxs(r.Fragment,{children:[r.jsx("h1",{className:"min-w-0 flex-1 truncate px-1 text-sm font-semibold text-fg",children:e}),m,d]}),w&&!p&&r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",size:"touch",icon:x?r.jsx(hs,{className:"size-5 animate-spin"}):r.jsx(Lt,{className:"size-5 text-danger"}),onClick:x?void 0:n,"aria-label":"Move selected messages to Trash","aria-busy":x||void 0,className:"shrink-0"}),!x&&a&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(za,{className:"size-5"}),onClick:a,"aria-label":"Move selected messages",className:"shrink-0"}),!x&&o&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(Dt,{className:"size-5"}),onClick:o,"aria-label":"Organize selected messages",className:"shrink-0"})]}),w&&r.jsx(wo,{triggerLabel:"More actions",items:R,className:"shrink-0",children:!x&&!p&&v})]}),!w&&h,w&&b&&r.jsx("div",{"data-selection-bar-row":"select-all",className:"px-row-inset pb-2 md:hidden",children:r.jsx(Xi,{selectAll:b,selecting:w,className:"w-full"})}),S&&r.jsx("div",{className:"px-row-inset pb-2",children:r.jsx(bm,{value:S.value,max:S.max,tone:S.tone})}),g&&r.jsx(gn,{"data-selection-notice":"",tone:g.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-row-inset mb-2",children:r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.text&&r.jsx("span",{children:g.text}),g.action&&r.jsx(ce,{variant:"ghost",size:"md",onClick:g.action.onClick,className:"-my-1 min-h-11 shrink-0",children:g.action.label})]})})]})}const ib={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function lb({search:e,onCompose:t,onReportBug:s,onOpenSettings:n,composeShortcut:a,refreshControl:o,account:i}){return r.jsx(nx,{leading:r.jsx(zx,{}),search:r.jsx(Co,{value:e.value,onChange:e.onChange,onClear:e.onClear,onClearQuery:e.onClearQuery,chips:e.chips,onRemoveChip:e.onRemoveChip,placeholder:ib[e.scope]}),actions:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Pp,{className:"size-4"}),title:a?`Compose (${a})`:"Compose","aria-label":"Compose",onClick:t}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Vc,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:s}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(eu,{className:"size-4"}),title:"Settings","aria-label":"Settings",onClick:n}),o,i]})})}const Io=[{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"}],ku={id:"unread",label:"Unread"},cb={id:"flagged",label:"Starred"},ju={id:"attachment",label:"Has attachment"};function ub(e){if(!(e.length<=1))return e.map(t=>({id:t.id,label:t.label,count:t.count,active:t.active}))}function db(e=[]){return{categories:[...Io],filters:vm,sources:ub(e)}}function Nu(){return{categories:[...Io],filters:[ku,cb,ju]}}function fb(){return{categories:[...Io],filters:[ku,ju]}}const mb=["p","br","div","h1","h2","h3","h4","h5","h6","strong","b","em","i","u","s","ul","ol","li","blockquote","pre","code","hr","table","thead","tbody","tr","th","td","a","img"],hb=["href","src","alt","colspan","rowspan","lang","dir"],pb=/^(?:https?:|mailto:)/i,gb=/^(?:https:|data:image\/)/i,xb=e=>{const t=dc();if(!t.isSupported)throw new Error("adopted HTML cannot be sanitized: no DOM is available");return t.addHook("afterSanitizeAttributes",s=>{if(s.tagName==="A"){pb.test(s.getAttribute("href")??"")||s.removeAttribute("href"),e==="quoted"&&(s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer nofollow"));return}if(s.tagName==="IMG"){if(e==="quoted"){s.remove();return}gb.test(s.getAttribute("src")??"")||s.remove()}}),t},Ji=new Map,bb=e=>{const t=Ji.get(e);if(t)return t;const s=xb(e);return Ji.set(e,s),s},Eu=(e,t)=>bb(t).sanitize(e,{ALLOWED_TAGS:mb,ALLOWED_ATTR:hb,ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1}),i1=e=>Eu(e,"outgoing"),vb=e=>Eu(e,"quoted");function wr(e){const t=[];let s=-1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];if(o==='"'){n=!n,s<0&&(s=a);continue}if(!n&&/\s/.test(o)){s>=0&&t.push({raw:e.slice(s,a),start:s,end:a}),s=-1;continue}s<0&&(s=a)}return s>=0&&t.push({raw:e.slice(s),start:s,end:e.length}),t}const yb=e=>{if(!e.startsWith('"'))return e;const t=e.slice(1);return t.endsWith('"')?t.slice(0,-1):t};function Sr(e){const t=e.indexOf(":");if(t<=0)return;const s=e.slice(t+1);return{name:e.slice(0,t).toLowerCase(),value:yb(s),rawValue:s}}const wb=e=>/[\s"]/.test(e),Sb=e=>wb(e)?`"${e.replace(/"/g,"")}"`:e,Cr=(e,t)=>`${e}:${Sb(t)}`,Iu=[{id:"unread",name:"is",value:"unread"},{id:"attachment",name:"has",value:"attachment"}],Ru="category",Cb={unclassified:"uncategorized"},bn=e=>wr(e).map(t=>t.raw),un=e=>e.join(" "),Ro=e=>{const t=Sr(e);if(t)return Iu.find(s=>s.name===t.name&&s.value===t.value.toLowerCase())?.id},To=e=>{const t=Sr(e);if(!t||t.name!==Ru)return;const s=t.value.toLowerCase(),n=Cb[s];if(n)return n;if(!(!ym(s)||s==="all"))return s},Tu=e=>Iu.find(t=>t.id===e),Mu=e=>Tu(e)!==void 0,kb=e=>{const t=new Set;for(const s of bn(e)){const n=Ro(s);n&&t.add(n)}return t},jb=e=>{let t="all";for(const s of bn(e)){const n=To(s);n&&(t=n)}return t},Nb=(e,t)=>{const s=Tu(t);if(!s)return;const n=bn(e),a=n.filter(o=>Ro(o)!==t);return a.length<n.length?un(a):un([...n,Cr(s.name,s.value)])},Eb=(e,t)=>{const s=bn(e).filter(n=>!To(n));return un(t==="all"?s:[...s,Cr(Ru,t)])},Ib=e=>un(bn(e).filter(t=>!Ro(t)&&!To(t))),Au=e=>e.trim().length>0,Rb=e=>{if(!Au(e.query))return e.ownFilters;const t=new Set(kb(e.query));for(const s of e.ownFilters)Mu(s)||t.add(s);return t},Tb=e=>Au(e.query)?jb(e.query):e.ownCategory,Mb=e=>typeof e=="string"&&e.length>0?"rich":"plain",l1=(e,t)=>t.length>0,Ab={plain:"Couldn't switch to plain text",rich:"Couldn't switch to rich text"},c1=(e,t,s)=>t.trim()===""||s.trim()!==""?{outcome:"switch"}:{outcome:"blocked",title:Ab[e],detail:"The conversion came back empty, so your message is unchanged."};function Ob(e,t){return e.endsWith(t)?e.length===t.length||e[e.length-t.length-1]===".":!1}function Db(e,t){const s=e.length-t.length-2,n=e.lastIndexOf(".",s);return n===-1?e:e.slice(n+1)}function Pb(e,t,s){if(s.validHosts!==null){const a=s.validHosts;for(const o of a)if(Ob(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:Db(t,e)}const Xr=/[\t\n\r]/g;let Na=!1;function Zi(e){return e>=97&&e<=122||e>=48&&e<=57||e>127||e>=65&&e<=90||e===45||e===95}function el(e,t,s){const n=s-t,a=e.charCodeAt(t)|32;if(n===2)return a===119&&(e.charCodeAt(t+1)|32)===115?1:0;if(n===3){const o=e.charCodeAt(t+1)|32,i=e.charCodeAt(t+2)|32;return a===119&&o===115&&i===115||a===102&&o===116&&i===112?1:0}else if(n===4){const o=e.charCodeAt(t+1)|32,i=e.charCodeAt(t+2)|32,c=e.charCodeAt(t+3)|32;return a===104&&o===116&&i===116&&c===112?1:a===102&&o===105&&i===108&&c===101?2:0}else if(n===5)return a===104&&(e.charCodeAt(t+1)|32)===116&&(e.charCodeAt(t+2)|32)===116&&(e.charCodeAt(t+3)|32)===112&&(e.charCodeAt(t+4)|32)===115?1:0;return 0}function an(e,t,s=!1){let n=0,a=e.length,o=!1,i=!1;if(Na=!1,!t){if(e.startsWith("data:"))return null;for(;n<e.length&&e.charCodeAt(n)<=32;)n+=1;for(;a>n+1&&e.charCodeAt(a-1)<=32;)a-=1;if(e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47)n+=2;else{const b=e.indexOf(":/",n);if(b!==-1){const y=el(e,n,b);if(y===1)for(i=!0,n=b+2;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1;else if(y===2){i=!0,n=b+1;let S=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&S<2;)n+=1,S+=1;if(S<2)return null}else{for(let S=n;S<b;S+=1){const g=e.charCodeAt(S)|32;if(!(g>=97&&g<=122||g>=48&&g<=57||g===46||g===45||g===43)){const w=e.charCodeAt(S);return w===9||w===10||w===13?an(e.replace(Xr,""),t,s):null}}if(e.charCodeAt(b+2)===47)n=b+3;else return null}}else if(e.charCodeAt(n)!==91){let y=-1;for(let S=n;S<a;S+=1){const g=e.charCodeAt(S);if(g===9||g===10||g===13)return an(e.replace(Xr,""),t,s);if(g===58){y=S;break}if(g===47||g===92||g===63||g===35)break}if(y!==-1){let S=!1;for(let g=y+1;g<a;g+=1){const w=e.charCodeAt(g);if(w===47||w===92||w===63||w===35)break;if(w===64){S=!0;break}}if(!S){let g=!0,w=y+1;for(;w<a;w+=1){const C=e.charCodeAt(w);if(C===47||C===92||C===63||C===35)break;if(C<48||C>57){g=!1;break}}if(w===y+1&&(g=!1),!g){const C=el(e,n,y);if(C===0){let R=!1;for(let O=y+1;O<a;O+=1){const k=e.charCodeAt(O);if(k===47||k===92||k===63||k===35)break;if(k===58){R=!0;break}}if(!R)return null}else if(i=!0,n=y+1,C===2){let R=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&R<2;)n+=1,R+=1;if(R<2)return null}else for(;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1}}}}}let u=-1,m=-1,d=-1,f=-1,h=!1,v=s,x=n-1,p=-1;if(s&&n<a){const b=e.charCodeAt(n);(!(Zi(b)||b===46||b===95)||b===45)&&(v=!1)}for(let b=n;b<a;b+=1){const y=e.charCodeAt(b);if(y<64)if(y===47||y===35||y===63){a=b;break}else y===58?(f===-1&&(f=b),d=b):y===9||y===10||y===13?h=!0:s&&(y===46?((b-x>64||p===46||p===45)&&(v=!1),x=b):(y<48||y>57)&&(y!==45||p===46)&&(v=!1));else if(i&&y===92){a=b;break}else y===64?(u=b,f=-1):y===93?m=b:y>=65&&y<=90?o=!0:s&&!Zi(y)&&(v=!1);s&&(p=y)}if(h)return an(e.replace(Xr,""),t,s);if(u!==-1&&u>=n&&u<a&&(n=u+1),e.charCodeAt(n)===91)return m!==-1?e.slice(n+1,m).toLowerCase():null;if(d!==-1&&d>n&&d<a&&f===d&&(a=d),n>=a)return null;s&&v&&u===-1&&d===-1&&m===-1&&e.charCodeAt(a-1)!==46&&a-n<=255&&a-x-1<=63&&p!==45&&(Na=!0)}for(;a>n+1&&e.charCodeAt(a-1)===46;)a-=1;const c=n!==0||a!==e.length?e.slice(n,a):e;return o?c.toLowerCase():c}function Lb(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 Fb(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 $b(e){return Fb(e)||Lb(e)}function tl(e){return e>=97&&e<=122||e>=48&&e<=57||e>127}function sl(e){if(e.length>255||e.length===0||!tl(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(!(tl(o)||o===45||o===95)||o===45&&s===46)return!1;s=o}return n-t-1<=63&&s!==45}function _b({allowIcannDomains:e=!0,allowPrivateDomains:t=!1,detectIp:s=!0,detectSpecialUse:n=!1,extractHostname:a=!0,mixedInputs:o=!0,validHosts:i=null,validateHostname:c=!0}){return{allowIcannDomains:e,allowPrivateDomains:t,detectIp:s,detectSpecialUse:n,extractHostname:a,mixedInputs:o,validHosts:i,validateHostname:c}}const zb=_b({});function Bb(e){return zb}function Ub(){return{domain:null,domainWithoutSuffix:null,hostname:null,isIcann:null,isIp:null,isPrivate:null,isSpecialUse:null,publicSuffix:null,subdomain:null}}function Kb(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 qb(e,t,s,n,a){const o=Bb();if(typeof e!="string")return a;let i=!1;return o.extractHostname?o.mixedInputs?(i=sl(e),a.hostname=an(e,i,o.validateHostname)):a.hostname=an(e,!1,o.validateHostname):a.hostname=e,o.detectIp&&a.hostname!==null&&(a.isIp=$b(a.hostname),a.isIp)?a:o.validateHostname&&o.extractHostname&&a.hostname!==null&&!(i&&a.hostname===e)&&!Na&&!sl(a.hostname)?(a.hostname=null,a):(a.hostname===null||(s(a.hostname,o,a),a.publicSuffix===null)||(a.domain=Pb(a.publicSuffix,a.hostname,o)),a)}const nl=Ub();function Hb(e,t){return Kb(nl),qb(e,3,wm,t,nl).domain}const kr=e=>{const t=new Set,s=[];for(const n of e){const a=n.trim();if(a==="")continue;const o=a.toLowerCase();t.has(o)||(t.add(o),s.push(a))}return s},Wb=e=>{const t=e.lastIndexOf("@");return t>=0?e.slice(t+1):e},Ou=e=>Hb(Wb(e.trim())),Vb=e=>{const t=kr(e);if(t.length<2)return null;let s=null;for(const n of t){const a=Ou(n);if(a===null)return null;if(s===null)s=a;else if(s!==a)return null}return s},jr=e=>{const t=Vb(e);return t!==null?[{field:"FromDomain",value:t}]:kr(e).map(s=>({field:"From",value:s}))},Qb=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},Du=e=>e.displayName?.trim()||e.normalizedEmail,Gb=/^\s*(?:(?:re|aw|fwd?|vs|sv|antw|res|enc|tr)\s*(?:\[\d+\])?\s*:|\[[^\]]{1,32}\])\s*/i,Yb=e=>{let t=e.replace(/\s+/g," ").trim();for(;;){const s=t.replace(Gb,"");if(s===t)return t.trim();t=s}},Xb=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"]),Jb=3,Jr=e=>e.split(" ").filter(t=>t!==""),rl=e=>e.length===0||e.join(" ").length<Jb?!1:e.some(t=>!Xb.has(t.toLowerCase())),Zb=(e,t)=>e.findIndex((s,n)=>t.every((a,o)=>e[n+o]?.toLowerCase()===a.toLowerCase())),ev=e=>{const t=e.map(Yb).filter(o=>o!=="");if(t.length===0)return;const[s,...n]=t;if(n.length===0)return rl(Jr(s))?s:void 0;const a=Jr(s);for(let o=a.length;o>0;o-=1)for(let i=0;i+o<=a.length;i+=1){const c=a.slice(i,i+o);if(rl(c)&&n.every(u=>Zb(Jr(u),c)>=0))return c.join(" ")}},tv=(e,t)=>{const s=jr(e);if(kr(e).length===1||s.length===1&&s[0].field==="FromDomain")return s;const n=ev(t);return n!==void 0?[{field:"Subject",value:n}]:s},sv=({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}`:""},nv=e=>e.clauses.length>0,rv=e=>({scopedOutFolder:e.scopedOut?.label,droppedFacets:e.droppedFacets.map(t=>t.label),droppedSemantic:e.droppedSemantic}),av=({orderedIds:e,isDesktop:t,initialFocusedId:s,initialSelectedIds:n,onExitSelection:a})=>{const[o,i]=l.useState(s),[c,u]=l.useState(),m=l.useCallback(T=>{u(F=>F===T?F:void 0),i(T)},[]),d=au({initialSelectedIds:n}),{selectedCount:f,toggle:h,clearSelection:v,selectRange:x,setAnchor:p,selectAll:b}=d,y=vo(f,t),S=l.useRef(null),g=l.useRef(!1),w=l.useCallback(()=>{a?.(),v()},[v,a]),C=l.useMemo(()=>o?e.indexOf(o):-1,[e,o]),R=l.useCallback(T=>{if(T<0||T>=e.length)return;const F=e[T];if(y){h(F);return}S.current=F,g.current=!1,u(F),i(F)},[e,y,h]),O=l.useCallback(()=>{e.length!==0&&R(C<0?0:Math.min(C+1,e.length-1))},[e.length,C,R]),k=l.useCallback(()=>{e.length!==0&&R(C<=0?0:C-1)},[e.length,C,R]),M=l.useCallback(()=>R(0),[R]),P=l.useCallback(()=>R(e.length-1),[R,e.length]),E=l.useCallback(()=>{o&&h(o)},[o,h]),L=l.useCallback((T,F)=>{const N=Wp(F);return N==="range"?(x(e,T,o),!0):N==="toggle"?(h(T),!0):(w(),p(T),!1)},[e,o,x,h,w,p]),A=l.useCallback(T=>{const F=ru(e,o,T);F!==void 0&&(x(e,F),S.current=F,g.current=!1,u(void 0),i(F))},[e,o,x]),j=l.useCallback(()=>A(-1),[A]),I=l.useCallback(()=>A(1),[A]),D=l.useCallback(()=>{e.length>0&&b(e)},[e,b]);return{focusedMessageId:o,setFocusedMessageId:m,keyboardFocusedMessageId:c,focusIndex:C,pendingDomFocusRef:S,cursorMovedByPointerRef:g,selection:d,isMultiSelectMode:y,exitSelection:w,moveFocusToIndex:R,focusNext:O,focusPrevious:k,focusFirst:M,focusLast:P,toggleFocusedSelection:E,extendRangeUp:j,extendRangeDown:I,selectAllLoaded:D,handleRowSelect:L}};function ov({handlers:e,enabled:t=!0,target:s,sequenceTimeoutMs:n=1e3}){const a=l.useRef(e);a.current=e;const o=l.useRef(null),i=l.useRef(null);l.useEffect(()=>{if(!t)return;const c=()=>{i.current!==null&&(clearTimeout(i.current),i.current=null)},u=d=>{const f=og({key:d.key,shiftKey:d.shiftKey,metaKey:d.metaKey,ctrlKey:d.ctrlKey,altKey:d.altKey,inEditable:ig(d.target),onControl:cg(d.target)},o.current);if(c(),o.current=f.nextPrefix,f.nextPrefix!==null&&(i.current=setTimeout(()=>{o.current=null,i.current=null},n)),f.action===null)return;const h=a.current[f.action];h&&(f.preventDefault&&d.preventDefault(),h())},m=s===void 0?window:s;if(m!==null)return m.addEventListener("keydown",u),()=>{m.removeEventListener("keydown",u),c(),o.current=null}},[t,n,s])}function Vt(e,t,{checkForDefaultPrevented:s=!0}={}){return function(a){if(e?.(a),s===!1||!a||!a.defaultPrevented)return t?.(a)}}function al(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function iv(...e){return t=>{let s=!1;const n=e.map(a=>{const o=al(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():al(e[a],null)}}}}function gs(...e){return l.useCallback(iv(...e),e)}function lv(e,t=[]){let s=[];function n(o,i){const c=l.createContext(i);c.displayName=o+"Context";const u=s.length;s=[...s,i];const m=f=>{const{scope:h,children:v,...x}=f,p=h?.[e]?.[u]||c,b=l.useMemo(()=>x,Object.values(x));return r.jsx(p.Provider,{value:b,children:v})};m.displayName=o+"Provider";function d(f,h,v={}){const{optional:x=!1}=v,p=h?.[e]?.[u]||c,b=l.useContext(p);if(b)return b;if(i!==void 0)return i;if(!x)throw new Error(`\`${f}\` must be used within \`${o}\``)}return[m,d]}const a=()=>{const o=s.map(i=>l.createContext(i));return function(c){const u=c?.[e]||o;return l.useMemo(()=>({[`__scope${e}`]:{...c,[e]:u}}),[c,u])}};return a.scopeName=e,[n,cv(a,...t)]}function cv(...e){const t=e[0];if(e.length===1)return t;const s=()=>{const n=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(o){const i=n.reduce((c,{useScope:u,scopeName:m})=>{const f=u(o)[`__scope${m}`];return{...c,...f}},{});return l.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return s.scopeName=t.scopeName,s}var dn=globalThis?.document?l.useLayoutEffect:()=>{},uv=qa[" useInsertionEffect ".trim().toString()]||dn;function dv({prop:e,defaultProp:t,onChange:s=()=>{},caller:n}){const[a,o,i]=fv({defaultProp:t,onChange:s}),c=e!==void 0,u=c?e:a;{const d=l.useRef(e!==void 0);l.useEffect(()=>{const f=d.current;f!==c&&console.warn(`${n} is changing from ${f?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=c},[c,n])}const m=l.useCallback(d=>{if(c){const f=mv(d)?d(e):d;f!==e&&i.current?.(f)}else o(d)},[c,e,o,i]);return[u,m]}function fv({defaultProp:e,onChange:t}){const[s,n]=l.useState(e),a=l.useRef(s),o=l.useRef(t);return uv(()=>{o.current=t},[t]),l.useEffect(()=>{a.current!==s&&(o.current?.(s),a.current=s)},[s,a]),[s,n,o]}function mv(e){return typeof e=="function"}function Pu(e){const t=l.forwardRef((s,n)=>{let{children:a,...o}=s,i=null,c=!1;const u=[];ol(a)&&typeof Mn=="function"&&(a=Mn(a._payload)),l.Children.forEach(a,h=>{if(bv(h)){c=!0;const v=h;let x="child"in v.props?v.props.child:v.props.children;ol(x)&&typeof Mn=="function"&&(x=Mn(x._payload)),i=pv(v,x),u.push(i?.props?.children)}else u.push(h)}),i?i=l.cloneElement(i,void 0,u):!c&&l.Children.count(a)===1&&l.isValidElement(a)&&(i=a);const m=i?xv(i):void 0,d=gs(n,m);if(!i){if(a||a===0)throw new Error(c?Sv(e):wv(e));return a}const f=gv(o,i.props??{});return i.type!==l.Fragment&&(f.ref=n?d:m),l.cloneElement(i,f)});return t.displayName=`${e}.Slot`,t}var hv=Symbol.for("radix.slottable"),pv=(e,t)=>{if("child"in e.props){const s=e.props.child;return l.isValidElement(s)?l.cloneElement(s,void 0,e.props.children(s.props.children)):null}return l.isValidElement(t)?t:null};function gv(e,t){const s={...t};for(const n in t){const a=e[n],o=t[n];/^on[A-Z]/.test(n)?a&&o?s[n]=(...c)=>{const u=o(...c);return a(...c),u}:a&&(s[n]=a):n==="style"?s[n]={...a,...o}:n==="className"&&(s[n]=[a,o].filter(Boolean).join(" "))}return{...e,...s}}function xv(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 bv(e){return l.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===hv}var vv=Symbol.for("react.lazy");function ol(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===vv&&"_payload"in e&&yv(e._payload)}function yv(e){return typeof e=="object"&&e!==null&&"then"in e}var wv=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,Sv=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Mn=qa[" use ".trim().toString()],Cv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_t=Cv.reduce((e,t)=>{const s=Pu(`Primitive.${t}`),n=l.forwardRef((a,o)=>{const{asChild:i,...c}=a,u=i?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),r.jsx(u,{...c,ref:o})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function kv(e,t){e&&Ha.flushSync(()=>e.dispatchEvent(t))}function fn(e){const t=l.useRef(e);return l.useEffect(()=>{t.current=e}),l.useMemo(()=>((...s)=>t.current?.(...s)),[])}var jv="DismissableLayer",Ea="dismissableLayer.update",Nv="dismissableLayer.pointerDownOutside",Ev="dismissableLayer.focusOutside",il,Mo=l.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Lu=l.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:n=!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:c,onDismiss:u,...m}=e,d=l.useContext(Mo),[f,h]=l.useState(null),v=f?.ownerDocument??globalThis?.document,[,x]=l.useState({}),p=gs(t,h),b=Array.from(d.layers),[y]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),S=y?b.indexOf(y):-1,g=f?b.indexOf(f):-1,w=d.layersWithOutsidePointerEventsDisabled.size>0,C=g>=S,R=l.useRef(!1),O=Av(E=>{o?.(E),c?.(E),E.defaultPrevented||u?.()},{ownerDocument:v,deferPointerDownOutside:n,isDeferredPointerDownOutsideRef:R,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:l.useCallback(E=>{if(!(E instanceof Node))return!1;const L=[...d.branches].some(A=>A.contains(E));return C&&!L},[d.branches,C])}),k=Ov(E=>{if(n&&R.current)return;const L=E.target;[...d.branches].some(j=>j.contains(L))||(i?.(E),c?.(E),E.defaultPrevented||u?.())},v),M=f?g===b.length-1:!1,P=fn(E=>{E.key==="Escape"&&(a?.(E),!E.defaultPrevented&&u&&(E.preventDefault(),u()))});return l.useEffect(()=>{if(M)return v.addEventListener("keydown",P,{capture:!0}),()=>v.removeEventListener("keydown",P,{capture:!0})},[v,M,P]),l.useEffect(()=>{if(f)return s&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(il=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(f)),d.layers.add(f),ll(),()=>{s&&(d.layersWithOutsidePointerEventsDisabled.delete(f),d.layersWithOutsidePointerEventsDisabled.size===0&&(v.body.style.pointerEvents=il))}},[f,v,s,d]),l.useEffect(()=>()=>{f&&(d.layers.delete(f),d.layersWithOutsidePointerEventsDisabled.delete(f),ll())},[f,d]),l.useEffect(()=>{const E=()=>x({});return document.addEventListener(Ea,E),()=>document.removeEventListener(Ea,E)},[]),r.jsx(_t.div,{...m,ref:p,style:{pointerEvents:w?C?"auto":"none":void 0,...e.style},onFocusCapture:Vt(e.onFocusCapture,k.onFocusCapture),onBlurCapture:Vt(e.onBlurCapture,k.onBlurCapture),onPointerDownCapture:Vt(e.onPointerDownCapture,O.onPointerDownCapture)})});Lu.displayName=jv;var Iv="DismissableLayerBranch",Rv=l.forwardRef((e,t)=>{const s=l.useContext(Mo),n=l.useRef(null),a=gs(t,n);return l.useEffect(()=>{const o=n.current;if(o)return s.branches.add(o),()=>{s.branches.delete(o)}},[s.branches]),r.jsx(_t.div,{...e,ref:a})});Rv.displayName=Iv;function Tv(){const e=l.useContext(Mo),[t,s]=l.useState(null);return l.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),s}var Mv=()=>!0;function Av(e,t){const{ownerDocument:s=globalThis?.document,deferPointerDownOutside:n=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:o,shouldHandlePointerDownOutside:i=Mv}=t,c=fn(e),u=l.useRef(!1),m=l.useRef(!1),d=l.useRef(new Map),f=l.useRef(()=>{});return l.useEffect(()=>{function h(){m.current=!1,a.current=!1,d.current.clear()}function v(){return Array.from(d.current.values()).some(Boolean)}function x(g){if(!m.current)return;const w=g.target;w instanceof Node&&[...o].some(R=>R.contains(w))||d.current.set(g.type,!0),g.type==="click"&&window.setTimeout(()=>{m.current&&f.current()},0)}function p(g){m.current&&d.current.set(g.type,!1)}const b=g=>{if(g.target&&!u.current){let w=function(){s.removeEventListener("click",f.current);const R=v();h(),R||Fu(Nv,c,C,{discrete:!0})};if(!i(g.target)){s.removeEventListener("click",f.current),h(),u.current=!1;return}const C={originalEvent:g};m.current=!0,a.current=n&&g.button===0,d.current.clear(),!n||g.button!==0?w():(s.removeEventListener("click",f.current),f.current=w,s.addEventListener("click",f.current,{once:!0}))}else s.removeEventListener("click",f.current),h();u.current=!1},y=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const g of y)s.addEventListener(g,x,!0),s.addEventListener(g,p);const S=window.setTimeout(()=>{s.addEventListener("pointerdown",b)},0);return()=>{window.clearTimeout(S),s.removeEventListener("pointerdown",b),s.removeEventListener("click",f.current);for(const g of y)s.removeEventListener(g,x,!0),s.removeEventListener(g,p)}},[s,c,n,a,o,i]),{onPointerDownCapture:()=>u.current=!0}}function Ov(e,t=globalThis?.document){const s=fn(e),n=l.useRef(!1);return l.useEffect(()=>{const a=o=>{o.target&&!n.current&&Fu(Ev,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 ll(){const e=new CustomEvent(Ea);document.dispatchEvent(e)}function Fu(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?kv(a,o):a.dispatchEvent(o)}var An=0,Ss=null;function Dv(){l.useEffect(()=>{Ss||(Ss={start:cl(),end:cl()});const{start:e,end:t}=Ss;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),An++,()=>{An===1&&(Ss?.start.remove(),Ss?.end.remove(),Ss=null),An=Math.max(0,An-1)}},[])}function cl(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Zr="focusScope.autoFocusOnMount",ea="focusScope.autoFocusOnUnmount",ul={bubbles:!1,cancelable:!0},Pv="FocusScope",$u=l.forwardRef((e,t)=>{const{loop:s=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[c,u]=l.useState(null),m=fn(a),d=fn(o),f=l.useRef(null),h=gs(t,u),v=l.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;l.useEffect(()=>{if(n){let p=function(g){if(v.paused||!c)return;const w=g.target;c.contains(w)?f.current=w:Ut(f.current,{select:!0})},b=function(g){if(v.paused||!c)return;const w=g.relatedTarget;w!==null&&(c.contains(w)||Ut(f.current,{select:!0}))},y=function(g){if(document.activeElement===document.body)for(const C of g)C.removedNodes.length>0&&Ut(c)};document.addEventListener("focusin",p),document.addEventListener("focusout",b);const S=new MutationObserver(y);return c&&S.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",b),S.disconnect()}}},[n,c,v.paused]),l.useEffect(()=>{if(c){fl.add(v);const p=document.activeElement;if(!c.contains(p)){const y=new CustomEvent(Zr,ul);c.addEventListener(Zr,m),c.dispatchEvent(y),y.defaultPrevented||(Lv(Bv(_u(c)),{select:!0}),document.activeElement===p&&Ut(c))}return()=>{c.removeEventListener(Zr,m),setTimeout(()=>{const y=new CustomEvent(ea,ul);c.addEventListener(ea,d),c.dispatchEvent(y),y.defaultPrevented||Ut(p??document.body,{select:!0}),c.removeEventListener(ea,d),fl.remove(v)},0)}}},[c,m,d,v]);const x=l.useCallback(p=>{if(!s&&!n||v.paused)return;const b=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,y=document.activeElement;if(b&&y){const S=p.currentTarget,[g,w]=Fv(S);g&&w?!p.shiftKey&&y===w?(p.preventDefault(),s&&Ut(g,{select:!0})):p.shiftKey&&y===g&&(p.preventDefault(),s&&Ut(w,{select:!0})):y===S&&p.preventDefault()}},[s,n,v.paused]);return r.jsx(_t.div,{tabIndex:-1,...i,ref:h,onKeyDown:x})});$u.displayName=Pv;function Lv(e,{select:t=!1}={}){const s=document.activeElement;for(const n of e)if(Ut(n,{select:t}),document.activeElement!==s)return}function Fv(e){const t=_u(e),s=dl(t,e),n=dl(t.reverse(),e);return[s,n]}function _u(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 dl(e,t){const s=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const n of e)if(!(s?!n.checkVisibility({checkVisibilityCSS:!0}):$v(n,{upTo:t})))return n}function $v(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 _v(e){return e instanceof HTMLInputElement&&"select"in e}function Ut(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&_v(e)&&t&&e.select()}}var fl=zv();function zv(){let e=[];return{add(t){const s=e[0];t!==s&&s?.pause(),e=ml(e,t),e.unshift(t)},remove(t){e=ml(e,t),e[0]?.resume()}}}function ml(e,t){const s=[...e],n=s.indexOf(t);return n!==-1&&s.splice(n,1),s}function Bv(e){return e.filter(t=>t.tagName!=="A")}var Uv=qa[" useId ".trim().toString()]||(()=>{}),Kv=0;function ta(e){const[t,s]=l.useState(Uv());return dn(()=>{s(n=>n??String(Kv++))},[e]),e||(t?`radix-${t}`:"")}var qv="Portal",zu=l.forwardRef((e,t)=>{const{container:s,...n}=e,[a,o]=l.useState(!1);dn(()=>o(!0),[]);const i=s||a&&globalThis?.document?.body;return i?Ha.createPortal(r.jsx(_t.div,{...n,ref:t}),i):null});zu.displayName=qv;function Hv(e,t){return l.useReducer((s,n)=>t[s][n]??s,e)}var Nr=e=>{const{present:t,children:s}=e,n=Wv(t),a=typeof s=="function"?s({present:n.isPresent}):l.Children.only(s),o=Vv(n.ref,Qv(a));return typeof s=="function"||n.isPresent?l.cloneElement(a,{ref:o}):null};Nr.displayName="Presence";function Wv(e){const[t,s]=l.useState(),n=l.useRef(null),a=l.useRef(e),o=l.useRef("none"),i=l.useRef(void 0),c=e?"mounted":"unmounted",[u,m]=Hv(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return l.useEffect(()=>{u==="mounted"?(o.current=i.current??Ys(n.current),i.current=void 0):o.current="none"},[u]),dn(()=>{const d=n.current,f=a.current;if(f!==e){const v=o.current,x=Ys(d);e?(i.current=x,m("MOUNT")):x==="none"||d?.display==="none"?m("UNMOUNT"):m(f&&v!==x?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,m]),dn(()=>{if(t){let d;const f=t.ownerDocument.defaultView??window,h=x=>{const b=Ys(n.current).includes(CSS.escape(x.animationName));if(x.target===t&&b&&(m("ANIMATION_END"),!a.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",d=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},v=x=>{x.target===t&&(o.current=Ys(n.current))};return t.addEventListener("animationstart",v),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{f.clearTimeout(d),t.removeEventListener("animationstart",v),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:l.useCallback(d=>{if(d){const f=getComputedStyle(d);n.current=f,i.current=Ys(f)}else n.current=null;s(d)},[])}}function hl(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Vv(...e){const t=l.useRef(e);return t.current=e,l.useCallback(s=>{const n=t.current;let a=!1;const o=n.map(i=>{const c=hl(i,s);return!a&&typeof c=="function"&&(a=!0),c});if(a)return()=>{for(let i=0;i<o.length;i++){const c=o[i];typeof c=="function"?c():hl(n[i],null)}}},[])}function Ys(e){return e?.animationName||"none"}function Qv(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 Gv=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Cs=new WeakMap,On=new WeakMap,Dn={},sa=0,Bu=function(e){return e&&(e.host||Bu(e.parentNode))},Yv=function(e,t){return t.map(function(s){if(e.contains(s))return s;var n=Bu(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})},Xv=function(e,t,s,n){var a=Yv(t,Array.isArray(e)?e:[e]);Dn[s]||(Dn[s]=new WeakMap);var o=Dn[s],i=[],c=new Set,u=new Set(a),m=function(f){!f||c.has(f)||(c.add(f),m(f.parentNode))};a.forEach(m);var d=function(f){!f||u.has(f)||Array.prototype.forEach.call(f.children,function(h){if(c.has(h))d(h);else try{var v=h.getAttribute(n),x=v!==null&&v!=="false",p=(Cs.get(h)||0)+1,b=(o.get(h)||0)+1;Cs.set(h,p),o.set(h,b),i.push(h),p===1&&x&&On.set(h,!0),b===1&&h.setAttribute(s,"true"),x||h.setAttribute(n,"true")}catch(y){console.error("aria-hidden: cannot operate on ",h,y)}})};return d(t),c.clear(),sa++,function(){i.forEach(function(f){var h=Cs.get(f)-1,v=o.get(f)-1;Cs.set(f,h),o.set(f,v),h||(On.has(f)||f.removeAttribute(n),On.delete(f)),v||f.removeAttribute(s)}),sa--,sa||(Cs=new WeakMap,Cs=new WeakMap,On=new WeakMap,Dn={})}},Jv=function(e,t,s){s===void 0&&(s="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),a=Gv(e);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live], script"))),Xv(n,a,s,"aria-hidden")):function(){return null}},Kn="right-scroll-bar-position",qn="width-before-scroll-bar",Zv="with-scroll-bars-hidden",ey="--removed-body-scroll-bar-size";function na(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function ty(e,t){var s=l.useState(function(){return{value:e,callback:t,facade:{get current(){return s.value},set current(n){var a=s.value;a!==n&&(s.value=n,s.callback(n,a))}}}})[0];return s.callback=t,s.facade}var sy=typeof window<"u"?l.useLayoutEffect:l.useEffect,pl=new WeakMap;function ny(e,t){var s=ty(null,function(n){return e.forEach(function(a){return na(a,n)})});return sy(function(){var n=pl.get(s);if(n){var a=new Set(n),o=new Set(e),i=s.current;a.forEach(function(c){o.has(c)||na(c,null)}),o.forEach(function(c){a.has(c)||na(c,i)})}pl.set(s,e)},[e]),s}function ry(e){return e}function ay(e,t){t===void 0&&(t=ry);var s=[],n=!1,a={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return s.length?s[s.length-1]:e},useMedium:function(o){var i=t(o,n);return s.push(i),function(){s=s.filter(function(c){return c!==i})}},assignSyncMedium:function(o){for(n=!0;s.length;){var i=s;s=[],i.forEach(o)}s={push:function(c){return o(c)},filter:function(){return s}}},assignMedium:function(o){n=!0;var i=[];if(s.length){var c=s;s=[],c.forEach(o),i=s}var u=function(){var d=i;i=[],d.forEach(o)},m=function(){return Promise.resolve().then(u)};m(),s={push:function(d){i.push(d),m()},filter:function(d){return i=i.filter(d),s}}}};return a}function oy(e){e===void 0&&(e={});var t=ay(null);return t.options=Kt({async:!0,ssr:!1},e),t}var Uu=function(e){var t=e.sideCar,s=xc(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return l.createElement(n,Kt({},s))};Uu.isSideCarExport=!0;function iy(e,t){return e.useMedium(t),Uu}var Ku=oy(),ra=function(){},Er=l.forwardRef(function(e,t){var s=l.useRef(null),n=l.useState({onScrollCapture:ra,onWheelCapture:ra,onTouchMoveCapture:ra}),a=n[0],o=n[1],i=e.forwardProps,c=e.children,u=e.className,m=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,v=e.noRelative,x=e.noIsolation,p=e.inert,b=e.allowPinchZoom,y=e.as,S=y===void 0?"div":y,g=e.gapMode,w=xc(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=h,R=ny([s,t]),O=Kt(Kt({},w),a);return l.createElement(l.Fragment,null,d&&l.createElement(C,{sideCar:Ku,removeScrollBar:m,shards:f,noRelative:v,noIsolation:x,inert:p,setCallbacks:o,allowPinchZoom:!!b,lockRef:s,gapMode:g}),i?l.cloneElement(l.Children.only(c),Kt(Kt({},O),{ref:R})):l.createElement(S,Kt({},O,{className:u,ref:R}),c))});Er.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Er.classNames={fullWidth:qn,zeroRight:Kn};var ly=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function cy(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=ly();return t&&e.setAttribute("nonce",t),e}function uy(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function dy(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var fy=function(){var e=0,t=null;return{add:function(s){e==0&&(t=cy())&&(uy(t,s),dy(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},my=function(){var e=fy();return function(t,s){l.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},qu=function(){var e=my(),t=function(s){var n=s.styles,a=s.dynamic;return e(n,a),null};return t},hy={left:0,top:0,right:0,gap:0},aa=function(e){return parseInt(e||"",10)||0},py=function(e){var t=window.getComputedStyle(document.body),s=t[e==="padding"?"paddingLeft":"marginLeft"],n=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return[aa(s),aa(n),aa(a)]},gy=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return hy;var t=py(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])}},xy=qu(),Ts="data-scroll-locked",by=function(e,t,s,n){var a=e.left,o=e.top,i=e.right,c=e.gap;return s===void 0&&(s="margin"),`
|
|
76
|
-
.`.concat(
|
|
74
|
+
`},zg=(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}",Bg=(e,t,s)=>{if(t==="plain")return`${Mi}<style>${_g(s)}</style>${e}`;const n=$g.test(e);return`${Mi}<style>${zg(s,n)}</style>${e}`},Ug=5e4,Kg=1e4,qg="(max-width: 640px)",Hg=.4,Wg="allow-same-origin allow-popups allow-popups-to-escape-sandbox",Ai=(e,t,s)=>Math.min(Math.ceil(Math.max(e,t)),s),Vg=(e,t)=>e<=0||t<=0||e<=t?1:Math.max(Hg,t/e),Qg=e=>{const[t,s]=l.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return l.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Gg=new Set(["Enter","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"]),Yg=e=>e===" "?!1:e.length===1?!0:Gg.has(e),Oi=e=>{if(e.metaKey||e.ctrlKey||e.altKey||!Yg(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}))},Di=({html:e,variant:t="framed",isDark:s=!1,className:n})=>{const a=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(0),[u,m]=l.useState(0),[d,f]=l.useState(0),h=Qg(qg),v=l.useMemo(()=>Bg(e,t,s),[e,t,s]);l.useEffect(()=>{const g=a.current;if(!g)return;const w=()=>f(R=>R===g.clientWidth?R:g.clientWidth);w();const C=new ResizeObserver(w);return C.observe(g),()=>C.disconnect()},[]),l.useEffect(()=>{const g=o.current;if(!g)return;const w=()=>{const k=g.contentDocument;if(!k?.body)return;const M=k.documentElement,P=Ai(k.body.scrollHeight,M?.scrollHeight??0,Ug);c(L=>L===P?L:P);const E=Ai(k.body.scrollWidth,M?.scrollWidth??0,Kg);m(L=>L===E?L:E)};let C,R;const O=()=>{w();const k=g.contentDocument;k?.body&&(C=new ResizeObserver(w),C.observe(k.body),k.documentElement&&C.observe(k.documentElement),k.addEventListener("keydown",Oi),R=k)};return g.addEventListener("load",O),()=>{g.removeEventListener("load",O),R?.removeEventListener("keydown",Oi),C?.disconnect()}},[]);const x=h?Vg(u,d):1,p=x<1,b=p?`${u}px`:h?"100%":t==="framed"&&u>0?`max(100%, ${u}px)`:u===0?"100%":`${u}px`,y=i===0?"1px":`${i}px`,S=r.jsx("iframe",{ref:o,title:"Email content",sandbox:Wg,srcDoc:v,className:p?void 0:n,scrolling:"no",style:{width:b,maxWidth:p?"none":void 0,border:"none",display:"block",height:y,overflow:"hidden",transform:p?`scale(${x})`:void 0,transformOrigin:p?"top left":void 0,colorScheme:"normal"}});return r.jsx("div",{ref:a,className:p?n:void 0,children:p?r.jsx("div",{style:{width:"100%",height:`${Math.ceil(i*x)}px`,overflow:"hidden"},children:S}):S})},Pi=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),xu=({html:e,text:t,isDark:s=!1,category:n,allowImages:a=!1,resolveCid:o,className:i,renderBlockedNotice:c})=>{const u=l.useMemo(()=>!e||typeof document>"u"?null:Lg({allowExternalImages:a,resolveCid:o})(e),[e,a,o]),m=u?.html??null,{framed:d,isPlain:f}=kg(n,u?.hasAuthorBackground??!1),h=l.useMemo(()=>!m||a?0:(m.match(/data-blocked-src/g)||[]).length,[m,a]);return!m&&!t?r.jsx("div",{className:Q("message-body",i),children:r.jsx(Pi,{})}):r.jsxs("div",{className:Q("message-body",i),children:[h>0&&r.jsx("div",{className:"message-body-notice",children:c?.(h)}),m?d?r.jsx("div",{className:"w-full max-w-full overflow-x-auto",children:r.jsx(Di,{html:m,variant:"framed",isDark:s})}):r.jsx("div",{className:"max-w-full overflow-x-auto lg:max-w-2xl",children:r.jsx(Di,{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(Pi,{})]})};function zs({message:e="Select a thread to read",icon:t,showHints:s=!0,className:n}){return r.jsxs("div",{className:Q("flex flex-1 flex-col items-center justify-center text-center",n),children:[t??r.jsx(Ba,{className:"size-10 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:e}),s&&r.jsxs("p",{className:"text-2xs text-fg-subtle",children:[r.jsx(Is,{children:"j"})," / ",r.jsx(Is,{children:"k"})," to move, ",r.jsx(Is,{children:"Enter"})," to open"]})]})}function bu({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(jt,{name:e.fromName,email:e.fromEmail,size:"md"}),n&&r.jsx("span",{className:"absolute -top-0.5 -right-0.5 size-2 rounded-full border border-canvas bg-accent"})]}),r.jsx("span",{className:Q("w-36 shrink-0 truncate text-sm",n?"font-semibold text-fg":"font-medium text-fg-muted"),children:e.fromName}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-fg-subtle",children:e.snippet}),a??r.jsx("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:e.dateLabel})]}),i=Q("group flex h-section-row w-full items-center gap-3 border-b border-line px-2 text-left transition-colors hover:bg-surface-sunken lg:px-4",s&&"bg-surface-sunken ring-1 ring-inset ring-accent/30");return t?r.jsx("div",{role:"button",tabIndex:0,"aria-expanded":!1,onClick:t,onKeyDown:c=>{rm(c)&&(c.preventDefault(),t())},className:Q(i,"cursor-pointer"),children:o}):r.jsx("div",{className:i,children:o})}function vu({message:e,warning:t,onHeaderClick:s,isFocused:n,senderBadge:a,trailing:o,to:i,indicators:c,actionMenu:u,actionBar:m,body:d}){const f=r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[r.jsxs("span",{className:"text-sm font-semibold text-fg",children:[e.fromName,a]}),o??r.jsx("span",{className:"text-2xs text-fg-subtle",children:e.dateLabel})]}),r.jsx("div",{className:"text-xs text-fg-subtle",children:e.fromEmail}),i!==null&&r.jsx("div",{className:"text-xs text-fg-subtle",children:i??r.jsxs(r.Fragment,{children:["to ",e.toLabel]})})]});return r.jsxs("div",{className:Q("px-2 py-3 lg:px-4",n&&"ring-1 ring-inset ring-accent/30"),children:[r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(Qt,{className:"mt-1 size-3.5 shrink-0 text-fg-subtle"}),r.jsx(jt,{name:e.fromName,email:e.fromEmail,size:"md"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[s?r.jsx("button",{type:"button",onClick:s,className:"w-full text-left",children:f}):f,c]}),u&&r.jsx("div",{className:"shrink-0",children:u})]}),t&&r.jsxs("div",{className:"mt-3 flex items-start gap-3 rounded-md bg-danger-soft p-3",children:[r.jsx($s,{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(xu,{className:"mt-3",html:e.bodyHtml,category:e.framed?"newsletter":"personal",allowImages:!0})})]})}function Xg({thread:e,onBack:t,intelligence:s,intelligenceOpen:n,onToggleIntelligence:a,actions:o,children:i,touchHandlers:c}){const[u,m]=l.useState(!1),d=a!==void 0,f=d?n??!1:u,h=!!s||d,v=()=>{if(d){a?.();return}m(p=>!p)},x=()=>{if(d){f&&a?.();return}m(!1)};return r.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Ua,{className:"size-4"}),onClick:t,"aria-label":"Back to messages",className:"-ml-1 shrink-0"}),r.jsx("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:e.subject}),h&&r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(uc,{className:"size-4"}),onClick:v,"aria-label":f?"Hide intelligence panel":"Show intelligence panel","aria-pressed":f,title:"Intelligence",className:Q("shrink-0",f&&"bg-accent-2-soft text-accent-2")})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",style:c?{touchAction:"pan-y"}:void 0,...c,children:i??e.messages.map(p=>{const b=y=>y?()=>y(p.id):void 0;return p.expanded?r.jsx(vu,{message:p,warning:e.warning,onHeaderClick:b(o?.onToggleExpand),actionBar:r.jsx(gu,{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(bu,{message:p,onClick:b(o?.onToggleExpand)},p.id)})}),s&&!d&&r.jsx(am,{open:f,onClose:x,title:"Intelligence",anchor:"right",className:"p-0",children:r.jsx(tu,{data:s,onClose:x,className:"h-full w-full border-l-0"})})]})}const Jg="button:not([disabled]), a[href]",us="outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-surface-sunken";function Zg({active:e,dimmed:t,indent:s}){return Q("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors",us,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 ex({icon:e,label:t,count:s,active:n}){return r.jsxs(r.Fragment,{children:[e&&r.jsx("span",{className:Q("shrink-0",n?"text-accent-2":"text-fg-subtle"),children:e}),r.jsx("span",{className:"flex-1 truncate",children:t}),s!=null&&s>0&&r.jsx("span",{className:Q("text-2xs tabular-nums",n?"text-accent-2":"text-fg-subtle"),children:s})]})}function rn({icon:e,label:t,count:s,active:n,dimmed:a,indent:o,navId:i,linkComponent:c,ariaLabel:u,title:m,onClick:d}){const f=Zg({active:n,dimmed:a,indent:o}),h=r.jsx(ex,{icon:e,label:t,count:s,active:n});return i&&c?c({navId:i,className:f,ariaLabel:u??t,title:m,onClick:d,children:h}):r.jsx("button",{type:"button",onClick:d,className:f,"aria-label":u,title:m,children:h})}const Li={inbox:0,flagged:1,drafts:2,sent:3,archive:4,all:5,junk:6,trash:7};function tx(e){switch(e){case"inbox":return r.jsx(Ba,{className:"size-4"});case"flagged":return r.jsx(Xt,{className:"size-4"});case"drafts":return r.jsx(fc,{className:"size-4"});case"sent":return r.jsx(pn,{className:"size-4"});case"archive":return r.jsx(cm,{className:"size-4"});case"all":return r.jsx(lm,{className:"size-4"});case"junk":return r.jsx(im,{className:"size-4"});case"trash":return r.jsx(Lt,{className:"size-4"})}}const Fi=e=>e.role!=null,Gr=8,$i="remit.nav.folders.open.",_i="remit.nav.account.open.";function zi(e,t,s){if(typeof localStorage>"u")return s;const n=localStorage.getItem(e+t);return n===null?s:n!=="0"}function Bi(e,t,s){typeof localStorage>"u"||localStorage.setItem(e+t,s?"1":"0")}function sx({query:e,onSelect:t,onRemove:s}){return r.jsxs("div",{className:"group flex w-full items-center gap-1 rounded-md pr-1 hover:bg-surface",children:[r.jsxs("button",{type:"button",onClick:t,className:Q("flex min-w-0 flex-1 items-center gap-2 px-2 py-1 text-left text-sm text-fg-muted transition-colors hover:text-fg",us),children:[r.jsx(ir,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate",children:e})]}),s&&r.jsx("button",{type:"button",onClick:s,"aria-label":`Remove saved search: ${e}`,className:Q("shrink-0 rounded-full p-1 text-fg-subtle opacity-0 transition-opacity hover:bg-surface-sunken hover:text-fg group-hover:opacity-100 focus-visible:opacity-100",us),children:r.jsx(Nt,{className:"size-3.5"})})]})}function nx({savedSearches:e,saveableQuery:t,onSelectSavedSearch:s,onRemoveSavedSearch:n,onSaveCurrentSearch:a}){return e.length===0&&!t?null:r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:"px-2 pb-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Saved searches"}),t&&r.jsxs("button",{type:"button",onClick:a,className:Q("flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-accent transition-colors hover:bg-surface",us),children:[r.jsx(Ap,{className:"size-4 shrink-0"}),r.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Save “",t,"”"]})]}),e.map(o=>r.jsx(sx,{query:o,onSelect:()=>s?.(o),onRemove:n?()=>n(o):void 0},o))]})}function rx({account:e,selectedNavId:t,onSelectNav:s,linkComponent:n}){const[a,o]=l.useState(()=>zi(_i,e.id,!0)),[i,c]=l.useState(()=>zi($i,e.id,!0)),[u,m]=l.useState(!1),d=()=>{o(S=>{const g=!S;return Bi(_i,e.id,g),g})},f=()=>{c(S=>{const g=!S;return Bi($i,e.id,g),g})},h=e.mailboxes.filter(Fi).sort((S,g)=>Li[S.role]-Li[g.role]),v=e.mailboxes.filter(S=>!Fi(S)),x=u||v.length<=Gr?v:v.slice(0,Gr),p=v.length-x.length,b=e.status??"ready",y=b==="ready"&&h.length===0&&v.length===0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("button",{type:"button",onClick:d,"aria-expanded":a,className:Q("flex w-full items-center gap-1.5 px-2 pb-1 text-left transition-colors hover:text-fg",us,e.muted&&"opacity-55"),children:[a?r.jsx(Qt,{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(Wc,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:"muted"})]})]}),a&&r.jsxs(r.Fragment,{children:[b==="loading"&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"Loading…"}),b==="error"&&r.jsxs("div",{role:"alert",className:"mx-2 my-1 flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-2 py-1.5 text-sm",children:[r.jsx(Pt,{className:"mt-0.5 size-4 shrink-0 text-danger","aria-hidden":"true"}),r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx("p",{className:"font-medium text-danger",children:"Couldn't load mailboxes"})}),e.onRetry&&r.jsx("button",{type:"button",onClick:e.onRetry,className:"shrink-0 text-sm font-medium text-accent hover:underline",children:"Retry"})]}),y&&r.jsx("div",{className:"px-2 py-1 text-sm text-fg-muted",children:"No mailboxes"}),b==="ready"&&r.jsxs(r.Fragment,{children:[h.map(S=>r.jsx(rn,{navId:S.id,linkComponent:n,icon:tx(S.role),label:S.name,ariaLabel:S.name,title:S.fullPath??S.name,count:S.unseen,active:t===S.id,dimmed:e.muted,onClick:()=>s?.(S.id)},S.id)),e.outboxPending!==void 0&&r.jsx(rn,{navId:"outbox",linkComponent:n,icon:r.jsx(pn,{className:"size-4"}),label:"Outbox",ariaLabel:"Outbox",count:e.outboxPending>0?e.outboxPending:void 0,active:t==="outbox",dimmed:e.muted,onClick:()=>s?.("outbox")}),v.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",onClick:f,"aria-expanded":i,className:Q("mt-1 flex w-full items-center gap-1 px-2 py-1 text-left text-2xs font-semibold uppercase tracking-wider text-fg-subtle transition-colors hover:text-fg",us),children:[i?r.jsx(Qt,{className:"size-3 shrink-0"}):r.jsx(Ms,{className:"size-3 shrink-0"}),r.jsx("span",{className:"flex-1",children:"Folders"}),r.jsx("span",{className:"tabular-nums opacity-70",children:v.length})]}),i&&r.jsxs(r.Fragment,{children:[x.map(S=>r.jsx(rn,{navId:S.id,linkComponent:n,icon:r.jsx(om,{className:"size-4"}),label:S.name,ariaLabel:S.name,title:S.fullPath??S.name,count:S.unseen,active:t===S.id,dimmed:e.muted,onClick:()=>s?.(S.id)},S.id)),(p>0||u)&&v.length>Gr&&r.jsx("button",{type:"button",onClick:()=>m(S=>!S),className:Q("ml-7 flex items-center px-2 py-1 text-2xs font-medium text-accent transition-colors hover:underline",us),children:u?"Show less":`Show all (${v.length})`})]})]})]})]})]})}function ax({accounts:e,selectedNavId:t,briefUnseen:s,onSelectNav:n,variant:a="desktop",linkComponent:o,savedSearches:i=[],saveableQuery:c,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:d}){const f=l.useRef(null);or({containerRef:f,itemSelector:Jg});const h=a==="drawer",v=r.jsxs("nav",{ref:h?f:void 0,className:h?"px-2 py-2":"flex-1 overflow-y-auto px-2 py-2","aria-label":"Mailboxes",children:[r.jsx(rn,{navId:"brief",linkComponent:o,icon:r.jsx(Dt,{className:"size-4"}),label:"Daily brief",ariaLabel:"Daily brief",count:s,active:t==="brief",onClick:()=>n?.("brief")}),r.jsx(rn,{navId:"flagged",linkComponent:o,icon:r.jsx(Xt,{className:"size-4"}),label:"Starred",ariaLabel:"Starred",active:t==="flagged",onClick:()=>n?.("flagged")}),r.jsx(nx,{savedSearches:i,saveableQuery:c,onSelectSavedSearch:u,onRemoveSavedSearch:m,onSaveCurrentSearch:d}),e.length===0?r.jsx("div",{className:"px-2 py-4 text-center text-sm text-fg-muted",children:"No accounts configured"}):e.map(x=>r.jsx(rx,{account:x,selectedNavId:t,onSelectNav:n,linkComponent:o},x.id))]});return h?v:r.jsx("aside",{ref:f,className:"flex h-full w-full flex-col bg-surface-sunken",children:v})}function ox({leading:e,search:t,actions:s,className:n}){return r.jsxs("header",{className:Q("flex min-h-pane-header w-full shrink-0 items-center gap-2 border-b border-line bg-canvas px-row-inset py-1",n),children:[e&&r.jsx("div",{className:"flex shrink-0 items-center gap-1",children:e}),r.jsx("div",{className:"flex min-w-0 flex-1 justify-start",children:r.jsx("div",{className:"w-full max-w-xs transition-[max-width] duration-150 ease-out focus-within:max-w-lg",children:t})}),s&&r.jsx("div",{className:"flex shrink-0 items-center gap-1",children:s})]})}const ix=/[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069\ufeff]/g,lx=/[<>:"|?*]/g,cx=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,Ui=120,ux=12,dx="attachment",Ki=e=>{const t=[...e];if(t.length<=Ui)return e;const s=e.lastIndexOf("."),n=s>0&&[...e.slice(s)].length<=ux?e.slice(s):"",a=Ui-[...n].length;return t.slice(0,a).join("")+n},fx=(e,t=dx)=>{const n=e.replace(ix,"").split(/[/\\]/),o=(n[n.length-1]??"").replace(lx,"_").replace(/^[.\s]+/,"").replace(/[.\s]+$/,"");if(o.length===0)return Ki(t);const i=cx.test(o)?`_${o}`:o;return Ki(i)},qi=["KB","MB","GB","TB"],mx=e=>{if(!Number.isFinite(e)||e<0)return"unknown size";const t=Math.round(e);if(t<1024)return t===1?"1 byte":`${t} bytes`;const s=1023.95;let n=t/1024,a=0;for(;n>=s&&a<qi.length-1;)n/=1024,a+=1;return`${n.toFixed(1).replace(/\.0$/,"")} ${qi[a]}`};function hx({state:e,onRetry:t}){return r.jsxs("div",{role:"alert","data-testid":"attachment-error",className:"flex items-start gap-2 border-t border-danger/30 bg-danger-soft px-2 py-2 text-xs",children:[r.jsx(Pt,{className:"mt-0.5 size-3.5 shrink-0 text-danger","aria-hidden":!0}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"font-medium text-danger",children:e.title}),r.jsx("p",{className:"mt-0.5 text-fg-muted",children:e.detail})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[r.jsx("button",{type:"button",onClick:t,className:"font-medium text-accent hover:underline",children:"Try again"}),e.reportUrl&&r.jsx("a",{href:e.reportUrl,target:"_blank",rel:"noreferrer",className:"font-medium text-accent hover:underline",children:"Report this"})]})]})}function px({attachments:e,onDownload:t,hasUnlistedAttachment:s=!1,className:n}){return e.length===0&&!s?null:r.jsxs("section",{"aria-label":"Attachments","data-testid":"attachment-list",className:Q("space-y-1.5",n),children:[r.jsxs("h3",{className:"flex items-center gap-1.5 text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:[r.jsx(yr,{className:"size-3","aria-hidden":!0}),e.length===0?"Attachment":e.length===1?"1 attachment":`${e.length} attachments`]}),e.length>0&&r.jsx("ul",{className:"overflow-hidden rounded-sm border border-line bg-surface",children:e.map(a=>{const o=a.download.status==="downloading";return r.jsxs("li",{className:"border-t border-line first:border-t-0",children:[r.jsxs("button",{type:"button",onClick:()=>t(a.attachmentId),disabled:o,"data-testid":"attachment-download","aria-label":`Download ${a.filename}`,className:"flex w-full items-center gap-2 px-2 py-2 text-left transition-colors hover:bg-surface-sunken disabled:cursor-progress disabled:opacity-60",children:[r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsx("bdi",{className:"block truncate text-sm text-fg",title:a.filename,children:a.filename}),r.jsxs("span",{className:"block truncate text-2xs text-fg-subtle",children:[a.typeLabel," ·"," ",mx(a.sizeOctets)]})]}),o?r.jsx(hs,{className:"size-4 shrink-0 animate-spin text-fg-subtle","aria-hidden":!0}):r.jsx(Vh,{className:"size-4 shrink-0 text-fg-subtle","aria-hidden":!0})]}),a.download.status==="failed"&&r.jsx(hx,{state:a.download,onRetry:()=>t(a.attachmentId)})]},a.attachmentId)})}),s&&r.jsx("p",{role:"alert","data-testid":"attachment-unlisted",className:"rounded-sm border border-line bg-surface px-2 py-2 text-xs text-fg-muted",children:"The mail server says this message carries an attachment, but none of its parts describe one. Re-sync the account from Settings; if the attachment still does not appear, the message is worth reporting."})]})}function gx({label:e,onUndo:t,undoLabel:s="Undo",filtersHref:n,className:a}){return r.jsxs(kt,{tone:"accent",className:Q("py-1 text-xs",a),children:[r.jsx(_p,{className:"size-3.5 shrink-0","aria-hidden":!0}),r.jsx("span",{children:e}),t&&r.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),t()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:s}),n&&r.jsx("a",{href:n,onClick:o=>{o.stopPropagation()},className:"font-semibold underline decoration-dotted underline-offset-2 hover:decoration-solid",children:"Manage filter"})]})}function xx({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(hs,{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:bx(e)})]}):r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 py-12 text-center px-4",children:[r.jsx(Dt,{className:"size-8 text-fg-subtle","aria-hidden":"true"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"You're caught up"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Nothing needs attention."})]})}function bx({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 vx="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",Hi="pointer-events-none absolute inset-0 m-auto size-3.5 text-accent-fg";function So({label:e,description:t,indeterminate:s=!1,checked:n,onChange:a,className:o,...i}){const c=l.useRef(null);l.useEffect(()=>{c.current&&(c.current.indeterminate=s)},[s]);const u=r.jsxs("span",{className:"relative inline-flex",children:[r.jsx("input",{ref:c,type:"checkbox",checked:n,onChange:a,className:vx,...i}),r.jsx(hn,{className:Q(Hi,"hidden peer-checked:block"),"aria-hidden":!0}),r.jsx(Pp,{className:Q(Hi,"hidden peer-indeterminate:block"),"aria-hidden":!0})]});return e===void 0&&t===void 0?r.jsx("span",{className:o,children:u}):r.jsxs("label",{className:Q("flex min-h-11 cursor-pointer items-center gap-3 text-left",o),children:[u,r.jsxs("span",{className:"flex min-w-0 flex-col",children:[e!==void 0&&r.jsx("span",{className:"text-sm text-fg",children:e}),t!==void 0&&r.jsx("span",{className:"text-xs text-fg-subtle",children:t})]})]})}const yx=({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 wx({onSend:e,onDiscard:t,sending:s,canSend:n,saveStatus:a="idle",unavailableReason:o,onUnavailable:i}){return r.jsxs("div",{className:"flex items-center justify-between border-t border-line px-3 py-2",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(ce,{variant:"primary",size:"md","aria-busy":s,title:n?void 0:o,className:"min-h-11 rounded-full px-4",icon:s?r.jsx(hs,{className:"size-4 animate-spin"}):r.jsx(pn,{className:"size-4"}),onClick:()=>{if(!s){if(!n){o&&i?.(o);return}e()}},children:"Send"}),r.jsx(yx,{status:a})]}),r.jsx(ce,{variant:"ghost",size:"md","aria-busy":s,"aria-label":"Discard",className:"min-h-11 min-w-11 px-2 hover:text-danger",icon:r.jsx(Lt,{className:"size-4"}),onClick:()=>{s||t()}})]})}const Sx=["Tab",","],Wi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),Cx=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(Wi(a))return{email:a,displayName:n}}if(Wi(t))return{email:t}},kx=({label:e,addresses:t,onChange:s,placeholder:n,suggestions:a=[],onQueryChange:o})=>{const[i,c]=l.useState(""),u=l.useRef(null),m=new Set(t.map(g=>g.email.toLowerCase())),d=i.length>=2?a.filter(g=>!m.has(g.email.toLowerCase())):[],f=l.useCallback(g=>{m.has(g.email.toLowerCase())||(s([...t,g]),c(""),o?.(""))},[t,m,s,o]),h=l.useCallback(g=>{s(t.filter((w,C)=>C!==g))},[t,s]),v=l.useCallback(g=>{f(g),u.current?.focus()},[f]),x=l.useCallback(()=>{const g=Cx(i);g&&f(g)},[i,f]),p=mc({count:d.length,acceptKeys:Sx,onAccept:g=>v(d[g])}),b=l.useMemo(()=>d.map(g=>({value:g.email,label:g.displayName??g.email,...g.displayName?{hint:g.email}:{}})),[d]),y=l.useCallback(g=>{if(g.key==="Backspace"&&i===""&&t.length>0){h(t.length-1);return}p.handleKeyDown(g)||(g.key==="Enter"||g.key==="Tab"||g.key===",")&&i.trim()&&(g.preventDefault(),x())},[i,t.length,h,p.handleKeyDown,x]),S=l.useCallback(()=>{setTimeout(()=>{x(),p.dismiss()},150)},[x,p.dismiss]);return r.jsxs("div",{className:"relative",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),r.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>u.current?.focus(),onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&u.current?.focus()},children:[t.map((g,w)=>r.jsx(Up,{email:g.email,displayName:g.displayName,onRemove:()=>h(w)},g.email)),r.jsx("input",{ref:u,id:`address-field-${e}`,type:"text",value:i,onChange:g=>{p.reopen(),c(g.target.value),o?.(g.target.value)},onKeyDown:y,onBlur:S,placeholder:t.length===0?n:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5",autoComplete:"off",...p.comboboxProps})]})]}),p.open&&r.jsx(hc,{id:p.listId,suggestions:b,activeIndex:p.activeIndex,optionId:p.optionId,onPick:g=>{const w=d.find(C=>C.email===g.value);w&&v(w)},onHighlight:p.setActiveIndex,label:`${e} suggestions`,className:"absolute left-12 right-0 z-50 mt-1 max-h-[200px] shadow-lg"})]})};function jx({banner:e,header:t,children:s,quoted:n,actionBar:a}){return r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e,t,r.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-auto","data-testid":"compose-body-area",children:[s,n&&r.jsx("div",{className:"shrink-0 px-3 pb-2",children:n})]}),a]})}const Yr=({label:e,onClick:t})=>r.jsx("button",{type:"button",onClick:t,className:"text-xs text-fg-muted hover:text-fg transition-colors",children:e}),Nx=({to:e,cc:t,bcc:s,subject:n})=>{const a=[];return e.length>0&&a.push(`To: ${e.map(o=>o.displayName??o.email).join(", ")}`),t.length>0&&a.push(`Cc: ${t.length}`),s.length>0&&a.push(`Bcc: ${s.length}`),n&&a.push(n),a.join(" · ")},Ex=({collapsed:e=!1,summary:t="",from:s,to:n,cc:a,bcc:o,subject:i,onShowCc:c,onShowBcc:u})=>e?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[r.jsx("span",{className:"truncate text-xs text-fg-muted",children:t||"…"}),r.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]}):r.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[s,n,a??r.jsxs("div",{className:"flex gap-2 pl-14",children:[r.jsx(Yr,{label:"Cc",onClick:c}),r.jsx(Yr,{label:"Bcc",onClick:u})]}),a&&!o&&r.jsx("div",{className:"pl-14",children:r.jsx(Yr,{label:"Bcc",onClick:u})}),o,i]}),Ix=({onConfigure:e})=>r.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[r.jsx(Ka,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),r.jsxs("button",{type:"button",onClick:e,className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",r.jsx(um,{className:"size-3","aria-hidden":"true"})]})]})]}),Rx=({value:e,onChange:t})=>r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),r.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]});function Tx({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 Mx({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 Ax(e,t){const s=t-1;return s<=0?null:e<s?e:s-1}const Ox=e=>e instanceof HTMLElement?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable:!1,Dx=({chips:e=[],onRemoveChip:t,value:s,onChange:n,onClear:a,onClearQuery:o,placeholder:i="Search mail...",globalFocusKey:c=!0,showClearButton:u=!0,size:m="sm",inputId:d,suggest:f,className:h})=>{const v=l.useId(),x=d??v,p=l.useRef(null),b=l.useRef([]),y=o??a,[S,g]=l.useState(null),w=l.useRef(void 0),[C,R]=l.useState(""),O=e.length>0;l.useEffect(()=>{g(I=>I!==null&&I>=e.length?null:I)},[e.length]),l.useEffect(()=>{const I=w.current;if(I!==void 0){if(w.current=void 0,I===null){p.current?.focus();return}b.current[I]?.focus()}});const k=l.useRef(void 0);l.useEffect(()=>{const I=f?.caret;if(!I||I===k.current)return;k.current=I;const D=p.current;!D||D.ownerDocument.activeElement!==D||(D.setSelectionRange(I.cursor,I.cursor),f?.onCaretChange(I.cursor))});const M=I=>{f?.onCaretChange(I.selectionStart??I.value.length)},P=l.useCallback(I=>{g(I),w.current=I},[]),E=l.useCallback(I=>{const D=e[I];D&&t&&(P(Ax(I,e.length)),R(`${D.label} removed`),t(D.id))},[e,t,P]),L=l.useCallback(()=>{P(null),a()},[a,P]),A=l.useCallback(I=>{const D=I.currentTarget;if(f?.onKeyDown(I))return;const T=Tx({key:I.key,shiftKey:I.shiftKey,repeat:I.repeat,caretAtStart:D.selectionStart===0&&D.selectionEnd===0,hasValue:s.length>0,chipCount:e.length});switch(T.type){case"focusChip":I.preventDefault(),P(T.index);return;case"clearQuery":y();return;case"blur":D.blur();return;case"none":return}},[e.length,s,y,P,f]),j=l.useCallback(I=>D=>{const T=Mx({key:D.key,repeat:D.repeat,index:I,chipCount:e.length});switch(T.type!=="none"&&D.preventDefault(),T.type){case"removeChip":E(T.index);return;case"focusChip":P(T.index);return;case"focusInput":P(null);return;case"activateChip":return;case"none":return}},[e,E,P]);return l.useEffect(()=>{if(!c)return;const I=D=>{D.key!=="/"||D.metaKey||D.ctrlKey||D.altKey||Ox(D.target)||(D.preventDefault(),p.current?.focus())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[c]),r.jsxs("label",{htmlFor:x,className:Q("flex w-full items-center gap-1.5 text-sm","bg-surface-sunken/50 border border-transparent","focus-within:bg-canvas focus-within:border-line focus-within:ring-2 focus-within:ring-ring","transition-colors",m==="lg"?"rounded-xl px-4 py-2":"rounded-md px-2.5 py-1",h),children:[r.jsx(ir,{className:Q("shrink-0 text-fg-muted pointer-events-none",m==="lg"?"size-5":"size-4")}),r.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1",children:[O&&r.jsx("div",{role:"grid","aria-label":"Search filters",className:"flex min-w-0 flex-wrap items-center gap-1",children:e.map((I,D)=>r.jsx(dm,{ref:T=>{b.current[D]=T},label:I.label,tone:I.tone,focused:S===D,onFocusLabel:()=>g(D),onKeyDown:j(D),onRemove:()=>E(D)},I.id))}),r.jsx("input",{ref:p,id:x,name:"q",type:"text","aria-label":"Search mail",autoComplete:"off",value:s,tabIndex:S===null?0:-1,onChange:I=>{n(I.target.value),M(I.target)},onKeyDown:A,onKeyUp:I=>M(I.currentTarget),onClick:I=>M(I.currentTarget),onFocus:I=>{g(null),f?.onFocusChange?.(!0),M(I.currentTarget)},onBlur:()=>f?.onFocusChange?.(!1),...f?.comboboxProps,placeholder:O?void 0:i,className:"min-w-24 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted"})]}),(s||O)&&u&&r.jsx("button",{type:"button",onClick:L,className:"shrink-0 rounded p-0.5 hover:bg-surface-raised transition-colors","aria-label":"Clear search",children:r.jsx(Nt,{className:Q("text-fg-muted",m==="lg"?"size-5":"size-4")})}),r.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:C})]})},Co=({value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i="Search mail...",globalFocusKey:c=!0,showClearButton:u=!0,size:m,inputId:d,suggest:f,className:h})=>r.jsx(Dx,{value:e,onChange:t,onClear:s,onClearQuery:n,chips:a,onRemoveChip:o,placeholder:i,globalFocusKey:c,showClearButton:u,size:m,inputId:d,suggest:f,className:h});function Px(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 Lx({result:e,onClick:t,query:s,showFolder:n=!0}){const a=n&&e.folder?fm(e.folder):void 0;return r.jsx("button",{type:"button",onClick:t,className:Q("group",_s({}),"border-b border-line"),children:r.jsx(yo,{thread:Px(e),highlightQuery:s,badge:r.jsxs(r.Fragment,{children:[a&&r.jsx(kt,{tone:"neutral",className:"shrink-0",children:a}),e.category&&r.jsx(kt,{tone:e.category.tone??"neutral",className:"shrink-0",children:e.category.label}),e.matchedChunkLabel&&r.jsx(kt,{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 Fx=e=>e===1?"result":"results";function yu({count:e,onScopeToSpam:t}){return r.jsx(gn,{tone:"info",variant:"soft",className:"items-center justify-between gap-3 rounded-none border-b border-line",children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("p",{className:"min-w-0 text-xs text-fg-muted",children:[r.jsx("span",{className:"font-semibold text-fg tabular-nums",children:e})," ",`${Fx(e)} from Spam`]}),r.jsx(ce,{variant:"ghost",size:"sm",onClick:t,className:"shrink-0 text-accent",children:"Go to Spam"})]})})}const Vi=6,$x={kind:"global"},_x=e=>e.kind==="folder"&&e.role==="junk",zx=e=>e.folder?.role==="junk";function ko(e){const t=[],s=[];for(const n of e)zx(n)?s.push(n):t.push(n);return{kept:t,spam:s}}function wu({onClick:e,blockedReason:t}){const s=l.useId(),[n,a]=l.useState(!1);return r.jsxs("div",{className:"border-b border-line px-row-inset py-1.5",children:[r.jsxs("button",{type:"button",onClick:()=>{if(t){a(!0);return}e()},"aria-describedby":t?s:void 0,className:Q("flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs font-medium transition-colors",t?"text-fg-subtle opacity-55":"text-accent hover:bg-surface-sunken"),children:[r.jsx(mm,{className:"size-3.5 shrink-0","aria-hidden":"true"}),r.jsx("span",{children:"Make this a filter"})]}),t&&r.jsx(hm,{id:s,reason:t,nudged:n,className:"px-2 pt-1 text-2xs text-warning"})]})}function Bx({section:e,query:t,onSelectResult:s,showFolder:n}){const[a,o]=l.useState(e.initialCollapsed??!1),[i,c]=l.useState(!1),u=e.results.length>Vi,d=!i&&u?e.results.slice(0,Vi):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(Qt,{className:Q("size-3 shrink-0 text-fg-subtle transition-transform duration-200",a?"rotate-0":"rotate-180")})]}),!a&&r.jsxs(r.Fragment,{children:[d.map(h=>r.jsx(Lx,{result:h,query:t,showFolder:n,onClick:s?()=>s(h):void 0},h.id)),u&&r.jsxs("button",{type:"button",onClick:()=>c(h=>!h),className:"flex w-full items-center justify-center border-b border-line px-row-inset py-1.5 text-2xs font-medium text-accent transition-colors hover:bg-surface",children:[i?"Show less":`Show ${f} more`,!i&&r.jsx(Qt,{className:"ml-1 size-3"})]})]})]})}function Su({value:e,recentSearches:t,onPickRecent:s,sections:n,loading:a,onSelectResult:o,tokens:i,scope:c=$x,makeFilter:u}){if(!(e.trim().length>0))return t&&t.length>0?r.jsxs("div",{className:"flex flex-col",children:[r.jsx("h3",{className:"px-row-inset pb-1 pt-3 text-2xs font-semibold uppercase tracking-wide text-fg-subtle",children:"Recent searches"}),t.map(w=>r.jsxs("button",{type:"button",onClick:()=>s?.(w),className:"flex w-full items-center gap-2.5 border-b border-line px-row-inset py-2.5 text-left transition-colors hover:bg-surface-sunken",children:[r.jsx(oo,{className:"size-4 shrink-0 text-fg-subtle"}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-fg-muted",children:w})]},w))]}):r.jsx("p",{className:"px-row-inset py-6 text-center text-sm text-fg-subtle",children:"Search across your mail by sender, subject or words in the message."});const d=i&&i.length>0&&r.jsx(pm,{tokens:i}),f=u&&r.jsx(wu,{...u});if(a)return r.jsxs("div",{className:"flex flex-col",children:[f,d,r.jsx("div",{className:"flex flex-col gap-3 px-row-inset py-4",children:[0,1,2,3].map(w=>r.jsxs("div",{className:"flex flex-col gap-1.5",children:[r.jsx("div",{className:"h-3 w-1/3 animate-pulse rounded bg-surface-sunken"}),r.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-surface-sunken"}),r.jsx("div",{className:"h-2.5 w-1/2 animate-pulse rounded bg-surface-sunken"})]},w))})]});const h=c.kind==="global",v=_x(c)||c.kind==="collection",x=h||c.kind==="collection",p=(n??[]).map(w=>{if(v)return{section:w,spam:[]};const{kept:C,spam:R}=ko(w.results);return{section:{...w,results:C},spam:R}}),b=p.map(w=>w.section),y=p.reduce((w,C)=>w+C.spam.length,0),S=c.kind==="global"&&y>0&&c.onScopeToSpam!==void 0?r.jsx(yu,{count:y,onScopeToSpam:c.onScopeToSpam}):void 0;return b.some(w=>w.results.length>0)?r.jsxs("div",{className:"flex flex-col",children:[f,d,S,b.filter(w=>w.results.length>0).map(w=>r.jsx(Bx,{section:w,query:e,showFolder:x,onSelectResult:o},w.id))]}):r.jsxs("div",{className:"flex flex-col",children:[f,d,S,r.jsxs("div",{className:"px-row-inset py-10 text-center",children:[r.jsxs("p",{className:"text-sm font-medium text-fg",children:["No matches for “",e,"”"]}),r.jsx("p",{className:"mt-1 text-xs text-fg-subtle",children:"Try a different word, or adjust the filters above."})]})]})}function Ux({value:e,onChange:t,onClear:s,onCancel:n,filter:a,recentSearches:o,onPickRecent:i,sections:c,loading:u,onSelectResult:m,tokens:d,chips:f,onRemoveChip:h,scope:v,makeFilter:x,suggest:p,suggestList:b}){const y=r.jsx(Su,{value:e,recentSearches:o,onPickRecent:i,sections:c,loading:u,onSelectResult:m,tokens:d,scope:v,makeFilter:x});return r.jsxs("article",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line bg-surface px-row-inset",children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(Co,{value:e,onChange:t,onClear:s,chips:f,onRemoveChip:h,globalFocusKey:!1,showClearButton:!1,suggest:p})}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Nt,{className:"size-4"}),onClick:n,"aria-label":"Clear and close search",className:"-mr-1 shrink-0"})]}),b,a&&e.trim().length===0?r.jsx(gm,{children:r.jsx(pc,{...a,children:y})}):r.jsx("div",{className:"flex-1 overflow-y-auto",children:y})]})}function Kx(){const e=ps();if(!e)return null;const t=e.showNavPane?!e.navCollapsed:!1;return r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(pr,{className:"size-4"}),onClick:e.toggleNav,"aria-label":t?"Hide folders":"Show folders","aria-expanded":t,title:"Folders",className:"shrink-0"})}const qx={queued:{icon:oo,label:"Queued",className:"text-warning"},sending:{icon:hs,label:"Sending…",className:"text-accent-2",spin:!0},sent:{icon:go,label:"Sent",className:"text-positive"},failed:{icon:Pt,label:"Failed",className:"text-danger"},blocked:{icon:Ka,label:"Blocked",className:"text-warning"}};function Qi({status:e,iconOnly:t,className:s}){const n=qx[e],a=n.icon;return r.jsxs("span",{className:Q("inline-flex items-center gap-1.5 text-xs font-medium",n.className,s),children:[r.jsx(a,{className:Q("size-4",n.spin&&"animate-spin")}),!t&&n.label]})}const Hx=(e,t)=>t?"bg-accent-2-soft":e==="failed"?"bg-danger-soft":e==="blocked"?"bg-warning/10":"";function Wx({recipients:e,subject:t,time:s,status:n,error:a,selected:o,onSelect:i,onRetry:c,retrying:u,onEdit:m,onDelete:d,deleting:f}){const h=n==="failed"||n==="blocked";return r.jsxs("div",{className:Q("flex items-start gap-3 border-b border-line px-4 py-3 transition-colors hover:bg-surface-raised",Hx(n,o)),children:[r.jsxs("button",{type:"button",...lc,onClick:i,className:"flex flex-1 min-w-0 items-start gap-3 text-left",children:[r.jsx("div",{className:"mt-0.5 shrink-0",children:r.jsx(Qi,{status:n,iconOnly:!0})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"truncate text-sm font-medium",children:e}),r.jsx("span",{className:"shrink-0 text-xs text-fg-muted",children:s})]}),r.jsx("div",{className:"truncate text-sm",children:t||"No subject"}),r.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[r.jsx(Qi,{status:n}),a&&r.jsxs("span",{className:"truncate text-xs text-fg-muted",children:["— ",a]})]})]})]}),h&&r.jsx("div",{className:"shrink-0",children:r.jsx(Dh,{actions:[...n==="failed"&&c?[{label:"Retry sending",iconOnly:!0,icon:r.jsx(Ah,{className:"size-3.5"}),busy:u,onClick:c}]:[],{label:"Edit as draft",iconOnly:!0,icon:r.jsx(pn,{className:"size-3.5"}),onClick:m}],destructive:{label:"Delete message",iconOnly:!0,icon:r.jsx(Lt,{className:"size-3.5"}),busy:f,confirm:{prompt:"Delete this message?",confirmLabel:"Delete"},onClick:d}})})]})}const Vx=e=>{const[t,s]=l.useState(()=>typeof window>"u"||!window.matchMedia?!1:window.matchMedia(e).matches);return l.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(e);s(n.matches);const a=o=>s(o.matches);return n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[e]),t},Qx=({children:e,onRefresh:t,isRefreshing:s})=>Vx(Mc)?e:r.jsx(xm,{onRefresh:t,isPullable:!s,children:e}),Gx=({text:e,html:t,senderName:s,date:n})=>{const[a,o]=l.useState(!1);if(!e&&!t)return null;const i=[s,n].filter(Boolean).join(" on ");return r.jsxs("div",{className:"mt-2 px-3 pb-2",children:[r.jsxs("button",{type:"button",onClick:()=>o(!a),"aria-expanded":a,className:"flex items-center gap-1 text-xs text-fg-muted hover:text-fg transition-colors",children:[a?r.jsx(Qt,{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((c,u)=>r.jsx("p",{className:"min-h-[1.2em]",children:c},u))})]})};function jo({state:e,onRefresh:t,label:s,errorMessage:n,hasUpdate:a,size:o="sm",className:i}){const c=e==="refreshing",u=e==="error",m=e==="success",d=u?r.jsx(Pt,{className:"size-4 text-danger"}):m?r.jsx(go,{className:"size-4 text-positive"}):r.jsx(xo,{className:Q("size-4",c&&"animate-spin")}),f=u?`${s} — failed: ${n??"try again"}`:c?`${s} — refreshing`:m?`${s} — up to date`:a?`${s} — new mail`:s;return r.jsxs("div",{className:"relative inline-flex",children:[r.jsx(ce,{variant:"ghost",size:o,icon:d,onClick:t,disabled:c,"aria-label":f,"aria-busy":c||void 0,title:u?n:s,className:i}),e==="idle"&&a&&r.jsx("span",{"aria-hidden":"true",className:"absolute right-1 top-1 size-1.5 rounded-full bg-accent-2"})]})}const Yx=e=>e===1?"message":"messages";function Xx({count:e,onReview:t,onDismiss:s,actionLabel:n="Review & rescue"}){return r.jsx(gn,{tone:"info",variant:"soft",onDismiss:s,children:r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsxs("p",{className:"flex items-start gap-2 text-sm text-fg",children:[r.jsx(xn,{className:"mt-0.5 size-4 shrink-0 text-positive","aria-hidden":!0}),r.jsxs("span",{children:[r.jsx("span",{className:"font-semibold text-fg",children:`${e} ${Yx(e)} here`})," ","may not be spam — they're from senders we can verify."]})]}),r.jsx(ce,{variant:"primary",size:"sm",onClick:t,className:"self-start",children:n})]})})}const Jx=(e,t)=>e==="vip"?"vip":e==="unknown"&&t==="md"?"unknown-pill":"hidden",Cu=({senderTrust:e,size:t="sm",className:s})=>{const n=Jx(e,t);return n==="vip"?r.jsx(Dt,{className:Q("text-warning shrink-0",t==="sm"&&"size-3.5",t==="md"&&"size-4",s),"aria-label":"VIP sender","data-testid":"sender-trust-vip"}):n==="unknown-pill"?r.jsx("span",{className:Q("inline-flex items-center rounded border border-dashed border-fg-subtle/40 font-medium uppercase tracking-wide text-fg-muted/80 shrink-0","px-2 py-0.5 text-xs",s),title:"First message from this sender","aria-label":"First message from this sender","data-testid":"sender-trust-unknown",children:"new"}):null};function Zx({candidate:e,selected:t,onToggle:s,hideSender:n=!1}){const{senderName:a,senderAddress:o,subject:i,snippet:c,trustReason:u,trustSubReason:m,senderTrust:d}=e;return r.jsxs("label",{className:Q("flex w-full cursor-pointer items-start gap-3 px-3 py-2.5 text-left transition-colors",n&&"pl-11",t?"bg-positive/10":"bg-surface hover:bg-surface-sunken"),children:[r.jsx(So,{className:"mt-0.5",checked:t,onChange:s,"aria-label":`${t?"Deselect":"Select"} ${n?i:`message from ${a}`}`}),!n&&r.jsx(jt,{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(Cu,{senderTrust:d,size:"sm"}),r.jsx("span",{className:"truncate text-2xs text-fg-subtle",children:o})]}),r.jsx("span",{className:"block truncate text-sm text-fg-muted",children:i}),r.jsx("span",{className:"block line-clamp-1 text-xs text-fg-subtle",children:c}),!n&&r.jsxs("span",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[r.jsxs(kt,{tone:"positive",children:[r.jsx(xn,{className:"size-3","aria-hidden":!0}),u]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:m})]})]})]})}const eb=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)},tb=(e,t)=>{const s=e.messages.filter(n=>t.has(n.id)).length;return s===0?"none":s===e.messages.length?"all":"some"},Gi=e=>e===1?"message":"messages";function sb({group:e,selected:t,onToggleGroup:s,onToggleMessage:n}){const[a,o]=l.useState(!1),i=tb(e,t),c=e.messages.length,u=a?Qt:Ms;return r.jsxs("div",{className:Q(i!=="none"?"bg-positive/10":"bg-surface"),children:[r.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-2.5",children:[r.jsx(So,{className:"mt-0.5",checked:i==="all",indeterminate:i==="some",onChange:()=>s(e,i!=="all"),"aria-label":`${i==="all"?"Deselect":"Select"} all ${c} ${Gi(c)} from ${e.senderName}`}),r.jsx(jt,{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(Cu,{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(kt,{tone:"positive",children:[r.jsx(xn,{className:"size-3","aria-hidden":!0}),e.trustReason]}),r.jsx("span",{className:"text-2xs text-fg-subtle",children:e.trustSubReason})]})]}),r.jsxs("button",{type:"button",onClick:()=>o(m=>!m),"aria-expanded":a,className:"flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-2xs text-fg-muted transition-colors hover:bg-surface-sunken hover:text-fg",children:[`${c} ${Gi(c)}`,r.jsx(u,{className:"size-3.5","aria-hidden":!0})]})]}),a&&r.jsx("div",{className:"divide-y divide-line border-t border-line",children:e.messages.map(m=>r.jsx(Zx,{candidate:m,selected:t.has(m.id),onToggle:()=>n(m.id),hideSender:!0},m.id))})]})}const No=e=>e===1?"message":"messages",nb=(e,t)=>`Moves ${e===1?"this message":`these ${e} ${No(e)}`} out of Spam to ${t} now. Nothing later.`,ja=(e,t)=>e.find(s=>s.id===t)?.label??"Inbox";function rb(){return r.jsx(gn,{tone:"info",variant:"soft",children:r.jsx("p",{className:"text-2xs text-fg-muted",children:"We list a message here only when we can confirm the sender is who they say — usually someone you've emailed before, write to often, or a service that consistently checks out. We never guess from words in the subject. Anything we can't confirm stays in Spam."})})}function ab({candidates:e,selected:t,onToggle:s,onToggleGroup:n,onSelectAll:a,onSelectNone:o,onContinue:i,onCancel:c}){const[u,m]=l.useState(!1),d=t.size,f=l.useMemo(()=>eb(e),[e]);return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("h2",{className:"flex items-center gap-2 text-sm font-semibold text-fg",children:[r.jsx(xn,{className:"size-4 text-positive","aria-hidden":!0}),"Rescue from Spam"]}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Mh,{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(rb,{})})]}),r.jsxs("div",{className:"flex items-center justify-between px-row-inset pb-1.5",children:[r.jsx("span",{className:"text-2xs font-medium text-fg-muted",children:`${d} of ${e.length} selected · ${f.length} ${f.length===1?"sender":"senders"}`}),r.jsxs("span",{className:"flex gap-1",children:[r.jsx(ce,{variant:"ghost",size:"sm",onClick:a,children:"Select all"}),r.jsx(ce,{variant:"ghost",size:"sm",onClick:o,children:"Select none"})]})]}),r.jsx("div",{className:"min-h-0 flex-1 divide-y divide-line overflow-y-auto border-y border-line",children:f.map(h=>r.jsx(sb,{group:h,selected:t,onToggleGroup:n,onToggleMessage:s},h.key))}),r.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[r.jsx(ce,{variant:"primary",onClick:i,className:"h-11 w-full font-semibold",children:`Continue with ${d} ${No(d)}`}),r.jsx(ce,{variant:"ghost",onClick:c,className:"h-11 w-full",children:"Cancel"})]})]})}function ob({count:e,folders:t,delimiter:s,destination:n,onPick:a,onMove:o,onBack:i}){const[c,u]=l.useState(!1);return r.jsxs("div",{className:"flex min-h-0 flex-col",children:[r.jsxs("div",{className:"px-row-inset pb-2 pt-1",children:[r.jsx("h2",{className:"text-sm font-semibold text-fg",children:"Where should they go?"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Pick a folder, then we move them out of Spam."})]}),r.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-row-inset py-2",children:c?r.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden rounded-xl border border-line bg-surface",children:r.jsx(gc,{folders:t,selectedId:n,delimiter:s,onSelect:a,onCancel:()=>u(!1)})}):r.jsxs("div",{className:"rounded-xl border border-line bg-surface-sunken p-3",children:[r.jsx("p",{className:"text-2xs text-fg-subtle",children:"Destination"}),r.jsx("p",{className:"mt-0.5 text-sm font-medium text-fg",children:ja(t,n)}),r.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"mt-2 px-0",children:"Move to a different folder"})]})}),r.jsxs("div",{className:"space-y-2 border-t border-line bg-surface px-row-inset py-3",children:[r.jsx("p",{className:"text-2xs text-fg-subtle",children:nb(e,ja(t,n))}),r.jsx(ce,{variant:"primary",onClick:o,className:"h-11 w-full font-semibold",children:`Move ${e} out of Spam`}),r.jsx(ce,{variant:"ghost",onClick:i,className:"h-11 w-full",children:"Back"})]})]})}function ib({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(Qh,{className:"size-10 text-positive","aria-hidden":!0}),r.jsx("p",{className:"text-base font-semibold text-fg",children:`Moved ${e} ${No(e)} out of Spam.`}),r.jsx("p",{className:"text-2xs text-fg-subtle",children:`You'll find them in ${t}.`})]}),r.jsx("div",{className:"border-t border-line bg-surface px-row-inset py-3",children:r.jsx(ce,{variant:"primary",onClick:s,className:"h-11 w-full font-semibold",children:"Done"})})]})}function lb({open:e,candidates:t,defaultDestinationId:s,availableFolders:n,delimiter:a,onConfirmMove:o,onCancel:i}){const[c,u]=l.useState("review"),[m,d]=l.useState(()=>e?new Set(t.map(w=>w.id)):new Set),[f,h]=l.useState(s),[v,x]=l.useState(0),p=l.useRef(!1);l.useEffect(()=>{e&&!p.current&&(u("review"),d(new Set(t.map(w=>w.id))),h(s),x(0)),p.current=e},[e,t,s]);const b=m.size,y=w=>{d(C=>{const R=new Set(C);return R.has(w)?R.delete(w):R.add(w),R})},S=(w,C)=>{d(R=>{const O=new Set(R);for(const k of w.messages)C?O.add(k.id):O.delete(k.id);return O})},g=()=>{const w=Array.from(m);x(w.length),o(w,f),u("done")};return r.jsxs(Lh,{open:e,onClose:i,dismissLabel:"Close rescue",children:[c==="review"&&r.jsx(ab,{candidates:t,selected:m,onToggle:y,onToggleGroup:S,onSelectAll:()=>d(new Set(t.map(w=>w.id))),onSelectNone:()=>d(new Set),onContinue:()=>u("destination"),onCancel:i}),c==="destination"&&r.jsx(ob,{count:b,folders:n,delimiter:a,destination:f,onPick:h,onMove:g,onBack:()=>u("review")}),c==="done"&&r.jsx(ib,{count:v,destinationLabel:ja(n,f),onClose:i})]})}const cb={html:"",text:"",formatting:[]},Yi=e=>e.toLocaleString();function Xi({selectAll:e,selecting:t,className:s}){return r.jsx(So,{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 Eo({title:e,count:t,onCancel:s,onDelete:n,onMove:a,onOrganize:o,onJunk:i,onMarkRead:c,navSlot:u,titleMeta:m,searchSlot:d,searchField:f,idleSlot:h,overflowSlot:v,isBusy:x=!1,isCounting:p=!1,selectAll:b,statusLabel:y,progress:S,notice:g}){const w=t>0||p,C=b?.checked?`All ${Yi(t)} loaded selected`:`${Yi(t)} ${t===1?"message":"messages"} selected`,R=[];return i&&!x&&!p&&R.push({key:"junk",label:"Junk",icon:r.jsx($s,{className:"size-4"}),onSelect:i}),c&&!x&&!p&&R.push({key:"mark-read",label:"Mark read",icon:r.jsx(vr,{className:"size-4"}),onSelect:c}),r.jsxs("header",{"data-selection-bar":"",className:"flex shrink-0 flex-col border-b border-line bg-surface-sunken",children:[r.jsxs("div",{"data-selection-bar-row":"actions",className:"flex h-pane-header items-center gap-1 px-row-inset",children:[w?r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(Ua,{className:"size-5"}),onClick:s,"aria-label":"Cancel selection",className:"-ml-2 shrink-0"}):u,b&&r.jsx(Xi,{selectAll:b,selecting:w,className:"hidden shrink-0 pr-2 md:flex"}),w?r.jsx("span",{"data-selection-count":"",className:"min-w-0 flex-1 truncate px-1 text-sm font-medium text-fg",role:"status","aria-live":"polite",children:y??C}):f?r.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:f}):r.jsxs(r.Fragment,{children:[r.jsx("h1",{className:"min-w-0 flex-1 truncate px-1 text-sm font-semibold text-fg",children:e}),m,d]}),w&&!p&&r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",size:"touch",icon:x?r.jsx(hs,{className:"size-5 animate-spin"}):r.jsx(Lt,{className:"size-5 text-danger"}),onClick:x?void 0:n,"aria-label":"Move selected messages to Trash","aria-busy":x||void 0,className:"shrink-0"}),!x&&a&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(za,{className:"size-5"}),onClick:a,"aria-label":"Move selected messages",className:"shrink-0"}),!x&&o&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(Dt,{className:"size-5"}),onClick:o,"aria-label":"Organize selected messages",className:"shrink-0"})]}),w&&r.jsx(wo,{triggerLabel:"More actions",items:R,className:"shrink-0",children:!x&&!p&&v})]}),!w&&h,w&&b&&r.jsx("div",{"data-selection-bar-row":"select-all",className:"px-row-inset pb-2 md:hidden",children:r.jsx(Xi,{selectAll:b,selecting:w,className:"w-full"})}),S&&r.jsx("div",{className:"px-row-inset pb-2",children:r.jsx(bm,{value:S.value,max:S.max,tone:S.tone})}),g&&r.jsx(gn,{"data-selection-notice":"",tone:g.tone,variant:"soft",role:"status","aria-live":"polite",className:"mx-row-inset mb-2",children:r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[g.text&&r.jsx("span",{children:g.text}),g.action&&r.jsx(ce,{variant:"ghost",size:"md",onClick:g.action.onClick,className:"-my-1 min-h-11 shrink-0",children:g.action.label})]})})]})}const ub={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function db({search:e,onCompose:t,onReportBug:s,onOpenSettings:n,composeShortcut:a,refreshControl:o,account:i}){return r.jsx(ox,{leading:r.jsx(Kx,{}),search:r.jsx(Co,{value:e.value,onChange:e.onChange,onClear:e.onClear,onClearQuery:e.onClearQuery,chips:e.chips,onRemoveChip:e.onRemoveChip,placeholder:ub[e.scope]}),actions:r.jsxs(r.Fragment,{children:[r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx($p,{className:"size-4"}),title:a?`Compose (${a})`:"Compose","aria-label":"Compose",onClick:t}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(Vc,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:s}),r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(eu,{className:"size-4"}),title:"Settings","aria-label":"Settings",onClick:n}),o,i]})})}const Io=[{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"}],ku={id:"unread",label:"Unread"},fb={id:"flagged",label:"Starred"},ju={id:"attachment",label:"Has attachment"};function mb(e){if(!(e.length<=1))return e.map(t=>({id:t.id,label:t.label,count:t.count,active:t.active}))}function hb(e=[]){return{categories:[...Io],filters:vm,sources:mb(e)}}function Nu(){return{categories:[...Io],filters:[ku,fb,ju]}}function pb(){return{categories:[...Io],filters:[ku,ju]}}const gb=["p","br","div","h1","h2","h3","h4","h5","h6","strong","b","em","i","u","s","ul","ol","li","blockquote","pre","code","hr","table","thead","tbody","tr","th","td","a","img"],xb=["href","src","alt","colspan","rowspan","lang","dir"],bb=/^(?:https?:|mailto:)/i,vb=/^(?:https:|data:image\/)/i,yb=e=>{const t=dc();if(!t.isSupported)throw new Error("adopted HTML cannot be sanitized: no DOM is available");return t.addHook("afterSanitizeAttributes",s=>{if(s.tagName==="A"){bb.test(s.getAttribute("href")??"")||s.removeAttribute("href"),e==="quoted"&&(s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer nofollow"));return}if(s.tagName==="IMG"){if(e==="quoted"){s.remove();return}vb.test(s.getAttribute("src")??"")||s.remove()}}),t},Ji=new Map,wb=e=>{const t=Ji.get(e);if(t)return t;const s=yb(e);return Ji.set(e,s),s},Eu=(e,t)=>wb(t).sanitize(e,{ALLOWED_TAGS:gb,ALLOWED_ATTR:xb,ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1}),f1=e=>Eu(e,"outgoing"),Sb=e=>Eu(e,"quoted");function wr(e){const t=[];let s=-1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];if(o==='"'){n=!n,s<0&&(s=a);continue}if(!n&&/\s/.test(o)){s>=0&&t.push({raw:e.slice(s,a),start:s,end:a}),s=-1;continue}s<0&&(s=a)}return s>=0&&t.push({raw:e.slice(s),start:s,end:e.length}),t}const Cb=e=>{if(!e.startsWith('"'))return e;const t=e.slice(1);return t.endsWith('"')?t.slice(0,-1):t};function Sr(e){const t=e.indexOf(":");if(t<=0)return;const s=e.slice(t+1);return{name:e.slice(0,t).toLowerCase(),value:Cb(s),rawValue:s}}const kb=e=>/[\s"]/.test(e),jb=e=>kb(e)?`"${e.replace(/"/g,"")}"`:e,Cr=(e,t)=>`${e}:${jb(t)}`,Iu=[{id:"unread",name:"is",value:"unread"},{id:"attachment",name:"has",value:"attachment"}],Ru="category",Nb={unclassified:"uncategorized"},bn=e=>wr(e).map(t=>t.raw),un=e=>e.join(" "),Ro=e=>{const t=Sr(e);if(t)return Iu.find(s=>s.name===t.name&&s.value===t.value.toLowerCase())?.id},To=e=>{const t=Sr(e);if(!t||t.name!==Ru)return;const s=t.value.toLowerCase(),n=Nb[s];if(n)return n;if(!(!ym(s)||s==="all"))return s},Tu=e=>Iu.find(t=>t.id===e),Mu=e=>Tu(e)!==void 0,Eb=e=>{const t=new Set;for(const s of bn(e)){const n=Ro(s);n&&t.add(n)}return t},Ib=e=>{let t="all";for(const s of bn(e)){const n=To(s);n&&(t=n)}return t},Rb=(e,t)=>{const s=Tu(t);if(!s)return;const n=bn(e),a=n.filter(o=>Ro(o)!==t);return a.length<n.length?un(a):un([...n,Cr(s.name,s.value)])},Tb=(e,t)=>{const s=bn(e).filter(n=>!To(n));return un(t==="all"?s:[...s,Cr(Ru,t)])},Mb=e=>un(bn(e).filter(t=>!Ro(t)&&!To(t))),Au=e=>e.trim().length>0,Ab=e=>{if(!Au(e.query))return e.ownFilters;const t=new Set(Eb(e.query));for(const s of e.ownFilters)Mu(s)||t.add(s);return t},Ob=e=>Au(e.query)?Ib(e.query):e.ownCategory,Db=e=>typeof e=="string"&&e.length>0?"rich":"plain",m1=(e,t)=>t.length>0,Pb={plain:"Couldn't switch to plain text",rich:"Couldn't switch to rich text"},h1=(e,t,s)=>t.trim()===""||s.trim()!==""?{outcome:"switch"}:{outcome:"blocked",title:Pb[e],detail:"The conversion came back empty, so your message is unchanged."};function Lb(e,t){return e.endsWith(t)?e.length===t.length||e[e.length-t.length-1]===".":!1}function Fb(e,t){const s=e.length-t.length-2,n=e.lastIndexOf(".",s);return n===-1?e:e.slice(n+1)}function $b(e,t,s){if(s.validHosts!==null){const a=s.validHosts;for(const o of a)if(Lb(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:Fb(t,e)}const Xr=/[\t\n\r]/g;let Na=!1;function Zi(e){return e>=97&&e<=122||e>=48&&e<=57||e>127||e>=65&&e<=90||e===45||e===95}function el(e,t,s){const n=s-t,a=e.charCodeAt(t)|32;if(n===2)return a===119&&(e.charCodeAt(t+1)|32)===115?1:0;if(n===3){const o=e.charCodeAt(t+1)|32,i=e.charCodeAt(t+2)|32;return a===119&&o===115&&i===115||a===102&&o===116&&i===112?1:0}else if(n===4){const o=e.charCodeAt(t+1)|32,i=e.charCodeAt(t+2)|32,c=e.charCodeAt(t+3)|32;return a===104&&o===116&&i===116&&c===112?1:a===102&&o===105&&i===108&&c===101?2:0}else if(n===5)return a===104&&(e.charCodeAt(t+1)|32)===116&&(e.charCodeAt(t+2)|32)===116&&(e.charCodeAt(t+3)|32)===112&&(e.charCodeAt(t+4)|32)===115?1:0;return 0}function an(e,t,s=!1){let n=0,a=e.length,o=!1,i=!1;if(Na=!1,!t){if(e.startsWith("data:"))return null;for(;n<e.length&&e.charCodeAt(n)<=32;)n+=1;for(;a>n+1&&e.charCodeAt(a-1)<=32;)a-=1;if(e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47)n+=2;else{const b=e.indexOf(":/",n);if(b!==-1){const y=el(e,n,b);if(y===1)for(i=!0,n=b+2;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1;else if(y===2){i=!0,n=b+1;let S=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&S<2;)n+=1,S+=1;if(S<2)return null}else{for(let S=n;S<b;S+=1){const g=e.charCodeAt(S)|32;if(!(g>=97&&g<=122||g>=48&&g<=57||g===46||g===45||g===43)){const w=e.charCodeAt(S);return w===9||w===10||w===13?an(e.replace(Xr,""),t,s):null}}if(e.charCodeAt(b+2)===47)n=b+3;else return null}}else if(e.charCodeAt(n)!==91){let y=-1;for(let S=n;S<a;S+=1){const g=e.charCodeAt(S);if(g===9||g===10||g===13)return an(e.replace(Xr,""),t,s);if(g===58){y=S;break}if(g===47||g===92||g===63||g===35)break}if(y!==-1){let S=!1;for(let g=y+1;g<a;g+=1){const w=e.charCodeAt(g);if(w===47||w===92||w===63||w===35)break;if(w===64){S=!0;break}}if(!S){let g=!0,w=y+1;for(;w<a;w+=1){const C=e.charCodeAt(w);if(C===47||C===92||C===63||C===35)break;if(C<48||C>57){g=!1;break}}if(w===y+1&&(g=!1),!g){const C=el(e,n,y);if(C===0){let R=!1;for(let O=y+1;O<a;O+=1){const k=e.charCodeAt(O);if(k===47||k===92||k===63||k===35)break;if(k===58){R=!0;break}}if(!R)return null}else if(i=!0,n=y+1,C===2){let R=0;for(;(e.charCodeAt(n)===47||e.charCodeAt(n)===92)&&R<2;)n+=1,R+=1;if(R<2)return null}else for(;e.charCodeAt(n)===47||e.charCodeAt(n)===92;)n+=1}}}}}let u=-1,m=-1,d=-1,f=-1,h=!1,v=s,x=n-1,p=-1;if(s&&n<a){const b=e.charCodeAt(n);(!(Zi(b)||b===46||b===95)||b===45)&&(v=!1)}for(let b=n;b<a;b+=1){const y=e.charCodeAt(b);if(y<64)if(y===47||y===35||y===63){a=b;break}else y===58?(f===-1&&(f=b),d=b):y===9||y===10||y===13?h=!0:s&&(y===46?((b-x>64||p===46||p===45)&&(v=!1),x=b):(y<48||y>57)&&(y!==45||p===46)&&(v=!1));else if(i&&y===92){a=b;break}else y===64?(u=b,f=-1):y===93?m=b:y>=65&&y<=90?o=!0:s&&!Zi(y)&&(v=!1);s&&(p=y)}if(h)return an(e.replace(Xr,""),t,s);if(u!==-1&&u>=n&&u<a&&(n=u+1),e.charCodeAt(n)===91)return m!==-1?e.slice(n+1,m).toLowerCase():null;if(d!==-1&&d>n&&d<a&&f===d&&(a=d),n>=a)return null;s&&v&&u===-1&&d===-1&&m===-1&&e.charCodeAt(a-1)!==46&&a-n<=255&&a-x-1<=63&&p!==45&&(Na=!0)}for(;a>n+1&&e.charCodeAt(a-1)===46;)a-=1;const c=n!==0||a!==e.length?e.slice(n,a):e;return o?c.toLowerCase():c}function _b(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 zb(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 Bb(e){return zb(e)||_b(e)}function tl(e){return e>=97&&e<=122||e>=48&&e<=57||e>127}function sl(e){if(e.length>255||e.length===0||!tl(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(!(tl(o)||o===45||o===95)||o===45&&s===46)return!1;s=o}return n-t-1<=63&&s!==45}function Ub({allowIcannDomains:e=!0,allowPrivateDomains:t=!1,detectIp:s=!0,detectSpecialUse:n=!1,extractHostname:a=!0,mixedInputs:o=!0,validHosts:i=null,validateHostname:c=!0}){return{allowIcannDomains:e,allowPrivateDomains:t,detectIp:s,detectSpecialUse:n,extractHostname:a,mixedInputs:o,validHosts:i,validateHostname:c}}const Kb=Ub({});function qb(e){return Kb}function Hb(){return{domain:null,domainWithoutSuffix:null,hostname:null,isIcann:null,isIp:null,isPrivate:null,isSpecialUse:null,publicSuffix:null,subdomain:null}}function Wb(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 Vb(e,t,s,n,a){const o=qb();if(typeof e!="string")return a;let i=!1;return o.extractHostname?o.mixedInputs?(i=sl(e),a.hostname=an(e,i,o.validateHostname)):a.hostname=an(e,!1,o.validateHostname):a.hostname=e,o.detectIp&&a.hostname!==null&&(a.isIp=Bb(a.hostname),a.isIp)?a:o.validateHostname&&o.extractHostname&&a.hostname!==null&&!(i&&a.hostname===e)&&!Na&&!sl(a.hostname)?(a.hostname=null,a):(a.hostname===null||(s(a.hostname,o,a),a.publicSuffix===null)||(a.domain=$b(a.publicSuffix,a.hostname,o)),a)}const nl=Hb();function Qb(e,t){return Wb(nl),Vb(e,3,wm,t,nl).domain}const kr=e=>{const t=new Set,s=[];for(const n of e){const a=n.trim();if(a==="")continue;const o=a.toLowerCase();t.has(o)||(t.add(o),s.push(a))}return s},Gb=e=>{const t=e.lastIndexOf("@");return t>=0?e.slice(t+1):e},Ou=e=>Qb(Gb(e.trim())),Yb=e=>{const t=kr(e);if(t.length<2)return null;let s=null;for(const n of t){const a=Ou(n);if(a===null)return null;if(s===null)s=a;else if(s!==a)return null}return s},jr=e=>{const t=Yb(e);return t!==null?[{field:"FromDomain",value:t}]:kr(e).map(s=>({field:"From",value:s}))},Xb=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},Du=e=>e.displayName?.trim()||e.normalizedEmail,Jb=/^\s*(?:(?:re|aw|fwd?|vs|sv|antw|res|enc|tr)\s*(?:\[\d+\])?\s*:|\[[^\]]{1,32}\])\s*/i,Zb=e=>{let t=e.replace(/\s+/g," ").trim();for(;;){const s=t.replace(Jb,"");if(s===t)return t.trim();t=s}},ev=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"]),tv=3,Jr=e=>e.split(" ").filter(t=>t!==""),rl=e=>e.length===0||e.join(" ").length<tv?!1:e.some(t=>!ev.has(t.toLowerCase())),sv=(e,t)=>e.findIndex((s,n)=>t.every((a,o)=>e[n+o]?.toLowerCase()===a.toLowerCase())),nv=e=>{const t=e.map(Zb).filter(o=>o!=="");if(t.length===0)return;const[s,...n]=t;if(n.length===0)return rl(Jr(s))?s:void 0;const a=Jr(s);for(let o=a.length;o>0;o-=1)for(let i=0;i+o<=a.length;i+=1){const c=a.slice(i,i+o);if(rl(c)&&n.every(u=>sv(Jr(u),c)>=0))return c.join(" ")}},rv=(e,t)=>{const s=jr(e);if(kr(e).length===1||s.length===1&&s[0].field==="FromDomain")return s;const n=nv(t);return n!==void 0?[{field:"Subject",value:n}]:s},av=({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}`:""},ov=e=>e.clauses.length>0,iv=e=>({scopedOutFolder:e.scopedOut?.label,droppedFacets:e.droppedFacets.map(t=>t.label),droppedSemantic:e.droppedSemantic}),lv=({orderedIds:e,isDesktop:t,initialFocusedId:s,initialSelectedIds:n,onExitSelection:a})=>{const[o,i]=l.useState(s),[c,u]=l.useState(),m=l.useCallback(T=>{u(F=>F===T?F:void 0),i(T)},[]),d=au({initialSelectedIds:n}),{selectedCount:f,toggle:h,clearSelection:v,selectRange:x,setAnchor:p,selectAll:b}=d,y=vo(f,t),S=l.useRef(null),g=l.useRef(!1),w=l.useCallback(()=>{a?.(),v()},[v,a]),C=l.useMemo(()=>o?e.indexOf(o):-1,[e,o]),R=l.useCallback(T=>{if(T<0||T>=e.length)return;const F=e[T];if(y){h(F);return}S.current=F,g.current=!1,u(F),i(F)},[e,y,h]),O=l.useCallback(()=>{e.length!==0&&R(C<0?0:Math.min(C+1,e.length-1))},[e.length,C,R]),k=l.useCallback(()=>{e.length!==0&&R(C<=0?0:C-1)},[e.length,C,R]),M=l.useCallback(()=>R(0),[R]),P=l.useCallback(()=>R(e.length-1),[R,e.length]),E=l.useCallback(()=>{o&&h(o)},[o,h]),L=l.useCallback((T,F)=>{const N=Gp(F);return N==="range"?(x(e,T,o),!0):N==="toggle"?(h(T),!0):(w(),p(T),!1)},[e,o,x,h,w,p]),A=l.useCallback(T=>{const F=ru(e,o,T);F!==void 0&&(x(e,F),S.current=F,g.current=!1,u(void 0),i(F))},[e,o,x]),j=l.useCallback(()=>A(-1),[A]),I=l.useCallback(()=>A(1),[A]),D=l.useCallback(()=>{e.length>0&&b(e)},[e,b]);return{focusedMessageId:o,setFocusedMessageId:m,keyboardFocusedMessageId:c,focusIndex:C,pendingDomFocusRef:S,cursorMovedByPointerRef:g,selection:d,isMultiSelectMode:y,exitSelection:w,moveFocusToIndex:R,focusNext:O,focusPrevious:k,focusFirst:M,focusLast:P,toggleFocusedSelection:E,extendRangeUp:j,extendRangeDown:I,selectAllLoaded:D,handleRowSelect:L}};function cv({handlers:e,enabled:t=!0,target:s,sequenceTimeoutMs:n=1e3}){const a=l.useRef(e);a.current=e;const o=l.useRef(null),i=l.useRef(null);l.useEffect(()=>{if(!t)return;const c=()=>{i.current!==null&&(clearTimeout(i.current),i.current=null)},u=d=>{const f=cg({key:d.key,shiftKey:d.shiftKey,metaKey:d.metaKey,ctrlKey:d.ctrlKey,altKey:d.altKey,inEditable:ug(d.target),onControl:fg(d.target)},o.current);if(c(),o.current=f.nextPrefix,f.nextPrefix!==null&&(i.current=setTimeout(()=>{o.current=null,i.current=null},n)),f.action===null)return;const h=a.current[f.action];h&&(f.preventDefault&&d.preventDefault(),h())},m=s===void 0?window:s;if(m!==null)return m.addEventListener("keydown",u),()=>{m.removeEventListener("keydown",u),c(),o.current=null}},[t,n,s])}function Vt(e,t,{checkForDefaultPrevented:s=!0}={}){return function(a){if(e?.(a),s===!1||!a||!a.defaultPrevented)return t?.(a)}}function al(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function uv(...e){return t=>{let s=!1;const n=e.map(a=>{const o=al(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():al(e[a],null)}}}}function gs(...e){return l.useCallback(uv(...e),e)}function dv(e,t=[]){let s=[];function n(o,i){const c=l.createContext(i);c.displayName=o+"Context";const u=s.length;s=[...s,i];const m=f=>{const{scope:h,children:v,...x}=f,p=h?.[e]?.[u]||c,b=l.useMemo(()=>x,Object.values(x));return r.jsx(p.Provider,{value:b,children:v})};m.displayName=o+"Provider";function d(f,h,v={}){const{optional:x=!1}=v,p=h?.[e]?.[u]||c,b=l.useContext(p);if(b)return b;if(i!==void 0)return i;if(!x)throw new Error(`\`${f}\` must be used within \`${o}\``)}return[m,d]}const a=()=>{const o=s.map(i=>l.createContext(i));return function(c){const u=c?.[e]||o;return l.useMemo(()=>({[`__scope${e}`]:{...c,[e]:u}}),[c,u])}};return a.scopeName=e,[n,fv(a,...t)]}function fv(...e){const t=e[0];if(e.length===1)return t;const s=()=>{const n=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(o){const i=n.reduce((c,{useScope:u,scopeName:m})=>{const f=u(o)[`__scope${m}`];return{...c,...f}},{});return l.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return s.scopeName=t.scopeName,s}var dn=globalThis?.document?l.useLayoutEffect:()=>{},mv=qa[" useInsertionEffect ".trim().toString()]||dn;function hv({prop:e,defaultProp:t,onChange:s=()=>{},caller:n}){const[a,o,i]=pv({defaultProp:t,onChange:s}),c=e!==void 0,u=c?e:a;{const d=l.useRef(e!==void 0);l.useEffect(()=>{const f=d.current;f!==c&&console.warn(`${n} is changing from ${f?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=c},[c,n])}const m=l.useCallback(d=>{if(c){const f=gv(d)?d(e):d;f!==e&&i.current?.(f)}else o(d)},[c,e,o,i]);return[u,m]}function pv({defaultProp:e,onChange:t}){const[s,n]=l.useState(e),a=l.useRef(s),o=l.useRef(t);return mv(()=>{o.current=t},[t]),l.useEffect(()=>{a.current!==s&&(o.current?.(s),a.current=s)},[s,a]),[s,n,o]}function gv(e){return typeof e=="function"}function Pu(e){const t=l.forwardRef((s,n)=>{let{children:a,...o}=s,i=null,c=!1;const u=[];ol(a)&&typeof Mn=="function"&&(a=Mn(a._payload)),l.Children.forEach(a,h=>{if(wv(h)){c=!0;const v=h;let x="child"in v.props?v.props.child:v.props.children;ol(x)&&typeof Mn=="function"&&(x=Mn(x._payload)),i=bv(v,x),u.push(i?.props?.children)}else u.push(h)}),i?i=l.cloneElement(i,void 0,u):!c&&l.Children.count(a)===1&&l.isValidElement(a)&&(i=a);const m=i?yv(i):void 0,d=gs(n,m);if(!i){if(a||a===0)throw new Error(c?jv(e):kv(e));return a}const f=vv(o,i.props??{});return i.type!==l.Fragment&&(f.ref=n?d:m),l.cloneElement(i,f)});return t.displayName=`${e}.Slot`,t}var xv=Symbol.for("radix.slottable"),bv=(e,t)=>{if("child"in e.props){const s=e.props.child;return l.isValidElement(s)?l.cloneElement(s,void 0,e.props.children(s.props.children)):null}return l.isValidElement(t)?t:null};function vv(e,t){const s={...t};for(const n in t){const a=e[n],o=t[n];/^on[A-Z]/.test(n)?a&&o?s[n]=(...c)=>{const u=o(...c);return a(...c),u}:a&&(s[n]=a):n==="style"?s[n]={...a,...o}:n==="className"&&(s[n]=[a,o].filter(Boolean).join(" "))}return{...e,...s}}function yv(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 wv(e){return l.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===xv}var Sv=Symbol.for("react.lazy");function ol(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Sv&&"_payload"in e&&Cv(e._payload)}function Cv(e){return typeof e=="object"&&e!==null&&"then"in e}var kv=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,jv=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Mn=qa[" use ".trim().toString()],Nv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_t=Nv.reduce((e,t)=>{const s=Pu(`Primitive.${t}`),n=l.forwardRef((a,o)=>{const{asChild:i,...c}=a,u=i?s:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),r.jsx(u,{...c,ref:o})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function Ev(e,t){e&&Ha.flushSync(()=>e.dispatchEvent(t))}function fn(e){const t=l.useRef(e);return l.useEffect(()=>{t.current=e}),l.useMemo(()=>((...s)=>t.current?.(...s)),[])}var Iv="DismissableLayer",Ea="dismissableLayer.update",Rv="dismissableLayer.pointerDownOutside",Tv="dismissableLayer.focusOutside",il,Mo=l.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Lu=l.forwardRef((e,t)=>{const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:n=!1,onEscapeKeyDown:a,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:c,onDismiss:u,...m}=e,d=l.useContext(Mo),[f,h]=l.useState(null),v=f?.ownerDocument??globalThis?.document,[,x]=l.useState({}),p=gs(t,h),b=Array.from(d.layers),[y]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),S=y?b.indexOf(y):-1,g=f?b.indexOf(f):-1,w=d.layersWithOutsidePointerEventsDisabled.size>0,C=g>=S,R=l.useRef(!1),O=Pv(E=>{o?.(E),c?.(E),E.defaultPrevented||u?.()},{ownerDocument:v,deferPointerDownOutside:n,isDeferredPointerDownOutsideRef:R,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:l.useCallback(E=>{if(!(E instanceof Node))return!1;const L=[...d.branches].some(A=>A.contains(E));return C&&!L},[d.branches,C])}),k=Lv(E=>{if(n&&R.current)return;const L=E.target;[...d.branches].some(j=>j.contains(L))||(i?.(E),c?.(E),E.defaultPrevented||u?.())},v),M=f?g===b.length-1:!1,P=fn(E=>{E.key==="Escape"&&(a?.(E),!E.defaultPrevented&&u&&(E.preventDefault(),u()))});return l.useEffect(()=>{if(M)return v.addEventListener("keydown",P,{capture:!0}),()=>v.removeEventListener("keydown",P,{capture:!0})},[v,M,P]),l.useEffect(()=>{if(f)return s&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(il=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(f)),d.layers.add(f),ll(),()=>{s&&(d.layersWithOutsidePointerEventsDisabled.delete(f),d.layersWithOutsidePointerEventsDisabled.size===0&&(v.body.style.pointerEvents=il))}},[f,v,s,d]),l.useEffect(()=>()=>{f&&(d.layers.delete(f),d.layersWithOutsidePointerEventsDisabled.delete(f),ll())},[f,d]),l.useEffect(()=>{const E=()=>x({});return document.addEventListener(Ea,E),()=>document.removeEventListener(Ea,E)},[]),r.jsx(_t.div,{...m,ref:p,style:{pointerEvents:w?C?"auto":"none":void 0,...e.style},onFocusCapture:Vt(e.onFocusCapture,k.onFocusCapture),onBlurCapture:Vt(e.onBlurCapture,k.onBlurCapture),onPointerDownCapture:Vt(e.onPointerDownCapture,O.onPointerDownCapture)})});Lu.displayName=Iv;var Mv="DismissableLayerBranch",Av=l.forwardRef((e,t)=>{const s=l.useContext(Mo),n=l.useRef(null),a=gs(t,n);return l.useEffect(()=>{const o=n.current;if(o)return s.branches.add(o),()=>{s.branches.delete(o)}},[s.branches]),r.jsx(_t.div,{...e,ref:a})});Av.displayName=Mv;function Ov(){const e=l.useContext(Mo),[t,s]=l.useState(null);return l.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),s}var Dv=()=>!0;function Pv(e,t){const{ownerDocument:s=globalThis?.document,deferPointerDownOutside:n=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:o,shouldHandlePointerDownOutside:i=Dv}=t,c=fn(e),u=l.useRef(!1),m=l.useRef(!1),d=l.useRef(new Map),f=l.useRef(()=>{});return l.useEffect(()=>{function h(){m.current=!1,a.current=!1,d.current.clear()}function v(){return Array.from(d.current.values()).some(Boolean)}function x(g){if(!m.current)return;const w=g.target;w instanceof Node&&[...o].some(R=>R.contains(w))||d.current.set(g.type,!0),g.type==="click"&&window.setTimeout(()=>{m.current&&f.current()},0)}function p(g){m.current&&d.current.set(g.type,!1)}const b=g=>{if(g.target&&!u.current){let w=function(){s.removeEventListener("click",f.current);const R=v();h(),R||Fu(Rv,c,C,{discrete:!0})};if(!i(g.target)){s.removeEventListener("click",f.current),h(),u.current=!1;return}const C={originalEvent:g};m.current=!0,a.current=n&&g.button===0,d.current.clear(),!n||g.button!==0?w():(s.removeEventListener("click",f.current),f.current=w,s.addEventListener("click",f.current,{once:!0}))}else s.removeEventListener("click",f.current),h();u.current=!1},y=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const g of y)s.addEventListener(g,x,!0),s.addEventListener(g,p);const S=window.setTimeout(()=>{s.addEventListener("pointerdown",b)},0);return()=>{window.clearTimeout(S),s.removeEventListener("pointerdown",b),s.removeEventListener("click",f.current);for(const g of y)s.removeEventListener(g,x,!0),s.removeEventListener(g,p)}},[s,c,n,a,o,i]),{onPointerDownCapture:()=>u.current=!0}}function Lv(e,t=globalThis?.document){const s=fn(e),n=l.useRef(!1);return l.useEffect(()=>{const a=o=>{o.target&&!n.current&&Fu(Tv,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 ll(){const e=new CustomEvent(Ea);document.dispatchEvent(e)}function Fu(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?Ev(a,o):a.dispatchEvent(o)}var An=0,Ss=null;function Fv(){l.useEffect(()=>{Ss||(Ss={start:cl(),end:cl()});const{start:e,end:t}=Ss;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),An++,()=>{An===1&&(Ss?.start.remove(),Ss?.end.remove(),Ss=null),An=Math.max(0,An-1)}},[])}function cl(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Zr="focusScope.autoFocusOnMount",ea="focusScope.autoFocusOnUnmount",ul={bubbles:!1,cancelable:!0},$v="FocusScope",$u=l.forwardRef((e,t)=>{const{loop:s=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[c,u]=l.useState(null),m=fn(a),d=fn(o),f=l.useRef(null),h=gs(t,u),v=l.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;l.useEffect(()=>{if(n){let p=function(g){if(v.paused||!c)return;const w=g.target;c.contains(w)?f.current=w:Ut(f.current,{select:!0})},b=function(g){if(v.paused||!c)return;const w=g.relatedTarget;w!==null&&(c.contains(w)||Ut(f.current,{select:!0}))},y=function(g){if(document.activeElement===document.body)for(const C of g)C.removedNodes.length>0&&Ut(c)};document.addEventListener("focusin",p),document.addEventListener("focusout",b);const S=new MutationObserver(y);return c&&S.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",b),S.disconnect()}}},[n,c,v.paused]),l.useEffect(()=>{if(c){fl.add(v);const p=document.activeElement;if(!c.contains(p)){const y=new CustomEvent(Zr,ul);c.addEventListener(Zr,m),c.dispatchEvent(y),y.defaultPrevented||(_v(qv(_u(c)),{select:!0}),document.activeElement===p&&Ut(c))}return()=>{c.removeEventListener(Zr,m),setTimeout(()=>{const y=new CustomEvent(ea,ul);c.addEventListener(ea,d),c.dispatchEvent(y),y.defaultPrevented||Ut(p??document.body,{select:!0}),c.removeEventListener(ea,d),fl.remove(v)},0)}}},[c,m,d,v]);const x=l.useCallback(p=>{if(!s&&!n||v.paused)return;const b=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,y=document.activeElement;if(b&&y){const S=p.currentTarget,[g,w]=zv(S);g&&w?!p.shiftKey&&y===w?(p.preventDefault(),s&&Ut(g,{select:!0})):p.shiftKey&&y===g&&(p.preventDefault(),s&&Ut(w,{select:!0})):y===S&&p.preventDefault()}},[s,n,v.paused]);return r.jsx(_t.div,{tabIndex:-1,...i,ref:h,onKeyDown:x})});$u.displayName=$v;function _v(e,{select:t=!1}={}){const s=document.activeElement;for(const n of e)if(Ut(n,{select:t}),document.activeElement!==s)return}function zv(e){const t=_u(e),s=dl(t,e),n=dl(t.reverse(),e);return[s,n]}function _u(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 dl(e,t){const s=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const n of e)if(!(s?!n.checkVisibility({checkVisibilityCSS:!0}):Bv(n,{upTo:t})))return n}function Bv(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 Uv(e){return e instanceof HTMLInputElement&&"select"in e}function Ut(e,{select:t=!1}={}){if(e&&e.focus){const s=document.activeElement;e.focus({preventScroll:!0}),e!==s&&Uv(e)&&t&&e.select()}}var fl=Kv();function Kv(){let e=[];return{add(t){const s=e[0];t!==s&&s?.pause(),e=ml(e,t),e.unshift(t)},remove(t){e=ml(e,t),e[0]?.resume()}}}function ml(e,t){const s=[...e],n=s.indexOf(t);return n!==-1&&s.splice(n,1),s}function qv(e){return e.filter(t=>t.tagName!=="A")}var Hv=qa[" useId ".trim().toString()]||(()=>{}),Wv=0;function ta(e){const[t,s]=l.useState(Hv());return dn(()=>{s(n=>n??String(Wv++))},[e]),e||(t?`radix-${t}`:"")}var Vv="Portal",zu=l.forwardRef((e,t)=>{const{container:s,...n}=e,[a,o]=l.useState(!1);dn(()=>o(!0),[]);const i=s||a&&globalThis?.document?.body;return i?Ha.createPortal(r.jsx(_t.div,{...n,ref:t}),i):null});zu.displayName=Vv;function Qv(e,t){return l.useReducer((s,n)=>t[s][n]??s,e)}var Nr=e=>{const{present:t,children:s}=e,n=Gv(t),a=typeof s=="function"?s({present:n.isPresent}):l.Children.only(s),o=Yv(n.ref,Xv(a));return typeof s=="function"||n.isPresent?l.cloneElement(a,{ref:o}):null};Nr.displayName="Presence";function Gv(e){const[t,s]=l.useState(),n=l.useRef(null),a=l.useRef(e),o=l.useRef("none"),i=l.useRef(void 0),c=e?"mounted":"unmounted",[u,m]=Qv(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return l.useEffect(()=>{u==="mounted"?(o.current=i.current??Ys(n.current),i.current=void 0):o.current="none"},[u]),dn(()=>{const d=n.current,f=a.current;if(f!==e){const v=o.current,x=Ys(d);e?(i.current=x,m("MOUNT")):x==="none"||d?.display==="none"?m("UNMOUNT"):m(f&&v!==x?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,m]),dn(()=>{if(t){let d;const f=t.ownerDocument.defaultView??window,h=x=>{const b=Ys(n.current).includes(CSS.escape(x.animationName));if(x.target===t&&b&&(m("ANIMATION_END"),!a.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",d=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},v=x=>{x.target===t&&(o.current=Ys(n.current))};return t.addEventListener("animationstart",v),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{f.clearTimeout(d),t.removeEventListener("animationstart",v),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else m("ANIMATION_END")},[t,m]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:l.useCallback(d=>{if(d){const f=getComputedStyle(d);n.current=f,i.current=Ys(f)}else n.current=null;s(d)},[])}}function hl(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Yv(...e){const t=l.useRef(e);return t.current=e,l.useCallback(s=>{const n=t.current;let a=!1;const o=n.map(i=>{const c=hl(i,s);return!a&&typeof c=="function"&&(a=!0),c});if(a)return()=>{for(let i=0;i<o.length;i++){const c=o[i];typeof c=="function"?c():hl(n[i],null)}}},[])}function Ys(e){return e?.animationName||"none"}function Xv(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 Jv=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Cs=new WeakMap,On=new WeakMap,Dn={},sa=0,Bu=function(e){return e&&(e.host||Bu(e.parentNode))},Zv=function(e,t){return t.map(function(s){if(e.contains(s))return s;var n=Bu(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})},ey=function(e,t,s,n){var a=Zv(t,Array.isArray(e)?e:[e]);Dn[s]||(Dn[s]=new WeakMap);var o=Dn[s],i=[],c=new Set,u=new Set(a),m=function(f){!f||c.has(f)||(c.add(f),m(f.parentNode))};a.forEach(m);var d=function(f){!f||u.has(f)||Array.prototype.forEach.call(f.children,function(h){if(c.has(h))d(h);else try{var v=h.getAttribute(n),x=v!==null&&v!=="false",p=(Cs.get(h)||0)+1,b=(o.get(h)||0)+1;Cs.set(h,p),o.set(h,b),i.push(h),p===1&&x&&On.set(h,!0),b===1&&h.setAttribute(s,"true"),x||h.setAttribute(n,"true")}catch(y){console.error("aria-hidden: cannot operate on ",h,y)}})};return d(t),c.clear(),sa++,function(){i.forEach(function(f){var h=Cs.get(f)-1,v=o.get(f)-1;Cs.set(f,h),o.set(f,v),h||(On.has(f)||f.removeAttribute(n),On.delete(f)),v||f.removeAttribute(s)}),sa--,sa||(Cs=new WeakMap,Cs=new WeakMap,On=new WeakMap,Dn={})}},ty=function(e,t,s){s===void 0&&(s="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),a=Jv(e);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live], script"))),ey(n,a,s,"aria-hidden")):function(){return null}},Kn="right-scroll-bar-position",qn="width-before-scroll-bar",sy="with-scroll-bars-hidden",ny="--removed-body-scroll-bar-size";function na(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function ry(e,t){var s=l.useState(function(){return{value:e,callback:t,facade:{get current(){return s.value},set current(n){var a=s.value;a!==n&&(s.value=n,s.callback(n,a))}}}})[0];return s.callback=t,s.facade}var ay=typeof window<"u"?l.useLayoutEffect:l.useEffect,pl=new WeakMap;function oy(e,t){var s=ry(null,function(n){return e.forEach(function(a){return na(a,n)})});return ay(function(){var n=pl.get(s);if(n){var a=new Set(n),o=new Set(e),i=s.current;a.forEach(function(c){o.has(c)||na(c,null)}),o.forEach(function(c){a.has(c)||na(c,i)})}pl.set(s,e)},[e]),s}function iy(e){return e}function ly(e,t){t===void 0&&(t=iy);var s=[],n=!1,a={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return s.length?s[s.length-1]:e},useMedium:function(o){var i=t(o,n);return s.push(i),function(){s=s.filter(function(c){return c!==i})}},assignSyncMedium:function(o){for(n=!0;s.length;){var i=s;s=[],i.forEach(o)}s={push:function(c){return o(c)},filter:function(){return s}}},assignMedium:function(o){n=!0;var i=[];if(s.length){var c=s;s=[],c.forEach(o),i=s}var u=function(){var d=i;i=[],d.forEach(o)},m=function(){return Promise.resolve().then(u)};m(),s={push:function(d){i.push(d),m()},filter:function(d){return i=i.filter(d),s}}}};return a}function cy(e){e===void 0&&(e={});var t=ly(null);return t.options=Kt({async:!0,ssr:!1},e),t}var Uu=function(e){var t=e.sideCar,s=xc(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return l.createElement(n,Kt({},s))};Uu.isSideCarExport=!0;function uy(e,t){return e.useMedium(t),Uu}var Ku=cy(),ra=function(){},Er=l.forwardRef(function(e,t){var s=l.useRef(null),n=l.useState({onScrollCapture:ra,onWheelCapture:ra,onTouchMoveCapture:ra}),a=n[0],o=n[1],i=e.forwardProps,c=e.children,u=e.className,m=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,v=e.noRelative,x=e.noIsolation,p=e.inert,b=e.allowPinchZoom,y=e.as,S=y===void 0?"div":y,g=e.gapMode,w=xc(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=h,R=oy([s,t]),O=Kt(Kt({},w),a);return l.createElement(l.Fragment,null,d&&l.createElement(C,{sideCar:Ku,removeScrollBar:m,shards:f,noRelative:v,noIsolation:x,inert:p,setCallbacks:o,allowPinchZoom:!!b,lockRef:s,gapMode:g}),i?l.cloneElement(l.Children.only(c),Kt(Kt({},O),{ref:R})):l.createElement(S,Kt({},O,{className:u,ref:R}),c))});Er.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Er.classNames={fullWidth:qn,zeroRight:Kn};var dy=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function fy(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=dy();return t&&e.setAttribute("nonce",t),e}function my(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function hy(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var py=function(){var e=0,t=null;return{add:function(s){e==0&&(t=fy())&&(my(t,s),hy(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},gy=function(){var e=py();return function(t,s){l.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&s])}},qu=function(){var e=gy(),t=function(s){var n=s.styles,a=s.dynamic;return e(n,a),null};return t},xy={left:0,top:0,right:0,gap:0},aa=function(e){return parseInt(e||"",10)||0},by=function(e){var t=window.getComputedStyle(document.body),s=t[e==="padding"?"paddingLeft":"marginLeft"],n=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return[aa(s),aa(n),aa(a)]},vy=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return xy;var t=by(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])}},yy=qu(),Ts="data-scroll-locked",wy=function(e,t,s,n){var a=e.left,o=e.top,i=e.right,c=e.gap;return s===void 0&&(s="margin"),`
|
|
76
|
+
.`.concat(sy,` {
|
|
77
77
|
overflow: hidden `).concat(n,`;
|
|
78
78
|
padding-right: `).concat(c,"px ").concat(n,`;
|
|
79
79
|
}
|
|
@@ -107,12 +107,12 @@ a, a:visited {
|
|
|
107
107
|
}
|
|
108
108
|
|
|
109
109
|
body[`).concat(Ts,`] {
|
|
110
|
-
`).concat(
|
|
110
|
+
`).concat(ny,": ").concat(c,`px;
|
|
111
111
|
}
|
|
112
|
-
`)},gl=function(){var e=parseInt(document.body.getAttribute(Ts)||"0",10);return isFinite(e)?e:0},
|
|
112
|
+
`)},gl=function(){var e=parseInt(document.body.getAttribute(Ts)||"0",10);return isFinite(e)?e:0},Sy=function(){l.useEffect(function(){return document.body.setAttribute(Ts,(gl()+1).toString()),function(){var e=gl()-1;e<=0?document.body.removeAttribute(Ts):document.body.setAttribute(Ts,e.toString())}},[])},Cy=function(e){var t=e.noRelative,s=e.noImportant,n=e.gapMode,a=n===void 0?"margin":n;Sy();var o=l.useMemo(function(){return vy(a)},[a]);return l.createElement(yy,{styles:wy(o,!t,a,s?"":"!important")})},Ia=!1;if(typeof window<"u")try{var Pn=Object.defineProperty({},"passive",{get:function(){return Ia=!0,!0}});window.addEventListener("test",Pn,Pn),window.removeEventListener("test",Pn,Pn)}catch{Ia=!1}var ks=Ia?{passive:!1}:!1,ky=function(e){return e.tagName==="TEXTAREA"},Hu=function(e,t){if(!(e instanceof Element))return!1;var s=window.getComputedStyle(e);return s[t]!=="hidden"&&!(s.overflowY===s.overflowX&&!ky(e)&&s[t]==="visible")},jy=function(e){return Hu(e,"overflowY")},Ny=function(e){return Hu(e,"overflowX")},xl=function(e,t){var s=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=Wu(e,n);if(a){var o=Vu(e,n),i=o[1],c=o[2];if(i>c)return!0}n=n.parentNode}while(n&&n!==s.body);return!1},Ey=function(e){var t=e.scrollTop,s=e.scrollHeight,n=e.clientHeight;return[t,s,n]},Iy=function(e){var t=e.scrollLeft,s=e.scrollWidth,n=e.clientWidth;return[t,s,n]},Wu=function(e,t){return e==="v"?jy(t):Ny(t)},Vu=function(e,t){return e==="v"?Ey(t):Iy(t)},Ry=function(e,t){return e==="h"&&t==="rtl"?-1:1},Ty=function(e,t,s,n,a){var o=Ry(e,window.getComputedStyle(t).direction),i=o*n,c=s.target,u=t.contains(c),m=!1,d=i>0,f=0,h=0;do{if(!c)break;var v=Vu(e,c),x=v[0],p=v[1],b=v[2],y=p-b-o*x;(x||y)&&Wu(e,c)&&(f+=y,h+=x);var S=c.parentNode;c=S&&S.nodeType===Node.DOCUMENT_FRAGMENT_NODE?S.host:S}while(!u&&c!==document.body||u&&(t.contains(c)||t===c));return(d&&Math.abs(f)<1||!d&&Math.abs(h)<1)&&(m=!0),m},Ln=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},bl=function(e){return[e.deltaX,e.deltaY]},vl=function(e){return e&&"current"in e?e.current:e},My=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Ay=function(e){return`
|
|
113
113
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
114
114
|
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
115
|
-
`)},Ty=0,js=[];function My(e){var t=l.useRef([]),s=l.useRef([0,0]),n=l.useRef(),a=l.useState(Ty++)[0],o=l.useState(qu)[0],i=l.useRef(e);l.useEffect(function(){i.current=e},[e]),l.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=Sm([e.lockRef.current],(e.shards||[]).map(vl),!0).filter(Boolean);return p.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var c=l.useCallback(function(p,b){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var y=Ln(p),S=s.current,g="deltaX"in p?p.deltaX:S[0]-y[0],w="deltaY"in p?p.deltaY:S[1]-y[1],C,R=p.target,O=Math.abs(g)>Math.abs(w)?"h":"v";if("touches"in p&&O==="h"&&R.type==="range")return!1;var k=window.getSelection(),M=k&&k.anchorNode,P=M?M===R||M.contains(R):!1;if(P)return!1;var E=xl(O,R);if(!E)return!0;if(E?C=O:(C=O==="v"?"h":"v",E=xl(O,R)),!E)return!1;if(!n.current&&"changedTouches"in p&&(g||w)&&(n.current=C),!C)return!0;var L=n.current||C;return Ey(L,b,p,L==="h"?g:w)},[]),u=l.useCallback(function(p){var b=p;if(!(!js.length||js[js.length-1]!==o)){var y="deltaY"in b?bl(b):Ln(b),S=t.current.filter(function(C){return C.name===b.type&&(C.target===b.target||b.target===C.shadowParent)&&Iy(C.delta,y)})[0];if(S&&S.should){b.cancelable&&b.preventDefault();return}if(!S){var g=(i.current.shards||[]).map(vl).filter(Boolean).filter(function(C){return C.contains(b.target)}),w=g.length>0?c(b,g[0]):!i.current.noIsolation;w&&b.cancelable&&b.preventDefault()}}},[]),m=l.useCallback(function(p,b,y,S){var g={name:p,delta:b,target:y,should:S,shadowParent:Ay(y)};t.current.push(g),setTimeout(function(){t.current=t.current.filter(function(w){return w!==g})},1)},[]),d=l.useCallback(function(p){s.current=Ln(p),n.current=void 0},[]),f=l.useCallback(function(p){m(p.type,bl(p),p.target,c(p,e.lockRef.current))},[]),h=l.useCallback(function(p){m(p.type,Ln(p),p.target,c(p,e.lockRef.current))},[]);l.useEffect(function(){return js.push(o),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",u,ks),document.addEventListener("touchmove",u,ks),document.addEventListener("touchstart",d,ks),function(){js=js.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,ks),document.removeEventListener("touchmove",u,ks),document.removeEventListener("touchstart",d,ks)}},[]);var v=e.removeScrollBar,x=e.inert;return l.createElement(l.Fragment,null,x?l.createElement(o,{styles:Ry(a)}):null,v?l.createElement(yy,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Ay(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Oy=iy(Ku,My);var Qu=l.forwardRef(function(e,t){return l.createElement(Er,Kt({},e,{ref:t,sideCar:Oy}))});Qu.classNames=Er.classNames;var Dy=class extends Wa{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,n=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:c}=n,u=s.fetchMeta?.fetchMore?.direction,m=i&&u==="forward",d=a&&u==="forward",f=i&&u==="backward",h=a&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:km(t,s.data),hasPreviousPage:Cm(t,s.data),isFetchNextPageError:m,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:c&&!m&&!f,isRefetching:o&&!d&&!h}}};function yl(e,t){const s=new Set(t);return e.filter(n=>!s.has(n))}function Py(e,t,s){const n=e.slice(0);return n[t]=s,n}var Ly=class extends jm{#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,xa.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,c=a.some((d,f)=>d!==s[f]),u=i||c,m=u?!0:o.some((d,f)=>{const h=this.#e[f];return!h||!Nm(d,h)});!u&&!m||(u&&(this.#c=n,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(yl(s,a).forEach(d=>{d.destroy()}),yl(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=Em(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 Wa(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=Py(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)&&xa.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function mt({queries:e,...t},s){const n=De(),a=Im(),o=Rm(),i=l.useMemo(()=>e.map(p=>{const b=n.defaultQueryOptions(p);return b._optimisticResults=a?"isRestoring":"optimistic",b}),[e,n,a]);i.forEach(p=>{Tm(p);const b=n.getQueryCache().get(p.queryHash);Mm(p,o,b)}),Am(o);const[c]=l.useState(()=>new Ly(n,i,t)),[u,m,d]=c.getOptimisticResult(i,t.combine),f=!a&&t.subscribed!==!1;l.useSyncExternalStore(l.useCallback(p=>f?c.subscribe(xa.batchCalls(p)):Om,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),l.useEffect(()=>{c.setQueries(i,t)},[i,t,c]);const v=u.some((p,b)=>li(i[b],p))?u.flatMap((p,b)=>{const y=i[b];if(y&&li(y,p)){const S=new Wa(n,y);return Dm(y,S,o)}return[]}):[];if(v.length>0)throw Promise.all(v);const x=u.find((p,b)=>{const y=i[b];return y&&Pm({result:p,errorResetBoundary:o,throwOnError:y.throwOnError,query:n.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(x?.error)throw x.error;return m(d())}function Gu(e,t){return Lm(e,Dy)}function Fy(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 Yu(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:a=!1,withResolver:o=!1}=Fy(e),i=Va(),{history:c}=i,[u,m]=l.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return l.useEffect(()=>{const d=async f=>{function h(y){const S=i.parseLocation(y),g=i.getMatchedRoutes(S.pathname);return g.foundRoute===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:g.routeParams,search:i.options.parseSearch(y.search)}:{routeId:g.foundRoute.id,fullPath:g.foundRoute.fullPath,pathname:S.pathname,params:g.routeParams,search:i.options.parseSearch(y.search)}}const v=h(f.currentLocation),x=h(f.nextLocation);if(v.routeId==="__notFound__"&&x.routeId!=="__notFound__")return!1;const p=await s({action:f.action,current:v,next:x});if(!o)return p;if(!p)return!1;const b=await new Promise(y=>{m({status:"blocked",current:v,next:x,action:f.action,proceed:()=>y(!1),reset:()=>y(!0)})});return m({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),b};return a?void 0:c.block({blockerFn:d,enableBeforeUnload:n})},[s,n,a,o,c,i]),u}function Ot(e){const t=Va({warn:e?.router===void 0}),s=e?.router||t;return bc(s.stores.__store,vc(e,s))}function Ir(e){const t=Va();return bc(t.stores.location,vc(e,t))}const $y=new Set(["outbox","flagged"]),_y=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!$y.has(s)};function zy(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,n]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Qa(n.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function Xu(e){const{openCompose:t}=Jt(),s=Ye(),n=Ir(),a=zy(e);return l.useCallback(()=>{if(_y(n.pathname)){l.startTransition(()=>{t({mode:"new"})});return}a&&(l.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,n.pathname,a])}const By=e=>e.startsWith("/mail")||e.startsWith("/settings"),Uy=({accounts:e})=>{const{state:t}=Jt(),s=Ir(),n=Xu(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!By(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(Eh,{className:"size-6"})})},Ju=({trigger:e,children:t,align:s="right"})=>{const[n,a]=l.useState(!1),o=l.useRef(null),i=l.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),c=l.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return l.useEffect(()=>(n&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",c)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",c)}),[n,i,c]),r.jsxs("div",{ref:o,className:"relative",children:[r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!n)},className:Ve("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),n&&r.jsx("div",{className:Ve("absolute z-50 mt-1 min-w-[180px] py-1","bg-surface border border-line rounded-md shadow-lg",s==="right"?"right-0":"left-0"),children:t})]})},nn=({onClick:e,disabled:t,destructive:s,children:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:Ve("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:n}),Zu=()=>r.jsx("div",{className:"my-1 h-px bg-line"}),ed=({children:e})=>{const{Account:t}=lr();return r.jsx(t,{children:e})},Ky=({email:e,onSignOut:t})=>{const s=e??"Account";return r.jsxs(Ju,{trigger:r.jsx(jt,{name:s,email:e??void 0,size:"sm"}),align:"right",children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),r.jsx(Zu,{})]}),r.jsxs(nn,{onClick:t,children:[r.jsx(Xc,{className:"size-4"}),"Sign out"]})]})},qy=()=>r.jsx(ed,{children:({email:e,signOut:t})=>r.jsx(Ky,{email:e,onSignOut:t})}),Hy=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function Ao(e){return!!e&&Hy.has(e)}const td=3e3,Wy=td*2,wl={syncing:!1,resolved:!1,synced:0,total:0};function Vy(e,t){const s=e.join(","),[n,a]=l.useState(!1),[o,i]=l.useState(!1);l.useEffect(()=>{a(!1),i(!1)},[s,t]),l.useEffect(()=>{if(!t)return;const x=setTimeout(()=>i(!0),Wy);return()=>clearTimeout(x)},[s,t]);const c=mt({queries:e.map(x=>({...Gn({path:{accountId:x}}),enabled:t&&!n,refetchInterval:td,meta:{softError:!0}}))}),u=c.every(x=>x.isSuccess||x.isError),m=c.length===0||u||o;let d=!1,f=0,h=0;for(const x of c)if(Ao(x.data?.syncPhase)){d=!0;for(const p of x.data?.mailboxes??[])f+=p.messagesSynced,h+=p.messagesTotal}const v=t&&m&&!d;return l.useEffect(()=>{v&&a(!0)},[v]),!t||!m?wl:{syncing:d,resolved:!0,synced:f,total:h}}const Sl=6e4,Qy=new Set(["sent","drafts","trash","archive"]),Cl=(e,t)=>{const s=new Map;for(const n of e){const a=t.get(n.mailboxId)?.role;a&&Qy.has(a)||s.set(n.mailboxId,n.messagesTotal)}return s},Gy=(e,t)=>{for(const[s,n]of t)if(n>(e.get(s)??0))return!0;return!1},sd=l.createContext(null),Rr=()=>{const e=l.useContext(sd);if(!e)throw new Error("useMailFreshness must be used inside <MailFreshnessProvider>");return e};function Yy({accountIds:e,children:t}){const s=De(),{resultFolderIndex:n}=Fe(),a=l.useRef(new Map),o=l.useRef(new Set),[i,c]=l.useState(new Set),u=mt({queries:e.map(x=>({...Gn({path:{accountId:x}}),refetchInterval:Sl,staleTime:Sl,meta:{softError:!0}}))}),m=u.map(x=>x.dataUpdatedAt).join(","),d=e.join(",");l.useEffect(()=>{let x=!1;const p=new Set(i);e.forEach((b,y)=>{const S=u[y]?.data;if(!S)return;const g=Cl(S.mailboxes??[],n);if(!o.current.has(b)){o.current.add(b),a.current.set(b,g);return}if(p.has(b))return;const w=a.current.get(b)??new Map;Gy(w,g)&&(p.add(b),x=!0)}),x&&c(p)},[d,m]);const f=l.useCallback(x=>x.some(p=>i.has(p)),[i]),h=l.useCallback(x=>{c(p=>{if(x.every(y=>!p.has(y)))return p;const b=new Set(p);for(const y of x)b.delete(y);return b});for(const p of x){const b=s.getQueryData(Gn({path:{accountId:p}}).queryKey);a.current.set(p,Cl(b?.mailboxes??[],n)),o.current.add(p)}},[s,n]),v=l.useMemo(()=>({hasNewMail:f,acknowledge:h}),[f,h]);return r.jsx(sd.Provider,{value:v,children:t})}const Xy=2e3,Jy=45e3,Zy=e=>new Promise(t=>setTimeout(t,e)),Ra=e=>e instanceof Error&&e.message?e.message:"Something went wrong",e0=e=>{wc(e,{softError:!0})&&Ga(e)},nd=e=>e.reduce((t,s)=>Math.max(t,s.lastSyncedAt??0),0),rd=(e,t)=>e.fetchQuery({...Gn({path:{accountId:t}}),staleTime:0}),t0=async(e,t,s,n)=>{let a=!1;for(;;){const o=await rd(e,t).then(u=>({ok:!0,data:u})).catch(u=>({ok:!1,error:u}));if(!o.ok)return{accountId:t,message:Ra(o.error)};const{syncPhase:i,mailboxes:c}=o.data;if(Ao(i))a=!0;else if(a||nd(c??[])>s)return i==="error"?{accountId:t,message:"Sync failed for this account"}:void 0;if(Date.now()>=n)return{accountId:t,message:"Refresh is taking longer than usual"};await Zy(Xy)}},s0=async(e,t,s,n)=>{const a=await rd(e,s).then(c=>({ok:!0,maxLastSynced:nd(c.mailboxes??[])})).catch(c=>({ok:!1,error:c}));if(!a.ok)return{accountId:s,enqueued:!1,ok:!1,message:Ra(a.error)};const o=await yc({path:{accountId:s},throwOnError:!0}).then(()=>({ok:!0})).catch(c=>({ok:!1,error:c}));if(!o.ok)return e0(o.error),{accountId:s,enqueued:!1,ok:!1,message:Ra(o.error)};t.recordEvent("sync.triggered");const i=await t0(e,s,a.maxLastSynced,n);return i?{accountId:s,enqueued:!0,ok:!1,message:i.message}:{accountId:s,enqueued:!0,ok:!0}},Oo=(e,t={})=>{const s=De(),n=Ls(),{acknowledge:a}=Rr(),[o,i]=l.useState("idle"),[c,u]=l.useState(),m=l.useRef(0),d=l.useRef(e);d.current=e;const f=l.useRef(t);f.current=t,l.useEffect(()=>{if(o!=="success")return;const v=setTimeout(()=>i("idle"),2e3);return()=>clearTimeout(v)},[o]);const h=l.useCallback(()=>{const v=d.current;if(v.length===0){i("error"),u("Nothing to refresh yet");return}const x=++m.current;i("refreshing"),u(void 0),(async()=>{const p=Date.now()+Jy,b=await Promise.all(v.map(g=>s0(s,n,g,p)));if(m.current!==x)return;const y=b.filter(g=>g.enqueued).map(g=>g.accountId);for(const g of y)s.invalidateQueries({queryKey:Ft({path:{accountId:g}})});y.length>0&&(f.current.onSettled?.(),a(y));const S=b.filter(g=>!g.ok);S.length===0?i("success"):(i("error"),u(S[0]?.message))})()},[a,s,n]);return{state:o,errorMessage:c,refresh:h}},ad="/mail/",Do="/mail/$mailboxId",od="/mail/outbox",id="/mail/flagged";function Po(e){return e.some(t=>t.routeId===ad)}function vn(e){return e.some(t=>t.routeId===id)}function Tr(e){return e.some(t=>t.routeId===od)}function ld(e){return e.some(t=>t.routeId===Do)}function n0(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Do}:${t}`:vn(e)?id:Tr(e)?od:Po(e)?ad:""}const Hn="search-scope";function r0(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function cd(e){return vn(e)||Tr(e)||ld(e)}function ud(e){return e.find(t=>t.routeId===Do)?.params?.mailboxId}function a0(e){const t=ud(e.matches);return t||(cd(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function o0(e,t){return Po(e)?{kind:"global"}:vn(e)?{kind:"scoped",chip:{id:Hn,label:"is:starred"}}:Tr(e)?{kind:"scoped",chip:{id:Hn,label:"in:outbox"}}:ld(e)?t?{kind:"scoped",chip:{id:Hn,label:r0(t)}}:{kind:"pending"}:{kind:"global"}}function i0(e,t,s){return t.kind==="global"?{kind:"global"}:vn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const dd=({accounts:e})=>{const t=Ya({strict:!1}),s=Ir(),n=t.mailboxId,{t:a}=Xa("mail",{useSuspense:!1}),o=l.useCallback((c,u)=>a(c,{defaultValue:u}),[a]),i=mt({queries:e.map(c=>({...it({path:{accountId:c.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!n)return null;for(let c=0;c<e.length;c++){const u=i[c]?.data?.items;if(!u)continue;const m=u.find(f=>f.mailboxId===n);if(!m)continue;const d=Qa(e[c].folderAppointments);return Yn(m,d.get(n),o)}return null},l0=({accounts:e})=>{const s=Ya({strict:!1}).mailboxId,n=mt({queries:e.map(a=>({...it({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of n){const o=a.data?.items;if(!o)continue;const i=o.find(c=>c.mailboxId===s);if(i)return i.unseenCount}return null};function fd(e){const t=Ye(),{searchInput:s}=Fe(),n=dd({accounts:e}),a=Ot({select:c=>c.matches}),o=o0(a,n),i=l.useCallback(c=>{c===Hn&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}function c0({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:n,onSearchClearQuery:a}=Fe(),o=Ye(),i=Xu(e),{scope:c,clearScope:u}=fd(e),m=c.kind==="scoped"?[{id:c.chip.id,label:c.chip.label,tone:"scope"}]:void 0,d=l.useMemo(()=>e.map(p=>p.accountId),[e]),{hasNewMail:f}=Rr(),{state:h,errorMessage:v,refresh:x}=Oo(d);return r.jsx(lb,{search:{value:t,scope:c.kind,chips:m,onChange:s,onClear:n,onClearQuery:a,onRemoveChip:u},onCompose:i,onReportBug:Sc,onOpenSettings:()=>o({to:"/settings/accounts"}),composeShortcut:nu("compose"),refreshControl:r.jsx(jo,{state:h,onRefresh:x,label:"Refresh all accounts",errorMessage:v,hasUpdate:f(d)}),account:r.jsx(qy,{})})}const Lo=({isOpen:e,onClose:t,children:s,ariaLabel:n="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=l.useRef(null),c=l.useRef(null);if(l.useEffect(()=>{if(!e)return;c.current=document.activeElement;const m=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",m),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=f,c.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return r.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":n,children:[r.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),r.jsxs("div",{ref:i,className:Ve("safe-area-frame absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[r.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:r.jsx(Nt,{className:"size-5"})})}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},u0=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},Ta={all:["messages"],detail:e=>[...Ta.all,"detail",e],body:e=>[...Ta.detail(e),"body"]};class cs 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 d0=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},f0=8,m0="x-remit-403-reason",md=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},h0=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,p0=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},g0=async(e,t,s=async()=>null)=>{const n={},a=await s();a&&(n.Authorization=`Bearer ${a}`);const o=await Cc(e,{headers:n});if(o.status===202)throw new cs("not-ready","Message body is still syncing",202,d0(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(m0),m=md(o.status,u);throw new cs(m,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(p0(t,i))throw new cs("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const c=await o.text();if(h0(c,i))throw new cs("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return c},x0=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),hd=({messageId:e,bodyParts:t,enabled:s=!0})=>{const n=t?u0(t):null,a=Ls(),{getToken:o}=lr(),i=l.useRef(null),c=De(),u=l.useRef(!1),m=l.useRef(null),d=e&&n?`${e}:${n.contentUrl}`:null;m.current!==d&&(m.current=d,u.current=!1);const f=we({queryKey:e?[...Ta.body(e),n?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!n)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const x=u.current;return u.current=!1,x0({fetchContent:(p,b)=>g0(p,b,o),refetchDescribeMessage:()=>c.refetchQueries({queryKey:Ja({path:{messageId:e}})})},{contentUrl:n.contentUrl,kind:n.kind,isRetryAfterNotReady:x})},enabled:s&&!!e&&!!n,staleTime:300*1e3,gcTime:1800*1e3,retry:(x,p)=>p instanceof cs&&p.reason==="not-ready"?x<f0:x<1,retryDelay:(x,p)=>p instanceof cs&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=f.isLoading&&!!n;l.useEffect(()=>{h&&(i.current=performance.now())},[h]),l.useEffect(()=>{f.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[f.isSuccess,a]);const v=f.data&&n?{kind:n.kind,body:f.data}:void 0;return{picked:n,data:v,isLoading:h,isError:f.isError,error:f.error,refetch:f.refetch}},b0=e=>e.then(()=>{},()=>{}),v0=({outboxMessageId:e,onDraftCreated:t})=>{const[s,n]=l.useState("idle"),[a,o]=l.useState(null),i=l.useRef(void 0),c=l.useRef(new Set),u=De(),m=l.useRef(e),d=l.useRef(e);m.current!==e&&(m.current=e,d.current=e);const f=Ue(Fm()),h=Ue($m()),v=l.useCallback(async g=>{n("saving"),o(null);const w=d.current;if(w){const R=await h.mutateAsync({path:{outboxMessageId:w},body:{toAddresses:g.toAddresses,ccAddresses:g.ccAddresses,bccAddresses:g.bccAddresses,subject:g.subject,textBody:g.textBody,htmlBody:g.htmlBody,inReplyTo:g.inReplyTo,references:g.references}});return n("saved"),R}const C=await f.mutateAsync({body:{...g,sendImmediately:!1}});return d.current=C.outboxMessageId,t(C.outboxMessageId),n("saved"),u.invalidateQueries({queryKey:cr().queryKey}),C},[f,h,t,u]),x=l.useRef(Promise.resolve()),p=l.useCallback(g=>{const w=x.current.then(()=>v(g));return x.current=b0(w),w},[v]),b=l.useCallback(g=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{const w=d.current;w&&c.current.has(w)||p(g).catch(C=>{o(C),n("error")})},2e3)},[p]),y=l.useCallback(g=>(i.current&&clearTimeout(i.current),p(g).then(w=>({outcome:"saved",outboxMessageId:w.outboxMessageId})).catch(w=>(n("error"),{outcome:"failed",error:w}))),[p]),S=l.useCallback(g=>{i.current&&clearTimeout(i.current),g&&c.current.add(g)},[]);return{saveStatus:s,saveError:a,saveDraft:b,saveImmediately:y,stopAutoSave:S}},oa=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=l.useState(""),i=gr(a,200),{data:c}=we({...ur({query:{q:i,limit:8}}),enabled:i.length>=2}),u=l.useMemo(()=>(c?.items??[]).map(m=>({email:m.normalizedEmail,displayName:m.displayName})),[c]);return r.jsx(wx,{label:e,addresses:t,onChange:s,placeholder:n,suggestions:u,onQueryChange:o})},y0=({accountId:e})=>{const t=Ye();return r.jsx(jx,{onConfigure:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})}})},kl=150,w0=()=>{const[e,t]=l.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>kl}});return l.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>kl})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},S0=({selectedAccountId:e,onSelect:t})=>{const{data:s}=we({...$t(),staleTime:1/0}),n=s?.accounts??[];if(l.useEffect(()=>{!e&&n.length===1&&n[0]&&t(n[0])},[e,n,t]),n.length<=1){const a=n[0];return a?r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=n.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:n.map(a=>r.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},C0=l.lazy(()=>Km(()=>import("./rich-text-DUirdWcq.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.ComposeBody}))),k0=()=>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"})]}),j0=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),N0=e=>e.split(`
|
|
116
|
-
`).map(t=>`<p>${j0(t)}</p>`).join(""),jl=e=>e?`<p></p><p>-- </p>${N0(e)}`:"",E0=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",I0=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",R0=(e,t,s)=>{const{envelope:n}=e,o=(n.replyTo.length>0?n.replyTo:n.from).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),c=new Set(o.map(m=>m.email.toLowerCase())),u=[...n.to,...n.cc].filter(m=>m.normalizedEmail.toLowerCase()!==i&&!c.has(m.normalizedEmail.toLowerCase())).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));return{to:o,cc:u}},T0=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}},Nl=(e,t,s)=>({textBody:t.text||void 0,htmlBody:e==="plain"?"":t.html?Um(t.html,s):void 0}),M0=(e,t,s,n,a)=>e.length===0&&t.length===0&&s.length===0&&n.trim()===""&&a.text.trim()==="",A0=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:n,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:c,showCc:u,setShowCc:m,showBcc:d,setShowBcc:f,subject:h,setSubject:v})=>{const x=es(),{isKeyboardOpen:p}=w0();return r.jsx(kx,{collapsed:!x&&p,summary:Cx({to:s,cc:a,bcc:i,subject:h}),from:r.jsx(S0,{selectedAccountId:e,onSelect:t}),to:r.jsx(oa,{label:"To",addresses:s,onChange:n,placeholder:"Recipients"}),cc:u?r.jsx(oa,{label:"Cc",addresses:a,onChange:o}):void 0,bcc:d?r.jsx(oa,{label:"Bcc",addresses:i,onChange:c}):void 0,subject:r.jsx(Nx,{value:h,onChange:v}),onShowCc:()=>m(!0),onShowBcc:()=>f(!0)})},Fo=({mode:e,account:t,sourceMessage:s,onClose:n,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:c}=Jt(),{pushError:u}=nt(),{outboxMessageId:m}=o,[d,f]=l.useState([]),[h,v]=l.useState([]),[x,p]=l.useState([]),[b,y]=l.useState(""),[S,g]=l.useState(!1),[w,C]=l.useState(!1),[R,O]=l.useState(t?.accountId),[k,M]=l.useState(!1),P=l.useRef(m);l.useEffect(()=>{const pe=P.current;pe!==m&&(P.current=m,!(!m||pe===void 0)&&(f([]),v([]),p([]),y(""),g(!1),C(!1),I(""),T(""),N("rich"),oe(void 0),Z(ob),A(Ce=>Ce+1),M(!1)))},[m]);const{signature:E}=Ah(R),[L,A]=l.useState(0),[j,I]=l.useState(()=>jl(E.plainText)),[D,T]=l.useState(E.plainText),[F,N]=l.useState("rich"),[V,J]=l.useState("en"),[re,oe]=l.useState(),[ie,Z]=l.useState(()=>({html:jl(E.plainText),text:E.plainText,formatting:[]})),{data:ae}=we({..._m({path:{outboxMessageId:m??""}}),enabled:!!m&&!k});l.useEffect(()=>{if(!ae||k)return;f(ae.toAddresses.map(_=>({email:_,displayName:void 0}))),ae.ccAddresses&&ae.ccAddresses.length>0&&(v(ae.ccAddresses.map(_=>({email:_,displayName:void 0}))),g(!0)),ae.bccAddresses&&ae.bccAddresses.length>0&&(p(ae.bccAddresses.map(_=>({email:_,displayName:void 0}))),C(!0)),ae.subject&&y(ae.subject);const pe=zm(ae.htmlBody??""),Ce=pe.html,Te=ae.textBody??"";N(Mb(ae.htmlBody)),oe(pe.language??void 0),I(Ce),T(Te),Z({html:Ce,text:Te,formatting:[]}),A(_=>_+1),O(ae.accountId),M(!0)},[ae,k]),l.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:pe,cc:Ce}=R0(s,e,t?.email);f(pe),v(Ce),Ce.length>0&&g(!0),y(E0(s.envelope.subject))}e==="forward"&&y(I0(s.envelope.subject))}},[e,s,t?.email]);const fe=e==="reply"||e==="reply_all"||e==="forward",{data:B}=hd({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:fe&&!!s}),$=B?.kind==="text"?B.body:"",me=B?.kind==="html"?vb(B.body):void 0,ge=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,Se=l.useCallback(pe=>{M(!0),i(pe)},[i]),{saveStatus:Ne,saveError:H,saveDraft:Ee,saveImmediately:xe,stopAutoSave:ke}=v0({outboxMessageId:m,onDraftCreated:Se});l.useEffect(()=>{H&&u({title:"Couldn't save draft",detail:ft(H)??"Saving the draft failed.",error:H})},[H,u]);const de=Ue(kc()),se=Ue({...dr(),onError:pe=>{u(ds("Couldn't discard draft","The draft wasn't discarded.",pe))}}),{data:ye}=we({...$t(),staleTime:1/0}),Pe=ye?.accounts.find(pe=>pe.accountId===R),ze=Pe?Th(Pe):!1,X=Pe?.composeLanguages,Ze=l.useMemo(()=>X&&X.length>0?X:Bm(navigator.languages),[X]),Ie=l.useRef(!1),[qe,K]=l.useState(!1),Qe=d.length>0&&!!R&&!ze;l.useEffect(()=>{if(!R||m&&!k||M0(d,h,x,b,ie))return;const{htmlBody:pe,textBody:Ce}=Nl(F,ie,V);Ee({accountId:R,toAddresses:d.map(Te=>Te.email),ccAddresses:h.length>0?h.map(Te=>Te.email):void 0,bccAddresses:x.length>0?x.map(Te=>Te.email):void 0,subject:b||void 0,textBody:Ce,htmlBody:pe})},[R,m,k,d,h,x,b,ie,F,V,Ee]);const Re=l.useCallback(async()=>{if(!Ie.current&&!(!R||d.length===0)){Ie.current=!0,K(!0);try{ke();const pe=s&&(e==="reply"||e==="reply_all")?T0(s):{},{htmlBody:Ce,textBody:Te}=Nl(F,ie,V),_=!m,le=await xe({accountId:R,toAddresses:d.map(q=>q.email),ccAddresses:h.length>0?h.map(q=>q.email):void 0,bccAddresses:x.length>0?x.map(q=>q.email):void 0,subject:b||void 0,textBody:Te,htmlBody:Ce,...pe});if(le.outcome==="failed"){u({title:"Couldn't send message",detail:ft(le.error)??"Saving the message failed, so nothing was sent. Try again.",error:le.error});return}const ue=le.outboxMessageId;if(await de.mutateAsync({path:{outboxMessageId:ue}}).catch(q=>(u({title:"Couldn't send message",detail:ft(q)??(_?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:q}),null))===null)return;ke(ue),c(ue),n()}finally{Ie.current=!1,K(!1)}}},[R,d,h,x,b,ie,F,V,e,s,m,xe,de,ke,c,u,n]),be=l.useCallback(()=>{ke(m),m&&se.mutate({path:{outboxMessageId:m}}),n()},[ke,m,se,n]),Oe=l.useCallback(pe=>{O(pe.accountId),a?.(pe)},[a]);return r.jsx(Sx,{banner:Pe&&ze?r.jsx(y0,{accountId:Pe.accountId}):void 0,header:r.jsx(A0,{selectedAccountId:R,onAccountChange:Oe,toAddresses:d,setToAddresses:f,ccAddresses:h,setCcAddresses:v,bccAddresses:x,setBccAddresses:p,showCc:S,setShowCc:g,showBcc:w,setShowBcc:C,subject:b,setSubject:y}),quoted:$||me?r.jsx(Wx,{text:$,html:me,senderName:ge}):void 0,actionBar:r.jsx(bx,{onSend:Re,onDiscard:be,sending:qe,canSend:Qe,saveStatus:Ne,unavailableReason:ze?"SMTP not configured":void 0,onUnavailable:pe=>u({title:"Can't send yet",detail:pe})}),children:r.jsx(l.Suspense,{fallback:r.jsx(k0,{}),children:r.jsx(C0,{mode:F,onModeChange:N,initialHtml:j,initialText:D,onChange:Z,onSubmit:Re,autoFocus:e==="new",onConversionError:u,languages:Ze,initialLanguage:re,onLanguageChange:J},L)})})},El=({mode:e,account:t,sourceMessage:s,onClose:n})=>r.jsx("div",{className:"border-t border-line bg-canvas max-h-[min(400px,60dvh)] flex flex-col",children:r.jsx(Fo,{mode:e,account:t,sourceMessage:s,onClose:n})}),pd=({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})]}),$o=({enabled:e=!0,bindings:t,capture:s=!1})=>{const n=l.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const m=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(m&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);l.useEffect(()=>{if(e)return window.addEventListener("keydown",n,s),()=>window.removeEventListener("keydown",n,s)},[e,n,s])},_o=e=>{const{data:t,isLoading:s}=we({...$t(),staleTime:1/0}),n=l.useMemo(()=>(t?.accounts??[]).map(c=>c.accountId),[t?.accounts]),a=mt({queries:n.map(c=>({...it({path:{accountId:c}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(c=>c.isLoading);return{accountId:l.useMemo(()=>{if(e){for(let c=0;c<n.length;c++)if((a[c].data?.items??[]).some(d=>d.mailboxId===e))return n[c]}},[e,n,a]),isLoading:o}},O0=100,Ma=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),D0=(e,t=O0)=>{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},gd=async(e,t,s,n)=>{const a=D0(e),o=e.length;let i=0;const c=[];for(let u=0;u<a.length;u++){if(n())return c.push(...a.slice(u).flat()),{done:i,failedIds:c,cancelled:!0};const m=a[u],d=await Ma(t(m));if(!d.ok)return c.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:c,cancelled:!1,error:d.error};i+=m.length,s({done:i,total:o})}return{done:i,failedIds:c,cancelled:!1}},Os=async(e,t)=>{await gd(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},P0=async(e,t,s,n,a)=>{let o=0;const i=[];let c;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await Ma(e(c));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const m=u.value;if(m.ids.length>0){const d=await Ma(s(m.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=m.ids.length,n({done:o,total:t})}c=m.continuationToken}while(c);return{done:o,failedIds:i,cancelled:!1}},L0=e=>({done:e.done,total:Math.max(e.total,e.done)}),xd=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),bd=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),vd=(e,t)=>e===void 0?e:xd(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:bd(e)?{...e,items:t(e.items)}:e,Et=e=>{const t=[];for(const s of new Set(e))t.push(fr({path:{mailboxId:s}})),t.push(Za({path:{mailboxId:s}}));return t.push(eo()),t},yn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),wn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,n])=>({queryKey:s,data:n})),Sn=(e,t,s)=>{const n=a=>vd(a,s);for(const a of t)e.setQueriesData({queryKey:a},n)},Cn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},It=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},F0=3e3,$0=(e,t,s)=>{if(e.length===0)return()=>{};const n=setTimeout(()=>s(e),t);return()=>clearTimeout(n)},Mr=(e,t,s)=>{const n=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(n.get(o)??s);return[...a]},tr=(e,t,s)=>e.map(n=>t.has(n.messageId)?{...n,isRead:s}:n),_0=(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),z0=({messages:e,expandedIds:t,threadId:s,mailboxId:n,accountId:a})=>{const o=De(),{pushError:i}=nt(),c=l.useRef(new Set),u=l.useRef(new Set),{mutate:m}=Ue({...mr(),onMutate:async h=>{const v=new Set(h.body.messageIds??[]),x=h.body.isRead??!0,p=Zt({path:{threadId:s}}),b=Et(Mr(v,e,n));await Promise.all([o.cancelQueries({queryKey:p}),yn(o,b)]);const y=o.getQueriesData({queryKey:p}).filter(g=>g[1]!==void 0).map(([g,w])=>({queryKey:g,data:w})),S=wn(o,b);return o.setQueriesData({queryKey:p},g=>g&&{...g,items:tr(g.items,v,x)}),Sn(o,b,g=>tr(g,v,x)),{threadMessagesPrefix:p,listPrefixes:b,previousThreadMessages:y,previousThreadsList:S}},onSuccess:(h,v)=>{const x=v.body.messageIds??[];for(const p of x)c.current.add(p),u.current.delete(p)},onError:(h,v,x)=>{const p=v.body.messageIds??[];for(const y of p)u.current.delete(y);if(x){for(const y of x.previousThreadMessages)o.setQueryData(y.queryKey,y.data);Cn(o,x.previousThreadsList)}const b=v.body.isRead??!0;i({title:b?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(h),error:h})},onSettled:(h,v,x,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),It(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:Ft({path:{accountId:a}})}))}}),d=l.useCallback(h=>{const v=h.filter(x=>!c.current.has(x)&&!u.current.has(x));if(v.length!==0){for(const x of v)u.current.add(x);m({body:{messageIds:v,isRead:!0}})}},[m]),f=l.useMemo(()=>_0(e,t,c.current,u.current),[e,t]);l.useEffect(()=>$0(f,F0,d),[f,d]),l.useEffect(()=>{c.current.clear(),u.current.clear()},[s])},Ar=e=>{const{mailboxId:t,accountId:s,messages:n}=e,a=De(),{pushError:o}=nt(),{mutateAsync:i,isPending:c}=Ue({...mr(),onError:(m,d)=>{const f=d.body.isRead??!0;o({title:f?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(m),error:m})},onSettled:(m,d,f)=>{It(a,Et(Mr(f.body.messageIds??[],n??[],t))),s&&a.invalidateQueries({queryKey:Ft({path:{accountId:s}})})}});return{toggleReadFor:l.useCallback((m,d)=>{m.length!==0&&Os(m,f=>i({body:{messageIds:f,isRead:d}}))},[i]),isPending:c}},B0=60,U0=1.5,K0=(e,t,s)=>{const n=Math.abs(e),a=Math.abs(t);return n<s?{direction:null}:n<a*U0?{direction:null}:{direction:e<0?"left":"right"}},q0=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=B0})=>{const n=l.useRef(null),a=l.useCallback(u=>{if(u.pointerType==="mouse"){n.current=null;return}n.current={x:u.clientX,y:u.clientY}},[]),o=l.useCallback(()=>{},[]),i=l.useCallback(u=>{const m=n.current;if(n.current=null,!m)return;const{direction:d}=K0(u.clientX-m.x,u.clientY-m.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),c=l.useCallback(()=>{n.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:c}}},H0=(e,t,s)=>t?.find(n=>n.messageId===e)?.mailboxId??s,Il=(e,t,s)=>e.map(n=>n.messageId===t?{...n,hasStars:s}:n),zo=({threadId:e,mailboxId:t,messages:s})=>{const n=De(),{pushError:a}=nt(),{mutate:o,isPending:i,variables:c}=Ue({...qm(),onMutate:async m=>{const d=m.path.messageId,f=m.body.isStarred??!1,h=Zt({path:{threadId:e}}),v=Et([H0(d,s,t)]);await Promise.all([n.cancelQueries({queryKey:h}),yn(n,v)]);const x=n.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})),p=wn(n,v);return n.setQueriesData({queryKey:h},b=>vd(b,y=>Il(y,d,f))),Sn(n,v,b=>Il(b,d,f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:x,previousThreadsList:p}},onError:(m,d,f)=>{if(f){for(const v of f.previousThreadMessages)n.setQueryData(v.queryKey,v.data);Cn(n,f.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:ft(m),error:m})},onSettled:(m,d,f,h)=>{h&&(n.invalidateQueries({queryKey:h.threadMessagesPrefix}),It(n,h.listPrefixes))}});return{toggleStar:(m,d)=>{o({path:{messageId:m},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?c?.path.messageId:void 0}};function Or(e){return e===void 0?"uncategorized":e}const W0={inbox:"Inbox",junk:"Junk"},Bo=e=>e.destinationMailboxId!==void 0,V0=(e,t)=>{if(Bo(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${W0[s]??"another folder"} by Remit`},Q0=(e,t)=>{if(e===hi.MoveToInbox)return t.inboxMailboxId;if(e===hi.MoveToJunk)return t.junkMailboxId},G0=(e,t,s)=>{if(!e||!t)return!1;const n=Bo(e)?e.destinationMailboxId:Q0(e.action,s);return n!==void 0&&n===t},Y0="Reported as spam",X0=(e,t)=>{if(e){if(Bo(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},Dr=(e,t)=>{const{data:s,isLoading:n}=we({...$t(),staleTime:1/0,enabled:!!e});return{mailboxId:l.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:n}},J0=e=>{const{mailboxId:t,isLoading:s}=Dr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Z0=e=>{const{mailboxId:t,isLoading:s}=Dr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},yd=e=>{const{mailboxId:t,isLoading:s}=Dr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},kn=e=>{const{mailboxId:t,isLoading:s}=Dr(e,"Junk");return{junkMailboxId:t,isLoading:s}},Uo=e=>{const{data:t}=we({...$t(),staleTime:1/0,enabled:!!e});return l.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Rl=(e,t)=>e.filter(s=>!t.has(s.messageId)),Ds=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=De(),{pushError:o}=nt(),{mutateAsync:i,isPending:c,isError:u}=Ue({...Hm(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],v=Et([e,d.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:h})]:[],yn(a,v)]);const x=t?a.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})):[],p=wn(a,v);return t&&a.setQueriesData({queryKey:h},b=>b&&{...b,items:Rl(b.items,f)}),Sn(a,v,b=>Rl(b,f)),n?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:x,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const x of h.previousThreadMessages)a.setQueryData(x.queryKey,x.data);Cn(a,h.previousThreadsList)}const v=f.body.messageIds?.length??0;o({title:v>1?`Couldn't move ${v} messages`:"Couldn't move this message",detail:ft(d),error:d})},onSettled:(d,f,h,v)=>{v&&(t&&a.invalidateQueries({queryKey:v.threadMessagesPrefix}),It(a,v.listPrefixes),s&&a.invalidateQueries({queryKey:Ft({path:{accountId:s}})}))}});return{moveMessages:l.useCallback((d,f)=>{d.length!==0&&Os(d,h=>i({body:{messageIds:h,destinationMailboxId:f}}))},[i]),isPending:c,isError:u}},ew="This message could not be processed. Please try again.",tw=(e,t)=>e.replace(`Message ${t}'s`,"This message's"),Tl=e=>{if(e.failureCount===0)return;const t=e.failures?.[0],s=t?.reason??ew,n=t?tw(s,t.messageId):s;throw new Qm(n,422)};function wd({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n}){const a=De(),{pushError:o}=nt(),i=Et([e]),c=t?Zt({path:{threadId:t}}):[],u=()=>{t&&a.invalidateQueries({queryKey:c}),It(a,i),s&&a.invalidateQueries({queryKey:Ft({path:{accountId:s}})})},m=()=>(p,b)=>{u(),n?.(b.body.messageIds)},d=p=>(b,y)=>{o({title:p(y.body.messageIds.length),detail:ft(b),error:b})},f=Ue({mutationFn:async p=>{const{data:b}=await Wm({...p,throwOnError:!0});return Tl(b),b},meta:{softError:!0},onSuccess:m(),onError:d(p=>p>1?`Couldn't report ${p} messages as spam`:"Couldn't report this message as spam")}),h=Ue({mutationFn:async p=>{const{data:b}=await Vm({...p,throwOnError:!0});return Tl(b),b},meta:{softError:!0},onSuccess:m(),onError:d(p=>p>1?`Couldn't undo the spam report for ${p} messages`:"Couldn't undo the spam report")}),v=l.useCallback(p=>{p.length!==0&&Os(p,b=>f.mutateAsync({body:{messageIds:b}}))},[f.mutateAsync]),x=l.useCallback(p=>{p.length!==0&&Os(p,b=>h.mutateAsync({body:{messageIds:b}}))},[h.mutateAsync]);return{reportSpam:v,notSpam:x,isReporting:f.isPending,isRestoring:h.isPending}}const sw=({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o})=>{const{inboxMailboxId:i}=yd(e),{junkMailboxId:c}=kn(e),{moveMessages:u,isPending:m}=Ds({mailboxId:n,threadId:s,accountId:e}),{notSpam:d,isRestoring:f}=wd({mailboxId:n,threadId:s,accountId:e}),{data:h}=we({...it({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),v={inboxMailboxId:i,junkMailboxId:c},x=X0(a,v),p=l.useCallback(()=>{x&&u([t],x)},[u,t,x]),b=l.useCallback(()=>{d([t])},[d,t]);if(o)return{show:!0,label:Y0,onUndo:b,isUndoing:f};if(!G0(a,n,v)||!a)return{show:!1,label:"",isUndoing:!1};const S=a.fromMailboxId?h?.items.filter(g=>g.mailboxId===a.fromMailboxId).map(g=>ba(g.fullPath))[0]:void 0;return{show:!0,label:V0(a,S),onUndo:x?p:void 0,isUndoing:m,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function nw({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o}){const i=sw({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o});return i.show?r.jsx(mx,{label:i.label,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:i.filtersHref}):null}const Ml=(e,t)=>e.filter(s=>!t.has(s.messageId)),rw=e=>e.filter(t=>t.isDeleted!==!0),ms=({mailboxId:e,threadId:t,accountId:s,messages:n,onAfterOptimisticRemove:a})=>{const o=De(),{pushError:i}=nt(),{mutateAsync:c,isPending:u}=Ue({...Gm(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],v=Et(Mr(f,n??[],e));await Promise.all([o.cancelQueries({queryKey:h}),yn(o,v)]);const x=t?o.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})):[],p=wn(o,v);return t&&o.setQueriesData({queryKey:h},b=>b&&{...b,items:Ml(b.items,f)}),Sn(o,v,b=>Ml(b,f)),a?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:x,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const x of h.previousThreadMessages)o.setQueryData(x.queryKey,x.data);Cn(o,h.previousThreadsList)}const v=f.body.messageIds?.length??0;i({title:v>1?`Couldn't delete ${v} messages`:"Couldn't delete this message",detail:ft(d),error:d})},onSettled:(d,f,h,v)=>{v&&(t&&o.invalidateQueries({queryKey:v.threadMessagesPrefix}),It(o,v.listPrefixes),s&&o.invalidateQueries({queryKey:Ft({path:{accountId:s}})}))}});return{deleteMessages:l.useCallback(d=>{d.length!==0&&Os(d,f=>c({body:{messageIds:f}}))},[c]),isPending:u}},Sd=(e,t=Date.now())=>({value:e,setAt:t}),aw=(e,t,s,n)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Sd(!0,n):delete a.trusted,{...e,flags:a}},ow=(e,t,s,n)=>{const a=o=>o.map(i=>aw(i,t,s,n));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},Ko=({messageId:e})=>{const t=De(),{pushError:s}=nt(),{mutate:n,isPending:a,error:o,reset:i}=Ue({...jc(),onMutate:async u=>{const m=u.path.addressId,f=u.body.flags?.trusted?.value===!0,h=Ja({path:{messageId:e}});await t.cancelQueries({queryKey:h});const v=t.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,p])=>({queryKey:x,data:p}));return t.setQueriesData({queryKey:h},x=>x&&ow(x,m,f)),{describePrefix:h,previous:v}},onError:(u,m,d)=>{if(d)for(const f of d.previous)t.setQueryData(f.queryKey,f.data);s(ds("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:Sd(!m)}}})},isPending:a,error:o,reset:i}};var Pr="Dialog",[Cd]=lv(Pr),[iw,xt]=Cd(Pr),kd=e=>{const{__scopeDialog:t,children:s,open:n,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,c=l.useRef(null),u=l.useRef(null),[m,d]=dv({prop:n,defaultProp:a??!1,onChange:o,caller:Pr});return r.jsx(iw,{scope:t,triggerRef:c,contentRef:u,contentId:ta(),titleId:ta(),descriptionId:ta(),open:m,onOpenChange:d,onOpenToggle:l.useCallback(()=>d(f=>!f),[d]),modal:i,children:s})};kd.displayName=Pr;var jd="DialogTrigger",lw=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(jd,s),o=gs(t,a.triggerRef);return r.jsx(_t.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Ho(a.open),...n,ref:o,onClick:Vt(e.onClick,a.onOpenToggle)})});lw.displayName=jd;var qo="DialogPortal",[cw,Nd]=Cd(qo,{forceMount:void 0}),Ed=e=>{const{__scopeDialog:t,forceMount:s,children:n,container:a}=e,o=xt(qo,t);return r.jsx(cw,{scope:t,forceMount:s,children:l.Children.map(n,i=>r.jsx(Nr,{present:s||o.open,children:r.jsx(zu,{asChild:!0,container:a,children:i})}))})};Ed.displayName=qo;var sr="DialogOverlay",Id=l.forwardRef((e,t)=>{const s=Nd(sr,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(sr,e.__scopeDialog);return o.modal?r.jsx(Nr,{present:n||o.open,children:r.jsx(dw,{...a,ref:t})}):null});Id.displayName=sr;var uw=Pu("DialogOverlay.RemoveScroll"),dw=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(sr,s),o=Tv(),i=gs(t,o);return r.jsx(Qu,{as:uw,allowPinchZoom:!0,shards:[a.contentRef],children:r.jsx(_t.div,{"data-state":Ho(a.open),...n,ref:i,style:{pointerEvents:"auto",...n.style}})})}),Ps="DialogContent",Rd=l.forwardRef((e,t)=>{const s=Nd(Ps,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(Ps,e.__scopeDialog);return r.jsx(Nr,{present:n||o.open,children:o.modal?r.jsx(fw,{...a,ref:t}):r.jsx(mw,{...a,ref:t})})});Rd.displayName=Ps;var fw=l.forwardRef((e,t)=>{const s=xt(Ps,e.__scopeDialog),n=l.useRef(null),a=gs(t,s.contentRef,n);return l.useEffect(()=>{const o=n.current;if(o)return Jv(o)},[]),r.jsx(Td,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Vt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Vt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&o.preventDefault()}),onFocusOutside:Vt(e.onFocusOutside,o=>o.preventDefault())})}),mw=l.forwardRef((e,t)=>{const s=xt(Ps,e.__scopeDialog),n=l.useRef(!1),a=l.useRef(!1);return r.jsx(Td,{...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()}})}),Td=l.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,c=xt(Ps,s);return Dv(),r.jsx(r.Fragment,{children:r.jsx($u,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:r.jsx(Lu,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":Ho(c.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})}),Md="DialogTitle",Ad=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Md,s);return r.jsx(_t.h2,{id:a.titleId,...n,ref:t})});Ad.displayName=Md;var Od="DialogDescription",hw=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Od,s);return r.jsx(_t.p,{id:a.descriptionId,...n,ref:t})});hw.displayName=Od;var Dd="DialogClose",pw=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Dd,s);return r.jsx(_t.button,{type:"button",...n,ref:t,onClick:Vt(e.onClick,()=>a.onOpenChange(!1))})});pw.displayName=Dd;function Ho(e){return e?"open":"closed"}function gw(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 Pd=W.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),jn=()=>{const e=W.useContext(Pd);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};gw(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
|
|
115
|
+
`)},Oy=0,js=[];function Dy(e){var t=l.useRef([]),s=l.useRef([0,0]),n=l.useRef(),a=l.useState(Oy++)[0],o=l.useState(qu)[0],i=l.useRef(e);l.useEffect(function(){i.current=e},[e]),l.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=Sm([e.lockRef.current],(e.shards||[]).map(vl),!0).filter(Boolean);return p.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var c=l.useCallback(function(p,b){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var y=Ln(p),S=s.current,g="deltaX"in p?p.deltaX:S[0]-y[0],w="deltaY"in p?p.deltaY:S[1]-y[1],C,R=p.target,O=Math.abs(g)>Math.abs(w)?"h":"v";if("touches"in p&&O==="h"&&R.type==="range")return!1;var k=window.getSelection(),M=k&&k.anchorNode,P=M?M===R||M.contains(R):!1;if(P)return!1;var E=xl(O,R);if(!E)return!0;if(E?C=O:(C=O==="v"?"h":"v",E=xl(O,R)),!E)return!1;if(!n.current&&"changedTouches"in p&&(g||w)&&(n.current=C),!C)return!0;var L=n.current||C;return Ty(L,b,p,L==="h"?g:w)},[]),u=l.useCallback(function(p){var b=p;if(!(!js.length||js[js.length-1]!==o)){var y="deltaY"in b?bl(b):Ln(b),S=t.current.filter(function(C){return C.name===b.type&&(C.target===b.target||b.target===C.shadowParent)&&My(C.delta,y)})[0];if(S&&S.should){b.cancelable&&b.preventDefault();return}if(!S){var g=(i.current.shards||[]).map(vl).filter(Boolean).filter(function(C){return C.contains(b.target)}),w=g.length>0?c(b,g[0]):!i.current.noIsolation;w&&b.cancelable&&b.preventDefault()}}},[]),m=l.useCallback(function(p,b,y,S){var g={name:p,delta:b,target:y,should:S,shadowParent:Py(y)};t.current.push(g),setTimeout(function(){t.current=t.current.filter(function(w){return w!==g})},1)},[]),d=l.useCallback(function(p){s.current=Ln(p),n.current=void 0},[]),f=l.useCallback(function(p){m(p.type,bl(p),p.target,c(p,e.lockRef.current))},[]),h=l.useCallback(function(p){m(p.type,Ln(p),p.target,c(p,e.lockRef.current))},[]);l.useEffect(function(){return js.push(o),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",u,ks),document.addEventListener("touchmove",u,ks),document.addEventListener("touchstart",d,ks),function(){js=js.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,ks),document.removeEventListener("touchmove",u,ks),document.removeEventListener("touchstart",d,ks)}},[]);var v=e.removeScrollBar,x=e.inert;return l.createElement(l.Fragment,null,x?l.createElement(o,{styles:Ay(a)}):null,v?l.createElement(Cy,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Py(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Ly=uy(Ku,Dy);var Qu=l.forwardRef(function(e,t){return l.createElement(Er,Kt({},e,{ref:t,sideCar:Ly}))});Qu.classNames=Er.classNames;var Fy=class extends Wa{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,n=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:c}=n,u=s.fetchMeta?.fetchMore?.direction,m=i&&u==="forward",d=a&&u==="forward",f=i&&u==="backward",h=a&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:km(t,s.data),hasPreviousPage:Cm(t,s.data),isFetchNextPageError:m,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:c&&!m&&!f,isRefetching:o&&!d&&!h}}};function yl(e,t){const s=new Set(t);return e.filter(n=>!s.has(n))}function $y(e,t,s){const n=e.slice(0);return n[t]=s,n}var _y=class extends jm{#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,xa.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,c=a.some((d,f)=>d!==s[f]),u=i||c,m=u?!0:o.some((d,f)=>{const h=this.#e[f];return!h||!Nm(d,h)});!u&&!m||(u&&(this.#c=n,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(yl(s,a).forEach(d=>{d.destroy()}),yl(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=Em(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 Wa(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=$y(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)&&xa.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function mt({queries:e,...t},s){const n=De(),a=Im(),o=Rm(),i=l.useMemo(()=>e.map(p=>{const b=n.defaultQueryOptions(p);return b._optimisticResults=a?"isRestoring":"optimistic",b}),[e,n,a]);i.forEach(p=>{Tm(p);const b=n.getQueryCache().get(p.queryHash);Mm(p,o,b)}),Am(o);const[c]=l.useState(()=>new _y(n,i,t)),[u,m,d]=c.getOptimisticResult(i,t.combine),f=!a&&t.subscribed!==!1;l.useSyncExternalStore(l.useCallback(p=>f?c.subscribe(xa.batchCalls(p)):Om,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),l.useEffect(()=>{c.setQueries(i,t)},[i,t,c]);const v=u.some((p,b)=>li(i[b],p))?u.flatMap((p,b)=>{const y=i[b];if(y&&li(y,p)){const S=new Wa(n,y);return Dm(y,S,o)}return[]}):[];if(v.length>0)throw Promise.all(v);const x=u.find((p,b)=>{const y=i[b];return y&&Pm({result:p,errorResetBoundary:o,throwOnError:y.throwOnError,query:n.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(x?.error)throw x.error;return m(d())}function Gu(e,t){return Lm(e,Fy)}function zy(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 Yu(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:a=!1,withResolver:o=!1}=zy(e),i=Va(),{history:c}=i,[u,m]=l.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return l.useEffect(()=>{const d=async f=>{function h(y){const S=i.parseLocation(y),g=i.getMatchedRoutes(S.pathname);return g.foundRoute===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:g.routeParams,search:i.options.parseSearch(y.search)}:{routeId:g.foundRoute.id,fullPath:g.foundRoute.fullPath,pathname:S.pathname,params:g.routeParams,search:i.options.parseSearch(y.search)}}const v=h(f.currentLocation),x=h(f.nextLocation);if(v.routeId==="__notFound__"&&x.routeId!=="__notFound__")return!1;const p=await s({action:f.action,current:v,next:x});if(!o)return p;if(!p)return!1;const b=await new Promise(y=>{m({status:"blocked",current:v,next:x,action:f.action,proceed:()=>y(!1),reset:()=>y(!0)})});return m({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),b};return a?void 0:c.block({blockerFn:d,enableBeforeUnload:n})},[s,n,a,o,c,i]),u}function Ot(e){const t=Va({warn:e?.router===void 0}),s=e?.router||t;return bc(s.stores.__store,vc(e,s))}function Ir(e){const t=Va();return bc(t.stores.location,vc(e,t))}const By=new Set(["outbox","flagged"]),Uy=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!By.has(s)};function Ky(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,n]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=Qa(n.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function Xu(e){const{openCompose:t}=Jt(),s=Ye(),n=Ir(),a=Ky(e);return l.useCallback(()=>{if(Uy(n.pathname)){l.startTransition(()=>{t({mode:"new"})});return}a&&(l.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,n.pathname,a])}const qy=e=>e.startsWith("/mail")||e.startsWith("/settings"),Hy=({accounts:e})=>{const{state:t}=Jt(),s=Ir(),n=Xu(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!qy(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(Th,{className:"size-6"})})},Ju=({trigger:e,children:t,align:s="right"})=>{const[n,a]=l.useState(!1),o=l.useRef(null),i=l.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),c=l.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return l.useEffect(()=>(n&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",c)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",c)}),[n,i,c]),r.jsxs("div",{ref:o,className:"relative",children:[r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!n)},className:Ve("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),n&&r.jsx("div",{className:Ve("absolute z-50 mt-1 min-w-[180px] py-1","bg-surface border border-line rounded-md shadow-lg",s==="right"?"right-0":"left-0"),children:t})]})},nn=({onClick:e,disabled:t,destructive:s,children:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:Ve("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:n}),Zu=()=>r.jsx("div",{className:"my-1 h-px bg-line"}),ed=({children:e})=>{const{Account:t}=lr();return r.jsx(t,{children:e})},Wy=({email:e,onSignOut:t})=>{const s=e??"Account";return r.jsxs(Ju,{trigger:r.jsx(jt,{name:s,email:e??void 0,size:"sm"}),align:"right",children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),r.jsx(Zu,{})]}),r.jsxs(nn,{onClick:t,children:[r.jsx(Xc,{className:"size-4"}),"Sign out"]})]})},Vy=()=>r.jsx(ed,{children:({email:e,signOut:t})=>r.jsx(Wy,{email:e,onSignOut:t})}),Qy=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function Ao(e){return!!e&&Qy.has(e)}const td=3e3,Gy=td*2,wl={syncing:!1,resolved:!1,synced:0,total:0};function Yy(e,t){const s=e.join(","),[n,a]=l.useState(!1),[o,i]=l.useState(!1);l.useEffect(()=>{a(!1),i(!1)},[s,t]),l.useEffect(()=>{if(!t)return;const x=setTimeout(()=>i(!0),Gy);return()=>clearTimeout(x)},[s,t]);const c=mt({queries:e.map(x=>({...Gn({path:{accountId:x}}),enabled:t&&!n,refetchInterval:td,meta:{softError:!0}}))}),u=c.every(x=>x.isSuccess||x.isError),m=c.length===0||u||o;let d=!1,f=0,h=0;for(const x of c)if(Ao(x.data?.syncPhase)){d=!0;for(const p of x.data?.mailboxes??[])f+=p.messagesSynced,h+=p.messagesTotal}const v=t&&m&&!d;return l.useEffect(()=>{v&&a(!0)},[v]),!t||!m?wl:{syncing:d,resolved:!0,synced:f,total:h}}const Sl=6e4,Xy=new Set(["sent","drafts","trash","archive"]),Cl=(e,t)=>{const s=new Map;for(const n of e){const a=t.get(n.mailboxId)?.role;a&&Xy.has(a)||s.set(n.mailboxId,n.messagesTotal)}return s},Jy=(e,t)=>{for(const[s,n]of t)if(n>(e.get(s)??0))return!0;return!1},sd=l.createContext(null),Rr=()=>{const e=l.useContext(sd);if(!e)throw new Error("useMailFreshness must be used inside <MailFreshnessProvider>");return e};function Zy({accountIds:e,children:t}){const s=De(),{resultFolderIndex:n}=Fe(),a=l.useRef(new Map),o=l.useRef(new Set),[i,c]=l.useState(new Set),u=mt({queries:e.map(x=>({...Gn({path:{accountId:x}}),refetchInterval:Sl,staleTime:Sl,meta:{softError:!0}}))}),m=u.map(x=>x.dataUpdatedAt).join(","),d=e.join(",");l.useEffect(()=>{let x=!1;const p=new Set(i);e.forEach((b,y)=>{const S=u[y]?.data;if(!S)return;const g=Cl(S.mailboxes??[],n);if(!o.current.has(b)){o.current.add(b),a.current.set(b,g);return}if(p.has(b))return;const w=a.current.get(b)??new Map;Jy(w,g)&&(p.add(b),x=!0)}),x&&c(p)},[d,m]);const f=l.useCallback(x=>x.some(p=>i.has(p)),[i]),h=l.useCallback(x=>{c(p=>{if(x.every(y=>!p.has(y)))return p;const b=new Set(p);for(const y of x)b.delete(y);return b});for(const p of x){const b=s.getQueryData(Gn({path:{accountId:p}}).queryKey);a.current.set(p,Cl(b?.mailboxes??[],n)),o.current.add(p)}},[s,n]),v=l.useMemo(()=>({hasNewMail:f,acknowledge:h}),[f,h]);return r.jsx(sd.Provider,{value:v,children:t})}const e0=2e3,t0=45e3,s0=e=>new Promise(t=>setTimeout(t,e)),Ra=e=>e instanceof Error&&e.message?e.message:"Something went wrong",n0=e=>{wc(e,{softError:!0})&&Ga(e)},nd=e=>e.reduce((t,s)=>Math.max(t,s.lastSyncedAt??0),0),rd=(e,t)=>e.fetchQuery({...Gn({path:{accountId:t}}),staleTime:0}),r0=async(e,t,s,n)=>{let a=!1;for(;;){const o=await rd(e,t).then(u=>({ok:!0,data:u})).catch(u=>({ok:!1,error:u}));if(!o.ok)return{accountId:t,message:Ra(o.error)};const{syncPhase:i,mailboxes:c}=o.data;if(Ao(i))a=!0;else if(a||nd(c??[])>s)return i==="error"?{accountId:t,message:"Sync failed for this account"}:void 0;if(Date.now()>=n)return{accountId:t,message:"Refresh is taking longer than usual"};await s0(e0)}},a0=async(e,t,s,n)=>{const a=await rd(e,s).then(c=>({ok:!0,maxLastSynced:nd(c.mailboxes??[])})).catch(c=>({ok:!1,error:c}));if(!a.ok)return{accountId:s,enqueued:!1,ok:!1,message:Ra(a.error)};const o=await yc({path:{accountId:s},throwOnError:!0}).then(()=>({ok:!0})).catch(c=>({ok:!1,error:c}));if(!o.ok)return n0(o.error),{accountId:s,enqueued:!1,ok:!1,message:Ra(o.error)};t.recordEvent("sync.triggered");const i=await r0(e,s,a.maxLastSynced,n);return i?{accountId:s,enqueued:!0,ok:!1,message:i.message}:{accountId:s,enqueued:!0,ok:!0}},Oo=(e,t={})=>{const s=De(),n=Ls(),{acknowledge:a}=Rr(),[o,i]=l.useState("idle"),[c,u]=l.useState(),m=l.useRef(0),d=l.useRef(e);d.current=e;const f=l.useRef(t);f.current=t,l.useEffect(()=>{if(o!=="success")return;const v=setTimeout(()=>i("idle"),2e3);return()=>clearTimeout(v)},[o]);const h=l.useCallback(()=>{const v=d.current;if(v.length===0){i("error"),u("Nothing to refresh yet");return}const x=++m.current;i("refreshing"),u(void 0),(async()=>{const p=Date.now()+t0,b=await Promise.all(v.map(g=>a0(s,n,g,p)));if(m.current!==x)return;const y=b.filter(g=>g.enqueued).map(g=>g.accountId);for(const g of y)s.invalidateQueries({queryKey:Ft({path:{accountId:g}})});y.length>0&&(f.current.onSettled?.(),a(y));const S=b.filter(g=>!g.ok);S.length===0?i("success"):(i("error"),u(S[0]?.message))})()},[a,s,n]);return{state:o,errorMessage:c,refresh:h}},ad="/mail/",Do="/mail/$mailboxId",od="/mail/outbox",id="/mail/flagged";function Po(e){return e.some(t=>t.routeId===ad)}function vn(e){return e.some(t=>t.routeId===id)}function Tr(e){return e.some(t=>t.routeId===od)}function ld(e){return e.some(t=>t.routeId===Do)}function o0(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${Do}:${t}`:vn(e)?id:Tr(e)?od:Po(e)?ad:""}const Hn="search-scope";function i0(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function cd(e){return vn(e)||Tr(e)||ld(e)}function ud(e){return e.find(t=>t.routeId===Do)?.params?.mailboxId}function l0(e){const t=ud(e.matches);return t||(cd(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function c0(e,t){return Po(e)?{kind:"global"}:vn(e)?{kind:"scoped",chip:{id:Hn,label:"is:starred"}}:Tr(e)?{kind:"scoped",chip:{id:Hn,label:"in:outbox"}}:ld(e)?t?{kind:"scoped",chip:{id:Hn,label:i0(t)}}:{kind:"pending"}:{kind:"global"}}function u0(e,t,s){return t.kind==="global"?{kind:"global"}:vn(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const dd=({accounts:e})=>{const t=Ya({strict:!1}),s=Ir(),n=t.mailboxId,{t:a}=Xa("mail",{useSuspense:!1}),o=l.useCallback((c,u)=>a(c,{defaultValue:u}),[a]),i=mt({queries:e.map(c=>({...it({path:{accountId:c.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!n)return null;for(let c=0;c<e.length;c++){const u=i[c]?.data?.items;if(!u)continue;const m=u.find(f=>f.mailboxId===n);if(!m)continue;const d=Qa(e[c].folderAppointments);return Yn(m,d.get(n),o)}return null},d0=({accounts:e})=>{const s=Ya({strict:!1}).mailboxId,n=mt({queries:e.map(a=>({...it({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of n){const o=a.data?.items;if(!o)continue;const i=o.find(c=>c.mailboxId===s);if(i)return i.unseenCount}return null};function fd(e){const t=Ye(),{searchInput:s}=Fe(),n=dd({accounts:e}),a=Ot({select:c=>c.matches}),o=c0(a,n),i=l.useCallback(c=>{c===Hn&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}function f0({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:n,onSearchClearQuery:a}=Fe(),o=Ye(),i=Xu(e),{scope:c,clearScope:u}=fd(e),m=c.kind==="scoped"?[{id:c.chip.id,label:c.chip.label,tone:"scope"}]:void 0,d=l.useMemo(()=>e.map(p=>p.accountId),[e]),{hasNewMail:f}=Rr(),{state:h,errorMessage:v,refresh:x}=Oo(d);return r.jsx(db,{search:{value:t,scope:c.kind,chips:m,onChange:s,onClear:n,onClearQuery:a,onRemoveChip:u},onCompose:i,onReportBug:Sc,onOpenSettings:()=>o({to:"/settings/accounts"}),composeShortcut:nu("compose"),refreshControl:r.jsx(jo,{state:h,onRefresh:x,label:"Refresh all accounts",errorMessage:v,hasUpdate:f(d)}),account:r.jsx(Vy,{})})}const Lo=({isOpen:e,onClose:t,children:s,ariaLabel:n="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=l.useRef(null),c=l.useRef(null);if(l.useEffect(()=>{if(!e)return;c.current=document.activeElement;const m=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",m),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=f,c.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return r.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":n,children:[r.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),r.jsxs("div",{ref:i,className:Ve("safe-area-frame absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[r.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:r.jsx(Nt,{className:"size-5"})})}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},m0=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},Ta={all:["messages"],detail:e=>[...Ta.all,"detail",e],body:e=>[...Ta.detail(e),"body"]};class cs 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 h0=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},p0=8,g0="x-remit-403-reason",md=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},x0=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,b0=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},v0=async(e,t,s=async()=>null)=>{const n={},a=await s();a&&(n.Authorization=`Bearer ${a}`);const o=await Cc(e,{headers:n});if(o.status===202)throw new cs("not-ready","Message body is still syncing",202,h0(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(g0),m=md(o.status,u);throw new cs(m,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(b0(t,i))throw new cs("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const c=await o.text();if(x0(c,i))throw new cs("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return c},y0=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),hd=({messageId:e,bodyParts:t,enabled:s=!0})=>{const n=t?m0(t):null,a=Ls(),{getToken:o}=lr(),i=l.useRef(null),c=De(),u=l.useRef(!1),m=l.useRef(null),d=e&&n?`${e}:${n.contentUrl}`:null;m.current!==d&&(m.current=d,u.current=!1);const f=we({queryKey:e?[...Ta.body(e),n?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!n)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const x=u.current;return u.current=!1,y0({fetchContent:(p,b)=>v0(p,b,o),refetchDescribeMessage:()=>c.refetchQueries({queryKey:Ja({path:{messageId:e}})})},{contentUrl:n.contentUrl,kind:n.kind,isRetryAfterNotReady:x})},enabled:s&&!!e&&!!n,staleTime:300*1e3,gcTime:1800*1e3,retry:(x,p)=>p instanceof cs&&p.reason==="not-ready"?x<p0:x<1,retryDelay:(x,p)=>p instanceof cs&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=f.isLoading&&!!n;l.useEffect(()=>{h&&(i.current=performance.now())},[h]),l.useEffect(()=>{f.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[f.isSuccess,a]);const v=f.data&&n?{kind:n.kind,body:f.data}:void 0;return{picked:n,data:v,isLoading:h,isError:f.isError,error:f.error,refetch:f.refetch}},w0=e=>e.then(()=>{},()=>{}),S0=({outboxMessageId:e,onDraftCreated:t})=>{const[s,n]=l.useState("idle"),[a,o]=l.useState(null),i=l.useRef(void 0),c=l.useRef(new Set),u=De(),m=l.useRef(e),d=l.useRef(e);m.current!==e&&(m.current=e,d.current=e);const f=Ue(Fm()),h=Ue($m()),v=l.useCallback(async g=>{n("saving"),o(null);const w=d.current;if(w){const R=await h.mutateAsync({path:{outboxMessageId:w},body:{toAddresses:g.toAddresses,ccAddresses:g.ccAddresses,bccAddresses:g.bccAddresses,subject:g.subject,textBody:g.textBody,htmlBody:g.htmlBody,inReplyTo:g.inReplyTo,references:g.references}});return n("saved"),R}const C=await f.mutateAsync({body:{...g,sendImmediately:!1}});return d.current=C.outboxMessageId,t(C.outboxMessageId),n("saved"),u.invalidateQueries({queryKey:cr().queryKey}),C},[f,h,t,u]),x=l.useRef(Promise.resolve()),p=l.useCallback(g=>{const w=x.current.then(()=>v(g));return x.current=w0(w),w},[v]),b=l.useCallback(g=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{const w=d.current;w&&c.current.has(w)||p(g).catch(C=>{o(C),n("error")})},2e3)},[p]),y=l.useCallback(g=>(i.current&&clearTimeout(i.current),p(g).then(w=>({outcome:"saved",outboxMessageId:w.outboxMessageId})).catch(w=>(n("error"),{outcome:"failed",error:w}))),[p]),S=l.useCallback(g=>{i.current&&clearTimeout(i.current),g&&c.current.add(g)},[]);return{saveStatus:s,saveError:a,saveDraft:b,saveImmediately:y,stopAutoSave:S}},oa=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=l.useState(""),i=gr(a,200),{data:c}=we({...ur({query:{q:i,limit:8}}),enabled:i.length>=2}),u=l.useMemo(()=>(c?.items??[]).map(m=>({email:m.normalizedEmail,displayName:m.displayName})),[c]);return r.jsx(kx,{label:e,addresses:t,onChange:s,placeholder:n,suggestions:u,onQueryChange:o})},C0=({accountId:e})=>{const t=Ye();return r.jsx(Ix,{onConfigure:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})}})},kl=150,k0=()=>{const[e,t]=l.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>kl}});return l.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>kl})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},j0=({selectedAccountId:e,onSelect:t})=>{const{data:s}=we({...$t(),staleTime:1/0}),n=s?.accounts??[];if(l.useEffect(()=>{!e&&n.length===1&&n[0]&&t(n[0])},[e,n,t]),n.length<=1){const a=n[0];return a?r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=n.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:n.map(a=>r.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},N0=l.lazy(()=>Km(()=>import("./rich-text-CoTs3nIc.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.ComposeBody}))),E0=()=>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"})]}),I0=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),R0=e=>e.split(`
|
|
116
|
+
`).map(t=>`<p>${I0(t)}</p>`).join(""),jl=e=>e?`<p></p><p>-- </p>${R0(e)}`:"",T0=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",M0=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",A0=(e,t,s)=>{const{envelope:n}=e,o=(n.replyTo.length>0?n.replyTo:n.from).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),c=new Set(o.map(m=>m.email.toLowerCase())),u=[...n.to,...n.cc].filter(m=>m.normalizedEmail.toLowerCase()!==i&&!c.has(m.normalizedEmail.toLowerCase())).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));return{to:o,cc:u}},O0=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}},Nl=(e,t,s)=>({textBody:t.text||void 0,htmlBody:e==="plain"?"":t.html?Um(t.html,s):void 0}),D0=(e,t,s,n,a)=>e.length===0&&t.length===0&&s.length===0&&n.trim()===""&&a.text.trim()==="",P0=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:n,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:c,showCc:u,setShowCc:m,showBcc:d,setShowBcc:f,subject:h,setSubject:v})=>{const x=es(),{isKeyboardOpen:p}=k0();return r.jsx(Ex,{collapsed:!x&&p,summary:Nx({to:s,cc:a,bcc:i,subject:h}),from:r.jsx(j0,{selectedAccountId:e,onSelect:t}),to:r.jsx(oa,{label:"To",addresses:s,onChange:n,placeholder:"Recipients"}),cc:u?r.jsx(oa,{label:"Cc",addresses:a,onChange:o}):void 0,bcc:d?r.jsx(oa,{label:"Bcc",addresses:i,onChange:c}):void 0,subject:r.jsx(Rx,{value:h,onChange:v}),onShowCc:()=>m(!0),onShowBcc:()=>f(!0)})},Fo=({mode:e,account:t,sourceMessage:s,onClose:n,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:c}=Jt(),{pushError:u}=nt(),{outboxMessageId:m}=o,[d,f]=l.useState([]),[h,v]=l.useState([]),[x,p]=l.useState([]),[b,y]=l.useState(""),[S,g]=l.useState(!1),[w,C]=l.useState(!1),[R,O]=l.useState(t?.accountId),[k,M]=l.useState(!1),P=l.useRef(m);l.useEffect(()=>{const pe=P.current;pe!==m&&(P.current=m,!(!m||pe===void 0)&&(f([]),v([]),p([]),y(""),g(!1),C(!1),I(""),T(""),N("rich"),oe(void 0),Z(cb),A(Ce=>Ce+1),M(!1)))},[m]);const{signature:E}=Ph(R),[L,A]=l.useState(0),[j,I]=l.useState(()=>jl(E.plainText)),[D,T]=l.useState(E.plainText),[F,N]=l.useState("rich"),[V,J]=l.useState("en"),[re,oe]=l.useState(),[ie,Z]=l.useState(()=>({html:jl(E.plainText),text:E.plainText,formatting:[]})),{data:ae}=we({..._m({path:{outboxMessageId:m??""}}),enabled:!!m&&!k});l.useEffect(()=>{if(!ae||k)return;f(ae.toAddresses.map(_=>({email:_,displayName:void 0}))),ae.ccAddresses&&ae.ccAddresses.length>0&&(v(ae.ccAddresses.map(_=>({email:_,displayName:void 0}))),g(!0)),ae.bccAddresses&&ae.bccAddresses.length>0&&(p(ae.bccAddresses.map(_=>({email:_,displayName:void 0}))),C(!0)),ae.subject&&y(ae.subject);const pe=zm(ae.htmlBody??""),Ce=pe.html,Te=ae.textBody??"";N(Db(ae.htmlBody)),oe(pe.language??void 0),I(Ce),T(Te),Z({html:Ce,text:Te,formatting:[]}),A(_=>_+1),O(ae.accountId),M(!0)},[ae,k]),l.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:pe,cc:Ce}=A0(s,e,t?.email);f(pe),v(Ce),Ce.length>0&&g(!0),y(T0(s.envelope.subject))}e==="forward"&&y(M0(s.envelope.subject))}},[e,s,t?.email]);const fe=e==="reply"||e==="reply_all"||e==="forward",{data:B}=hd({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:fe&&!!s}),$=B?.kind==="text"?B.body:"",me=B?.kind==="html"?Sb(B.body):void 0,ge=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,Se=l.useCallback(pe=>{M(!0),i(pe)},[i]),{saveStatus:Ne,saveError:H,saveDraft:Ee,saveImmediately:xe,stopAutoSave:ke}=S0({outboxMessageId:m,onDraftCreated:Se});l.useEffect(()=>{H&&u({title:"Couldn't save draft",detail:ft(H)??"Saving the draft failed.",error:H})},[H,u]);const de=Ue(kc()),se=Ue({...dr(),onError:pe=>{u(ds("Couldn't discard draft","The draft wasn't discarded.",pe))}}),{data:ye}=we({...$t(),staleTime:1/0}),Pe=ye?.accounts.find(pe=>pe.accountId===R),ze=Pe?Oh(Pe):!1,X=Pe?.composeLanguages,Ze=l.useMemo(()=>X&&X.length>0?X:Bm(navigator.languages),[X]),Ie=l.useRef(!1),[qe,K]=l.useState(!1),Qe=d.length>0&&!!R&&!ze;l.useEffect(()=>{if(!R||m&&!k||D0(d,h,x,b,ie))return;const{htmlBody:pe,textBody:Ce}=Nl(F,ie,V);Ee({accountId:R,toAddresses:d.map(Te=>Te.email),ccAddresses:h.length>0?h.map(Te=>Te.email):void 0,bccAddresses:x.length>0?x.map(Te=>Te.email):void 0,subject:b||void 0,textBody:Ce,htmlBody:pe})},[R,m,k,d,h,x,b,ie,F,V,Ee]);const Re=l.useCallback(async()=>{if(!Ie.current&&!(!R||d.length===0)){Ie.current=!0,K(!0);try{ke();const pe=s&&(e==="reply"||e==="reply_all")?O0(s):{},{htmlBody:Ce,textBody:Te}=Nl(F,ie,V),_=!m,le=await xe({accountId:R,toAddresses:d.map(q=>q.email),ccAddresses:h.length>0?h.map(q=>q.email):void 0,bccAddresses:x.length>0?x.map(q=>q.email):void 0,subject:b||void 0,textBody:Te,htmlBody:Ce,...pe});if(le.outcome==="failed"){u({title:"Couldn't send message",detail:ft(le.error)??"Saving the message failed, so nothing was sent. Try again.",error:le.error});return}const ue=le.outboxMessageId;if(await de.mutateAsync({path:{outboxMessageId:ue}}).catch(q=>(u({title:"Couldn't send message",detail:ft(q)??(_?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:q}),null))===null)return;ke(ue),c(ue),n()}finally{Ie.current=!1,K(!1)}}},[R,d,h,x,b,ie,F,V,e,s,m,xe,de,ke,c,u,n]),be=l.useCallback(()=>{ke(m),m&&se.mutate({path:{outboxMessageId:m}}),n()},[ke,m,se,n]),Oe=l.useCallback(pe=>{O(pe.accountId),a?.(pe)},[a]);return r.jsx(jx,{banner:Pe&&ze?r.jsx(C0,{accountId:Pe.accountId}):void 0,header:r.jsx(P0,{selectedAccountId:R,onAccountChange:Oe,toAddresses:d,setToAddresses:f,ccAddresses:h,setCcAddresses:v,bccAddresses:x,setBccAddresses:p,showCc:S,setShowCc:g,showBcc:w,setShowBcc:C,subject:b,setSubject:y}),quoted:$||me?r.jsx(Gx,{text:$,html:me,senderName:ge}):void 0,actionBar:r.jsx(wx,{onSend:Re,onDiscard:be,sending:qe,canSend:Qe,saveStatus:Ne,unavailableReason:ze?"SMTP not configured":void 0,onUnavailable:pe=>u({title:"Can't send yet",detail:pe})}),children:r.jsx(l.Suspense,{fallback:r.jsx(E0,{}),children:r.jsx(N0,{mode:F,onModeChange:N,initialHtml:j,initialText:D,onChange:Z,onSubmit:Re,autoFocus:e==="new",onConversionError:u,languages:Ze,initialLanguage:re,onLanguageChange:J},L)})})},El=({mode:e,account:t,sourceMessage:s,onClose:n})=>r.jsx("div",{className:"border-t border-line bg-canvas max-h-[min(400px,60dvh)] flex flex-col",children:r.jsx(Fo,{mode:e,account:t,sourceMessage:s,onClose:n})}),pd=({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})]}),$o=({enabled:e=!0,bindings:t,capture:s=!1})=>{const n=l.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const m=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(m&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);l.useEffect(()=>{if(e)return window.addEventListener("keydown",n,s),()=>window.removeEventListener("keydown",n,s)},[e,n,s])},_o=e=>{const{data:t,isLoading:s}=we({...$t(),staleTime:1/0}),n=l.useMemo(()=>(t?.accounts??[]).map(c=>c.accountId),[t?.accounts]),a=mt({queries:n.map(c=>({...it({path:{accountId:c}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(c=>c.isLoading);return{accountId:l.useMemo(()=>{if(e){for(let c=0;c<n.length;c++)if((a[c].data?.items??[]).some(d=>d.mailboxId===e))return n[c]}},[e,n,a]),isLoading:o}},L0=100,Ma=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),F0=(e,t=L0)=>{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},gd=async(e,t,s,n)=>{const a=F0(e),o=e.length;let i=0;const c=[];for(let u=0;u<a.length;u++){if(n())return c.push(...a.slice(u).flat()),{done:i,failedIds:c,cancelled:!0};const m=a[u],d=await Ma(t(m));if(!d.ok)return c.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:c,cancelled:!1,error:d.error};i+=m.length,s({done:i,total:o})}return{done:i,failedIds:c,cancelled:!1}},Os=async(e,t)=>{await gd(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},$0=async(e,t,s,n,a)=>{let o=0;const i=[];let c;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await Ma(e(c));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const m=u.value;if(m.ids.length>0){const d=await Ma(s(m.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=m.ids.length,n({done:o,total:t})}c=m.continuationToken}while(c);return{done:o,failedIds:i,cancelled:!1}},_0=e=>({done:e.done,total:Math.max(e.total,e.done)}),xd=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),bd=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),vd=(e,t)=>e===void 0?e:xd(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:bd(e)?{...e,items:t(e.items)}:e,Et=e=>{const t=[];for(const s of new Set(e))t.push(fr({path:{mailboxId:s}})),t.push(Za({path:{mailboxId:s}}));return t.push(eo()),t},yn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),wn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,n])=>({queryKey:s,data:n})),Sn=(e,t,s)=>{const n=a=>vd(a,s);for(const a of t)e.setQueriesData({queryKey:a},n)},Cn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},It=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},z0=3e3,B0=(e,t,s)=>{if(e.length===0)return()=>{};const n=setTimeout(()=>s(e),t);return()=>clearTimeout(n)},Mr=(e,t,s)=>{const n=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(n.get(o)??s);return[...a]},tr=(e,t,s)=>e.map(n=>t.has(n.messageId)?{...n,isRead:s}:n),U0=(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),K0=({messages:e,expandedIds:t,threadId:s,mailboxId:n,accountId:a})=>{const o=De(),{pushError:i}=nt(),c=l.useRef(new Set),u=l.useRef(new Set),{mutate:m}=Ue({...mr(),onMutate:async h=>{const v=new Set(h.body.messageIds??[]),x=h.body.isRead??!0,p=Zt({path:{threadId:s}}),b=Et(Mr(v,e,n));await Promise.all([o.cancelQueries({queryKey:p}),yn(o,b)]);const y=o.getQueriesData({queryKey:p}).filter(g=>g[1]!==void 0).map(([g,w])=>({queryKey:g,data:w})),S=wn(o,b);return o.setQueriesData({queryKey:p},g=>g&&{...g,items:tr(g.items,v,x)}),Sn(o,b,g=>tr(g,v,x)),{threadMessagesPrefix:p,listPrefixes:b,previousThreadMessages:y,previousThreadsList:S}},onSuccess:(h,v)=>{const x=v.body.messageIds??[];for(const p of x)c.current.add(p),u.current.delete(p)},onError:(h,v,x)=>{const p=v.body.messageIds??[];for(const y of p)u.current.delete(y);if(x){for(const y of x.previousThreadMessages)o.setQueryData(y.queryKey,y.data);Cn(o,x.previousThreadsList)}const b=v.body.isRead??!0;i({title:b?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(h),error:h})},onSettled:(h,v,x,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),It(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:Ft({path:{accountId:a}})}))}}),d=l.useCallback(h=>{const v=h.filter(x=>!c.current.has(x)&&!u.current.has(x));if(v.length!==0){for(const x of v)u.current.add(x);m({body:{messageIds:v,isRead:!0}})}},[m]),f=l.useMemo(()=>U0(e,t,c.current,u.current),[e,t]);l.useEffect(()=>B0(f,z0,d),[f,d]),l.useEffect(()=>{c.current.clear(),u.current.clear()},[s])},Ar=e=>{const{mailboxId:t,accountId:s,messages:n}=e,a=De(),{pushError:o}=nt(),{mutateAsync:i,isPending:c}=Ue({...mr(),onError:(m,d)=>{const f=d.body.isRead??!0;o({title:f?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(m),error:m})},onSettled:(m,d,f)=>{It(a,Et(Mr(f.body.messageIds??[],n??[],t))),s&&a.invalidateQueries({queryKey:Ft({path:{accountId:s}})})}});return{toggleReadFor:l.useCallback((m,d)=>{m.length!==0&&Os(m,f=>i({body:{messageIds:f,isRead:d}}))},[i]),isPending:c}},q0=60,H0=1.5,W0=(e,t,s)=>{const n=Math.abs(e),a=Math.abs(t);return n<s?{direction:null}:n<a*H0?{direction:null}:{direction:e<0?"left":"right"}},V0=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=q0})=>{const n=l.useRef(null),a=l.useCallback(u=>{if(u.pointerType==="mouse"){n.current=null;return}n.current={x:u.clientX,y:u.clientY}},[]),o=l.useCallback(()=>{},[]),i=l.useCallback(u=>{const m=n.current;if(n.current=null,!m)return;const{direction:d}=W0(u.clientX-m.x,u.clientY-m.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),c=l.useCallback(()=>{n.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:c}}},Q0=(e,t,s)=>t?.find(n=>n.messageId===e)?.mailboxId??s,Il=(e,t,s)=>e.map(n=>n.messageId===t?{...n,hasStars:s}:n),zo=({threadId:e,mailboxId:t,messages:s})=>{const n=De(),{pushError:a}=nt(),{mutate:o,isPending:i,variables:c}=Ue({...qm(),onMutate:async m=>{const d=m.path.messageId,f=m.body.isStarred??!1,h=Zt({path:{threadId:e}}),v=Et([Q0(d,s,t)]);await Promise.all([n.cancelQueries({queryKey:h}),yn(n,v)]);const x=n.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})),p=wn(n,v);return n.setQueriesData({queryKey:h},b=>vd(b,y=>Il(y,d,f))),Sn(n,v,b=>Il(b,d,f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:x,previousThreadsList:p}},onError:(m,d,f)=>{if(f){for(const v of f.previousThreadMessages)n.setQueryData(v.queryKey,v.data);Cn(n,f.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:ft(m),error:m})},onSettled:(m,d,f,h)=>{h&&(n.invalidateQueries({queryKey:h.threadMessagesPrefix}),It(n,h.listPrefixes))}});return{toggleStar:(m,d)=>{o({path:{messageId:m},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?c?.path.messageId:void 0}};function Or(e){return e===void 0?"uncategorized":e}const G0={inbox:"Inbox",junk:"Junk"},Bo=e=>e.destinationMailboxId!==void 0,Y0=(e,t)=>{if(Bo(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${G0[s]??"another folder"} by Remit`},X0=(e,t)=>{if(e===hi.MoveToInbox)return t.inboxMailboxId;if(e===hi.MoveToJunk)return t.junkMailboxId},J0=(e,t,s)=>{if(!e||!t)return!1;const n=Bo(e)?e.destinationMailboxId:X0(e.action,s);return n!==void 0&&n===t},Z0="Reported as spam",ew=(e,t)=>{if(e){if(Bo(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},Dr=(e,t)=>{const{data:s,isLoading:n}=we({...$t(),staleTime:1/0,enabled:!!e});return{mailboxId:l.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:n}},tw=e=>{const{mailboxId:t,isLoading:s}=Dr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},sw=e=>{const{mailboxId:t,isLoading:s}=Dr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},yd=e=>{const{mailboxId:t,isLoading:s}=Dr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},kn=e=>{const{mailboxId:t,isLoading:s}=Dr(e,"Junk");return{junkMailboxId:t,isLoading:s}},Uo=e=>{const{data:t}=we({...$t(),staleTime:1/0,enabled:!!e});return l.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Rl=(e,t)=>e.filter(s=>!t.has(s.messageId)),Ds=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=De(),{pushError:o}=nt(),{mutateAsync:i,isPending:c,isError:u}=Ue({...Hm(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],v=Et([e,d.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:h})]:[],yn(a,v)]);const x=t?a.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})):[],p=wn(a,v);return t&&a.setQueriesData({queryKey:h},b=>b&&{...b,items:Rl(b.items,f)}),Sn(a,v,b=>Rl(b,f)),n?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:x,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const x of h.previousThreadMessages)a.setQueryData(x.queryKey,x.data);Cn(a,h.previousThreadsList)}const v=f.body.messageIds?.length??0;o({title:v>1?`Couldn't move ${v} messages`:"Couldn't move this message",detail:ft(d),error:d})},onSettled:(d,f,h,v)=>{v&&(t&&a.invalidateQueries({queryKey:v.threadMessagesPrefix}),It(a,v.listPrefixes),s&&a.invalidateQueries({queryKey:Ft({path:{accountId:s}})}))}});return{moveMessages:l.useCallback((d,f)=>{d.length!==0&&Os(d,h=>i({body:{messageIds:h,destinationMailboxId:f}}))},[i]),isPending:c,isError:u}},nw="This message could not be processed. Please try again.",rw=(e,t)=>e.replace(`Message ${t}'s`,"This message's"),Tl=e=>{if(e.failureCount===0)return;const t=e.failures?.[0],s=t?.reason??nw,n=t?rw(s,t.messageId):s;throw new Qm(n,422)};function wd({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n}){const a=De(),{pushError:o}=nt(),i=Et([e]),c=t?Zt({path:{threadId:t}}):[],u=()=>{t&&a.invalidateQueries({queryKey:c}),It(a,i),s&&a.invalidateQueries({queryKey:Ft({path:{accountId:s}})})},m=()=>(p,b)=>{u(),n?.(b.body.messageIds)},d=p=>(b,y)=>{o({title:p(y.body.messageIds.length),detail:ft(b),error:b})},f=Ue({mutationFn:async p=>{const{data:b}=await Wm({...p,throwOnError:!0});return Tl(b),b},meta:{softError:!0},onSuccess:m(),onError:d(p=>p>1?`Couldn't report ${p} messages as spam`:"Couldn't report this message as spam")}),h=Ue({mutationFn:async p=>{const{data:b}=await Vm({...p,throwOnError:!0});return Tl(b),b},meta:{softError:!0},onSuccess:m(),onError:d(p=>p>1?`Couldn't undo the spam report for ${p} messages`:"Couldn't undo the spam report")}),v=l.useCallback(p=>{p.length!==0&&Os(p,b=>f.mutateAsync({body:{messageIds:b}}))},[f.mutateAsync]),x=l.useCallback(p=>{p.length!==0&&Os(p,b=>h.mutateAsync({body:{messageIds:b}}))},[h.mutateAsync]);return{reportSpam:v,notSpam:x,isReporting:f.isPending,isRestoring:h.isPending}}const aw=({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o})=>{const{inboxMailboxId:i}=yd(e),{junkMailboxId:c}=kn(e),{moveMessages:u,isPending:m}=Ds({mailboxId:n,threadId:s,accountId:e}),{notSpam:d,isRestoring:f}=wd({mailboxId:n,threadId:s,accountId:e}),{data:h}=we({...it({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),v={inboxMailboxId:i,junkMailboxId:c},x=ew(a,v),p=l.useCallback(()=>{x&&u([t],x)},[u,t,x]),b=l.useCallback(()=>{d([t])},[d,t]);if(o)return{show:!0,label:Z0,onUndo:b,isUndoing:f};if(!J0(a,n,v)||!a)return{show:!1,label:"",isUndoing:!1};const S=a.fromMailboxId?h?.items.filter(g=>g.mailboxId===a.fromMailboxId).map(g=>ba(g.fullPath))[0]:void 0;return{show:!0,label:Y0(a,S),onUndo:x?p:void 0,isUndoing:m,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function ow({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o}){const i=aw({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a,spamReport:o});return i.show?r.jsx(gx,{label:i.label,onUndo:i.onUndo,undoLabel:i.isUndoing?"Undoing…":"Undo",filtersHref:i.filtersHref}):null}const Ml=(e,t)=>e.filter(s=>!t.has(s.messageId)),iw=e=>e.filter(t=>t.isDeleted!==!0),ms=({mailboxId:e,threadId:t,accountId:s,messages:n,onAfterOptimisticRemove:a})=>{const o=De(),{pushError:i}=nt(),{mutateAsync:c,isPending:u}=Ue({...Gm(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?Zt({path:{threadId:t}}):[],v=Et(Mr(f,n??[],e));await Promise.all([o.cancelQueries({queryKey:h}),yn(o,v)]);const x=t?o.getQueriesData({queryKey:h}).filter(b=>b[1]!==void 0).map(([b,y])=>({queryKey:b,data:y})):[],p=wn(o,v);return t&&o.setQueriesData({queryKey:h},b=>b&&{...b,items:Ml(b.items,f)}),Sn(o,v,b=>Ml(b,f)),a?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:v,previousThreadMessages:x,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const x of h.previousThreadMessages)o.setQueryData(x.queryKey,x.data);Cn(o,h.previousThreadsList)}const v=f.body.messageIds?.length??0;i({title:v>1?`Couldn't delete ${v} messages`:"Couldn't delete this message",detail:ft(d),error:d})},onSettled:(d,f,h,v)=>{v&&(t&&o.invalidateQueries({queryKey:v.threadMessagesPrefix}),It(o,v.listPrefixes),s&&o.invalidateQueries({queryKey:Ft({path:{accountId:s}})}))}});return{deleteMessages:l.useCallback(d=>{d.length!==0&&Os(d,f=>c({body:{messageIds:f}}))},[c]),isPending:u}},Sd=(e,t=Date.now())=>({value:e,setAt:t}),lw=(e,t,s,n)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Sd(!0,n):delete a.trusted,{...e,flags:a}},cw=(e,t,s,n)=>{const a=o=>o.map(i=>lw(i,t,s,n));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},Ko=({messageId:e})=>{const t=De(),{pushError:s}=nt(),{mutate:n,isPending:a,error:o,reset:i}=Ue({...jc(),onMutate:async u=>{const m=u.path.addressId,f=u.body.flags?.trusted?.value===!0,h=Ja({path:{messageId:e}});await t.cancelQueries({queryKey:h});const v=t.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,p])=>({queryKey:x,data:p}));return t.setQueriesData({queryKey:h},x=>x&&cw(x,m,f)),{describePrefix:h,previous:v}},onError:(u,m,d)=>{if(d)for(const f of d.previous)t.setQueryData(f.queryKey,f.data);s(ds("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:Sd(!m)}}})},isPending:a,error:o,reset:i}};var Pr="Dialog",[Cd]=dv(Pr),[uw,xt]=Cd(Pr),kd=e=>{const{__scopeDialog:t,children:s,open:n,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,c=l.useRef(null),u=l.useRef(null),[m,d]=hv({prop:n,defaultProp:a??!1,onChange:o,caller:Pr});return r.jsx(uw,{scope:t,triggerRef:c,contentRef:u,contentId:ta(),titleId:ta(),descriptionId:ta(),open:m,onOpenChange:d,onOpenToggle:l.useCallback(()=>d(f=>!f),[d]),modal:i,children:s})};kd.displayName=Pr;var jd="DialogTrigger",dw=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(jd,s),o=gs(t,a.triggerRef);return r.jsx(_t.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":Ho(a.open),...n,ref:o,onClick:Vt(e.onClick,a.onOpenToggle)})});dw.displayName=jd;var qo="DialogPortal",[fw,Nd]=Cd(qo,{forceMount:void 0}),Ed=e=>{const{__scopeDialog:t,forceMount:s,children:n,container:a}=e,o=xt(qo,t);return r.jsx(fw,{scope:t,forceMount:s,children:l.Children.map(n,i=>r.jsx(Nr,{present:s||o.open,children:r.jsx(zu,{asChild:!0,container:a,children:i})}))})};Ed.displayName=qo;var sr="DialogOverlay",Id=l.forwardRef((e,t)=>{const s=Nd(sr,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(sr,e.__scopeDialog);return o.modal?r.jsx(Nr,{present:n||o.open,children:r.jsx(hw,{...a,ref:t})}):null});Id.displayName=sr;var mw=Pu("DialogOverlay.RemoveScroll"),hw=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(sr,s),o=Ov(),i=gs(t,o);return r.jsx(Qu,{as:mw,allowPinchZoom:!0,shards:[a.contentRef],children:r.jsx(_t.div,{"data-state":Ho(a.open),...n,ref:i,style:{pointerEvents:"auto",...n.style}})})}),Ps="DialogContent",Rd=l.forwardRef((e,t)=>{const s=Nd(Ps,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(Ps,e.__scopeDialog);return r.jsx(Nr,{present:n||o.open,children:o.modal?r.jsx(pw,{...a,ref:t}):r.jsx(gw,{...a,ref:t})})});Rd.displayName=Ps;var pw=l.forwardRef((e,t)=>{const s=xt(Ps,e.__scopeDialog),n=l.useRef(null),a=gs(t,s.contentRef,n);return l.useEffect(()=>{const o=n.current;if(o)return ty(o)},[]),r.jsx(Td,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Vt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Vt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&o.preventDefault()}),onFocusOutside:Vt(e.onFocusOutside,o=>o.preventDefault())})}),gw=l.forwardRef((e,t)=>{const s=xt(Ps,e.__scopeDialog),n=l.useRef(!1),a=l.useRef(!1);return r.jsx(Td,{...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()}})}),Td=l.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,c=xt(Ps,s);return Fv(),r.jsx(r.Fragment,{children:r.jsx($u,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:r.jsx(Lu,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":Ho(c.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})}),Md="DialogTitle",Ad=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Md,s);return r.jsx(_t.h2,{id:a.titleId,...n,ref:t})});Ad.displayName=Md;var Od="DialogDescription",xw=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Od,s);return r.jsx(_t.p,{id:a.descriptionId,...n,ref:t})});xw.displayName=Od;var Dd="DialogClose",bw=l.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Dd,s);return r.jsx(_t.button,{type:"button",...n,ref:t,onClick:Vt(e.onClick,()=>a.onOpenChange(!1))})});bw.displayName=Dd;function Ho(e){return e?"open":"closed"}function vw(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 Pd=W.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),jn=()=>{const e=W.useContext(Pd);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};vw(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
|
|
117
117
|
[data-state=closed]
|
|
118
|
-
){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function xw(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function bw(){return Wo(/^Mac/)}function vw(){return Wo(/^iPhone/)}function Al(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function yw(){return Wo(/^iPad/)||bw()&&navigator.maxTouchPoints>1}function Ld(){return vw()||yw()}function Wo(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const ww=24,Sw=typeof window<"u"?l.useLayoutEffect:l.useEffect;function Ol(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const ia=typeof document<"u"&&window.visualViewport;function Dl(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Fd(e){for(Dl(e)&&(e=e.parentElement);e&&!Dl(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Cw=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Fn=0,la;function kw(e={}){let{isDisabled:t}=e;Sw(()=>{if(!t)return Fn++,Fn===1&&Ld()&&(la=jw()),()=>{Fn--,Fn===0&&la?.()}},[t])}function jw(){let e,t=0,s=f=>{e=Fd(f.target),!(e===document.documentElement&&e===document.body)&&(t=f.changedTouches[0].pageY)},n=f=>{if(!e||e===document.documentElement||e===document.body){f.preventDefault();return}let h=f.changedTouches[0].pageY,v=e.scrollTop,x=e.scrollHeight-e.clientHeight;x!==0&&((v<=0&&h>t||v>=x&&h<t)&&f.preventDefault(),t=h)},a=f=>{let h=f.target;Aa(h)&&h!==document.activeElement&&(f.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=f=>{let h=f.target;Aa(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",ia&&(ia.height<window.innerHeight?requestAnimationFrame(()=>{Pl(h)}):ia.addEventListener("resize",()=>Pl(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},c=window.pageXOffset,u=window.pageYOffset,m=Ol(Nw(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=Ol(Xs(document,"touchstart",s,{passive:!1,capture:!0}),Xs(document,"touchmove",n,{passive:!1,capture:!0}),Xs(document,"touchend",a,{passive:!1,capture:!0}),Xs(document,"focus",o,!0),Xs(window,"scroll",i));return()=>{m(),d(),window.scrollTo(c,u)}}function Nw(e,t,s){let n=e.style[t];return e.style[t]=s,()=>{e.style[t]=n}}function Xs(e,t,s,n){return e.addEventListener(t,s,n),()=>{e.removeEventListener(t,s,n)}}function Pl(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=Fd(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+ww;o>i&&(s.scrollTop+=a-n)}e=s.parentElement}}function Aa(e){return e instanceof HTMLInputElement&&!Cw.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function Ew(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function Iw(...e){return t=>e.forEach(s=>Ew(s,t))}function $d(...e){return l.useCallback(Iw(...e),e)}const _d=new WeakMap;function Ge(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let n={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}n[a]=e.style[a],e.style[a]=o}),!s&&_d.set(e,n)}function Rw(e,t){if(!e||!(e instanceof HTMLElement))return;let s=_d.get(e);s&&(e.style[t]=s[t])}const We=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function $n(e,t){if(!e)return null;const s=window.getComputedStyle(e),n=s.transform||s.webkitTransform||s.mozTransform;let a=n.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[We(t)?13:12]):(a=n.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[We(t)?5:4]):null)}function Tw(e){return 8*(Math.log(e+1)-2)}function ca(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function Mw(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const $e={DURATION:.5,EASE:[.32,.72,0,1]},zd=.4,Aw=.25,Ow=100,Bd=8,is=16,Oa=26,ua="vaul-dragging";function Ud(e){const t=W.useRef(e);return W.useEffect(()=>{t.current=e}),W.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function Dw({defaultProp:e,onChange:t}){const s=W.useState(e),[n]=s,a=W.useRef(n),o=Ud(t);return W.useEffect(()=>{a.current!==n&&(o(n),a.current=n)},[n,a,o]),s}function Kd({prop:e,defaultProp:t,onChange:s=()=>{}}){const[n,a]=Dw({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:n,c=Ud(s),u=W.useCallback(m=>{if(o){const f=typeof m=="function"?m(e):m;f!==e&&c(f)}else a(m)},[o,e,a,c]);return[i,u]}function Pw({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:n,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:c="bottom",container:u,snapToSequentialPoint:m}){const[d,f]=Kd({prop:e,defaultProp:s?.[0],onChange:t}),[h,v]=W.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);W.useEffect(()=>{function O(){v({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]);const x=W.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=W.useMemo(()=>{var O;return(O=s?.findIndex(k=>k===d))!=null?O:null},[s,d]),b=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,y=W.useMemo(()=>{const O=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var k;return(k=s?.map(M=>{const P=typeof M=="string";let E=0;if(P&&(E=parseInt(M,10)),We(c)){const A=P?E:h?M*O.height:0;return h?c==="bottom"?O.height-A:-O.height+A:A}const L=P?E:h?M*O.width:0;return h?c==="right"?O.width-L:-O.width+L:L}))!=null?k:[]},[s,h,u]),S=W.useMemo(()=>p!==null?y?.[p]:null,[y,p]),g=W.useCallback(O=>{var k;const M=(k=y?.findIndex(P=>P===O))!=null?k:null;i(M),Ge(n.current,{transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,transform:We(c)?`translate3d(0, ${O}px, 0)`:`translate3d(${O}px, 0, 0)`}),y&&M!==y.length-1&&o!==void 0&&M!==o&&M<o?Ge(a.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,opacity:"0"}):Ge(a.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,opacity:"1"}),f(s?.[Math.max(M,0)])},[n.current,s,y,o,a,f]);W.useEffect(()=>{if(d||e){var O;const k=(O=s?.findIndex(M=>M===e||M===d))!=null?O:-1;y&&k!==-1&&typeof y[k]=="number"&&g(y[k])}},[d,e,s,y,g]);function w({draggedDistance:O,closeDrawer:k,velocity:M,dismissible:P}){if(o===void 0)return;const E=c==="bottom"||c==="right"?(S??0)-O:(S??0)+O,L=p===o-1,A=p===0,j=O>0;if(L&&Ge(a.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`}),!m&&M>2&&!j){P?k():g(y[0]);return}if(!m&&M>2&&j&&y&&s){g(y[s.length-1]);return}const I=y?.reduce((T,F)=>typeof T!="number"||typeof F!="number"?T:Math.abs(F-E)<Math.abs(T-E)?F:T),D=We(c)?window.innerHeight:window.innerWidth;if(M>zd&&Math.abs(O)<D*.4){const T=j?1:-1;if(T>0&&x&&s){g(y[s.length-1]);return}if(A&&T<0&&P&&k(),p===null)return;g(y[p+T]);return}g(I)}function C({draggedDistance:O}){if(S===null)return;const k=c==="bottom"||c==="right"?S-O:S+O;(c==="bottom"||c==="right")&&k<y[y.length-1]||(c==="top"||c==="left")&&k>y[y.length-1]||Ge(n.current,{transform:We(c)?`translate3d(0, ${k}px, 0)`:`translate3d(${k}px, 0, 0)`})}function R(O,k){if(!s||typeof p!="number"||!y||o===void 0)return null;const M=p===o-1;if(p>=o&&k)return 0;if(M&&!k)return 1;if(!b&&!M)return null;const E=M?p+1:p-1,L=M?y[E]-y[E-1]:y[E+1]-y[E],A=O/Math.abs(L);return M?1-A:A}return{isLastSnapPoint:x,activeSnapPoint:d,shouldFade:b,getPercentageDragged:R,setActiveSnapPoint:f,activeSnapPointIndex:p,onRelease:w,onDrag:C,snapPointsOffset:y}}const Lw=()=>()=>{};function Fw(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:n,noBodyStyles:a}=jn(),o=W.useRef(null),i=l.useMemo(()=>document.body.style.backgroundColor,[]);function c(){return(window.innerWidth-Oa)/window.innerWidth}W.useEffect(()=>{if(t&&s){o.current&&clearTimeout(o.current);const u=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!u)return;Mw(n&&!a?ca(document.body,{background:"black"}):Lw,ca(u,{transformOrigin:We(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${$e.DURATION}s`,transitionTimingFunction:`cubic-bezier(${$e.EASE.join(",")})`}));const m=ca(u,{borderRadius:`${Bd}px`,overflow:"hidden",...We(e)?{transform:`scale(${c()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${c()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{m(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},$e.DURATION*1e3)}}},[t,s,i])}let Js=null;function $w({isOpen:e,modal:t,nested:s,hasBeenOpened:n,preventScrollRestoration:a,noBodyStyles:o}){const[i,c]=W.useState(()=>typeof window<"u"?window.location.href:""),u=W.useRef(0),m=W.useCallback(()=>{if(Al()&&Js===null&&e&&!o){Js={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:f,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-f}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const v=h-window.innerHeight;v&&u.current>=h&&(document.body.style.top=`${-(u.current+v)}px`)}),300)}},[e]),d=W.useCallback(()=>{if(Al()&&Js!==null&&!o){const f=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Js),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){c(window.location.href);return}window.scrollTo(h,f)}),Js=null}},[i]);return W.useEffect(()=>{function f(){u.current=window.scrollY}return f(),window.addEventListener("scroll",f),()=>{window.removeEventListener("scroll",f)}},[]),W.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),W.useEffect(()=>{s||!n||(e?(!window.matchMedia("(display-mode: standalone)").matches&&m(),t||window.setTimeout(()=>{d()},500)):d())},[e,n,i,t,s,m,d]),{restorePositionSetting:d}}function _w({open:e,onOpenChange:t,children:s,onDrag:n,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:c=!0,closeThreshold:u=Aw,scrollLockTimeout:m=Ow,dismissible:d=!0,handleOnly:f=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:v,setActiveSnapPoint:x,fixed:p,modal:b=!0,onClose:y,nested:S,noBodyStyles:g=!1,direction:w="bottom",defaultOpen:C=!1,disablePreventScroll:R=!0,snapToSequentialPoint:O=!1,preventScrollRestoration:k=!1,repositionInputs:M=!0,onAnimationEnd:P,container:E,autoFocus:L=!1}){var A,j;const[I=!1,D]=Kd({defaultProp:C,prop:e,onChange:q=>{t?.(q),!q&&!S&&K(),setTimeout(()=>{P?.(q)},$e.DURATION*1e3),q&&!b&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),q||(document.body.style.pointerEvents="auto")}}),[T,F]=W.useState(!1),[N,V]=W.useState(!1),[J,re]=W.useState(!1),oe=W.useRef(null),ie=W.useRef(null),Z=W.useRef(null),ae=W.useRef(null),fe=W.useRef(null),B=W.useRef(!1),$=W.useRef(null),me=W.useRef(0),ge=W.useRef(!1),Se=W.useRef(!C),Ne=W.useRef(0),H=W.useRef(null),Ee=W.useRef(((A=H.current)==null?void 0:A.getBoundingClientRect().height)||0),xe=W.useRef(((j=H.current)==null?void 0:j.getBoundingClientRect().width)||0),ke=W.useRef(0),de=W.useCallback(q=>{o&&q===X.length-1&&(ie.current=new Date)},[]),{activeSnapPoint:se,activeSnapPointIndex:ye,setActiveSnapPoint:Pe,onRelease:ze,snapPointsOffset:X,onDrag:Ze,shouldFade:Ie,getPercentageDragged:qe}=Pw({snapPoints:o,activeSnapPointProp:v,setActiveSnapPointProp:x,drawerRef:H,fadeFromIndex:h,overlayRef:oe,onSnapPointChange:de,direction:w,container:E,snapToSequentialPoint:O});kw({isDisabled:!I||N||!b||J||!T||!M||!R});const{restorePositionSetting:K}=$w({isOpen:I,modal:b,nested:S??!1,hasBeenOpened:T,preventScrollRestoration:k,noBodyStyles:g});function Qe(){return(window.innerWidth-Oa)/window.innerWidth}function Re(q){var he,ne;!d&&!o||H.current&&!H.current.contains(q.target)||(Ee.current=((he=H.current)==null?void 0:he.getBoundingClientRect().height)||0,xe.current=((ne=H.current)==null?void 0:ne.getBoundingClientRect().width)||0,V(!0),Z.current=new Date,Ld()&&window.addEventListener("touchend",()=>B.current=!1,{once:!0}),q.target.setPointerCapture(q.pointerId),me.current=We(w)?q.pageY:q.pageX)}function be(q,he){var ne;let ee=q;const je=(ne=window.getSelection())==null?void 0:ne.toString(),Le=H.current?$n(H.current,w):null,Be=new Date;if(ee.tagName==="SELECT"||ee.hasAttribute("data-vaul-no-drag")||ee.closest("[data-vaul-no-drag]"))return!1;if(w==="right"||w==="left")return!0;if(ie.current&&Be.getTime()-ie.current.getTime()<500)return!1;if(Le!==null&&(w==="bottom"?Le>0:Le<0))return!0;if(je&&je.length>0)return!1;if(fe.current&&Be.getTime()-fe.current.getTime()<m&&Le===0||he)return fe.current=Be,!1;for(;ee;){if(ee.scrollHeight>ee.clientHeight){if(ee.scrollTop!==0)return fe.current=new Date,!1;if(ee.getAttribute("role")==="dialog")return!0}ee=ee.parentNode}return!0}function Oe(q){if(H.current&&N){const he=w==="bottom"||w==="right"?1:-1,ne=(me.current-(We(w)?q.pageY:q.pageX))*he,ee=ne>0,je=o&&!d&&!ee;if(je&&ye===0)return;const Le=Math.abs(ne),Be=document.querySelector("[data-vaul-drawer-wrapper]"),Xe=w==="bottom"||w==="top"?Ee.current:xe.current;let He=Le/Xe;const Me=qe(Le,ee);if(Me!==null&&(He=Me),je&&He>=1||!B.current&&!be(q.target,ee))return;if(H.current.classList.add(ua),B.current=!0,Ge(H.current,{transition:"none"}),Ge(oe.current,{transition:"none"}),o&&Ze({draggedDistance:ne}),ee&&!o){const Ke=Tw(ne),lt=Math.min(Ke*-1,0)*he;Ge(H.current,{transform:We(w)?`translate3d(0, ${lt}px, 0)`:`translate3d(${lt}px, 0, 0)`});return}const et=1-He;if((Ie||h&&ye===h-1)&&(n?.(q,He),Ge(oe.current,{opacity:`${et}`,transition:"none"},!0)),Be&&oe.current&&i){const Ke=Math.min(Qe()+He*(1-Qe()),1),lt=8-He*8,tt=Math.max(0,14-He*14);Ge(Be,{borderRadius:`${lt}px`,transform:We(w)?`scale(${Ke}) translate3d(0, ${tt}px, 0)`:`scale(${Ke}) translate3d(${tt}px, 0, 0)`,transition:"none"},!0)}if(!o){const Ke=Le*he;Ge(H.current,{transform:We(w)?`translate3d(0, ${Ke}px, 0)`:`translate3d(${Ke}px, 0, 0)`})}}}W.useEffect(()=>{window.requestAnimationFrame(()=>{Se.current=!0})},[]),W.useEffect(()=>{var q;function he(){if(!H.current||!M)return;const ne=document.activeElement;if(Aa(ne)||ge.current){var ee;const je=((ee=window.visualViewport)==null?void 0:ee.height)||0,Le=window.innerHeight;let Be=Le-je;const Xe=H.current.getBoundingClientRect().height||0,He=Xe>Le*.8;ke.current||(ke.current=Xe);const Me=H.current.getBoundingClientRect().top;if(Math.abs(Ne.current-Be)>60&&(ge.current=!ge.current),o&&o.length>0&&X&&ye){const et=X[ye]||0;Be+=et}if(Ne.current=Be,Xe>je||ge.current){const et=H.current.getBoundingClientRect().height;let Ke=et;et>je&&(Ke=je-(He?Me:Oa)),p?H.current.style.height=`${et-Math.max(Be,0)}px`:H.current.style.height=`${Math.max(Ke,je-Me)}px`}else xw()||(H.current.style.height=`${ke.current}px`);o&&o.length>0&&!ge.current?H.current.style.bottom="0px":H.current.style.bottom=`${Math.max(Be,0)}px`}}return(q=window.visualViewport)==null||q.addEventListener("resize",he),()=>{var ne;return(ne=window.visualViewport)==null?void 0:ne.removeEventListener("resize",he)}},[ye,o,X]);function pe(q){Te(),y?.(),q||D(!1),setTimeout(()=>{o&&Pe(o[0])},$e.DURATION*1e3)}function Ce(){if(!H.current)return;const q=document.querySelector("[data-vaul-drawer-wrapper]"),he=$n(H.current,w);Ge(H.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`}),Ge(oe.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,opacity:"1"}),i&&he&&he>0&&I&&Ge(q,{borderRadius:`${Bd}px`,overflow:"hidden",...We(w)?{transform:`scale(${Qe()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${Qe()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${$e.DURATION}s`,transitionTimingFunction:`cubic-bezier(${$e.EASE.join(",")})`},!0)}function Te(){!N||!H.current||(H.current.classList.remove(ua),B.current=!1,V(!1),ae.current=new Date)}function _(q){if(!N||!H.current)return;H.current.classList.remove(ua),B.current=!1,V(!1),ae.current=new Date;const he=$n(H.current,w);if(!q||!be(q.target,!1)||!he||Number.isNaN(he)||Z.current===null)return;const ne=ae.current.getTime()-Z.current.getTime(),ee=me.current-(We(w)?q.pageY:q.pageX),je=Math.abs(ee)/ne;if(je>.05&&(re(!0),setTimeout(()=>{re(!1)},200)),o){ze({draggedDistance:ee*(w==="bottom"||w==="right"?1:-1),closeDrawer:pe,velocity:je,dismissible:d}),a?.(q,!0);return}if(w==="bottom"||w==="right"?ee>0:ee<0){Ce(),a?.(q,!0);return}if(je>zd){pe(),a?.(q,!1);return}var Le;const Be=Math.min((Le=H.current.getBoundingClientRect().height)!=null?Le:0,window.innerHeight);var Xe;const He=Math.min((Xe=H.current.getBoundingClientRect().width)!=null?Xe:0,window.innerWidth),Me=w==="left"||w==="right";if(Math.abs(he)>=(Me?He:Be)*u){pe(),a?.(q,!1);return}a?.(q,!0),Ce()}W.useEffect(()=>(I&&(Ge(document.documentElement,{scrollBehavior:"auto"}),ie.current=new Date),()=>{Rw(document.documentElement,"scrollBehavior")}),[I]);function le(q){const he=q?(window.innerWidth-is)/window.innerWidth:1,ne=q?-is:0;$.current&&window.clearTimeout($.current),Ge(H.current,{transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,transform:We(w)?`scale(${he}) translate3d(0, ${ne}px, 0)`:`scale(${he}) translate3d(${ne}px, 0, 0)`}),!q&&H.current&&($.current=setTimeout(()=>{const ee=$n(H.current,w);Ge(H.current,{transition:"none",transform:We(w)?`translate3d(0, ${ee}px, 0)`:`translate3d(${ee}px, 0, 0)`})},500))}function ue(q,he){if(he<0)return;const ne=(window.innerWidth-is)/window.innerWidth,ee=ne+he*(1-ne),je=-is+he*is;Ge(H.current,{transform:We(w)?`scale(${ee}) translate3d(0, ${je}px, 0)`:`scale(${ee}) translate3d(${je}px, 0, 0)`,transition:"none"})}function ve(q,he){const ne=We(w)?window.innerHeight:window.innerWidth,ee=he?(ne-is)/ne:1,je=he?-is:0;he&&Ge(H.current,{transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,transform:We(w)?`scale(${ee}) translate3d(0, ${je}px, 0)`:`scale(${ee}) translate3d(${je}px, 0, 0)`})}return W.useEffect(()=>{b||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[b]),W.createElement(kd,{defaultOpen:C,onOpenChange:q=>{!d&&!q||(q?F(!0):pe(!0),D(q))},open:I},W.createElement(Pd.Provider,{value:{activeSnapPoint:se,snapPoints:o,setActiveSnapPoint:Pe,drawerRef:H,overlayRef:oe,onOpenChange:t,onPress:Re,onRelease:_,onDrag:Oe,dismissible:d,shouldAnimate:Se,handleOnly:f,isOpen:I,isDragging:N,shouldFade:Ie,closeDrawer:pe,onNestedDrag:ue,onNestedOpenChange:le,onNestedRelease:ve,keyboardIsOpen:ge,modal:b,snapPointsOffset:X,activeSnapPointIndex:ye,direction:w,shouldScaleBackground:i,setBackgroundColorOnScale:c,noBodyStyles:g,container:E,autoFocus:L}},s))}const qd=W.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:n,onRelease:a,shouldFade:o,isOpen:i,modal:c,shouldAnimate:u}=jn(),m=$d(t,s),d=n&&n.length>0;if(!c)return null;const f=W.useCallback(h=>a(h),[a]);return W.createElement(Id,{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})});qd.displayName="Drawer.Overlay";const Hd=W.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...n},a){const{drawerRef:o,onPress:i,onRelease:c,onDrag:u,keyboardIsOpen:m,snapPointsOffset:d,activeSnapPointIndex:f,modal:h,isOpen:v,direction:x,snapPoints:p,container:b,handleOnly:y,shouldAnimate:S,autoFocus:g}=jn(),[w,C]=W.useState(!1),R=$d(a,o),O=W.useRef(null),k=W.useRef(null),M=W.useRef(!1),P=p&&p.length>0;Fw();const E=(A,j,I=0)=>{if(M.current)return!0;const D=Math.abs(A.y),T=Math.abs(A.x),F=T>D,N=["bottom","right"].includes(j)?1:-1;if(j==="left"||j==="right"){if(!(A.x*N<0)&&T>=0&&T<=I)return F}else if(!(A.y*N<0)&&D>=0&&D<=I)return!F;return M.current=!0,!0};W.useEffect(()=>{P&&window.requestAnimationFrame(()=>{C(!0)})},[]);function L(A){O.current=null,M.current=!1,c(A)}return W.createElement(Rd,{"data-vaul-drawer-direction":x,"data-vaul-drawer":"","data-vaul-delayed-snap-points":w?"true":"false","data-vaul-snap-points":v&&P?"true":"false","data-vaul-custom-container":b?"true":"false","data-vaul-animate":S?.current?"true":"false",...n,ref:R,style:d&&d.length>0?{"--snap-point-height":`${d[f??0]}px`,...t}:t,onPointerDown:A=>{y||(n.onPointerDown==null||n.onPointerDown.call(n,A),O.current={x:A.pageX,y:A.pageY},i(A))},onOpenAutoFocus:A=>{s?.(A),g||A.preventDefault()},onPointerDownOutside:A=>{if(e?.(A),!h||A.defaultPrevented){A.preventDefault();return}m.current&&(m.current=!1)},onFocusOutside:A=>{if(!h){A.preventDefault();return}},onPointerMove:A=>{if(k.current=A,y||(n.onPointerMove==null||n.onPointerMove.call(n,A),!O.current))return;const j=A.pageY-O.current.y,I=A.pageX-O.current.x,D=A.pointerType==="touch"?10:2;E({x:I,y:j},x,D)?u(A):(Math.abs(I)>D||Math.abs(j)>D)&&(O.current=null)},onPointerUp:A=>{n.onPointerUp==null||n.onPointerUp.call(n,A),O.current=null,M.current=!1,c(A)},onPointerOut:A=>{n.onPointerOut==null||n.onPointerOut.call(n,A),L(k.current)},onContextMenu:A=>{n.onContextMenu==null||n.onContextMenu.call(n,A),k.current&&L(k.current)}})});Hd.displayName="Drawer.Content";const zw=250,Bw=120,Wd=W.forwardRef(function({preventCycle:e=!1,children:t,...s},n){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:c,setActiveSnapPoint:u,dismissible:m,handleOnly:d,isOpen:f,onPress:h,onDrag:v}=jn(),x=W.useRef(null),p=W.useRef(!1);function b(){if(p.current){g();return}window.setTimeout(()=>{y()},Bw)}function y(){if(o||e||p.current){g();return}if(g(),!i||i.length===0){m||a();return}if(c===i[i.length-1]&&m){a();return}const C=i.findIndex(O=>O===c);if(C===-1)return;const R=i[C+1];u(R)}function S(){x.current=window.setTimeout(()=>{p.current=!0},zw)}function g(){x.current&&window.clearTimeout(x.current),p.current=!1}return W.createElement("div",{onClick:b,onPointerCancel:g,onPointerDown:w=>{d&&h(w),S()},onPointerMove:w=>{d&&v(w)},ref:n,"data-vaul-drawer-visible":f?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},W.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});Wd.displayName="Drawer.Handle";function Uw(e){const t=jn(),{container:s=t.container,...n}=e;return W.createElement(Ed,{container:s,...n})}const dt={Root:_w,Content:Hd,Overlay:qd,Portal:Uw,Handle:Wd,Title:Ad},Vd="inline-flex items-center justify-center transition-colors",Kw=Ve(Vd,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),qw=Ve(Vd,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),Vo=({accountId:e,currentMailboxId:t,onMove:s,disabled:n=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[c,u]=l.useState(!1),[m,d]=l.useState(),f=es(),h=l.useRef(null),v=i??"Move to folder",x=l.useId(),{t:p}=Xa("mail",{useSuspense:!1}),b=io(),{data:y,isLoading:S,isError:g,error:w,refetch:C}=we({...it({path:{accountId:e}}),staleTime:1/0,enabled:c}),R=Uo(e),{createFolderIn:O}=Pc(e),k=l.useMemo(()=>lo({mailboxes:y?.items??[],folderAppointments:R,currentMailboxId:t,translator:b}),[y?.items,R,t,b]),M=co(y?.items??[]),P=k.find(T=>T.id===m),E=l.useCallback(()=>{u(!1),d(void 0)},[]),L=l.useCallback(()=>{P&&(E(),s(P.id))},[P,E,s]);l.useEffect(()=>{if(!c||!f)return;const T=N=>{h.current&&!h.current.contains(N.target)&&E()},F=N=>{N.key==="Escape"&&E()};return document.addEventListener("mousedown",T),document.addEventListener("keydown",F),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",F)}},[c,f,E]);const A=n||!!a,j=r.jsxs("button",{type:"button",onClick:T=>{T.stopPropagation(),!A&&u(F=>!F)},"aria-label":v,"aria-haspopup":f?"tree":"dialog","aria-expanded":c,"aria-controls":c?x:void 0,title:a,className:o==="icon-only"?Kw:qw,children:[r.jsx(za,{className:o==="icon-only"?"size-5":"size-4"}),o==="compact"&&r.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),I=S?r.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):g?r.jsx("div",{className:"p-3",children:r.jsx(ts,{variant:"inline",title:"Couldn't load folders",error:w,onRetry:()=>C()})}):r.jsx(gc,{folders:k,selectedId:m,delimiter:M,onSelect:d,onCreateFolder:O,onCancel:E,labels:{filterPlaceholder:p("move_picker_filter_placeholder",{defaultValue:"Filter folders…"}),filterAriaLabel:p("move_picker_filter_label",{defaultValue:"Filter folders"})}}),D=P&&r.jsx("div",{className:"shrink-0 border-t border-line p-2",children:r.jsx(ce,{variant:"primary",onClick:L,className:"h-11 w-full font-semibold",children:`Move to ${P.label}`})});return f?r.jsxs("div",{ref:h,className:"relative inline-block",children:[j,c&&r.jsxs("div",{id:x,className:Ve("absolute right-0 mt-1 z-50 w-72 max-h-96 flex flex-col","bg-surface border border-line rounded-md shadow-lg"),children:[I,D]})]}):r.jsxs(r.Fragment,{children:[j,r.jsx(dt.Root,{open:c,onOpenChange:T=>T?u(!0):E(),children:r.jsxs(dt.Portal,{children:[r.jsx(dt.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(dt.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-lg bg-canvas pb-[env(safe-area-inset-bottom,0px)]",style:{maxHeight:"85dvh"},id:x,children:[r.jsx(dt.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),r.jsx(dt.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),r.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:I}),D]})]})})]})},Hw=({messageId:e,threadId:t,mailboxId:s,isRead:n,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:c=!1,onToggleRaw:u})=>{const m=De(),d=Ye(),{pushError:f}=nt(),{selectedMessageId:h}=As({strict:!1}),{mutate:v,isPending:x}=Ue({...mr(),onMutate:async I=>{const D=I.body.isRead??!0,T=new Set(I.body.messageIds??[]),F=Zt({path:{threadId:t}}),N=Et([s]);await Promise.all([m.cancelQueries({queryKey:F}),yn(m,N)]);const V=m.getQueriesData({queryKey:F}).filter(re=>re[1]!==void 0).map(([re,oe])=>({queryKey:re,data:oe})),J=wn(m,N);return m.setQueriesData({queryKey:F},re=>re&&{...re,items:tr(re.items,T,D)}),Sn(m,N,re=>tr(re,T,D)),{threadMessagesPrefix:F,listPrefixes:N,previousThreadMessages:V,previousThreadsList:J}},onError:(I,D,T)=>{if(T){for(const N of T.previousThreadMessages)m.setQueryData(N.queryKey,N.data);Cn(m,T.previousThreadsList)}const F=D.body.isRead??!0;f({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(I),error:I})},onSettled:(I,D,T,F)=>{F&&(m.invalidateQueries({queryKey:F.threadMessagesPrefix}),It(m,F.listPrefixes))}}),p=l.useCallback(I=>{h&&I.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:D=>({...D,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:b,isPending:y}=ms({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:S,isPending:g}=Ds({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:w,isPending:C,error:R,reset:O}=Ko({messageId:e}),k=()=>{v({body:{messageIds:[e],isRead:!1}})},M=()=>{b([e])},P=()=>{o&&w(o,i)},E=x||y||g||C,L=E||!o,A=l.useCallback(I=>{S([e],I)},[S,e]),j=o?void 0:"Sender has no parseable address";return r.jsxs("div",{className:"flex flex-col items-end gap-1",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[a&&r.jsx(Vo,{accountId:a,currentMailboxId:s,onMove:A,disabled:E,label:"Move this message"}),r.jsxs(Ju,{trigger:r.jsx(Gc,{className:"size-4"}),children:[r.jsxs(nn,{onClick:P,disabled:L,children:[i?r.jsx(br,{className:"size-4 text-positive"}):r.jsx(hn,{className:"size-4 opacity-0"}),r.jsx("span",{title:j,children:"Trusted sender"})]}),n&&r.jsxs(nn,{onClick:k,disabled:E,children:[r.jsx(vr,{className:"size-4"}),"Mark as unread"]}),u&&r.jsxs(nn,{onClick:u,children:[r.jsx(Qc,{className:"size-4"}),c?"Show formatted":"Show raw email"]}),r.jsx(Zu,{}),r.jsxs(nn,{onClick:M,disabled:E,destructive:!0,children:[r.jsx(Lt,{className:"size-4"}),"Delete"]})]})]}),R&&r.jsx("div",{className:"w-64",children:r.jsx(ts,{variant:"inline",title:"Couldn't update trust",error:R,onRetry:()=>{O(),P()}})})]})},Ww=e=>e==="link-expired"||e==="not-ready";class Da extends Error{reason;status;constructor(t,s,n){super(s),this.name="AttachmentFetchError",this.reason=t,this.status=n}}const Vw="x-remit-403-reason",Qw="expired",Gw=(e,t)=>{if(t?.trim()===Qw)return"link-expired";const s=md(e,t);return s==="auth"?"auth":s==="body-missing"?"missing":"generic"},Yw=300*1e3,Ll=async(e,t)=>{const s={},n=await t();n&&(s.Authorization=`Bearer ${n}`);const a=await Cc(e,{headers:s,signal:AbortSignal.timeout(Yw)});if(a.status===202)throw new Da("not-ready","Attachment is still being fetched from the mail server",202);if(!a.ok)throw new Da(Gw(a.status,a.headers.get(Vw)),`Failed to download attachment (${a.status} ${a.statusText})`,a.status);return a.blob()},Xw=(e,t,s)=>{switch(e){case"auth":return{title:"Your session expired",detail:`Sign in again, then download ${t} once more. Other parts of the app may also stop responding until you do.`};case"link-expired":return{title:"This download link expired and could not be renewed",detail:`Reload the page, then download ${t} again. If that keeps failing, this is worth reporting.`};case"missing":return{title:"This attachment is missing from storage",detail:"Remit has the message but not the file. Re-sync the account from Settings, then try again."};case"not-ready":return{title:"Still fetching this attachment",detail:"Remit is downloading it from the mail server now. Try again in a few seconds."};default:return{title:"Couldn't download this attachment",detail:s}}},Fl=e=>e instanceof Da?e.reason:"generic",Jw=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while downloading this attachment.",Zw=(e,t,s)=>{if(e!=="auth")return to(so({title:`Bug: attachment download failed (${e})`,errorMessage:`Downloading "${t}" failed: ${s}`}))},eS=(e,t)=>{const s=URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,n.rel="noopener",document.body.append(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(s),0)},tS=e=>{const t=e.toUpperCase();return t==="OCTET-STREAM"?"FILE":t},sS=e=>{const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return t.length>0?`attachment.${t}`:"attachment"},$l=e=>e.filter(t=>!t.isMultipart&&t.disposition===Kh.Attachment&&t.contentUrl.length>0).map(t=>({bodyPartId:t.bodyPartId,filename:cx(t.dispositionFilename??"",sS(t.mediaSubtype)),typeLabel:tS(t.mediaSubtype),sizeOctets:t.sizeOctets,contentUrl:t.contentUrl})),_l={status:"idle"},nS=({messageId:e,bodyParts:t,hasAttachment:s=!1,className:n})=>{const{getToken:a}=lr(),o=De(),[i,c]=l.useState({}),u=l.useMemo(()=>$l(t??[]),[t]),m=Ja({path:{messageId:e}}),d=x=>Ll(x.contentUrl,a).catch(p=>{if(!Ww(Fl(p)))throw p;return o.refetchQueries({queryKey:m}).then(()=>{const b=o.getQueryData(m),y=b?$l(b.bodyParts).find(S=>S.bodyPartId===x.bodyPartId):void 0;return Ll(y?.contentUrl??x.contentUrl,a)})}),f=(x,p)=>c(b=>({...b,[x]:p})),h=x=>{const p=u.find(b=>b.bodyPartId===x);if(!p)throw new Error(`No attachment part ${x} on message ${e}`);f(x,{status:"downloading"}),d(p).then(b=>{eS(b,p.filename),f(x,_l)}).catch(b=>{const y=Fl(b),S=Jw(b),{title:g,detail:w}=Xw(y,p.filename,S);f(x,{status:"failed",title:g,detail:w,reportUrl:Zw(y,p.filename,S)})})},v=s&&t!==void 0&&u.length===0;return r.jsx(fx,{className:n,attachments:u.map(x=>({attachmentId:x.bodyPartId,filename:x.filename,typeLabel:x.typeLabel,sizeOctets:x.sizeOctets,download:i[x.bodyPartId]??_l})),onDownload:h,hasUnlistedAttachment:v})},rS=()=>{const[e,t]=l.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return l.useEffect(()=>{const s=document.documentElement,n=new MutationObserver(()=>{t(s.classList.contains("dark"))});return n.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e},aS=({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"})]})]}),oS=(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}}},iS=e=>e instanceof cs?e.reason:"generic",lS=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",cS=({error:e,onRetry:t})=>{const s=iS(e),n=lS(e),{title:a,detail:o}=oS(s,n),[i,c]=l.useState(!1),{Account:u}=lr();return i?null:r.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[r.jsx(Pt,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"font-medium text-danger",children:a}),r.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&r.jsx(u,{children:({signOut:m})=>r.jsx("button",{type:"button",onClick:()=>m(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&r.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),r.jsx("button",{type:"button",onClick:()=>c(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:r.jsx(Nt,{className:"size-4","aria-hidden":"true"})})]})]})},uS=()=>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"})]}),zl=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Qd=({bodyParts:e,html:t,text:s,isTrusted:n=!1,messageId:a,fromAddressId:o,category:i,className:c})=>{const[u,m]=l.useState(!1),d=n||u,f=rS(),{toggleTrusted:h,isPending:v}=Ko({messageId:a??""}),x=!!e&&e.length>0,{picked:p,data:b,isLoading:y,isError:S,error:g,refetch:w}=hd({messageId:a,bodyParts:e,enabled:x}),C=l.useMemo(()=>Cg(e??[]),[e]),R=x&&b?.kind==="html"?b.body:t,O=x&&b?.kind==="text"?b.body:s;if(x){if(y)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(uS,{})});if(S)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(cS,{error:g,onRetry:()=>w()})});if(!p)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(zl,{})})}else if(!t&&!s)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(zl,{})});const k=!!(o&&a),M=()=>{!o||v||(m(!0),h(o,!1))};return r.jsx(xu,{className:c,html:R,text:O,isDark:f,category:i,allowImages:d,resolveCid:C,renderBlockedNotice:P=>r.jsx(aS,{blockedImageCount:P,canAlwaysTrust:k,isTrustPending:v,onLoadOnce:()=>m(!0),onAlwaysTrust:M})})},dS=({messageId:e,threadId:t,mailboxId:s,accountId:n,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:c,isTrusted:u,showRaw:m,onToggleRaw:d,onReply:f,onReplyAll:h,onForward:v})=>{const x=De(),{deleteMessages:p}=ms({mailboxId:s,threadId:t}),{moveMessages:b}=Ds({mailboxId:s,threadId:t,accountId:n}),{toggleTrusted:y}=Ko({messageId:e}),{mutate:S}=Ue({...mr(),onSettled:()=>{x.invalidateQueries({queryKey:Zt({path:{threadId:t}})}),It(x,Et([s]))}}),g=l.useCallback(O=>{b([e],O)},[b,e]),w=l.useCallback(()=>{p([e])},[p,e]),C=l.useCallback(()=>{S({body:{messageIds:[e],isRead:!a}})},[S,e,a]),R=[];return c&&R.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?r.jsx(br,{className:"size-4 text-positive"}):r.jsx(hn,{className:"size-4"}),onSelect:()=>y(c,u)}),d&&R.push({key:"raw",label:m?"Show formatted":"Show raw email",icon:r.jsx(Qc,{className:"size-4"}),onSelect:d}),r.jsx(gu,{hasThread:!0,onReply:f,onReplyAll:h,onForward:v,isStarred:o,onToggleStar:i,onDelete:w,isRead:a,onToggleRead:C,overflowItems:R,moveSlot:n?r.jsx(Vo,{accountId:n,currentMailboxId:s,onMove:g,label:"Move this message"}):void 0})},fS=()=>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"})]}),mS=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:n,isError:a,error:o,refetch:i}=we({...Ym({path:{messageId:e}}),enabled:t});if(n)return r.jsx("div",{className:"message-body",children:r.jsx(fS,{})});if(a)return r.jsx("div",{className:"message-body",children:r.jsx(ts,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const c=s?.raw??"";return c===""?r.jsx("div",{className:"message-body",children:r.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):r.jsx("div",{className:"message-body",children:r.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:c})})},hS=()=>r.jsx(br,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),Gd=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),Yd=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:Ve("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":Ve("text-fg-subtle hover:text-warning",n&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:r.jsx(Xt,{className:Ve("size-3.5",e&&"fill-current")})}),pS=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:n,isStarPending:a})=>{const o=Oc(e.sentDate,"datetime"),i=Gd(e,o);return r.jsx(bu,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:r.jsxs(r.Fragment,{children:[e.hasAttachment&&r.jsx(yr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"}),r.jsx(Yd,{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})]})})},gS=({threadMessage:e,messageData:t,isLoading:s,isError:n,error:a,onRetry:o,isFocused:i,onToggle:c,onToggleStar:u,isStarPending:m,accountId:d,showRaw:f,onToggleRaw:h,mobile:v,onReply:x,onReplyAll:p,onForward:b})=>{const y=Oc(e.sentDate,"long"),S=!e.isRead,g=t?.envelope.from[0]?.flags?.trusted?.value===!0,w=t?.envelope.from[0]?.addressId,C=Gd(e,y),R=e.autoMoved||e.spamReport?r.jsx(nw,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,spamReport:e.spamReport}):null;return r.jsx(vu,{message:C,isFocused:v?!1:i,onHeaderClick:c,senderBadge:g?r.jsx(hS,{}):void 0,trailing:r.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:y}),to:t?r.jsx($p,{label:"To",addresses:t.envelope.to}):null,indicators:R||!v?r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[R,!v&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"flex items-center justify-end gap-1",children:r.jsx(Yd,{isStarred:e.hasStars,onToggleStar:u,isStarPending:m})}),S&&r.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:v?void 0:r.jsx(Hw,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:w,isTrusted:g,showRaw:f,onToggleRaw:h}),actionBar:v?r.jsx(dS,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:w,isTrusted:g,showRaw:f,onToggleRaw:h,onReply:x,onReplyAll:p,onForward:b}):void 0,body:s?r.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):n&&Xm(a)?r.jsx("div",{className:"mt-3",children:r.jsx(pd,{message:"This message has been deleted"})}):n?r.jsx("div",{className:"mt-3",children:r.jsx(ts,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):f?r.jsx("div",{className:"mt-3",children:r.jsx(mS,{messageId:e.messageId})}):r.jsxs("div",{className:"mt-3",children:[r.jsx(Qd,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:g,category:Or(e.category)}),r.jsx(nS,{messageId:e.messageId,bodyParts:t?.bodyParts,hasAttachment:e.hasAttachment,className:"mt-4 px-2 lg:px-0"})]})})},xS=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,mobile:c,onReply:u,onReplyAll:m,onForward:d})=>{const[f,h]=l.useState(!1),{data:v,isLoading:x,isError:p,error:b,refetch:y}=we({...hr({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?r.jsx(gS,{threadMessage:e,messageData:v,isLoading:x,isError:p,error:b,onRetry:()=>y(),isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,showRaw:f,onToggleRaw:()=>h(S=>!S),mobile:c,onReply:u,onReplyAll:m,onForward:d}):r.jsx(pS,{threadMessage:e,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o})},bS=()=>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 Bl({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($s,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",r.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&r.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const Bs=({threadId:e,mailboxId:t,subject:s,selectedMessageId:n,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:c,onComposeClose:u,onSwipeNext:m,onSwipePrevious:d,mobileIntelligenceOpen:f})=>{const h=es(),{handlers:v}=q0({onSwipeLeft:m,onSwipeRight:d}),{accountId:x}=_o(t),{data:p,isLoading:b,isError:y,error:S,refetch:g}=we({...Jm({path:{threadId:e}})}),w=l.useMemo(()=>p?.items??[],[p?.items]),C=w[w.length-1],R=l.useRef(new Map),[O,k]=l.useState(new Set),[M,P]=l.useState(null),[E,L]=l.useState(0);l.useEffect(()=>{if(w.length>0&&e!==M){P(e);const de=new Set([w[w.length-1].threadMessageId]);if(n){const se=w.find(ye=>ye.messageId===n);se&&de.add(se.threadMessageId)}k(de),L(w.length-1)}},[e,w,M,n]);const A=l.useCallback(de=>{k(se=>{const ye=new Set(se);return ye.has(de)?ye.delete(de):ye.add(de),ye})},[]),j=l.useCallback(de=>{const se=w[de];if(!se)return;R.current.get(se.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[w]),I=l.useCallback(()=>{if(w.length===0)return;const de=Math.min(E+1,w.length-1);L(de),j(de)},[w.length,E,j]),D=l.useCallback(()=>{if(w.length===0)return;const de=Math.max(E-1,0);L(de),j(de)},[w.length,E,j]),T=l.useCallback(()=>{const de=w[E];de&&A(de.threadMessageId)},[w,E,A]),{data:F}=we({...$t(),staleTime:1/0}),N=F?.accounts?.[0];z0({messages:w,expandedIds:O,threadId:e,mailboxId:t,accountId:N?.accountId});const{toggleStar:V,isPending:J,pendingMessageId:re}=zo({threadId:e,mailboxId:t,messages:w}),[oe,ie]=l.useState(null),[Z,ae]=l.useState(0),fe=l.useCallback(de=>{ie(de),ae(se=>se+1)},[]);l.useEffect(()=>{c&&c!=="new"&&(fe(c),u?.())},[c,u,fe]);const{data:B}=we({...hr({path:{messageId:C?.messageId??""}}),enabled:!!C&&oe!==null}),$=l.useCallback(()=>fe("reply"),[fe]),me=l.useCallback(()=>fe("reply_all"),[fe]),ge=l.useCallback(()=>fe("forward"),[fe]),Se=l.useCallback(()=>{ie(null),u?.()},[u]),Ne=l.useRef(null);if(l.useEffect(()=>{if(oe===null||Z===0)return;const de=Ne.current;if(!de)return;const se=()=>de.scrollIntoView({behavior:"smooth",block:"end"});if(se(),typeof ResizeObserver>"u")return;const ye=new ResizeObserver(se);return ye.observe(de),()=>ye.disconnect()},[Z,oe]),$o({enabled:!b&&w.length>0&&oe===null,bindings:[{key:"j",handler:I,preventDefault:!0},{key:"ArrowDown",handler:I,preventDefault:!0},{key:"k",handler:D,preventDefault:!0},{key:"ArrowUp",handler:D,preventDefault:!0},{key:"Enter",handler:T,preventDefault:!0},{key:"o",handler:T,preventDefault:!0},{key:"r",handler:$,preventDefault:!0},{key:"R",handler:me,noModifiers:!1,preventDefault:!0},{key:"f",handler:ge,preventDefault:!0}]}),b)return r.jsx(bS,{});if(y)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(ts,{title:"Couldn't load this conversation",error:S,onRetry:()=>g()})});if(w.length===0)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(pd,{message:"No messages in this thread"})});const H=s||w[0]?.subject||"(No subject)",Ee=w.length,xe=de=>r.jsx("div",{children:w.map((se,ye)=>r.jsx("div",{ref:Pe=>{Pe&&R.current.set(se.threadMessageId,Pe)},children:r.jsx(xS,{threadMessage:se,isExpanded:O.has(se.threadMessageId),isFocused:ye===E,onToggle:()=>A(se.threadMessageId),onToggleStar:()=>V(se.messageId,se.hasStars),isStarPending:J&&re===se.messageId,accountId:x,mobile:de,onReply:de?$:void 0,onReplyAll:de?me:void 0,onForward:de?ge:void 0})},se.threadMessageId))}),ke=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:H}),r.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Ee," ",Ee===1?"message":"messages"]})]});return h?r.jsxs("article",{className:"h-full flex flex-col",children:[ke,a?.dkimMismatch&&r.jsx(Bl,{authenticity:a,onOpenIntelligence:o}),r.jsx("div",{className:"flex-1 overflow-auto",children:xe(!1)}),oe!==null&&r.jsx(El,{mode:oe,account:N,sourceMessage:B,onClose:Se})]}):r.jsxs(Qg,{thread:{subject:H,messages:[]},onBack:i??(()=>{}),intelligenceOpen:f,onToggleIntelligence:o,touchHandlers:v,children:[a?.dkimMismatch&&r.jsx(Bl,{authenticity:a,onOpenIntelligence:o}),xe(!0),oe!==null&&r.jsx("div",{ref:Ne,children:r.jsx(El,{mode:oe,account:N,sourceMessage:B,onClose:Se})})]})},vS=768,Xd=e=>e!=="desktop",Nn=()=>{const e=fi(`(min-width: ${vS}px)`);return fi(Mc)?"desktop":e?"tablet":"phone"};function xs(){const{mailboxNameIndex:e,accountNameIndex:t}=Fe();return{...Ot({select:n=>cd(n.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Qo=e=>e.trim().toLocaleLowerCase(),Jd={personal:"Personal",uncategorized:"Unclassified",transactional:"Transactional",newsletter:"Newsletter",marketing:"Marketing",social:"Social",automated:"Automated"},yS=Object.values(ot).map(e=>({value:e,label:Jd[e]})),wS={unclassified:"uncategorized"},Pa=[{name:"from",label:"Sender",values:"contact"},{name:"subject",label:"Subject",values:"text"},{name:"category",label:"Category",values:"fixed",options:yS},{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"}],SS=new Map(Pa.map(e=>[e.name,e])),Zd=e=>SS.get(e.toLowerCase()),CS=/^\d{4}-\d{2}-\d{2}$/;function kS(e,t,s){if(!CS.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 jS(e){const t=e.toLowerCase(),s=wS[t];return s||Object.values(ot).find(a=>a===t)}function NS(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 ES(e,t){const s=Sr(e);if(!s||s.value.length===0)return;const{name:n,value:a}=s;switch(n){case"from":return{type:"from",raw:e,value:a};case"subject":return{type:"subject",raw:e,value:a};case"category":{const o=jS(a);return o?{type:"category",raw:e,value:a,category:o}:void 0}case"is":return NS(e,a);case"has":return a.toLowerCase()==="attachment"?{type:"hasAttachment",raw:e}:void 0;case"before":case"after":return kS(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 Us(e,t={}){const s=[],n=[];for(const a of wr(e)){const o=ES(a.raw,t);o?s.push(o):n.push(a.raw)}return{freeText:n.join(" "),tokens:s}}function IS(e,t){return wr(e).filter(s=>s.raw!==t.raw).map(s=>s.raw).join(" ")}function ef(e){switch(e.type){case"from":return`From: ${e.value}`;case"subject":return`Subject: ${e.value}`;case"category":return`Category: ${Jd[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 RS=20,TS=new Set(Object.values(ot)),MS=e=>e!==void 0&&TS.has(e)?e:void 0,AS=e=>{if(e.some(t=>t.type==="isUnread"))return!1;if(e.some(t=>t.type==="isRead"))return!0};function tf({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Fe(),n=xs(),a=Ot({select:w=>w.matches}),o=Qo(s),{freeText:i,tokens:c}=Us(o,n),u=i.length>0,m=c.find(w=>w.type==="category"),d=MS(t)??m?.category,f=c.some(w=>w.type==="hasAttachment")?!0:void 0,h=c.some(w=>w.type==="isStarred")?!0:void 0,v=AS(c),x=c.find(w=>w.type==="after"),p=c.find(w=>w.type==="before"),b=c.find(w=>w.type==="in"),y=a0({matches:a,callerMailboxId:e,inTokenMailboxId:b?.mailboxId}),{data:S,isLoading:g}=we({...Nc({query:{query:i,mailboxId:y,limit:RS,...d!==void 0?{category:d}:{},...f!==void 0?{hasAttachment:f}:{},...h!==void 0?{hasStars:h}:{},...v!==void 0?{isRead:v}:{},...x?{sentDateFrom:x.epochSeconds}:{},...p?{sentDateTo:p.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:S?.items??[],isLoading:u&&g}}const OS=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),DS=e=>[...e].sort(OS);function nr(e){const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId,mailboxId:e.mailboxId,threadId:e.threadId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:gt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Or(e.category),suspicious:t}}function Ul(e){return e.filter(t=>t.muted!==!0)}function PS(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 Kl=[{id:"personal",label:"Personal",category:ot.personal},{id:"transactional",label:"Transactional",category:ot.transactional},{id:"newsletter",label:"Newsletter",category:ot.newsletter},{id:"marketing",label:"Marketing",category:ot.marketing},{id:"social",label:"Social",category:ot.social},{id:"automated",label:"Automated",category:ot.automated},{id:"uncategorized",label:"Unclassified",category:ot.uncategorized}];function LS(e){const t=new Map(Kl.map(n=>[n.category,[]]));for(const n of e){const a=n.category??ot.uncategorized;(t.get(a)??t.get(ot.uncategorized))?.push(n)}const s=[];for(const n of Kl){const a=t.get(n.category);a&&a.length>0&&s.push({id:n.id,label:n.label,threads:a})}return s}function sf(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Go(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 nf="This account has no Junk folder appointed, so there is nowhere to file these. Appoint one under Settings › Folders.",FS="These are already in Junk, so there is nowhere to file them.",Lr=(e,t)=>e!==void 0&&e!==t?e:void 0,$S=(e,t)=>{if(Lr(e,t)===void 0)return e===void 0?nf:FS},_S={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function zS(e){return _S[e]??e}function BS(e,t){const{folder:s}=no(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:gt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Wn(e,t){const{folder:s}=no(t,e.mailboxId?[e.mailboxId]:[]);return{id:e.id,sender:e.fromName,...e.fromEmail?{senderEmail:e.fromEmail}:{},subject:e.subject,snippet:e.snippet,date:e.timeLabel,unread:!e.isRead,flagged:e.starred===!0,...e.threadId?{threadId:e.threadId}:{},...e.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function US(e,t){const{mailboxId:s,folder:n}=no(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?gt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:zS(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...n?{folder:n}:{}}}function rf(e,t,s){const n=new Set(t),a=[];for(const o of[...e].sort((i,c)=>c.score-i.score))n.has(o.threadId)||(n.add(o.threadId),a.push(US(o,s)));return a}const af=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function of(e){const{spam:t}=ko([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let n;for(const[a,o]of s)(!n||o>n.count)&&(n={mailboxId:a,count:o});return n}const KS=e=>{const{mailboxId:t,messages:s}=e,n=De(),{pushError:a}=nt(),{mutateAsync:o,isPending:i}=Ue({...Zm(),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)=>{It(n,Et(Mr(d.body.messageIds??[],s??[],t)))}});return{applyLabel:l.useCallback((u,m,d)=>{u.length!==0&&Os(u,f=>o({body:{messageIds:f,labelId:m,action:d}}))},[o]),isPending:i}};function lf({accountId:e,mailboxId:t,messageIds:s}){const{labels:n}=uo(e),{applyLabel:a}=KS({mailboxId:t}),o=l.useMemo(()=>n.map(i=>({key:i.labelId,label:i.name,icon:r.jsx("span",{className:`size-2.5 rounded-full ${eh(i.color)?ci[i.color]:ci.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[n,s,a]);return o.length===0?null:r.jsx(wo,{triggerLabel:"Apply label to selected messages",triggerIcon:r.jsx(th,{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 cf=8;function Yo(e,t){const s=Math.max(0,Math.min(t,e.length)),n=wr(e).find(o=>s>=o.start&&s<=o.end);if(!n)return{start:s,end:s,raw:""};const a=Sr(n.raw);return a?{start:n.start,end:n.end,raw:n.raw,name:a.name,value:a.value}:{start:n.start,end:n.end,raw:n.raw}}function qS(e,t){const s=Yo(e,t);if(s.name===void 0)return{kind:"token",query:s.raw};const n=Zd(s.name);if(n)return{kind:"value",token:n.name,source:n.values,query:s.value??""}}const HS={mailbox:"mailboxes",account:"accounts",contact:"contacts"},WS=(e,t)=>{if(e.values==="fixed")return e.options??[];const s=HS[e.values];return s?t[s]??[]:[]},VS=(e,t)=>{if(t==="")return 1;const s=e.toLowerCase();return s.startsWith(t)?0:s.includes(t)?1:-1},La=(e,...t)=>{let s=-1;for(const n of t){if(n===void 0)continue;const a=VS(n,e);a<0||(s<0||a<s)&&(s=a)}return s},uf=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,cf).map(s=>s.suggestion)},ql=e=>({value:`${e.name}:`,label:`${e.name}:`,hint:e.label});function QS(e){const t=e.trim().toLowerCase();if(t==="")return Pa.map(ql);const s=[];for(const n of Pa)if(s.push({rank:La(t,`${n.name}:`,n.label),suggestion:ql(n)}),n.values==="fixed")for(const a of n.options??[]){const o=Cr(n.name,a.value);s.push({rank:La(t,o,a.label),suggestion:{value:o,label:a.label??o,hint:o}})}return uf(s)}function GS(e,t,s){const n=t.trim().toLowerCase(),a=WS(e,s).map(o=>({rank:La(n,o.value,o.label),suggestion:{value:Cr(e.name,o.value),label:o.label??o.value,...o.hint?{hint:o.hint}:{}}}));return uf(a)}function YS(e,t,s={}){const n=Yo(e,t);if(n.name===void 0)return QS(n.raw);const a=Zd(n.name);return a?GS(a,n.value??"",s):[]}function XS(e,t,s){const n=Yo(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 JS=e=>({value:e.normalizedEmail,...e.displayName?{label:e.displayName,hint:e.normalizedEmail}:{}});function ZS(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 eC(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 tC(e,t=[]){const s=e.flat().filter(o=>o.fullPath),n=new Map;for(const o of s){const i=ba(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=ba(o.fullPath),c=n.get(i.toLowerCase())===1,u=t.length>1?a.get(o.accountId):void 0;return{value:c?i:o.fullPath,label:o.displayNameOverride?.trim()||i,...u?{hint:u}:{}}})}function sC(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 nC=250,rC=2;function aC({query:e,cursor:t,enabled:s}){const{accounts:n}=Fe(),{mailboxesByName:a}=xs(),o=a!==void 0,i=s?qS(e,t):void 0,c=i?.source==="contact"?i.query.trim():"",u=gr(c,nC),{data:m}=we({...ur({query:{q:u,limit:cf}}),enabled:u.length>=rC}),d=mt({queries:n.map(x=>({...it({path:{accountId:x.accountId}}),staleTime:1/0}))}),f=l.useMemo(()=>o?tC(d.map(x=>x.data?.items??[]),n):[],[o,d,n]),h=l.useMemo(()=>sC(n),[n]),v=l.useMemo(()=>(m?.items??[]).map(JS),[m]);return l.useMemo(()=>{if(!s)return[];const x=YS(e,t,{mailboxes:f,accounts:h,contacts:v});return o?x:x.filter(p=>p.value!=="in:")},[s,e,t,f,h,v,o])}const oC={title:"",navSlot:null,titleMeta:null,searchSlot:null,searchField:null,searchResults:null,makeFilterSlot:null},Fa=l.createContext(oC),Fr=()=>l.useContext(Fa),iC=new Set(["hasAttachment","isUnread","isRead","isStarred","category","before","after"]),lC=e=>iC.has(e),cC=(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}lC(u.type)&&n.push({type:u.type,label:ef(u)})}const i=e.freeText.trim(),c=i.length>0;return c&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:n,targetAccountId:o,keptTerms:c,droppedSemantic:c&&t}},uC=(e,t,s)=>e.targetAccountId??t??s[0]?.accountId,df="remit.recentSearches",dC=5;function $a(){try{const e=localStorage.getItem(df);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Hl(e){const t=e.trim();if(!t)return $a();const s=[t,...$a().filter(n=>n!==t)].slice(0,dC);try{localStorage.setItem(df,JSON.stringify(s))}catch{return s}return s}function ff({title:e,unreadCount:t,children:s,selectionBar:n,paneOverlay:a,footer:o,searchFilter:i,searchResults:c,searchLoading:u,relatedResults:m,relatedLoading:d,onSelectSearchResult:f,searchResultsLabel:h="Top matches",relatedResultsLabel:v="Related",searchResultsInBody:x=!1,refreshControl:p}){const{accounts:b,resultFolderIndex:y,searchQuery:S,searchInput:g,onSearchChange:w,onSearchClear:C,searchViewKey:R}=Fe(),O=xs(),k=Ye(),M=ps(),P=Nn(),[E,L]=l.useState(!1),[A,j]=l.useState($a),I=sh(),D=l.useRef(R);l.useEffect(()=>{D.current!==R&&(D.current=R,L(!1))},[R]);const[T,F]=l.useState(0),[N,V]=l.useState(!1),[J,re]=l.useState(void 0),oe=aC({query:g,cursor:T,enabled:N&&g.trim().length>0}),ie=l.useCallback(ne=>{const ee=XS(g,T,ne);w(ee.query),re({cursor:ee.cursor})},[g,T,w]),Z=mc({count:oe.length,onAccept:ne=>{const ee=oe[ne];ee&&ie(ee)}}),{comboboxProps:ae,handleKeyDown:fe}=Z,B=l.useMemo(()=>({comboboxProps:ae,onKeyDown:fe,onCaretChange:F,onFocusChange:V,...J?{caret:J}:{}}),[ae,fe,J]),$=Z.open?r.jsx(hc,{id:Z.listId,suggestions:oe,activeIndex:Z.activeIndex,optionId:Z.optionId,onPick:ie,onHighlight:Z.setActiveIndex,label:"Search suggestions",className:"mx-row-inset mt-1 shrink-0"}):null,me=g.trim().length>0,{mailboxesByName:ge,accountsByName:Se}=O,Ne=l.useMemo(()=>Us(g,{mailboxesByName:ge,accountsByName:Se}),[g,ge,Se]),H=Ne.tokens.map(ne=>({label:ef(ne),onRemove:()=>w(IS(g,ne))})),Ee=c??[],xe=m??[],ke=me?[{id:"top",label:h,results:Ee},{id:"related",label:v,results:xe}]:[],se=!(Ee.length+xe.length>0)&&(u===!0||d===!0),{scope:ye}=fd(b),Pe=Ot({select:ne=>ne.matches}),ze=ud(Pe),X=i0(Pe,ye,ze?y.get(ze)?.role:void 0),Ze=X.kind==="global"?of([...Ee,...xe]):void 0,Ie=Ze?{kind:"global",onScopeToSpam:()=>k({to:"/mail/$mailboxId",params:{mailboxId:Ze.mailboxId},search:{q:S||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:X,qe=xe.length>0,K=l.useMemo(()=>cC(Ne,{searchHadSemanticReach:qe}),[Ne,qe]),Qe=me?K:void 0,Re=me?{onClick:()=>{L(!1),I("properties","search")},blockedReason:nv(K)?void 0:nh(K.droppedFacets.map(ne=>ne.label))}:void 0,be=Re?r.jsx(wu,{...Re}):null,Oe=af({tier:P,hasLiveInput:me,hasCommittedQuery:S.trim().length>0,bodyRendersCommittedResults:x}),pe=ne=>{j(Hl(g)),f?.(ne)},Ce=r.jsx(Su,{value:g,sections:ke,loading:se,onSelectResult:pe,tokens:H,scope:Ie}),Te=n===void 0,_=Oe?r.jsx("div",{className:"h-full overflow-y-auto",children:Ce}):null,le=_&&!Te?_:s,ue=_&&Te?_:null,ve=Xd(P),q=ve&&(E||me),he=l.useMemo(()=>({title:e,searchResults:ue,makeFilterSlot:be,searchConversion:Qe,navSlot:M&&!M.showNavPane&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(pr,{className:"size-5"}),onClick:()=>M.openNav(),"aria-label":"Menu",className:"-ml-2 shrink-0"}),titleMeta:r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[t.toLocaleString()," unread"]}),r.jsx(ui,{}),p]}),searchSlot:ve&&!q&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(ir,{className:"size-5"}),onClick:()=>L(!0),"aria-label":"Search",className:"shrink-0"}),searchField:q&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(Co,{value:g,onChange:w,onClear:C,globalFocusKey:!1,showClearButton:!1,suggest:B})}),r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(Nt,{className:"size-5"}),onClick:()=>{C(),L(!1)},"aria-label":"Close search",className:"shrink-0"}),r.jsx(ui,{})]})}),[e,t,M,ve,q,g,w,C,B,ue,be,Qe,p]);if(P==="phone"&&E){const ne=ee=>{j(Hl(g)),L(!1),f?.(ee)};return r.jsxs(Fa.Provider,{value:he,children:[r.jsx(_x,{value:g,onChange:w,onClear:C,onCancel:()=>{L(!1),C()},filter:i,recentSearches:A,onPickRecent:w,makeFilter:Re,sections:ke,loading:se,onSelectResult:ne,tokens:H,scope:Ie,suggest:B,suggestList:$}),a]})}return r.jsx(Fa.Provider,{value:he,children:r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[n?.(he),$,r.jsx("div",{className:"min-h-0 flex-1",children:le}),o,a]})})}const fC=120,mf=({keyboardFocusedMessageId:e,openMessageId:t,enabled:s,open:n,delayMs:a=fC})=>{const o=l.useRef(n);o.current=n;const i=l.useRef(void 0);l.useEffect(()=>{const c=e;if(!s){i.current=c;return}if(c===void 0||c===t)return;if(c===i.current){i.current=void 0;return}const u=setTimeout(()=>o.current(c),a);return()=>clearTimeout(u)},[s,e,t,a])};function hf(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Xo=l.createContext(null),mC=e=>{const t=l.useContext(Xo);return t?t.rowInteraction(e):null},Jo=()=>{const e=l.useContext(Xo);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},hC="[data-message-id]",pC=e=>Array.from(e.querySelectorAll(hC)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),gC=(e,t)=>e.length===t.length&&e.every((s,n)=>s===t[n]),xC=e=>{const[t,s]=l.useState([]);return l.useEffect(()=>{const n=e.current;if(!n)return;const a=()=>{const i=pC(n);s(c=>gC(c,i)?c:i)};a();const o=new MutationObserver(a);return o.observe(n,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function pf({selectedMessageId:e,onOpen:t,onDeleteMessages:s,onSelectionVerb:n,wizardOpen:a=!1,isDeleting:o=!1,commandsRef:i,onTriageContextChange:c,children:u}){const m=es(),d=l.useRef(null),f=xC(d),h=av({orderedIds:f,isDesktop:m,initialFocusedId:e}),{focusedMessageId:v,setFocusedMessageId:x,pendingDomFocusRef:p,cursorMovedByPointerRef:b,selection:y,isMultiSelectMode:S,exitSelection:g,handleRowSelect:w}=h,{selectedIds:C,selectedCount:R,isSelected:O,toggle:k,select:M,toggleAll:P}=y,E=f.length>0&&f.every($=>C.has($)),L=l.useCallback(()=>{f.length>0&&P(f)},[f,P]),{intersectWith:A}=y;l.useEffect(()=>{A(f)},[A,f]),l.useEffect(()=>{const $=p.current;$!==null&&(p.current=null,d.current?.querySelector(`[data-message-id="${$}"]`)?.focus())});const j=l.useCallback($=>{b.current=!0,x($)},[b,x]),I=l.useCallback($=>{m||M($)},[m,M]),D=l.useCallback(()=>{v&&t(v)},[v,t]),T=l.useCallback($=>t($,{replace:!0}),[t]);mf({keyboardFocusedMessageId:h.keyboardFocusedMessageId,openMessageId:e,enabled:m&&R===0,open:T});const[F,N]=l.useState(null),V=l.useCallback($=>F!==null?!0:R>0?(n($),!0):$!=="delete"||!v?!1:(N([v]),!0),[F,R,n,v]),J=l.useCallback(()=>{F!==null&&(s(F),N(null),g())},[F,s,g]),re=l.useCallback(()=>N(null),[]),oe=l.useCallback(()=>R===0?!1:(g(),!0),[R,g]),ie=f.length>0;l.useEffect(()=>{if(i){if(!ie){i.current=null;return}return i.current={focusNext:h.focusNext,focusPrevious:h.focusPrevious,focusFirst:h.focusFirst,focusLast:h.focusLast,openFocused:D,toggleSelect:h.toggleFocusedSelection,extendSelectDown:h.extendRangeDown,extendSelectUp:h.extendRangeUp,selectAll:h.selectAllLoaded,clearSelection:oe,requestVerb:V,toggleDensity:()=>{}},()=>{i.current=null}}},[i,ie,h.focusNext,h.focusPrevious,h.focusFirst,h.focusLast,h.toggleFocusedSelection,h.extendRangeDown,h.extendRangeUp,h.selectAllLoaded,D,oe,V]);const Z=l.useMemo(()=>Array.from(C),[C]),ae=F!==null;l.useEffect(()=>{c?.({focusedMessageId:v,selectedIds:Z,orderedIds:f,hasList:ie,blocksKeyboard:ae||a})},[c,v,Z,f,ie,ae,a]);const fe=hf(f,v),B=l.useMemo(()=>({selectedIds:C,selectedCount:R,exitSelection:g,startSelectionVerb:n,orderedIds:f,allSelected:E,toggleAllLoaded:L,rowInteraction:$=>({focused:$===v,isTabStop:$===fe,isDesktop:m,onFocusRow:j,selection:{isChecked:O($),onToggleCheck:k,onRowSelect:w,isMultiSelectMode:S,onLongPress:I}})}),[C,R,g,n,f,E,L,v,fe,m,j,O,k,w,S,I]);return r.jsxs(Xo.Provider,{value:B,children:[r.jsx("div",{ref:d,className:"contents",children:u}),r.jsx(fo,{isOpen:ae,title:Dc(F?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:o,onConfirm:J,onCancel:re})]})}function bC({title:e,isDeleting:t}){const s=Fr(),{selectedCount:n,exitSelection:a,startSelectionVerb:o,orderedIds:i,allSelected:c,toggleAllLoaded:u}=Jo();return r.jsx(Eo,{title:s.title||e,navSlot:s.navSlot,titleMeta:s.titleMeta,searchSlot:s.searchSlot,searchField:s.searchField,idleSlot:s.makeFilterSlot,count:n,onCancel:a,onDelete:()=>o("delete"),onMarkRead:()=>o("markRead"),isBusy:t,selectAll:i.length>0?{checked:c,indeterminate:n>0&&!c,onChange:u}:void 0})}const da=e=>{e.preventDefault(),e.stopPropagation()},gf=(e,t)=>{const s=l.useRef(!1),n=l.useCallback(i=>{if(s.current=!1,i.button!==0)return;const c=Zn(i);ki(c)&&t?.(e,c)&&(da(i),s.current=!0,i.currentTarget.focus(),c.shiftKey&&window.getSelection()?.removeAllRanges())},[t,e]),a=l.useCallback(i=>{!i.ctrlKey||!t||i.preventDefault()},[t]),o=l.useCallback(i=>{if(s.current)return s.current=!1,da(i),!0;const c=Zn(i);return!ki(c)||!t?.(e,c)?!1:(da(i),c.shiftKey&&window.getSelection()?.removeAllRanges(),!0)},[t,e]);return{onMouseDown:n,onContextMenu:a,claimClick:o}},vC=({thread:e,active:t=!1,focused:s,isTabStop:n,density:a="comfortable",isDesktop:o,badge:i,selection:c,inListbox:u=!1,linkMailboxId:m,onClick:d,onFocusRow:f})=>{const h=De(),v=e.id,x=mC(v),p=s??x?.focused??!1,b=n??x?.isTabStop??!1,y=c??x?.selection,S=f??x?.onFocusRow,g=o??x?.isDesktop??!0,w=y?.isChecked??!1,C=y?.isMultiSelectMode??!1,R=y?.onToggleCheck,O=y?.onRowSelect,k=y?.onLongPress,M=l.useCallback(N=>{N.preventDefault(),N.stopPropagation(),R?.(v)},[R,v]),P=gf(v,O),E=l.useCallback(N=>{if(!P.claimClick(N)){if(!g){if(C){N.preventDefault(),N.stopPropagation(),R?.(v);return}d?.();return}O?.(v,Zn(N)),d?.()}},[P,g,C,R,O,d,v]),L=l.useCallback(()=>{k?.(v)},[k,v]),{longPressProps:A}=mu({onLongPress:L,accessibilityDescription:w?"Deselect message":"Select message"}),j=l.useCallback(()=>{h.prefetchQuery(hr({path:{messageId:v}}))},[h,v]),I=l.useCallback(()=>{j(),S?.(v)},[j,S,v]),D=Fs({"data-list-row":"","data-message-row":!0,"data-message-id":v,...u?{role:"option","aria-selected":w}:{},tabIndex:b?0:-1,onClick:E,onMouseDown:P.onMouseDown,onContextMenu:P.onContextMenu,onMouseEnter:j,onFocus:I},g||!y?{}:A),T=Ve(a==="compact"?cu({active:t,focused:p}):Ve("group",_s({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",w&&"bg-accent-soft",!g&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?r.jsx(uu,{thread:e}):r.jsx(yo,{thread:e,badge:i,selection:y?{checked:w,alwaysVisible:C,onToggle:M}:void 0});return m===void 0?r.jsx("button",{type:"button",...D,className:T,children:F}):r.jsx(qt,{to:"/mail/$mailboxId",params:{mailboxId:m},search:N=>({...N,selectedMessageId:v}),...D,className:T,children:F})},Zo=l.memo(vC),xf=8,bf=e=>e==="From"||e==="FromDomain",yC=e=>({value:e.email,label:e.displayName??e.email,...e.displayName?{hint:e.email}:{},...e.fromSelection?{source:"selected"}:{}}),wC=e=>{const t=Ou(e.email);if(t!==null)return{value:t,...e.fromSelection?{source:"selected"}:{}}},SC=(e,t)=>e.value.toLowerCase().includes(t)||(e.label??"").toLowerCase().includes(t),CC=(e,t,s)=>{if(!bf(e))return[];const n=t.trim().toLowerCase(),a=new Set,o=[];for(const i of s){if(i.email.trim()==="")continue;const c=e==="From"?yC(i):wC(i);if(!c)continue;const u=c.value.toLowerCase();if(!(u===""||a.has(u))&&(a.add(u),u!==n&&!(n!==""&&!SC(c,n))&&(o.push(c),o.length===xf)))break}return o},kC=250,jC=2,NC=(e,t,s)=>{const n=t.trim(),a=gr(n,kC),o=e!==void 0&&bf(e),{data:i}=we({...ur({query:{q:a,limit:xf}}),enabled:o&&a.length>=jC});if(!o||e===void 0)return[];const c=[...s.map(u=>({email:u,fromSelection:!0})),...(i?.items??[]).map(u=>({email:u.normalizedEmail,...u.displayName?{displayName:u.displayName}:{}}))];return CC(e,n,c)},EC={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},vf={delete:"moved to Trash",move:"moved",markRead:"marked as read"},IC={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},RC={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},TC={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},MC=(e,t,s)=>EC[e](Gt(t),Gt(s)),Wl=(e,t)=>`${Gt(t)} ${vf[e]}. Your mail server is still catching up.`,AC=e=>`Stopped after ${Gt(e)}`,OC=(e,t,s)=>`${Gt(t)} of ${Gt(s)} ${vf[e]}. Nothing was sent for the rest, so they are untouched.`,DC=(e,t)=>t>0?`Stopped after ${Gt(t)} — some messages ${IC[e]}`:RC[e],PC=e=>TC[e],LC=e=>e==="delete"?"danger":"info",FC=100,$C=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],yf=({mailboxId:e,accountId:t,enabled:s,predicateKey:n,searchQuery:a})=>{const[o,i]=l.useState({kind:"idle"}),[c,u]=l.useState(void 0),[m,d]=l.useState(void 0),f=l.useRef(!1),h=l.useRef(!1),v=De(),{pushError:x}=nt();l.useEffect(()=>{h.current||(f.current=!0),i({kind:"idle"})},[s,n]);const p=l.useRef(a);p.current=a;const b=l.useCallback(k=>async M=>{const{data:P}=await va({path:{mailboxId:e},query:{...k,continuationToken:M,limit:FC},throwOnError:!0});return{ids:(P.items??[]).map(E=>E.messageId),continuationToken:P.continuationToken}},[e]),y=l.useCallback(async()=>{const{data:k}=await va({path:{mailboxId:e},query:{...p.current,count:!0,results:!1},throwOnError:!0});if(k.count===void 0)throw new Error("the search returned no count for the selection");return k.count},[e]),S=l.useCallback(k=>async M=>{if(k.kind==="move"){const{data:E}=await rh({body:{messageIds:M,destinationMailboxId:k.destinationMailboxId},throwOnError:!0});return E}if(k.kind==="markRead"){const{data:E}=await ah({body:{messageIds:M,isRead:!0},throwOnError:!0});return E}const{data:P}=await oh({body:{messageIds:M},throwOnError:!0});return P},[]),g=l.useCallback(k=>{It(v,Et($C(k,e))),t&&v.invalidateQueries({queryKey:Ft({path:{accountId:t}})})},[v,e,t]),w=l.useCallback(()=>{f.current=!1,i({kind:"counting"}),y().then(k=>{if(f.current){i({kind:"idle"});return}i({kind:"escalated",total:k})},k=>{x(ds("Couldn't count matching messages","The count didn't finish.",k)),i({kind:"idle"})})},[y,x]),C=l.useCallback(()=>{f.current=!0},[]),R=l.useCallback(()=>{h.current||(f.current=!0,i({kind:"idle"}))},[]),O=l.useCallback(async(k,M)=>{f.current=!1,h.current=!0,u(k);const P=j=>d(L0(j)),E=S(k),L=b(p.current);let A;try{A=M!==void 0?await gd(M,E,P,()=>f.current):await P0(L,o.kind==="escalated"?o.total:0,E,P,()=>f.current)}finally{h.current=!1}return u(void 0),d(void 0),i({kind:"idle"}),A.error&&x(ds(DC(k.kind,A.done),PC(k.kind),A.error)),A.done>0&&g(k),A},[S,b,o,x,g]);return{phase:o,escalate:w,stop:C,clear:R,isRunning:c!==void 0,runningAction:c,progress:m,runAction:O}},wf=12,_C=e=>{const{envelope:t}=e,s=t.from[0];return{id:t.messageId,sender:s?Du({normalizedEmail:s.normalizedEmail,displayName:s.displayName}):"Unknown",subject:t.subject??"(No subject)",date:gt(t.date)}},zC=(e,t)=>{const s=e!==void 0&&t!==void 0,{data:n,isLoading:a}=we({...Ec({path:{mailboxId:e??""},query:{...t,limit:wf}}),enabled:s,staleTime:3e4});return{messages:(n?.items??[]).map(BC),isPending:s&&a}},BC=e=>({id:e.messageId,sender:e.fromName||e.fromEmail||"Unknown",subject:e.subject??"(No subject)",date:gt(e.sentDate)}),UC=e=>mt({queries:e.slice(0,wf).map(t=>({...hr({path:{messageId:t}}),staleTime:Number.POSITIVE_INFINITY})),combine:t=>({messages:t.map(s=>s.data).filter(s=>s!==void 0).map(_C),isPending:t.some(s=>s.isPending)})}),KC=e=>({matchOperator:"Or",literalClauses:jr(e)}),qC=(e,t,s)=>{const n=Ue(ih()),{mutate:a,reset:o}=n,[i,c]=l.useState(!1),u=l.useMemo(()=>kr(s),[s]),m=l.useCallback(()=>{!e||!t||(c(!1),a({path:{accountId:e},body:mi({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=l.useCallback(()=>{c(!1),o()},[o]),f=n.data,h=f?.semanticUnavailable===!0&&!i&&u.length>0;l.useEffect(()=>{!h||!e||(c(!0),a({path:{accountId:e},body:mi(KC(u))}))},[h,e,u,a]);const v=i||(f?.semanticUnavailable??!1),x=n.isPending||h,p=i?{matchOperator:"Or",literalClauses:jr(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:m,reset:d,matchedCount:x?void 0:f?.matchedCount,messageIds:x?void 0:f?.messageIds,semanticUnavailable:v,senderFallback:i,senders:u,matchPredicate:p,isPending:x,isError:n.isError,error:n.error}},HC=()=>[fr({path:{mailboxId:""}}),Za({path:{mailboxId:""}}),eo()].map(e=>[{_id:e[0]._id}]),WC=e=>xd(e)?e.pages:bd(e)?[e]:[],VC=e=>typeof e=="object"&&e!==null&&typeof e.messageId=="string",QC=(e,t)=>{const s=new Set(t),n=new Map;for(const a of e)for(const o of WC(a))for(const i of o.items){if(!VC(i)||!s.has(i.messageId))continue;const c=i.subject?.trim();c&&n.set(i.messageId,c)}return t.map(a=>n.get(a)).filter(a=>a!==void 0)},GC=e=>{const t=De(),s=e.join("\0");return l.useMemo(()=>{const n=HC().flatMap(a=>t.getQueriesData({queryKey:a}).map(([,o])=>o));return QC(n,e)},[t,s])},YC=({failure:e,isStarting:t,isRunning:s,isDone:n,failedCount:a,ruleSaved:o})=>e?.kind==="restartFailed"?"backApplyRestartFailed":e?.kind==="startFailed"?o?"backApplyStartFailed":"commitFailed":n?a>0?"backApplyFailed":"backApplyComplete":e?.kind==="statusUnreadable"?"statusUnknown":t||s?"backApplyRunning":"saving",XC={clauses:[],matchOperator:"any"},JC={clauses:[],matchOperator:"all",droppedFacets:[],keptTerms:!1,droppedSemantic:!1},ZC=[],ls={state:"saving",matched:0,applied:0,failed:0,failures:[]},fa=(e,t)=>e.map((s,n)=>({...s,id:`${t}-${n}`})),Vl=(e,t,s)=>{if(e==="delete")return{kind:"delete"};if(e==="markRead")return{kind:"markRead"};const n=e==="junk"?s:t;return n?{kind:"move",destinationMailboxId:n}:void 0},ma=e=>e==="move"||e==="junk"||e==="organize",Ql=e=>e==="junk"?nf:"No destination was chosen, so there is nowhere to file these. Go back and pick a folder.";function ek({verb:e,accountId:t,mailboxId:s,selection:n,crossAccount:a=!1,escalated:o,escalatedProgress:i,searchConversion:c,onFinished:u,onRunEnded:m,step:d,goToStep:f,goBack:h,closeWizard:v}){const[x]=l.useState(()=>c),[p]=l.useState(()=>o),b=x!==void 0,[y,S]=l.useState(b?"properties":"selected"),g=p?"escalated":y,[w,C]=l.useState(()=>x?{clauses:fa(x.clauses,"search"),matchOperator:x.matchOperator}:XC),[R,O]=l.useState(void 0),[k,M]=l.useState(void 0),[P,E]=l.useState(!1),[L,A]=l.useState(void 0),[j,I]=l.useState(void 0),[D,T]=l.useState(),F=l.useRef(!1),N=l.useRef(!1),V=l.useMemo(()=>n.map(U=>U.id),[n]),J=l.useMemo(()=>n.map(U=>U.email).filter(Boolean),[n]),re=V[0],oe=GC(V),{junkMailboxId:ie}=kn(t),Z=qC(p?void 0:t,re,J),{preview:ae}=Z;l.useEffect(()=>{ae()},[ae]);const fe=g==="similar"||g==="properties",B=l.useMemo(()=>({matchOperator:w.matchOperator==="all"?"And":"Or",literalClauses:w.clauses.map(U=>({field:U.field,value:U.value}))}),[w.clauses,w.matchOperator]),$=g==="similar"?Z.matchPredicate:B,{count:me,matchedIds:ge}=Dh(fe?t:void 0,$),Se=UC(fe?ge:[]),Ne=zC(p?s:void 0,p?.searchQuery),H=p?{status:"ready",count:p.total}:fe?me:{status:"ready",count:n.length},{data:Ee}=we({...it({path:{accountId:t??""}}),enabled:!!t,staleTime:Number.POSITIVE_INFINITY}),xe=Uo(t),ke=io(),de=l.useMemo(()=>lo({mailboxes:Ee?.items??[],folderAppointments:xe,currentMailboxId:s,translator:ke}),[Ee?.items,xe,s,ke]),{createFolderIn:se}=Pc(t),ye=de.find(U=>U.id===w.moveMailboxId)?.label,Pe=Qb(n.map(U=>({normalizedEmail:U.email,displayName:U.sender}))),ze=sv({match:g==="properties"&&w.clauses[0]?.value.trim()||void 0,sender:Pe?Du(Pe):void 0,folder:ye}),X=l.useMemo(()=>({...w,name:w.name??ze}),[w,ze]),Ze=NC(R?.draft.field,R?.draft.value??"",J),Ie=Ph(t),qe=Lh(t),K=yf({mailboxId:s??"",accountId:t,enabled:!1,predicateKey:"selection-wizard",searchQuery:{}}),{runAction:Qe}=K,Re=uh({verb:e,mode:g,scope:w.scope,fromSearch:b}),be=Re[di(Re,d)],Oe=!a&&!!t,pe=Oe?void 0:mh,Ce=Oe?void 0:hh,_=(U=>{if(U==="folder")return Ce;if(U==="rule")return X.scope==="standing"||X.scope==="until"?pe:void 0})(be)??dh(be,X,H),le=l.useCallback(()=>fa(tv(J,oe),"seed"),[J,oe]),ue=l.useCallback(U=>{S(U),C(Y=>({...Y,widen:U==="similar"&&re?{anchorCount:Math.max(n.length,1)}:void 0,...U==="properties"&&Y.clauses.length===0?{clauses:le()}:{}}))},[re,n.length,le]),ve=l.useCallback(()=>{E(!0),S("properties"),C(U=>({...U,widen:void 0,clauses:fa(jr(J),"sender"),matchOperator:"any"})),f("properties")},[J,f]),q=Z.semanticUnavailable||Z.isError;l.useEffect(()=>{be==="match"&&(g!=="similar"||!q||P||ve())},[be,g,q,P,ve]);const he=l.useCallback(()=>{O({mode:"add",draft:{field:"From",value:""}})},[]),ne=l.useCallback(U=>{const Y=w.clauses.find(Ae=>Ae.id===U);Y&&O({mode:"edit",clauseId:U,draft:{field:Y.field,value:Y.value}})},[w.clauses]),ee=l.useCallback(U=>{C(Y=>({...Y,clauses:Y.clauses.filter(Ae=>Ae.id!==U)}))},[]),je=l.useCallback(U=>{O(Y=>Y&&{...Y,draft:U})},[]),Le=l.useCallback(()=>{O(U=>{if(!U)return;const Y=Fh(U.draft.field,U.draft.value),Ae={...U.draft,value:Y};C(pt=>({...pt,clauses:U.clauseId?pt.clauses.map(yt=>yt.id===U.clauseId?{...yt,...Ae}:yt):[...pt.clauses,{id:crypto.randomUUID(),...Ae}]}))})},[]),Be=l.useCallback(()=>{if(_){M(be);return}M(void 0);const U=Re[di(Re,be)+1];U&&f(U)},[_,be,Re,f]),Xe=l.useCallback(async U=>{const Y=Vl(e,X.moveMailboxId,ie);if(!Y){I({matched:U.length,failureReason:Ql(e)});return}I({matched:U.length});const Ae=await Qe(Y,[...U]);I({matched:U.length,outcome:Ae}),N.current&&m?.(Y.kind,U.length,Ae)},[e,X.moveMailboxId,ie,Qe,m]),He=l.useCallback(async()=>{if(!p)return;const U=Vl(e,X.moveMailboxId,ie);if(!U){I({matched:p.total,failureReason:Ql(e)});return}I({matched:p.total});const Y=await p.run(U);I({matched:p.total,outcome:Y}),N.current&&m?.(U.kind,p.total,Y)},[p,e,X.moveMailboxId,ie,m]),{start:Me}=Ie,{createFilterAsync:et}=qe,Ke=l.useCallback(()=>{if(p){He();return}const U=$h({mode:y,ruleScope:X.scope}),Y=_h({mode:y,ruleScope:X.scope,anchorMessageId:re,clauses:X.clauses,matchOperator:X.matchOperator,moveMailboxId:X.moveMailboxId,until:X.until});if(A(U),U==="standing"||U==="temporary"){const Ae=zh(Y)?Y:void 0;T(Ae),et(Y,U,(X.name??"").trim()).then(pt=>{pt&&Ae&&Me(Ae)});return}if(U==="all-like-these"&&ma(e)){Me(Y);return}Xe(U==="just-these"?V:ge)},[p,He,y,X,re,e,V,ge,et,Me,Xe]),lt=l.useCallback(()=>{if(_){M(be);return}F.current||(F.current=!0,f("run"),Ke())},[_,be,f,Ke]),tt=l.useCallback(U=>{const Y=Ie.progress,Ae=YC({failure:Ie.failure,isStarting:Ie.isStarting,isRunning:Ie.isRunning,isDone:Ie.isDone,failedCount:Y.failedCount,ruleSaved:U});return Ae==="saving"||Ae==="commitFailed"||Ae==="backApplyStartFailed"?{...ls,state:Ae}:{state:Ae,matched:Y.matchedCount,applied:Y.appliedCount,failed:Ae==="backApplyFailed"||Ae==="backApplyRestartFailed"?Y.failedCount:0,failures:[]}},[Ie]),zt=l.useMemo(()=>{const U=new Map;for(const Y of[...n,...Se.messages,...Ne.messages])U.set(Y.id,Y);return U},[n,Se.messages,Ne.messages]),Rt=p?i:K.progress,ns=l.useCallback(()=>{if(!j)return ls;const{matched:U,outcome:Y,failureReason:Ae}=j;if(Ae!==void 0)return{...ls,state:"commitFailed",failureReason:Ae};if(!Y){const wt=Rt?.done??0;return{state:"backApplyRunning",matched:Math.max(U,wt),applied:wt,failed:0,failures:[]}}if(!(Y.cancelled||Y.error!==void 0))return{state:"backApplyComplete",matched:Math.max(U,Y.done),applied:Y.done,failed:0,failures:[]};if(Y.done===0)return{...ls,state:"commitFailed"};const yt=Y.failedIds.map(wt=>zt.get(wt)).filter(wt=>wt!==void 0),vs=Y.failedIds.length>0?Y.failedIds.length:Math.max(U-Y.done,1);return{state:"runStopped",matched:Math.max(U,Y.done),applied:Y.done,failed:vs,failures:yt}},[j,Rt,zt]),rt=p?ns():L==="standing"||L==="temporary"?qe.isError?{...ls,state:"commitFailed"}:qe.isSuccess?D?tt(!0):{...ls,state:"filterSaved"}:ls:L==="all-like-these"&&ma(e)?tt(!1):ns(),Tt=()=>{if(rt.state==="statusUnknown"){Ie.refreshStatus();return}if(p){He();return}if(L==="standing"||L==="temporary"){if(qe.isError){qe.reset(),Ke();return}D&&Me(D);return}if(L==="all-like-these"&&ma(e)){Ke();return}const U=j?.outcome?.failedIds??[];Xe(U.length>0?U:V)},bt=l.useCallback(()=>{v(Re,be)},[v,Re,be]),vt=l.useCallback(()=>{N.current=!0,v(Re,be),u()},[v,Re,be,u]),{stop:ht}=K,rs=j!==void 0&&j.outcome===void 0&&j.failureReason===void 0,qs=l.useCallback(()=>{if(p){p.stop();return}ht()},[p,ht]);Yu({shouldBlockFn:({action:U})=>U!=="BACK"?!1:(vt(),!0),enableBeforeUnload:!1,disabled:be!=="run"});const ct={messages:p?Ne.messages:fe?Se.messages:n,count:H,label:g==="selected"?"Your selection":"A sample of what matches",emptyReason:g==="similar"&&q?"notIndexed":"noMatch",loading:p?Ne.isPending:fe&&(H.status==="loading"||Se.isPending)};return r.jsx(fh,{verb:e,steps:Re,step:be,blockedReason:_,nudged:k===be,onBack:h,onExit:be==="run"?vt:bt,onContinue:Be,onCommit:lt,match:{selectedCount:n.length,mode:g,onModeChange:ue,semanticUnavailable:q,semanticErrorDetail:Z.error instanceof Error?Z.error.message:void 0,semanticFallbackTaken:P,onSemanticFallback:ve,escalatedScope:p?.scope,sample:ct},properties:{clauses:X.clauses,matchOperator:X.matchOperator,onMatchOperatorChange:U=>C(Y=>({...Y,matchOperator:U})),clauseEdit:R,onStartAddClause:he,onStartEditClause:ne,onRemoveClause:ee,onChangeDraft:je,onSubmitClause:Le,onCancelClause:()=>O(void 0),clauseFields:Bh,clauseSuggestions:Ze,conversionNotice:x?rv(x):void 0,semanticFallbackTaken:P,sample:{...ct,label:"What this matches"}},folder:{folders:de,mailboxId:X.moveMailboxId,delimiter:co(Ee?.items??[]),onSelect:U=>C(Y=>({...Y,moveMailboxId:U})),onCreateFolder:t?se:void 0,restriction:Ce},rule:{draft:X,onScopeChange:U=>C(Y=>({...Y,scope:U})),onUntilChange:U=>C(Y=>({...Y,until:U})),restriction:pe},name:{name:X.name??"",onNameChange:U=>C(Y=>({...Y,name:U})),nudged:k===be},review:{verb:e,mode:g,selectedCount:n.length,clauses:X.clauses,matchOperator:X.matchOperator,folder:ye,scope:X.scope,until:X.until,ruleName:Re.includes("name")?X.name:void 0,escalatedScope:p?.scope,sample:ct},run:{state:rt.state,verb:e,scope:X.scope,matched:rt.matched,applied:rt.applied,failedCount:rt.failed,failures:rt.failures,failureReason:rt.failureReason,onRetry:Tt,onDismiss:vt,onCancelRun:rs?qs:void 0}})}function ei(e){const t=lh()==="search",{searchConversion:s}=Fr(),{accounts:n}=Fe(),{step:a,goToStep:o,goBack:i,closeWizard:c}=ch(t?"properties":"match");if(!a)return null;const u=t?s??JC:void 0;return r.jsx(ek,{...e,...u?{verb:"organize",accountId:uC(u,e.accountId,n),selection:ZC,crossAccount:!1,escalated:void 0,searchConversion:u}:{},step:a,goToStep:o,goBack:i,closeWizard:c})}const tk=200,Gl=()=>r.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>r.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[r.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsxs("div",{className:"flex justify-between gap-2",children:[r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),sk=({accountEmail:e})=>{const t=Ye();return r.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[r.jsx(Pt,{className:"size-3.5 shrink-0"}),r.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),r.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})},nk=(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 rk({header:e,rows:t,wizard:s,children:n}){const{selectedIds:a,selectedCount:o,exitSelection:i,orderedIds:c,allSelected:u,toggleAllLoaded:m}=Jo(),d=l.useMemo(()=>nk(t,a),[t,a]),{junkMailboxId:f}=kn(d.accountId),{labels:h}=uo(d.accountId),v=l.useMemo(()=>Array.from(a),[a]),x=l.useMemo(()=>t.filter(g=>a.has(g.id)).map(g=>({id:g.id,sender:g.fromName,email:g.fromEmail,subject:g.subject,date:g.timeLabel})),[t,a]),p=Lr(f,d.mailboxId),b=l.useMemo(()=>c.length>0?{checked:u,indeterminate:o>0&&!u,onChange:m}:void 0,[c.length,u,o,m]),y=d.moveDisabledHint?{tone:"warning",text:d.moveDisabledHint}:void 0,S=g=>r.jsx(Eo,{title:g.title,navSlot:g.navSlot,titleMeta:g.titleMeta,searchSlot:g.searchSlot,searchField:g.searchField,idleSlot:g.makeFilterSlot,count:o,onCancel:i,onDelete:()=>s.start("delete"),onMove:()=>s.start("move"),onOrganize:()=>s.start("organize"),onJunk:p?()=>s.start("junk"):void 0,onMarkRead:()=>s.start("markRead"),overflowSlot:d.accountId&&d.mailboxId&&o>0&&h.length>0?r.jsx(lf,{accountId:d.accountId,mailboxId:d.mailboxId,messageIds:v}):void 0,selectAll:b,notice:y});return r.jsx(ff,{...e,selectionBar:S,paneOverlay:r.jsx(ei,{verb:s.verb,accountId:d.accountId,mailboxId:d.mailboxId,selection:x,crossAccount:d.moveDisabledHint!==void 0,onFinished:i}),children:n})}function ak({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:n,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i}){const{searchQuery:c,searchInput:u,resultFolderIndex:m,onSearchChange:d}=Fe(),f=xs(),h=es(),v=Nn(),x=ro(),p=Ye(),b=l.useMemo(()=>DS(e.filter(_=>!_.muted?.value)),[e]),[y,S]=l.useState("all"),[g,w]=l.useState("all"),[C,R]=l.useState(new Set),[O,k]=l.useState(!1),M=l.useCallback(_=>{R(le=>{const ue=new Set(le);return ue.has(_)?ue.delete(_):ue.add(_),ue})},[]),P=l.useCallback(()=>R(new Set),[]),E=u.trim().length>0,L=l.useMemo(()=>Rb({query:u,ownFilters:C}),[u,C]),A=l.useMemo(()=>Tb({query:u,ownCategory:g}),[u,g]),j=l.useCallback(_=>{if(!E||!Mu(_)){M(_);return}const le=Nb(u,_);le!==void 0&&d(le)},[E,u,d,M]),I=l.useCallback(_=>{if(!E){w(_);return}d(Eb(u,_))},[E,u,d]),D=l.useCallback(()=>{w("all"),S("all"),P(),E&&d(Ib(u))},[E,u,d,P]),{data:T,isLoading:F,isError:N,refetch:V}=we({...ya(),staleTime:6e4}),J=mt({queries:b.map(_=>({...it({path:{accountId:_.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),re=l.useMemo(()=>{const _=new Map;for(let le=0;le<b.length;le++){const ue=b[le].accountId,q=(J[le]?.data?.items??[]).reduce((he,ne)=>he+(ne.unseenCount??0),0);_.set(ue,q)}return _},[b,J]),oe=l.useMemo(()=>b.filter((_,le)=>{const ue=J[le];return ue?.isError?!wa(ue.error):!1}),[b,J]),{freeText:ie,tokens:Z}=Us(c.trim().toLowerCase(),f),{data:ae,isFetching:fe}=we({...ya({query:{query:ie,limit:tk}}),enabled:ie.length>0,staleTime:3e4}),B=l.useMemo(()=>{const _=Ul(T?.items??[]).map(nr);return(ie?PS(_.filter(ue=>sf(ue,ie)),Ul(ae?.items??[]).map(nr)):_).filter(ue=>(y==="all"||ue.accountId===y)&&Go(ue,Z))},[T,ae,y,ie,Z]),{bodyRows:$,briefSpamOffer:me}=l.useMemo(()=>{if(!ie)return{bodyRows:B,briefSpamOffer:void 0};const _=B.map(ve=>Wn(ve,m)),{spam:le}=ko(_);if(le.length===0)return{bodyRows:B,briefSpamOffer:void 0};const ue=new Set(le.map(ve=>ve.id));return{bodyRows:B.filter(ve=>!ue.has(ve.id)),briefSpamOffer:of(_)}},[B,ie,m]),ge=l.useMemo(()=>LS($),[$]),Se=l.useCallback((_,le)=>{const ue=ie?$.find(ve=>ve.id===_):void 0;if(ue?.threadId&&ue.mailboxId&&n){n(Wn(ue,m),le);return}s?.(_,le)},[ie,$,m,n,s]),Ne=l.useMemo(()=>b.length<=1?[]:[{id:"all",label:"All",active:y==="all"},...b.map(_=>({id:_.accountId,label:_.email.split("@")[0]??_.email,count:re.get(_.accountId),active:y===_.accountId}))],[b,re,y]),H=l.useMemo(()=>e.filter(_=>_.muted?.value).length,[e]),Ee=l.useMemo(()=>Array.from(re.values()).reduce((_,le)=>_+le,0),[re]),xe=l.useMemo(()=>b.map(_=>_.accountId),[b]),{hasNewMail:ke}=Rr(),{state:de,errorMessage:se,refresh:ye}=Oo(xe,{onSettled:()=>V()}),Pe=l.useMemo(()=>r.jsx(jo,{state:de,onRefresh:ye,label:"Refresh daily brief",errorMessage:se,hasUpdate:ke(xe)}),[de,ye,se,ke,xe]),ze=l.useMemo(()=>B.filter(_=>(A==="all"||_.category===A)&&ph(_,L)).map(_=>Wn(_,m)),[B,A,L,m]),{hits:X,isLoading:Ze}=tf(),Ie=l.useMemo(()=>{const _=new Map;for(const ue of T?.items??[])_.set(ue.messageId,ue.threadId);const le=ze.map(ue=>_.get(ue.id)).filter(ue=>ue!=null);return rf(X,le,m)},[X,ze,T,m]),qe=l.useMemo(()=>{const _=db(Ne.map(le=>({id:le.id,label:le.label,count:le.count,active:le.active})));return{categories:_.categories,filters:_.filters,sources:_.sources,sourcesNote:H>0?`+${H} muted`:void 0,selectedCategory:A,activeFilters:L,expanded:O,onExpandedChange:k,onSelectCategory:le=>I(le),onSelectSource:S,onToggleFilter:le=>j(le),onClear:D}},[Ne,H,A,L,O,j,I,D]),K=ge.length===0&&y==="all"&&ie.length===0&&Z.length===0,Qe=l.useMemo(()=>b.map(_=>_.accountId),[b]),Re=l.useMemo(()=>b.some(_=>Ao(_.syncPhase)),[b]),be=Vy(Qe,K||Re),Oe=r.jsxs("div",{className:"h-full overflow-y-auto",children:[r.jsx(Gl,{}),r.jsx(Gl,{})]}),pe=!F&&!N&&!K,Ce=af({tier:v,hasLiveInput:E,hasCommittedQuery:c.trim().length>0,bodyRendersCommittedResults:!0}),Te=pe?r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[me&&r.jsx(yu,{count:me.count,onScopeToSpam:()=>p({to:"/mail/$mailboxId",params:{mailboxId:me.mailboxId},search:{q:c||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}),r.jsx("div",{className:"min-h-0 flex-1",children:r.jsx(cc,{sections:ge,briefCategory:A,Row:Zo,selectedThreadId:t,onSelectThread:Se,onSelectBriefCategory:I,sources:Ne,sourcesNote:H>0?`+${H} muted`:void 0,onSelectSource:S,activeFilters:L,onToggleFilter:j,onClearFilters:D})})]}):F?Oe: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(Pt,{className:"size-8 text-danger"}),r.jsx("p",{children:"Couldn't load your messages"}),r.jsxs("button",{type:"button",onClick:()=>V(),className:"flex items-center gap-1 text-accent underline text-xs",children:[r.jsx(xo,{className:"size-3.5"}),"Try again"]})]}):be.resolved?r.jsx(hx,{sync:be.syncing?{synced:be.synced,total:be.total}:void 0}):Oe;return r.jsx(Ic,{hasSheet:pe&&!Ce,children:r.jsx(pf,{selectedMessageId:t,onOpen:Se,onDeleteMessages:i,onSelectionVerb:x.start,wizardOpen:x.isOpen,commandsRef:a,onTriageContextChange:o,children:r.jsx(rk,{wizard:x,header:{title:"Daily brief",unreadCount:Ee,footer:h?r.jsx(ou,{}):void 0,searchFilter:qe,searchResults:ze,searchLoading:F||fe,relatedResults:Ie,relatedLoading:Ze,onSelectSearchResult:n,searchResultsInBody:!0,refreshControl:Pe},rows:B,children:r.jsxs("div",{className:"flex h-full flex-col",children:[oe.map(_=>r.jsx(sk,{accountEmail:_.email,accountId:_.accountId},_.accountId)),r.jsx("div",{className:"min-h-0 flex-1",children:Te})]})})})})}const ok=10,Sf=e=>({q:e?.toLowerCase()??"",limit:ok}),ik=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(n=>n.normalizedEmail===s)};function lk(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Xn(t,{month:"short",year:"numeric"})}function Cf(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const ck="We can't verify the sender of this email, which could mean it's from an insecure source.",uk="We couldn't read this sender's address, so we can't confirm who really sent this message.";function dk(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?lk(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Cf(e.fromEmail)}}function fk(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 Yl(e){if(e.fromName&&e.fromName!==e.fromEmail)return e.fromName}function mk(e){return e.length===1?e[0]:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function hk(e,t){const s=[],n=e.displayNameCorrespondence;t&&(n===pi.Unrelated?s.push(`The name it shows, "${t}", has nothing to do with ${e.fromDomain}.`):n===pi.Lookalike&&s.push(`The name it shows, "${t}", only looks like ${e.fromDomain}.`));const a=pk(e.offDomainLinkDomains);return a.length>0&&s.push(`Its links go to ${mk(a.slice(0,3))}.`),s}function pk(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function gk(e,t){const s=t>0?t:void 0;if(Cf(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:uk,similarCount:s};const n=e.authenticity;if(!n)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:ck};if(!n.dkimMismatch){const m=Yl(e),d=hk(n,m);return d.length>0?{verdict:"caution",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,claimedBrand:m,summary:d.join(" ")}:{verdict:"aligned",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,summary:n.dkimDomain?`This message was signed by ${n.dkimDomain}.`:"Nothing looks unusual about this sender."}}const a=n.fromDomain,o=n.dkimDomain,i=Yl(e),c=o?`it was actually sent from ${o}`:"its signature failed to verify",u=i?`The display name claims "${i}", but ${c}${o?` — not ${a}`:""}. Real senders use their own address.`:`This message claims to be from ${a}, but ${c}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:u,similarCount:s}}function kf(e,t){const s=e?.fromEmail??null,n=e?.subject??"",{data:a,error:o}=we({...ur({query:Sf(s??void 0)}),enabled:!!s,staleTime:3e4}),i=ik(a?.items,s??void 0),c=[n,s].filter(Boolean).join(" "),{data:u,isLoading:m,error:d}=we({...Nc({query:{query:c,limit:5}}),enabled:!!(e&&c.length>3),staleTime:6e4,retry:1});return{data:l.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(y=>y.messageId!==e.messageId).map(y=>({id:y.messageId,mailboxId:t!=null&&y.mailboxIds.includes(t)?t:y.mailboxIds[0]??"",fromName:y.fromName??"",subject:y.subject??"(No subject)",timeLabel:y.sentDate!=null?gt(y.sentDate*1e3):"",matched:y.matchedChunkType})),v=dk(e,i),x=gk(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},b=fk(i);return{sender:v,authenticity:x,category:p,flags:b,similar:h}},[e,i,u,t]),isSimilarLoading:m,similarError:d,similarErrorIsFatal:wa(d),addressErrorIsFatal:wa(o),addressId:i?.addressId,address:i}}function xk(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 jf({addressId:e,senderEmail:t}){const s=De(),{pushError:n}=nt(),a=gh({query:Sf(t)}),{mutate:o,isPending:i}=Ue({...jc(),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:xk(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:l.useCallback(u=>{if(!e){Ga(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 bk=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Nf=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function vk(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function yk(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function wk(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Ef(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const Sk=["personal","newsletter","marketing","automated","transactional","social"],Ck=e=>e.spamReport?"notSpam":"reportSpam",kk=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:n}=e;return t&&!s?"error":n?"loading":"ready"};function jk(){return r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Dt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"h-8 rounded bg-surface"})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>r.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function Nk({isOpen:e,current:t,onSelect:s,onCancel:n}){return e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx(Rc,{label:"Dismiss reclassify sender",onDismiss:n,className:"backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),r.jsx("div",{className:"mt-4 flex flex-col gap-1",children:Sk.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 Ek({thread:e,onClose:t,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o}){const{data:i,addressId:c,isSimilarLoading:u,similarError:m,similarErrorIsFatal:d}=kf(e,s),[f,h]=l.useState(!1),v=e.fromEmail??void 0,{updateFlags:x}=jf({addressId:c,senderEmail:v}),{reportSpam:p,notSpam:b,isReporting:y,isRestoring:S}=wd({mailboxId:e.mailboxId,threadId:e.threadId,accountId:n,onAfterOptimisticRemove:o}),g=Ls(),w=Ck(e),C=l.useCallback(()=>{b([e.messageId])},[b,e.messageId]),R=l.useCallback(()=>{Ef(g,{count:1,senderTrust:e.senderTrust,wasRescuable:Nf(e)}),p([e.messageId])},[p,e,g]),O=l.useCallback(()=>{},[]),k=l.useCallback(()=>{const D=i?.flags?.vip!==!0;x({vip:{value:D}})},[i?.flags?.vip,x]),M=l.useCallback(()=>{const D=i?.flags?.muted!==!0;x({muted:{value:D}})},[i?.flags?.muted,x]),P=l.useCallback(()=>{const D=i?.flags?.unsubscribed!==!0;x({unsubscribed:{value:D}})},[i?.flags?.unsubscribed,x]),E=l.useCallback(D=>{h(!1),x({category:{value:D}})},[x]),L=c!==void 0,A={onToggleVip:L?k:void 0,onToggleMute:L?M:void 0,onToggleUnsubscribe:L?P:void 0,onReclassify:L?()=>h(!0):void 0,onNotSpam:w==="notSpam"?C:void 0,onReportSpam:w==="reportSpam"?R:void 0},j=({mailboxId:D,messageId:T,className:F,ariaLabel:N,children:V})=>r.jsx(qt,{to:"/mail/$mailboxId",params:{mailboxId:D},search:J=>({...J,selectedMessageId:T}),className:F,"aria-label":N,children:V});if(!i)return r.jsx(jk,{});const I=kk({similarError:m,similarErrorIsFatal:d,isSimilarLoading:u});return r.jsxs(r.Fragment,{children:[r.jsx(tu,{data:i,onClose:t,hideCloseButton:a,onShowSimilar:O,actions:A,similarState:I,similarLinkComponent:j,reportSpamPending:y,notSpamPending:S,className:"border-l-0 h-full w-full"}),r.jsx(Nk,{isOpen:f,current:i.category.value,onSelect:E,onCancel:()=>h(!1)})]})}const Ks=({onClose:e,thread:t,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o})=>t?r.jsx(Ek,{thread:t,onClose:e,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o}):r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Dt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[r.jsx(Dt,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),ha="Open a message first",ti=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:n,onReply:a,onReplyAll:o,onForward:i,onDelete:c,canDelete:u,onToggleStar:m,isStarred:d,moveContext:f})=>{const[h,v]=l.useState(null),x=u??e,p=b=>()=>v(b);return r.jsx(yg,{hasThread:e,isStarred:d,onUnavailable:b=>v(ha),unavailableHint:h,replyTitle:`Reply ${Vs("reply")}`,replyAllTitle:`Reply all ${Vs("replyAll")}`,forwardTitle:`Forward ${Vs("forward")}`,deleteTitle:`Move to Trash ${Vs("delete")}`,flagTitle:`Star ${Vs("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:x?c:p(ha),onToggleStar:m,onMove:p(ha),moveSlot:f?r.jsx(Vo,{accountId:f.accountId,currentMailboxId:f.currentMailboxId,onMove:f.onMove,label:"Move to mailbox"}):void 0,children:r.jsx(vg,{open:t,enabled:s,onToggle:n})})},If=()=>{const e=De();return l.useCallback(t=>{const s=Zt({path:{threadId:t.threadId}}),a=e.getQueriesData({queryKey:s}).flatMap(([,o])=>o?.items.map(i=>i.messageId)??[]);return a.length>0?a:[t.messageId]},[e])},mn=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=t??e?.mailboxId,o=s??e?.accountId,{accountId:i}=_o(o?void 0:a),c=o??i,u=If(),{deleteMessages:m}=ms({mailboxId:a??"",threadId:e?.threadId,accountId:c,onAfterOptimisticRemove:n}),{moveMessages:d}=Ds({mailboxId:a??"",threadId:e?.threadId,accountId:c,onAfterOptimisticRemove:n}),{toggleStar:f}=zo({threadId:e?.threadId??"",mailboxId:a??""}),h=l.useCallback(()=>{e&&m(u(e))},[e,u,m]),v=l.useCallback(S=>{e&&d(u(e),S)},[e,u,d]),x=l.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[p,b]=l.useState(null),y=l.useCallback(()=>b(null),[]);return{mailboxId:a,accountId:c,isStarred:e?.hasStars,deleteThread:h,moveThread:v,toggleStar:x,composeRequest:p,requestCompose:b,clearComposeRequest:y}},Xl=(e,t,s)=>{if(!t)return null;const n=e.indexOf(t);if(n===-1)return null;const a=s==="next"?n+1:n-1;return a<0||a>=e.length?null:e[a]},si=()=>{const[e,t]=l.useState(void 0),[s,n]=l.useState([]),[a,o]=l.useState([]),i=l.useRef(null),[c,u]=l.useState(!1),[m,d]=l.useState(!1),f=l.useCallback(h=>{t(h.focusedMessageId),n(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:f,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:c,blocksKeyboard:m}},ni=({context:e,orderedIds:t,selectedMessageId:s,enabled:n=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:c,blocksKeyboard:u}=e,m=l.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return ov({enabled:n&&!u,handlers:{...c?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:m,...o}}),{goBack:m,nextMessageId:Xl(t,s,"next")??void 0,previousMessageId:Xl(t,s,"previous")??void 0}};function Ik(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function Rf(e,t){if(e)return Ik(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const Tf=l.createContext(null);function $r(){const e=l.useContext(Tf);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function Rk({selectedMessageId:e,children:t}){const s=Ye(),{searchInput:n}=Fe(),{selectedThreadId:a,selectedMailboxId:o}=As({strict:!1}),{data:i}=we({...ya(),staleTime:6e4}),c=l.useMemo(()=>{if(e)return i?.items.find(M=>M.messageId===e)},[i,e]),u=l.useMemo(()=>Rf(c,{messageId:e,threadId:a,mailboxId:o}),[c,e,a,o]),m=l.useCallback((M,P)=>{s({to:"/mail",search:E=>({...E,selectedMessageId:M,selectedThreadId:void 0,selectedMailboxId:void 0}),replace:P?.replace})},[s]),d=l.useCallback((M,P)=>{s({to:"/mail",replace:P?.replace,search:E=>({...E,q:n||void 0,selectedMessageId:M.id,selectedThreadId:M.threadId,selectedMailboxId:M.mailboxId})})},[s,n]),f=l.useCallback(M=>{e&&M.includes(e)&&s({to:"/mail",search:P=>({...P,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=mn({thread:c,onAfterOptimisticRemove:f}),v=l.useCallback(()=>{s({to:"/mail",search:M=>({...M,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),x=si(),p=l.useMemo(()=>i?.items??[],[i]),{deleteMessages:b}=ms({mailboxId:c?.mailboxId??"",messages:p,onAfterOptimisticRemove:f}),{toggleReadFor:y}=Ar({mailboxId:c?.mailboxId??"",messages:p}),S=x.focusedMessageId,w=l.useMemo(()=>i?.items.find(M=>M.messageId===S),[i,S])??c,C=mn({thread:w}),{nextMessageId:R,previousMessageId:O}=ni({context:x,orderedIds:x.orderedIds,selectedMessageId:e,onClose:v,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{x.listCommandsRef.current?.requestVerb("delete")||C.deleteThread()},toggleStar:C.toggleStar,toggleRead:()=>{x.listCommandsRef.current?.requestVerb("markRead")||w&&y([w.messageId],!w.isRead)},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),k={selectedMessageId:e,selectedThread:c,conversation:u,onSelectMessage:m,onSelectSearchResult:d,onCloseThread:v,actions:h,triage:x,onDeleteMessages:b,nextMessageId:R,previousMessageId:O,handleDeselectIfRemoved:f};return r.jsx(Tf.Provider,{value:k,children:t})}function Mf(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:n,onDeleteMessages:a}=$r(),{accounts:o}=Fe();return r.jsx(ak,{accounts:o,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:n.listCommandsRef,onTriageContextChange:n.onTriageContextChange,onDeleteMessages:a})}function Tk(){const{conversation:e,actions:t}=$r(),{intelligenceOpen:s,onToggleIntelligence:n}=Fe(),a=ps()?.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(ti,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(zs,{})})]})}function Mk(){const{selectedThread:e,handleDeselectIfRemoved:t}=$r(),{onToggleIntelligence:s}=Fe();return r.jsx(Ks,{onClose:s,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,onAfterOptimisticRemove:t})}function Ak(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:n,nextMessageId:a,previousMessageId:o,handleDeselectIfRemoved:i}=$r(),{intelligenceOpen:c,onToggleIntelligence:u}=Fe();return t?r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:n,onOpenIntelligence:u,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:c}),r.jsx(Lo,{isOpen:c,onClose:u,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:u,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,hideCloseButton:!0,onAfterOptimisticRemove:i})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Mf,{})})}const Zs=Object.assign(Rk,{List:Mf,Reading:Tk,Intelligence:Mk,Phone:Ak}),Ok=()=>eo({query:{starred:!0,order:"desc"}});function Af(){const{data:e,isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:c}=Gu({queryKey:Ok(),queryFn:async({pageParam:m})=>{const{data:d}=await xh({query:{starred:!0,order:"desc",continuationToken:m},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:m=>m.continuationToken,staleTime:6e4});return{threads:l.useMemo(()=>(e?.pages??[]).flatMap(m=>m.items??[]),[e]),isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:c}}const Dk=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function Of({title:e,unreadCount:t,preset:s,selectedCategory:n,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:c,onClearFilters:u,children:m,footer:d,searchResults:f,searchLoading:h,relatedResults:v,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:y,searchResultsInBody:S,refreshControl:g}){const{searchInput:w}=Fe(),C=w.trim().length>0,R={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:n,activeFilters:a,onSelectCategory:o,onSelectSource:c,onToggleFilter:i,onClear:u};return r.jsx(Ic,{hasSheet:!C,children:r.jsx(ff,{title:e,unreadCount:t,footer:d,searchFilter:R,searchResults:f,searchLoading:h,relatedResults:v,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:y,searchResultsInBody:S,refreshControl:g,children:r.jsx(pc,{...R,hideChrome:C,children:m})})})}const Pk={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function Lk({rows:e,verb:t}){const{selectedIds:s,exitSelection:n}=Jo(),a=l.useMemo(()=>e.filter(o=>s.has(o.id)).map(o=>({id:o.id,sender:o.fromName,email:o.fromEmail,subject:o.subject,date:o.timeLabel})),[e,s]);return r.jsx(ei,{verb:t,selection:a,crossAccount:!0,onFinished:n})}function Fk({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:n,onDeleteMessages:a}){const{searchQuery:o,resultFolderIndex:i}=Fe(),c=xs(),u=es(),m=ro(),[d,f]=l.useState("all"),[h,v]=l.useState(new Set),x=l.useCallback(F=>{v(N=>{const V=new Set(N);return V.has(F)?V.delete(F):V.add(F),V})},[]),p=l.useCallback(()=>{f("all"),v(new Set)},[]),{threads:b,isLoading:y,isError:S,error:g,refetch:w,fetchNextPage:C,hasNextPage:R,isFetchingNextPage:O}=Af(),{freeText:k,tokens:M}=Us(o.trim().toLowerCase(),c),P=l.useMemo(()=>{const F=Array.from(h).map(N=>Pk[N]).filter(N=>N!=null);return Dk(b).map(nr).filter(N=>(d==="all"||N.category===d)&&F.every(V=>V(N))&&(!k||sf(N,k))&&Go(N,M))},[b,d,h,k,M]),E=l.useMemo(()=>fb(),[]),L=l.useMemo(()=>P.map(F=>Wn(F,i)),[P,i]),A=l.useMemo(()=>P.filter(F=>!F.isRead).length,[P]),j=y?"loading":S?"error":P.length===0?"empty":"ready",I=l.useCallback(()=>{const F=to(so());window.open(F,"_blank","noopener,noreferrer")},[]),D=Fr(),T=r.jsx("div",{className:"flex h-full min-h-0 flex-col",children:r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r.jsx("div",{className:"divide-y divide-line",children:P.map(F=>r.jsx(Zo,{thread:F,active:F.id===e,onClick:()=>t?.(F.id)},F.id))}),R?r.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>C(),disabled:O,children:O?"Loading…":"Load more"}):null]})});return r.jsx(Of,{title:"Starred",unreadCount:A,preset:E,selectedCategory:d,activeFilters:h,onSelectCategory:f,onToggleFilter:x,onClearFilters:p,searchResults:L,searchLoading:y,onSelectSearchResult:F=>t?.(F.id),searchResultsInBody:!0,children:r.jsxs(pf,{selectedMessageId:e,onOpen:(F,N)=>t?.(F,N),onDeleteMessages:a,onSelectionVerb:m.start,wizardOpen:m.isOpen,commandsRef:s,onTriageContextChange:n,children:[r.jsx(pu,{listTitle:"Starred",sections:[{id:"flagged",threads:P}],flatList:!0,hideHeader:!0,listState:D.searchResults?"ready":j,searchQuery:k?o:void 0,errorMessage:S?Ac(g):void 0,onRetry:()=>w(),onReportError:I,selectedThreadId:e,onSelectThread:t,isDesktop:u,selectionBar:r.jsx(bC,{title:"Starred"}),listBody:D.searchResults??(j==="ready"?T:void 0)}),r.jsx(Lk,{rows:P,verb:m.verb})]})})}const Df=l.createContext(null);function _r(){const e=l.useContext(Df);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function $k({selectedMessageId:e,children:t}){const s=Ye(),{threads:n}=Af(),a=l.useMemo(()=>{if(e)return n.find(g=>g.messageId===e)},[n,e]),o=l.useCallback((g,w)=>{s({to:"/mail/flagged",search:C=>({...C,selectedMessageId:g}),replace:w?.replace})},[s]),i=l.useCallback(()=>{s({to:"/mail/flagged",search:g=>({...g,selectedMessageId:void 0})})},[s]),c=l.useCallback(g=>{e&&g.includes(e)&&i()},[e,i]),u=mn({thread:a,onAfterOptimisticRemove:c}),m=si(),{deleteMessages:d}=ms({mailboxId:a?.mailboxId??"",messages:n,onAfterOptimisticRemove:c}),{toggleReadFor:f}=Ar({mailboxId:a?.mailboxId??"",messages:n}),h=m.focusedMessageId,x=l.useMemo(()=>n.find(g=>g.messageId===h),[n,h])??a,p=mn({thread:x}),{nextMessageId:b,previousMessageId:y}=ni({context:m,orderedIds:m.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{m.listCommandsRef.current?.requestVerb("delete")||p.deleteThread()},toggleStar:p.toggleStar,toggleRead:()=>{m.listCommandsRef.current?.requestVerb("markRead")||x&&f([x.messageId],!x.isRead)},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),S={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:m,onDeleteMessages:d,nextMessageId:b,previousMessageId:y,handleDeselectIfRemoved:c};return r.jsx(Df.Provider,{value:S,children:t})}function Pf(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:n}=_r();return r.jsx(Fk,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:n})}function _k(){const{selectedThread:e,actions:t}=_r(),{intelligenceOpen:s,onToggleIntelligence:n}=Fe(),a=ps()?.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(ti,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(zs,{})})]})}function zk(){const{selectedThread:e,handleDeselectIfRemoved:t}=_r(),{onToggleIntelligence:s}=Fe();return r.jsx(Ks,{onClose:s,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,onAfterOptimisticRemove:t})}function Bk(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:n,previousMessageId:a,handleDeselectIfRemoved:o}=_r(),{intelligenceOpen:i,onToggleIntelligence:c}=Fe();return e?r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:c,onSwipeNext:n?()=>s(n):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:i}),r.jsx(Lo,{isOpen:i,onClose:c,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:c,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,hideCloseButton:!0,onAfterOptimisticRemove:o})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Pf,{})})}const en=Object.assign($k,{List:Pf,Reading:_k,Intelligence:zk,Phone:Bk}),Uk={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Kk=()=>{const e=l.useRef(!1);return l.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector('[data-testid="compose-body"]')?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},qk=()=>{const{state:e,closeCompose:t}=Jt(),s=Kk(),[n,a]=l.useState(!1),{isError:o,error:i,refetch:c}=we({...$t(),staleTime:1/0}),u=l.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),m=l.useCallback(()=>{a(!1),t()},[t]),d=l.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const f=Uk[e.mode]??"New Message";return r.jsxs(dt.Root,{open:e.isOpen,onOpenChange:u,children:[r.jsxs(dt.Portal,{children:[r.jsx(dt.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(dt.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-lg bg-canvas pb-[env(safe-area-inset-bottom,0px)]",style:{height:"95dvh"},children:[r.jsx(dt.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),r.jsx(dt.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:f}),o?r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(ts,{title:"Couldn't load compose",error:i,onRetry:()=>{c()}})}):r.jsx("div",{className:"flex-1 overflow-hidden",children:r.jsx(Fo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),r.jsx(fo,{isOpen:n,title:"Discard draft?",description:"Your message has unsaved content. Are you sure you want to discard it?",confirmLabel:"Discard",cancelLabel:"Keep editing",destructive:!0,onConfirm:m,onCancel:d})]})},Hk={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Lf=()=>{const{state:e,closeCompose:t}=Jt(),s=es(),{isError:n,error:a,refetch:o}=we({...$t(),staleTime:1/0});if(!s)return r.jsx(qk,{});if(!e.isOpen)return null;const i=Hk[e.mode]??"New Message",c=r.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[r.jsx("div",{className:"flex items-center gap-2 min-w-0",children:r.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:r.jsx(Nt,{className:"size-5"})})]});return n?r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[c,r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(ts,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):r.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[c,r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:r.jsx(Fo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function Wk(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:gt(e.updatedAt),isRead:!0}}function Vk(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:gt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function Qk({outboxMessages:e,accountId:t,imapThreads:s}){const n=e.filter(i=>i.status==="draft"&&i.accountId===t).map(Wk),a=s.map(Vk),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 ri(){const e=ps();return!e||e.showNavPane?null:r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(pr,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const Gk=({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})]}),Yk=({row:e,isSelected:t,onOpen:s,onDelete:n,isDeleting:a})=>r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:Q("group",_s({active:t})),children:[r.jsx(fc,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),r.jsx(cn,{thread:e}),r.jsx("div",{className:"flex items-center gap-1 shrink-0",children:r.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),n(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:r.jsx(Lt,{className:"size-3.5"})})})]}),Xk=({row:e,isSelected:t,onOpen:s})=>{const n=!e.isRead;return r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:Q("group",_s({active:t})),children:[n&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx(jt,{name:e.fromName,email:e.fromEmail,size:"sm"}),r.jsx(cn,{thread:e})]})};function Jk({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:n,title:a,unreadCount:o}){const{openCompose:i,state:c}=Jt(),u=Ye(),m=De(),{data:d}=we(cr()),f=l.useMemo(()=>Qk({outboxMessages:d?.items??[],accountId:t,imapThreads:n}),[d?.items,t,n]),h=Ue({...dr(),onSuccess:()=>{m.invalidateQueries({queryKey:ao()})}}),v=y=>{h.mutate({path:{outboxMessageId:y}})},x=y=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:y})},p=y=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:y}})},b=f.length===0;return r.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(ri,{}),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(Ba,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):f.map(y=>r.jsxs("div",{children:[y.label&&r.jsx(Gk,{label:y.label,count:y.threads.length}),r.jsx("div",{className:"divide-y divide-line",children:y.threads.map(S=>y.id==="remit-drafts"?r.jsx(Yk,{row:S,isSelected:c.isOpen&&S.id===c.outboxMessageId,onOpen:x,onDelete:v,isDeleting:h.isPending},S.id):r.jsx(Xk,{row:S,isSelected:S.id===s,onOpen:p},S.id))})]},y.id))})]})}function Zk(e,t,s){const n=new Array(e);return new Proxy(n,{get(a,o,i){if(typeof o=="string"){const c=o.charCodeAt(0);if(c>=48&&c<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let m=a[u];if(!m){const d=t[u*2];m=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return m}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function Ns(e,t,s){let n=s.initialDeps??[],a,o=!0;function i(){const c=e();return(c.length!==n.length||c.some((m,d)=>n[d]!==m))&&(n=c,a=t(...c),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=c=>{n=c},i}function Jl(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const ej=(e,t)=>Math.abs(e-t)<1.01,tj=(e,t,s)=>{let n;return function(...a){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,a),s)}};let tn;const pa=()=>{if(tn!==void 0)return tn;if(typeof navigator>"u")return tn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return tn=!0;const e=navigator.maxTouchPoints;return tn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Zl=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},sj=e=>e,nj=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},rj=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const a=i=>{const{width:c,height:u}=i;t({width:Math.round(c),height:Math.round(u)})};if(a(Zl(s)),!n.ResizeObserver)return()=>{};const o=new n.ResizeObserver(i=>{const c=()=>{const u=i[0];if(u?.borderBoxSize){const m=u.borderBoxSize[0];if(m){a({width:m.inlineSize,height:m.blockSize});return}}a(Zl(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},rr={passive:!0},aj=typeof window>"u"?!0:"onscrollend"in window,oj=(e,t,s)=>{const n=e.scrollElement;if(!n)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&aj;let i=0;const c=o?null:tj(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=f=>()=>{i=s(n),c?.(),t(i,f)},m=u(!0),d=u(!1);return n.addEventListener("scroll",m,rr),o&&n.addEventListener("scrollend",d,rr),()=>{n.removeEventListener("scroll",m),o&&n.removeEventListener("scrollend",d)}},ij=(e,t)=>oj(e,t,s=>{const{horizontal:n,isRtl:a}=e.options;return n?s.scrollLeft*(a&&-1||1):s.scrollTop}),lj=(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"]},cj=(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})},uj=cj;class dj{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,n,a;return((a=(n=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:n.now)==null?void 0:a.call(n))??Date.now()},this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const c=o.target,u=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);for(const[m,d]of this.elementsCache)if(d===c){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(c,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=n())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=n())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=n())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var n,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:sj,rangeExtractor:nj,onChange:()=>{},measureElement:lj,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in s){const v=s[h];v!==void 0&&(o[h]=v)}const i=this.options;let c=null,u=null,m=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,v=o.count,x=this.getMeasurements(),p=h>0?((n=x[0])==null?void 0:n.key)??i.getItemKey(0):null,b=h>0?((a=x[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(v!==h||h>0&&v>0&&(o.getItemKey(0)!==p||o.getItemKey(v-1)!==b)){m=!0;const g=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??x[0]:null;g&&(c=[g.key,this.getScrollOffset()-g.start]);const w=o.followOnAppend===!0?"auto":o.followOnAppend||null;w&&v>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(v-1)!==b)&&(u=w)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(c&&this.scrollOffset!==null){const[h,v]=c,x=this.getMeasurements(),{count:p,getItemKey:b}=this.options;let y=0;for(;y<p&&b(y)!==h;)y++;if(y<p){const S=x[y];if(S){const g=S.start+v;g!==this.scrollOffset&&(f=g-this.scrollOffset,this.scrollOffset=g,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?c[0]:null,d?c[1]:0,u,f])},this.notify=s=>{var n,a;(a=(n=this.options).onChange)==null||a.call(n,this,s)},this.maybeNotify=Ns(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}if(this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const c=this.getScrollOffset();this.scrollDirection=i?c===o?this.scrollDirection:c<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},c=()=>{this._iosTouching=!1,!(!pa()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,rr),o.addEventListener("touchend",c,rr),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",c),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,c,u]=a;o!==null&&!c&&(pa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),c&&this.scrollToEnd({behavior:c})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),n=this.getMaxScrollOffset();if(s<0||s>n)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=Ns(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,n,a,o,i,c,u,m)=>(this.prevLanes!==void 0&&this.prevLanes!==c&&(this.lanesChangedFlag=!0),this.prevLanes=c,this.pendingMin=null,{count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:c,laneAssignmentMode:u,gap:m}),{key:!1}),this.getMeasurements=Ns(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:c,laneAssignmentMode:u,gap:m},d)=>{const f=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const y of this.laneAssignments.keys())y>=s&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),c===1){const y=s*2;let S=this._flatMeasurements;if(!S||S.length<y){const C=new Float64Array(y);S&&h>0&&C.set(S.subarray(0,h*2)),S=C,this._flatMeasurements=S}let g;if(h===0)g=n+a;else{const C=h-1;g=S[C*2]+S[C*2+1]+m}for(let C=h;C<s;C++){const R=o(C),O=f.get(R),k=typeof O=="number"?O:this.options.estimateSize(C);S[C*2]=g,S[C*2+1]=k,g+=k+m}const w=Zk(s,S,o);return this.measurementsCache=w,w}const v=this.measurementsCache.slice(0,h),x=new Array(c).fill(void 0),p=new Float64Array(c);let b=0;for(let y=0;y<h;y++){const S=v[y];S&&(x[S.lane]===void 0&&b++,x[S.lane]=y,p[S.lane]=S.end)}for(let y=h;y<s;y++){const S=o(y),g=this.laneAssignments.get(y);let w,C;const R=u==="estimate"||f.has(S);if(g!==void 0&&this.options.lanes>1){w=g;const P=x[w],E=P!==void 0?v[P]:void 0;C=E?E.end+m:n+a}else if(b===c){let P=0,E=p[0],L=x[0];for(let A=1;A<c;A++){const j=p[A];(j<E||j===E&&x[A]<L)&&(P=A,E=j,L=x[A])}w=P,C=E+m,R&&this.laneAssignments.set(y,w)}else w=y%this.options.lanes,C=n+a,R&&this.laneAssignments.set(y,w);const O=f.get(S),k=typeof O=="number"?O:this.options.estimateSize(y),M=C+k;v[y]={index:y,start:C,size:k,end:M,key:S,lane:w},x[w]===void 0&&b++,x[w]=y,p[w]=M}return this.measurementsCache=v,v},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ns(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,a,o)=>s.length===0||n===0?(this.range=null,null):(this.range=mj(s,n,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ns(()=>{let s=null,n=null;const a=this.calculateRange();return a&&(s=a.startIndex,n=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:n,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,a=s.getAttribute(n);return a?parseInt(a,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),c=Math.min(this.options.count-1,a+o);return s>=i&&s<=c}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,c)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(c))});return}const n=this.indexFromElement(s),a=this.options.getItemKey(n),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,n)=>{var a,o;if(s<0||s>=this.options.count)return;let i,c,u;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)u=this.options.getItemKey(s),c=m[s*2],i=m[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,c=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,f=n-d;if(f!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,v=h?this.getTotalSize():0,x=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:c,size:i,end:c+i,lane:0},f,this):c<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,n),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-v):x&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=Ns(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const c=s[o],u=n[c];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=Ff(0,n.length-1,o?c=>a[c*2]:c=>Jl(n[c]).start,s);return Jl(n[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,n,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+o?"end":"start"),n==="center"?s+=(a-o)/2:n==="end"&&(s-=o);const c=this.getMaxScrollOffset();return Math.max(Math.min(c,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(n==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)n="end";else if(i.start<=o+this.options.scrollPaddingStart)n="start";else return[o,n];if(n==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),n];const c=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(c,n,i.size),n]},this.scrollToOffset=(s,{align:n="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,n),i=this.now();this.scrollState={index:null,align:n,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:n="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,n);if(!o)return;const[i,c]=o,u=this.now();this.scrollState={index:s,align:c,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:n="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let a;if(n.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=n.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=n[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&o.some(c=>c===null);){const c=n[i];o[c.lane]===null&&(o[c.lane]=c.end),i--}a=Math.max(...o.filter(c=>c!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const n=this.getMeasurements();for(const a of n)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:n,behavior:a})=>{this._intendedScrollOffset=s+(n??0),this.options.scrollToFn(s,{behavior:a,adjustments:n},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&(pa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const n=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=n?n[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&ej(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const c=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&u>c;this.scrollState.lastTargetOffset=a,m||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Ff=(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 fj(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 mj(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=fj(a,o,s);let d=m;const f=s+t;for(;d<o&&a[d*2]+a[d*2+1]<f;)d++;return{startIndex:m,endIndex:d}}let c=Ff(0,o,m=>e[m].start,s),u=c;if(n===1)for(;u<o&&e[u].end<s+t;)u++;else if(n>1){const m=Array(n).fill(0);for(;u<o&&m.some(f=>f<s+t);){const f=e[u];m[f.lane]=f.end,u++}const d=Array(n).fill(s+t);for(;c>=0&&d.some(f=>f>=s);){const f=e[c];d[f.lane]=f.start,c--}c=Math.max(0,c-c%n),u=Math.min(o,u+(n-1-u%n))}return{startIndex:c,endIndex:u}}const ga=typeof document<"u"?l.useLayoutEffect:l.useEffect;function hj({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...n}){const a=l.useReducer(m=>m+1,0)[1],o=l.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=m=>{const d=o.current;if(!d.enabled||!d.container)return;const f=m.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const y=m.options.horizontal?"width":"height";d.container.style[y]=`${f}px`}const h=!!m.options.horizontal,v=d.mode==="transform",x=h?"left":"top",p=m.options.scrollMargin,b=m.getVirtualItems();for(const y of b){const S=y.start-p,g=m.elementsCache.get(y.key);g&&d.lastPositions.get(g)!==S&&(d.lastPositions.set(g,S),v?g.style.transform=h?`translate3d(${S}px, 0, 0)`:`translate3d(0, ${S}px, 0)`:g.style[x]=`${S}px`)}},c={...n,onChange:(m,d)=>{var f;const h=o.current;let v=!0;if(h.enabled){i(m);const x=m.range,p=h.prevRange;v=!p||p.isScrolling!==m.isScrolling||p.startIndex!==x?.startIndex||p.endIndex!==x?.endIndex,v&&(h.prevRange=x?{startIndex:x.startIndex,endIndex:x.endIndex,isScrolling:m.isScrolling}:null)}v&&(e&&d?Ha.flushSync(a):a()),(f=n.onChange)==null||f.call(n,m,d)}},[u]=l.useState(()=>{const m=new dj(c);return Object.assign(m,{containerRef:d=>{const f=o.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const h=m.getTotalSize();f.lastSize=h;const v=m.options.horizontal?"width":"height";d.style[v]=`${h}px`}}})});return u.setOptions(c),ga(()=>u._didMount(),[]),ga(()=>u._willUpdate()),ga(()=>{i(u)}),u}function pj(e){return hj({observeElementRect:rj,observeElementOffset:ij,scrollToFn:uj,...e})}const ai=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",gj=e=>`Select all ${ai(e)}`,xj=(e,t)=>`All ${Gt(t)} ${ai(e)} selected`,bj=({verb:e,confirmingDelete:t,hasSelection:s,junkMailboxId:n,currentMailboxId:a,deletableMessageId:o})=>{if(t)return{kind:"withheld"};if(e==="junk"){const i=$S(n,a);if(i!==void 0)return{kind:"unavailable",reason:i}}return s?{kind:"openWizard"}:e!=="delete"||o===void 0?{kind:"declined"}:{kind:"confirmDelete",messageId:o}},vj=(e,t,s)=>e==="BACK"&&t&&s===void 0,yj=(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:gt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Or(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),wj=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,messageCount:m,isMultiSelectMode:d,onLongPress:f,isDesktop:h,density:v})=>r.jsx(Zo,{thread:yj(e,m),linkMailboxId:t,inListbox:!0,active:s,focused:n,isTabStop:a,density:v,isDesktop:h,onFocusRow:o,selection:{isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:d,onLongPress:f}}),Sj=l.memo(wj),Cj=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:gt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Or(e.category),suspicious:t}},kj=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,onDelete:h,onToggleRead:v,density:x})=>{const[p,b]=l.useState("none"),y=Ye(),S=l.useCallback(O=>{navigator.vibrate?.(10),O==="trailing"?h(e.messageId):v(e.messageId,e.isRead),b("none")},[h,v,e.messageId,e.isRead]),g=l.useCallback(()=>{d(e.messageId)},[d,e.messageId]),w=l.useCallback(()=>{c(e.messageId)},[c,e.messageId]),C=l.useCallback(()=>{y({to:"/mail/$mailboxId",params:{mailboxId:t},search:O=>({...O,selectedMessageId:e.messageId})})},[y,t,e.messageId]),R=gf(e.messageId,u);return f||m?r.jsx(Sj,{thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,density:x}):r.jsx("div",{role:"presentation",onPointerDownCapture:R.onMouseDown,onClickCapture:R.claimClick,onContextMenu:R.onContextMenu,children:r.jsx(hu,{thread:Cj(e),selectionMode:!1,checked:!1,active:s,peek:p,onPeek:b,onToggleCheck:w,onLongPress:g,onOpen:C,onAct:S})})},jj=72,Nj=32,Ej=5,$f="remit:list-density",Ij=()=>{try{const e=localStorage.getItem($f);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},Rj=({query:e})=>r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[r.jsx(ir,{className:"size-4 text-fg-muted"}),r.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),Tj=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:n,isError:a=!1,error:o,onRetry:i,searchQuery:c,searchPredicate:u,onDeleteMessages:m,isDeleting:d=!1,isMoving:f=!1,onLoadMore:h,hasMore:v=!1,isLoadingMore:x=!1,accountId:p,listTitle:b,listMeta:y,listFilter:S,listScopeLabel:g,onTriageContextChange:w,commandsRef:C,hideHeader:R=!1})=>{const O=l.useRef(null),k=Ye(),M=es(),P=ro(),{verb:E,start:L,startFromSearch:A}=P,j=bh(),I=!!c?.trim(),D=Fr(),{labels:T}=uo(p),{pushError:F}=nt(),[N,V]=l.useState(s),[J,re]=l.useState(),oe=l.useCallback(z=>{re(G=>G===z?G:void 0),V(z)},[]),[ie,Z]=l.useState(Ij),ae=l.useCallback(()=>{Z(z=>{const G=z==="comfortable"?"compact":"comfortable";try{localStorage.setItem($f,G)}catch{}return G})},[]),{toggleReadFor:fe}=Ar({mailboxId:e}),{junkMailboxId:B}=kn(p),$=Lr(B,e),{selectedIds:me,selectedCount:ge,hasSelection:Se,isSelected:Ne,toggle:H,select:Ee,clearSelection:xe,selectRange:ke,setAnchor:de,selectAll:se,toggleAll:ye,intersectWith:Pe}=au(),ze=vo(ge,M),[X,Ze]=l.useState(null),Ie=I&&!!u,qe=`${e}|${JSON.stringify(u??{})}`,K=yf({mailboxId:e,accountId:p,enabled:Ie,predicateKey:qe,searchQuery:u??{}}),Qe=l.useCallback((z,G,St)=>{if(St.error===void 0){if(St.cancelled){F({severity:"warning",title:AC(St.done),detail:OC(z,St.done,G)});return}F({severity:"info",title:Wl(z,St.done)})}},[F]),Re=K.phase.kind,be=K.clear,Oe=l.useCallback(()=>{Re==="escalated"&&be(),xe()},[xe,be,Re]),[pe,Ce]=l.useState(null),Te=l.useRef(null),_=l.useRef(!1),le=l.useRef(null),ue=!n&&t.length>0,ve=X!==null,q=pj({count:t.length,getScrollElement:()=>O.current,estimateSize:()=>ie==="compact"?Nj:jj,overscan:Ej}),he=s?t.findIndex(z=>z.messageId===s):-1,ne=N?t.findIndex(z=>z.messageId===N):-1,ee=l.useCallback(z=>{if(z<0||z>=t.length)return;const G=t[z];if(ze){H(G.messageId);return}Te.current=G.messageId,_.current=!1,re(G.messageId),V(G.messageId)},[t,ze,H]),je=l.useCallback(()=>{if(t.length===0)return;const z=ne<0?0:Math.min(ne+1,t.length-1);ee(z)},[t.length,ne,ee]),Le=l.useCallback(()=>{if(t.length===0)return;const z=ne<=0?0:ne-1;ee(z)},[t.length,ne,ee]),Be=l.useCallback(()=>ee(0),[ee]),Xe=l.useCallback(()=>ee(t.length-1),[ee,t.length]),He=l.useCallback(()=>{N&&H(N)},[N,H]),Me=l.useMemo(()=>t.map(z=>z.messageId),[t]),et=l.useMemo(()=>{const z=[];for(const G of t)me.has(G.messageId)&&z.push({id:G.messageId,sender:G.fromName??G.fromEmail??"Unknown",email:G.fromEmail??"",subject:G.subject??"(No subject)",date:gt(G.sentDate)});return z},[t,me]),Ke=l.useCallback((z,G)=>G.shiftKey?(ke(Me,z,N),!0):G.metaKey||G.ctrlKey?(H(z),!0):(Oe(),de(z),!1),[Me,N,ke,H,Oe,de]),lt=l.useCallback(z=>{!m||z.length===0||(le.current=N??null,Ze(z))},[m,N]),tt=l.useCallback(z=>{const G=ru(Me,N,z);G!==void 0&&(ke(Me,G),Te.current=G,_.current=!1,re(void 0),V(G))},[Me,N,ke]),zt=l.useCallback(()=>tt(-1),[tt]),Rt=l.useCallback(()=>tt(1),[tt]),ns=l.useCallback(()=>{Me.length>0&&se(Me)},[Me,se]),bs=l.useCallback(z=>{const G=bj({verb:z,confirmingDelete:X!==null,hasSelection:Se,junkMailboxId:B,currentMailboxId:e,deletableMessageId:m?N:void 0});return G.kind==="openWizard"?(L(z),!0):G.kind==="confirmDelete"?(lt([G.messageId]),!0):G.kind==="unavailable"?(F({severity:"warning",title:G.reason}),!0):G.kind==="withheld"},[X,m,Se,B,e,L,N,lt,F]),rt=l.useCallback(()=>{N&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:z=>({...z,selectedMessageId:N})})},[N,k,e]),Tt=l.useCallback(z=>{k({to:"/mail/$mailboxId",params:{mailboxId:e},search:G=>({...G,selectedMessageId:z}),replace:!0})},[k,e]);mf({keyboardFocusedMessageId:J,openMessageId:s,enabled:M&&ge===0,open:Tt});const bt=K.phase.kind==="escalated"?{scope:ai(u??{}),total:K.phase.total,searchQuery:u??{},run:z=>K.runAction(z),stop:K.stop}:void 0,vt=l.useCallback(()=>{if(!X)return;const z=X;if(z.length===0){Ze(null);return}const G=new Set(z),St=t.findIndex(st=>G.has(st.messageId));let Mt;for(let st=St+1;st<t.length;st++)if(!G.has(t[st].messageId)){Mt=t[st].messageId;break}if(Mt===void 0){for(let st=St-1;st>=0;st--)if(!G.has(t[st].messageId)){Mt=t[st].messageId;break}}m?.(z),Oe(),le.current=null,Ze(null),Mt!==void 0&&(Te.current=Mt,_.current=!1,oe(Mt),M&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:st=>({...st,selectedMessageId:Mt}),replace:!0})),M||Ce(Wl("delete",z.length))},[X,t,m,Oe,k,e,M,oe]),ht=l.useCallback(()=>{const z=le.current;le.current=null,Ze(null),z!==null&&(Te.current=z,_.current=!1,oe(z))},[oe]),rs=l.useMemo(()=>{if(ge===0)return;const z=new Set;for(const G of t)me.has(G.messageId)&&z.add(G.accountConfigId);if(z.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[ge,me,t]),qs=l.useCallback(()=>{if(bt){A();return}L("organize")},[bt,A,L]),En=l.useCallback(z=>{m?.([z])},[m]),ct=l.useCallback((z,G)=>{fe([z],!G)},[fe]),U=l.useCallback(z=>{M||Ee(z)},[M,Ee]),Y=l.useCallback(()=>{if(K.isRunning||K.phase.kind==="counting"){K.stop();return}Oe()},[K,Oe]),Ae=l.useCallback(()=>{K.clear()},[K]);l.useEffect(()=>{if(_.current||!M&&s)return;const z=ne>=0?ne:he;z>=0&&q.scrollToIndex(z,{align:"auto"})},[ne,he,q,M,s]),l.useEffect(()=>{s&&(_.current=!1,oe(s))},[s,oe]),l.useEffect(()=>{N&&(t.some(z=>z.messageId===N)||oe(t[0]?.messageId))},[t,N,oe]),l.useEffect(()=>{w?.({focusedMessageId:N,selectedIds:Array.from(me),hasList:ue,blocksKeyboard:ve||P.isOpen})},[N,me,ue,ve,P.isOpen,w]);const pt=l.useRef(w);pt.current=w,l.useEffect(()=>()=>pt.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),l.useEffect(()=>{K.phase.kind!=="idle"||K.isRunning||Pe(t.map(z=>z.messageId))},[t,Pe,K.phase,K.isRunning]);const yt=l.useRef(e);l.useEffect(()=>{yt.current!==e&&(yt.current=e,Oe())},[e,Oe]),Yu({shouldBlockFn:({action:z})=>vj(z,Se,j)?(Oe(),!0):!1,enableBeforeUnload:!1,disabled:!Se||j!==void 0}),l.useEffect(()=>{const z=O.current;if(!z||!v||!h)return;const G=()=>{if(x)return;const{scrollTop:St,scrollHeight:Mt,clientHeight:st}=z;St+st>=Mt-200&&h()};return z.addEventListener("scroll",G,{passive:!0}),G(),()=>z.removeEventListener("scroll",G)},[v,x,h]),l.useEffect(()=>{const z=Te.current;if(!z)return;const G=O.current?.querySelector(`[data-message-id="${z}"]`);G&&(Te.current=null,G.focus({preventScroll:!0}))}),l.useEffect(()=>{if(C){if(!ue){C.current=null;return}return C.current={focusNext:je,focusPrevious:Le,focusFirst:Be,focusLast:Xe,openFocused:rt,toggleSelect:He,extendSelectDown:Rt,extendSelectUp:zt,selectAll:ns,clearSelection:()=>Se?(Oe(),!0):!1,requestVerb:bs,toggleDensity:ae},()=>{C.current=null}}},[C,ue,je,Le,Be,Xe,rt,He,Rt,zt,ns,Se,Oe,bs,ae]);const vs=n?"loading":a?"error":t.length===0?"empty":"ready",wt=a?Ac(o):void 0,as=l.useCallback(()=>{const z=to(so());window.open(z,"_blank","noopener,noreferrer")},[]),In=[{id:"inbox",threads:[]}],ys=Me.length>0&&Me.every(z=>me.has(z)),Br=Ie&&v&&ys&&!d&&!f&&K.phase.kind==="idle"&&!K.isRunning,Ur=d||f||K.isRunning,Hs=K.phase.kind==="escalated"?K.phase.total:ge,Kr=K.runningAction?MC(K.runningAction.kind,K.progress?.done??0,K.progress?.total??Hs):K.phase.kind==="counting"?"Counting matches…":K.phase.kind==="escalated"?xj(u??{},K.phase.total):void 0,qr=K.phase.kind!=="escalated"&&Me.length>0?{checked:ys,indeterminate:ge>0&&!ys,onChange:()=>ye(Me)}:void 0,te=K.runningAction?{value:K.progress?.done??0,max:K.progress?.total??Hs,tone:LC(K.runningAction.kind)}:void 0,at=(K.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:K.stop}}:K.phase.kind==="escalated"&&!K.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:Ae}}:Br?{tone:"info",text:"",action:{label:gj(u??{}),onClick:K.escalate}}:void 0)??(rs?{tone:"warning",text:rs}:void 0),Yf=r.jsx(Eo,{title:D.title||b,navSlot:D.navSlot,titleMeta:D.titleMeta,searchSlot:D.searchSlot,searchField:D.searchField,idleSlot:D.makeFilterSlot,count:Hs,onCancel:Y,onDelete:()=>L("delete"),onMove:()=>L("move"),onOrganize:qs,onJunk:$?()=>L("junk"):void 0,onMarkRead:()=>L("markRead"),overflowSlot:p&&e&&ge>0&&T.length>0?r.jsx(lf,{accountId:p,mailboxId:e,messageIds:Array.from(me)}):void 0,isBusy:Ur,isCounting:K.phase.kind==="counting",selectAll:qr,statusLabel:Kr,progress:te,notice:at}),Xf=hf(Me,N),Jf=l.useCallback(z=>{_.current=!0,oe(z)},[oe]),Zf=r.jsxs(r.Fragment,{children:[I&&c&&r.jsx(Rj,{query:c}),r.jsxs("div",{ref:O,role:"listbox","aria-multiselectable":!0,"aria-label":b,className:"flex-1 overflow-y-auto",children:[r.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${q.getTotalSize()}px`},children:q.getVirtualItems().map(z=>{const G=t[z.index];return r.jsx("div",{role:"presentation","data-index":z.index,ref:q.measureElement,className:Ve("absolute left-0 top-0 w-full border-b border-line",K.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${z.start}px)`},children:r.jsx(kj,{thread:G,mailboxId:e,isSelected:s===G.messageId,isFocused:N===G.messageId,isTabStop:Xf===G.messageId,onFocusRow:Jf,isChecked:Ne(G.messageId),onToggleCheck:H,onRowSelect:Ke,isMultiSelectMode:ze,onLongPress:U,isDesktop:M,onDelete:En,onToggleRead:ct,density:ie})},z.key)})}),x&&r.jsx(sg,{})]})]});return r.jsxs(r.Fragment,{children:[pe&&!M&&r.jsx(gn,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>Ce(null),children:pe}),r.jsx(pu,{listTitle:b,listMeta:y,sections:In,flatList:!0,listState:D.searchResults?"ready":vs,searchQuery:I?c:void 0,listFilter:S,listScopeLabel:g,errorMessage:wt,onRetry:i,onReportError:as,density:ie,selectedThreadId:s,onSelectThread:z=>k({to:"/mail/$mailboxId",params:{mailboxId:e},search:G=>({...G,selectedMessageId:z})}),isDesktop:M,hideHeader:R,selectionBar:Yf,listBody:D.searchResults??(vs==="ready"?Zf:void 0)}),r.jsx(fo,{isOpen:X!==null,title:Dc(X?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:d,onConfirm:vt,onCancel:ht}),r.jsx(ei,{verb:E,accountId:p,mailboxId:e,selection:et,crossAccount:rs!==void 0,escalated:bt,escalatedProgress:K.progress,onFinished:Oe,onRunEnded:Qe})]})},Mj=e=>Ft({path:{accountId:e}}),Aj=e=>{const t=De(),s=Ls(),n=Ue({...vh(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:Mj(e)})}});return{trigger:()=>{n.mutate({path:{accountId:e}})},triggerAsync:()=>n.mutateAsync({path:{accountId:e}}),isPending:n.isPending,error:n.error,reset:n.reset}},Oj=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:n}=Aj(e);return r.jsx(Hx,{onRefresh:s,isRefreshing:n,children:t})};function Dj({accountId:e,currentMailboxId:t,candidates:s,onMove:n,children:a}){const[o,i]=l.useState(!1),c=Ls(),u=io(),{inboxMailboxId:m}=yd(e),d=Uo(e),{data:f}=we({...it({path:{accountId:e}}),staleTime:1/0}),h=l.useMemo(()=>lo({mailboxes:f?.items??[],folderAppointments:d,currentMailboxId:t,translator:u}),[f?.items,d,t,u]),v=l.useMemo(()=>m||(h.find(S=>S.label.toLowerCase()==="inbox")?.id??h.find(S=>!S.isCurrent)?.id??""),[m,h]),x=l.useRef(!1);l.useEffect(()=>{x.current||(x.current=!0,vk(c,s.length))},[c,s.length]);const p=l.useCallback(()=>{yk(c,s.length),i(!0)},[c,s.length]),b=l.useCallback((y,S)=>{wk(c,{selected:y.length,total:s.length,toInbox:S===m}),n(y,S)},[c,s.length,m,n]);return r.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[r.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:r.jsx(Qx,{count:s.length,onReview:p})}),r.jsx("div",{className:"min-h-0 flex-1",children:a}),r.jsx(ab,{open:o,candidates:s,defaultDestinationId:v,availableFolders:h,delimiter:co(f?.items??[]),onConfirmMove:b,onCancel:()=>i(!1)})]})}const Pj="We can verify this sender";function Lj(e){const{data:t}=we({...Ec({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:Pj,trustSubReason:bk(n.senderTrust),senderTrust:n.senderTrust}))}}const Fj=e=>{const t=new Set,s=[];for(const n of e)t.has(n.threadMessageId)||(t.add(n.threadMessageId),s.push(n));return s},$j={unread:"unread",flagged:"starred",attachment:"attachments"},_j=new Set(Object.values(ot)),_f=e=>_j.has(e),zj=e=>_f(e.category)||e.attributes.size>0,Bj=e=>{const t={};_f(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const n=$j[s];n&&(t[n]=!0)}return t},Uj=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",Kj=["category","unread","starred","attachments"],ec=e=>JSON.stringify(Kj.map(t=>e?.[t]??null)),qj=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},Hj=(e,t)=>{const s=qj(e);return s?ec(s)===ec(t):!1},zf="remit:intelligence-open";function Wj(){try{return localStorage.getItem(zf)!=="closed"}catch{return!0}}function tc(e){try{localStorage.setItem(zf,e?"open":"closed")}catch{}}const Vj=(e,t)=>e!==t,Qj=(e,t,s)=>{if(!(s||!t))return e.find(n=>n.messageId===t)},Gj=(e,t,s,n)=>{if(e)return e;if(!(n||!s))return t?.messageId===s?t:void 0},_n=e=>e[0],Yj=e=>{const t=_n(e.filter(c=>c.type==="from").map(c=>c.value)),s=_n(e.filter(c=>c.type==="subject").map(c=>c.value)),n=_n(e.filter(c=>c.type==="category").map(c=>c.category)),a=_n(e.filter(c=>c.type==="isUnread"||c.type==="isRead").map(c=>c.type==="isUnread")),o=e.some(c=>c.type==="isStarred")?!0:void 0,i=e.some(c=>c.type==="hasAttachment")?!0:void 0;return{...t!==void 0?{from:t}:{},...s!==void 0?{subject:s}:{},...n!==void 0?{category:[n]}:{},...a!==void 0?{unread:a}:{},...o!==void 0?{starred:o}:{},...i!==void 0?{attachments:i}:{}}},Xj=(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 Jj(e,t={}){const s=Yj(e),n={...s,...t};return{params:s,residual:e.filter(a=>!Xj(n,a))}}function Zj(e,t,s){if(t.length===0)return e;const n=[...t];return e.filter(a=>{const o=nr(a);return Go({...o,accountId:o.accountId??s},n)})}const eN=50,tN=new Map(Nu().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),Bf=l.createContext(null);function zr(){const e=l.useContext(Bf);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function sN({mailboxId:e,selectedMessageId:t,children:s}){const n=Ye(),o=Nn()==="desktop",i=Ls(),{accounts:c,searchQuery:u,searchInput:m,intelligenceOpen:d,onToggleIntelligence:f,onSetIntelligenceOpen:h}=Fe(),v=xs(),x=Qo(u),p=x.length>0,{freeText:b,tokens:y}=Us(x,v),[S,g]=l.useState("all"),[w,C]=l.useState(new Set),R=l.useMemo(()=>({category:S,attributes:w}),[S,w]),O=l.useMemo(()=>Bj(R),[R]),k=p||zj(R),{params:M,residual:P}=Jj(y,O),E={order:"desc",limit:eN,...b?{query:b}:{},...M,...O},L={category:E.category,unread:E.unread,starred:E.starred,attachments:E.attachments},A=k?Za({path:{mailboxId:e},query:E}):fr({path:{mailboxId:e},query:{order:"desc"}}),{data:j,isLoading:I,isError:D,error:T,refetch:F,fetchNextPage:N,hasNextPage:V,isFetchingNextPage:J}=Gu({queryKey:A,queryFn:async({pageParam:te})=>{if(k){const{data:at}=await va({path:{mailboxId:e},query:{...E,continuationToken:te},throwOnError:!0});return at}const{data:ut}=await yh({path:{mailboxId:e},query:{order:"desc",continuationToken:te},throwOnError:!0});return ut},initialPageParam:void 0,getNextPageParam:te=>te.continuationToken,placeholderData:(te,ut)=>Hj(ut?.queryKey,L)?te:void 0}),re=l.useCallback(te=>{t&&te.includes(t)&&n({to:"/mail/$mailboxId",params:{mailboxId:e},search:ut=>({...ut,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,n]),{deleteMessages:oe,isPending:ie}=ms({mailboxId:e,onAfterOptimisticRemove:re}),{accountId:Z}=_o(e),ae=dd({accounts:c}),{moveMessages:fe,isPending:B}=Ds({mailboxId:e,accountId:Z,onAfterOptimisticRemove:re}),$=Zj(rw(Fj(j?.pages.flatMap(te=>te.items??[])??[])),P,Z),me=l.useCallback(te=>{g(te)},[]),ge=l.useCallback(te=>{C(ut=>{const at=new Set(ut);return at.has(te)?at.delete(te):at.add(te),at})},[]),Se=l.useCallback(()=>{g("all"),C(new Set)},[]),Ne=tN.get(S),H=Ne?{label:Ne,reach:P.length>0?"loaded-pages":Uj(E),onClear:Se}:void 0,Ee=Vj(m,u),xe=Qj($,t,Ee),[ke,de]=l.useState(void 0);l.useEffect(()=>{xe&&de(xe)},[xe]);const se=Gj(xe,ke,t,Ee),{selectedThreadId:ye}=As({strict:!1}),Pe=l.useMemo(()=>Rf(se,{messageId:t,threadId:Ee?void 0:ye,mailboxId:e}),[se,t,ye,Ee,e]),ze=si(),{listCommandsRef:X,onTriageContextChange:Ze,focusedMessageId:Ie,selectedIds:qe}=ze,K=$.find(te=>te.messageId===Ie)??se,Qe=l.useRef(null);l.useEffect(()=>{const te=se?.messageId??null;te&&Qe.current!==te&&se?.authenticity?.dkimMismatch&&(Qe.current=te,d||f())},[se?.messageId,se?.authenticity?.dkimMismatch,d,f]);const Re=l.useRef(!1);l.useEffect(()=>{Re.current||o&&se?.messageId&&(Re.current=!0,Wj()&&!d&&h(!0))},[o,se?.messageId,d,h]);const be=l0({accounts:c})??0,Oe=De(),{pushError:pe}=nt(),Ce=mn({thread:se,mailboxId:e,accountId:Z,onAfterOptimisticRemove:re}),{draftsMailboxId:Te}=Z0(Z),_=Te!==void 0&&Te===e,{archiveMailboxId:le}=J0(Z),ue=If(),{requestCompose:ve}=Ce,q=l.useCallback(()=>{ve("reply")},[ve]),he=l.useCallback(()=>{ve("reply_all")},[ve]),ne=l.useCallback(()=>{ve("forward")},[ve]),{state:ee,openCompose:je,closeCompose:Le}=Jt(),Be=l.useCallback(()=>{je({mode:"new"})},[je]),Xe=Ue({...dr(),onError:te=>{pe(ds("Couldn't discard draft","The draft wasn't deleted.",te))}}),He=l.useCallback(()=>{const te=ee.outboxMessageId;te&&(Xe.mutate({path:{outboxMessageId:te}}),Oe.invalidateQueries({queryKey:ao()}),Le())},[ee.outboxMessageId,Xe,Oe,Le]),Me=l.useCallback(()=>{n({to:"/mail/$mailboxId",params:{mailboxId:e},search:te=>({...te,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,n]),et=l.useCallback(te=>te?ue(te):[],[ue]),{toggleStar:Ke}=zo({threadId:K?.threadId??"",mailboxId:e}),{toggleReadFor:lt}=Ar({mailboxId:e,accountId:Z}),{junkMailboxId:tt}=kn(Z),zt=tt!=null&&tt===e,Rt=Lr(tt,e),{candidates:ns}=Lj(zt?tt:void 0),{moveMessages:bs}=Ds({mailboxId:e,threadId:K?.threadId,accountId:Z,onAfterOptimisticRemove:re}),{deleteMessages:rt}=ms({mailboxId:e,threadId:K?.threadId,onAfterOptimisticRemove:re}),{addressId:Tt,address:bt}=kf(K),{updateFlags:vt}=jf({addressId:Tt,senderEmail:K?.fromEmail??void 0}),ht=l.useCallback(()=>t||!Ie?!1:(n({to:"/mail/$mailboxId",params:{mailboxId:e},search:te=>({...te,selectedMessageId:Ie})}),!0),[t,Ie,e,n]),rs=l.useCallback(()=>{ht()||se&&ve("reply")},[ht,se,ve]),qs=l.useCallback(()=>{ht()||se&&ve("reply_all")},[ht,se,ve]),En=l.useCallback(()=>{ht()||se&&ve("forward")},[ht,se,ve]),ct=l.useCallback(()=>et(K),[et,K]),U=l.useCallback(()=>{if(X.current?.requestVerb("delete"))return;const te=ct();te.length>0&&rt(te)},[X,ct,rt]),Y=l.useCallback(()=>{if(X.current?.requestVerb("junk")||!Rt)return;const te=ct();te.length!==0&&(Ef(i,{count:te.length,senderTrust:K?.senderTrust??"unknown",wasRescuable:K?Nf(K):!1}),bs(te,Rt))},[X,Rt,ct,bs,i,K]),Ae=l.useCallback(()=>{if(qe.length>0){const te=!(K?.hasStars??!1),ut=new Set(qe);for(const at of $)ut.has(at.messageId)&&at.hasStars!==te&&Ke(at.messageId,at.hasStars);return}K&&Ke(K.messageId,K.hasStars)},[qe,$,K,Ke]),pt=l.useCallback(()=>{if(X.current?.requestVerb("markRead"))return;const te=ct();if(te.length===0)return;const ut=!(K?.isRead??!1);lt(te,ut)},[X,ct,K,lt]),yt=l.useCallback(()=>{if(!Tt)return;const te=bt?.flags?.muted?.value!==!0;vt({muted:{value:te}})},[Tt,bt,vt]),vs=l.useCallback(()=>{if(!Tt)return;const te=bt?.flags?.vip?.value!==!0;vt({vip:{value:te}})},[Tt,bt,vt]),wt=l.useCallback(()=>{d||f()},[d,f]),as=l.useCallback(te=>{n({to:te})},[n]),In=_?"drafts":le===e?"archive":tt===e?"junk":"inbox",ys=l.useRef("");l.useEffect(()=>{const te=ys.current;ys.current=x,x.length>0&&te.length===0&&i.recordEvent("search.submitted",{mailboxType:In})},[x,In,i]);const Br=_&&ee.isOpen&&!!ee.outboxMessageId&&!se,{goBack:Ur,nextMessageId:Hs,previousMessageId:Kr}=ni({context:ze,orderedIds:$.map(te=>te.messageId),selectedMessageId:t,enabled:!ee.isOpen,onClose:Me,handlers:{reply:rs,replyAll:qs,forward:En,delete:U,toggleStar:Ae,toggleRead:pt,muteSender:yt,blockSender:wt,vipSender:vs,markJunk:Y,toggleIntelligence:se?f:void 0,compose:Be,goBrief:()=>as("/mail"),goInbox:()=>as("/mail"),goSent:()=>as("/mail"),goFlagged:()=>as("/mail/flagged"),goSettings:()=>as("/settings")}});$o({enabled:ee.isOpen,bindings:[{key:"Escape",handler:Le,preventDefault:!0}]});const qr={mailboxId:e,selectedMessageId:t,selectedThread:se,conversation:Pe,threads:$,isLoading:I,isError:D,error:T,mailboxAccountId:Z,mailboxName:ae,unreadCount:be,isDraftsMailbox:_,isSpamFolder:zt,rescueCandidates:ns,filterCategory:S,filterAttributes:w,onSelectFilterCategory:me,onToggleFilterAttribute:ge,onClearFilters:Se,listFilter:H,intelligenceOpen:d,onToggleIntelligence:f,handleDeselectIfRemoved:re,searchPredicate:p&&P.length===0?E:void 0,onDeleteMessages:oe,onMoveMessages:fe,isDeleting:ie,isMoving:B,onLoadMore:N,hasMore:V,isLoadingMore:J,onTriageContextChange:Ze,listCommandsRef:X,onRetry:()=>F(),toolbarComposeRequest:Ce.composeRequest,onToolbarReply:q,onToolbarReplyAll:he,onToolbarForward:ne,onClearComposeRequest:Ce.clearComposeRequest,onToolbarDelete:Ce.deleteThread,onToolbarStar:Ce.toggleStar,onToolbarDiscardDraft:He,onToolbarMove:Ce.moveThread,composeState:ee,closeCompose:Le,hasRemitDraftOpen:Br,onBack:Ur,nextMessageId:Hs,previousMessageId:Kr};return r.jsx(Bf.Provider,{value:qr,children:s})}function Uf(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:n,isError:a,error:o,onDeleteMessages:i,onMoveMessages:c,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,mailboxAccountId:v,mailboxName:x,unreadCount:p,isDraftsMailbox:b,isSpamFolder:y,rescueCandidates:S,onTriageContextChange:g,listCommandsRef:w,onRetry:C,filterCategory:R,filterAttributes:O,onSelectFilterCategory:k,onToggleFilterAttribute:M,onClearFilters:P,listFilter:E,searchPredicate:L}=zr(),{searchQuery:A,searchInput:j,accounts:I,resultFolderIndex:D}=Fe(),T=Nn(),F=Ye(),N=x??"Inbox",V=l.useMemo(()=>Nu(),[]),J=l.useMemo(()=>v?[v]:[],[v]),{hasNewMail:re}=Rr(),{state:oe,errorMessage:ie,refresh:Z}=Oo(J,{onSettled:C}),ae=l.useMemo(()=>r.jsx(jo,{state:oe,onRefresh:Z,label:`Refresh ${N}`,errorMessage:ie,hasUpdate:re(J)}),[oe,Z,N,ie,re,J]),fe=l.useMemo(()=>s.map(xe=>BS(xe,D)),[s,D]),{hits:B,isLoading:$}=tf({mailboxId:e,filterCategory:R}),me=l.useMemo(()=>rf(B,s.map(xe=>xe.threadId),D),[B,s,D]),ge=l.useCallback(xe=>F({to:"/mail/$mailboxId",params:{mailboxId:xe.mailboxId??e},search:ke=>({...ke,q:j||void 0,selectedMessageId:xe.id,selectedThreadId:xe.threadId})}),[e,F,j]);if(b&&v)return r.jsx(Jk,{mailboxId:e,accountId:v,selectedMessageId:t,imapThreads:s,title:x??"Drafts",unreadCount:p??void 0});const Se=r.jsx(Tj,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:n,isError:a,error:o,onRetry:C,searchQuery:A,searchPredicate:L,onDeleteMessages:i,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,accountId:v,listTitle:N,listFilter:E,listScopeLabel:N,hideHeader:!0,onTriageContextChange:g,commandsRef:w}),Ne=I[0]?.accountId,H=T==="phone"&&Ne?r.jsx(Oj,{accountId:Ne,children:Se}):Se,Ee=y&&S.length>0&&v?r.jsx(Dj,{accountId:v,currentMailboxId:e,candidates:S,onMove:c,children:H}):H;return r.jsx(Of,{title:N,unreadCount:p,preset:V,selectedCategory:R,activeFilters:O,onSelectCategory:k,onToggleFilter:M,onClearFilters:P,searchResults:fe,searchLoading:n,relatedResults:me,relatedLoading:$,onSelectSearchResult:ge,searchResultsInBody:!0,refreshControl:ae,children:Ee})}function nN(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:c,onToolbarReply:u,onToolbarReplyAll:m,onToolbarForward:d,onClearComposeRequest:f,onToolbarDelete:h,onToolbarStar:v,onToolbarDiscardDraft:x,onToolbarMove:p,composeState:b}=zr(),y=ps()?.showIntelligencePane??!1,S=!!n,g=y&&S,w=b.isOpen&&!n?r.jsx(Lf,{}):n?r.jsx(Bs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onOpenIntelligence:n.authenticity?.dkimMismatch?i:void 0,composeRequest:c,onComposeClose:f}):r.jsx(zs,{});return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(ti,{hasThread:S,intelligenceOpen:g&&o,canToggleIntelligence:g,onToggleIntelligence:i,onReply:S?u:void 0,onReplyAll:S?m:void 0,onForward:S?d:void 0,canDelete:S||a,onDelete:S?h:a?x:void 0,onToggleStar:S?v:void 0,isStarred:s?.hasStars,moveContext:S&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:w})]})}function rN(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:n,handleDeselectIfRemoved:a}=zr();return r.jsx(Ks,{onClose:n,thread:s,mailboxId:e,accountId:t,onAfterOptimisticRemove:a})}function aN(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,intelligenceOpen:a,onToggleIntelligence:o,onBack:i,nextMessageId:c,previousMessageId:u,composeState:m,handleDeselectIfRemoved:d}=zr(),f=Ye();if(n){const h=v=>f({to:"/mail/$mailboxId",params:{mailboxId:e},search:x=>({...x,selectedMessageId:v,selectedThreadId:void 0})});return r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onBack:i,onOpenIntelligence:o,onSwipeNext:c?()=>h(c):void 0,onSwipePrevious:u?()=>h(u):void 0,mobileIntelligenceOpen:a}),r.jsx(Lo,{isOpen:a,onClose:o,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:o,thread:s,mailboxId:e,accountId:t,hideCloseButton:!0,onAfterOptimisticRemove:d})})]})}return m.isOpen?r.jsx("div",{className:"h-full",children:r.jsx(Lf,{})}):r.jsx(Uf,{})}const sn=Object.assign(sN,{List:Uf,Reading:nN,Intelligence:rN,Phone:aN}),Kf=e=>e==="failed"||e==="blocked",qf=e=>e!=="draft"&&e!=="sent",oi="remit.savedSearches",oN=25;function ar(){try{const e=localStorage.getItem(oi);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function iN(e){const t=e.trim();if(!t)return ar();const s=[t,...ar().filter(n=>n!==t)].slice(0,oN);try{localStorage.setItem(oi,JSON.stringify(s))}catch{return s}return s}function lN(e){const t=ar().filter(s=>s!==e);try{localStorage.setItem(oi,JSON.stringify(t))}catch{return t}return t}const sc=e=>/^\d/.test(e),cN=(e,t)=>{const s=sc(e),n=sc(t);return s&&!n?-1:!s&&n?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function uN(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)=>cN(Yn(o,void 0,s),Yn(i,void 0,s))),{system:n,labels:a}}function dN(e,t,s){const n=wh(t)&&e.unseenCount>0;return{id:e.mailboxId,name:Yn(e,t,s),unseen:n?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function fN(){const e=Ir(),t=Ya({strict:!1});return e.pathname.startsWith("/settings")?"settings":e.pathname.startsWith("/mail/outbox")?"outbox":e.pathname.startsWith("/mail/flagged")?"flagged":t.mailboxId?t.mailboxId:e.pathname==="/mail"||e.pathname==="/mail/"?"brief":""}function nc({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const n=De(),a=Ye(),o=fN(),{searchInput:i,onSearchChange:c}=Fe(),[u,m]=l.useState(ar),{t:d}=Xa("mail",{useSuspense:!1}),f=l.useCallback((k,M)=>d(k,{defaultValue:M}),[d]),h=mt({queries:e.map(k=>({...it({path:{accountId:k.accountId}}),staleTime:1/0}))}),{data:v}=we(cr()),x=l.useMemo(()=>(v?.items??[]).filter(k=>qf(k.status)).length,[v?.items]),p=l.useMemo(()=>e.map((k,M)=>{const P=h[M],E=P?.data?.items??[],L=Qa(k.folderAppointments),{system:A,labels:j}=uN(E,L,f),I=P?.isError?"error":P?.isLoading?"loading":"ready";return{id:k.accountId,label:k.email,email:k.email,muted:!!k.muted,outboxPending:x,status:I,onRetry:()=>P?.refetch(),mailboxes:[...A,...j].map(D=>dN(D,L.get(D.mailboxId),f))}}),[e,h,x,f]),b=k=>{n.invalidateQueries({queryKey:fr({path:{mailboxId:k},query:{order:"desc"}})})},y=({navId:k,className:M,ariaLabel:P,title:E,children:L,onClick:A})=>k==="brief"?r.jsx(qt,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>A?.(),className:M,"aria-label":P,title:E,children:L}):k==="outbox"?r.jsx(qt,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>A?.(),className:M,"aria-label":P,title:E,children:L}):k==="flagged"?r.jsx(qt,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>A?.(),className:M,"aria-label":P,title:E,children:L}):k==="settings"?r.jsx(qt,{to:"/settings/accounts",onClick:()=>A?.(),className:M,"aria-label":P,title:E,children:L}):r.jsx(qt,{to:"/mail/$mailboxId",params:{mailboxId:k},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{b(k),A?.()},className:M,"aria-label":P,title:E,children:L}),S=()=>{c(""),t?.()},g=i.trim(),w=g.length>0&&!u.includes(g)?g:void 0,C=l.useCallback(()=>{w&&m(iN(w))},[w]),R=l.useCallback(k=>{m(lN(k))},[]),O=l.useCallback(k=>{c(k),a({to:"/mail",search:{q:k,selectedMessageId:void 0}}),t?.()},[c,a,t]);return r.jsx(sx,{accounts:p,selectedNavId:o,onSelectNav:S,linkComponent:y,variant:s,savedSearches:u,saveableQuery:w,onSaveCurrentSearch:C,onSelectSavedSearch:O,onRemoveSavedSearch:R})}function mN(){return r.jsxs("button",{type:"button",onClick:Sc,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(Vc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]})}function hN({accounts:e,onMailboxSelect:t}){return ps()?.showNavPane??!0?r.jsx(nc,{accounts:e}):r.jsxs("div",{className:"flex h-full flex-col",children:[r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(nc,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),r.jsxs("div",{className:"border-t border-line px-2 py-2",children:[r.jsxs(qt,{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(eu,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),r.jsx(mN,{}),r.jsx(ed,{children:({signOut:a})=>r.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[r.jsx(Xc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function pN(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 gN(e){return e.tokens.length>0&&e.freeText.trim().length===0}const Hf={queued:{icon:oo,label:"Queued",className:"text-warning"},sending:{icon:hs,label:"Sending…",className:"text-accent-2"},sent:{icon:go,label:"Sent",className:"text-positive"},failed:{icon:Pt,label:"Failed",className:"text-danger"},blocked:{icon:Ka,label:"Blocked",className:"text-warning"}},xN=e=>Uh(e).toDateString()===new Date().toDateString()?Xn(e,{hour:"numeric",minute:"2-digit"}):Xn(e,{month:"short",day:"numeric"}),rc=e=>Xn(e,{dateStyle:"medium",timeStyle:"short"}),bN=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},Wf=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",Vf=l.createContext(null);function ii(){const e=l.useContext(Vf);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function vN({children:e}){const t=Ye(),{selectedOutboxMessageId:s}=As({strict:!1}),{data:n,isLoading:a}=we(cr()),{searchQuery:o}=Fe(),i=xs(),c=Qo(o),u=Us(c,i),m=c.length>0,d=gN(u),f=l.useMemo(()=>d?[]:(n?.items??[]).filter(p=>qf(p.status)).filter(p=>pN(p,u.freeText)),[n,u.freeText,d]),h=l.useMemo(()=>f.find(p=>p.outboxMessageId===s),[f,s]),v=l.useCallback(p=>{t({to:"/mail/outbox",search:b=>({...b,selectedOutboxMessageId:p})})},[t]),x={messages:f,hasQuery:m,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:v};return r.jsx(Vf.Provider,{value:x,children:e})}function Qf({message:e,isSelected:t,onSelect:s}){const n=De(),{openCompose:a}=Jt(),{pushError:o}=nt(),i=l.useCallback(()=>{n.invalidateQueries({queryKey:ao()})},[n]),c=Ue({...kc(),onSuccess:i,onError:f=>{o(ds("Couldn't resend message","The message wasn't sent.",f))}}),u=Ue({...dr(),onSuccess:i,onError:f=>{o(ds("Couldn't delete message","The message wasn't deleted.",f))}}),m=e.status;if(!Hf[m])return null;const d=Kf(e.status);return r.jsx(Kx,{recipients:bN(e),subject:e.subject||"",time:xN(e.sentAt??e.updatedAt),status:m,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:m==="failed"?()=>c.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:c.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function Gf({message:e,onBack:t}){const s=e.status,n=Hf[s],a=n?.icon??pn,o=e.sentAt?rc(e.sentAt):rc(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(Ua,{className:"size-4"}),r.jsx("span",{children:"Back"})]}),r.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),r.jsxs("div",{className:"space-y-1 text-sm",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),r.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),r.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),r.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),r.jsx("span",{className:"text-fg",children:o})]}),n&&r.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[r.jsx(a,{className:Ve("size-4",n.className,s==="sending"&&"animate-spin")}),r.jsx("span",{className:Ve("text-xs font-medium",n.className),children:n.label}),Kf(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(Qd,{html:e.htmlBody,text:e.textBody})})]})}function yN(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,onSelectMessage:o}=ii(),i=l.useRef(null);return or({containerRef:i,itemSelector:Qn}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(zs,{message:Wf(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(ri,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(c=>r.jsx(Qf,{message:c,isSelected:a===c.outboxMessageId,onSelect:()=>o(c.outboxMessageId)},c.outboxMessageId))})]})}function wN(){const{selectedMessage:e}=ii();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(Gf,{message:e}):r.jsx(zs,{message:"Select a message to read",showHints:!1})})]})}function SN(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=ii(),c=l.useRef(null);return or({containerRef:c,itemSelector:Qn}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?r.jsx(Gf,{message:o,onBack:()=>i(void 0)}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(zs,{message:Wf(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(ri,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:c,className:"flex-1 overflow-y-auto",children:e.map(u=>r.jsx(Qf,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const zn=Object.assign(vN,{List:yN,Reading:wN,Phone:SN}),CN=({isOpen:e,onClose:t})=>{const s=l.useCallback(n=>{n.key==="Escape"&&(n.preventDefault(),t())},[t]);return l.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx(Rc,{label:"Dismiss keyboard shortcuts",onDismiss:t,className:"backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",className:Ve("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),children:[r.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),r.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:r.jsx(Nt,{className:"size-5"})})]}),r.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:su.map(n=>r.jsxs("div",{children:[r.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:n.title}),r.jsx("div",{className:"space-y-2",children:n.hints.map(a=>r.jsxs("div",{className:"flex items-center justify-between gap-4",children:[r.jsx("span",{className:"text-sm",children:a.description}),r.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>r.jsxs(l.Fragment,{children:[i>0&&a.keys[0]==="g"&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),r.jsx(Is,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},n.title))}),r.jsx("div",{className:"mt-6 border-t border-line pt-4",children:r.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",r.jsx(Is,{children:"Esc"})," to close"]})})]})]}):null};function kN(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});return l.useMemo(()=>eC(t.map(s=>s.data?.items??[])),[t])}const jN=e=>e.map(t=>t.data?.items??[]);function NN(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0})),combine:jN});return l.useMemo(()=>Sh(e.map((s,n)=>({folderAppointments:s.folderAppointments,mailboxes:t[n]??[]}))),[e,t])}var Bn={exports:{}},ac;function EN(){if(ac)return Bn.exports;ac=1;const e=(t,s,n)=>new Promise((a,o)=>{if(n=Object.assign({concurrency:1/0},n),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=n;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const c=[],u=t[Symbol.iterator]();let m=!1,d=!1,f=0,h=0;const v=()=>{if(m)return;const x=u.next(),p=h;if(h++,x.done){d=!0,f===0&&a(c);return}f++,Promise.resolve(x.value).then(b=>s(b,p)).then(b=>{c[p]=b,f--,v()},b=>{m=!0,o(b)})};for(let x=0;x<i&&(v(),!d);x++);});return Bn.exports=e,Bn.exports.default=e,Bn.exports}var IN=EN();const RN=Ch(IN),TN=900*1e3,MN=300,AN=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},ON=60*1e3,DN=e=>Math.max(AN(e,MN)*1e3,ON),Vn=DN(kh().mailboxPollIntervalSeconds),PN=5,_a=new Set,LN=(e,t,s=TN)=>e.filter(n=>{const a=n.lastSyncAt;return a==null?!0:t-a>s}).map(n=>n.accountId),FN=(e,t,s=Vn)=>e-t>=s,$N=(e,t)=>e.filter(s=>!t.has(s)),oc=(e,t)=>{if(_a.delete(e),wc(t,{softError:!0})){Ga(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},ic=(e,t)=>yc({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:Ft({path:{accountId:e}})})}),_N=e=>{const t=De(),s=l.useRef(e);s.current=e;const n=e.map(a=>a.accountId).join(",");l.useEffect(()=>{const a=Date.now(),i=LN(s.current,a).filter(c=>!_a.has(c));if(i.length!==0)for(const c of i)_a.add(c),ic(c,t).catch(u=>{oc(c,u)})},[n,t]),l.useEffect(()=>{let a=Date.now(),o;const i=new Set,c=()=>{a=Date.now();const d=$N(s.current.map(f=>f.accountId),i);for(const f of d)i.add(f);RN(d,f=>ic(f,t).catch(h=>{oc(f,h)}).finally(()=>{i.delete(f)}),{concurrency:PN})},u=()=>{if(document.visibilityState==="visible"){c(),o=setTimeout(u,Vn);return}},m=()=>{document.visibilityState==="visible"&&FN(Date.now(),a)&&(o!==void 0&&clearTimeout(o),c(),o=setTimeout(u,Vn))};return o=setTimeout(u,Vn),document.addEventListener("visibilitychange",m),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",m)}},[n,t])};function zN(e,t,s){if(e!==t)return s}function BN(e,t){return e===""?"":t}function UN(e,t,s){return t!==e?!1:t!==s}function KN(){const{q:e=""}=As({from:"/mail"}),t=Ye(),s=Nn(),n=Xd(s),[a,o]=l.useState(!1),[i,c]=l.useState(!1),[u,m]=l.useState(!1),d=l.useCallback($=>{m($),tc($)},[]),[f,h]=l.useState(e),v=gr(f,200),x=BN(f,v),p=l.useRef(e);p.current=e;const b=Ot({select:$=>n0($.matches)}),[y,S]=l.useState(b);if(y!==b){const $=zN(y,b,e);S(b),$!==void 0&&h($)}l.useEffect(()=>{UN(f,x,p.current)&&t({to:".",search:$=>{const me=$.q===x;return{...$,q:x||void 0,...x&&!me?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[f,x,t]);const{data:g,isLoading:w,isError:C,error:R,refetch:O}=we({...$t(),staleTime:1/0}),k=!!(g&&(g.accounts?.length??0)===0);l.useEffect(()=>{k&&t({to:"/onboarding",replace:!0})},[k,t]),$o({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const M=l.useCallback($=>{h($)},[]),P=l.useCallback(()=>{h("")},[]),E=l.useCallback(()=>{h("")},[]),L=l.useCallback(()=>{m($=>{const me=!$;return tc(me),me})},[]),A=g?.accounts??[],j=l.useMemo(()=>A.map($=>$.accountId),[A]),I=kN(A),D=NN(A),T=l.useMemo(()=>ZS(A),[A]),F=Ot({select:$=>$.matches.find(ge=>"mailboxId"in ge.params)?.params.mailboxId}),{selectedMessageId:N}=As({strict:!1}),V=Ot({select:$=>Po($.matches)}),J=Ot({select:$=>vn($.matches)}),re=Ot({select:$=>Tr($.matches)});_N(A);const oe=l.useCallback(()=>{c(!1)},[]),ie={accounts:A,mailboxNameIndex:I,accountNameIndex:T,resultFolderIndex:D,searchQuery:x,searchInput:f,searchViewKey:b,onSearchChange:M,onSearchClear:P,onSearchClearQuery:E,intelligenceOpen:u,onToggleIntelligence:L,onSetIntelligenceOpen:d},Z=r.jsx(hN,{accounts:A,onMailboxSelect:oe}),ae=n?r.jsx(Uy,{accounts:A}):void 0,fe=n?void 0:r.jsx(c0,{accounts:A}),B={navOpen:i,onOpenNav:()=>c(!0),onCloseNav:()=>c(!1)};return r.jsx(jh.Provider,{value:ie,children:r.jsxs(Yy,{accountIds:j,children:[C?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:r.jsx(ts,{title:"Couldn't load your account",error:R,onRetry:()=>{O()}})}):V?r.jsx(Zs,{selectedMessageId:N,children:n?r.jsx(Bt,{nav:Z,list:r.jsx(Zs.Phone,{}),intelligenceOpen:u,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B}):r.jsx(Bt,{nav:Z,topBar:fe,list:r.jsx(Zs.List,{}),reading:r.jsx(Zs.Reading,{}),intelligence:r.jsx(Zs.Intelligence,{}),intelligenceOpen:u,hasThread:!!N,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B})}):J?r.jsx(en,{selectedMessageId:N,children:n?r.jsx(Bt,{nav:Z,list:r.jsx(en.Phone,{}),intelligenceOpen:u,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B}):r.jsx(Bt,{nav:Z,topBar:fe,list:r.jsx(en.List,{}),reading:r.jsx(en.Reading,{}),intelligence:r.jsx(en.Intelligence,{}),intelligenceOpen:u,hasThread:!!N,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B})}):F?r.jsx(sn,{mailboxId:F,selectedMessageId:N,children:n?r.jsx(Bt,{nav:Z,list:r.jsx(sn.Phone,{}),intelligenceOpen:u,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B}):r.jsx(Bt,{nav:Z,topBar:fe,list:r.jsx(sn.List,{}),reading:r.jsx(sn.Reading,{}),intelligence:r.jsx(sn.Intelligence,{}),intelligenceOpen:u,hasThread:!!N,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B})}):re?r.jsx(zn,{children:n?r.jsx(Bt,{nav:Z,list:r.jsx(zn.Phone,{}),intelligenceOpen:!1,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B}):r.jsx(Bt,{nav:Z,topBar:fe,list:r.jsx(zn.List,{}),reading:r.jsx(zn.Reading,{}),intelligenceOpen:!1,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B})}):r.jsx(At,{}),r.jsx(CN,{isOpen:a,onClose:()=>o(!1)}),r.jsx(Nh,{})]})})}const u1=Object.freeze(Object.defineProperty({__proto__:null,component:KN,useMailContext:Fe},Symbol.toStringTag,{value:"Module"}));export{ob as E,Lp as U,l1 as a,c1 as c,u1 as m,i1 as s};
|
|
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 yw(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function ww(){return Wo(/^Mac/)}function Sw(){return Wo(/^iPhone/)}function Al(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Cw(){return Wo(/^iPad/)||ww()&&navigator.maxTouchPoints>1}function Ld(){return Sw()||Cw()}function Wo(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const kw=24,jw=typeof window<"u"?l.useLayoutEffect:l.useEffect;function Ol(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const ia=typeof document<"u"&&window.visualViewport;function Dl(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Fd(e){for(Dl(e)&&(e=e.parentElement);e&&!Dl(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Nw=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Fn=0,la;function Ew(e={}){let{isDisabled:t}=e;jw(()=>{if(!t)return Fn++,Fn===1&&Ld()&&(la=Iw()),()=>{Fn--,Fn===0&&la?.()}},[t])}function Iw(){let e,t=0,s=f=>{e=Fd(f.target),!(e===document.documentElement&&e===document.body)&&(t=f.changedTouches[0].pageY)},n=f=>{if(!e||e===document.documentElement||e===document.body){f.preventDefault();return}let h=f.changedTouches[0].pageY,v=e.scrollTop,x=e.scrollHeight-e.clientHeight;x!==0&&((v<=0&&h>t||v>=x&&h<t)&&f.preventDefault(),t=h)},a=f=>{let h=f.target;Aa(h)&&h!==document.activeElement&&(f.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=f=>{let h=f.target;Aa(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",ia&&(ia.height<window.innerHeight?requestAnimationFrame(()=>{Pl(h)}):ia.addEventListener("resize",()=>Pl(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},c=window.pageXOffset,u=window.pageYOffset,m=Ol(Rw(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=Ol(Xs(document,"touchstart",s,{passive:!1,capture:!0}),Xs(document,"touchmove",n,{passive:!1,capture:!0}),Xs(document,"touchend",a,{passive:!1,capture:!0}),Xs(document,"focus",o,!0),Xs(window,"scroll",i));return()=>{m(),d(),window.scrollTo(c,u)}}function Rw(e,t,s){let n=e.style[t];return e.style[t]=s,()=>{e.style[t]=n}}function Xs(e,t,s,n){return e.addEventListener(t,s,n),()=>{e.removeEventListener(t,s,n)}}function Pl(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=Fd(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+kw;o>i&&(s.scrollTop+=a-n)}e=s.parentElement}}function Aa(e){return e instanceof HTMLInputElement&&!Nw.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function Tw(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function Mw(...e){return t=>e.forEach(s=>Tw(s,t))}function $d(...e){return l.useCallback(Mw(...e),e)}const _d=new WeakMap;function Ge(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let n={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}n[a]=e.style[a],e.style[a]=o}),!s&&_d.set(e,n)}function Aw(e,t){if(!e||!(e instanceof HTMLElement))return;let s=_d.get(e);s&&(e.style[t]=s[t])}const We=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function $n(e,t){if(!e)return null;const s=window.getComputedStyle(e),n=s.transform||s.webkitTransform||s.mozTransform;let a=n.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[We(t)?13:12]):(a=n.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[We(t)?5:4]):null)}function Ow(e){return 8*(Math.log(e+1)-2)}function ca(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function Dw(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const $e={DURATION:.5,EASE:[.32,.72,0,1]},zd=.4,Pw=.25,Lw=100,Bd=8,is=16,Oa=26,ua="vaul-dragging";function Ud(e){const t=W.useRef(e);return W.useEffect(()=>{t.current=e}),W.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function Fw({defaultProp:e,onChange:t}){const s=W.useState(e),[n]=s,a=W.useRef(n),o=Ud(t);return W.useEffect(()=>{a.current!==n&&(o(n),a.current=n)},[n,a,o]),s}function Kd({prop:e,defaultProp:t,onChange:s=()=>{}}){const[n,a]=Fw({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:n,c=Ud(s),u=W.useCallback(m=>{if(o){const f=typeof m=="function"?m(e):m;f!==e&&c(f)}else a(m)},[o,e,a,c]);return[i,u]}function $w({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:n,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:c="bottom",container:u,snapToSequentialPoint:m}){const[d,f]=Kd({prop:e,defaultProp:s?.[0],onChange:t}),[h,v]=W.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);W.useEffect(()=>{function O(){v({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]);const x=W.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=W.useMemo(()=>{var O;return(O=s?.findIndex(k=>k===d))!=null?O:null},[s,d]),b=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,y=W.useMemo(()=>{const O=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var k;return(k=s?.map(M=>{const P=typeof M=="string";let E=0;if(P&&(E=parseInt(M,10)),We(c)){const A=P?E:h?M*O.height:0;return h?c==="bottom"?O.height-A:-O.height+A:A}const L=P?E:h?M*O.width:0;return h?c==="right"?O.width-L:-O.width+L:L}))!=null?k:[]},[s,h,u]),S=W.useMemo(()=>p!==null?y?.[p]:null,[y,p]),g=W.useCallback(O=>{var k;const M=(k=y?.findIndex(P=>P===O))!=null?k:null;i(M),Ge(n.current,{transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,transform:We(c)?`translate3d(0, ${O}px, 0)`:`translate3d(${O}px, 0, 0)`}),y&&M!==y.length-1&&o!==void 0&&M!==o&&M<o?Ge(a.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,opacity:"0"}):Ge(a.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,opacity:"1"}),f(s?.[Math.max(M,0)])},[n.current,s,y,o,a,f]);W.useEffect(()=>{if(d||e){var O;const k=(O=s?.findIndex(M=>M===e||M===d))!=null?O:-1;y&&k!==-1&&typeof y[k]=="number"&&g(y[k])}},[d,e,s,y,g]);function w({draggedDistance:O,closeDrawer:k,velocity:M,dismissible:P}){if(o===void 0)return;const E=c==="bottom"||c==="right"?(S??0)-O:(S??0)+O,L=p===o-1,A=p===0,j=O>0;if(L&&Ge(a.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`}),!m&&M>2&&!j){P?k():g(y[0]);return}if(!m&&M>2&&j&&y&&s){g(y[s.length-1]);return}const I=y?.reduce((T,F)=>typeof T!="number"||typeof F!="number"?T:Math.abs(F-E)<Math.abs(T-E)?F:T),D=We(c)?window.innerHeight:window.innerWidth;if(M>zd&&Math.abs(O)<D*.4){const T=j?1:-1;if(T>0&&x&&s){g(y[s.length-1]);return}if(A&&T<0&&P&&k(),p===null)return;g(y[p+T]);return}g(I)}function C({draggedDistance:O}){if(S===null)return;const k=c==="bottom"||c==="right"?S-O:S+O;(c==="bottom"||c==="right")&&k<y[y.length-1]||(c==="top"||c==="left")&&k>y[y.length-1]||Ge(n.current,{transform:We(c)?`translate3d(0, ${k}px, 0)`:`translate3d(${k}px, 0, 0)`})}function R(O,k){if(!s||typeof p!="number"||!y||o===void 0)return null;const M=p===o-1;if(p>=o&&k)return 0;if(M&&!k)return 1;if(!b&&!M)return null;const E=M?p+1:p-1,L=M?y[E]-y[E-1]:y[E+1]-y[E],A=O/Math.abs(L);return M?1-A:A}return{isLastSnapPoint:x,activeSnapPoint:d,shouldFade:b,getPercentageDragged:R,setActiveSnapPoint:f,activeSnapPointIndex:p,onRelease:w,onDrag:C,snapPointsOffset:y}}const _w=()=>()=>{};function zw(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:n,noBodyStyles:a}=jn(),o=W.useRef(null),i=l.useMemo(()=>document.body.style.backgroundColor,[]);function c(){return(window.innerWidth-Oa)/window.innerWidth}W.useEffect(()=>{if(t&&s){o.current&&clearTimeout(o.current);const u=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!u)return;Dw(n&&!a?ca(document.body,{background:"black"}):_w,ca(u,{transformOrigin:We(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${$e.DURATION}s`,transitionTimingFunction:`cubic-bezier(${$e.EASE.join(",")})`}));const m=ca(u,{borderRadius:`${Bd}px`,overflow:"hidden",...We(e)?{transform:`scale(${c()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${c()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{m(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},$e.DURATION*1e3)}}},[t,s,i])}let Js=null;function Bw({isOpen:e,modal:t,nested:s,hasBeenOpened:n,preventScrollRestoration:a,noBodyStyles:o}){const[i,c]=W.useState(()=>typeof window<"u"?window.location.href:""),u=W.useRef(0),m=W.useCallback(()=>{if(Al()&&Js===null&&e&&!o){Js={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:f,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-f}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const v=h-window.innerHeight;v&&u.current>=h&&(document.body.style.top=`${-(u.current+v)}px`)}),300)}},[e]),d=W.useCallback(()=>{if(Al()&&Js!==null&&!o){const f=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Js),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){c(window.location.href);return}window.scrollTo(h,f)}),Js=null}},[i]);return W.useEffect(()=>{function f(){u.current=window.scrollY}return f(),window.addEventListener("scroll",f),()=>{window.removeEventListener("scroll",f)}},[]),W.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),W.useEffect(()=>{s||!n||(e?(!window.matchMedia("(display-mode: standalone)").matches&&m(),t||window.setTimeout(()=>{d()},500)):d())},[e,n,i,t,s,m,d]),{restorePositionSetting:d}}function Uw({open:e,onOpenChange:t,children:s,onDrag:n,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:c=!0,closeThreshold:u=Pw,scrollLockTimeout:m=Lw,dismissible:d=!0,handleOnly:f=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:v,setActiveSnapPoint:x,fixed:p,modal:b=!0,onClose:y,nested:S,noBodyStyles:g=!1,direction:w="bottom",defaultOpen:C=!1,disablePreventScroll:R=!0,snapToSequentialPoint:O=!1,preventScrollRestoration:k=!1,repositionInputs:M=!0,onAnimationEnd:P,container:E,autoFocus:L=!1}){var A,j;const[I=!1,D]=Kd({defaultProp:C,prop:e,onChange:q=>{t?.(q),!q&&!S&&K(),setTimeout(()=>{P?.(q)},$e.DURATION*1e3),q&&!b&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),q||(document.body.style.pointerEvents="auto")}}),[T,F]=W.useState(!1),[N,V]=W.useState(!1),[J,re]=W.useState(!1),oe=W.useRef(null),ie=W.useRef(null),Z=W.useRef(null),ae=W.useRef(null),fe=W.useRef(null),B=W.useRef(!1),$=W.useRef(null),me=W.useRef(0),ge=W.useRef(!1),Se=W.useRef(!C),Ne=W.useRef(0),H=W.useRef(null),Ee=W.useRef(((A=H.current)==null?void 0:A.getBoundingClientRect().height)||0),xe=W.useRef(((j=H.current)==null?void 0:j.getBoundingClientRect().width)||0),ke=W.useRef(0),de=W.useCallback(q=>{o&&q===X.length-1&&(ie.current=new Date)},[]),{activeSnapPoint:se,activeSnapPointIndex:ye,setActiveSnapPoint:Pe,onRelease:ze,snapPointsOffset:X,onDrag:Ze,shouldFade:Ie,getPercentageDragged:qe}=$w({snapPoints:o,activeSnapPointProp:v,setActiveSnapPointProp:x,drawerRef:H,fadeFromIndex:h,overlayRef:oe,onSnapPointChange:de,direction:w,container:E,snapToSequentialPoint:O});Ew({isDisabled:!I||N||!b||J||!T||!M||!R});const{restorePositionSetting:K}=Bw({isOpen:I,modal:b,nested:S??!1,hasBeenOpened:T,preventScrollRestoration:k,noBodyStyles:g});function Qe(){return(window.innerWidth-Oa)/window.innerWidth}function Re(q){var he,ne;!d&&!o||H.current&&!H.current.contains(q.target)||(Ee.current=((he=H.current)==null?void 0:he.getBoundingClientRect().height)||0,xe.current=((ne=H.current)==null?void 0:ne.getBoundingClientRect().width)||0,V(!0),Z.current=new Date,Ld()&&window.addEventListener("touchend",()=>B.current=!1,{once:!0}),q.target.setPointerCapture(q.pointerId),me.current=We(w)?q.pageY:q.pageX)}function be(q,he){var ne;let ee=q;const je=(ne=window.getSelection())==null?void 0:ne.toString(),Le=H.current?$n(H.current,w):null,Be=new Date;if(ee.tagName==="SELECT"||ee.hasAttribute("data-vaul-no-drag")||ee.closest("[data-vaul-no-drag]"))return!1;if(w==="right"||w==="left")return!0;if(ie.current&&Be.getTime()-ie.current.getTime()<500)return!1;if(Le!==null&&(w==="bottom"?Le>0:Le<0))return!0;if(je&&je.length>0)return!1;if(fe.current&&Be.getTime()-fe.current.getTime()<m&&Le===0||he)return fe.current=Be,!1;for(;ee;){if(ee.scrollHeight>ee.clientHeight){if(ee.scrollTop!==0)return fe.current=new Date,!1;if(ee.getAttribute("role")==="dialog")return!0}ee=ee.parentNode}return!0}function Oe(q){if(H.current&&N){const he=w==="bottom"||w==="right"?1:-1,ne=(me.current-(We(w)?q.pageY:q.pageX))*he,ee=ne>0,je=o&&!d&&!ee;if(je&&ye===0)return;const Le=Math.abs(ne),Be=document.querySelector("[data-vaul-drawer-wrapper]"),Xe=w==="bottom"||w==="top"?Ee.current:xe.current;let He=Le/Xe;const Me=qe(Le,ee);if(Me!==null&&(He=Me),je&&He>=1||!B.current&&!be(q.target,ee))return;if(H.current.classList.add(ua),B.current=!0,Ge(H.current,{transition:"none"}),Ge(oe.current,{transition:"none"}),o&&Ze({draggedDistance:ne}),ee&&!o){const Ke=Ow(ne),lt=Math.min(Ke*-1,0)*he;Ge(H.current,{transform:We(w)?`translate3d(0, ${lt}px, 0)`:`translate3d(${lt}px, 0, 0)`});return}const et=1-He;if((Ie||h&&ye===h-1)&&(n?.(q,He),Ge(oe.current,{opacity:`${et}`,transition:"none"},!0)),Be&&oe.current&&i){const Ke=Math.min(Qe()+He*(1-Qe()),1),lt=8-He*8,tt=Math.max(0,14-He*14);Ge(Be,{borderRadius:`${lt}px`,transform:We(w)?`scale(${Ke}) translate3d(0, ${tt}px, 0)`:`scale(${Ke}) translate3d(${tt}px, 0, 0)`,transition:"none"},!0)}if(!o){const Ke=Le*he;Ge(H.current,{transform:We(w)?`translate3d(0, ${Ke}px, 0)`:`translate3d(${Ke}px, 0, 0)`})}}}W.useEffect(()=>{window.requestAnimationFrame(()=>{Se.current=!0})},[]),W.useEffect(()=>{var q;function he(){if(!H.current||!M)return;const ne=document.activeElement;if(Aa(ne)||ge.current){var ee;const je=((ee=window.visualViewport)==null?void 0:ee.height)||0,Le=window.innerHeight;let Be=Le-je;const Xe=H.current.getBoundingClientRect().height||0,He=Xe>Le*.8;ke.current||(ke.current=Xe);const Me=H.current.getBoundingClientRect().top;if(Math.abs(Ne.current-Be)>60&&(ge.current=!ge.current),o&&o.length>0&&X&&ye){const et=X[ye]||0;Be+=et}if(Ne.current=Be,Xe>je||ge.current){const et=H.current.getBoundingClientRect().height;let Ke=et;et>je&&(Ke=je-(He?Me:Oa)),p?H.current.style.height=`${et-Math.max(Be,0)}px`:H.current.style.height=`${Math.max(Ke,je-Me)}px`}else yw()||(H.current.style.height=`${ke.current}px`);o&&o.length>0&&!ge.current?H.current.style.bottom="0px":H.current.style.bottom=`${Math.max(Be,0)}px`}}return(q=window.visualViewport)==null||q.addEventListener("resize",he),()=>{var ne;return(ne=window.visualViewport)==null?void 0:ne.removeEventListener("resize",he)}},[ye,o,X]);function pe(q){Te(),y?.(),q||D(!1),setTimeout(()=>{o&&Pe(o[0])},$e.DURATION*1e3)}function Ce(){if(!H.current)return;const q=document.querySelector("[data-vaul-drawer-wrapper]"),he=$n(H.current,w);Ge(H.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`}),Ge(oe.current,{transition:`opacity ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,opacity:"1"}),i&&he&&he>0&&I&&Ge(q,{borderRadius:`${Bd}px`,overflow:"hidden",...We(w)?{transform:`scale(${Qe()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${Qe()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${$e.DURATION}s`,transitionTimingFunction:`cubic-bezier(${$e.EASE.join(",")})`},!0)}function Te(){!N||!H.current||(H.current.classList.remove(ua),B.current=!1,V(!1),ae.current=new Date)}function _(q){if(!N||!H.current)return;H.current.classList.remove(ua),B.current=!1,V(!1),ae.current=new Date;const he=$n(H.current,w);if(!q||!be(q.target,!1)||!he||Number.isNaN(he)||Z.current===null)return;const ne=ae.current.getTime()-Z.current.getTime(),ee=me.current-(We(w)?q.pageY:q.pageX),je=Math.abs(ee)/ne;if(je>.05&&(re(!0),setTimeout(()=>{re(!1)},200)),o){ze({draggedDistance:ee*(w==="bottom"||w==="right"?1:-1),closeDrawer:pe,velocity:je,dismissible:d}),a?.(q,!0);return}if(w==="bottom"||w==="right"?ee>0:ee<0){Ce(),a?.(q,!0);return}if(je>zd){pe(),a?.(q,!1);return}var Le;const Be=Math.min((Le=H.current.getBoundingClientRect().height)!=null?Le:0,window.innerHeight);var Xe;const He=Math.min((Xe=H.current.getBoundingClientRect().width)!=null?Xe:0,window.innerWidth),Me=w==="left"||w==="right";if(Math.abs(he)>=(Me?He:Be)*u){pe(),a?.(q,!1);return}a?.(q,!0),Ce()}W.useEffect(()=>(I&&(Ge(document.documentElement,{scrollBehavior:"auto"}),ie.current=new Date),()=>{Aw(document.documentElement,"scrollBehavior")}),[I]);function le(q){const he=q?(window.innerWidth-is)/window.innerWidth:1,ne=q?-is:0;$.current&&window.clearTimeout($.current),Ge(H.current,{transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,transform:We(w)?`scale(${he}) translate3d(0, ${ne}px, 0)`:`scale(${he}) translate3d(${ne}px, 0, 0)`}),!q&&H.current&&($.current=setTimeout(()=>{const ee=$n(H.current,w);Ge(H.current,{transition:"none",transform:We(w)?`translate3d(0, ${ee}px, 0)`:`translate3d(${ee}px, 0, 0)`})},500))}function ue(q,he){if(he<0)return;const ne=(window.innerWidth-is)/window.innerWidth,ee=ne+he*(1-ne),je=-is+he*is;Ge(H.current,{transform:We(w)?`scale(${ee}) translate3d(0, ${je}px, 0)`:`scale(${ee}) translate3d(${je}px, 0, 0)`,transition:"none"})}function ve(q,he){const ne=We(w)?window.innerHeight:window.innerWidth,ee=he?(ne-is)/ne:1,je=he?-is:0;he&&Ge(H.current,{transition:`transform ${$e.DURATION}s cubic-bezier(${$e.EASE.join(",")})`,transform:We(w)?`scale(${ee}) translate3d(0, ${je}px, 0)`:`scale(${ee}) translate3d(${je}px, 0, 0)`})}return W.useEffect(()=>{b||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[b]),W.createElement(kd,{defaultOpen:C,onOpenChange:q=>{!d&&!q||(q?F(!0):pe(!0),D(q))},open:I},W.createElement(Pd.Provider,{value:{activeSnapPoint:se,snapPoints:o,setActiveSnapPoint:Pe,drawerRef:H,overlayRef:oe,onOpenChange:t,onPress:Re,onRelease:_,onDrag:Oe,dismissible:d,shouldAnimate:Se,handleOnly:f,isOpen:I,isDragging:N,shouldFade:Ie,closeDrawer:pe,onNestedDrag:ue,onNestedOpenChange:le,onNestedRelease:ve,keyboardIsOpen:ge,modal:b,snapPointsOffset:X,activeSnapPointIndex:ye,direction:w,shouldScaleBackground:i,setBackgroundColorOnScale:c,noBodyStyles:g,container:E,autoFocus:L}},s))}const qd=W.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:n,onRelease:a,shouldFade:o,isOpen:i,modal:c,shouldAnimate:u}=jn(),m=$d(t,s),d=n&&n.length>0;if(!c)return null;const f=W.useCallback(h=>a(h),[a]);return W.createElement(Id,{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})});qd.displayName="Drawer.Overlay";const Hd=W.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...n},a){const{drawerRef:o,onPress:i,onRelease:c,onDrag:u,keyboardIsOpen:m,snapPointsOffset:d,activeSnapPointIndex:f,modal:h,isOpen:v,direction:x,snapPoints:p,container:b,handleOnly:y,shouldAnimate:S,autoFocus:g}=jn(),[w,C]=W.useState(!1),R=$d(a,o),O=W.useRef(null),k=W.useRef(null),M=W.useRef(!1),P=p&&p.length>0;zw();const E=(A,j,I=0)=>{if(M.current)return!0;const D=Math.abs(A.y),T=Math.abs(A.x),F=T>D,N=["bottom","right"].includes(j)?1:-1;if(j==="left"||j==="right"){if(!(A.x*N<0)&&T>=0&&T<=I)return F}else if(!(A.y*N<0)&&D>=0&&D<=I)return!F;return M.current=!0,!0};W.useEffect(()=>{P&&window.requestAnimationFrame(()=>{C(!0)})},[]);function L(A){O.current=null,M.current=!1,c(A)}return W.createElement(Rd,{"data-vaul-drawer-direction":x,"data-vaul-drawer":"","data-vaul-delayed-snap-points":w?"true":"false","data-vaul-snap-points":v&&P?"true":"false","data-vaul-custom-container":b?"true":"false","data-vaul-animate":S?.current?"true":"false",...n,ref:R,style:d&&d.length>0?{"--snap-point-height":`${d[f??0]}px`,...t}:t,onPointerDown:A=>{y||(n.onPointerDown==null||n.onPointerDown.call(n,A),O.current={x:A.pageX,y:A.pageY},i(A))},onOpenAutoFocus:A=>{s?.(A),g||A.preventDefault()},onPointerDownOutside:A=>{if(e?.(A),!h||A.defaultPrevented){A.preventDefault();return}m.current&&(m.current=!1)},onFocusOutside:A=>{if(!h){A.preventDefault();return}},onPointerMove:A=>{if(k.current=A,y||(n.onPointerMove==null||n.onPointerMove.call(n,A),!O.current))return;const j=A.pageY-O.current.y,I=A.pageX-O.current.x,D=A.pointerType==="touch"?10:2;E({x:I,y:j},x,D)?u(A):(Math.abs(I)>D||Math.abs(j)>D)&&(O.current=null)},onPointerUp:A=>{n.onPointerUp==null||n.onPointerUp.call(n,A),O.current=null,M.current=!1,c(A)},onPointerOut:A=>{n.onPointerOut==null||n.onPointerOut.call(n,A),L(k.current)},onContextMenu:A=>{n.onContextMenu==null||n.onContextMenu.call(n,A),k.current&&L(k.current)}})});Hd.displayName="Drawer.Content";const Kw=250,qw=120,Wd=W.forwardRef(function({preventCycle:e=!1,children:t,...s},n){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:c,setActiveSnapPoint:u,dismissible:m,handleOnly:d,isOpen:f,onPress:h,onDrag:v}=jn(),x=W.useRef(null),p=W.useRef(!1);function b(){if(p.current){g();return}window.setTimeout(()=>{y()},qw)}function y(){if(o||e||p.current){g();return}if(g(),!i||i.length===0){m||a();return}if(c===i[i.length-1]&&m){a();return}const C=i.findIndex(O=>O===c);if(C===-1)return;const R=i[C+1];u(R)}function S(){x.current=window.setTimeout(()=>{p.current=!0},Kw)}function g(){x.current&&window.clearTimeout(x.current),p.current=!1}return W.createElement("div",{onClick:b,onPointerCancel:g,onPointerDown:w=>{d&&h(w),S()},onPointerMove:w=>{d&&v(w)},ref:n,"data-vaul-drawer-visible":f?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},W.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});Wd.displayName="Drawer.Handle";function Hw(e){const t=jn(),{container:s=t.container,...n}=e;return W.createElement(Ed,{container:s,...n})}const dt={Root:Uw,Content:Hd,Overlay:qd,Portal:Hw,Handle:Wd,Title:Ad},Vd="inline-flex items-center justify-center transition-colors",Ww=Ve(Vd,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Vw=Ve(Vd,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),Vo=({accountId:e,currentMailboxId:t,onMove:s,disabled:n=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[c,u]=l.useState(!1),[m,d]=l.useState(),f=es(),h=l.useRef(null),v=i??"Move to folder",x=l.useId(),{t:p}=Xa("mail",{useSuspense:!1}),b=io(),{data:y,isLoading:S,isError:g,error:w,refetch:C}=we({...it({path:{accountId:e}}),staleTime:1/0,enabled:c}),R=Uo(e),{createFolderIn:O}=Pc(e),k=l.useMemo(()=>lo({mailboxes:y?.items??[],folderAppointments:R,currentMailboxId:t,translator:b}),[y?.items,R,t,b]),M=co(y?.items??[]),P=k.find(T=>T.id===m),E=l.useCallback(()=>{u(!1),d(void 0)},[]),L=l.useCallback(()=>{P&&(E(),s(P.id))},[P,E,s]);l.useEffect(()=>{if(!c||!f)return;const T=N=>{h.current&&!h.current.contains(N.target)&&E()},F=N=>{N.key==="Escape"&&E()};return document.addEventListener("mousedown",T),document.addEventListener("keydown",F),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",F)}},[c,f,E]);const A=n||!!a,j=r.jsxs("button",{type:"button",onClick:T=>{T.stopPropagation(),!A&&u(F=>!F)},"aria-label":v,"aria-haspopup":f?"tree":"dialog","aria-expanded":c,"aria-controls":c?x:void 0,title:a,className:o==="icon-only"?Ww:Vw,children:[r.jsx(za,{className:o==="icon-only"?"size-5":"size-4"}),o==="compact"&&r.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),I=S?r.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):g?r.jsx("div",{className:"p-3",children:r.jsx(ts,{variant:"inline",title:"Couldn't load folders",error:w,onRetry:()=>C()})}):r.jsx(gc,{folders:k,selectedId:m,delimiter:M,onSelect:d,onCreateFolder:O,onCancel:E,labels:{filterPlaceholder:p("move_picker_filter_placeholder",{defaultValue:"Filter folders…"}),filterAriaLabel:p("move_picker_filter_label",{defaultValue:"Filter folders"})}}),D=P&&r.jsx("div",{className:"shrink-0 border-t border-line p-2",children:r.jsx(ce,{variant:"primary",onClick:L,className:"h-11 w-full font-semibold",children:`Move to ${P.label}`})});return f?r.jsxs("div",{ref:h,className:"relative inline-block",children:[j,c&&r.jsxs("div",{id:x,className:Ve("absolute right-0 mt-1 z-50 w-72 max-h-96 flex flex-col","bg-surface border border-line rounded-md shadow-lg"),children:[I,D]})]}):r.jsxs(r.Fragment,{children:[j,r.jsx(dt.Root,{open:c,onOpenChange:T=>T?u(!0):E(),children:r.jsxs(dt.Portal,{children:[r.jsx(dt.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(dt.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-lg bg-canvas pb-[env(safe-area-inset-bottom,0px)]",style:{maxHeight:"85dvh"},id:x,children:[r.jsx(dt.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),r.jsx(dt.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),r.jsx("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:I}),D]})]})})]})},Qw=({messageId:e,threadId:t,mailboxId:s,isRead:n,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:c=!1,onToggleRaw:u})=>{const m=De(),d=Ye(),{pushError:f}=nt(),{selectedMessageId:h}=As({strict:!1}),{mutate:v,isPending:x}=Ue({...mr(),onMutate:async I=>{const D=I.body.isRead??!0,T=new Set(I.body.messageIds??[]),F=Zt({path:{threadId:t}}),N=Et([s]);await Promise.all([m.cancelQueries({queryKey:F}),yn(m,N)]);const V=m.getQueriesData({queryKey:F}).filter(re=>re[1]!==void 0).map(([re,oe])=>({queryKey:re,data:oe})),J=wn(m,N);return m.setQueriesData({queryKey:F},re=>re&&{...re,items:tr(re.items,T,D)}),Sn(m,N,re=>tr(re,T,D)),{threadMessagesPrefix:F,listPrefixes:N,previousThreadMessages:V,previousThreadsList:J}},onError:(I,D,T)=>{if(T){for(const N of T.previousThreadMessages)m.setQueryData(N.queryKey,N.data);Cn(m,T.previousThreadsList)}const F=D.body.isRead??!0;f({title:F?"Couldn't mark as read":"Couldn't mark as unread",detail:ft(I),error:I})},onSettled:(I,D,T,F)=>{F&&(m.invalidateQueries({queryKey:F.threadMessagesPrefix}),It(m,F.listPrefixes))}}),p=l.useCallback(I=>{h&&I.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:D=>({...D,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:b,isPending:y}=ms({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:S,isPending:g}=Ds({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:w,isPending:C,error:R,reset:O}=Ko({messageId:e}),k=()=>{v({body:{messageIds:[e],isRead:!1}})},M=()=>{b([e])},P=()=>{o&&w(o,i)},E=x||y||g||C,L=E||!o,A=l.useCallback(I=>{S([e],I)},[S,e]),j=o?void 0:"Sender has no parseable address";return r.jsxs("div",{className:"flex flex-col items-end gap-1",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[a&&r.jsx(Vo,{accountId:a,currentMailboxId:s,onMove:A,disabled:E,label:"Move this message"}),r.jsxs(Ju,{trigger:r.jsx(Gc,{className:"size-4"}),children:[r.jsxs(nn,{onClick:P,disabled:L,children:[i?r.jsx(br,{className:"size-4 text-positive"}):r.jsx(hn,{className:"size-4 opacity-0"}),r.jsx("span",{title:j,children:"Trusted sender"})]}),n&&r.jsxs(nn,{onClick:k,disabled:E,children:[r.jsx(vr,{className:"size-4"}),"Mark as unread"]}),u&&r.jsxs(nn,{onClick:u,children:[r.jsx(Qc,{className:"size-4"}),c?"Show formatted":"Show raw email"]}),r.jsx(Zu,{}),r.jsxs(nn,{onClick:M,disabled:E,destructive:!0,children:[r.jsx(Lt,{className:"size-4"}),"Delete"]})]})]}),R&&r.jsx("div",{className:"w-64",children:r.jsx(ts,{variant:"inline",title:"Couldn't update trust",error:R,onRetry:()=>{O(),P()}})})]})},Gw=e=>e==="link-expired"||e==="not-ready";class Da extends Error{reason;status;constructor(t,s,n){super(s),this.name="AttachmentFetchError",this.reason=t,this.status=n}}const Yw="x-remit-403-reason",Xw="expired",Jw=(e,t)=>{if(t?.trim()===Xw)return"link-expired";const s=md(e,t);return s==="auth"?"auth":s==="body-missing"?"missing":"generic"},Zw=300*1e3,Ll=async(e,t)=>{const s={},n=await t();n&&(s.Authorization=`Bearer ${n}`);const a=await Cc(e,{headers:s,signal:AbortSignal.timeout(Zw)});if(a.status===202)throw new Da("not-ready","Attachment is still being fetched from the mail server",202);if(!a.ok)throw new Da(Jw(a.status,a.headers.get(Yw)),`Failed to download attachment (${a.status} ${a.statusText})`,a.status);return a.blob()},eS=(e,t,s)=>{switch(e){case"auth":return{title:"Your session expired",detail:`Sign in again, then download ${t} once more. Other parts of the app may also stop responding until you do.`};case"link-expired":return{title:"This download link expired and could not be renewed",detail:`Reload the page, then download ${t} again. If that keeps failing, this is worth reporting.`};case"missing":return{title:"This attachment is missing from storage",detail:"Remit has the message but not the file. Re-sync the account from Settings, then try again."};case"not-ready":return{title:"Still fetching this attachment",detail:"Remit is downloading it from the mail server now. Try again in a few seconds."};default:return{title:"Couldn't download this attachment",detail:s}}},Fl=e=>e instanceof Da?e.reason:"generic",tS=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while downloading this attachment.",sS=(e,t,s)=>{if(e!=="auth")return to(so({title:`Bug: attachment download failed (${e})`,errorMessage:`Downloading "${t}" failed: ${s}`}))},nS=(e,t)=>{const s=URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,n.rel="noopener",document.body.append(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(s),0)},rS=e=>{const t=e.toUpperCase();return t==="OCTET-STREAM"?"FILE":t},aS=e=>{const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return t.length>0?`attachment.${t}`:"attachment"},$l=e=>e.filter(t=>!t.isMultipart&&t.disposition===Wh.Attachment&&t.contentUrl.length>0).map(t=>({bodyPartId:t.bodyPartId,filename:fx(t.dispositionFilename??"",aS(t.mediaSubtype)),typeLabel:rS(t.mediaSubtype),sizeOctets:t.sizeOctets,contentUrl:t.contentUrl})),_l={status:"idle"},oS=({messageId:e,bodyParts:t,hasAttachment:s=!1,className:n})=>{const{getToken:a}=lr(),o=De(),[i,c]=l.useState({}),u=l.useMemo(()=>$l(t??[]),[t]),m=Ja({path:{messageId:e}}),d=x=>Ll(x.contentUrl,a).catch(p=>{if(!Gw(Fl(p)))throw p;return o.refetchQueries({queryKey:m}).then(()=>{const b=o.getQueryData(m),y=b?$l(b.bodyParts).find(S=>S.bodyPartId===x.bodyPartId):void 0;return Ll(y?.contentUrl??x.contentUrl,a)})}),f=(x,p)=>c(b=>({...b,[x]:p})),h=x=>{const p=u.find(b=>b.bodyPartId===x);if(!p)throw new Error(`No attachment part ${x} on message ${e}`);f(x,{status:"downloading"}),d(p).then(b=>{nS(b,p.filename),f(x,_l)}).catch(b=>{const y=Fl(b),S=tS(b),{title:g,detail:w}=eS(y,p.filename,S);f(x,{status:"failed",title:g,detail:w,reportUrl:sS(y,p.filename,S)})})},v=s&&t!==void 0&&u.length===0;return r.jsx(px,{className:n,attachments:u.map(x=>({attachmentId:x.bodyPartId,filename:x.filename,typeLabel:x.typeLabel,sizeOctets:x.sizeOctets,download:i[x.bodyPartId]??_l})),onDownload:h,hasUnlistedAttachment:v})},iS=()=>{const[e,t]=l.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return l.useEffect(()=>{const s=document.documentElement,n=new MutationObserver(()=>{t(s.classList.contains("dark"))});return n.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e},lS=({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"})]})]}),cS=(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}}},uS=e=>e instanceof cs?e.reason:"generic",dS=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",fS=({error:e,onRetry:t})=>{const s=uS(e),n=dS(e),{title:a,detail:o}=cS(s,n),[i,c]=l.useState(!1),{Account:u}=lr();return i?null:r.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[r.jsx(Pt,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"font-medium text-danger",children:a}),r.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&r.jsx(u,{children:({signOut:m})=>r.jsx("button",{type:"button",onClick:()=>m(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&r.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),r.jsx("button",{type:"button",onClick:()=>c(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:r.jsx(Nt,{className:"size-4","aria-hidden":"true"})})]})]})},mS=()=>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"})]}),zl=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Qd=({bodyParts:e,html:t,text:s,isTrusted:n=!1,messageId:a,fromAddressId:o,category:i,className:c})=>{const[u,m]=l.useState(!1),d=n||u,f=iS(),{toggleTrusted:h,isPending:v}=Ko({messageId:a??""}),x=!!e&&e.length>0,{picked:p,data:b,isLoading:y,isError:S,error:g,refetch:w}=hd({messageId:a,bodyParts:e,enabled:x}),C=l.useMemo(()=>Ng(e??[]),[e]),R=x&&b?.kind==="html"?b.body:t,O=x&&b?.kind==="text"?b.body:s;if(x){if(y)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(mS,{})});if(S)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(fS,{error:g,onRetry:()=>w()})});if(!p)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(zl,{})})}else if(!t&&!s)return r.jsx("div",{className:Ve("message-body",c),children:r.jsx(zl,{})});const k=!!(o&&a),M=()=>{!o||v||(m(!0),h(o,!1))};return r.jsx(xu,{className:c,html:R,text:O,isDark:f,category:i,allowImages:d,resolveCid:C,renderBlockedNotice:P=>r.jsx(lS,{blockedImageCount:P,canAlwaysTrust:k,isTrustPending:v,onLoadOnce:()=>m(!0),onAlwaysTrust:M})})},hS=({messageId:e,threadId:t,mailboxId:s,accountId:n,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:c,isTrusted:u,showRaw:m,onToggleRaw:d,onReply:f,onReplyAll:h,onForward:v})=>{const x=De(),{deleteMessages:p}=ms({mailboxId:s,threadId:t}),{moveMessages:b}=Ds({mailboxId:s,threadId:t,accountId:n}),{toggleTrusted:y}=Ko({messageId:e}),{mutate:S}=Ue({...mr(),onSettled:()=>{x.invalidateQueries({queryKey:Zt({path:{threadId:t}})}),It(x,Et([s]))}}),g=l.useCallback(O=>{b([e],O)},[b,e]),w=l.useCallback(()=>{p([e])},[p,e]),C=l.useCallback(()=>{S({body:{messageIds:[e],isRead:!a}})},[S,e,a]),R=[];return c&&R.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?r.jsx(br,{className:"size-4 text-positive"}):r.jsx(hn,{className:"size-4"}),onSelect:()=>y(c,u)}),d&&R.push({key:"raw",label:m?"Show formatted":"Show raw email",icon:r.jsx(Qc,{className:"size-4"}),onSelect:d}),r.jsx(gu,{hasThread:!0,onReply:f,onReplyAll:h,onForward:v,isStarred:o,onToggleStar:i,onDelete:w,isRead:a,onToggleRead:C,overflowItems:R,moveSlot:n?r.jsx(Vo,{accountId:n,currentMailboxId:s,onMove:g,label:"Move this message"}):void 0})},pS=()=>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"})]}),gS=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:n,isError:a,error:o,refetch:i}=we({...Ym({path:{messageId:e}}),enabled:t});if(n)return r.jsx("div",{className:"message-body",children:r.jsx(pS,{})});if(a)return r.jsx("div",{className:"message-body",children:r.jsx(ts,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const c=s?.raw??"";return c===""?r.jsx("div",{className:"message-body",children:r.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):r.jsx("div",{className:"message-body",children:r.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:c})})},xS=()=>r.jsx(br,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),Gd=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),Yd=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:Ve("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":Ve("text-fg-subtle hover:text-warning",n&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:r.jsx(Xt,{className:Ve("size-3.5",e&&"fill-current")})}),bS=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:n,isStarPending:a})=>{const o=Oc(e.sentDate,"datetime"),i=Gd(e,o);return r.jsx(bu,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:r.jsxs(r.Fragment,{children:[e.hasAttachment&&r.jsx(yr,{className:"size-3 shrink-0 text-fg-subtle",role:"img","aria-label":"Has an attachment"}),r.jsx(Yd,{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})]})})},vS=({threadMessage:e,messageData:t,isLoading:s,isError:n,error:a,onRetry:o,isFocused:i,onToggle:c,onToggleStar:u,isStarPending:m,accountId:d,showRaw:f,onToggleRaw:h,mobile:v,onReply:x,onReplyAll:p,onForward:b})=>{const y=Oc(e.sentDate,"long"),S=!e.isRead,g=t?.envelope.from[0]?.flags?.trusted?.value===!0,w=t?.envelope.from[0]?.addressId,C=Gd(e,y),R=e.autoMoved||e.spamReport?r.jsx(ow,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved,spamReport:e.spamReport}):null;return r.jsx(vu,{message:C,isFocused:v?!1:i,onHeaderClick:c,senderBadge:g?r.jsx(xS,{}):void 0,trailing:r.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:y}),to:t?r.jsx(Bp,{label:"To",addresses:t.envelope.to}):null,indicators:R||!v?r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[R,!v&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"flex items-center justify-end gap-1",children:r.jsx(Yd,{isStarred:e.hasStars,onToggleStar:u,isStarPending:m})}),S&&r.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:v?void 0:r.jsx(Qw,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:w,isTrusted:g,showRaw:f,onToggleRaw:h}),actionBar:v?r.jsx(hS,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:w,isTrusted:g,showRaw:f,onToggleRaw:h,onReply:x,onReplyAll:p,onForward:b}):void 0,body:s?r.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):n&&Xm(a)?r.jsx("div",{className:"mt-3",children:r.jsx(pd,{message:"This message has been deleted"})}):n?r.jsx("div",{className:"mt-3",children:r.jsx(ts,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):f?r.jsx("div",{className:"mt-3",children:r.jsx(gS,{messageId:e.messageId})}):r.jsxs("div",{className:"mt-3",children:[r.jsx(Qd,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:g,category:Or(e.category)}),r.jsx(oS,{messageId:e.messageId,bodyParts:t?.bodyParts,hasAttachment:e.hasAttachment,className:"mt-4 px-2 lg:px-0"})]})})},yS=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,mobile:c,onReply:u,onReplyAll:m,onForward:d})=>{const[f,h]=l.useState(!1),{data:v,isLoading:x,isError:p,error:b,refetch:y}=we({...hr({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?r.jsx(vS,{threadMessage:e,messageData:v,isLoading:x,isError:p,error:b,onRetry:()=>y(),isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,showRaw:f,onToggleRaw:()=>h(S=>!S),mobile:c,onReply:u,onReplyAll:m,onForward:d}):r.jsx(bS,{threadMessage:e,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o})},wS=()=>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 Bl({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($s,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",r.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&r.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const Bs=({threadId:e,mailboxId:t,subject:s,selectedMessageId:n,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:c,onComposeClose:u,onSwipeNext:m,onSwipePrevious:d,mobileIntelligenceOpen:f})=>{const h=es(),{handlers:v}=V0({onSwipeLeft:m,onSwipeRight:d}),{accountId:x}=_o(t),{data:p,isLoading:b,isError:y,error:S,refetch:g}=we({...Jm({path:{threadId:e}})}),w=l.useMemo(()=>p?.items??[],[p?.items]),C=w[w.length-1],R=l.useRef(new Map),[O,k]=l.useState(new Set),[M,P]=l.useState(null),[E,L]=l.useState(0);l.useEffect(()=>{if(w.length>0&&e!==M){P(e);const de=new Set([w[w.length-1].threadMessageId]);if(n){const se=w.find(ye=>ye.messageId===n);se&&de.add(se.threadMessageId)}k(de),L(w.length-1)}},[e,w,M,n]);const A=l.useCallback(de=>{k(se=>{const ye=new Set(se);return ye.has(de)?ye.delete(de):ye.add(de),ye})},[]),j=l.useCallback(de=>{const se=w[de];if(!se)return;R.current.get(se.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[w]),I=l.useCallback(()=>{if(w.length===0)return;const de=Math.min(E+1,w.length-1);L(de),j(de)},[w.length,E,j]),D=l.useCallback(()=>{if(w.length===0)return;const de=Math.max(E-1,0);L(de),j(de)},[w.length,E,j]),T=l.useCallback(()=>{const de=w[E];de&&A(de.threadMessageId)},[w,E,A]),{data:F}=we({...$t(),staleTime:1/0}),N=F?.accounts?.[0];K0({messages:w,expandedIds:O,threadId:e,mailboxId:t,accountId:N?.accountId});const{toggleStar:V,isPending:J,pendingMessageId:re}=zo({threadId:e,mailboxId:t,messages:w}),[oe,ie]=l.useState(null),[Z,ae]=l.useState(0),fe=l.useCallback(de=>{ie(de),ae(se=>se+1)},[]);l.useEffect(()=>{c&&c!=="new"&&(fe(c),u?.())},[c,u,fe]);const{data:B}=we({...hr({path:{messageId:C?.messageId??""}}),enabled:!!C&&oe!==null}),$=l.useCallback(()=>fe("reply"),[fe]),me=l.useCallback(()=>fe("reply_all"),[fe]),ge=l.useCallback(()=>fe("forward"),[fe]),Se=l.useCallback(()=>{ie(null),u?.()},[u]),Ne=l.useRef(null);if(l.useEffect(()=>{if(oe===null||Z===0)return;const de=Ne.current;if(!de)return;const se=()=>de.scrollIntoView({behavior:"smooth",block:"end"});if(se(),typeof ResizeObserver>"u")return;const ye=new ResizeObserver(se);return ye.observe(de),()=>ye.disconnect()},[Z,oe]),$o({enabled:!b&&w.length>0&&oe===null,bindings:[{key:"j",handler:I,preventDefault:!0},{key:"ArrowDown",handler:I,preventDefault:!0},{key:"k",handler:D,preventDefault:!0},{key:"ArrowUp",handler:D,preventDefault:!0},{key:"Enter",handler:T,preventDefault:!0},{key:"o",handler:T,preventDefault:!0},{key:"r",handler:$,preventDefault:!0},{key:"R",handler:me,noModifiers:!1,preventDefault:!0},{key:"f",handler:ge,preventDefault:!0}]}),b)return r.jsx(wS,{});if(y)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(ts,{title:"Couldn't load this conversation",error:S,onRetry:()=>g()})});if(w.length===0)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(pd,{message:"No messages in this thread"})});const H=s||w[0]?.subject||"(No subject)",Ee=w.length,xe=de=>r.jsx("div",{children:w.map((se,ye)=>r.jsx("div",{ref:Pe=>{Pe&&R.current.set(se.threadMessageId,Pe)},children:r.jsx(yS,{threadMessage:se,isExpanded:O.has(se.threadMessageId),isFocused:ye===E,onToggle:()=>A(se.threadMessageId),onToggleStar:()=>V(se.messageId,se.hasStars),isStarPending:J&&re===se.messageId,accountId:x,mobile:de,onReply:de?$:void 0,onReplyAll:de?me:void 0,onForward:de?ge:void 0})},se.threadMessageId))}),ke=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:H}),r.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[Ee," ",Ee===1?"message":"messages"]})]});return h?r.jsxs("article",{className:"h-full flex flex-col",children:[ke,a?.dkimMismatch&&r.jsx(Bl,{authenticity:a,onOpenIntelligence:o}),r.jsx("div",{className:"flex-1 overflow-auto",children:xe(!1)}),oe!==null&&r.jsx(El,{mode:oe,account:N,sourceMessage:B,onClose:Se})]}):r.jsxs(Xg,{thread:{subject:H,messages:[]},onBack:i??(()=>{}),intelligenceOpen:f,onToggleIntelligence:o,touchHandlers:v,children:[a?.dkimMismatch&&r.jsx(Bl,{authenticity:a,onOpenIntelligence:o}),xe(!0),oe!==null&&r.jsx("div",{ref:Ne,children:r.jsx(El,{mode:oe,account:N,sourceMessage:B,onClose:Se})})]})},SS=768,Xd=e=>e!=="desktop",Nn=()=>{const e=fi(`(min-width: ${SS}px)`);return fi(Mc)?"desktop":e?"tablet":"phone"};function xs(){const{mailboxNameIndex:e,accountNameIndex:t}=Fe();return{...Ot({select:n=>cd(n.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const Qo=e=>e.trim().toLocaleLowerCase(),Jd={personal:"Personal",uncategorized:"Unclassified",transactional:"Transactional",newsletter:"Newsletter",marketing:"Marketing",social:"Social",automated:"Automated"},CS=Object.values(ot).map(e=>({value:e,label:Jd[e]})),kS={unclassified:"uncategorized"},Pa=[{name:"from",label:"Sender",values:"contact"},{name:"subject",label:"Subject",values:"text"},{name:"category",label:"Category",values:"fixed",options:CS},{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"}],jS=new Map(Pa.map(e=>[e.name,e])),Zd=e=>jS.get(e.toLowerCase()),NS=/^\d{4}-\d{2}-\d{2}$/;function ES(e,t,s){if(!NS.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 IS(e){const t=e.toLowerCase(),s=kS[t];return s||Object.values(ot).find(a=>a===t)}function RS(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 TS(e,t){const s=Sr(e);if(!s||s.value.length===0)return;const{name:n,value:a}=s;switch(n){case"from":return{type:"from",raw:e,value:a};case"subject":return{type:"subject",raw:e,value:a};case"category":{const o=IS(a);return o?{type:"category",raw:e,value:a,category:o}:void 0}case"is":return RS(e,a);case"has":return a.toLowerCase()==="attachment"?{type:"hasAttachment",raw:e}:void 0;case"before":case"after":return ES(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 Us(e,t={}){const s=[],n=[];for(const a of wr(e)){const o=TS(a.raw,t);o?s.push(o):n.push(a.raw)}return{freeText:n.join(" "),tokens:s}}function MS(e,t){return wr(e).filter(s=>s.raw!==t.raw).map(s=>s.raw).join(" ")}function ef(e){switch(e.type){case"from":return`From: ${e.value}`;case"subject":return`Subject: ${e.value}`;case"category":return`Category: ${Jd[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 AS=20,OS=new Set(Object.values(ot)),DS=e=>e!==void 0&&OS.has(e)?e:void 0,PS=e=>{if(e.some(t=>t.type==="isUnread"))return!1;if(e.some(t=>t.type==="isRead"))return!0};function tf({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Fe(),n=xs(),a=Ot({select:w=>w.matches}),o=Qo(s),{freeText:i,tokens:c}=Us(o,n),u=i.length>0,m=c.find(w=>w.type==="category"),d=DS(t)??m?.category,f=c.some(w=>w.type==="hasAttachment")?!0:void 0,h=c.some(w=>w.type==="isStarred")?!0:void 0,v=PS(c),x=c.find(w=>w.type==="after"),p=c.find(w=>w.type==="before"),b=c.find(w=>w.type==="in"),y=l0({matches:a,callerMailboxId:e,inTokenMailboxId:b?.mailboxId}),{data:S,isLoading:g}=we({...Nc({query:{query:i,mailboxId:y,limit:AS,...d!==void 0?{category:d}:{},...f!==void 0?{hasAttachment:f}:{},...h!==void 0?{hasStars:h}:{},...v!==void 0?{isRead:v}:{},...x?{sentDateFrom:x.epochSeconds}:{},...p?{sentDateTo:p.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:S?.items??[],isLoading:u&&g}}const LS=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),FS=e=>[...e].sort(LS);function nr(e){const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId,mailboxId:e.mailboxId,threadId:e.threadId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:gt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Or(e.category),suspicious:t}}function Ul(e){return e.filter(t=>t.muted!==!0)}function $S(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 Kl=[{id:"personal",label:"Personal",category:ot.personal},{id:"transactional",label:"Transactional",category:ot.transactional},{id:"newsletter",label:"Newsletter",category:ot.newsletter},{id:"marketing",label:"Marketing",category:ot.marketing},{id:"social",label:"Social",category:ot.social},{id:"automated",label:"Automated",category:ot.automated},{id:"uncategorized",label:"Unclassified",category:ot.uncategorized}];function _S(e){const t=new Map(Kl.map(n=>[n.category,[]]));for(const n of e){const a=n.category??ot.uncategorized;(t.get(a)??t.get(ot.uncategorized))?.push(n)}const s=[];for(const n of Kl){const a=t.get(n.category);a&&a.length>0&&s.push({id:n.id,label:n.label,threads:a})}return s}function sf(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Go(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 nf="This account has no Junk folder appointed, so there is nowhere to file these. Appoint one under Settings › Folders.",zS="These are already in Junk, so there is nowhere to file them.",Lr=(e,t)=>e!==void 0&&e!==t?e:void 0,BS=(e,t)=>{if(Lr(e,t)===void 0)return e===void 0?nf:zS},US={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function KS(e){return US[e]??e}function qS(e,t){const{folder:s}=no(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:gt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function Wn(e,t){const{folder:s}=no(t,e.mailboxId?[e.mailboxId]:[]);return{id:e.id,sender:e.fromName,...e.fromEmail?{senderEmail:e.fromEmail}:{},subject:e.subject,snippet:e.snippet,date:e.timeLabel,unread:!e.isRead,flagged:e.starred===!0,...e.threadId?{threadId:e.threadId}:{},...e.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function HS(e,t){const{mailboxId:s,folder:n}=no(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?gt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:KS(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...n?{folder:n}:{}}}function rf(e,t,s){const n=new Set(t),a=[];for(const o of[...e].sort((i,c)=>c.score-i.score))n.has(o.threadId)||(n.add(o.threadId),a.push(HS(o,s)));return a}const af=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function of(e){const{spam:t}=ko([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let n;for(const[a,o]of s)(!n||o>n.count)&&(n={mailboxId:a,count:o});return n}const WS=e=>{const{mailboxId:t,messages:s}=e,n=De(),{pushError:a}=nt(),{mutateAsync:o,isPending:i}=Ue({...Zm(),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)=>{It(n,Et(Mr(d.body.messageIds??[],s??[],t)))}});return{applyLabel:l.useCallback((u,m,d)=>{u.length!==0&&Os(u,f=>o({body:{messageIds:f,labelId:m,action:d}}))},[o]),isPending:i}};function lf({accountId:e,mailboxId:t,messageIds:s}){const{labels:n}=uo(e),{applyLabel:a}=WS({mailboxId:t}),o=l.useMemo(()=>n.map(i=>({key:i.labelId,label:i.name,icon:r.jsx("span",{className:`size-2.5 rounded-full ${eh(i.color)?ci[i.color]:ci.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[n,s,a]);return o.length===0?null:r.jsx(wo,{triggerLabel:"Apply label to selected messages",triggerIcon:r.jsx(th,{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 cf=8;function Yo(e,t){const s=Math.max(0,Math.min(t,e.length)),n=wr(e).find(o=>s>=o.start&&s<=o.end);if(!n)return{start:s,end:s,raw:""};const a=Sr(n.raw);return a?{start:n.start,end:n.end,raw:n.raw,name:a.name,value:a.value}:{start:n.start,end:n.end,raw:n.raw}}function VS(e,t){const s=Yo(e,t);if(s.name===void 0)return{kind:"token",query:s.raw};const n=Zd(s.name);if(n)return{kind:"value",token:n.name,source:n.values,query:s.value??""}}const QS={mailbox:"mailboxes",account:"accounts",contact:"contacts"},GS=(e,t)=>{if(e.values==="fixed")return e.options??[];const s=QS[e.values];return s?t[s]??[]:[]},YS=(e,t)=>{if(t==="")return 1;const s=e.toLowerCase();return s.startsWith(t)?0:s.includes(t)?1:-1},La=(e,...t)=>{let s=-1;for(const n of t){if(n===void 0)continue;const a=YS(n,e);a<0||(s<0||a<s)&&(s=a)}return s},uf=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,cf).map(s=>s.suggestion)},ql=e=>({value:`${e.name}:`,label:`${e.name}:`,hint:e.label});function XS(e){const t=e.trim().toLowerCase();if(t==="")return Pa.map(ql);const s=[];for(const n of Pa)if(s.push({rank:La(t,`${n.name}:`,n.label),suggestion:ql(n)}),n.values==="fixed")for(const a of n.options??[]){const o=Cr(n.name,a.value);s.push({rank:La(t,o,a.label),suggestion:{value:o,label:a.label??o,hint:o}})}return uf(s)}function JS(e,t,s){const n=t.trim().toLowerCase(),a=GS(e,s).map(o=>({rank:La(n,o.value,o.label),suggestion:{value:Cr(e.name,o.value),label:o.label??o.value,...o.hint?{hint:o.hint}:{}}}));return uf(a)}function ZS(e,t,s={}){const n=Yo(e,t);if(n.name===void 0)return XS(n.raw);const a=Zd(n.name);return a?JS(a,n.value??"",s):[]}function eC(e,t,s){const n=Yo(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 tC=e=>({value:e.normalizedEmail,...e.displayName?{label:e.displayName,hint:e.normalizedEmail}:{}});function sC(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 nC(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 rC(e,t=[]){const s=e.flat().filter(o=>o.fullPath),n=new Map;for(const o of s){const i=ba(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=ba(o.fullPath),c=n.get(i.toLowerCase())===1,u=t.length>1?a.get(o.accountId):void 0;return{value:c?i:o.fullPath,label:o.displayNameOverride?.trim()||i,...u?{hint:u}:{}}})}function aC(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 oC=250,iC=2;function lC({query:e,cursor:t,enabled:s}){const{accounts:n}=Fe(),{mailboxesByName:a}=xs(),o=a!==void 0,i=s?VS(e,t):void 0,c=i?.source==="contact"?i.query.trim():"",u=gr(c,oC),{data:m}=we({...ur({query:{q:u,limit:cf}}),enabled:u.length>=iC}),d=mt({queries:n.map(x=>({...it({path:{accountId:x.accountId}}),staleTime:1/0}))}),f=l.useMemo(()=>o?rC(d.map(x=>x.data?.items??[]),n):[],[o,d,n]),h=l.useMemo(()=>aC(n),[n]),v=l.useMemo(()=>(m?.items??[]).map(tC),[m]);return l.useMemo(()=>{if(!s)return[];const x=ZS(e,t,{mailboxes:f,accounts:h,contacts:v});return o?x:x.filter(p=>p.value!=="in:")},[s,e,t,f,h,v,o])}const cC={title:"",navSlot:null,titleMeta:null,searchSlot:null,searchField:null,searchResults:null,makeFilterSlot:null},Fa=l.createContext(cC),Fr=()=>l.useContext(Fa),uC=new Set(["hasAttachment","isUnread","isRead","isStarred","category","before","after"]),dC=e=>uC.has(e),fC=(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}dC(u.type)&&n.push({type:u.type,label:ef(u)})}const i=e.freeText.trim(),c=i.length>0;return c&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:n,targetAccountId:o,keptTerms:c,droppedSemantic:c&&t}},mC=(e,t,s)=>e.targetAccountId??t??s[0]?.accountId,df="remit.recentSearches",hC=5;function $a(){try{const e=localStorage.getItem(df);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function Hl(e){const t=e.trim();if(!t)return $a();const s=[t,...$a().filter(n=>n!==t)].slice(0,hC);try{localStorage.setItem(df,JSON.stringify(s))}catch{return s}return s}function ff({title:e,unreadCount:t,children:s,selectionBar:n,paneOverlay:a,footer:o,searchFilter:i,searchResults:c,searchLoading:u,relatedResults:m,relatedLoading:d,onSelectSearchResult:f,searchResultsLabel:h="Top matches",relatedResultsLabel:v="Related",searchResultsInBody:x=!1,refreshControl:p}){const{accounts:b,resultFolderIndex:y,searchQuery:S,searchInput:g,onSearchChange:w,onSearchClear:C,searchViewKey:R}=Fe(),O=xs(),k=Ye(),M=ps(),P=Nn(),[E,L]=l.useState(!1),[A,j]=l.useState($a),I=sh(),D=l.useRef(R);l.useEffect(()=>{D.current!==R&&(D.current=R,L(!1))},[R]);const[T,F]=l.useState(0),[N,V]=l.useState(!1),[J,re]=l.useState(void 0),oe=lC({query:g,cursor:T,enabled:N&&g.trim().length>0}),ie=l.useCallback(ne=>{const ee=eC(g,T,ne);w(ee.query),re({cursor:ee.cursor})},[g,T,w]),Z=mc({count:oe.length,onAccept:ne=>{const ee=oe[ne];ee&&ie(ee)}}),{comboboxProps:ae,handleKeyDown:fe}=Z,B=l.useMemo(()=>({comboboxProps:ae,onKeyDown:fe,onCaretChange:F,onFocusChange:V,...J?{caret:J}:{}}),[ae,fe,J]),$=Z.open?r.jsx(hc,{id:Z.listId,suggestions:oe,activeIndex:Z.activeIndex,optionId:Z.optionId,onPick:ie,onHighlight:Z.setActiveIndex,label:"Search suggestions",className:"mx-row-inset mt-1 shrink-0"}):null,me=g.trim().length>0,{mailboxesByName:ge,accountsByName:Se}=O,Ne=l.useMemo(()=>Us(g,{mailboxesByName:ge,accountsByName:Se}),[g,ge,Se]),H=Ne.tokens.map(ne=>({label:ef(ne),onRemove:()=>w(MS(g,ne))})),Ee=c??[],xe=m??[],ke=me?[{id:"top",label:h,results:Ee},{id:"related",label:v,results:xe}]:[],se=!(Ee.length+xe.length>0)&&(u===!0||d===!0),{scope:ye}=fd(b),Pe=Ot({select:ne=>ne.matches}),ze=ud(Pe),X=u0(Pe,ye,ze?y.get(ze)?.role:void 0),Ze=X.kind==="global"?of([...Ee,...xe]):void 0,Ie=Ze?{kind:"global",onScopeToSpam:()=>k({to:"/mail/$mailboxId",params:{mailboxId:Ze.mailboxId},search:{q:S||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:X,qe=xe.length>0,K=l.useMemo(()=>fC(Ne,{searchHadSemanticReach:qe}),[Ne,qe]),Qe=me?K:void 0,Re=me?{onClick:()=>{L(!1),I("properties","search")},blockedReason:ov(K)?void 0:nh(K.droppedFacets.map(ne=>ne.label))}:void 0,be=Re?r.jsx(wu,{...Re}):null,Oe=af({tier:P,hasLiveInput:me,hasCommittedQuery:S.trim().length>0,bodyRendersCommittedResults:x}),pe=ne=>{j(Hl(g)),f?.(ne)},Ce=r.jsx(Su,{value:g,sections:ke,loading:se,onSelectResult:pe,tokens:H,scope:Ie}),Te=n===void 0,_=Oe?r.jsx("div",{className:"h-full overflow-y-auto",children:Ce}):null,le=_&&!Te?_:s,ue=_&&Te?_:null,ve=Xd(P),q=ve&&(E||me),he=l.useMemo(()=>({title:e,searchResults:ue,makeFilterSlot:be,searchConversion:Qe,navSlot:M&&!M.showNavPane&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(pr,{className:"size-5"}),onClick:()=>M.openNav(),"aria-label":"Menu",className:"-ml-2 shrink-0"}),titleMeta:r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[t.toLocaleString()," unread"]}),r.jsx(ui,{}),p]}),searchSlot:ve&&!q&&r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(ir,{className:"size-5"}),onClick:()=>L(!0),"aria-label":"Search",className:"shrink-0"}),searchField:q&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(Co,{value:g,onChange:w,onClear:C,globalFocusKey:!1,showClearButton:!1,suggest:B})}),r.jsx(ce,{variant:"ghost",size:"touch",icon:r.jsx(Nt,{className:"size-5"}),onClick:()=>{C(),L(!1)},"aria-label":"Close search",className:"shrink-0"}),r.jsx(ui,{})]})}),[e,t,M,ve,q,g,w,C,B,ue,be,Qe,p]);if(P==="phone"&&E){const ne=ee=>{j(Hl(g)),L(!1),f?.(ee)};return r.jsxs(Fa.Provider,{value:he,children:[r.jsx(Ux,{value:g,onChange:w,onClear:C,onCancel:()=>{L(!1),C()},filter:i,recentSearches:A,onPickRecent:w,makeFilter:Re,sections:ke,loading:se,onSelectResult:ne,tokens:H,scope:Ie,suggest:B,suggestList:$}),a]})}return r.jsx(Fa.Provider,{value:he,children:r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[n?.(he),$,r.jsx("div",{className:"min-h-0 flex-1",children:le}),o,a]})})}const pC=["intelligence","nav","shortcuts","filters"];rh(pC);const gC=ah(oh);function Ht({fragment:e,...t}){return r.jsx(gC,{...t,hash:e})}const xC=120,mf=({keyboardFocusedMessageId:e,openMessageId:t,enabled:s,open:n,delayMs:a=xC})=>{const o=l.useRef(n);o.current=n;const i=l.useRef(void 0);l.useEffect(()=>{const c=e;if(!s){i.current=c;return}if(c===void 0||c===t)return;if(c===i.current){i.current=void 0;return}const u=setTimeout(()=>o.current(c),a);return()=>clearTimeout(u)},[s,e,t,a])};function hf(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Xo=l.createContext(null),bC=e=>{const t=l.useContext(Xo);return t?t.rowInteraction(e):null},Jo=()=>{const e=l.useContext(Xo);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},vC="[data-message-id]",yC=e=>Array.from(e.querySelectorAll(vC)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),wC=(e,t)=>e.length===t.length&&e.every((s,n)=>s===t[n]),SC=e=>{const[t,s]=l.useState([]);return l.useEffect(()=>{const n=e.current;if(!n)return;const a=()=>{const i=yC(n);s(c=>wC(c,i)?c:i)};a();const o=new MutationObserver(a);return o.observe(n,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function pf({selectedMessageId:e,onOpen:t,onDeleteMessages:s,onSelectionVerb:n,wizardOpen:a=!1,isDeleting:o=!1,commandsRef:i,onTriageContextChange:c,children:u}){const m=es(),d=l.useRef(null),f=SC(d),h=lv({orderedIds:f,isDesktop:m,initialFocusedId:e}),{focusedMessageId:v,setFocusedMessageId:x,pendingDomFocusRef:p,cursorMovedByPointerRef:b,selection:y,isMultiSelectMode:S,exitSelection:g,handleRowSelect:w}=h,{selectedIds:C,selectedCount:R,isSelected:O,toggle:k,select:M,toggleAll:P}=y,E=f.length>0&&f.every($=>C.has($)),L=l.useCallback(()=>{f.length>0&&P(f)},[f,P]),{intersectWith:A}=y;l.useEffect(()=>{A(f)},[A,f]),l.useEffect(()=>{const $=p.current;$!==null&&(p.current=null,d.current?.querySelector(`[data-message-id="${$}"]`)?.focus())});const j=l.useCallback($=>{b.current=!0,x($)},[b,x]),I=l.useCallback($=>{m||M($)},[m,M]),D=l.useCallback(()=>{v&&t(v)},[v,t]),T=l.useCallback($=>t($,{replace:!0}),[t]);mf({keyboardFocusedMessageId:h.keyboardFocusedMessageId,openMessageId:e,enabled:m&&R===0,open:T});const[F,N]=l.useState(null),V=l.useCallback($=>F!==null?!0:R>0?(n($),!0):$!=="delete"||!v?!1:(N([v]),!0),[F,R,n,v]),J=l.useCallback(()=>{F!==null&&(s(F),N(null),g())},[F,s,g]),re=l.useCallback(()=>N(null),[]),oe=l.useCallback(()=>R===0?!1:(g(),!0),[R,g]),ie=f.length>0;l.useEffect(()=>{if(i){if(!ie){i.current=null;return}return i.current={focusNext:h.focusNext,focusPrevious:h.focusPrevious,focusFirst:h.focusFirst,focusLast:h.focusLast,openFocused:D,toggleSelect:h.toggleFocusedSelection,extendSelectDown:h.extendRangeDown,extendSelectUp:h.extendRangeUp,selectAll:h.selectAllLoaded,clearSelection:oe,requestVerb:V,toggleDensity:()=>{}},()=>{i.current=null}}},[i,ie,h.focusNext,h.focusPrevious,h.focusFirst,h.focusLast,h.toggleFocusedSelection,h.extendRangeDown,h.extendRangeUp,h.selectAllLoaded,D,oe,V]);const Z=l.useMemo(()=>Array.from(C),[C]),ae=F!==null;l.useEffect(()=>{c?.({focusedMessageId:v,selectedIds:Z,orderedIds:f,hasList:ie,blocksKeyboard:ae||a})},[c,v,Z,f,ie,ae,a]);const fe=hf(f,v),B=l.useMemo(()=>({selectedIds:C,selectedCount:R,exitSelection:g,startSelectionVerb:n,orderedIds:f,allSelected:E,toggleAllLoaded:L,rowInteraction:$=>({focused:$===v,isTabStop:$===fe,isDesktop:m,onFocusRow:j,selection:{isChecked:O($),onToggleCheck:k,onRowSelect:w,isMultiSelectMode:S,onLongPress:I}})}),[C,R,g,n,f,E,L,v,fe,m,j,O,k,w,S,I]);return r.jsxs(Xo.Provider,{value:B,children:[r.jsx("div",{ref:d,className:"contents",children:u}),r.jsx(fo,{isOpen:ae,title:Dc(F?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:o,onConfirm:J,onCancel:re})]})}function CC({title:e,isDeleting:t}){const s=Fr(),{selectedCount:n,exitSelection:a,startSelectionVerb:o,orderedIds:i,allSelected:c,toggleAllLoaded:u}=Jo();return r.jsx(Eo,{title:s.title||e,navSlot:s.navSlot,titleMeta:s.titleMeta,searchSlot:s.searchSlot,searchField:s.searchField,idleSlot:s.makeFilterSlot,count:n,onCancel:a,onDelete:()=>o("delete"),onMarkRead:()=>o("markRead"),isBusy:t,selectAll:i.length>0?{checked:c,indeterminate:n>0&&!c,onChange:u}:void 0})}const da=e=>{e.preventDefault(),e.stopPropagation()},gf=(e,t)=>{const s=l.useRef(!1),n=l.useCallback(i=>{if(s.current=!1,i.button!==0)return;const c=Zn(i);ki(c)&&t?.(e,c)&&(da(i),s.current=!0,i.currentTarget.focus(),c.shiftKey&&window.getSelection()?.removeAllRanges())},[t,e]),a=l.useCallback(i=>{!i.ctrlKey||!t||i.preventDefault()},[t]),o=l.useCallback(i=>{if(s.current)return s.current=!1,da(i),!0;const c=Zn(i);return!ki(c)||!t?.(e,c)?!1:(da(i),c.shiftKey&&window.getSelection()?.removeAllRanges(),!0)},[t,e]);return{onMouseDown:n,onContextMenu:a,claimClick:o}},kC=({thread:e,active:t=!1,focused:s,isTabStop:n,density:a="comfortable",isDesktop:o,badge:i,selection:c,inListbox:u=!1,linkMailboxId:m,onClick:d,onFocusRow:f})=>{const h=De(),v=e.id,x=bC(v),p=s??x?.focused??!1,b=n??x?.isTabStop??!1,y=c??x?.selection,S=f??x?.onFocusRow,g=o??x?.isDesktop??!0,w=y?.isChecked??!1,C=y?.isMultiSelectMode??!1,R=y?.onToggleCheck,O=y?.onRowSelect,k=y?.onLongPress,M=l.useCallback(N=>{N.preventDefault(),N.stopPropagation(),R?.(v)},[R,v]),P=gf(v,O),E=l.useCallback(N=>{if(!P.claimClick(N)){if(!g){if(C){N.preventDefault(),N.stopPropagation(),R?.(v);return}d?.();return}O?.(v,Zn(N)),d?.()}},[P,g,C,R,O,d,v]),L=l.useCallback(()=>{k?.(v)},[k,v]),{longPressProps:A}=mu({onLongPress:L,accessibilityDescription:w?"Deselect message":"Select message"}),j=l.useCallback(()=>{h.prefetchQuery(hr({path:{messageId:v}}))},[h,v]),I=l.useCallback(()=>{j(),S?.(v)},[j,S,v]),D=Fs({"data-list-row":"","data-message-row":!0,"data-message-id":v,...u?{role:"option","aria-selected":w}:{},tabIndex:b?0:-1,onClick:E,onMouseDown:P.onMouseDown,onContextMenu:P.onContextMenu,onMouseEnter:j,onFocus:I},g||!y?{}:A),T=Ve(a==="compact"?cu({active:t,focused:p}):Ve("group",_s({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",w&&"bg-accent-soft",!g&&"min-h-11 select-none [-webkit-touch-callout:none]"),F=a==="compact"?r.jsx(uu,{thread:e}):r.jsx(yo,{thread:e,badge:i,selection:y?{checked:w,alwaysVisible:C,onToggle:M}:void 0});return m===void 0?r.jsx("button",{type:"button",...D,className:T,children:F}):r.jsx(Ht,{to:"/mail/$mailboxId",params:{mailboxId:m},search:N=>({...N,selectedMessageId:v}),variant:"row",...D,className:T,children:F})},Zo=l.memo(kC),xf=8,bf=e=>e==="From"||e==="FromDomain",jC=e=>({value:e.email,label:e.displayName??e.email,...e.displayName?{hint:e.email}:{},...e.fromSelection?{source:"selected"}:{}}),NC=e=>{const t=Ou(e.email);if(t!==null)return{value:t,...e.fromSelection?{source:"selected"}:{}}},EC=(e,t)=>e.value.toLowerCase().includes(t)||(e.label??"").toLowerCase().includes(t),IC=(e,t,s)=>{if(!bf(e))return[];const n=t.trim().toLowerCase(),a=new Set,o=[];for(const i of s){if(i.email.trim()==="")continue;const c=e==="From"?jC(i):NC(i);if(!c)continue;const u=c.value.toLowerCase();if(!(u===""||a.has(u))&&(a.add(u),u!==n&&!(n!==""&&!EC(c,n))&&(o.push(c),o.length===xf)))break}return o},RC=250,TC=2,MC=(e,t,s)=>{const n=t.trim(),a=gr(n,RC),o=e!==void 0&&bf(e),{data:i}=we({...ur({query:{q:a,limit:xf}}),enabled:o&&a.length>=TC});if(!o||e===void 0)return[];const c=[...s.map(u=>({email:u,fromSelection:!0})),...(i?.items??[]).map(u=>({email:u.normalizedEmail,...u.displayName?{displayName:u.displayName}:{}}))];return IC(e,n,c)},AC={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},vf={delete:"moved to Trash",move:"moved",markRead:"marked as read"},OC={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},DC={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},PC={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},LC=(e,t,s)=>AC[e](Gt(t),Gt(s)),Wl=(e,t)=>`${Gt(t)} ${vf[e]}. Your mail server is still catching up.`,FC=e=>`Stopped after ${Gt(e)}`,$C=(e,t,s)=>`${Gt(t)} of ${Gt(s)} ${vf[e]}. Nothing was sent for the rest, so they are untouched.`,_C=(e,t)=>t>0?`Stopped after ${Gt(t)} — some messages ${OC[e]}`:DC[e],zC=e=>PC[e],BC=e=>e==="delete"?"danger":"info",UC=100,KC=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],yf=({mailboxId:e,accountId:t,enabled:s,predicateKey:n,searchQuery:a})=>{const[o,i]=l.useState({kind:"idle"}),[c,u]=l.useState(void 0),[m,d]=l.useState(void 0),f=l.useRef(!1),h=l.useRef(!1),v=De(),{pushError:x}=nt();l.useEffect(()=>{h.current||(f.current=!0),i({kind:"idle"})},[s,n]);const p=l.useRef(a);p.current=a;const b=l.useCallback(k=>async M=>{const{data:P}=await va({path:{mailboxId:e},query:{...k,continuationToken:M,limit:UC},throwOnError:!0});return{ids:(P.items??[]).map(E=>E.messageId),continuationToken:P.continuationToken}},[e]),y=l.useCallback(async()=>{const{data:k}=await va({path:{mailboxId:e},query:{...p.current,count:!0,results:!1},throwOnError:!0});if(k.count===void 0)throw new Error("the search returned no count for the selection");return k.count},[e]),S=l.useCallback(k=>async M=>{if(k.kind==="move"){const{data:E}=await ih({body:{messageIds:M,destinationMailboxId:k.destinationMailboxId},throwOnError:!0});return E}if(k.kind==="markRead"){const{data:E}=await lh({body:{messageIds:M,isRead:!0},throwOnError:!0});return E}const{data:P}=await ch({body:{messageIds:M},throwOnError:!0});return P},[]),g=l.useCallback(k=>{It(v,Et(KC(k,e))),t&&v.invalidateQueries({queryKey:Ft({path:{accountId:t}})})},[v,e,t]),w=l.useCallback(()=>{f.current=!1,i({kind:"counting"}),y().then(k=>{if(f.current){i({kind:"idle"});return}i({kind:"escalated",total:k})},k=>{x(ds("Couldn't count matching messages","The count didn't finish.",k)),i({kind:"idle"})})},[y,x]),C=l.useCallback(()=>{f.current=!0},[]),R=l.useCallback(()=>{h.current||(f.current=!0,i({kind:"idle"}))},[]),O=l.useCallback(async(k,M)=>{f.current=!1,h.current=!0,u(k);const P=j=>d(_0(j)),E=S(k),L=b(p.current);let A;try{A=M!==void 0?await gd(M,E,P,()=>f.current):await $0(L,o.kind==="escalated"?o.total:0,E,P,()=>f.current)}finally{h.current=!1}return u(void 0),d(void 0),i({kind:"idle"}),A.error&&x(ds(_C(k.kind,A.done),zC(k.kind),A.error)),A.done>0&&g(k),A},[S,b,o,x,g]);return{phase:o,escalate:w,stop:C,clear:R,isRunning:c!==void 0,runningAction:c,progress:m,runAction:O}},wf=12,qC=e=>{const{envelope:t}=e,s=t.from[0];return{id:t.messageId,sender:s?Du({normalizedEmail:s.normalizedEmail,displayName:s.displayName}):"Unknown",subject:t.subject??"(No subject)",date:gt(t.date)}},HC=(e,t)=>{const s=e!==void 0&&t!==void 0,{data:n,isLoading:a}=we({...Ec({path:{mailboxId:e??""},query:{...t,limit:wf}}),enabled:s,staleTime:3e4});return{messages:(n?.items??[]).map(WC),isPending:s&&a}},WC=e=>({id:e.messageId,sender:e.fromName||e.fromEmail||"Unknown",subject:e.subject??"(No subject)",date:gt(e.sentDate)}),VC=e=>mt({queries:e.slice(0,wf).map(t=>({...hr({path:{messageId:t}}),staleTime:Number.POSITIVE_INFINITY})),combine:t=>({messages:t.map(s=>s.data).filter(s=>s!==void 0).map(qC),isPending:t.some(s=>s.isPending)})}),QC=e=>({matchOperator:"Or",literalClauses:jr(e)}),GC=(e,t,s)=>{const n=Ue(uh()),{mutate:a,reset:o}=n,[i,c]=l.useState(!1),u=l.useMemo(()=>kr(s),[s]),m=l.useCallback(()=>{!e||!t||(c(!1),a({path:{accountId:e},body:mi({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=l.useCallback(()=>{c(!1),o()},[o]),f=n.data,h=f?.semanticUnavailable===!0&&!i&&u.length>0;l.useEffect(()=>{!h||!e||(c(!0),a({path:{accountId:e},body:mi(QC(u))}))},[h,e,u,a]);const v=i||(f?.semanticUnavailable??!1),x=n.isPending||h,p=i?{matchOperator:"Or",literalClauses:jr(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:m,reset:d,matchedCount:x?void 0:f?.matchedCount,messageIds:x?void 0:f?.messageIds,semanticUnavailable:v,senderFallback:i,senders:u,matchPredicate:p,isPending:x,isError:n.isError,error:n.error}},YC=()=>[fr({path:{mailboxId:""}}),Za({path:{mailboxId:""}}),eo()].map(e=>[{_id:e[0]._id}]),XC=e=>xd(e)?e.pages:bd(e)?[e]:[],JC=e=>typeof e=="object"&&e!==null&&typeof e.messageId=="string",ZC=(e,t)=>{const s=new Set(t),n=new Map;for(const a of e)for(const o of XC(a))for(const i of o.items){if(!JC(i)||!s.has(i.messageId))continue;const c=i.subject?.trim();c&&n.set(i.messageId,c)}return t.map(a=>n.get(a)).filter(a=>a!==void 0)},ek=e=>{const t=De(),s=e.join("\0");return l.useMemo(()=>{const n=YC().flatMap(a=>t.getQueriesData({queryKey:a}).map(([,o])=>o));return ZC(n,e)},[t,s])},tk=({failure:e,isStarting:t,isRunning:s,isDone:n,failedCount:a,ruleSaved:o})=>e?.kind==="restartFailed"?"backApplyRestartFailed":e?.kind==="startFailed"?o?"backApplyStartFailed":"commitFailed":n?a>0?"backApplyFailed":"backApplyComplete":e?.kind==="statusUnreadable"?"statusUnknown":t||s?"backApplyRunning":"saving",sk={clauses:[],matchOperator:"any"},nk={clauses:[],matchOperator:"all",droppedFacets:[],keptTerms:!1,droppedSemantic:!1},rk=[],ls={state:"saving",matched:0,applied:0,failed:0,failures:[]},fa=(e,t)=>e.map((s,n)=>({...s,id:`${t}-${n}`})),Vl=(e,t,s)=>{if(e==="delete")return{kind:"delete"};if(e==="markRead")return{kind:"markRead"};const n=e==="junk"?s:t;return n?{kind:"move",destinationMailboxId:n}:void 0},ma=e=>e==="move"||e==="junk"||e==="organize",Ql=e=>e==="junk"?nf:"No destination was chosen, so there is nowhere to file these. Go back and pick a folder.";function ak({verb:e,accountId:t,mailboxId:s,selection:n,crossAccount:a=!1,escalated:o,escalatedProgress:i,searchConversion:c,onFinished:u,onRunEnded:m,step:d,goToStep:f,goBack:h,closeWizard:v}){const[x]=l.useState(()=>c),[p]=l.useState(()=>o),b=x!==void 0,[y,S]=l.useState(b?"properties":"selected"),g=p?"escalated":y,[w,C]=l.useState(()=>x?{clauses:fa(x.clauses,"search"),matchOperator:x.matchOperator}:sk),[R,O]=l.useState(void 0),[k,M]=l.useState(void 0),[P,E]=l.useState(!1),[L,A]=l.useState(void 0),[j,I]=l.useState(void 0),[D,T]=l.useState(),F=l.useRef(!1),N=l.useRef(!1),V=l.useMemo(()=>n.map(U=>U.id),[n]),J=l.useMemo(()=>n.map(U=>U.email).filter(Boolean),[n]),re=V[0],oe=ek(V),{junkMailboxId:ie}=kn(t),Z=GC(p?void 0:t,re,J),{preview:ae}=Z;l.useEffect(()=>{ae()},[ae]);const fe=g==="similar"||g==="properties",B=l.useMemo(()=>({matchOperator:w.matchOperator==="all"?"And":"Or",literalClauses:w.clauses.map(U=>({field:U.field,value:U.value}))}),[w.clauses,w.matchOperator]),$=g==="similar"?Z.matchPredicate:B,{count:me,matchedIds:ge}=Fh(fe?t:void 0,$),Se=VC(fe?ge:[]),Ne=HC(p?s:void 0,p?.searchQuery),H=p?{status:"ready",count:p.total}:fe?me:{status:"ready",count:n.length},{data:Ee}=we({...it({path:{accountId:t??""}}),enabled:!!t,staleTime:Number.POSITIVE_INFINITY}),xe=Uo(t),ke=io(),de=l.useMemo(()=>lo({mailboxes:Ee?.items??[],folderAppointments:xe,currentMailboxId:s,translator:ke}),[Ee?.items,xe,s,ke]),{createFolderIn:se}=Pc(t),ye=de.find(U=>U.id===w.moveMailboxId)?.label,Pe=Xb(n.map(U=>({normalizedEmail:U.email,displayName:U.sender}))),ze=av({match:g==="properties"&&w.clauses[0]?.value.trim()||void 0,sender:Pe?Du(Pe):void 0,folder:ye}),X=l.useMemo(()=>({...w,name:w.name??ze}),[w,ze]),Ze=MC(R?.draft.field,R?.draft.value??"",J),Ie=$h(t),qe=_h(t),K=yf({mailboxId:s??"",accountId:t,enabled:!1,predicateKey:"selection-wizard",searchQuery:{}}),{runAction:Qe}=K,Re=mh({verb:e,mode:g,scope:w.scope,fromSearch:b}),be=Re[di(Re,d)],Oe=!a&&!!t,pe=Oe?void 0:gh,Ce=Oe?void 0:xh,_=(U=>{if(U==="folder")return Ce;if(U==="rule")return X.scope==="standing"||X.scope==="until"?pe:void 0})(be)??hh(be,X,H),le=l.useCallback(()=>fa(rv(J,oe),"seed"),[J,oe]),ue=l.useCallback(U=>{S(U),C(Y=>({...Y,widen:U==="similar"&&re?{anchorCount:Math.max(n.length,1)}:void 0,...U==="properties"&&Y.clauses.length===0?{clauses:le()}:{}}))},[re,n.length,le]),ve=l.useCallback(()=>{E(!0),S("properties"),C(U=>({...U,widen:void 0,clauses:fa(jr(J),"sender"),matchOperator:"any"})),f("properties")},[J,f]),q=Z.semanticUnavailable||Z.isError;l.useEffect(()=>{be==="match"&&(g!=="similar"||!q||P||ve())},[be,g,q,P,ve]);const he=l.useCallback(()=>{O({mode:"add",draft:{field:"From",value:""}})},[]),ne=l.useCallback(U=>{const Y=w.clauses.find(Ae=>Ae.id===U);Y&&O({mode:"edit",clauseId:U,draft:{field:Y.field,value:Y.value}})},[w.clauses]),ee=l.useCallback(U=>{C(Y=>({...Y,clauses:Y.clauses.filter(Ae=>Ae.id!==U)}))},[]),je=l.useCallback(U=>{O(Y=>Y&&{...Y,draft:U})},[]),Le=l.useCallback(()=>{O(U=>{if(!U)return;const Y=zh(U.draft.field,U.draft.value),Ae={...U.draft,value:Y};C(pt=>({...pt,clauses:U.clauseId?pt.clauses.map(yt=>yt.id===U.clauseId?{...yt,...Ae}:yt):[...pt.clauses,{id:crypto.randomUUID(),...Ae}]}))})},[]),Be=l.useCallback(()=>{if(_){M(be);return}M(void 0);const U=Re[di(Re,be)+1];U&&f(U)},[_,be,Re,f]),Xe=l.useCallback(async U=>{const Y=Vl(e,X.moveMailboxId,ie);if(!Y){I({matched:U.length,failureReason:Ql(e)});return}I({matched:U.length});const Ae=await Qe(Y,[...U]);I({matched:U.length,outcome:Ae}),N.current&&m?.(Y.kind,U.length,Ae)},[e,X.moveMailboxId,ie,Qe,m]),He=l.useCallback(async()=>{if(!p)return;const U=Vl(e,X.moveMailboxId,ie);if(!U){I({matched:p.total,failureReason:Ql(e)});return}I({matched:p.total});const Y=await p.run(U);I({matched:p.total,outcome:Y}),N.current&&m?.(U.kind,p.total,Y)},[p,e,X.moveMailboxId,ie,m]),{start:Me}=Ie,{createFilterAsync:et}=qe,Ke=l.useCallback(()=>{if(p){He();return}const U=Bh({mode:y,ruleScope:X.scope}),Y=Uh({mode:y,ruleScope:X.scope,anchorMessageId:re,clauses:X.clauses,matchOperator:X.matchOperator,moveMailboxId:X.moveMailboxId,until:X.until});if(A(U),U==="standing"||U==="temporary"){const Ae=Kh(Y)?Y:void 0;T(Ae),et(Y,U,(X.name??"").trim()).then(pt=>{pt&&Ae&&Me(Ae)});return}if(U==="all-like-these"&&ma(e)){Me(Y);return}Xe(U==="just-these"?V:ge)},[p,He,y,X,re,e,V,ge,et,Me,Xe]),lt=l.useCallback(()=>{if(_){M(be);return}F.current||(F.current=!0,f("run"),Ke())},[_,be,f,Ke]),tt=l.useCallback(U=>{const Y=Ie.progress,Ae=tk({failure:Ie.failure,isStarting:Ie.isStarting,isRunning:Ie.isRunning,isDone:Ie.isDone,failedCount:Y.failedCount,ruleSaved:U});return Ae==="saving"||Ae==="commitFailed"||Ae==="backApplyStartFailed"?{...ls,state:Ae}:{state:Ae,matched:Y.matchedCount,applied:Y.appliedCount,failed:Ae==="backApplyFailed"||Ae==="backApplyRestartFailed"?Y.failedCount:0,failures:[]}},[Ie]),zt=l.useMemo(()=>{const U=new Map;for(const Y of[...n,...Se.messages,...Ne.messages])U.set(Y.id,Y);return U},[n,Se.messages,Ne.messages]),Rt=p?i:K.progress,ns=l.useCallback(()=>{if(!j)return ls;const{matched:U,outcome:Y,failureReason:Ae}=j;if(Ae!==void 0)return{...ls,state:"commitFailed",failureReason:Ae};if(!Y){const wt=Rt?.done??0;return{state:"backApplyRunning",matched:Math.max(U,wt),applied:wt,failed:0,failures:[]}}if(!(Y.cancelled||Y.error!==void 0))return{state:"backApplyComplete",matched:Math.max(U,Y.done),applied:Y.done,failed:0,failures:[]};if(Y.done===0)return{...ls,state:"commitFailed"};const yt=Y.failedIds.map(wt=>zt.get(wt)).filter(wt=>wt!==void 0),vs=Y.failedIds.length>0?Y.failedIds.length:Math.max(U-Y.done,1);return{state:"runStopped",matched:Math.max(U,Y.done),applied:Y.done,failed:vs,failures:yt}},[j,Rt,zt]),rt=p?ns():L==="standing"||L==="temporary"?qe.isError?{...ls,state:"commitFailed"}:qe.isSuccess?D?tt(!0):{...ls,state:"filterSaved"}:ls:L==="all-like-these"&&ma(e)?tt(!1):ns(),Tt=()=>{if(rt.state==="statusUnknown"){Ie.refreshStatus();return}if(p){He();return}if(L==="standing"||L==="temporary"){if(qe.isError){qe.reset(),Ke();return}D&&Me(D);return}if(L==="all-like-these"&&ma(e)){Ke();return}const U=j?.outcome?.failedIds??[];Xe(U.length>0?U:V)},bt=l.useCallback(()=>{v(Re,be)},[v,Re,be]),vt=l.useCallback(()=>{N.current=!0,v(Re,be),u()},[v,Re,be,u]),{stop:ht}=K,rs=j!==void 0&&j.outcome===void 0&&j.failureReason===void 0,qs=l.useCallback(()=>{if(p){p.stop();return}ht()},[p,ht]);Yu({shouldBlockFn:({action:U})=>U!=="BACK"?!1:(vt(),!0),enableBeforeUnload:!1,disabled:be!=="run"});const ct={messages:p?Ne.messages:fe?Se.messages:n,count:H,label:g==="selected"?"Your selection":"A sample of what matches",emptyReason:g==="similar"&&q?"notIndexed":"noMatch",loading:p?Ne.isPending:fe&&(H.status==="loading"||Se.isPending)};return r.jsx(ph,{verb:e,steps:Re,step:be,blockedReason:_,nudged:k===be,onBack:h,onExit:be==="run"?vt:bt,onContinue:Be,onCommit:lt,match:{selectedCount:n.length,mode:g,onModeChange:ue,semanticUnavailable:q,semanticErrorDetail:Z.error instanceof Error?Z.error.message:void 0,semanticFallbackTaken:P,onSemanticFallback:ve,escalatedScope:p?.scope,sample:ct},properties:{clauses:X.clauses,matchOperator:X.matchOperator,onMatchOperatorChange:U=>C(Y=>({...Y,matchOperator:U})),clauseEdit:R,onStartAddClause:he,onStartEditClause:ne,onRemoveClause:ee,onChangeDraft:je,onSubmitClause:Le,onCancelClause:()=>O(void 0),clauseFields:qh,clauseSuggestions:Ze,conversionNotice:x?iv(x):void 0,semanticFallbackTaken:P,sample:{...ct,label:"What this matches"}},folder:{folders:de,mailboxId:X.moveMailboxId,delimiter:co(Ee?.items??[]),onSelect:U=>C(Y=>({...Y,moveMailboxId:U})),onCreateFolder:t?se:void 0,restriction:Ce},rule:{draft:X,onScopeChange:U=>C(Y=>({...Y,scope:U})),onUntilChange:U=>C(Y=>({...Y,until:U})),restriction:pe},name:{name:X.name??"",onNameChange:U=>C(Y=>({...Y,name:U})),nudged:k===be},review:{verb:e,mode:g,selectedCount:n.length,clauses:X.clauses,matchOperator:X.matchOperator,folder:ye,scope:X.scope,until:X.until,ruleName:Re.includes("name")?X.name:void 0,escalatedScope:p?.scope,sample:ct},run:{state:rt.state,verb:e,scope:X.scope,matched:rt.matched,applied:rt.applied,failedCount:rt.failed,failures:rt.failures,failureReason:rt.failureReason,onRetry:Tt,onDismiss:vt,onCancelRun:rs?qs:void 0}})}function ei(e){const t=dh()==="search",{searchConversion:s}=Fr(),{accounts:n}=Fe(),{step:a,goToStep:o,goBack:i,closeWizard:c}=fh(t?"properties":"match");if(!a)return null;const u=t?s??nk:void 0;return r.jsx(ak,{...e,...u?{verb:"organize",accountId:mC(u,e.accountId,n),selection:rk,crossAccount:!1,escalated:void 0,searchConversion:u}:{},step:a,goToStep:o,goBack:i,closeWizard:c})}const ok=200,Gl=()=>r.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>r.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[r.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsxs("div",{className:"flex justify-between gap-2",children:[r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),ik=({accountEmail:e})=>{const t=Ye();return r.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[r.jsx(Pt,{className:"size-3.5 shrink-0"}),r.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),r.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})},lk=(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 ck({header:e,rows:t,wizard:s,children:n}){const{selectedIds:a,selectedCount:o,exitSelection:i,orderedIds:c,allSelected:u,toggleAllLoaded:m}=Jo(),d=l.useMemo(()=>lk(t,a),[t,a]),{junkMailboxId:f}=kn(d.accountId),{labels:h}=uo(d.accountId),v=l.useMemo(()=>Array.from(a),[a]),x=l.useMemo(()=>t.filter(g=>a.has(g.id)).map(g=>({id:g.id,sender:g.fromName,email:g.fromEmail,subject:g.subject,date:g.timeLabel})),[t,a]),p=Lr(f,d.mailboxId),b=l.useMemo(()=>c.length>0?{checked:u,indeterminate:o>0&&!u,onChange:m}:void 0,[c.length,u,o,m]),y=d.moveDisabledHint?{tone:"warning",text:d.moveDisabledHint}:void 0,S=g=>r.jsx(Eo,{title:g.title,navSlot:g.navSlot,titleMeta:g.titleMeta,searchSlot:g.searchSlot,searchField:g.searchField,idleSlot:g.makeFilterSlot,count:o,onCancel:i,onDelete:()=>s.start("delete"),onMove:()=>s.start("move"),onOrganize:()=>s.start("organize"),onJunk:p?()=>s.start("junk"):void 0,onMarkRead:()=>s.start("markRead"),overflowSlot:d.accountId&&d.mailboxId&&o>0&&h.length>0?r.jsx(lf,{accountId:d.accountId,mailboxId:d.mailboxId,messageIds:v}):void 0,selectAll:b,notice:y});return r.jsx(ff,{...e,selectionBar:S,paneOverlay:r.jsx(ei,{verb:s.verb,accountId:d.accountId,mailboxId:d.mailboxId,selection:x,crossAccount:d.moveDisabledHint!==void 0,onFinished:i}),children:n})}function uk({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:n,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i}){const{searchQuery:c,searchInput:u,resultFolderIndex:m,onSearchChange:d}=Fe(),f=xs(),h=es(),v=Nn(),x=ro(),p=Ye(),b=l.useMemo(()=>FS(e.filter(_=>!_.muted?.value)),[e]),[y,S]=l.useState("all"),[g,w]=l.useState("all"),[C,R]=l.useState(new Set),[O,k]=l.useState(!1),M=l.useCallback(_=>{R(le=>{const ue=new Set(le);return ue.has(_)?ue.delete(_):ue.add(_),ue})},[]),P=l.useCallback(()=>R(new Set),[]),E=u.trim().length>0,L=l.useMemo(()=>Ab({query:u,ownFilters:C}),[u,C]),A=l.useMemo(()=>Ob({query:u,ownCategory:g}),[u,g]),j=l.useCallback(_=>{if(!E||!Mu(_)){M(_);return}const le=Rb(u,_);le!==void 0&&d(le)},[E,u,d,M]),I=l.useCallback(_=>{if(!E){w(_);return}d(Tb(u,_))},[E,u,d]),D=l.useCallback(()=>{w("all"),S("all"),P(),E&&d(Mb(u))},[E,u,d,P]),{data:T,isLoading:F,isError:N,refetch:V}=we({...ya(),staleTime:6e4}),J=mt({queries:b.map(_=>({...it({path:{accountId:_.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),re=l.useMemo(()=>{const _=new Map;for(let le=0;le<b.length;le++){const ue=b[le].accountId,q=(J[le]?.data?.items??[]).reduce((he,ne)=>he+(ne.unseenCount??0),0);_.set(ue,q)}return _},[b,J]),oe=l.useMemo(()=>b.filter((_,le)=>{const ue=J[le];return ue?.isError?!wa(ue.error):!1}),[b,J]),{freeText:ie,tokens:Z}=Us(c.trim().toLowerCase(),f),{data:ae,isFetching:fe}=we({...ya({query:{query:ie,limit:ok}}),enabled:ie.length>0,staleTime:3e4}),B=l.useMemo(()=>{const _=Ul(T?.items??[]).map(nr);return(ie?$S(_.filter(ue=>sf(ue,ie)),Ul(ae?.items??[]).map(nr)):_).filter(ue=>(y==="all"||ue.accountId===y)&&Go(ue,Z))},[T,ae,y,ie,Z]),{bodyRows:$,briefSpamOffer:me}=l.useMemo(()=>{if(!ie)return{bodyRows:B,briefSpamOffer:void 0};const _=B.map(ve=>Wn(ve,m)),{spam:le}=ko(_);if(le.length===0)return{bodyRows:B,briefSpamOffer:void 0};const ue=new Set(le.map(ve=>ve.id));return{bodyRows:B.filter(ve=>!ue.has(ve.id)),briefSpamOffer:of(_)}},[B,ie,m]),ge=l.useMemo(()=>_S($),[$]),Se=l.useCallback((_,le)=>{const ue=ie?$.find(ve=>ve.id===_):void 0;if(ue?.threadId&&ue.mailboxId&&n){n(Wn(ue,m),le);return}s?.(_,le)},[ie,$,m,n,s]),Ne=l.useMemo(()=>b.length<=1?[]:[{id:"all",label:"All",active:y==="all"},...b.map(_=>({id:_.accountId,label:_.email.split("@")[0]??_.email,count:re.get(_.accountId),active:y===_.accountId}))],[b,re,y]),H=l.useMemo(()=>e.filter(_=>_.muted?.value).length,[e]),Ee=l.useMemo(()=>Array.from(re.values()).reduce((_,le)=>_+le,0),[re]),xe=l.useMemo(()=>b.map(_=>_.accountId),[b]),{hasNewMail:ke}=Rr(),{state:de,errorMessage:se,refresh:ye}=Oo(xe,{onSettled:()=>V()}),Pe=l.useMemo(()=>r.jsx(jo,{state:de,onRefresh:ye,label:"Refresh daily brief",errorMessage:se,hasUpdate:ke(xe)}),[de,ye,se,ke,xe]),ze=l.useMemo(()=>B.filter(_=>(A==="all"||_.category===A)&&bh(_,L)).map(_=>Wn(_,m)),[B,A,L,m]),{hits:X,isLoading:Ze}=tf(),Ie=l.useMemo(()=>{const _=new Map;for(const ue of T?.items??[])_.set(ue.messageId,ue.threadId);const le=ze.map(ue=>_.get(ue.id)).filter(ue=>ue!=null);return rf(X,le,m)},[X,ze,T,m]),qe=l.useMemo(()=>{const _=hb(Ne.map(le=>({id:le.id,label:le.label,count:le.count,active:le.active})));return{categories:_.categories,filters:_.filters,sources:_.sources,sourcesNote:H>0?`+${H} muted`:void 0,selectedCategory:A,activeFilters:L,expanded:O,onExpandedChange:k,onSelectCategory:le=>I(le),onSelectSource:S,onToggleFilter:le=>j(le),onClear:D}},[Ne,H,A,L,O,j,I,D]),K=ge.length===0&&y==="all"&&ie.length===0&&Z.length===0,Qe=l.useMemo(()=>b.map(_=>_.accountId),[b]),Re=l.useMemo(()=>b.some(_=>Ao(_.syncPhase)),[b]),be=Yy(Qe,K||Re),Oe=r.jsxs("div",{className:"h-full overflow-y-auto",children:[r.jsx(Gl,{}),r.jsx(Gl,{})]}),pe=!F&&!N&&!K,Ce=af({tier:v,hasLiveInput:E,hasCommittedQuery:c.trim().length>0,bodyRendersCommittedResults:!0}),Te=pe?r.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[me&&r.jsx(yu,{count:me.count,onScopeToSpam:()=>p({to:"/mail/$mailboxId",params:{mailboxId:me.mailboxId},search:{q:c||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}),r.jsx("div",{className:"min-h-0 flex-1",children:r.jsx(cc,{sections:ge,briefCategory:A,Row:Zo,selectedThreadId:t,onSelectThread:Se,onSelectBriefCategory:I,sources:Ne,sourcesNote:H>0?`+${H} muted`:void 0,onSelectSource:S,activeFilters:L,onToggleFilter:j,onClearFilters:D})})]}):F?Oe: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(Pt,{className:"size-8 text-danger"}),r.jsx("p",{children:"Couldn't load your messages"}),r.jsxs("button",{type:"button",onClick:()=>V(),className:"flex items-center gap-1 text-accent underline text-xs",children:[r.jsx(xo,{className:"size-3.5"}),"Try again"]})]}):be.resolved?r.jsx(xx,{sync:be.syncing?{synced:be.synced,total:be.total}:void 0}):Oe;return r.jsx(Ic,{hasSheet:pe&&!Ce,children:r.jsx(pf,{selectedMessageId:t,onOpen:Se,onDeleteMessages:i,onSelectionVerb:x.start,wizardOpen:x.isOpen,commandsRef:a,onTriageContextChange:o,children:r.jsx(ck,{wizard:x,header:{title:"Daily brief",unreadCount:Ee,footer:h?r.jsx(ou,{}):void 0,searchFilter:qe,searchResults:ze,searchLoading:F||fe,relatedResults:Ie,relatedLoading:Ze,onSelectSearchResult:n,searchResultsInBody:!0,refreshControl:Pe},rows:B,children:r.jsxs("div",{className:"flex h-full flex-col",children:[oe.map(_=>r.jsx(ik,{accountEmail:_.email,accountId:_.accountId},_.accountId)),r.jsx("div",{className:"min-h-0 flex-1",children:Te})]})})})})}const dk=10,Sf=e=>({q:e?.toLowerCase()??"",limit:dk}),fk=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(n=>n.normalizedEmail===s)};function mk(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Xn(t,{month:"short",year:"numeric"})}function Cf(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const hk="We can't verify the sender of this email, which could mean it's from an insecure source.",pk="We couldn't read this sender's address, so we can't confirm who really sent this message.";function gk(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?mk(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Cf(e.fromEmail)}}function xk(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 Yl(e){if(e.fromName&&e.fromName!==e.fromEmail)return e.fromName}function bk(e){return e.length===1?e[0]:`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function vk(e,t){const s=[],n=e.displayNameCorrespondence;t&&(n===pi.Unrelated?s.push(`The name it shows, "${t}", has nothing to do with ${e.fromDomain}.`):n===pi.Lookalike&&s.push(`The name it shows, "${t}", only looks like ${e.fromDomain}.`));const a=yk(e.offDomainLinkDomains);return a.length>0&&s.push(`Its links go to ${bk(a.slice(0,3))}.`),s}function yk(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function wk(e,t){const s=t>0?t:void 0;if(Cf(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:pk,similarCount:s};const n=e.authenticity;if(!n)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:hk};if(!n.dkimMismatch){const m=Yl(e),d=vk(n,m);return d.length>0?{verdict:"caution",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,claimedBrand:m,summary:d.join(" ")}:{verdict:"aligned",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,summary:n.dkimDomain?`This message was signed by ${n.dkimDomain}.`:"Nothing looks unusual about this sender."}}const a=n.fromDomain,o=n.dkimDomain,i=Yl(e),c=o?`it was actually sent from ${o}`:"its signature failed to verify",u=i?`The display name claims "${i}", but ${c}${o?` — not ${a}`:""}. Real senders use their own address.`:`This message claims to be from ${a}, but ${c}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:u,similarCount:s}}function kf(e,t){const s=e?.fromEmail??null,n=e?.subject??"",{data:a,error:o}=we({...ur({query:Sf(s??void 0)}),enabled:!!s,staleTime:3e4}),i=fk(a?.items,s??void 0),c=[n,s].filter(Boolean).join(" "),{data:u,isLoading:m,error:d}=we({...Nc({query:{query:c,limit:5}}),enabled:!!(e&&c.length>3),staleTime:6e4,retry:1});return{data:l.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(y=>y.messageId!==e.messageId).map(y=>({id:y.messageId,mailboxId:t!=null&&y.mailboxIds.includes(t)?t:y.mailboxIds[0]??"",fromName:y.fromName??"",subject:y.subject??"(No subject)",timeLabel:y.sentDate!=null?gt(y.sentDate*1e3):"",matched:y.matchedChunkType})),v=gk(e,i),x=wk(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},b=xk(i);return{sender:v,authenticity:x,category:p,flags:b,similar:h}},[e,i,u,t]),isSimilarLoading:m,similarError:d,similarErrorIsFatal:wa(d),addressErrorIsFatal:wa(o),addressId:i?.addressId,address:i}}function Sk(e,t){const s={...e??{}};for(const[n,a]of Object.entries(t))a==null?delete s[n]:s[n]={...a,setAt:a.setAt??Date.now()};return s}function jf({addressId:e,senderEmail:t}){const s=De(),{pushError:n}=nt(),a=vh({query:Sf(t)}),{mutate:o,isPending:i}=Ue({...jc(),onMutate:async u=>{const m=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,f=>f&&{...f,items:f.items.map(h=>h.addressId===u.path.addressId?{...h,flags:Sk(h.flags,m)}:h)}),{previous:d}},onError:(u,m,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),n({title:"Couldn't update sender preference",detail:ft(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:l.useCallback(u=>{if(!e){Ga(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 Ck=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Nf=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function kk(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function jk(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function Nk(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Ef(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const Ek=["personal","newsletter","marketing","automated","transactional","social"],Ik=e=>e.spamReport?"notSpam":"reportSpam",Rk=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:n}=e;return t&&!s?"error":n?"loading":"ready"};function Tk(){return r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Dt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"h-8 rounded bg-surface"})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>r.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function Mk({isOpen:e,current:t,onSelect:s,onCancel:n}){return e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx(Rc,{label:"Dismiss reclassify sender",onDismiss:n,className:"backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),r.jsx("div",{className:"mt-4 flex flex-col gap-1",children:Ek.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 Ak({thread:e,onClose:t,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o}){const{data:i,addressId:c,isSimilarLoading:u,similarError:m,similarErrorIsFatal:d}=kf(e,s),[f,h]=l.useState(!1),v=e.fromEmail??void 0,{updateFlags:x}=jf({addressId:c,senderEmail:v}),{reportSpam:p,notSpam:b,isReporting:y,isRestoring:S}=wd({mailboxId:e.mailboxId,threadId:e.threadId,accountId:n,onAfterOptimisticRemove:o}),g=Ls(),w=Ik(e),C=l.useCallback(()=>{b([e.messageId])},[b,e.messageId]),R=l.useCallback(()=>{Ef(g,{count:1,senderTrust:e.senderTrust,wasRescuable:Nf(e)}),p([e.messageId])},[p,e,g]),O=l.useCallback(()=>{},[]),k=l.useCallback(()=>{const D=i?.flags?.vip!==!0;x({vip:{value:D}})},[i?.flags?.vip,x]),M=l.useCallback(()=>{const D=i?.flags?.muted!==!0;x({muted:{value:D}})},[i?.flags?.muted,x]),P=l.useCallback(()=>{const D=i?.flags?.unsubscribed!==!0;x({unsubscribed:{value:D}})},[i?.flags?.unsubscribed,x]),E=l.useCallback(D=>{h(!1),x({category:{value:D}})},[x]),L=c!==void 0,A={onToggleVip:L?k:void 0,onToggleMute:L?M:void 0,onToggleUnsubscribe:L?P:void 0,onReclassify:L?()=>h(!0):void 0,onNotSpam:w==="notSpam"?C:void 0,onReportSpam:w==="reportSpam"?R:void 0},j=({mailboxId:D,messageId:T,className:F,ariaLabel:N,children:V})=>r.jsx(Ht,{to:"/mail/$mailboxId",params:{mailboxId:D},search:J=>({...J,selectedMessageId:T}),variant:"row",className:F,"aria-label":N,children:V});if(!i)return r.jsx(Tk,{});const I=Rk({similarError:m,similarErrorIsFatal:d,isSimilarLoading:u});return r.jsxs(r.Fragment,{children:[r.jsx(tu,{data:i,onClose:t,hideCloseButton:a,onShowSimilar:O,actions:A,similarState:I,similarLinkComponent:j,reportSpamPending:y,notSpamPending:S,className:"border-l-0 h-full w-full"}),r.jsx(Mk,{isOpen:f,current:i.category.value,onSelect:E,onCancel:()=>h(!1)})]})}const Ks=({onClose:e,thread:t,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o})=>t?r.jsx(Ak,{thread:t,onClose:e,mailboxId:s,accountId:n,hideCloseButton:a,onAfterOptimisticRemove:o}):r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Dt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[r.jsx(Dt,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),ha="Open a message first",ti=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:n,onReply:a,onReplyAll:o,onForward:i,onDelete:c,canDelete:u,onToggleStar:m,isStarred:d,moveContext:f})=>{const[h,v]=l.useState(null),x=u??e,p=b=>()=>v(b);return r.jsx(Cg,{hasThread:e,isStarred:d,onUnavailable:b=>v(ha),unavailableHint:h,replyTitle:`Reply ${Vs("reply")}`,replyAllTitle:`Reply all ${Vs("replyAll")}`,forwardTitle:`Forward ${Vs("forward")}`,deleteTitle:`Move to Trash ${Vs("delete")}`,flagTitle:`Star ${Vs("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:x?c:p(ha),onToggleStar:m,onMove:p(ha),moveSlot:f?r.jsx(Vo,{accountId:f.accountId,currentMailboxId:f.currentMailboxId,onMove:f.onMove,label:"Move to mailbox"}):void 0,children:r.jsx(Sg,{open:t,enabled:s,onToggle:n})})},If=()=>{const e=De();return l.useCallback(t=>{const s=Zt({path:{threadId:t.threadId}}),a=e.getQueriesData({queryKey:s}).flatMap(([,o])=>o?.items.map(i=>i.messageId)??[]);return a.length>0?a:[t.messageId]},[e])},mn=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=t??e?.mailboxId,o=s??e?.accountId,{accountId:i}=_o(o?void 0:a),c=o??i,u=If(),{deleteMessages:m}=ms({mailboxId:a??"",threadId:e?.threadId,accountId:c,onAfterOptimisticRemove:n}),{moveMessages:d}=Ds({mailboxId:a??"",threadId:e?.threadId,accountId:c,onAfterOptimisticRemove:n}),{toggleStar:f}=zo({threadId:e?.threadId??"",mailboxId:a??""}),h=l.useCallback(()=>{e&&m(u(e))},[e,u,m]),v=l.useCallback(S=>{e&&d(u(e),S)},[e,u,d]),x=l.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[p,b]=l.useState(null),y=l.useCallback(()=>b(null),[]);return{mailboxId:a,accountId:c,isStarred:e?.hasStars,deleteThread:h,moveThread:v,toggleStar:x,composeRequest:p,requestCompose:b,clearComposeRequest:y}},Xl=(e,t,s)=>{if(!t)return null;const n=e.indexOf(t);if(n===-1)return null;const a=s==="next"?n+1:n-1;return a<0||a>=e.length?null:e[a]},si=()=>{const[e,t]=l.useState(void 0),[s,n]=l.useState([]),[a,o]=l.useState([]),i=l.useRef(null),[c,u]=l.useState(!1),[m,d]=l.useState(!1),f=l.useCallback(h=>{t(h.focusedMessageId),n(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:f,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:c,blocksKeyboard:m}},ni=({context:e,orderedIds:t,selectedMessageId:s,enabled:n=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:c,blocksKeyboard:u}=e,m=l.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return cv({enabled:n&&!u,handlers:{...c?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:m,...o}}),{goBack:m,nextMessageId:Xl(t,s,"next")??void 0,previousMessageId:Xl(t,s,"previous")??void 0}};function Ok(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function Rf(e,t){if(e)return Ok(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const Tf=l.createContext(null);function $r(){const e=l.useContext(Tf);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function Dk({selectedMessageId:e,children:t}){const s=Ye(),{searchInput:n}=Fe(),{selectedThreadId:a,selectedMailboxId:o}=As({strict:!1}),{data:i}=we({...ya(),staleTime:6e4}),c=l.useMemo(()=>{if(e)return i?.items.find(M=>M.messageId===e)},[i,e]),u=l.useMemo(()=>Rf(c,{messageId:e,threadId:a,mailboxId:o}),[c,e,a,o]),m=l.useCallback((M,P)=>{s({to:"/mail",search:E=>({...E,selectedMessageId:M,selectedThreadId:void 0,selectedMailboxId:void 0}),replace:P?.replace})},[s]),d=l.useCallback((M,P)=>{s({to:"/mail",replace:P?.replace,search:E=>({...E,q:n||void 0,selectedMessageId:M.id,selectedThreadId:M.threadId,selectedMailboxId:M.mailboxId})})},[s,n]),f=l.useCallback(M=>{e&&M.includes(e)&&s({to:"/mail",search:P=>({...P,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=mn({thread:c,onAfterOptimisticRemove:f}),v=l.useCallback(()=>{s({to:"/mail",search:M=>({...M,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),x=si(),p=l.useMemo(()=>i?.items??[],[i]),{deleteMessages:b}=ms({mailboxId:c?.mailboxId??"",messages:p,onAfterOptimisticRemove:f}),{toggleReadFor:y}=Ar({mailboxId:c?.mailboxId??"",messages:p}),S=x.focusedMessageId,w=l.useMemo(()=>i?.items.find(M=>M.messageId===S),[i,S])??c,C=mn({thread:w}),{nextMessageId:R,previousMessageId:O}=ni({context:x,orderedIds:x.orderedIds,selectedMessageId:e,onClose:v,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{x.listCommandsRef.current?.requestVerb("delete")||C.deleteThread()},toggleStar:C.toggleStar,toggleRead:()=>{x.listCommandsRef.current?.requestVerb("markRead")||w&&y([w.messageId],!w.isRead)},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),k={selectedMessageId:e,selectedThread:c,conversation:u,onSelectMessage:m,onSelectSearchResult:d,onCloseThread:v,actions:h,triage:x,onDeleteMessages:b,nextMessageId:R,previousMessageId:O,handleDeselectIfRemoved:f};return r.jsx(Tf.Provider,{value:k,children:t})}function Mf(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:n,onDeleteMessages:a}=$r(),{accounts:o}=Fe();return r.jsx(uk,{accounts:o,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:n.listCommandsRef,onTriageContextChange:n.onTriageContextChange,onDeleteMessages:a})}function Pk(){const{conversation:e,actions:t}=$r(),{intelligenceOpen:s,onToggleIntelligence:n}=Fe(),a=ps()?.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(ti,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(zs,{})})]})}function Lk(){const{selectedThread:e,handleDeselectIfRemoved:t}=$r(),{onToggleIntelligence:s}=Fe();return r.jsx(Ks,{onClose:s,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,onAfterOptimisticRemove:t})}function Fk(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:n,nextMessageId:a,previousMessageId:o,handleDeselectIfRemoved:i}=$r(),{intelligenceOpen:c,onToggleIntelligence:u}=Fe();return t?r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:n,onOpenIntelligence:u,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:c}),r.jsx(Lo,{isOpen:c,onClose:u,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:u,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,hideCloseButton:!0,onAfterOptimisticRemove:i})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Mf,{})})}const Zs=Object.assign(Dk,{List:Mf,Reading:Pk,Intelligence:Lk,Phone:Fk}),$k=()=>eo({query:{starred:!0,order:"desc"}});function Af(){const{data:e,isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:c}=Gu({queryKey:$k(),queryFn:async({pageParam:m})=>{const{data:d}=await yh({query:{starred:!0,order:"desc",continuationToken:m},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:m=>m.continuationToken,staleTime:6e4});return{threads:l.useMemo(()=>(e?.pages??[]).flatMap(m=>m.items??[]),[e]),isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:c}}const _k=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function Of({title:e,unreadCount:t,preset:s,selectedCategory:n,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:c,onClearFilters:u,children:m,footer:d,searchResults:f,searchLoading:h,relatedResults:v,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:y,searchResultsInBody:S,refreshControl:g}){const{searchInput:w}=Fe(),C=w.trim().length>0,R={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:n,activeFilters:a,onSelectCategory:o,onSelectSource:c,onToggleFilter:i,onClear:u};return r.jsx(Ic,{hasSheet:!C,children:r.jsx(ff,{title:e,unreadCount:t,footer:d,searchFilter:R,searchResults:f,searchLoading:h,relatedResults:v,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:b,relatedResultsLabel:y,searchResultsInBody:S,refreshControl:g,children:r.jsx(pc,{...R,hideChrome:C,children:m})})})}const zk={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function Bk({rows:e,verb:t}){const{selectedIds:s,exitSelection:n}=Jo(),a=l.useMemo(()=>e.filter(o=>s.has(o.id)).map(o=>({id:o.id,sender:o.fromName,email:o.fromEmail,subject:o.subject,date:o.timeLabel})),[e,s]);return r.jsx(ei,{verb:t,selection:a,crossAccount:!0,onFinished:n})}function Uk({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:n,onDeleteMessages:a}){const{searchQuery:o,resultFolderIndex:i}=Fe(),c=xs(),u=es(),m=ro(),[d,f]=l.useState("all"),[h,v]=l.useState(new Set),x=l.useCallback(F=>{v(N=>{const V=new Set(N);return V.has(F)?V.delete(F):V.add(F),V})},[]),p=l.useCallback(()=>{f("all"),v(new Set)},[]),{threads:b,isLoading:y,isError:S,error:g,refetch:w,fetchNextPage:C,hasNextPage:R,isFetchingNextPage:O}=Af(),{freeText:k,tokens:M}=Us(o.trim().toLowerCase(),c),P=l.useMemo(()=>{const F=Array.from(h).map(N=>zk[N]).filter(N=>N!=null);return _k(b).map(nr).filter(N=>(d==="all"||N.category===d)&&F.every(V=>V(N))&&(!k||sf(N,k))&&Go(N,M))},[b,d,h,k,M]),E=l.useMemo(()=>pb(),[]),L=l.useMemo(()=>P.map(F=>Wn(F,i)),[P,i]),A=l.useMemo(()=>P.filter(F=>!F.isRead).length,[P]),j=y?"loading":S?"error":P.length===0?"empty":"ready",I=l.useCallback(()=>{const F=to(so());window.open(F,"_blank","noopener,noreferrer")},[]),D=Fr(),T=r.jsx("div",{className:"flex h-full min-h-0 flex-col",children:r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r.jsx("div",{className:"divide-y divide-line",children:P.map(F=>r.jsx(Zo,{thread:F,active:F.id===e,onClick:()=>t?.(F.id)},F.id))}),R?r.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>C(),disabled:O,children:O?"Loading…":"Load more"}):null]})});return r.jsx(Of,{title:"Starred",unreadCount:A,preset:E,selectedCategory:d,activeFilters:h,onSelectCategory:f,onToggleFilter:x,onClearFilters:p,searchResults:L,searchLoading:y,onSelectSearchResult:F=>t?.(F.id),searchResultsInBody:!0,children:r.jsxs(pf,{selectedMessageId:e,onOpen:(F,N)=>t?.(F,N),onDeleteMessages:a,onSelectionVerb:m.start,wizardOpen:m.isOpen,commandsRef:s,onTriageContextChange:n,children:[r.jsx(pu,{listTitle:"Starred",sections:[{id:"flagged",threads:P}],flatList:!0,hideHeader:!0,listState:D.searchResults?"ready":j,searchQuery:k?o:void 0,errorMessage:S?Ac(g):void 0,onRetry:()=>w(),onReportError:I,selectedThreadId:e,onSelectThread:t,isDesktop:u,selectionBar:r.jsx(CC,{title:"Starred"}),listBody:D.searchResults??(j==="ready"?T:void 0)}),r.jsx(Bk,{rows:P,verb:m.verb})]})})}const Df=l.createContext(null);function _r(){const e=l.useContext(Df);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function Kk({selectedMessageId:e,children:t}){const s=Ye(),{threads:n}=Af(),a=l.useMemo(()=>{if(e)return n.find(g=>g.messageId===e)},[n,e]),o=l.useCallback((g,w)=>{s({to:"/mail/flagged",search:C=>({...C,selectedMessageId:g}),replace:w?.replace})},[s]),i=l.useCallback(()=>{s({to:"/mail/flagged",search:g=>({...g,selectedMessageId:void 0})})},[s]),c=l.useCallback(g=>{e&&g.includes(e)&&i()},[e,i]),u=mn({thread:a,onAfterOptimisticRemove:c}),m=si(),{deleteMessages:d}=ms({mailboxId:a?.mailboxId??"",messages:n,onAfterOptimisticRemove:c}),{toggleReadFor:f}=Ar({mailboxId:a?.mailboxId??"",messages:n}),h=m.focusedMessageId,x=l.useMemo(()=>n.find(g=>g.messageId===h),[n,h])??a,p=mn({thread:x}),{nextMessageId:b,previousMessageId:y}=ni({context:m,orderedIds:m.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{m.listCommandsRef.current?.requestVerb("delete")||p.deleteThread()},toggleStar:p.toggleStar,toggleRead:()=>{m.listCommandsRef.current?.requestVerb("markRead")||x&&f([x.messageId],!x.isRead)},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),S={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:m,onDeleteMessages:d,nextMessageId:b,previousMessageId:y,handleDeselectIfRemoved:c};return r.jsx(Df.Provider,{value:S,children:t})}function Pf(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:n}=_r();return r.jsx(Uk,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:n})}function qk(){const{selectedThread:e,actions:t}=_r(),{intelligenceOpen:s,onToggleIntelligence:n}=Fe(),a=ps()?.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(ti,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(zs,{})})]})}function Hk(){const{selectedThread:e,handleDeselectIfRemoved:t}=_r(),{onToggleIntelligence:s}=Fe();return r.jsx(Ks,{onClose:s,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,onAfterOptimisticRemove:t})}function Wk(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:n,previousMessageId:a,handleDeselectIfRemoved:o}=_r(),{intelligenceOpen:i,onToggleIntelligence:c}=Fe();return e?r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:c,onSwipeNext:n?()=>s(n):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:i}),r.jsx(Lo,{isOpen:i,onClose:c,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:c,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId,hideCloseButton:!0,onAfterOptimisticRemove:o})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Pf,{})})}const en=Object.assign(Kk,{List:Pf,Reading:qk,Intelligence:Hk,Phone:Wk}),Vk={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Qk=()=>{const e=l.useRef(!1);return l.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector('[data-testid="compose-body"]')?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},Gk=()=>{const{state:e,closeCompose:t}=Jt(),s=Qk(),[n,a]=l.useState(!1),{isError:o,error:i,refetch:c}=we({...$t(),staleTime:1/0}),u=l.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),m=l.useCallback(()=>{a(!1),t()},[t]),d=l.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const f=Vk[e.mode]??"New Message";return r.jsxs(dt.Root,{open:e.isOpen,onOpenChange:u,children:[r.jsxs(dt.Portal,{children:[r.jsx(dt.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(dt.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-lg bg-canvas pb-[env(safe-area-inset-bottom,0px)]",style:{height:"95dvh"},children:[r.jsx(dt.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),r.jsx(dt.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:f}),o?r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(ts,{title:"Couldn't load compose",error:i,onRetry:()=>{c()}})}):r.jsx("div",{className:"flex-1 overflow-hidden",children:r.jsx(Fo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),r.jsx(fo,{isOpen:n,title:"Discard draft?",description:"Your message has unsaved content. Are you sure you want to discard it?",confirmLabel:"Discard",cancelLabel:"Keep editing",destructive:!0,onConfirm:m,onCancel:d})]})},Yk={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},Lf=()=>{const{state:e,closeCompose:t}=Jt(),s=es(),{isError:n,error:a,refetch:o}=we({...$t(),staleTime:1/0});if(!s)return r.jsx(Gk,{});if(!e.isOpen)return null;const i=Yk[e.mode]??"New Message",c=r.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[r.jsx("div",{className:"flex items-center gap-2 min-w-0",children:r.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:r.jsx(Nt,{className:"size-5"})})]});return n?r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[c,r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(ts,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):r.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[c,r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:r.jsx(Fo,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function Xk(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:gt(e.updatedAt),isRead:!0}}function Jk(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:gt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function Zk({outboxMessages:e,accountId:t,imapThreads:s}){const n=e.filter(i=>i.status==="draft"&&i.accountId===t).map(Xk),a=s.map(Jk),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 ri(){const e=ps();return!e||e.showNavPane?null:r.jsx(ce,{variant:"ghost",size:"sm",icon:r.jsx(pr,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const ej=({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})]}),tj=({row:e,isSelected:t,onOpen:s,onDelete:n,isDeleting:a})=>r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:Q("group",_s({active:t})),children:[r.jsx(fc,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),r.jsx(cn,{thread:e}),r.jsx("div",{className:"flex items-center gap-1 shrink-0",children:r.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),n(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:r.jsx(Lt,{className:"size-3.5"})})})]}),sj=({row:e,isSelected:t,onOpen:s})=>{const n=!e.isRead;return r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:Q("group",_s({active:t})),children:[n&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx(jt,{name:e.fromName,email:e.fromEmail,size:"sm"}),r.jsx(cn,{thread:e})]})};function nj({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:n,title:a,unreadCount:o}){const{openCompose:i,state:c}=Jt(),u=Ye(),m=De(),{data:d}=we(cr()),f=l.useMemo(()=>Zk({outboxMessages:d?.items??[],accountId:t,imapThreads:n}),[d?.items,t,n]),h=Ue({...dr(),onSuccess:()=>{m.invalidateQueries({queryKey:ao()})}}),v=y=>{h.mutate({path:{outboxMessageId:y}})},x=y=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:y})},p=y=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:y}})},b=f.length===0;return r.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(ri,{}),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(Ba,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):f.map(y=>r.jsxs("div",{children:[y.label&&r.jsx(ej,{label:y.label,count:y.threads.length}),r.jsx("div",{className:"divide-y divide-line",children:y.threads.map(S=>y.id==="remit-drafts"?r.jsx(tj,{row:S,isSelected:c.isOpen&&S.id===c.outboxMessageId,onOpen:x,onDelete:v,isDeleting:h.isPending},S.id):r.jsx(sj,{row:S,isSelected:S.id===s,onOpen:p},S.id))})]},y.id))})]})}function rj(e,t,s){const n=new Array(e);return new Proxy(n,{get(a,o,i){if(typeof o=="string"){const c=o.charCodeAt(0);if(c>=48&&c<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let m=a[u];if(!m){const d=t[u*2];m=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return m}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function Ns(e,t,s){let n=s.initialDeps??[],a,o=!0;function i(){const c=e();return(c.length!==n.length||c.some((m,d)=>n[d]!==m))&&(n=c,a=t(...c),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=c=>{n=c},i}function Jl(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const aj=(e,t)=>Math.abs(e-t)<1.01,oj=(e,t,s)=>{let n;return function(...a){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,a),s)}};let tn;const pa=()=>{if(tn!==void 0)return tn;if(typeof navigator>"u")return tn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return tn=!0;const e=navigator.maxTouchPoints;return tn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Zl=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},ij=e=>e,lj=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},cj=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const a=i=>{const{width:c,height:u}=i;t({width:Math.round(c),height:Math.round(u)})};if(a(Zl(s)),!n.ResizeObserver)return()=>{};const o=new n.ResizeObserver(i=>{const c=()=>{const u=i[0];if(u?.borderBoxSize){const m=u.borderBoxSize[0];if(m){a({width:m.inlineSize,height:m.blockSize});return}}a(Zl(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},rr={passive:!0},uj=typeof window>"u"?!0:"onscrollend"in window,dj=(e,t,s)=>{const n=e.scrollElement;if(!n)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&uj;let i=0;const c=o?null:oj(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=f=>()=>{i=s(n),c?.(),t(i,f)},m=u(!0),d=u(!1);return n.addEventListener("scroll",m,rr),o&&n.addEventListener("scrollend",d,rr),()=>{n.removeEventListener("scroll",m),o&&n.removeEventListener("scrollend",d)}},fj=(e,t)=>dj(e,t,s=>{const{horizontal:n,isRtl:a}=e.options;return n?s.scrollLeft*(a&&-1||1):s.scrollTop}),mj=(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"]},hj=(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})},pj=hj;class gj{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,n,a;return((a=(n=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:n.now)==null?void 0:a.call(n))??Date.now()},this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const c=o.target,u=this.indexFromElement(c);if(!c.isConnected){this.observer.unobserve(c);for(const[m,d]of this.elementsCache)if(d===c){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(c,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=n())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=n())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=n())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var n,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:ij,rangeExtractor:lj,onChange:()=>{},measureElement:mj,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in s){const v=s[h];v!==void 0&&(o[h]=v)}const i=this.options;let c=null,u=null,m=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,v=o.count,x=this.getMeasurements(),p=h>0?((n=x[0])==null?void 0:n.key)??i.getItemKey(0):null,b=h>0?((a=x[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(v!==h||h>0&&v>0&&(o.getItemKey(0)!==p||o.getItemKey(v-1)!==b)){m=!0;const g=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??x[0]:null;g&&(c=[g.key,this.getScrollOffset()-g.start]);const w=o.followOnAppend===!0?"auto":o.followOnAppend||null;w&&v>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(v-1)!==b)&&(u=w)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(c&&this.scrollOffset!==null){const[h,v]=c,x=this.getMeasurements(),{count:p,getItemKey:b}=this.options;let y=0;for(;y<p&&b(y)!==h;)y++;if(y<p){const S=x[y];if(S){const g=S.start+v;g!==this.scrollOffset&&(f=g-this.scrollOffset,this.scrollOffset=g,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?c[0]:null,d?c[1]:0,u,f])},this.notify=s=>{var n,a;(a=(n=this.options).onChange)==null||a.call(n,this,s)},this.maybeNotify=Ns(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}if(this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const c=this.getScrollOffset();this.scrollDirection=i?c===o?this.scrollDirection:c<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},c=()=>{this._iosTouching=!1,!(!pa()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,rr),o.addEventListener("touchend",c,rr),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",c),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,c,u]=a;o!==null&&!c&&(pa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),c&&this.scrollToEnd({behavior:c})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),n=this.getMaxScrollOffset();if(s<0||s>n)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=Ns(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,n,a,o,i,c,u,m)=>(this.prevLanes!==void 0&&this.prevLanes!==c&&(this.lanesChangedFlag=!0),this.prevLanes=c,this.pendingMin=null,{count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:c,laneAssignmentMode:u,gap:m}),{key:!1}),this.getMeasurements=Ns(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:c,laneAssignmentMode:u,gap:m},d)=>{const f=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const y of this.laneAssignments.keys())y>=s&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),c===1){const y=s*2;let S=this._flatMeasurements;if(!S||S.length<y){const C=new Float64Array(y);S&&h>0&&C.set(S.subarray(0,h*2)),S=C,this._flatMeasurements=S}let g;if(h===0)g=n+a;else{const C=h-1;g=S[C*2]+S[C*2+1]+m}for(let C=h;C<s;C++){const R=o(C),O=f.get(R),k=typeof O=="number"?O:this.options.estimateSize(C);S[C*2]=g,S[C*2+1]=k,g+=k+m}const w=rj(s,S,o);return this.measurementsCache=w,w}const v=this.measurementsCache.slice(0,h),x=new Array(c).fill(void 0),p=new Float64Array(c);let b=0;for(let y=0;y<h;y++){const S=v[y];S&&(x[S.lane]===void 0&&b++,x[S.lane]=y,p[S.lane]=S.end)}for(let y=h;y<s;y++){const S=o(y),g=this.laneAssignments.get(y);let w,C;const R=u==="estimate"||f.has(S);if(g!==void 0&&this.options.lanes>1){w=g;const P=x[w],E=P!==void 0?v[P]:void 0;C=E?E.end+m:n+a}else if(b===c){let P=0,E=p[0],L=x[0];for(let A=1;A<c;A++){const j=p[A];(j<E||j===E&&x[A]<L)&&(P=A,E=j,L=x[A])}w=P,C=E+m,R&&this.laneAssignments.set(y,w)}else w=y%this.options.lanes,C=n+a,R&&this.laneAssignments.set(y,w);const O=f.get(S),k=typeof O=="number"?O:this.options.estimateSize(y),M=C+k;v[y]={index:y,start:C,size:k,end:M,key:S,lane:w},x[w]===void 0&&b++,x[w]=y,p[w]=M}return this.measurementsCache=v,v},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ns(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,a,o)=>s.length===0||n===0?(this.range=null,null):(this.range=bj(s,n,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ns(()=>{let s=null,n=null;const a=this.calculateRange();return a&&(s=a.startIndex,n=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:n,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,a=s.getAttribute(n);return a?parseInt(a,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),c=Math.min(this.options.count-1,a+o);return s>=i&&s<=c}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,c)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(c))});return}const n=this.indexFromElement(s),a=this.options.getItemKey(n),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,n)=>{var a,o;if(s<0||s>=this.options.count)return;let i,c,u;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)u=this.options.getItemKey(s),c=m[s*2],i=m[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,c=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,f=n-d;if(f!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,v=h?this.getTotalSize():0,x=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:c,size:i,end:c+i,lane:0},f,this):c<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,n),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-v):x&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=Ns(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const c=s[o],u=n[c];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=Ff(0,n.length-1,o?c=>a[c*2]:c=>Jl(n[c]).start,s);return Jl(n[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,n,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+o?"end":"start"),n==="center"?s+=(a-o)/2:n==="end"&&(s-=o);const c=this.getMaxScrollOffset();return Math.max(Math.min(c,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(n==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)n="end";else if(i.start<=o+this.options.scrollPaddingStart)n="start";else return[o,n];if(n==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),n];const c=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(c,n,i.size),n]},this.scrollToOffset=(s,{align:n="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,n),i=this.now();this.scrollState={index:null,align:n,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:n="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,n);if(!o)return;const[i,c]=o,u=this.now();this.scrollState={index:s,align:c,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:n="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let a;if(n.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=n.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=n[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&o.some(c=>c===null);){const c=n[i];o[c.lane]===null&&(o[c.lane]=c.end),i--}a=Math.max(...o.filter(c=>c!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const n=this.getMeasurements();for(const a of n)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:n,behavior:a})=>{this._intendedScrollOffset=s+(n??0),this.options.scrollToFn(s,{behavior:a,adjustments:n},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&(pa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const n=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=n?n[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&aj(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const c=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&u>c;this.scrollState.lastTargetOffset=a,m||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Ff=(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 xj(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 bj(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=xj(a,o,s);let d=m;const f=s+t;for(;d<o&&a[d*2]+a[d*2+1]<f;)d++;return{startIndex:m,endIndex:d}}let c=Ff(0,o,m=>e[m].start,s),u=c;if(n===1)for(;u<o&&e[u].end<s+t;)u++;else if(n>1){const m=Array(n).fill(0);for(;u<o&&m.some(f=>f<s+t);){const f=e[u];m[f.lane]=f.end,u++}const d=Array(n).fill(s+t);for(;c>=0&&d.some(f=>f>=s);){const f=e[c];d[f.lane]=f.start,c--}c=Math.max(0,c-c%n),u=Math.min(o,u+(n-1-u%n))}return{startIndex:c,endIndex:u}}const ga=typeof document<"u"?l.useLayoutEffect:l.useEffect;function vj({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...n}){const a=l.useReducer(m=>m+1,0)[1],o=l.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=m=>{const d=o.current;if(!d.enabled||!d.container)return;const f=m.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const y=m.options.horizontal?"width":"height";d.container.style[y]=`${f}px`}const h=!!m.options.horizontal,v=d.mode==="transform",x=h?"left":"top",p=m.options.scrollMargin,b=m.getVirtualItems();for(const y of b){const S=y.start-p,g=m.elementsCache.get(y.key);g&&d.lastPositions.get(g)!==S&&(d.lastPositions.set(g,S),v?g.style.transform=h?`translate3d(${S}px, 0, 0)`:`translate3d(0, ${S}px, 0)`:g.style[x]=`${S}px`)}},c={...n,onChange:(m,d)=>{var f;const h=o.current;let v=!0;if(h.enabled){i(m);const x=m.range,p=h.prevRange;v=!p||p.isScrolling!==m.isScrolling||p.startIndex!==x?.startIndex||p.endIndex!==x?.endIndex,v&&(h.prevRange=x?{startIndex:x.startIndex,endIndex:x.endIndex,isScrolling:m.isScrolling}:null)}v&&(e&&d?Ha.flushSync(a):a()),(f=n.onChange)==null||f.call(n,m,d)}},[u]=l.useState(()=>{const m=new gj(c);return Object.assign(m,{containerRef:d=>{const f=o.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const h=m.getTotalSize();f.lastSize=h;const v=m.options.horizontal?"width":"height";d.style[v]=`${h}px`}}})});return u.setOptions(c),ga(()=>u._didMount(),[]),ga(()=>u._willUpdate()),ga(()=>{i(u)}),u}function yj(e){return vj({observeElementRect:cj,observeElementOffset:fj,scrollToFn:pj,...e})}const ai=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",wj=e=>`Select all ${ai(e)}`,Sj=(e,t)=>`All ${Gt(t)} ${ai(e)} selected`,Cj=({verb:e,confirmingDelete:t,hasSelection:s,junkMailboxId:n,currentMailboxId:a,deletableMessageId:o})=>{if(t)return{kind:"withheld"};if(e==="junk"){const i=BS(n,a);if(i!==void 0)return{kind:"unavailable",reason:i}}return s?{kind:"openWizard"}:e!=="delete"||o===void 0?{kind:"declined"}:{kind:"confirmDelete",messageId:o}},kj=(e,t,s)=>e==="BACK"&&t&&s===void 0,jj=(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:gt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Or(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),Nj=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,messageCount:m,isMultiSelectMode:d,onLongPress:f,isDesktop:h,density:v})=>r.jsx(Zo,{thread:jj(e,m),linkMailboxId:t,inListbox:!0,active:s,focused:n,isTabStop:a,density:v,isDesktop:h,onFocusRow:o,selection:{isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:d,onLongPress:f}}),Ej=l.memo(Nj),Ij=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:gt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:Or(e.category),suspicious:t}},Rj=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,onDelete:h,onToggleRead:v,density:x})=>{const[p,b]=l.useState("none"),y=Ye(),S=l.useCallback(O=>{navigator.vibrate?.(10),O==="trailing"?h(e.messageId):v(e.messageId,e.isRead),b("none")},[h,v,e.messageId,e.isRead]),g=l.useCallback(()=>{d(e.messageId)},[d,e.messageId]),w=l.useCallback(()=>{c(e.messageId)},[c,e.messageId]),C=l.useCallback(()=>{y({to:"/mail/$mailboxId",params:{mailboxId:t},search:O=>({...O,selectedMessageId:e.messageId})})},[y,t,e.messageId]),R=gf(e.messageId,u);return f||m?r.jsx(Ej,{thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:c,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,density:x}):r.jsx("div",{role:"presentation",onPointerDownCapture:R.onMouseDown,onClickCapture:R.claimClick,onContextMenu:R.onContextMenu,children:r.jsx(hu,{thread:Ij(e),selectionMode:!1,checked:!1,active:s,peek:p,onPeek:b,onToggleCheck:w,onLongPress:g,onOpen:C,onAct:S})})},Tj=72,Mj=32,Aj=5,$f="remit:list-density",Oj=()=>{try{const e=localStorage.getItem($f);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},Dj=({query:e})=>r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[r.jsx(ir,{className:"size-4 text-fg-muted"}),r.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),Pj=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:n,isError:a=!1,error:o,onRetry:i,searchQuery:c,searchPredicate:u,onDeleteMessages:m,isDeleting:d=!1,isMoving:f=!1,onLoadMore:h,hasMore:v=!1,isLoadingMore:x=!1,accountId:p,listTitle:b,listMeta:y,listFilter:S,listScopeLabel:g,onTriageContextChange:w,commandsRef:C,hideHeader:R=!1})=>{const O=l.useRef(null),k=Ye(),M=es(),P=ro(),{verb:E,start:L,startFromSearch:A}=P,j=wh(),I=!!c?.trim(),D=Fr(),{labels:T}=uo(p),{pushError:F}=nt(),[N,V]=l.useState(s),[J,re]=l.useState(),oe=l.useCallback(z=>{re(G=>G===z?G:void 0),V(z)},[]),[ie,Z]=l.useState(Oj),ae=l.useCallback(()=>{Z(z=>{const G=z==="comfortable"?"compact":"comfortable";try{localStorage.setItem($f,G)}catch{}return G})},[]),{toggleReadFor:fe}=Ar({mailboxId:e}),{junkMailboxId:B}=kn(p),$=Lr(B,e),{selectedIds:me,selectedCount:ge,hasSelection:Se,isSelected:Ne,toggle:H,select:Ee,clearSelection:xe,selectRange:ke,setAnchor:de,selectAll:se,toggleAll:ye,intersectWith:Pe}=au(),ze=vo(ge,M),[X,Ze]=l.useState(null),Ie=I&&!!u,qe=`${e}|${JSON.stringify(u??{})}`,K=yf({mailboxId:e,accountId:p,enabled:Ie,predicateKey:qe,searchQuery:u??{}}),Qe=l.useCallback((z,G,St)=>{if(St.error===void 0){if(St.cancelled){F({severity:"warning",title:FC(St.done),detail:$C(z,St.done,G)});return}F({severity:"info",title:Wl(z,St.done)})}},[F]),Re=K.phase.kind,be=K.clear,Oe=l.useCallback(()=>{Re==="escalated"&&be(),xe()},[xe,be,Re]),[pe,Ce]=l.useState(null),Te=l.useRef(null),_=l.useRef(!1),le=l.useRef(null),ue=!n&&t.length>0,ve=X!==null,q=yj({count:t.length,getScrollElement:()=>O.current,estimateSize:()=>ie==="compact"?Mj:Tj,overscan:Aj}),he=s?t.findIndex(z=>z.messageId===s):-1,ne=N?t.findIndex(z=>z.messageId===N):-1,ee=l.useCallback(z=>{if(z<0||z>=t.length)return;const G=t[z];if(ze){H(G.messageId);return}Te.current=G.messageId,_.current=!1,re(G.messageId),V(G.messageId)},[t,ze,H]),je=l.useCallback(()=>{if(t.length===0)return;const z=ne<0?0:Math.min(ne+1,t.length-1);ee(z)},[t.length,ne,ee]),Le=l.useCallback(()=>{if(t.length===0)return;const z=ne<=0?0:ne-1;ee(z)},[t.length,ne,ee]),Be=l.useCallback(()=>ee(0),[ee]),Xe=l.useCallback(()=>ee(t.length-1),[ee,t.length]),He=l.useCallback(()=>{N&&H(N)},[N,H]),Me=l.useMemo(()=>t.map(z=>z.messageId),[t]),et=l.useMemo(()=>{const z=[];for(const G of t)me.has(G.messageId)&&z.push({id:G.messageId,sender:G.fromName??G.fromEmail??"Unknown",email:G.fromEmail??"",subject:G.subject??"(No subject)",date:gt(G.sentDate)});return z},[t,me]),Ke=l.useCallback((z,G)=>G.shiftKey?(ke(Me,z,N),!0):G.metaKey||G.ctrlKey?(H(z),!0):(Oe(),de(z),!1),[Me,N,ke,H,Oe,de]),lt=l.useCallback(z=>{!m||z.length===0||(le.current=N??null,Ze(z))},[m,N]),tt=l.useCallback(z=>{const G=ru(Me,N,z);G!==void 0&&(ke(Me,G),Te.current=G,_.current=!1,re(void 0),V(G))},[Me,N,ke]),zt=l.useCallback(()=>tt(-1),[tt]),Rt=l.useCallback(()=>tt(1),[tt]),ns=l.useCallback(()=>{Me.length>0&&se(Me)},[Me,se]),bs=l.useCallback(z=>{const G=Cj({verb:z,confirmingDelete:X!==null,hasSelection:Se,junkMailboxId:B,currentMailboxId:e,deletableMessageId:m?N:void 0});return G.kind==="openWizard"?(L(z),!0):G.kind==="confirmDelete"?(lt([G.messageId]),!0):G.kind==="unavailable"?(F({severity:"warning",title:G.reason}),!0):G.kind==="withheld"},[X,m,Se,B,e,L,N,lt,F]),rt=l.useCallback(()=>{N&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:z=>({...z,selectedMessageId:N})})},[N,k,e]),Tt=l.useCallback(z=>{k({to:"/mail/$mailboxId",params:{mailboxId:e},search:G=>({...G,selectedMessageId:z}),replace:!0})},[k,e]);mf({keyboardFocusedMessageId:J,openMessageId:s,enabled:M&&ge===0,open:Tt});const bt=K.phase.kind==="escalated"?{scope:ai(u??{}),total:K.phase.total,searchQuery:u??{},run:z=>K.runAction(z),stop:K.stop}:void 0,vt=l.useCallback(()=>{if(!X)return;const z=X;if(z.length===0){Ze(null);return}const G=new Set(z),St=t.findIndex(st=>G.has(st.messageId));let Mt;for(let st=St+1;st<t.length;st++)if(!G.has(t[st].messageId)){Mt=t[st].messageId;break}if(Mt===void 0){for(let st=St-1;st>=0;st--)if(!G.has(t[st].messageId)){Mt=t[st].messageId;break}}m?.(z),Oe(),le.current=null,Ze(null),Mt!==void 0&&(Te.current=Mt,_.current=!1,oe(Mt),M&&k({to:"/mail/$mailboxId",params:{mailboxId:e},search:st=>({...st,selectedMessageId:Mt}),replace:!0})),M||Ce(Wl("delete",z.length))},[X,t,m,Oe,k,e,M,oe]),ht=l.useCallback(()=>{const z=le.current;le.current=null,Ze(null),z!==null&&(Te.current=z,_.current=!1,oe(z))},[oe]),rs=l.useMemo(()=>{if(ge===0)return;const z=new Set;for(const G of t)me.has(G.messageId)&&z.add(G.accountConfigId);if(z.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[ge,me,t]),qs=l.useCallback(()=>{if(bt){A();return}L("organize")},[bt,A,L]),En=l.useCallback(z=>{m?.([z])},[m]),ct=l.useCallback((z,G)=>{fe([z],!G)},[fe]),U=l.useCallback(z=>{M||Ee(z)},[M,Ee]),Y=l.useCallback(()=>{if(K.isRunning||K.phase.kind==="counting"){K.stop();return}Oe()},[K,Oe]),Ae=l.useCallback(()=>{K.clear()},[K]);l.useEffect(()=>{if(_.current||!M&&s)return;const z=ne>=0?ne:he;z>=0&&q.scrollToIndex(z,{align:"auto"})},[ne,he,q,M,s]),l.useEffect(()=>{s&&(_.current=!1,oe(s))},[s,oe]),l.useEffect(()=>{N&&(t.some(z=>z.messageId===N)||oe(t[0]?.messageId))},[t,N,oe]),l.useEffect(()=>{w?.({focusedMessageId:N,selectedIds:Array.from(me),hasList:ue,blocksKeyboard:ve||P.isOpen})},[N,me,ue,ve,P.isOpen,w]);const pt=l.useRef(w);pt.current=w,l.useEffect(()=>()=>pt.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),l.useEffect(()=>{K.phase.kind!=="idle"||K.isRunning||Pe(t.map(z=>z.messageId))},[t,Pe,K.phase,K.isRunning]);const yt=l.useRef(e);l.useEffect(()=>{yt.current!==e&&(yt.current=e,Oe())},[e,Oe]),Yu({shouldBlockFn:({action:z})=>kj(z,Se,j)?(Oe(),!0):!1,enableBeforeUnload:!1,disabled:!Se||j!==void 0}),l.useEffect(()=>{const z=O.current;if(!z||!v||!h)return;const G=()=>{if(x)return;const{scrollTop:St,scrollHeight:Mt,clientHeight:st}=z;St+st>=Mt-200&&h()};return z.addEventListener("scroll",G,{passive:!0}),G(),()=>z.removeEventListener("scroll",G)},[v,x,h]),l.useEffect(()=>{const z=Te.current;if(!z)return;const G=O.current?.querySelector(`[data-message-id="${z}"]`);G&&(Te.current=null,G.focus({preventScroll:!0}))}),l.useEffect(()=>{if(C){if(!ue){C.current=null;return}return C.current={focusNext:je,focusPrevious:Le,focusFirst:Be,focusLast:Xe,openFocused:rt,toggleSelect:He,extendSelectDown:Rt,extendSelectUp:zt,selectAll:ns,clearSelection:()=>Se?(Oe(),!0):!1,requestVerb:bs,toggleDensity:ae},()=>{C.current=null}}},[C,ue,je,Le,Be,Xe,rt,He,Rt,zt,ns,Se,Oe,bs,ae]);const vs=n?"loading":a?"error":t.length===0?"empty":"ready",wt=a?Ac(o):void 0,as=l.useCallback(()=>{const z=to(so());window.open(z,"_blank","noopener,noreferrer")},[]),In=[{id:"inbox",threads:[]}],ys=Me.length>0&&Me.every(z=>me.has(z)),Br=Ie&&v&&ys&&!d&&!f&&K.phase.kind==="idle"&&!K.isRunning,Ur=d||f||K.isRunning,Hs=K.phase.kind==="escalated"?K.phase.total:ge,Kr=K.runningAction?LC(K.runningAction.kind,K.progress?.done??0,K.progress?.total??Hs):K.phase.kind==="counting"?"Counting matches…":K.phase.kind==="escalated"?Sj(u??{},K.phase.total):void 0,qr=K.phase.kind!=="escalated"&&Me.length>0?{checked:ys,indeterminate:ge>0&&!ys,onChange:()=>ye(Me)}:void 0,te=K.runningAction?{value:K.progress?.done??0,max:K.progress?.total??Hs,tone:BC(K.runningAction.kind)}:void 0,at=(K.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:K.stop}}:K.phase.kind==="escalated"&&!K.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:Ae}}:Br?{tone:"info",text:"",action:{label:wj(u??{}),onClick:K.escalate}}:void 0)??(rs?{tone:"warning",text:rs}:void 0),Yf=r.jsx(Eo,{title:D.title||b,navSlot:D.navSlot,titleMeta:D.titleMeta,searchSlot:D.searchSlot,searchField:D.searchField,idleSlot:D.makeFilterSlot,count:Hs,onCancel:Y,onDelete:()=>L("delete"),onMove:()=>L("move"),onOrganize:qs,onJunk:$?()=>L("junk"):void 0,onMarkRead:()=>L("markRead"),overflowSlot:p&&e&&ge>0&&T.length>0?r.jsx(lf,{accountId:p,mailboxId:e,messageIds:Array.from(me)}):void 0,isBusy:Ur,isCounting:K.phase.kind==="counting",selectAll:qr,statusLabel:Kr,progress:te,notice:at}),Xf=hf(Me,N),Jf=l.useCallback(z=>{_.current=!0,oe(z)},[oe]),Zf=r.jsxs(r.Fragment,{children:[I&&c&&r.jsx(Dj,{query:c}),r.jsxs("div",{ref:O,role:"listbox","aria-multiselectable":!0,"aria-label":b,className:"flex-1 overflow-y-auto",children:[r.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${q.getTotalSize()}px`},children:q.getVirtualItems().map(z=>{const G=t[z.index];return r.jsx("div",{role:"presentation","data-index":z.index,ref:q.measureElement,className:Ve("absolute left-0 top-0 w-full border-b border-line",K.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${z.start}px)`},children:r.jsx(Rj,{thread:G,mailboxId:e,isSelected:s===G.messageId,isFocused:N===G.messageId,isTabStop:Xf===G.messageId,onFocusRow:Jf,isChecked:Ne(G.messageId),onToggleCheck:H,onRowSelect:Ke,isMultiSelectMode:ze,onLongPress:U,isDesktop:M,onDelete:En,onToggleRead:ct,density:ie})},z.key)})}),x&&r.jsx(ag,{})]})]});return r.jsxs(r.Fragment,{children:[pe&&!M&&r.jsx(gn,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>Ce(null),children:pe}),r.jsx(pu,{listTitle:b,listMeta:y,sections:In,flatList:!0,listState:D.searchResults?"ready":vs,searchQuery:I?c:void 0,listFilter:S,listScopeLabel:g,errorMessage:wt,onRetry:i,onReportError:as,density:ie,selectedThreadId:s,onSelectThread:z=>k({to:"/mail/$mailboxId",params:{mailboxId:e},search:G=>({...G,selectedMessageId:z})}),isDesktop:M,hideHeader:R,selectionBar:Yf,listBody:D.searchResults??(vs==="ready"?Zf:void 0)}),r.jsx(fo,{isOpen:X!==null,title:Dc(X?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:d,onConfirm:vt,onCancel:ht}),r.jsx(ei,{verb:E,accountId:p,mailboxId:e,selection:et,crossAccount:rs!==void 0,escalated:bt,escalatedProgress:K.progress,onFinished:Oe,onRunEnded:Qe})]})},Lj=e=>Ft({path:{accountId:e}}),Fj=e=>{const t=De(),s=Ls(),n=Ue({...Sh(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:Lj(e)})}});return{trigger:()=>{n.mutate({path:{accountId:e}})},triggerAsync:()=>n.mutateAsync({path:{accountId:e}}),isPending:n.isPending,error:n.error,reset:n.reset}},$j=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:n}=Fj(e);return r.jsx(Qx,{onRefresh:s,isRefreshing:n,children:t})};function _j({accountId:e,currentMailboxId:t,candidates:s,onMove:n,children:a}){const[o,i]=l.useState(!1),c=Ls(),u=io(),{inboxMailboxId:m}=yd(e),d=Uo(e),{data:f}=we({...it({path:{accountId:e}}),staleTime:1/0}),h=l.useMemo(()=>lo({mailboxes:f?.items??[],folderAppointments:d,currentMailboxId:t,translator:u}),[f?.items,d,t,u]),v=l.useMemo(()=>m||(h.find(S=>S.label.toLowerCase()==="inbox")?.id??h.find(S=>!S.isCurrent)?.id??""),[m,h]),x=l.useRef(!1);l.useEffect(()=>{x.current||(x.current=!0,kk(c,s.length))},[c,s.length]);const p=l.useCallback(()=>{jk(c,s.length),i(!0)},[c,s.length]),b=l.useCallback((y,S)=>{Nk(c,{selected:y.length,total:s.length,toInbox:S===m}),n(y,S)},[c,s.length,m,n]);return r.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[r.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:r.jsx(Xx,{count:s.length,onReview:p})}),r.jsx("div",{className:"min-h-0 flex-1",children:a}),r.jsx(lb,{open:o,candidates:s,defaultDestinationId:v,availableFolders:h,delimiter:co(f?.items??[]),onConfirmMove:b,onCancel:()=>i(!1)})]})}const zj="We can verify this sender";function Bj(e){const{data:t}=we({...Ec({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:zj,trustSubReason:Ck(n.senderTrust),senderTrust:n.senderTrust}))}}const Uj=e=>{const t=new Set,s=[];for(const n of e)t.has(n.threadMessageId)||(t.add(n.threadMessageId),s.push(n));return s},Kj={unread:"unread",flagged:"starred",attachment:"attachments"},qj=new Set(Object.values(ot)),_f=e=>qj.has(e),Hj=e=>_f(e.category)||e.attributes.size>0,Wj=e=>{const t={};_f(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const n=Kj[s];n&&(t[n]=!0)}return t},Vj=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",Qj=["category","unread","starred","attachments"],ec=e=>JSON.stringify(Qj.map(t=>e?.[t]??null)),Gj=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},Yj=(e,t)=>{const s=Gj(e);return s?ec(s)===ec(t):!1},zf="remit:intelligence-open";function Xj(){try{return localStorage.getItem(zf)!=="closed"}catch{return!0}}function tc(e){try{localStorage.setItem(zf,e?"open":"closed")}catch{}}const Jj=(e,t)=>e!==t,Zj=(e,t,s)=>{if(!(s||!t))return e.find(n=>n.messageId===t)},eN=(e,t,s,n)=>{if(e)return e;if(!(n||!s))return t?.messageId===s?t:void 0},_n=e=>e[0],tN=e=>{const t=_n(e.filter(c=>c.type==="from").map(c=>c.value)),s=_n(e.filter(c=>c.type==="subject").map(c=>c.value)),n=_n(e.filter(c=>c.type==="category").map(c=>c.category)),a=_n(e.filter(c=>c.type==="isUnread"||c.type==="isRead").map(c=>c.type==="isUnread")),o=e.some(c=>c.type==="isStarred")?!0:void 0,i=e.some(c=>c.type==="hasAttachment")?!0:void 0;return{...t!==void 0?{from:t}:{},...s!==void 0?{subject:s}:{},...n!==void 0?{category:[n]}:{},...a!==void 0?{unread:a}:{},...o!==void 0?{starred:o}:{},...i!==void 0?{attachments:i}:{}}},sN=(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 nN(e,t={}){const s=tN(e),n={...s,...t};return{params:s,residual:e.filter(a=>!sN(n,a))}}function rN(e,t,s){if(t.length===0)return e;const n=[...t];return e.filter(a=>{const o=nr(a);return Go({...o,accountId:o.accountId??s},n)})}const aN=50,oN=new Map(Nu().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),Bf=l.createContext(null);function zr(){const e=l.useContext(Bf);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function iN({mailboxId:e,selectedMessageId:t,children:s}){const n=Ye(),o=Nn()==="desktop",i=Ls(),{accounts:c,searchQuery:u,searchInput:m,intelligenceOpen:d,onToggleIntelligence:f,onSetIntelligenceOpen:h}=Fe(),v=xs(),x=Qo(u),p=x.length>0,{freeText:b,tokens:y}=Us(x,v),[S,g]=l.useState("all"),[w,C]=l.useState(new Set),R=l.useMemo(()=>({category:S,attributes:w}),[S,w]),O=l.useMemo(()=>Wj(R),[R]),k=p||Hj(R),{params:M,residual:P}=nN(y,O),E={order:"desc",limit:aN,...b?{query:b}:{},...M,...O},L={category:E.category,unread:E.unread,starred:E.starred,attachments:E.attachments},A=k?Za({path:{mailboxId:e},query:E}):fr({path:{mailboxId:e},query:{order:"desc"}}),{data:j,isLoading:I,isError:D,error:T,refetch:F,fetchNextPage:N,hasNextPage:V,isFetchingNextPage:J}=Gu({queryKey:A,queryFn:async({pageParam:te})=>{if(k){const{data:at}=await va({path:{mailboxId:e},query:{...E,continuationToken:te},throwOnError:!0});return at}const{data:ut}=await Ch({path:{mailboxId:e},query:{order:"desc",continuationToken:te},throwOnError:!0});return ut},initialPageParam:void 0,getNextPageParam:te=>te.continuationToken,placeholderData:(te,ut)=>Yj(ut?.queryKey,L)?te:void 0}),re=l.useCallback(te=>{t&&te.includes(t)&&n({to:"/mail/$mailboxId",params:{mailboxId:e},search:ut=>({...ut,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,n]),{deleteMessages:oe,isPending:ie}=ms({mailboxId:e,onAfterOptimisticRemove:re}),{accountId:Z}=_o(e),ae=dd({accounts:c}),{moveMessages:fe,isPending:B}=Ds({mailboxId:e,accountId:Z,onAfterOptimisticRemove:re}),$=rN(iw(Uj(j?.pages.flatMap(te=>te.items??[])??[])),P,Z),me=l.useCallback(te=>{g(te)},[]),ge=l.useCallback(te=>{C(ut=>{const at=new Set(ut);return at.has(te)?at.delete(te):at.add(te),at})},[]),Se=l.useCallback(()=>{g("all"),C(new Set)},[]),Ne=oN.get(S),H=Ne?{label:Ne,reach:P.length>0?"loaded-pages":Vj(E),onClear:Se}:void 0,Ee=Jj(m,u),xe=Zj($,t,Ee),[ke,de]=l.useState(void 0);l.useEffect(()=>{xe&&de(xe)},[xe]);const se=eN(xe,ke,t,Ee),{selectedThreadId:ye}=As({strict:!1}),Pe=l.useMemo(()=>Rf(se,{messageId:t,threadId:Ee?void 0:ye,mailboxId:e}),[se,t,ye,Ee,e]),ze=si(),{listCommandsRef:X,onTriageContextChange:Ze,focusedMessageId:Ie,selectedIds:qe}=ze,K=$.find(te=>te.messageId===Ie)??se,Qe=l.useRef(null);l.useEffect(()=>{const te=se?.messageId??null;te&&Qe.current!==te&&se?.authenticity?.dkimMismatch&&(Qe.current=te,d||f())},[se?.messageId,se?.authenticity?.dkimMismatch,d,f]);const Re=l.useRef(!1);l.useEffect(()=>{Re.current||o&&se?.messageId&&(Re.current=!0,Xj()&&!d&&h(!0))},[o,se?.messageId,d,h]);const be=d0({accounts:c})??0,Oe=De(),{pushError:pe}=nt(),Ce=mn({thread:se,mailboxId:e,accountId:Z,onAfterOptimisticRemove:re}),{draftsMailboxId:Te}=sw(Z),_=Te!==void 0&&Te===e,{archiveMailboxId:le}=tw(Z),ue=If(),{requestCompose:ve}=Ce,q=l.useCallback(()=>{ve("reply")},[ve]),he=l.useCallback(()=>{ve("reply_all")},[ve]),ne=l.useCallback(()=>{ve("forward")},[ve]),{state:ee,openCompose:je,closeCompose:Le}=Jt(),Be=l.useCallback(()=>{je({mode:"new"})},[je]),Xe=Ue({...dr(),onError:te=>{pe(ds("Couldn't discard draft","The draft wasn't deleted.",te))}}),He=l.useCallback(()=>{const te=ee.outboxMessageId;te&&(Xe.mutate({path:{outboxMessageId:te}}),Oe.invalidateQueries({queryKey:ao()}),Le())},[ee.outboxMessageId,Xe,Oe,Le]),Me=l.useCallback(()=>{n({to:"/mail/$mailboxId",params:{mailboxId:e},search:te=>({...te,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,n]),et=l.useCallback(te=>te?ue(te):[],[ue]),{toggleStar:Ke}=zo({threadId:K?.threadId??"",mailboxId:e}),{toggleReadFor:lt}=Ar({mailboxId:e,accountId:Z}),{junkMailboxId:tt}=kn(Z),zt=tt!=null&&tt===e,Rt=Lr(tt,e),{candidates:ns}=Bj(zt?tt:void 0),{moveMessages:bs}=Ds({mailboxId:e,threadId:K?.threadId,accountId:Z,onAfterOptimisticRemove:re}),{deleteMessages:rt}=ms({mailboxId:e,threadId:K?.threadId,onAfterOptimisticRemove:re}),{addressId:Tt,address:bt}=kf(K),{updateFlags:vt}=jf({addressId:Tt,senderEmail:K?.fromEmail??void 0}),ht=l.useCallback(()=>t||!Ie?!1:(n({to:"/mail/$mailboxId",params:{mailboxId:e},search:te=>({...te,selectedMessageId:Ie})}),!0),[t,Ie,e,n]),rs=l.useCallback(()=>{ht()||se&&ve("reply")},[ht,se,ve]),qs=l.useCallback(()=>{ht()||se&&ve("reply_all")},[ht,se,ve]),En=l.useCallback(()=>{ht()||se&&ve("forward")},[ht,se,ve]),ct=l.useCallback(()=>et(K),[et,K]),U=l.useCallback(()=>{if(X.current?.requestVerb("delete"))return;const te=ct();te.length>0&&rt(te)},[X,ct,rt]),Y=l.useCallback(()=>{if(X.current?.requestVerb("junk")||!Rt)return;const te=ct();te.length!==0&&(Ef(i,{count:te.length,senderTrust:K?.senderTrust??"unknown",wasRescuable:K?Nf(K):!1}),bs(te,Rt))},[X,Rt,ct,bs,i,K]),Ae=l.useCallback(()=>{if(qe.length>0){const te=!(K?.hasStars??!1),ut=new Set(qe);for(const at of $)ut.has(at.messageId)&&at.hasStars!==te&&Ke(at.messageId,at.hasStars);return}K&&Ke(K.messageId,K.hasStars)},[qe,$,K,Ke]),pt=l.useCallback(()=>{if(X.current?.requestVerb("markRead"))return;const te=ct();if(te.length===0)return;const ut=!(K?.isRead??!1);lt(te,ut)},[X,ct,K,lt]),yt=l.useCallback(()=>{if(!Tt)return;const te=bt?.flags?.muted?.value!==!0;vt({muted:{value:te}})},[Tt,bt,vt]),vs=l.useCallback(()=>{if(!Tt)return;const te=bt?.flags?.vip?.value!==!0;vt({vip:{value:te}})},[Tt,bt,vt]),wt=l.useCallback(()=>{d||f()},[d,f]),as=l.useCallback(te=>{n({to:te})},[n]),In=_?"drafts":le===e?"archive":tt===e?"junk":"inbox",ys=l.useRef("");l.useEffect(()=>{const te=ys.current;ys.current=x,x.length>0&&te.length===0&&i.recordEvent("search.submitted",{mailboxType:In})},[x,In,i]);const Br=_&&ee.isOpen&&!!ee.outboxMessageId&&!se,{goBack:Ur,nextMessageId:Hs,previousMessageId:Kr}=ni({context:ze,orderedIds:$.map(te=>te.messageId),selectedMessageId:t,enabled:!ee.isOpen,onClose:Me,handlers:{reply:rs,replyAll:qs,forward:En,delete:U,toggleStar:Ae,toggleRead:pt,muteSender:yt,blockSender:wt,vipSender:vs,markJunk:Y,toggleIntelligence:se?f:void 0,compose:Be,goBrief:()=>as("/mail"),goInbox:()=>as("/mail"),goSent:()=>as("/mail"),goFlagged:()=>as("/mail/flagged"),goSettings:()=>as("/settings")}});$o({enabled:ee.isOpen,bindings:[{key:"Escape",handler:Le,preventDefault:!0}]});const qr={mailboxId:e,selectedMessageId:t,selectedThread:se,conversation:Pe,threads:$,isLoading:I,isError:D,error:T,mailboxAccountId:Z,mailboxName:ae,unreadCount:be,isDraftsMailbox:_,isSpamFolder:zt,rescueCandidates:ns,filterCategory:S,filterAttributes:w,onSelectFilterCategory:me,onToggleFilterAttribute:ge,onClearFilters:Se,listFilter:H,intelligenceOpen:d,onToggleIntelligence:f,handleDeselectIfRemoved:re,searchPredicate:p&&P.length===0?E:void 0,onDeleteMessages:oe,onMoveMessages:fe,isDeleting:ie,isMoving:B,onLoadMore:N,hasMore:V,isLoadingMore:J,onTriageContextChange:Ze,listCommandsRef:X,onRetry:()=>F(),toolbarComposeRequest:Ce.composeRequest,onToolbarReply:q,onToolbarReplyAll:he,onToolbarForward:ne,onClearComposeRequest:Ce.clearComposeRequest,onToolbarDelete:Ce.deleteThread,onToolbarStar:Ce.toggleStar,onToolbarDiscardDraft:He,onToolbarMove:Ce.moveThread,composeState:ee,closeCompose:Le,hasRemitDraftOpen:Br,onBack:Ur,nextMessageId:Hs,previousMessageId:Kr};return r.jsx(Bf.Provider,{value:qr,children:s})}function Uf(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:n,isError:a,error:o,onDeleteMessages:i,onMoveMessages:c,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,mailboxAccountId:v,mailboxName:x,unreadCount:p,isDraftsMailbox:b,isSpamFolder:y,rescueCandidates:S,onTriageContextChange:g,listCommandsRef:w,onRetry:C,filterCategory:R,filterAttributes:O,onSelectFilterCategory:k,onToggleFilterAttribute:M,onClearFilters:P,listFilter:E,searchPredicate:L}=zr(),{searchQuery:A,searchInput:j,accounts:I,resultFolderIndex:D}=Fe(),T=Nn(),F=Ye(),N=x??"Inbox",V=l.useMemo(()=>Nu(),[]),J=l.useMemo(()=>v?[v]:[],[v]),{hasNewMail:re}=Rr(),{state:oe,errorMessage:ie,refresh:Z}=Oo(J,{onSettled:C}),ae=l.useMemo(()=>r.jsx(jo,{state:oe,onRefresh:Z,label:`Refresh ${N}`,errorMessage:ie,hasUpdate:re(J)}),[oe,Z,N,ie,re,J]),fe=l.useMemo(()=>s.map(xe=>qS(xe,D)),[s,D]),{hits:B,isLoading:$}=tf({mailboxId:e,filterCategory:R}),me=l.useMemo(()=>rf(B,s.map(xe=>xe.threadId),D),[B,s,D]),ge=l.useCallback(xe=>F({to:"/mail/$mailboxId",params:{mailboxId:xe.mailboxId??e},search:ke=>({...ke,q:j||void 0,selectedMessageId:xe.id,selectedThreadId:xe.threadId})}),[e,F,j]);if(b&&v)return r.jsx(nj,{mailboxId:e,accountId:v,selectedMessageId:t,imapThreads:s,title:x??"Drafts",unreadCount:p??void 0});const Se=r.jsx(Pj,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:n,isError:a,error:o,onRetry:C,searchQuery:A,searchPredicate:L,onDeleteMessages:i,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,accountId:v,listTitle:N,listFilter:E,listScopeLabel:N,hideHeader:!0,onTriageContextChange:g,commandsRef:w}),Ne=I[0]?.accountId,H=T==="phone"&&Ne?r.jsx($j,{accountId:Ne,children:Se}):Se,Ee=y&&S.length>0&&v?r.jsx(_j,{accountId:v,currentMailboxId:e,candidates:S,onMove:c,children:H}):H;return r.jsx(Of,{title:N,unreadCount:p,preset:V,selectedCategory:R,activeFilters:O,onSelectCategory:k,onToggleFilter:M,onClearFilters:P,searchResults:fe,searchLoading:n,relatedResults:me,relatedLoading:$,onSelectSearchResult:ge,searchResultsInBody:!0,refreshControl:ae,children:Ee})}function lN(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:c,onToolbarReply:u,onToolbarReplyAll:m,onToolbarForward:d,onClearComposeRequest:f,onToolbarDelete:h,onToolbarStar:v,onToolbarDiscardDraft:x,onToolbarMove:p,composeState:b}=zr(),y=ps()?.showIntelligencePane??!1,S=!!n,g=y&&S,w=b.isOpen&&!n?r.jsx(Lf,{}):n?r.jsx(Bs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onOpenIntelligence:n.authenticity?.dkimMismatch?i:void 0,composeRequest:c,onComposeClose:f}):r.jsx(zs,{});return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(ti,{hasThread:S,intelligenceOpen:g&&o,canToggleIntelligence:g,onToggleIntelligence:i,onReply:S?u:void 0,onReplyAll:S?m:void 0,onForward:S?d:void 0,canDelete:S||a,onDelete:S?h:a?x:void 0,onToggleStar:S?v:void 0,isStarred:s?.hasStars,moveContext:S&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:w})]})}function cN(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:n,handleDeselectIfRemoved:a}=zr();return r.jsx(Ks,{onClose:n,thread:s,mailboxId:e,accountId:t,onAfterOptimisticRemove:a})}function uN(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,intelligenceOpen:a,onToggleIntelligence:o,onBack:i,nextMessageId:c,previousMessageId:u,composeState:m,handleDeselectIfRemoved:d}=zr(),f=Ye();if(n){const h=v=>f({to:"/mail/$mailboxId",params:{mailboxId:e},search:x=>({...x,selectedMessageId:v,selectedThreadId:void 0})});return r.jsxs(r.Fragment,{children:[r.jsx(Bs,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onBack:i,onOpenIntelligence:o,onSwipeNext:c?()=>h(c):void 0,onSwipePrevious:u?()=>h(u):void 0,mobileIntelligenceOpen:a}),r.jsx(Lo,{isOpen:a,onClose:o,ariaLabel:"Message details",side:"right",children:r.jsx(Ks,{onClose:o,thread:s,mailboxId:e,accountId:t,hideCloseButton:!0,onAfterOptimisticRemove:d})})]})}return m.isOpen?r.jsx("div",{className:"h-full",children:r.jsx(Lf,{})}):r.jsx(Uf,{})}const sn=Object.assign(iN,{List:Uf,Reading:lN,Intelligence:cN,Phone:uN}),Kf=e=>e==="failed"||e==="blocked",qf=e=>e!=="draft"&&e!=="sent",oi="remit.savedSearches",dN=25;function ar(){try{const e=localStorage.getItem(oi);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function fN(e){const t=e.trim();if(!t)return ar();const s=[t,...ar().filter(n=>n!==t)].slice(0,dN);try{localStorage.setItem(oi,JSON.stringify(s))}catch{return s}return s}function mN(e){const t=ar().filter(s=>s!==e);try{localStorage.setItem(oi,JSON.stringify(t))}catch{return t}return t}const sc=e=>/^\d/.test(e),hN=(e,t)=>{const s=sc(e),n=sc(t);return s&&!n?-1:!s&&n?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function pN(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)=>hN(Yn(o,void 0,s),Yn(i,void 0,s))),{system:n,labels:a}}function gN(e,t,s){const n=kh(t)&&e.unseenCount>0;return{id:e.mailboxId,name:Yn(e,t,s),unseen:n?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function xN(){const e=Ir(),t=Ya({strict:!1});return e.pathname.startsWith("/settings")?"settings":e.pathname.startsWith("/mail/outbox")?"outbox":e.pathname.startsWith("/mail/flagged")?"flagged":t.mailboxId?t.mailboxId:e.pathname==="/mail"||e.pathname==="/mail/"?"brief":""}function nc({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const n=De(),a=Ye(),o=xN(),{searchInput:i,onSearchChange:c}=Fe(),[u,m]=l.useState(ar),{t:d}=Xa("mail",{useSuspense:!1}),f=l.useCallback((k,M)=>d(k,{defaultValue:M}),[d]),h=mt({queries:e.map(k=>({...it({path:{accountId:k.accountId}}),staleTime:1/0}))}),{data:v}=we(cr()),x=l.useMemo(()=>(v?.items??[]).filter(k=>qf(k.status)).length,[v?.items]),p=l.useMemo(()=>e.map((k,M)=>{const P=h[M],E=P?.data?.items??[],L=Qa(k.folderAppointments),{system:A,labels:j}=pN(E,L,f),I=P?.isError?"error":P?.isLoading?"loading":"ready";return{id:k.accountId,label:k.email,email:k.email,muted:!!k.muted,outboxPending:x,status:I,onRetry:()=>P?.refetch(),mailboxes:[...A,...j].map(D=>gN(D,L.get(D.mailboxId),f))}}),[e,h,x,f]),b=k=>{n.invalidateQueries({queryKey:fr({path:{mailboxId:k},query:{order:"desc"}})})},y=({navId:k,className:M,ariaLabel:P,title:E,children:L,onClick:A})=>k==="brief"?r.jsx(Ht,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},activeOptions:{exact:!0,includeSearch:!1},onClick:()=>A?.(),className:M,"aria-label":P,title:E,children:L}):k==="outbox"?r.jsx(Ht,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>A?.(),className:M,"aria-label":P,title:E,children:L}):k==="flagged"?r.jsx(Ht,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>A?.(),className:M,"aria-label":P,title:E,children:L}):k==="settings"?r.jsx(Ht,{to:"/settings/accounts",onClick:()=>A?.(),className:M,"aria-label":P,title:E,children:L}):r.jsx(Ht,{to:"/mail/$mailboxId",params:{mailboxId:k},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{b(k),A?.()},className:M,"aria-label":P,title:E,children:L}),S=()=>{c(""),t?.()},g=i.trim(),w=g.length>0&&!u.includes(g)?g:void 0,C=l.useCallback(()=>{w&&m(fN(w))},[w]),R=l.useCallback(k=>{m(mN(k))},[]),O=l.useCallback(k=>{c(k),a({to:"/mail",search:{q:k,selectedMessageId:void 0}}),t?.()},[c,a,t]);return r.jsx(ax,{accounts:p,selectedNavId:o,onSelectNav:S,linkComponent:y,variant:s,savedSearches:u,saveableQuery:w,onSaveCurrentSearch:C,onSelectSavedSearch:O,onRemoveSavedSearch:R})}function bN(){return r.jsxs("button",{type:"button",onClick:Sc,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(Vc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]})}function vN({accounts:e,onMailboxSelect:t}){return ps()?.showNavPane??!0?r.jsx(nc,{accounts:e}):r.jsxs("div",{className:"flex h-full flex-col",children:[r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(nc,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),r.jsxs("div",{className:"border-t border-line px-2 py-2",children:[r.jsxs(Ht,{to:"/settings/accounts",onClick:t,children:[r.jsx(eu,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),r.jsx(bN,{}),r.jsx(ed,{children:({signOut:a})=>r.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[r.jsx(Xc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function yN(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 wN(e){return e.tokens.length>0&&e.freeText.trim().length===0}const Hf={queued:{icon:oo,label:"Queued",className:"text-warning"},sending:{icon:hs,label:"Sending…",className:"text-accent-2"},sent:{icon:go,label:"Sent",className:"text-positive"},failed:{icon:Pt,label:"Failed",className:"text-danger"},blocked:{icon:Ka,label:"Blocked",className:"text-warning"}},SN=e=>Hh(e).toDateString()===new Date().toDateString()?Xn(e,{hour:"numeric",minute:"2-digit"}):Xn(e,{month:"short",day:"numeric"}),rc=e=>Xn(e,{dateStyle:"medium",timeStyle:"short"}),CN=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},Wf=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",Vf=l.createContext(null);function ii(){const e=l.useContext(Vf);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function kN({children:e}){const t=Ye(),{selectedOutboxMessageId:s}=As({strict:!1}),{data:n,isLoading:a}=we(cr()),{searchQuery:o}=Fe(),i=xs(),c=Qo(o),u=Us(c,i),m=c.length>0,d=wN(u),f=l.useMemo(()=>d?[]:(n?.items??[]).filter(p=>qf(p.status)).filter(p=>yN(p,u.freeText)),[n,u.freeText,d]),h=l.useMemo(()=>f.find(p=>p.outboxMessageId===s),[f,s]),v=l.useCallback(p=>{t({to:"/mail/outbox",search:b=>({...b,selectedOutboxMessageId:p})})},[t]),x={messages:f,hasQuery:m,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:v};return r.jsx(Vf.Provider,{value:x,children:e})}function Qf({message:e,isSelected:t,onSelect:s}){const n=De(),{openCompose:a}=Jt(),{pushError:o}=nt(),i=l.useCallback(()=>{n.invalidateQueries({queryKey:ao()})},[n]),c=Ue({...kc(),onSuccess:i,onError:f=>{o(ds("Couldn't resend message","The message wasn't sent.",f))}}),u=Ue({...dr(),onSuccess:i,onError:f=>{o(ds("Couldn't delete message","The message wasn't deleted.",f))}}),m=e.status;if(!Hf[m])return null;const d=Kf(e.status);return r.jsx(Wx,{recipients:CN(e),subject:e.subject||"",time:SN(e.sentAt??e.updatedAt),status:m,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:m==="failed"?()=>c.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:c.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function Gf({message:e,onBack:t}){const s=e.status,n=Hf[s],a=n?.icon??pn,o=e.sentAt?rc(e.sentAt):rc(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(Ua,{className:"size-4"}),r.jsx("span",{children:"Back"})]}),r.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),r.jsxs("div",{className:"space-y-1 text-sm",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),r.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),r.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),r.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),r.jsx("span",{className:"text-fg",children:o})]}),n&&r.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[r.jsx(a,{className:Ve("size-4",n.className,s==="sending"&&"animate-spin")}),r.jsx("span",{className:Ve("text-xs font-medium",n.className),children:n.label}),Kf(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(Qd,{html:e.htmlBody,text:e.textBody})})]})}function jN(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,onSelectMessage:o}=ii(),i=l.useRef(null);return or({containerRef:i,itemSelector:Qn}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(zs,{message:Wf(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(ri,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(c=>r.jsx(Qf,{message:c,isSelected:a===c.outboxMessageId,onSelect:()=>o(c.outboxMessageId)},c.outboxMessageId))})]})}function NN(){const{selectedMessage:e}=ii();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(Gf,{message:e}):r.jsx(zs,{message:"Select a message to read",showHints:!1})})]})}function EN(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=ii(),c=l.useRef(null);return or({containerRef:c,itemSelector:Qn}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?r.jsx(Gf,{message:o,onBack:()=>i(void 0)}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(zs,{message:Wf(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(ri,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:c,className:"flex-1 overflow-y-auto",children:e.map(u=>r.jsx(Qf,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const zn=Object.assign(kN,{List:jN,Reading:NN,Phone:EN}),IN=({isOpen:e,onClose:t})=>{const s=l.useCallback(n=>{n.key==="Escape"&&(n.preventDefault(),t())},[t]);return l.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx(Rc,{label:"Dismiss keyboard shortcuts",onDismiss:t,className:"backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",className:Ve("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),children:[r.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),r.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:r.jsx(Nt,{className:"size-5"})})]}),r.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:su.map(n=>r.jsxs("div",{children:[r.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:n.title}),r.jsx("div",{className:"space-y-2",children:n.hints.map(a=>r.jsxs("div",{className:"flex items-center justify-between gap-4",children:[r.jsx("span",{className:"text-sm",children:a.description}),r.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>r.jsxs(l.Fragment,{children:[i>0&&a.keys[0]==="g"&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),r.jsx(Is,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},n.title))}),r.jsx("div",{className:"mt-6 border-t border-line pt-4",children:r.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",r.jsx(Is,{children:"Esc"})," to close"]})})]})]}):null};function RN(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});return l.useMemo(()=>nC(t.map(s=>s.data?.items??[])),[t])}const TN=e=>e.map(t=>t.data?.items??[]);function MN(e){const t=mt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0})),combine:TN});return l.useMemo(()=>jh(e.map((s,n)=>({folderAppointments:s.folderAppointments,mailboxes:t[n]??[]}))),[e,t])}var Bn={exports:{}},ac;function AN(){if(ac)return Bn.exports;ac=1;const e=(t,s,n)=>new Promise((a,o)=>{if(n=Object.assign({concurrency:1/0},n),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=n;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const c=[],u=t[Symbol.iterator]();let m=!1,d=!1,f=0,h=0;const v=()=>{if(m)return;const x=u.next(),p=h;if(h++,x.done){d=!0,f===0&&a(c);return}f++,Promise.resolve(x.value).then(b=>s(b,p)).then(b=>{c[p]=b,f--,v()},b=>{m=!0,o(b)})};for(let x=0;x<i&&(v(),!d);x++);});return Bn.exports=e,Bn.exports.default=e,Bn.exports}var ON=AN();const DN=Nh(ON),PN=900*1e3,LN=300,FN=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},$N=60*1e3,_N=e=>Math.max(FN(e,LN)*1e3,$N),Vn=_N(Eh().mailboxPollIntervalSeconds),zN=5,_a=new Set,BN=(e,t,s=PN)=>e.filter(n=>{const a=n.lastSyncAt;return a==null?!0:t-a>s}).map(n=>n.accountId),UN=(e,t,s=Vn)=>e-t>=s,KN=(e,t)=>e.filter(s=>!t.has(s)),oc=(e,t)=>{if(_a.delete(e),wc(t,{softError:!0})){Ga(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},ic=(e,t)=>yc({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:Ft({path:{accountId:e}})})}),qN=e=>{const t=De(),s=l.useRef(e);s.current=e;const n=e.map(a=>a.accountId).join(",");l.useEffect(()=>{const a=Date.now(),i=BN(s.current,a).filter(c=>!_a.has(c));if(i.length!==0)for(const c of i)_a.add(c),ic(c,t).catch(u=>{oc(c,u)})},[n,t]),l.useEffect(()=>{let a=Date.now(),o;const i=new Set,c=()=>{a=Date.now();const d=KN(s.current.map(f=>f.accountId),i);for(const f of d)i.add(f);DN(d,f=>ic(f,t).catch(h=>{oc(f,h)}).finally(()=>{i.delete(f)}),{concurrency:zN})},u=()=>{if(document.visibilityState==="visible"){c(),o=setTimeout(u,Vn);return}},m=()=>{document.visibilityState==="visible"&&UN(Date.now(),a)&&(o!==void 0&&clearTimeout(o),c(),o=setTimeout(u,Vn))};return o=setTimeout(u,Vn),document.addEventListener("visibilitychange",m),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",m)}},[n,t])};function HN(e,t,s){if(e!==t)return s}function WN(e,t){return e===""?"":t}function VN(e,t,s){return t!==e?!1:t!==s}function QN(){const{q:e=""}=As({from:"/mail"}),t=Ye(),s=Nn(),n=Xd(s),[a,o]=l.useState(!1),[i,c]=l.useState(!1),[u,m]=l.useState(!1),d=l.useCallback($=>{m($),tc($)},[]),[f,h]=l.useState(e),v=gr(f,200),x=WN(f,v),p=l.useRef(e);p.current=e;const b=Ot({select:$=>o0($.matches)}),[y,S]=l.useState(b);if(y!==b){const $=HN(y,b,e);S(b),$!==void 0&&h($)}l.useEffect(()=>{VN(f,x,p.current)&&t({to:".",search:$=>{const me=$.q===x;return{...$,q:x||void 0,...x&&!me?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[f,x,t]);const{data:g,isLoading:w,isError:C,error:R,refetch:O}=we({...$t(),staleTime:1/0}),k=!!(g&&(g.accounts?.length??0)===0);l.useEffect(()=>{k&&t({to:"/onboarding",replace:!0})},[k,t]),$o({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const M=l.useCallback($=>{h($)},[]),P=l.useCallback(()=>{h("")},[]),E=l.useCallback(()=>{h("")},[]),L=l.useCallback(()=>{m($=>{const me=!$;return tc(me),me})},[]),A=g?.accounts??[],j=l.useMemo(()=>A.map($=>$.accountId),[A]),I=RN(A),D=MN(A),T=l.useMemo(()=>sC(A),[A]),F=Ot({select:$=>$.matches.find(ge=>"mailboxId"in ge.params)?.params.mailboxId}),{selectedMessageId:N}=As({strict:!1}),V=Ot({select:$=>Po($.matches)}),J=Ot({select:$=>vn($.matches)}),re=Ot({select:$=>Tr($.matches)});qN(A);const oe=l.useCallback(()=>{c(!1)},[]),ie={accounts:A,mailboxNameIndex:I,accountNameIndex:T,resultFolderIndex:D,searchQuery:x,searchInput:f,searchViewKey:b,onSearchChange:M,onSearchClear:P,onSearchClearQuery:E,intelligenceOpen:u,onToggleIntelligence:L,onSetIntelligenceOpen:d},Z=r.jsx(vN,{accounts:A,onMailboxSelect:oe}),ae=n?r.jsx(Hy,{accounts:A}):void 0,fe=n?void 0:r.jsx(f0,{accounts:A}),B={navOpen:i,onOpenNav:()=>c(!0),onCloseNav:()=>c(!1)};return r.jsx(Ih.Provider,{value:ie,children:r.jsxs(Zy,{accountIds:j,children:[C?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:r.jsx(ts,{title:"Couldn't load your account",error:R,onRetry:()=>{O()}})}):V?r.jsx(Zs,{selectedMessageId:N,children:n?r.jsx(Bt,{nav:Z,list:r.jsx(Zs.Phone,{}),intelligenceOpen:u,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B}):r.jsx(Bt,{nav:Z,topBar:fe,list:r.jsx(Zs.List,{}),reading:r.jsx(Zs.Reading,{}),intelligence:r.jsx(Zs.Intelligence,{}),intelligenceOpen:u,hasThread:!!N,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B})}):J?r.jsx(en,{selectedMessageId:N,children:n?r.jsx(Bt,{nav:Z,list:r.jsx(en.Phone,{}),intelligenceOpen:u,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B}):r.jsx(Bt,{nav:Z,topBar:fe,list:r.jsx(en.List,{}),reading:r.jsx(en.Reading,{}),intelligence:r.jsx(en.Intelligence,{}),intelligenceOpen:u,hasThread:!!N,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B})}):F?r.jsx(sn,{mailboxId:F,selectedMessageId:N,children:n?r.jsx(Bt,{nav:Z,list:r.jsx(sn.Phone,{}),intelligenceOpen:u,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B}):r.jsx(Bt,{nav:Z,topBar:fe,list:r.jsx(sn.List,{}),reading:r.jsx(sn.Reading,{}),intelligence:r.jsx(sn.Intelligence,{}),intelligenceOpen:u,hasThread:!!N,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B})}):re?r.jsx(zn,{children:n?r.jsx(Bt,{nav:Z,list:r.jsx(zn.Phone,{}),intelligenceOpen:!1,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B}):r.jsx(Bt,{nav:Z,topBar:fe,list:r.jsx(zn.List,{}),reading:r.jsx(zn.Reading,{}),intelligenceOpen:!1,overlay:ae,skeleton:r.jsx(At,{}),isLoading:w||k,...B})}):r.jsx(At,{}),r.jsx(IN,{isOpen:a,onClose:()=>o(!1)}),r.jsx(Rh,{})]})})}const p1=Object.freeze(Object.defineProperty({__proto__:null,component:QN,useMailContext:Fe},Symbol.toStringTag,{value:"Module"}));export{cb as E,_p as U,m1 as a,h1 as c,p1 as m,f1 as s};
|