1 line
110 KiB
JavaScript
1 line
110 KiB
JavaScript
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4968],{16891:(e,t,a)=>{"use strict";a.d(t,{F:()=>s});var n=a(95155),l=a(12115),r=a(64792),o=a(53999);let s=l.forwardRef((e,t)=>{let{className:a,children:l,...s}=e;return(0,n.jsxs)(r.bL,{ref:t,className:(0,o.cn)("relative overflow-hidden",a),...s,children:[(0,n.jsx)(r.LM,{className:"h-full w-full rounded-[inherit]",children:l}),(0,n.jsx)(i,{}),(0,n.jsx)(r.OK,{})]})});s.displayName=r.bL.displayName;let i=l.forwardRef((e,t)=>{let{className:a,orientation:l="vertical",...s}=e;return(0,n.jsx)(r.VM,{ref:t,orientation:l,className:(0,o.cn)("flex touch-none select-none transition-colors","vertical"===l&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===l&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...s,children:(0,n.jsx)(r.lr,{className:"relative flex-1 rounded-full bg-border"})})});i.displayName=r.VM.displayName},37777:(e,t,a)=>{"use strict";a.d(t,{Bc:()=>s,ZI:()=>d,k$:()=>c,m_:()=>i});var n=a(95155),l=a(12115),r=a(78082),o=a(53999);let s=r.Kq,i=r.bL,c=r.l9,d=l.forwardRef((e,t)=>{let{className:a,sideOffset:l=4,...s}=e;return(0,n.jsx)(r.UC,{ref:t,sideOffset:l,className:(0,o.cn)("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...s})});d.displayName=r.UC.displayName},38128:(e,t,a)=>{"use strict";a.r(t),a.d(t,{default:()=>e_});var n=a(95155),l=a(12115),r=a(35695),o=a(12108),s=a(97108),i=a(12486),c=a(74126),d=a(39022),m=a(13717),u=a(40528),p=a(21380),g=a(74783),h=a(51154),f=a(85339),x=a(5196),b=a(99840),y=a(49026),w=a(16559),E=a(97168),j=a(89852),v=a(82714),N=a(14503),S=a(81497),A=a(28883),T=a(84616),C=a(53904),_=a(47863),L=a(66474),k=a(67133),F=a(34964),D=a(95139);function R(e){let{accounts:t,selectedAccount:a,selectedFolders:r,currentFolder:o,loading:p,unreadCount:g,showAddAccountForm:f,showFolders:x=!0,onFolderChange:b,onRefresh:y,onComposeNew:w,onAccountSelect:N,onShowAddAccountForm:R,onAddAccount:I,onEditAccount:O,onDeleteAccount:M,onSelectEmail:P,onShowFoldersToggle:U}=e,[G,B]=(0,l.useState)(!1),[H,q]=(0,l.useState)({email:"",password:"",displayName:"",host:"",port:"993",useSSL:!0,smtpHost:"",smtpPort:"587",smtpUseSSL:!1}),[z,W]=(0,l.useState)("imap"),$=async e=>{e.preventDefault(),B(!0);try{let e=new FormData;e.append("email",H.email),e.append("password",H.password),e.append("display_name",H.displayName),e.append("host",H.host),e.append("port",H.port),e.append("secure",H.useSSL?"on":"off"),e.append("smtp_host",H.smtpHost),e.append("smtp_port",H.smtpPort),e.append("smtp_secure",H.smtpUseSSL?"on":"off"),await I(e),q({email:"",password:"",displayName:"",host:"",port:"993",useSSL:!0,smtpHost:"",smtpPort:"587",smtpUseSSL:!1}),R(!1)}catch(e){console.error("Failed to add account:",e)}finally{B(!1)}},J=e=>{let{name:t,value:a,type:n,checked:l}=e.target;q(e=>({...e,[t]:"checkbox"===n?l:a}))},K=e=>{let t=e.toLowerCase();if(t.includes("inbox"))return(0,n.jsx)(s.A,{className:"h-4 w-4 text-gray-500"});if(t.includes("sent"))return(0,n.jsx)(i.A,{className:"h-4 w-4 text-gray-500"});if(t.includes("trash"))return(0,n.jsx)(c.A,{className:"h-4 w-4 text-gray-500"});if(t.includes("archive"))return(0,n.jsx)(d.A,{className:"h-4 w-4 text-gray-500"});if(t.includes("draft"))return(0,n.jsx)(m.A,{className:"h-4 w-4 text-gray-500"});else if(t.includes("spam")||t.includes("junk"))return(0,n.jsx)(u.A,{className:"h-4 w-4 text-gray-500"});else return(0,n.jsx)(S.A,{className:"h-4 w-4 text-gray-500"})},Y=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),V=(e,t)=>{var a;let l=e,o=e,s=t;if(e.includes(":")){let t=e.split(":");s=t[0],o=t[1]}else l="".concat(t,":").concat(e);if(s!==t)return null;let i=r[t]===l||r[t]===o||(null==(a=r[t])?void 0:a.split(":")[1])===o,c=0,d="inbox"===o.toLowerCase();if(d&&g&&g[t])if("number"==typeof g[t][o])c=g[t][o];else if("number"==typeof g[t][l])c=g[t][l];else{let e=g[t];for(let t in e)if(t.toLowerCase()===o.toLowerCase()||t.toLowerCase()===l.toLowerCase()){c=e[t];break}}return(0,n.jsx)(E.$,{variant:"ghost",className:"w-full justify-start text-xs py-1 h-7 ".concat(i?"bg-gray-100":""),onClick:()=>{b(e.includes(":")?e:"".concat(t,":").concat(e),t)},children:(0,n.jsxs)("div",{className:"flex items-center w-full",children:[K(o),(0,n.jsx)("span",{className:"ml-2 truncate text-gray-700",children:Y(o)}),d&&c>0&&(0,n.jsx)("span",{className:"ml-auto bg-blue-500 text-white text-[10px] px-1.5 rounded-full",children:c})]})},l)},X=async()=>{try{let e=await fetch("/api/courrier/microsoft"),t=await e.json();e.ok&&t.authUrl?window.location.href=t.authUrl:console.error("Failed to initiate Microsoft authentication:",t.error)}catch(e){console.error("Error connecting Microsoft account:",e)}};return(0,n.jsxs)("div",{className:"w-60 bg-white/95 backdrop-blur-sm border-r border-gray-100 flex flex-col md:flex",style:{display:"flex !important"},children:[(0,n.jsx)("div",{className:"p-3 border-b border-gray-100",children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(A.A,{className:"h-6 w-6 text-gray-600"}),(0,n.jsx)("span",{className:"text-xl font-semibold text-gray-900",children:"COURRIER"})]})}),(0,n.jsxs)("div",{className:"p-2 border-b border-gray-100 flex items-center gap-2",children:[(0,n.jsx)(E.$,{className:"flex-1 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center transition-all py-1.5 text-sm",onClick:w,children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(T.A,{className:"h-3.5 w-3.5"}),(0,n.jsx)("span",{children:"Compose"})]})}),(0,n.jsx)(E.$,{variant:"ghost",size:"icon",className:"h-9 w-9 text-gray-400 hover:text-gray-600",onClick:y,children:(0,n.jsx)(C.A,{className:"h-4 w-4 ".concat(p?"animate-spin":"")})})]}),(0,n.jsx)("div",{className:"flex-1 overflow-y-auto",children:(0,n.jsxs)("div",{className:"p-3 border-b border-gray-100",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,n.jsx)("span",{className:"text-sm font-medium text-gray-500",children:"Accounts"}),(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[(0,n.jsx)(E.$,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-gray-400 hover:text-gray-600",onClick:()=>null==U?void 0:U(!x),children:x?(0,n.jsx)(_.A,{className:"h-4 w-4"}):(0,n.jsx)(L.A,{className:"h-4 w-4"})}),(0,n.jsx)(E.$,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-gray-400 hover:text-gray-600",onClick:()=>R(!f),children:(0,n.jsx)(T.A,{className:"h-4 w-4"})})]})]}),(0,n.jsxs)("div",{className:"mt-1",children:[f&&(0,n.jsxs)("div",{className:"mb-2 p-2 border border-gray-200 rounded-md bg-white",children:[(0,n.jsx)("h4",{className:"text-xs font-medium mb-0.5 text-gray-700",children:"Add IMAP Account"}),(0,n.jsx)("form",{onSubmit:$,children:(0,n.jsxs)("div",{children:[(0,n.jsxs)(F.tU,{defaultValue:"imap",className:"w-full",children:[(0,n.jsxs)(F.j7,{className:"grid w-full grid-cols-2 h-6 mb-0.5 bg-gray-100",children:[(0,n.jsx)(F.Xi,{value:"imap",className:"text-xs h-5 data-[state=active]:bg-blue-500 data-[state=active]:text-white",children:"IMAP"}),(0,n.jsx)(F.Xi,{value:"smtp",className:"text-xs h-5 data-[state=active]:bg-blue-500 data-[state=active]:text-white",children:"SMTP"})]}),(0,n.jsxs)(F.av,{value:"imap",className:"mt-0.5 space-y-0.5",children:[(0,n.jsx)("div",{children:(0,n.jsx)(j.p,{id:"email",name:"email",placeholder:"email@example.com",className:"h-7 text-xs bg-white border-gray-300 mb-0.5 text-gray-900",required:!0,value:H.email,onChange:J})}),(0,n.jsx)("div",{children:(0,n.jsx)(j.p,{id:"password",name:"password",type:"password",placeholder:"•••••••••",className:"h-7 text-xs bg-white border-gray-300 mb-0.5 text-gray-900",required:!0,value:H.password,onChange:J})}),(0,n.jsx)("div",{children:(0,n.jsx)(j.p,{id:"display_name",name:"displayName",placeholder:"John Doe",className:"h-7 text-xs bg-white border-gray-300 mb-0.5 text-gray-900",value:H.displayName,onChange:J})}),(0,n.jsx)("div",{children:(0,n.jsx)(j.p,{id:"host",name:"host",placeholder:"imap.example.com",className:"h-7 text-xs bg-white border-gray-300 mb-0.5 text-gray-900",required:!0,value:H.host,onChange:J})}),(0,n.jsxs)("div",{className:"flex gap-1",children:[(0,n.jsx)("div",{className:"flex-1",children:(0,n.jsx)(j.p,{id:"port",name:"port",placeholder:"993",className:"h-7 text-xs bg-white border-gray-300 text-gray-900",value:H.port,onChange:J})}),(0,n.jsx)("div",{className:"flex items-center pl-1",children:(0,n.jsxs)("div",{className:"flex items-center space-x-1",children:[(0,n.jsx)(D.S,{id:"useSSL",name:"useSSL",checked:H.useSSL,onCheckedChange:e=>{q(t=>({...t,useSSL:!0===e}))}}),(0,n.jsx)(v.J,{htmlFor:"useSSL",className:"text-xs",children:"SSL"})]})})]})]}),(0,n.jsxs)(F.av,{value:"smtp",className:"mt-0.5 space-y-0.5",children:[(0,n.jsx)("div",{children:(0,n.jsx)(j.p,{id:"smtp_host",name:"smtpHost",placeholder:"smtp.example.com",className:"h-7 text-xs bg-white border-gray-300 mb-0.5 text-gray-900",value:H.smtpHost,onChange:J})}),(0,n.jsxs)("div",{className:"flex gap-1",children:[(0,n.jsx)("div",{className:"flex-1",children:(0,n.jsx)(j.p,{id:"smtp_port",name:"smtpPort",placeholder:"587",className:"h-7 text-xs bg-white border-gray-300 text-gray-900",value:H.smtpPort,onChange:J})}),(0,n.jsx)("div",{className:"flex items-center pl-1",children:(0,n.jsxs)("div",{className:"flex items-center space-x-1",children:[(0,n.jsx)(D.S,{id:"smtp_secure",name:"smtpUseSSL",checked:H.smtpUseSSL,onCheckedChange:e=>{q(t=>({...t,smtpUseSSL:!0===e}))}}),(0,n.jsx)(v.J,{htmlFor:"smtp_secure",className:"text-xs",children:"SSL"})]})})]}),(0,n.jsx)("div",{className:"text-xs text-gray-500 italic",children:"Note: SMTP settings needed for sending emails"})]})]}),(0,n.jsxs)("div",{className:"flex gap-1 mt-1",children:[(0,n.jsxs)(E.$,{type:"submit",className:"flex-1 h-6 text-xs bg-blue-500 hover:bg-blue-600 text-white rounded-md px-2 py-0",disabled:G,children:[G?(0,n.jsx)(h.A,{className:"h-3 w-3 animate-spin mr-1"}):null,"Test & Add"]}),(0,n.jsx)(E.$,{type:"button",className:"h-6 text-xs bg-gray-200 text-gray-800 hover:bg-gray-300 rounded-md px-2 py-0",onClick:()=>R(!1),children:"Cancel"})]})]})}),(0,n.jsx)("div",{className:"mt-2 pt-2 border-t border-gray-100",children:(0,n.jsxs)("button",{type:"button",onClick:X,className:"w-full flex items-center justify-center gap-2 h-7 text-xs bg-[#0078D4] hover:bg-[#106EBE] text-white rounded-md px-2 py-0",children:[(0,n.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 23 23",children:[(0,n.jsx)("path",{fill:"#f3f3f3",d:"M0 0h23v23H0z"}),(0,n.jsx)("path",{fill:"#f35325",d:"M1 1h10v10H1z"}),(0,n.jsx)("path",{fill:"#81bc06",d:"M12 1h10v10H12z"}),(0,n.jsx)("path",{fill:"#05a6f0",d:"M1 12h10v10H1z"}),(0,n.jsx)("path",{fill:"#ffba08",d:"M12 12h10v10H12z"})]}),"Connect Microsoft Account"]})})]}),t.map(e=>{var t;return(0,n.jsxs)("div",{className:"mb-1",children:[(0,n.jsxs)("div",{className:"flex items-center w-full px-1 py-1 rounded-md cursor-pointer ".concat((null==a?void 0:a.id)===e.id?"bg-gray-100":""),onClick:()=>N(e),tabIndex:0,role:"button",onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&N(e)},children:[(0,n.jsx)("div",{className:"w-3 h-3 rounded-full ".concat((null==(t=e.color)?void 0:t.startsWith("#"))?"bg-blue-500":e.color||"bg-blue-500"," mr-2")}),(0,n.jsx)("span",{className:"truncate text-gray-700 flex-1",children:e.name}),"loading-account"!==e.id&&(0,n.jsxs)(k.rI,{children:[(0,n.jsx)(k.ty,{asChild:!0,children:(0,n.jsx)("button",{type:"button",className:"ml-1 text-gray-400 hover:text-gray-600 cursor-pointer flex items-center justify-center h-5 w-5",tabIndex:-1,"aria-label":"Account options",children:(0,n.jsx)("span",{style:{fontSize:"18px",lineHeight:1},children:"⋮"})})}),(0,n.jsxs)(k.SQ,{align:"end",children:[(0,n.jsx)(k._2,{onClick:()=>O(e),children:"Edit"}),(0,n.jsx)(k._2,{onClick:()=>M(e),children:"Delete"})]})]})]}),(null==a?void 0:a.id)===e.id&&x&&e.folders&&e.folders.length>0&&(0,n.jsx)("div",{className:"pl-4",children:e.folders.map(t=>V(t,e.id.toString()))})]},e.id)})]})]})})]})}var I=a(47924),O=a(54416),M=a(38564),P=a(53999);function U(e){var t,a,l,r;let o,{email:s,isSelected:i,isActive:c,onSelect:d,onToggleSelect:m,onToggleStarred:u}=e;return(0,n.jsxs)("div",{className:(0,P.cn)("flex items-center gap-3 px-4 py-2 hover:bg-gray-50/80 cursor-pointer",c?"bg-blue-50/50":"",(null==(t=s.flags)?void 0:t.seen)?"":"bg-blue-50/20"),onClick:e=>{e.target.closest(".checkbox-area")||d()},children:[(0,n.jsx)("div",{className:"flex-shrink-0 pr-2 checkbox-area",onClick:e=>{e.stopPropagation()},children:(0,n.jsx)(D.S,{checked:i,onCheckedChange:e=>{e!==i&&m({stopPropagation:()=>{}})},onClick:e=>{e.stopPropagation()},className:"mt-0.5"})}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,n.jsx)("div",{className:"flex items-center gap-2 min-w-0",children:(0,n.jsx)("span",{className:"text-sm truncate ".concat((null==(a=s.flags)?void 0:a.seen)?"text-gray-600":"font-semibold text-gray-900"),children:(()=>{if(!s.from||0===s.from.length)return"Unknown";let e=s.from[0];return e.name&&e.name.trim()?e.name.trim():e.address||"Unknown"})()})}),(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-shrink-0",children:[(0,n.jsx)("span",{className:"text-xs text-gray-500 whitespace-nowrap",children:(e=>{let t=new Date(e),a=new Date,n=new Date(a.getFullYear(),a.getMonth(),a.getDate()),l=new Date(n);return(l.setDate(l.getDate()-1),t>=n)?t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):t>=l?"Yesterday":t.getFullYear()===a.getFullYear()?t.toLocaleDateString([],{month:"short",day:"numeric"}):t.toLocaleDateString([],{year:"numeric",month:"short",day:"numeric"})})(s.date.toString())}),(0,n.jsx)("button",{className:"h-6 w-6 text-gray-400 hover:text-yellow-400",onClick:e=>{e.stopPropagation(),u(e)},children:(0,n.jsx)(M.A,{className:"h-4 w-4 ".concat((null==(l=s.flags)?void 0:l.flagged)?"fill-yellow-400 text-yellow-400":"")})})]})]}),(0,n.jsx)("h3",{className:"text-sm text-gray-900 truncate",children:s.subject||"(No subject)"}),(0,n.jsx)("div",{className:"text-xs text-gray-500 truncate",children:(r=s.content,o="",(o=(o=(o="string"==typeof r?r:r.text||r.html).replace(/<[^>]+>/g," ")).replace(/\s+/g," ").trim()).length>70?o.substring(0,70)+"...":o)})]})]})}function G(e){let{allSelected:t,someSelected:a,onToggleSelectAll:l,currentFolder:r="Inbox",totalEmails:o=0}=e;return(0,n.jsxs)("div",{className:"flex items-center justify-between px-4 h-14",children:[(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)(D.S,{checked:t,ref:e=>{e&&(e.indeterminate=a&&!t)},onCheckedChange:l,className:"mt-0.5"}),(0,n.jsx)("h2",{className:"text-base font-semibold text-gray-900 capitalize",children:"Messages"})]}),(0,n.jsxs)("span",{className:"text-sm text-gray-600",children:[o," ",1===o?"email":"emails"]})]})}var B=a(78749),H=a(62525),q=a(37777);function z(e){let{selectedCount:t,onBulkAction:a}=e;return(0,n.jsxs)("div",{className:"bg-blue-50 border-b border-blue-100 px-4 py-2 flex items-center justify-between shadow-md transition-all duration-200",children:[(0,n.jsxs)("span",{className:"text-xs font-medium text-blue-700",children:[t," selected"]}),(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[(0,n.jsx)(q.Bc,{children:(0,n.jsxs)(q.m_,{children:[(0,n.jsx)(q.k$,{asChild:!0,children:(0,n.jsx)(E.$,{variant:"ghost",size:"icon",className:"h-7 w-7 text-blue-600 hover:text-blue-900 hover:bg-blue-100",onClick:()=>a("mark-unread"),children:(0,n.jsx)(B.A,{className:"h-3.5 w-3.5"})})}),(0,n.jsx)(q.ZI,{children:(0,n.jsx)("p",{children:"Mark as unread"})})]})}),(0,n.jsx)(q.Bc,{children:(0,n.jsxs)(q.m_,{children:[(0,n.jsx)(q.k$,{asChild:!0,children:(0,n.jsx)(E.$,{variant:"ghost",size:"icon",className:"h-7 w-7 text-blue-600 hover:text-blue-900 hover:bg-blue-100",onClick:()=>a("archive"),children:(0,n.jsx)(d.A,{className:"h-3.5 w-3.5"})})}),(0,n.jsx)(q.ZI,{children:(0,n.jsx)("p",{children:"Archive"})})]})}),(0,n.jsx)(q.Bc,{children:(0,n.jsxs)(q.m_,{children:[(0,n.jsx)(q.k$,{asChild:!0,children:(0,n.jsx)(E.$,{variant:"ghost",size:"icon",className:"h-7 w-7 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>a("delete"),children:(0,n.jsx)(H.A,{className:"h-3.5 w-3.5"})})}),(0,n.jsx)(q.ZI,{children:(0,n.jsx)("p",{children:"Delete"})})]})})]})]})}function W(e){let{emails:t,selectedEmailIds:a,selectedEmail:r,currentFolder:o,isLoading:s,totalEmails:i,hasMoreEmails:c,onSelectEmail:d,onToggleSelect:m,onToggleSelectAll:u,onBulkAction:p,onToggleStarred:g,onLoadMore:h,onSearch:f}=e,[x,b]=(0,l.useState)(0),[y,w]=(0,l.useState)("");if(s&&0===t.length)return(0,n.jsx)("div",{className:"flex justify-center items-center h-full p-8 bg-white/95 backdrop-blur-sm",children:(0,n.jsx)("div",{className:"animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"})});if(0===t.length)return(0,n.jsxs)("div",{className:"flex flex-col justify-center items-center h-64 p-8 text-center bg-white/95 backdrop-blur-sm",children:[(0,n.jsx)(A.A,{className:"h-8 w-8 text-gray-400 mb-2"}),(0,n.jsx)("p",{className:"text-gray-500 text-sm",children:y?"No emails match your search":"INBOX"===o?"Your inbox is empty. You're all caught up!":"No emails in this folder"})]});let E=a.length===t.length&&t.length>0,v=a.length>0&&a.length<t.length;return(0,n.jsxs)("div",{className:"w-[320px] bg-white/95 backdrop-blur-sm border-r border-gray-100 flex flex-col",children:[a.length>0&&(0,n.jsx)("div",{className:"sticky top-0 z-10",children:(0,n.jsx)(z,{selectedCount:a.length,onBulkAction:p})}),(0,n.jsxs)("div",{className:"border-b border-gray-100",children:[(0,n.jsx)("div",{className:"px-4 py-2",children:(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(I.A,{className:"absolute left-2 top-2.5 h-4 w-4 text-gray-400"}),(0,n.jsxs)("form",{onSubmit:e=>{e.preventDefault(),null==f||f(y)},children:[(0,n.jsx)(j.p,{type:"search",placeholder:"Search in folder...",className:"pl-8 h-9 bg-gray-50",value:y,onChange:e=>w(e.target.value)}),y&&(0,n.jsx)("button",{type:"button",onClick:()=>{w(""),null==f||f("")},className:"absolute right-2 top-1/2 transform -translate-y-1/2",children:(0,n.jsx)(O.A,{className:"h-4 w-4 text-gray-400"})})]})]})}),(0,n.jsx)(G,{allSelected:E,someSelected:v,onToggleSelectAll:u,currentFolder:o,totalEmails:i})]}),(0,n.jsx)("div",{className:"flex-1 overflow-y-auto",onScroll:e=>{let{scrollTop:t,scrollHeight:a,clientHeight:n}=e.target;b(t);let l=a-t-n;console.log("[DEBUG] Scroll metrics - Distance to bottom: ".concat(l,"px, scrollHeight: ").concat(a,", scrollTop: ").concat(t,", clientHeight: ").concat(n));let r=(t+n)/a;console.log("[DEBUG] Scroll percentage: ".concat(Math.round(100*r),"%, hasMoreEmails: ").concat(c,", isLoading: ").concat(s)),(l<500||r>.8)&&c&&!s?(console.log("[DEBUG-TRIGGER] Loading more emails - distance: ".concat(l,"px, percentage: ").concat(Math.round(100*r),"%")),h()):(l<500||r>.8)&&c&&s?console.log("[DEBUG-BLOCKED] Not loading more emails because isLoading is true"):(l<500||r>.8)&&!c&&console.log("[DEBUG-BLOCKED] Not loading more emails because hasMoreEmails is false")},children:(0,n.jsxs)("div",{className:"divide-y divide-gray-100",children:[t.map(e=>(0,n.jsx)(U,{email:e,isSelected:a.includes(e.id),isActive:(null==r?void 0:r.id)===e.id,onSelect:()=>d(e.id,e.accountId||"",e.folder||""),onToggleSelect:t=>{t.stopPropagation(),m(e.id)},onToggleStarred:t=>{t.stopPropagation(),g(e.id)}},e.id)),s&&t.length>0&&(0,n.jsx)("div",{className:"flex items-center justify-center p-4",children:(0,n.jsx)("div",{className:"animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-blue-500"})})]})})]})}var $=a(11518),J=a.n($),K=a(42355),Y=a(54032),V=a(47734),X=a(50005),Z=a(16891),Q=a(69663);function ee(e){var t,a,l,r,o,s,i,c,d,m;let{email:u,onBack:p,onReply:g,onReplyAll:h,onForward:f,onToggleStar:x}=e;return(0,n.jsxs)("div",{className:"jsx-a4b854e4f3e043c7 flex flex-col h-full overflow-hidden",children:[(0,n.jsx)("div",{className:"jsx-a4b854e4f3e043c7 flex-none px-4 py-3 border-b border-gray-100",children:(0,n.jsxs)("div",{className:"jsx-a4b854e4f3e043c7 flex items-center gap-4",children:[(0,n.jsxs)("div",{className:"jsx-a4b854e4f3e043c7 flex items-center gap-2 min-w-0 flex-1",children:[(0,n.jsx)(E.$,{variant:"ghost",size:"icon",onClick:p,className:"md:hidden flex-shrink-0",children:(0,n.jsx)(K.A,{className:"h-5 w-5"})}),(0,n.jsx)("div",{className:"jsx-a4b854e4f3e043c7 min-w-0 max-w-[500px]",children:(0,n.jsx)("h2",{className:"jsx-a4b854e4f3e043c7 text-lg font-semibold text-gray-900 truncate",children:u.subject})})]}),(0,n.jsx)("div",{className:"jsx-a4b854e4f3e043c7 flex items-center gap-1 flex-shrink-0 ml-auto",children:(0,n.jsxs)("div",{className:"jsx-a4b854e4f3e043c7 flex items-center border-l border-gray-200 pl-4",children:[(0,n.jsx)(E.$,{variant:"ghost",size:"icon",className:"text-gray-400 hover:text-gray-900 h-9 w-9",onClick:g,children:(0,n.jsx)(Y.A,{className:"h-4 w-4"})}),(0,n.jsx)(E.$,{variant:"ghost",size:"icon",className:"text-gray-400 hover:text-gray-900 h-9 w-9",onClick:h,children:(0,n.jsx)(V.A,{className:"h-4 w-4"})}),(0,n.jsx)(E.$,{variant:"ghost",size:"icon",className:"text-gray-400 hover:text-gray-900 h-9 w-9",onClick:f,children:(0,n.jsx)(X.A,{className:"h-4 w-4"})}),(0,n.jsx)(E.$,{variant:"ghost",size:"icon",className:"text-gray-400 hover:text-gray-900 h-9 w-9",onClick:x,children:(0,n.jsx)(M.A,{className:"h-4 w-4 ".concat(u.starred?"fill-yellow-400 text-yellow-400":"")})})]})})]})}),(0,n.jsx)(Z.F,{className:"flex-1 overflow-auto",children:(0,n.jsxs)("div",{className:"jsx-a4b854e4f3e043c7 p-6",children:[(0,n.jsxs)("div",{className:"jsx-a4b854e4f3e043c7 flex items-center gap-4 mb-6",children:[(0,n.jsx)(Q.eu,{className:"h-10 w-10",children:(0,n.jsx)(Q.q5,{children:((null==(a=u.from)||null==(t=a[0])?void 0:t.name)||"").charAt(0)||((null==(r=u.from)||null==(l=r[0])?void 0:l.address)||"").charAt(0)||"?"})}),(0,n.jsxs)("div",{className:"jsx-a4b854e4f3e043c7 flex-1",children:[(0,n.jsxs)("p",{className:"jsx-a4b854e4f3e043c7 font-medium text-gray-900",children:[(null==(s=u.from)||null==(o=s[0])?void 0:o.name)||""," ",(0,n.jsxs)("span",{className:"jsx-a4b854e4f3e043c7 text-gray-500",children:["<",(null==(c=u.from)||null==(i=c[0])?void 0:i.address)||"",">"]})]}),(0,n.jsxs)("p",{className:"jsx-a4b854e4f3e043c7 text-sm text-gray-500",children:["to ",(null==(m=u.to)||null==(d=m[0])?void 0:d.address)||""]}),u.cc&&u.cc.length>0&&(0,n.jsxs)("p",{className:"jsx-a4b854e4f3e043c7 text-sm text-gray-500",children:["cc ",u.cc.map(e=>e.address).join(", ")]})]}),(0,n.jsx)("div",{className:"jsx-a4b854e4f3e043c7 text-sm text-gray-500 whitespace-nowrap",children:(e=>{let t="string"==typeof e?new Date(e):e,a=new Date;return t.toDateString()===a.toDateString()?t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):t.toLocaleDateString([],{month:"short",day:"numeric"})})(u.date)})]}),(0,n.jsx)("div",{className:"jsx-a4b854e4f3e043c7 prose prose-sm max-w-none email-content-wrapper",children:(()=>{try{console.log("EmailDetailView renderEmailContent",{hasContent:!!u.content,contentType:typeof u.content,hasHtml:!!u.html,hasText:!!u.text});let e="";return u.content?"string"==typeof u.content?e=u.content:"object"==typeof u.content&&(e=u.content.html||u.content.text||""):u.html?e=u.html:u.text&&(e=u.text.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br>")),e?(0,n.jsx)("div",{dangerouslySetInnerHTML:{__html:e}}):(0,n.jsx)("div",{className:"text-gray-500",children:"No content available"})}catch(e){return console.error("Error rendering email:",e),(0,n.jsx)("div",{className:"text-gray-500",children:"Failed to render email content"})}})()}),u.hasAttachments&&u.attachments&&u.attachments.length>0&&(0,n.jsxs)("div",{className:"jsx-a4b854e4f3e043c7 mt-6 border-t border-gray-100 pt-4",children:[(0,n.jsx)("h3",{className:"jsx-a4b854e4f3e043c7 text-sm font-medium text-gray-900 mb-2",children:"Attachments"}),(0,n.jsx)("div",{className:"jsx-a4b854e4f3e043c7 grid grid-cols-1 sm:grid-cols-2 gap-2",children:u.attachments.map((e,t)=>(0,n.jsx)("div",{className:"jsx-a4b854e4f3e043c7 flex items-center gap-2 p-2 border border-gray-200 rounded-md",children:(0,n.jsxs)("div",{className:"jsx-a4b854e4f3e043c7 flex-1 min-w-0",children:[(0,n.jsx)("p",{className:"jsx-a4b854e4f3e043c7 text-sm font-medium text-gray-700 truncate",children:e.filename}),(0,n.jsxs)("p",{className:"jsx-a4b854e4f3e043c7 text-xs text-gray-500",children:[(e.size/1024).toFixed(1)," KB"]})]})},t))})]})]})}),(0,n.jsx)(J(),{id:"a4b854e4f3e043c7",children:".email-content-wrapper{width:100%;overflow-wrap:break-word;word-wrap:break-word;word-break:break-word}.email-content-wrapper img{max-width:100%;height:auto}.email-content-wrapper table{max-width:100%;overflow-x:auto;display:block}@media(max-width:640px){.email-content-wrapper{font-size:14px}}"})]})}var et=a(50492),ea=a(50429);a(87548);var en=a(75915),el=a.n(en);function er(e){if(!e)return"";try{return el().sanitize(e,{ADD_ATTR:["style","class","id","align","valign","colspan","rowspan","cellspacing","cellpadding","bgcolor"]}).replace(/<!--\[if\s+gte\s+mso/g,"\x3c!--[if gte mso").replace(/(src|background)="(?!http|data|https|cid)/gi,'$1="https://')}catch(t){return console.error("Error sanitizing HTML:",t),e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+="[^"]*"/g,"").replace(/(javascript|jscript|vbscript|mocha):/gi,"removed:")}}function eo(e){return e&&/[\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC]/.test(e)?"rtl":"ltr"}function es(e){let t="",a="";if(!e)return console.log("extractEmailContent: No email provided"),{text:"",html:""};try{if(e.content&&"object"==typeof e.content)t=e.content.text||"",a=e.content.html||"",t||a||(e.content.body&&("string"==typeof e.content.body?ei(e.content.body)?a=e.content.body:t=e.content.body:"object"==typeof e.content.body&&e.content.body&&(a=e.content.body.html||"",t=e.content.body.text||"")),t||a||!e.content.data||"string"!=typeof e.content.data||(ei(e.content.data)?a=e.content.data:t=e.content.data));else if("string"==typeof e.content)ei(e.content)?a=e.content:t=e.content;else if(a=e.html||"",t=e.text||"",!a&&!t){var n,l;a=(null==(n=e.body)?void 0:n.html)||e.bodyHtml||e.htmlBody||"",t=(null==(l=e.body)?void 0:l.text)||e.bodyText||e.plainText||""}}catch(e){console.error("Error extracting email content:",e)}return!t&&a&&(t=function(e){if(!e)return"";try{if("undefined"==typeof document)return e.replace(/<[^>]*>/g," ").replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/\s+/g," ").trim();{let t=document.createElement("div");return t.innerHTML=e,t.textContent||t.innerText||""}}catch(t){return console.error("Error extracting text from HTML:",t),e.replace(/<[^>]*>/g," ").trim()}}(a)),console.log("Extracted email content:",{hasHtml:!!a,htmlLength:(null==a?void 0:a.length)||0,hasText:!!t,textLength:(null==t?void 0:t.length)||0}),{text:t,html:a}}function ei(e){return!!e&&e.trim().startsWith("<")&&(e.includes("<html")||e.includes("<body")||e.includes("<div")||e.includes("<p>")||e.includes("<br>"))}function ec(e,t){if(!e)return"";try{console.log("processHtmlContent input:",{length:e.length,startsWithHtml:e.trim().startsWith("<html"),startsWithDiv:e.trim().startsWith("<div"),hasBody:e.includes("<body"),containsForwardedMessage:e.includes("---------- Forwarded message ----------"),containsQuoteHeader:e.includes("wrote:"),hasBlockquote:e.includes("<blockquote"),hasTable:e.includes("<table")});let t=e.includes("<html"),a=e.includes("<body"),n=e;if(t&&a&&"undefined"!=typeof DOMParser)try{let t=new DOMParser().parseFromString(e,"text/html").body.innerHTML;t&&(console.log("Extracted body content from HTML document, length:",t.length),e=t)}catch(e){console.error("Error extracting body content:",e)}let l=er(e);console.log("After sanitizeHtml:",{originalLength:n.length,sanitizedLength:l.length,difference:n.length-l.length,percentRemoved:((n.length-l.length)/n.length*100).toFixed(2)+"%",containsForwardedMessage:l.includes("---------- Forwarded message ----------"),hasTable:l.includes("<table"),hasBlockquote:l.includes("<blockquote")});try{if("undefined"!=typeof document){let e=document.createElement("div");e.innerHTML=l,e.querySelectorAll("a").forEach(e=>{let t=e.getAttribute("href");if(t&&t.includes("%"))try{let a=decodeURIComponent(t);e.setAttribute("href",a)}catch(e){console.warn("Failed to decode href:",t)}}),e.querySelectorAll("img").forEach(e=>{let t=e.getAttribute("src");t&&(t.startsWith("cid:")?console.log("Preserving CID reference:",t):t.startsWith("http://")?e.setAttribute("src",t.replace("http://","https://")):t.startsWith("https://")||t.startsWith("data:")||(t.startsWith("/")?e.setAttribute("src","https://example.com".concat(t)):e.setAttribute("src","https://example.com/".concat(t))))});let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),a=[];for(;t.nextNode();)a.push(t.currentNode);a.forEach(e=>{e.nodeValue&&(e.nodeValue=e.nodeValue.replace(/\s+/g," ").trim())}),e.querySelectorAll("p, div, span").forEach(e=>{if(""===e.innerHTML.trim()||" "===e.innerHTML){var t;null==(t=e.parentNode)||t.removeChild(e)}});let n=e.innerHTML;e.innerHTML=n=n.replace(/(<br\s*\/?>\s*){3,}/gi,"<br><br>"),l=e.innerHTML}}catch(e){console.error("Error fixing content:",e)}return l.replace(/<!--\[if\s+gte\s+mso/g,"\x3c!--[if gte mso").replace(/(src|background)="(?!(?:https?:|data:|cid:))/gi,'$1="https://').replace(/src="data:image\/[^;]+;base64,\s*([^"]+)\s*"/gi,(e,t)=>'src="data:image/png;base64,'.concat(t.replace(/\s+/g,""),'"')).replace(/>\s+</g,"> <")}catch(t){return console.error("Error processing HTML content:",t),e}}el().removeAllHooks(),el().setConfig({ADD_TAGS:["html","head","body","style","link","meta","title","table","caption","col","colgroup","thead","tbody","tfoot","tr","td","th","div","span","img","br","hr","section","article","header","footer","h1","h2","h3","h4","h5","h6","p","blockquote","pre","code","ul","ol","li","dl","dt","dd","a","b","i","u","em","strong","del","ins","mark","small","sub","sup","q","abbr","font"],ADD_ATTR:["style","class","id","name","href","src","alt","title","width","height","border","cellspacing","cellpadding","bgcolor","background","color","align","valign","dir","lang","target","rel","charset","media","colspan","rowspan","scope","span","size","face","hspace","vspace","data-*","start","type","value","cite","datetime","wrap","summary"],KEEP_CONTENT:!0,WHOLE_DOCUMENT:!1,ALLOW_DATA_ATTR:!0,ALLOW_UNKNOWN_PROTOCOLS:!0,FORBID_TAGS:["script","iframe","object","embed","form","input","button","select","textarea"],FORBID_ATTR:["onerror","onload","onclick","onmouseover","onmouseout"],FORCE_BODY:!1,USE_PROFILES:{html:!0}});let ed=e=>{let{initialContent:t,onChange:r,placeholder:o="Write your message here...",minHeight:s="200px",maxHeight:i="calc(100vh - 400px)",preserveFormatting:c=!1}=e,d=(0,l.useRef)(null),m=(0,l.useRef)(null),u=(0,l.useRef)(null),[p,g]=(0,l.useState)(!1);return(0,l.useEffect)(()=>((async()=>{if(!d.current||!m.current)return;let e=(await a.e(7477).then(a.bind(a,57477))).default;try{let t=await Promise.all([a.e(7477),a.e(8789)]).then(a.t.bind(a,98789,23));t&&t.default&&(e.register({"modules/better-table":t.default},!0),t.default,console.log("Better Table module registered successfully"))}catch(e){console.warn("Table module not available:",e)}let n=d.current;if(u.current=new e(n,{modules:{toolbar:{container:m.current,handlers:{}},clipboard:{matchVisual:!1},"better-table":!1},placeholder:o,theme:"snow"}),t)try{let e;console.log("Setting initial content in editor",{length:t.length,startsWithHtml:t.trim().startsWith("<"),containsForwardedMessage:t.includes("---------- Forwarded message ----------"),containsReplyIndicator:t.includes("wrote:"),hasBlockquote:t.includes("<blockquote")});let a=eo(t);if((t.includes("---------- Forwarded message ----------")||t.includes("wrote:"))&&t.includes("<blockquote")?(console.log("Content appears to be pre-formatted as reply/forward, using as-is"),e=er(t)):e=ec(t),console.log("Sanitized content details:",{length:e.length,isEmpty:0===e.trim().length,startsWithDiv:e.trim().startsWith("<div"),containsForwardedMessage:e.includes("---------- Forwarded message ----------"),containsQuoteHeader:e.includes("wrote:"),hasTable:e.includes("<table"),hasBlockquote:e.includes("<blockquote"),firstNChars:e.substring(0,100).replace(/\n/g,"\\n")}),0===e.trim().length){console.warn("Sanitized content is empty after processing, using fallback approach");try{let e=document.createElement("div");e.innerHTML=t;let a=e.textContent||e.innerText||"Empty content";u.current.setText(a)}catch(e){console.error("Text extraction fallback failed:",e),u.current.setText("Error loading content")}}else u.current.root.innerHTML=e,u.current&&u.current.format?(u.current.format("direction",a),"rtl"===a&&u.current.format("align","right")):console.warn("Cannot format content: editor not fully initialized");u.current.setSelection(0,0),d.current&&(d.current.scrollTop=0,[d.current.closest(".ql-container"),d.current.closest(".rich-email-editor-container"),d.current.closest(".overflow-y-auto"),document.querySelector(".overflow-y-auto")].forEach(e=>{e instanceof HTMLElement&&(e.scrollTop=0)}))}catch(e){console.error("Error setting initial content:",e);try{let e=document.createElement("div");e.innerHTML=t;let a=e.textContent||e.innerText||"";a.trim()?(console.log("Using extracted text fallback, length:",a.length),u.current.setText(a)):(console.log("Using empty content fallback"),u.current.setText("Unable to load original content"))}catch(e){console.error("All fallbacks failed:",e),u.current.setText("Error loading content")}}u.current.on("text-change",()=>{r(u.current.root.innerHTML)});let l=n.closest(".ql-container");l&&l.classList.add("email-editor-container"),g(!0)})().catch(e=>{console.error("Failed to initialize Quill editor:",e)}),()=>{u.current&&u.current.off("text-change")}),[]),(0,l.useEffect)(()=>{if(u.current&&p&&t&&t!==u.current.root.innerHTML)try{let e;console.log("Updating content in editor:",{contentLength:t.length,startsWithHtml:t.trim().startsWith("<"),containsForwardedMessage:t.includes("---------- Forwarded message ----------"),containsQuoteHeader:t.includes("wrote:"),hasBlockquote:t.includes("<blockquote"),hasTable:t.includes("<table"),firstNChars:t.substring(0,100).replace(/\n/g,"\\n")});let a=eo(t);if((t.includes("---------- Forwarded message ----------")||t.includes("wrote:"))&&t.includes("<blockquote")?(console.log("Content appears to be pre-formatted as reply/forward, using as-is"),e=er(t)):e=ec(t),console.log("Sanitized content details:",{length:e.length,isEmpty:0===e.trim().length,startsWithDiv:e.trim().startsWith("<div"),containsForwardedMessage:e.includes("---------- Forwarded message ----------"),containsQuoteHeader:e.includes("wrote:"),hasTable:e.includes("<table"),hasBlockquote:e.includes("<blockquote"),firstNChars:e.substring(0,100).replace(/\n/g,"\\n")}),0===e.trim().length){console.warn("Sanitized content is empty, using original content");let e=document.createElement("div");e.innerHTML=t;let a=e.textContent||e.innerText||"";u.current&&u.current.setText(a||"No content available")}else if(u.current&&u.current.root){u.current.root.innerHTML=e;try{u.current&&u.current.format&&u.current.root.innerHTML.trim().length>0?(u.current.format("direction",a),"rtl"===a&&u.current.format("align","right"),u.current.update(),u.current.setSelection(0,0)):console.warn("Skipping format - either editor not ready or content empty")}catch(e){console.error("Error applying formatting:",e)}}}catch(e){console.error("Error updating content:",e);try{let e=document.createElement("div");e.innerHTML=t;let a=e.textContent||e.innerText||"";u.current&&u.current.setText(a||"Error loading content")}catch(e){console.error("All fallbacks failed:",e),u.current&&u.current.setText("Error loading content")}}},[t,p]),(0,n.jsxs)("div",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" rich-email-editor-wrapper",children:[(0,n.jsxs)("div",{ref:m,className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-toolbar ql-snow",children:[(0,n.jsxs)("span",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-formats",children:[(0,n.jsx)("button",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-bold"}),(0,n.jsx)("button",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-italic"}),(0,n.jsx)("button",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-underline"}),(0,n.jsx)("button",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-strike"})]}),(0,n.jsxs)("span",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-formats",children:[(0,n.jsx)("select",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-color"}),(0,n.jsx)("select",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-background"})]}),(0,n.jsxs)("span",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-formats",children:[(0,n.jsx)("button",{value:"ordered",className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-list"}),(0,n.jsx)("button",{value:"bullet",className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-list"})]}),(0,n.jsxs)("span",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-formats",children:[(0,n.jsx)("button",{value:"-1",className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-indent"}),(0,n.jsx)("button",{value:"+1",className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-indent"})]}),(0,n.jsx)("span",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-formats",children:(0,n.jsx)("select",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-align"})}),(0,n.jsx)("span",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-formats",children:(0,n.jsx)("button",{value:"rtl",className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-direction"})}),(0,n.jsx)("span",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-formats",children:(0,n.jsx)("button",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-link"})}),(0,n.jsx)("span",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-formats",children:(0,n.jsx)("button",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" ql-clean"})})]}),(0,n.jsxs)("div",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" rich-email-editor-container",children:[(0,n.jsx)("div",{ref:d,className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" quill-editor"}),!p&&(0,n.jsx)("div",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" flex items-center justify-center py-8",children:(0,n.jsx)("div",{className:J().dynamic([["768df40fab0720e1",[s,i,p?"":"{ display: none; }",s,s]]])+" h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})})]}),(0,n.jsx)(J(),{id:"768df40fab0720e1",dynamic:[s,i,p?"":"{ display: none; }",s,s],children:".rich-email-editor-wrapper.__jsx-style-dynamic-selector{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;-moz-box-orient:vertical;-moz-box-direction:normal;-ms-flex-direction:column;flex-direction:column;width:100%;height:100%;overflow:hidden;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-flex:1;-webkit-flex:1;-moz-box-flex:1;-ms-flex:1;flex:1;border:1px solid#e2e8f0}.rich-email-editor-container.__jsx-style-dynamic-selector{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;-moz-box-orient:vertical;-moz-box-direction:normal;-ms-flex-direction:column;flex-direction:column;width:100%;height:100%;overflow:auto;-webkit-box-flex:1;-webkit-flex:1;-moz-box-flex:1;-ms-flex:1;flex:1;position:relative}.quill-editor.__jsx-style-dynamic-selector{width:100%;min-height:".concat(s,";max-height:").concat(i,";overflow-y:auto;overflow-x:hidden}.quill-editor.__jsx-style-dynamic-selector ").concat(!p?"{ display: none; }":"",'.__jsx-style-dynamic-selector .ql-toolbar.ql-snow+.ql-toolbar.ql-snow{display:none!important}[dir="rtl"] .ql-editor{text-align:right;direction:rtl}.ql-editor[dir="rtl"]{text-align:right;direction:rtl}.ql-container{border:none!important;height:auto!important;min-height:').concat(s,";max-height:none!important;overflow:visible}.ql-editor{padding:12px;min-height:").concat(s,';overflow-y:auto!important;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;font-size:14px;line-height:1.5;color:#333!important}.ql-editor p,.ql-editor div,.ql-editor span,.ql-editor li{color:#333!important}.ql-editor.ql-blank::before{color:#aaa!important;font-style:italic!important}.ql-editor blockquote{border-left:2px solid#ddd!important;margin:0!important;padding:10px 0 10px 15px!important;color:#505050!important;background-color:#f9f9f9!important;-webkit-border-radius:4px!important;-moz-border-radius:4px!important;border-radius:4px!important;font-size:13px!important}.ql-editor[dir="rtl"] blockquote,[dir="rtl"] .ql-editor blockquote{border-left:none!important;border-right:2px solid#ddd!important;padding:10px 15px 10px 0!important}.ql-editor table{width:100%!important;border-collapse:collapse!important;table-layout:fixed!important;margin:10px 0!important;border:1px solid#ddd!important}.ql-editor td,.ql-editor th{border:1px solid#ddd!important;padding:6px 8px!important;word-wrap:break-word!important;overflow-wrap:break-word!important;word-break:break-word!important;min-width:30px!important;font-size:13px!important}.email-original-content{margin-top:20px!important;padding-top:10px!important;border-top:1px solid#ddd!important;color:#555!important;font-size:13px!important}.ql-editor blockquote p{margin-bottom:8px!important;margin-top:0!important}.ql-editor div[style*="font-weight: 400"]{margin-top:20px!important;margin-bottom:8px!important;color:#555!important;font-size:13px!important}')})]})};function em(e){var t,a;let n,l,r,o;if(!e)throw Error("Cannot adapt null or undefined email");let s=function(e){try{let t={};e.content&&"object"==typeof e.content?t=e.content:"string"==typeof e.content?e.content.trim().startsWith("<")&&(e.content.includes("<html")||e.content.includes("<body")||e.content.includes("<div")||e.content.includes("<p>"))?t.html=e.content:t.text=e.content:(e.html&&(t.html=e.html),e.text?t.text=e.text:e.plainText?t.text=e.plainText:e.formattedContent&&(t.html=e.formattedContent));let{html:a,text:n}=es(t),l=eo(n||"");return{html:a,text:n,isHtml:!!a,direction:l}}catch(e){return console.error("Error normalizing email content:",e),{text:"Error loading email content",isHtml:!1,direction:"ltr"}}}(e);n=Array.isArray(e.from)?eu(ep(e.from)):"object"==typeof e.from&&"address"in e.from?eu([e.from]):String(e.from||""),l=Array.isArray(e.to)?eu(ep(e.to)):"object"==typeof e.to&&"address"in e.to?eu([e.to]):String(e.to||""),e.cc&&(r=Array.isArray(e.cc)?eu(ep(e.cc)):"object"==typeof e.cc&&"address"in e.cc?eu([e.cc]):String(e.cc)),e.bcc&&(o=Array.isArray(e.bcc)?eu(ep(e.bcc)):"object"==typeof e.bcc&&"address"in e.bcc?eu([e.bcc]):String(e.bcc));let i=(t=e.flags)?Array.isArray(t)?t:Object.entries(t).filter(e=>{let[t,a]=e;return!0===a}).map(e=>{let[t]=e;return t}):[];return{id:e.id||"",from:n,to:l,cc:r,bcc:o,subject:e.subject||"",content:s,date:e.date||new Date().toISOString(),flags:i,attachments:(a=e.attachments)&&Array.isArray(a)?a.map(e=>({filename:e.filename||e.name||"unknown",contentType:e.contentType||"application/octet-stream",encoding:e.encoding,content:e.content})):[],_originalFormat:e}}function eu(e){return e.map(e=>e.name&&e.name!==e.address?"".concat(e.name," <").concat(e.address,">"):e.address).join(", ")}function ep(e){if(!e)return[];if("string"==typeof e){let t=e.match(/^([^<]+)<([^>]+)>$/);return t?[{name:t[1].trim(),address:t[2].trim()}]:[{name:e.split("@")[0]||"",address:e}]}return Array.isArray(e)?e.length>0&&"object"==typeof e[0]&&"address"in e[0]?e:e.map(e=>{if("string"==typeof e){let t=e.match(/^([^<]+)<([^>]+)>$/);return t?{name:t[1].trim(),address:t[2].trim()}:{name:e.split("@")[0]||"",address:e}}return"object"==typeof e&&null!==e&&"address"in e?{name:e.name||e.address.split("@")[0]||"",address:e.address}:{name:"",address:String(e||"")}}):(console.warn("Unexpected addresses format: ".concat(typeof e),e),[])}function eg(e){let t=!e.subject||e.subject.startsWith("Re:")||e.subject.startsWith("Fwd:")?e.subject||"":e.subject,a=e.date?new Date(e.date).toLocaleString():"Unknown Date",n=Array.isArray(e.from)?e.from.map(e=>"string"==typeof e?e:e.name?"".concat(e.name," <").concat(e.address,">"):e.address).join(", "):"string"==typeof e.from?e.from:"Unknown Sender";return{fromStr:n,toStr:Array.isArray(e.to)?e.to.map(e=>"string"==typeof e?e:e.name?"".concat(e.name," <").concat(e.address,">"):e.address).join(", "):"string"==typeof e.to?e.to:"",ccStr:Array.isArray(e.cc)?e.cc.map(e=>"string"==typeof e?e:e.name?"".concat(e.name," <").concat(e.address,">"):e.address).join(", "):"string"==typeof e.cc?e.cc:"",dateStr:a,subject:t}}function eh(e){var t,a,n;let l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"reply";if(console.log("formatReplyEmail called:",{type:l,emailId:null==e?void 0:e.id}),!e)return console.warn("formatReplyEmail: No original email provided"),{to:"",subject:"",content:{text:"",html:"",isHtml:!1,direction:"ltr"}};let r="content"in e?e:em(e),o=r.subject?r.subject.toLowerCase().startsWith("re:")?r.subject:"Re: ".concat(r.subject):"Re: ",{to:s,cc:i}=function(e,t){let a=Array.isArray(e.from)?e.from.map(e=>"string"==typeof e?e:e.address?e.address:"").filter(Boolean).join(", "):"string"==typeof e.from?e.from:"",n="";return"reply-all"===t&&(n=[...Array.isArray(e.to)?e.to.map(e=>"string"==typeof e?e:e.address?e.address:"").filter(Boolean):"string"==typeof e.to?[e.to]:[],...Array.isArray(e.cc)?e.cc.map(e=>"string"==typeof e?e:e.address?e.address:"").filter(Boolean):"string"==typeof e.cc?[e.cc]:[]].join(", ")),{to:a,cc:n}}(r,l),{fromStr:c,dateStr:d}=eg(r),{text:m,html:u}=es(r.content),p=er(u||m),g='\n <div style="margin: 20px 0 10px 0; color: #666; border-bottom: 1px solid #ddd; padding-bottom: 5px;">\n On '.concat(d,", ").concat(c,' wrote:\n </div>\n <blockquote style="margin: 0; padding-left: 10px; border-left: 3px solid #ddd; color: #505050; background-color: #f9f9f9; padding: 10px;">\n ').concat(p,"\n </blockquote>\n "),h="";if(m){let e=m.split(/\r\n|\r|\n/);h="On ".concat(d,", ").concat(c," wrote:\n\n").concat(e.map(e=>"> ".concat(e)).join("\n"))}let f={to:s,cc:i||void 0,subject:o,content:{html:g,text:h||m,isHtml:!0,direction:"object"==typeof r.content&&r.content&&r.content.direction||"ltr"},attachments:null==(t=r.attachments)?void 0:t.map(e=>"name"in e?{filename:e.filename||e.name||"attachment",contentType:e.contentType||"application/octet-stream",content:e.content}:{filename:e.filename||"attachment",contentType:e.contentType||"application/octet-stream",content:e.content})};return console.log("formatReplyEmail result:",{to:f.to,subject:f.subject,hasHtml:!!f.content.html,htmlLength:(null==(a=f.content.html)?void 0:a.length)||0,hasText:!!f.content.text,textLength:(null==(n=f.content.text)?void 0:n.length)||0}),f}function ef(e){var t,a,n;if(console.log("formatForwardedEmail called:",{emailId:null==e?void 0:e.id}),!e)return console.warn("formatForwardedEmail: No original email provided"),{to:"",subject:"",content:{text:"",html:"",isHtml:!1,direction:"ltr"}};let l="content"in e?e:em(e),r=l.subject?l.subject.toLowerCase().startsWith("fwd:")?l.subject:"Fwd: ".concat(l.subject):"Fwd: ",{fromStr:o,toStr:s,ccStr:i,dateStr:c}=eg(l);console.log("Forward header info:",{fromStr:o,toStr:s,dateStr:c,subject:r});let{text:d,html:m}=es(l.content),u=er(m||d),p='\n <div style="margin: 20px 0 10px 0; color: #666; font-family: Arial, sans-serif;">\n ---------- Forwarded message ----------<br>\n <table style="margin: 10px 0 15px 0; border-collapse: collapse; font-size: 13px; color: #333;">\n <tbody>\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">From:</td>\n <td style="padding: 3px 0;">'.concat(o,'</td>\n </tr>\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">Date:</td>\n <td style="padding: 3px 0;">').concat(c,'</td>\n </tr>\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">Subject:</td>\n <td style="padding: 3px 0;">').concat(l.subject||"",'</td>\n </tr>\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">To:</td>\n <td style="padding: 3px 0;">').concat(s,"</td>\n </tr>\n ").concat(i?'\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">Cc:</td>\n <td style="padding: 3px 0;">'.concat(i,"</td>\n </tr>\n "):"",'\n </tbody>\n </table>\n </div>\n <blockquote style="margin: 0; padding-left: 10px; border-left: 3px solid #ddd; color: #505050; background-color: #f9f9f9; padding: 10px;">\n ').concat(u,"\n </blockquote>\n "),g="";d&&(g="\n---------- Forwarded message ----------\nFrom: ".concat(o,"\nDate: ").concat(c,"\nSubject: ").concat(l.subject||"","\nTo: ").concat(s,"\n").concat(i?"Cc: ".concat(i,"\n"):"","\n\n").concat(d,"\n ").trim());let h={to:"",subject:r,content:{html:p,text:g||d,isHtml:!0,direction:"object"==typeof l.content&&l.content&&l.content.direction||"ltr"},attachments:null==(t=l.attachments)?void 0:t.map(e=>"name"in e?{filename:e.filename||e.name||"attachment",contentType:e.contentType||"application/octet-stream",content:e.content}:{filename:e.filename||"attachment",contentType:e.contentType||"application/octet-stream",content:e.content})};return console.log("formatForwardedEmail result:",{subject:h.subject,hasHtml:!!h.content.html,htmlLength:(null==(a=h.content.html)?void 0:a.length)||0,hasText:!!h.content.text,textLength:(null==(n=h.content.text)?void 0:n.length)||0}),h}function ex(e){let{initialEmail:t,type:a="new",onClose:r,onSend:o,accounts:s=[]}=e,[i,c]=(0,l.useState)(s[0]),[d,m]=(0,l.useState)(""),[u,p]=(0,l.useState)(""),[g,f]=(0,l.useState)(""),[x,b]=(0,l.useState)(""),[y,w]=(0,l.useState)(""),[v,N]=(0,l.useState)(!1),[S,A]=(0,l.useState)(!1),[T,C]=(0,l.useState)(!1),[_,F]=(0,l.useState)([]),D=(0,l.useRef)(null);function R(e){var t;let a=e.subject||"",n=e.date?new Date(e.date).toLocaleString():"Unknown Date",l=Array.isArray(e.from)?e.from.map(e=>"string"==typeof e?e:e.name?"".concat(e.name," <").concat(e.address,">"):e.address).join(", "):"string"==typeof e.from?e.from:(null==(t=e.from)?void 0:t.address)?e.from.name?"".concat(e.from.name," <").concat(e.from.address,">"):e.from.address:"Unknown Sender";return{fromStr:l,toStr:Array.isArray(e.to)?e.to.map(e=>"string"==typeof e?e:e.name?"".concat(e.name," <").concat(e.address,">"):e.address).join(", "):"string"==typeof e.to?e.to:"",ccStr:Array.isArray(e.cc)?e.cc.map(e=>"string"==typeof e?e:e.name?"".concat(e.name," <").concat(e.address,">"):e.address).join(", "):"string"==typeof e.cc?e.cc:"",dateStr:n,subject:a}}(0,l.useEffect)(()=>{if(t)try{if(console.log("Initializing compose with email:",{id:t.id,subject:t.subject,hasContent:!!t.content,contentType:t.content?typeof t.content:"none"}),t.accountId&&(null==s?void 0:s.length)){let e=s.find(e=>e.id===t.accountId);e&&c(e)}if("reply"===a||"reply-all"===a){let e=eh(t,a);m(e.to),e.cc&&(N(!0),p(e.cc)),b(e.subject);let n=e.content.html||e.content.text||"";if(n)console.log("Setting reply content:",{length:n.length,isHtml:e.content.isHtml,startsWithHtml:n.trim().startsWith("<"),contentType:typeof n}),w(n);else{console.warn("Reply content is empty, falling back to a basic template");let{fromStr:e,dateStr:a}=R(t),n='\n <div style="margin: 20px 0 10px 0; color: #666; border-bottom: 1px solid #ddd; padding-bottom: 5px;">\n On '.concat(a,", ").concat(e,' wrote:\n </div>\n <blockquote style="margin: 0; padding-left: 10px; border-left: 3px solid #ddd; color: #505050; background-color: #f9f9f9; padding: 10px;">\n [Original message content could not be loaded]\n </blockquote>\n ');w(n)}if(e.attachments&&e.attachments.length>0){let t=e.attachments.map(e=>({name:e.filename||"attachment",type:e.contentType||"application/octet-stream",content:e.content||""}));F(t)}}else if("forward"===a){let e=ef(t);b(e.subject);let a=e.content.html||e.content.text||"";if(a)console.log("Setting forward content:",{length:a.length,isHtml:e.content.isHtml}),w(a);else{console.warn("Forward content is empty, falling back to a basic template");let{fromStr:e,dateStr:a,subject:n,toStr:l,ccStr:r}=R(t);console.log("Creating forward fallback with:",{fromStr:e,dateStr:a,origSubject:n});let o='\n <div style="margin: 20px 0 10px 0; color: #666; font-family: Arial, sans-serif;">\n <div style="border-bottom: 1px solid #ccc; margin-bottom: 10px; padding-bottom: 5px;">\n <div>---------------------------- Forwarded Message ----------------------------</div>\n </div>\n <table style="margin-bottom: 10px; font-size: 14px;">\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">From:</td>\n <td style="padding: 3px 0;">'.concat(e,'</td>\n </tr>\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">Date:</td>\n <td style="padding: 3px 0;">').concat(a,'</td>\n </tr>\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">Subject:</td>\n <td style="padding: 3px 0;">').concat(n||"",'</td>\n </tr>\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">To:</td>\n <td style="padding: 3px 0;">').concat(l,"</td>\n </tr>\n ").concat(r?'\n <tr>\n <td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">Cc:</td>\n <td style="padding: 3px 0;">'.concat(r,"</td>\n </tr>"):"",'\n </table>\n <div style="border-bottom: 1px solid #ccc; margin-top: 5px; margin-bottom: 15px; padding-bottom: 5px;">\n <div>----------------------------------------------------------------------</div>\n </div>\n </div>\n <div class="forwarded-content" style="margin: 0; color: #333;">\n [Original message content could not be loaded]\n </div>\n ');w(o)}if(e.attachments&&e.attachments.length>0){console.log("Processing ".concat(e.attachments.length," attachments for forwarded email"));let t=e.attachments.map(e=>({name:e.filename||"attachment",type:e.contentType||"application/octet-stream",content:e.content||""}));F(t)}}}catch(e){console.error("Error initializing compose form:",e),w("<p>Error loading email content</p>")}},[t,a,s]),(0,l.useEffect)(()=>{D.current&&"new"!==a&&setTimeout(()=>{if(D.current){D.current.focus(),D.current.scrollTop=0;let e=D.current.parentElement;for(;e;)e.classList.contains("overflow-y-auto")&&(e.scrollTop=0),e=e.parentElement}},100)},[y,a]);let I=async e=>{let t=Array.from(e).map(e=>({name:e.name,type:e.type,content:URL.createObjectURL(e)}));F(e=>[...e,...t])},M=e=>{F(t=>t.filter((t,a)=>a!==e))},P=async()=>{if(!d)return void alert("Please specify at least one recipient");C(!0);try{await o({to:d,cc:u||void 0,bcc:g||void 0,subject:x,body:y,fromAccount:null==i?void 0:i.id,attachments:_}),r()}catch(e){console.error("Error sending email:",e),alert("Failed to send email. Please try again.")}finally{C(!1)}};return(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex flex-col h-full max-h-[80vh] bg-white border rounded-md shadow-md",children:[(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex items-center justify-between p-3 border-b bg-gray-50",children:[(0,n.jsx)("h2",{className:"jsx-4bd026b7b30bfd4c text-lg font-medium text-gray-800",children:(()=>{switch(a){case"reply":return"Reply";case"reply-all":return"Reply All";case"forward":return"Forward";default:return"New Message"}})()}),(0,n.jsx)(E.$,{variant:"ghost",size:"icon",onClick:r,children:(0,n.jsx)(O.A,{className:"h-5 w-5"})})]}),(0,n.jsx)("div",{className:"jsx-4bd026b7b30bfd4c flex-1 overflow-y-auto bg-white",children:(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c p-2 space-y-2",children:[(0,n.jsx)("div",{className:"jsx-4bd026b7b30bfd4c border-b pb-1",children:(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex items-center",children:[(0,n.jsx)("span",{className:"jsx-4bd026b7b30bfd4c w-16 text-gray-700 text-sm font-medium",children:"From:"}),(0,n.jsxs)(k.rI,{children:[(0,n.jsx)(k.ty,{asChild:!0,children:(0,n.jsxs)(E.$,{variant:"outline",className:"w-full flex justify-between items-center h-8 px-2 py-1 text-left font-normal bg-white text-gray-800 border-gray-200",children:[(0,n.jsx)("span",{className:"jsx-4bd026b7b30bfd4c truncate",children:i?i.display_name?"".concat(i.display_name," <").concat(i.email,">"):i.email:"Select account"}),(0,n.jsx)(L.A,{className:"h-4 w-4 opacity-50"})]})}),(0,n.jsxs)(k.SQ,{align:"start",className:"w-[240px]",children:[(0,n.jsx)(k.lp,{children:"Select account"}),(0,n.jsx)(k.mB,{}),s.length>0?s.map(e=>(0,n.jsx)(k._2,{onClick:()=>c(e),className:"cursor-pointer hover:bg-blue-50 focus:bg-blue-50",children:e.display_name?"".concat(e.display_name," <").concat(e.email,">"):e.email},e.id)):(0,n.jsx)(k._2,{disabled:!0,children:"No accounts available"})]})]})]})}),(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c border-b pb-1",children:[(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex items-center",children:[(0,n.jsx)("span",{className:"jsx-4bd026b7b30bfd4c w-16 text-gray-700 text-sm font-medium",children:"To:"}),(0,n.jsx)(j.p,{type:"text",value:d,onChange:e=>m(e.target.value),placeholder:"recipient@example.com",className:"flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"})]}),v&&(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex items-center",children:[(0,n.jsx)("span",{className:"jsx-4bd026b7b30bfd4c w-16 text-gray-700 text-sm font-medium",children:"Cc:"}),(0,n.jsx)(j.p,{type:"text",value:u,onChange:e=>p(e.target.value),placeholder:"cc@example.com",className:"flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"})]}),S&&(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex items-center",children:[(0,n.jsx)("span",{className:"jsx-4bd026b7b30bfd4c w-16 text-gray-700 text-sm font-medium",children:"Bcc:"}),(0,n.jsx)(j.p,{type:"text",value:g,onChange:e=>f(e.target.value),placeholder:"bcc@example.com",className:"flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"})]}),(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex gap-3 ml-16",children:[!v&&(0,n.jsx)("button",{onClick:()=>N(!0),className:"jsx-4bd026b7b30bfd4c text-blue-600 text-sm hover:underline",children:"Add Cc"}),!S&&(0,n.jsx)("button",{onClick:()=>A(!0),className:"jsx-4bd026b7b30bfd4c text-blue-600 text-sm hover:underline",children:"Add Bcc"})]})]}),(0,n.jsx)("div",{className:"jsx-4bd026b7b30bfd4c border-b pb-1",children:(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex items-center",children:[(0,n.jsx)("span",{className:"jsx-4bd026b7b30bfd4c w-16 text-gray-700 text-sm font-medium",children:"Subject:"}),(0,n.jsx)(j.p,{type:"text",value:x,onChange:e=>b(e.target.value),placeholder:"Subject",className:"flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"})]})}),(0,n.jsx)(ed,{initialContent:y,onChange:e=>{w(e)},placeholder:"Write your message here...",minHeight:"320px"}),_.length>0&&(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c p-2 border rounded-md bg-gray-50",children:[(0,n.jsx)("div",{className:"jsx-4bd026b7b30bfd4c text-sm font-medium mb-1 text-gray-700",children:"Attachments:"}),_.map((e,t)=>(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex items-center justify-between text-sm py-1",children:[(0,n.jsx)("span",{className:"jsx-4bd026b7b30bfd4c truncate mr-2 text-gray-800",children:e.name}),(0,n.jsx)(E.$,{variant:"ghost",size:"sm",onClick:()=>M(t),className:"h-6 w-6 p-0",children:(0,n.jsx)(O.A,{className:"h-4 w-4"})})]},t))]})]})}),(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c border-t p-3 flex items-center justify-between bg-gray-50",children:[(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex items-center gap-2",children:[(0,n.jsx)("input",{type:"file",id:"file-attachment",multiple:!0,onChange:e=>{e.target.files&&e.target.files.length>0&&I(e.target.files)},className:"jsx-4bd026b7b30bfd4c hidden"}),(0,n.jsx)("label",{htmlFor:"file-attachment",className:"jsx-4bd026b7b30bfd4c cursor-pointer",children:(0,n.jsx)(E.$,{variant:"ghost",size:"sm",className:"p-1 text-gray-700 hover:bg-gray-100",title:"Attach files",children:(0,n.jsx)(et.A,{className:"h-5 w-5"})})})]}),(0,n.jsxs)("div",{className:"jsx-4bd026b7b30bfd4c flex items-center gap-2",children:[(0,n.jsx)(E.$,{variant:"default",onClick:r,className:"bg-red-600 hover:bg-red-700 text-white",children:"Cancel"}),(0,n.jsx)(E.$,{variant:"default",onClick:P,disabled:T,className:"bg-blue-600 hover:bg-blue-700 text-white",children:T?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(h.A,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending"]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ea.A,{className:"mr-2 h-4 w-4"}),"Send"]})})]})]}),(0,n.jsx)(J(),{id:"4bd026b7b30bfd4c",children:'[contenteditable]{-webkit-user-modify:read-write-plaintext-only;word-wrap:break-word;overflow-wrap:break-word;-webkit-line-break:after-white-space;-webkit-user-select:text;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;font-size:14px;line-height:1.5;color:#333;background-color:#fff}[contenteditable]:focus{outline:none}[contenteditable] blockquote{margin:10px 0;padding-left:15px;border-left:2px solid#ddd;color:#666}[contenteditable] img{max-width:100%;height:auto}[contenteditable] table{border-collapse:collapse;width:100%;max-width:100%;margin-bottom:1rem}[contenteditable] th,[contenteditable] td{padding:5px;border:1px solid#ddd}[contenteditable] th{background-color:#f8f9fa;font-weight:600;text-align:left}.email-original-content{margin-top:20px;color:#505050}'})]})}function eb(e){let{show:t,selectedCount:a,onConfirm:l,onCancel:r}=e;return(0,n.jsx)(w.Lt,{open:t,onOpenChange:e=>!e&&r(),children:(0,n.jsxs)(w.EO,{children:[(0,n.jsxs)(w.wd,{children:[(0,n.jsxs)(w.r7,{children:["Delete ",a," email",1!==a?"s":"","?"]}),(0,n.jsxs)(w.$v,{children:["This will move the selected email",1!==a?"s":""," to the trash folder. You can restore them later from the trash folder if needed."]})]}),(0,n.jsxs)(w.ck,{children:[(0,n.jsx)(w.Zr,{onClick:r,children:"Cancel"}),(0,n.jsx)(w.Rx,{onClick:l,children:"Delete"})]})]})})}var ey=a(53580);let ew={accounts:[],selectedAccount:null,selectedFolders:{},currentFolder:"INBOX",emails:[],selectedEmail:null,selectedEmailIds:[],isLoading:!1,isLoadingUnreadCounts:!1,error:null,page:1,perPage:20,totalPages:0,totalEmails:0,mailboxes:[],unreadCountMap:{},showFolders:!1},eE=(e,t)=>{let a,n=t||"default";if(e.includes(":")){let l=e.split(":"),r=l[0];a=l[1],t?(console.log("Using provided accountId (".concat(t,") over folder prefix (").concat(r,")")),n=t):n=r}else a=e;return{normalizedFolder:a,effectiveAccountId:n,prefixedFolder:"".concat(n,":").concat(a)}};function ej(e,t){switch(console.log("[EMAIL_REDUCER] Action: ".concat(t.type),t),t.type){case"SET_ACCOUNTS":return{...e,accounts:t.payload};case"SELECT_ACCOUNT":{let a=t.payload,n="".concat(a.id,":INBOX");return console.log("[EMAIL_REDUCER] Selecting account: ".concat(a.email," (").concat(a.id,")")),{...e,selectedAccount:a,currentFolder:n,selectedFolders:{...e.selectedFolders,[a.id]:n},selectedEmail:null,selectedEmailIds:[],emails:[],isLoading:!0,showFolders:!0,page:1}}case"CHANGE_FOLDER":{let{folder:a,accountId:n}=t.payload,{normalizedFolder:l,effectiveAccountId:r,prefixedFolder:o}=eE(a,n);return console.log("[EMAIL_REDUCER] Changing folder to: ".concat(o," (account: ").concat(r,")")),{...e,currentFolder:o,selectedFolders:{...e.selectedFolders,[r]:o},selectedEmail:null,selectedEmailIds:[],emails:[],isLoading:!0,page:1}}case"SET_EMAILS":let a=[...t.payload];a.length>0&&(console.log("[EMAIL_REDUCER] Sorting ".concat(a.length," emails")),console.log("[EMAIL_REDUCER] Sample emails before sorting:",a.slice(0,3).map(e=>{var t;return{id:e.id.substring(0,8),subject:null==(t=e.subject)?void 0:t.substring(0,20),date:e.date,timestamp:new Date(e.date).getTime()}})));let n=a.sort((e,t)=>{let a,n;try{a=e.date instanceof Date?e.date.getTime():new Date(e.date).getTime()}catch(e){a=0}try{n=t.date instanceof Date?t.date.getTime():new Date(t.date).getTime()}catch(e){n=0}return isNaN(a)&&isNaN(n)?0:isNaN(a)?1:isNaN(n)?-1:n-a});return n.length>0&&console.log("[EMAIL_REDUCER] Sample emails after sorting:",n.slice(0,3).map(e=>{var t;return{id:e.id.substring(0,8),subject:null==(t=e.subject)?void 0:t.substring(0,20),date:e.date,timestamp:new Date(e.date).getTime()}})),{...e,emails:n,isLoading:!1};case"APPEND_EMAILS":{let a=new Set(e.emails.map(e=>e.id));console.log("[DEBUG-REDUCER] APPEND_EMAILS - Got ".concat(t.payload.length," emails to append, current list has ").concat(e.emails.length));let n=t.payload.filter(e=>!a.has(e.id));if(console.log("[DEBUG-REDUCER] Filtered to ".concat(n.length," new non-duplicate emails")),0===n.length)return console.log("[DEBUG-REDUCER] No new emails to append, returning current state with isLoading=false"),{...e,isLoading:!1};n.length>0&&console.log("[DEBUG-REDUCER] Sample new emails before combining:",n.slice(0,3).map(e=>{var t;return{id:e.id.substring(0,8),subject:null==(t=e.subject)?void 0:t.substring(0,20),date:e.date,timestamp:new Date(e.date).getTime()}}));let l=[...e.emails,...n].sort((e,t)=>{let a,n;try{a=e.date instanceof Date?e.date.getTime():new Date(e.date).getTime()}catch(e){a=0}try{n=t.date instanceof Date?t.date.getTime():new Date(t.date).getTime()}catch(e){n=0}return isNaN(a)&&isNaN(n)?0:isNaN(a)?1:isNaN(n)?-1:n-a});return console.log("[DEBUG-REDUCER] Final combined list has ".concat(l.length," emails (").concat(e.emails.length," old + ").concat(n.length," new)")),{...e,emails:l,isLoading:!1}}case"SELECT_EMAIL":return{...e,selectedEmail:t.payload.email};case"TOGGLE_EMAIL_SELECTION":{let a=t.payload,n=e.selectedEmailIds.includes(a);return{...e,selectedEmailIds:n?e.selectedEmailIds.filter(e=>e!==a):[...e.selectedEmailIds,a]}}case"TOGGLE_SELECT_ALL":{let t=e.emails.map(e=>e.id),a=t.every(t=>e.selectedEmailIds.includes(t));return{...e,selectedEmailIds:a?[]:t}}case"CLEAR_SELECTED_EMAILS":return{...e,selectedEmailIds:[],selectedEmail:null};case"SET_LOADING":return{...e,isLoading:t.payload};case"SET_LOADING_UNREAD_COUNTS":return{...e,isLoadingUnreadCounts:t.payload};case"SET_ERROR":return{...e,error:t.payload,isLoading:!1};case"SET_PAGE":return{...e,page:t.payload};case"INCREMENT_PAGE":return{...e,page:e.page+1};case"SET_TOTAL_PAGES":return{...e,totalPages:t.payload};case"SET_TOTAL_EMAILS":return{...e,totalEmails:t.payload};case"SET_MAILBOXES":return{...e,mailboxes:t.payload};case"UPDATE_UNREAD_COUNT":{let{accountId:a,folder:n,count:l}=t.payload;return{...e,unreadCountMap:{...e.unreadCountMap,[a]:{...e.unreadCountMap[a]||{},[n]:l}}}}case"SET_UNREAD_COUNTS":return{...e,unreadCountMap:t.payload};case"TOGGLE_SHOW_FOLDERS":return{...e,showFolders:t.payload};case"MARK_EMAIL_AS_READ":{let{emailId:a,isRead:n,accountId:l}=t.payload,r=e.emails.map(e=>e.id!==a||l&&e.accountId!==l?e:{...e,flags:{...e.flags,seen:n}}),o=e.selectedEmail&&e.selectedEmail.id===a&&(!l||e.selectedEmail.accountId===l)?{...e.selectedEmail,flags:{...e.selectedEmail.flags,seen:n}}:e.selectedEmail;return{...e,emails:r,selectedEmail:o}}default:return e}}var ev=a(34477);let eN=(0,ev.createServerReference)("7e1755ba4afc4a5581b657e52055fecb168bbe2070",ev.callServer,void 0,ev.findSourceMapURL,"getCachedEmailsWithTimeout"),eS=()=>{var e,t,a,n,r;let[s,i]=(0,l.useReducer)(ej,ew),{data:c}=(0,o.useSession)(),{toast:d}=(0,ey.dj)();(0,l.useRef)(null);let m=(0,l.useRef)(null);(0,l.useRef)(0),(0,l.useRef)(null);let u=(0,l.useRef)(0),p=(0,l.useRef)(null);(0,l.useRef)(0),(0,l.useEffect)(()=>(window.dispatchEmailAction=i,window.__emailStateDispatch=i,()=>{window.dispatchEmailAction=void 0,window.__emailStateDispatch=void 0}),[i]);let g=(0,l.useCallback)((e,t,a)=>{let n=new Date().toISOString().split("T")[1].substring(0,12);console.log("[".concat(n,"][EMAIL-STATE][").concat(e,"] ").concat(t)),a&&console.log("[".concat(n,"][EMAIL-STATE][DATA]"),a)},[]),h=(0,l.useCallback)(async function(e,t){var a,n,l,r,o;let m=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!(null==c||null==(a=c.user)?void 0:a.id))return;console.log("[DEBUG-LOAD_EMAILS] Called with isLoadMore=".concat(m,", page=").concat(e,", currentEmails=").concat(s.emails.length));let u=s.currentFolder,p=s.selectedAccount?s.selectedAccount.id:"default";i({type:"SET_LOADING",payload:!0});try{let a=s.selectedAccount?s.selectedAccount.id:void 0,{normalizedFolder:o,effectiveAccountId:d,prefixedFolder:u}=eE(s.currentFolder,a);g("LOAD_EMAILS","Loading emails for ".concat(u," (account: ").concat(d,", isLoadMore: ").concat(m,", page: ").concat(e,")"));let p=new URLSearchParams({folder:o,page:e.toString(),perPage:t.toString(),accountId:d});m&&console.log("[DEBUG-PAGINATION] Loading more emails. Current page: ".concat(e,", existing emails: ").concat(s.emails.length)),g("CACHE_CHECK","Checking cache for ".concat(u,", page: ").concat(e));let h=await eN(c.user.id,u,e,t,100,d);if(h){g("CACHE_HIT","Using cached data for ".concat(u,", page: ").concat(e,", emails: ").concat((null==(r=h.emails)?void 0:r.length)||0,", isLoadMore: ").concat(m)),Array.isArray(h.emails)&&(console.log("[DEBUG-CACHE_HIT] Dispatching ".concat(m?"APPEND_EMAILS":"SET_EMAILS"," with ").concat(h.emails.length," emails")),i({type:m?"APPEND_EMAILS":"SET_EMAILS",payload:h.emails}),h.totalEmails&&i({type:"SET_TOTAL_EMAILS",payload:h.totalEmails}),h.totalPages&&i({type:"SET_TOTAL_PAGES",payload:h.totalPages}),h.mailboxes&&h.mailboxes.length>0&&i({type:"SET_MAILBOXES",payload:h.mailboxes})),m&&setTimeout(()=>{console.log("[DEBUG-CACHE_HIT_APPEND] After ".concat(m?"APPEND":"SET",", email count is now: ").concat(s.emails.length))},0);return}g("API_FETCH","Fetching emails from API: ".concat(p.toString(),", isLoadMore: ").concat(m)),console.log("[DEBUG-API_FETCH] Fetching from /api/courrier/emails?".concat(p.toString()));let f=await fetch("/api/courrier/emails?".concat(p.toString()));if(!f.ok){if(m&&e>1){g("ERROR_RECOVERY","Failed to fetch emails for page ".concat(e,", attempting to recover by decrementing page")),console.log("[DEBUG-ERROR] API returned ".concat(f.status," for page ").concat(e)),i({type:"SET_PAGE",payload:e-1}),i({type:"SET_LOADING",payload:!1}),i({type:"SET_TOTAL_PAGES",payload:e});return}let t=await f.json();throw Error(t.error||"Failed to fetch emails")}let x=await f.json();if(console.log("[DEBUG-API_RESPONSE] Got response with ".concat((null==(n=x.emails)?void 0:n.length)||0," emails, totalPages: ").concat(x.totalPages,", totalEmails: ").concat(x.totalEmails,", isLoadMore: ").concat(m)),!x.emails||0===x.emails.length){if(console.log("[DEBUG-EMPTY] No emails in response for page ".concat(e)),e>1&&!m){g("EMPTY_RESULTS","No emails returned for page ".concat(e,", resetting to page 1")),i({type:"SET_PAGE",payload:1}),i({type:"SET_LOADING",payload:!1});return}m?i({type:"SET_LOADING",payload:!1}):(g("EMPTY_RESULTS","No emails found in ".concat(s.currentFolder)),i({type:"SET_EMAILS",payload:[]}),i({type:"SET_TOTAL_EMAILS",payload:0}),i({type:"SET_TOTAL_PAGES",payload:0}));return}Array.isArray(x.emails)&&(x.emails.length>0&&g("EMAIL_DATES","First few email dates before processing:",x.emails.slice(0,5).map(e=>{var t;return{id:e.id.substring(0,8),subject:null==(t=e.subject)?void 0:t.substring(0,20),date:e.date,dateObj:new Date(e.date),timestamp:new Date(e.date).getTime()}})),x.emails.forEach(e=>{if(e.accountId||(e.accountId=d),e.folder&&!e.folder.includes(":")&&(e.folder="".concat(e.accountId,":").concat(e.folder)),e.date&&!(e.date instanceof Date))try{let t=new Date(e.date);isNaN(t.getTime())||(e.date=t)}catch(t){console.error("Invalid date format for email ".concat(e.id,": ").concat(e.date)),e.date=new Date}})),console.log("[DEBUG-DISPATCH] About to dispatch ".concat(m?"APPEND_EMAILS":"SET_EMAILS"," with ").concat((null==(l=x.emails)?void 0:l.length)||0," emails")),i({type:m?"APPEND_EMAILS":"SET_EMAILS",payload:Array.isArray(x.emails)?x.emails:[]}),setTimeout(()=>{var e;console.log("[DEBUG-AFTER-DISPATCH] Email count is now: ".concat(s.emails.length,", should include the ").concat((null==(e=x.emails)?void 0:e.length)||0," new emails we just loaded"))},0),x.totalEmails&&i({type:"SET_TOTAL_EMAILS",payload:x.totalEmails}),x.totalPages&&i({type:"SET_TOTAL_PAGES",payload:x.totalPages}),x.mailboxes&&x.mailboxes.length>0&&i({type:"SET_MAILBOXES",payload:x.mailboxes})}catch(e){g("ERROR","Failed to load emails: ".concat(e instanceof Error?e.message:String(e))),i({type:"SET_ERROR",payload:e instanceof Error?e.message:"Failed to load emails"}),d({variant:"destructive",title:"Error",description:e instanceof Error?e.message:"Failed to load emails"})}finally{u===s.currentFolder&&p===((null==(o=s.selectedAccount)?void 0:o.id)||"default")?i({type:"SET_LOADING",payload:!1}):console.log("[DEBUG-LOAD_EMAILS] Folder/account changed during load, not clearing loading state")}},[null==c||null==(e=c.user)?void 0:e.id,s.currentFolder,s.selectedAccount,s.page,s.perPage,s.emails.length,d,g]),f=(0,l.useCallback)(async(e,t)=>{g("CHANGE_FOLDER","Changing to folder ".concat(e," with account ").concat(t||"default"));try{u.current=0,i({type:"SET_PAGE",payload:1}),i({type:"SET_EMAILS",payload:[]}),i({type:"SET_LOADING",payload:!0}),i({type:"CHANGE_FOLDER",payload:{folder:e,accountId:t||"default"}})}catch(e){g("ERROR","Failed to change folder: ".concat(e instanceof Error?e.message:String(e))),i({type:"SET_ERROR",payload:e instanceof Error?e.message:"Failed to change folder"}),i({type:"SET_LOADING",payload:!1})}},[g,i]),x=(0,l.useCallback)(e=>{g("SELECT_ACCOUNT","Selecting account: ".concat(e.email," (").concat(e.id,")")),i({type:"SELECT_ACCOUNT",payload:e})},[g]),b=(0,l.useCallback)(async(e,t,a)=>{if(g("SELECT_EMAIL","Selecting email ".concat(e," from account ").concat(t," in folder ").concat(a)),!e)return void i({type:"SELECT_EMAIL",payload:{emailId:"",accountId:"",folder:"",email:null}});try{let n=s.emails.find(t=>t.id===e);if(n&&n.contentFetched){i({type:"SELECT_EMAIL",payload:{emailId:e,accountId:t,folder:a,email:n}}),n.flags.seen||E(e,!0,t);return}i({type:"SET_LOADING",payload:!0});let{normalizedFolder:l,effectiveAccountId:r}=eE(a,t),o=await fetch("/api/courrier/".concat(e,"?folder=").concat(l,"&accountId=").concat(r));if(!o.ok)throw Error("Failed to fetch email content: ".concat(o.status));let c=await o.json();E(e,!0,r),i({type:"SELECT_EMAIL",payload:{emailId:e,accountId:r,folder:a,email:c}})}catch(e){g("ERROR","Failed to select email: ".concat(e instanceof Error?e.message:String(e))),i({type:"SET_ERROR",payload:e instanceof Error?e.message:"Failed to select email"})}finally{i({type:"SET_LOADING",payload:!1})}},[s.emails,g]),y=(0,l.useCallback)(e=>{i({type:"TOGGLE_EMAIL_SELECTION",payload:e})},[]),w=(0,l.useCallback)(()=>{i({type:"TOGGLE_SELECT_ALL"})},[]),E=(0,l.useCallback)(async(e,t,a)=>{try{let n=s.emails.find(t=>t.id===e),l=a||(null==n?void 0:n.accountId)||"default",r=(null==n?void 0:n.folder)||s.currentFolder,{normalizedFolder:o}=eE(r,l);if(g("MARK_READ","Marking email ".concat(e," as ").concat(t?"read":"unread"," in ").concat(o)),i({type:"MARK_EMAIL_AS_READ",payload:{emailId:e,isRead:t,accountId:l}}),!(await fetch("/api/courrier/".concat(e,"/mark-read"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({isRead:t,folder:o,accountId:l})})).ok)throw Error("Failed to mark email as read");return!0}catch(e){return g("ERROR","Failed to mark email as read: ".concat(e instanceof Error?e.message:String(e))),d({variant:"destructive",title:"Error",description:"Failed to update email read status"}),!1}},[s.emails,s.currentFolder,d,g]),j=(0,l.useCallback)(async e=>{try{let t=s.emails.find(t=>t.id===e);if(!t)throw Error("Email not found");let a=!t.flags.flagged;if(g("TOGGLE_STAR","Setting starred status to ".concat(a," for email ").concat(e)),!(await fetch("/api/courrier/".concat(e,"/flag"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({flagged:a,folder:t.folder,accountId:t.accountId})})).ok)throw Error("Failed to update star status");return h(s.page,s.perPage,!0),!0}catch(e){return g("ERROR","Failed to toggle star: ".concat(e instanceof Error?e.message:String(e))),d({variant:"destructive",title:"Error",description:"Failed to update star status"}),!1}},[s.emails,d,h,g]),v=(0,l.useCallback)(async()=>{var e;if((null==c||null==(e=c.user)?void 0:e.id)&&!s.isLoading)try{let e=s.selectedAccount?s.selectedAccount.id:void 0,{normalizedFolder:t,effectiveAccountId:a,prefixedFolder:n}=eE(s.currentFolder,e);g("CHECK_NEW_EMAILS","Checking for new emails in ".concat(n));let l=new URLSearchParams({folder:t,page:"1",perPage:"1",accountId:a,checkOnly:"true"}),r=await fetch("/api/courrier/emails?".concat(l.toString()),{method:"GET",headers:{"Content-Type":"application/json"},cache:"no-cache"});if(!r.ok)throw Error("Failed to check for new emails: ".concat(r.status));let o=await r.json(),c=s.emails.length>0?parseInt(s.emails[0].id):0;o.newestEmailId&&o.newestEmailId>c?(g("NEW_EMAILS","Found new emails, newest ID: ".concat(o.newestEmailId," (current: ").concat(c,")")),d({variant:"new-email",title:"New emails",description:"You have new emails in your inbox",duration:5e3}),i({type:"SET_PAGE",payload:1}),h(1,s.perPage,!1)):g("CHECK_NEW_EMAILS","No new emails found")}catch(e){console.error("Error checking for new emails:",e)}},[null==c||null==(t=c.user)?void 0:t.id,s.currentFolder,s.isLoading,s.emails,s.perPage,d,h,g,i]),N=(0,l.useCallback)(async e=>{if(0!==e.length){i({type:"SET_LOADING",payload:!0});try{g("DELETE","Deleting ".concat(e.length," emails"));let t=s.emails.find(t=>t.id===e[0]),a=(null==t?void 0:t.accountId)||"default",n=(null==t?void 0:t.folder)||s.currentFolder,{normalizedFolder:l}=eE(n,a);if(!(await fetch("/api/courrier/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({emailIds:e,folder:l,accountId:a})})).ok)throw Error("Failed to delete emails");return i({type:"CLEAR_SELECTED_EMAILS"}),d({title:"Emails Deleted",description:"".concat(e.length," email(s) moved to trash")}),i({type:"SET_PAGE",payload:1}),h(1,s.perPage,!1),!0}catch(e){return g("ERROR","Failed to delete emails: ".concat(e instanceof Error?e.message:String(e))),d({variant:"destructive",title:"Error",description:"Failed to delete emails"}),!1}finally{i({type:"SET_LOADING",payload:!1})}}},[s.emails,s.currentFolder,s.perPage,d,h,g,i]),S=(0,l.useCallback)(async e=>{i({type:"SET_LOADING",payload:!0});try{g("SEND","Sending email to ".concat(e.to));let t=await fetch("/api/courrier/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let e=await t.json();throw Error(e.error||"Failed to send email")}let a=await t.json();return d({title:"Email Sent",description:"Your message has been sent successfully"}),setTimeout(()=>{v(),h(s.page,s.perPage,!1)},1500),{success:!0,...a}}catch(e){return g("ERROR","Failed to send email: ".concat(e instanceof Error?e.message:String(e))),d({variant:"destructive",title:"Error",description:e instanceof Error?e.message:"Failed to send email"}),{success:!1,error:e instanceof Error?e.message:"Failed to send email"}}finally{i({type:"SET_LOADING",payload:!1})}},[d,h,g,v]),A=(0,l.useCallback)(async e=>{i({type:"SET_LOADING",payload:!0});try{var t;if(!(null==c||null==(t=c.user)?void 0:t.id))return;g("SEARCH",'Searching for "'.concat(e,'" in ').concat(s.currentFolder));let{normalizedFolder:a,effectiveAccountId:n}=eE(s.currentFolder),l=new URLSearchParams({folder:a,search:e,accountId:n}),r=await fetch("/api/courrier/search?".concat(l.toString()));if(!r.ok){let e=await r.json();throw Error(e.error||"Failed to search emails")}let o=await r.json();i({type:"SET_EMAILS",payload:o.emails||[]}),o.totalEmails&&i({type:"SET_TOTAL_EMAILS",payload:o.totalEmails}),o.totalPages&&i({type:"SET_TOTAL_PAGES",payload:o.totalPages})}catch(e){g("ERROR","Search failed: ".concat(e instanceof Error?e.message:String(e))),i({type:"SET_ERROR",payload:e instanceof Error?e.message:"Failed to search emails"}),d({variant:"destructive",title:"Error",description:"Failed to search emails"})}finally{i({type:"SET_LOADING",payload:!1})}},[null==c||null==(a=c.user)?void 0:a.id,s.currentFolder,d,g]),T=(0,l.useCallback)((e,t)=>(function(e,t){return"forward"===t?ef(e):eh(e,t)})(e,t),[]),C=(0,l.useCallback)(e=>{i({type:"SET_PAGE",payload:e})},[]),_=(0,l.useCallback)(e=>{i({type:"SET_EMAILS",payload:e})},[]),L=(0,l.useCallback)(()=>{if(s.isLoading||s.page>=s.totalPages)return void console.log("[LOAD_MORE] Skipping load more - already loading: ".concat(s.isLoading,", page: ").concat(s.page,", totalPages: ").concat(s.totalPages));console.log("[LOAD_MORE] Loading more emails for ".concat(s.currentFolder,", currentPage: ").concat(s.page,", totalPages: ").concat(s.totalPages,", current email count: ").concat(s.emails.length)),i({type:"SET_LOADING",payload:!0});let e=s.page+1;i({type:"SET_PAGE",payload:e}),u.current=e,h(e,s.perPage,!0).then(()=>{console.log("[LOAD_MORE] Completed loading more emails for page ".concat(e))})},[s.isLoading,s.page,s.totalPages,s.currentFolder,s.emails.length,s.perPage,i,h]);(0,l.useEffect)(()=>{var e;if((null==c||null==(e=c.user)?void 0:e.id)&&s.currentFolder){let{effectiveAccountId:e}=eE(s.currentFolder);if(p.current!==s.currentFolder){console.log("[DEBUG-FOLDER_EFFECT] Folder changed from ".concat(p.current," to ").concat(s.currentFolder)),p.current=s.currentFolder,console.log("[DEBUG-FOLDER_EFFECT] Folder changed - resetting pagination state"),u.current=0,1!==s.page&&(console.log("[DEBUG-FOLDER_EFFECT] Resetting page to 1 because folder changed"),i({type:"SET_PAGE",payload:1})),i({type:"SET_EMAILS",payload:[]}),i({type:"SET_LOADING",payload:!0}),console.log("[DEBUG-FOLDER_EFFECT] Loading emails for new folder: ".concat(s.currentFolder)),h(1,s.perPage,!1);return}1===s.page&&0===u.current&&(g("FOLDER_LOAD","Loading initial emails for folder ".concat(s.currentFolder)),h(s.page,s.perPage,!1))}},[null==c||null==(n=c.user)?void 0:n.id,s.currentFolder,s.page,s.perPage,h,g,i]),(0,l.useEffect)(()=>{var e;if(!(null==c||null==(e=c.user)?void 0:e.id)||!s.currentFolder)return;if(s.page<1)return void i({type:"SET_PAGE",payload:1});if(console.log("[DEBUG-PAGE_EFFECT] Page changed to ".concat(s.page)),1===s.page){let e=s.currentFolder;if(e!==p.current||0===u.current){console.log("[DEBUG-PAGE_EFFECT] Force loading page 1 for folder: ".concat(e)),i({type:"SET_LOADING",payload:!0}),p.current=e,u.current=1,h(1,s.perPage,!1);return}}if(s.isLoading)return void console.log("[DEBUG-PAGE_EFFECT] Skipping effect execution entirely - already loading");let{effectiveAccountId:t}=eE(s.currentFolder);return s.page===u.current?void console.log("[DEBUG-PAGE_EFFECT] Skipping - already loaded page ".concat(s.page)):0===s.page?void console.log("[DEBUG-PAGE_EFFECT] Skipping load for invalid page ".concat(s.page)):void(u.current=s.page,console.log("[DEBUG-PAGE_EFFECT] Calling loadEmails with isLoadMore=true for page ".concat(s.page)),h(s.page,s.perPage,!0))},[null==c||null==(r=c.user)?void 0:r.id,s.page,s.currentFolder,s.isLoading,s.perPage,h,g,i]);let k=(0,l.useCallback)(async()=>{var e;if(!(null==c?void 0:c.user)||s.isLoadingUnreadCounts)return;let t=Date.now();if(null===m.current&&(m.current=t),t-m.current<5e3)return void console.log("Skipping unread count update - email viewed recently");try{let e="unread_counts_".concat(c.user.id),a=sessionStorage.getItem(e);if(a){let{data:e,timestamp:n}=JSON.parse(a);if(t-n<3e4){g("FETCH_UNREAD","Using sessionStorage data",{age:Math.round((t-n)/1e3)+"s"}),i({type:"SET_UNREAD_COUNTS",payload:e});return}}}catch(e){}if((null==(e=window.__unreadCountFailures)?void 0:e.lastFailureTime)&&t-window.__unreadCountFailures.lastFailureTime>6e4&&(window.__unreadCountFailures={count:0,lastFailureTime:0}),window.__unreadCountFailures||(window.__unreadCountFailures={count:0,lastFailureTime:0}),window.__unreadCountFailures.count>0){let e=Math.min(3e4,1e3*Math.pow(2,window.__unreadCountFailures.count-1));if(t-window.__unreadCountFailures.lastFailureTime<e)return void g("BACKOFF","Skipping unread fetch, in backoff period (".concat(e,"ms)"))}try{i({type:"SET_LOADING_UNREAD_COUNTS",payload:!0});let e=performance.now();g("FETCH_UNREAD","Fetching unread counts from API");let a=await fetch("/api/courrier/unread-counts",{method:"GET",headers:{"Content-Type":"application/json"},cache:"no-cache",next:{revalidate:0}});if(a.ok){window.__unreadCountFailures={count:0,lastFailureTime:0};let n=await a.json(),l=performance.now();if("pending_refresh"===n._status){g("FETCH_UNREAD","Server is refreshing counts, will try again soon"),setTimeout(()=>{k()},2e3);return}if(g("FETCH_UNREAD","Received unread counts in ".concat((l-e).toFixed(2),"ms")),n&&"object"==typeof n){i({type:"SET_UNREAD_COUNTS",payload:n});try{sessionStorage.setItem("unread_counts_".concat(c.user.id),JSON.stringify({data:n,timestamp:t}))}catch(e){}}}else{window.__unreadCountFailures.count=Math.min(window.__unreadCountFailures.count+1,10),window.__unreadCountFailures.lastFailureTime=t;let e=window.__unreadCountFailures.count;if(e>3){let t=Math.min(1e3*Math.pow(2,e-3),3e4);throw g("FETCH_UNREAD","API failure #".concat(e,", backing off for ").concat(t,"ms")),window.__failureBackoffTimer&&clearTimeout(window.__failureBackoffTimer),window.__failureBackoffTimer=setTimeout(()=>{k()},t),Error("Failed to fetch unread counts: ".concat(a.status))}}}catch(e){console.error("Error fetching unread counts:",e)}finally{i({type:"SET_LOADING_UNREAD_COUNTS",payload:!1})}},[i,null==c?void 0:c.user,s.isLoadingUnreadCounts,g]),F=(0,l.useCallback)(()=>{if(0===s.emails.length||0===s.accounts.length)return;window.__lastUnreadUpdate||(window.__lastUnreadUpdate={timestamp:0});let e=Date.now(),t=window.__lastUnreadUpdate;e-t.timestamp<1e4||(k(),t.timestamp=e)},[s.emails.length,s.accounts.length,k]);(0,l.useEffect)(()=>{let e;if(!s.emails||0===s.emails.length)return;e=setTimeout(()=>{F()},5e3);let t=setInterval(()=>{"visible"===document.visibilityState&&F()},6e4);return()=>{clearTimeout(e),clearInterval(t)}},[s.emails,F]),(0,l.useEffect)(()=>{if(!s.emails||0===s.emails.length)return;let e=setInterval(()=>{"visible"===document.visibilityState&&v()},6e4);return()=>{clearInterval(e)}},[s.emails,v]);let D=(0,l.useRef)(null);(0,l.useRef)(0),(0,l.useRef)(null);let R=(0,l.useCallback)((e,t,a,n)=>{i({type:"SELECT_EMAIL",payload:{emailId:e,accountId:t,folder:a,email:n}}),n?(D.current=Date.now(),n.flags&&!n.flags.seen&&i({type:"MARK_EMAIL_AS_READ",payload:{emailId:e,isRead:!0,accountId:t}})):setTimeout(()=>{k()},2e3)},[i,k]),I=(0,l.useCallback)(()=>{s.isLoading||(g("MANUAL_CHECK","Manually checking for new emails"),i({type:"SET_PAGE",payload:1}),h(1,s.perPage,!1),k())},[s.isLoading,s.perPage,h,g,i,k]);return{...s,loadEmails:h,handleEmailSelect:b,toggleEmailSelection:y,toggleSelectAll:w,markEmailAsRead:E,toggleStarred:j,changeFolder:f,deleteEmails:N,sendEmail:S,searchEmails:A,formatEmailForAction:T,setPage:C,setEmails:_,selectAccount:x,handleLoadMore:L,fetchUnreadCounts:k,viewEmail:R,checkForNewEmails:v,forceCheckForNewEmails:I}};function eA(){return null}let eT=["bg-blue-500","bg-green-500","bg-red-500","bg-yellow-500","bg-purple-500","bg-pink-500","bg-indigo-500","bg-teal-500","bg-orange-500","bg-cyan-500"],eC=(e,t,a)=>{let n=new Date().toISOString().split("T")[1].substring(0,12);console.log("[".concat(n,"][EMAIL-APP][").concat(e,"] ").concat(t)),a&&console.log("[".concat(n,"][EMAIL-APP][DATA]"),a)};function e_(){var e;(0,r.useRouter)();let{data:t}=(0,o.useSession)(),{accounts:a,selectedAccount:S,selectedFolders:A,currentFolder:T,emails:C,selectedEmail:_,selectedEmailIds:L,isLoading:k,error:F,page:D,totalPages:I,totalEmails:O,mailboxes:M,unreadCountMap:P,showFolders:U,loadEmails:G,handleEmailSelect:B,toggleEmailSelection:H,toggleSelectAll:q,markEmailAsRead:z,toggleStarred:$,changeFolder:J,deleteEmails:K,sendEmail:Y,searchEmails:V,formatEmailForAction:X,setPage:Z,setEmails:Q,selectAccount:et,handleLoadMore:ea}=eS(),[en,el]=(0,l.useState)(!1),[er,eo]=(0,l.useState)("new"),[es,ei]=(0,l.useState)(!1),[ec,ed]=(0,l.useState)(!1),[em,eu]=(0,l.useState)(!0),[ep,eg]=(0,l.useState)(!1),[eh,ef]=(0,l.useState)(!1),[ey,ew]=(0,l.useState)(!1),[eE,ej]=(0,l.useState)(!1),[ev,eN]=(0,l.useState)(!1),[e_,eL]=(0,l.useState)(!1),[ek,eF]=(0,l.useState)(null),[eD,eR]=(0,l.useState)(null),[eI,eO]=(0,l.useState)(""),[eM,eP]=(0,l.useState)(!1),[eU,eG]=(0,l.useState)(!1),[eB,eH]=(0,l.useState)(""),[eq,ez]=(0,l.useState)(""),[eW,e$]=(0,l.useState)(0);(0,l.useEffect)(()=>{if(S&&"loading-account"!==S.id){let e=P[S.id.toString()];e?e$(e[T]||0):e$(0)}else{let e=0;Object.values(P).forEach(t=>{e+=t[T]||0}),e$(e)}},[P,S,T]),(0,l.useEffect)(()=>{var e;let n=!0,l=0,r=async()=>{try{var e;if(!n||(eC("SESSION","Initializing email session"),ef(!0),await fetch("/api/redis/status").then(e=>e.json()).catch(()=>({ready:!1})),!n))return;eC("SESSION","Fetching session data from API");let t=await fetch("/api/courrier/session",{credentials:"include",headers:{"Content-Type":"application/json"}});if(401===t.status)if(l<3)return l++,console.log("Session request failed (attempt ".concat(l,"/").concat(3,"), retrying in ").concat(1e3,"ms...")),await new Promise(e=>setTimeout(e,1e3)),r();else return void console.error("Max retries reached for session request");if(!t.ok)throw Error("Session request failed with status ".concat(t.status));let o=await t.json();if(console.log("[DEBUG] Session API response details:",{authenticated:o.authenticated,hasEmailCredentials:o.hasEmailCredentials,accountsCount:(null==(e=o.allAccounts)?void 0:e.length)||0}),o.authenticated&&o.hasEmailCredentials){ew(!!o.prefetchStarted);let e=[];if(o.allAccounts&&Array.isArray(o.allAccounts)&&o.allAccounts.length>0)console.log("[DEBUG] Processing multiple accounts:",o.allAccounts.length),o.allAccounts.forEach(t=>{let a=(t.folders&&Array.isArray(t.folders)?t.folders:[]).map(e=>e.includes(":")?e:"".concat(t.id,":").concat(e));e.push({id:t.id,name:t.display_name||t.email,email:t.email,color:t.color||eT[e.length%eT.length],folders:a})}),console.log("[DEBUG] Constructed accounts:",e);else{let t=o.mailboxes&&o.mailboxes.length>0?o.mailboxes:[];e.push({id:"default-account",name:o.displayName||o.email,email:o.email,color:eT[0],folders:t}),console.log("[DEBUG] Constructed single fallback account:",e[0])}if(Q([]),console.log("[DEBUG] Current state before setting accounts:",{accounts:(null==a?void 0:a.length)||0,selectedAccount:(null==S?void 0:S.id)||"none",currentFolder:T||"none"}),eY(e),e.length>0){let t=e[0];console.log("[DEBUG] Auto-selecting first account:",t),setTimeout(()=>{console.log("[DEBUG] Now calling selectAccount"),et(t)},100)}}else ed(!0)}catch(e){console.error("Error initializing session:",e)}finally{n&&ef(!1)}};return(null==t||null==(e=t.user)?void 0:e.id)&&r(),()=>{n=!1}},[null==t||null==(e=t.user)?void 0:e.id,Q,et]);let eJ=async e=>{if(0!==L.length)switch(e){case"delete":ei(!0);break;case"mark-read":for(let e of L)await z(e,!0);break;case"mark-unread":for(let e of L)await z(e,!1)}},eK=async()=>{await K(L),ei(!1),ef(!0),Z(1),G(1,20,!1).finally(()=>{ef(!1)})},eY=e=>{console.log("[DEBUG] Setting accounts:",e);let t=window;if("function"==typeof t.dispatchEmailAction)t.dispatchEmailAction({type:"SET_ACCOUNTS",payload:e});else{console.error("Cannot dispatch SET_ACCOUNTS action - no dispatch function available"),console.log("[DEBUG] Using fallback method to update accounts");let a=t.__emailStateDispatch;"function"==typeof a?a({type:"SET_ACCOUNTS",payload:e}):console.error("No fallback dispatch method available either")}};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eA,{}),(0,n.jsx)("main",{className:"w-full h-screen bg-black",children:(0,n.jsx)("div",{className:"w-full h-full px-4 pt-12 pb-4",children:(0,n.jsxs)("div",{className:"flex h-full bg-carnet-bg",children:[(0,n.jsx)(R,{accounts:a,selectedAccount:S,selectedFolders:A,currentFolder:T,loading:eh||k,unreadCount:P,showAddAccountForm:eE,onFolderChange:(e,t)=>{ef(!0),J(e,t).finally(()=>{ef(!1)})},onRefresh:()=>{ef(!0),Z(1),G(D,10,!1).finally(()=>ef(!1))},onComposeNew:()=>{eo("new"),el(!0)},onAccountSelect:e=>{var t;return(console.log("[DEBUG] handleAccountSelect called with account:",{id:e.id,email:e.email,folders:null==(t=e.folders)?void 0:t.length}),e&&e.id)?(null==S?void 0:S.id)===e.id?void console.log("[DEBUG] Account already selected, skipping"):void(ef(!0),console.log("[DEBUG] Now selecting account through reducer action"),et(e),console.log("[DEBUG] Account selection completed"),setTimeout(()=>ef(!1),300)):void console.error("Invalid account passed to handleAccountSelect")},onShowAddAccountForm:ej,onAddAccount:async e=>{var t,n,l,r,o,s,i,c;ef(!0),console.log("[DEBUG] Add account form submission:",e);let d={email:(null==(t=e.get("email"))?void 0:t.toString())||"",password:(null==(n=e.get("password"))?void 0:n.toString())||"",host:(null==(l=e.get("host"))?void 0:l.toString())||"",port:parseInt((null==(r=e.get("port"))?void 0:r.toString())||"993"),secure:"on"===e.get("secure"),display_name:(null==(o=e.get("display_name"))?void 0:o.toString())||"",smtp_host:(null==(s=e.get("smtp_host"))?void 0:s.toString())||"",smtp_port:(null==(i=e.get("smtp_port"))?void 0:i.toString())?parseInt((null==(c=e.get("smtp_port"))?void 0:c.toString())||"587"):void 0,smtp_secure:"on"===e.get("smtp_secure")};d.display_name||(d.display_name=d.email);try{let e=await fetch("/api/courrier/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:d.email,password:d.password,host:d.host,port:d.port,secure:d.secure})}),t=await e.json();if(!e.ok)throw Error(t.error||"Connection test failed");console.log("Connection test successful:",t);let n=a.filter(e=>"loading-account"!==e.id),l=await fetch("/api/courrier/account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}),r=await l.json();if(!l.ok)throw Error(r.error||"Failed to add account");let o=r.account;o.color=eT[n.length%eT.length],o.folders=t.details.sampleFolders||["INBOX","Sent","Drafts","Trash"],eY([...a,o]),ej(!1),(0,N.oR)({title:"Account added successfully",description:"Your email account ".concat(d.email," has been added."),duration:5e3})}catch(e){console.error("Error adding account:",e),(0,N.oR)({title:"Failed to add account",description:e instanceof Error?e.message:"Unknown error",variant:"destructive",duration:5e3})}finally{ef(!1)}},onEditAccount:async e=>{try{let t=a.find(t=>t.id===e.id);t?(eF(t),eH(t.color||""),eN(!0)):(0,N.oR)({title:"Error",description:"Could not find account data",variant:"destructive",duration:3e3})}catch(e){console.error("Error preparing account edit:",e),(0,N.oR)({title:"Error",description:"Failed to load account settings",variant:"destructive",duration:3e3})}},onDeleteAccount:e=>{eR(e),eL(!0)},onSelectEmail:(e,t,a)=>{"string"==typeof e&&B(e,t||"",a||T)}}),(0,n.jsxs)("div",{className:"w-80 flex flex-col border-r border-gray-100 overflow-hidden",children:[(0,n.jsxs)("div",{className:"p-2 border-b border-gray-100 bg-white flex items-center justify-between",children:[(0,n.jsx)(E.$,{variant:"ghost",size:"icon",className:"md:hidden h-9 w-9",onClick:()=>eg(!ep),children:(0,n.jsx)(g.A,{className:"h-5 w-5 text-gray-500"})}),(0,n.jsx)("div",{className:"flex-1",children:(0,n.jsxs)("div",{className:"flex items-center",children:[(e=>{let t=e.toLowerCase();if(t.includes("inbox"))return(0,n.jsx)(s.A,{className:"h-4 w-4 text-gray-500"});if(t.includes("sent"))return(0,n.jsx)(i.A,{className:"h-4 w-4 text-gray-500"});if(t.includes("trash"))return(0,n.jsx)(c.A,{className:"h-4 w-4 text-gray-500"});if(t.includes("archive"))return(0,n.jsx)(d.A,{className:"h-4 w-4 text-gray-500"});if(t.includes("draft"))return(0,n.jsx)(m.A,{className:"h-4 w-4 text-gray-500"});else if(t.includes("spam")||t.includes("junk"))return(0,n.jsx)(u.A,{className:"h-4 w-4 text-gray-500"});else return(0,n.jsx)(p.A,{className:"h-4 w-4 text-gray-500"})})(T),(0,n.jsxs)("span",{className:"ml-2 font-medium text-gray-700",children:[(null==S?void 0:S.email)?"".concat(S.email,": "):"",(e=>{let t=e.includes(":")?e.split(":")[1]:e;return t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()})(T.includes(":")?T.split(":")[1]:T)]})]})})]}),(0,n.jsx)("div",{className:"flex-1 overflow-hidden bg-white",children:k?(0,n.jsx)("div",{className:"h-full flex items-center justify-center",children:(0,n.jsxs)("div",{className:"flex flex-col items-center",children:[(0,n.jsx)(h.A,{className:"h-8 w-8 text-blue-500 animate-spin mb-2"}),(0,n.jsx)("p",{className:"text-sm text-gray-500",children:"Loading emails..."})]})}):F?(0,n.jsx)("div",{className:"h-full flex items-center justify-center",children:(0,n.jsx)("div",{className:"max-w-md p-4",children:(0,n.jsxs)(y.Fc,{variant:"destructive",children:[(0,n.jsx)(f.A,{className:"h-4 w-4"}),(0,n.jsx)(y.XL,{children:"Error"}),(0,n.jsx)(y.TN,{children:F})]})})}):(0,n.jsx)("div",{className:"h-full overflow-hidden flex flex-col",children:(0,n.jsx)("div",{className:"flex-1 overflow-y-auto",onScroll:e=>{let t=e.currentTarget,{scrollTop:a,scrollHeight:n,clientHeight:l}=t,r=n-a-l,o=(a+l)/n,s=a>(t.dataset.lastScrollTop?parseInt(t.dataset.lastScrollTop):0);t.dataset.lastScrollTop=a.toString();let i=Date.now();i-parseInt(t.dataset.lastLogTime||"0")>500&&(console.log("[DEBUG-WRAPPER-SCROLL] Distance: ".concat(r,"px, %: ").concat(Math.round(100*o),"%, direction: ").concat(s?"down":"up",", more: ").concat(D<I,", loading: ").concat(k)),t.dataset.lastLogTime=i.toString());let c=parseInt(t.dataset.lastTriggerTime||"0");s&&r<5&&!k&&D<I&&i-c>1e3&&(console.log("[DEBUG-WRAPPER-TRIGGER] *** AT BOTTOM *** Loading more emails"),t.dataset.lastTriggerTime=i.toString(),ea())},children:0===C.length?(0,n.jsx)("div",{className:"h-full flex items-center justify-center",children:(0,n.jsxs)("div",{className:"text-center p-6",children:[(0,n.jsx)(s.A,{className:"h-12 w-12 text-gray-300 mx-auto mb-4"}),(0,n.jsx)("h3",{className:"text-lg font-medium text-gray-700",children:"No emails found"}),(0,n.jsx)("p",{className:"text-sm text-gray-500 mt-1",children:eq?'No results found for "'.concat(eq,'"'):"Your ".concat(T.toLowerCase()," is empty")})]})}):(0,n.jsx)(W,{emails:C,selectedEmailIds:L,selectedEmail:_,onSelectEmail:(e,t,a)=>{B(e,t||(null==S?void 0:S.id)||"",a||T)},onToggleSelect:H,onToggleSelectAll:q,onToggleStarred:$,onLoadMore:ea,hasMoreEmails:D<I,currentFolder:T,isLoading:k,totalEmails:C.length,onBulkAction:eJ})})})})]}),(0,n.jsx)("div",{className:"flex-1 flex flex-col overflow-hidden",children:(0,n.jsx)("div",{className:"flex-1 overflow-hidden bg-white",children:_?(0,n.jsx)(ee,{email:_,onBack:()=>{B("","",""),eu(!0)},onReply:()=>{_&&(eo("reply"),el(!0))},onReplyAll:()=>{_&&(eo("reply-all"),el(!0))},onForward:()=>{_&&(eo("forward"),el(!0))},onToggleStar:()=>$(_.id)}):(0,n.jsx)("div",{className:"h-full flex items-center justify-center",children:(0,n.jsxs)("div",{className:"text-center text-muted-foreground",children:[(0,n.jsx)("p",{children:"Select an email to view or"}),(0,n.jsx)("button",{className:"text-primary mt-2 hover:underline",onClick:()=>{eo("new"),el(!0)},children:"Compose a new message"})]})})})})]})})}),(0,n.jsx)(eb,{show:es,selectedCount:L.length,onConfirm:eK,onCancel:()=>ei(!1)}),(0,n.jsx)(b.lG,{open:en,onOpenChange:e=>!e&&el(!1),children:(0,n.jsxs)(b.Cf,{className:"sm:max-w-[800px] p-0 h-[80vh]",children:[(0,n.jsx)(b.L3,{asChild:!0,children:(0,n.jsx)("span",{className:"sr-only",children:"New Message"})}),(0,n.jsx)(ex,{type:er,initialEmail:"new"!==er?_:void 0,onSend:async e=>{try{await Y(e);return}catch(e){throw console.error("Error sending email:",e),e}},onClose:()=>el(!1),accounts:a})]})}),(0,n.jsx)(b.lG,{open:ev,onOpenChange:e=>{e||(eN(!1),eP(!1),eF(null),eO(""),eH(""),window.location.reload())},children:(0,n.jsxs)(b.Cf,{className:"sm:max-w-[500px] bg-white text-gray-800",children:[(0,n.jsx)(b.L3,{className:"text-gray-800",children:"Edit Account Settings"}),(0,n.jsxs)("form",{onSubmit:async e=>{if(e.preventDefault(),ek){eP(!0);try{let t=e.target.querySelector("#display-name").value;if(eI)try{let e=await fetch("/api/courrier/account-details?accountId=".concat(ek.id));if(!e.ok)throw Error("Failed to fetch account connection details");let t=await e.json(),a=await fetch("/api/courrier/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:ek.email,password:eI,host:t.host,port:t.port||993,secure:t.secure||!0})}),n=await a.json();if(!a.ok)throw Error(n.error||"Connection test failed with new password");console.log("Connection test successful with new password")}catch(e){throw console.error("Error testing connection:",e),Error("Password test failed: ".concat(e instanceof Error?e.message:"Unknown error"))}let n=await fetch("/api/courrier/account",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:ek.id,newPassword:eI||void 0,display_name:t,color:eB})}),l=await n.json();if(!n.ok)throw Error(l.error||"Failed to update account settings");(0,N.oR)({title:"Account updated",description:"Account settings updated successfully."}),eN(!1),eO(""),eY(a.map(e=>e.id===ek.id?{...e,name:t,color:eB}:e)),eF(null),window.location.reload()}catch(e){(0,N.oR)({title:"Error",description:e instanceof Error?e.message:"Failed to update account settings",variant:"destructive"})}finally{eP(!1)}}},children:[(0,n.jsxs)("div",{className:"mb-4",children:[(0,n.jsx)(v.J,{htmlFor:"display-name",className:"text-gray-800",children:"Account Name"}),(0,n.jsx)(j.p,{id:"display-name",type:"text",defaultValue:null==ek?void 0:ek.name,className:"mt-1 bg-white text-gray-800",disabled:eM})]}),(0,n.jsxs)("div",{className:"mb-4",children:[(0,n.jsx)(v.J,{htmlFor:"new-password",className:"text-gray-800",children:"New Password (optional)"}),(0,n.jsx)(j.p,{id:"new-password",type:"password",value:eI,onChange:e=>eO(e.target.value),className:"mt-1 bg-white text-gray-800",placeholder:"Leave blank to keep current password",disabled:eM})]}),(0,n.jsxs)("div",{className:"mb-4",children:[(0,n.jsx)(v.J,{className:"block mb-2 text-gray-800",children:"Account Color"}),(0,n.jsx)("div",{className:"grid grid-cols-5 gap-2",children:eT.map((e,t)=>(0,n.jsxs)("div",{className:"flex items-center",children:[(0,n.jsx)("input",{type:"radio",id:"color-".concat(t),name:"color",value:e,checked:eB===e,onChange:()=>eH(e),className:"sr-only"}),(0,n.jsx)("label",{htmlFor:"color-".concat(t),className:"w-8 h-8 rounded-full cursor-pointer flex items-center justify-center ".concat(e," hover:ring-2 hover:ring-blue-300 transition-all"),style:{boxShadow:eB===e?"0 0 0 2px white, 0 0 0 4px #3b82f6":"none"},onClick:()=>eH(e),children:eB===e&&(0,n.jsx)(x.A,{className:"h-4 w-4 text-white"})})]},t))})]}),(0,n.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,n.jsx)(E.$,{type:"button",className:"bg-red-500 hover:bg-red-600 text-white",onClick:()=>{eN(!1),window.location.reload()},children:"Cancel"}),(0,n.jsxs)(E.$,{type:"submit",className:"bg-blue-500 hover:bg-blue-600 text-white",disabled:eM,children:[eM?(0,n.jsx)(h.A,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save"]})]})]})]})}),(0,n.jsx)(w.Lt,{open:e_,onOpenChange:e=>{e||eL(!1)},children:(0,n.jsxs)(w.EO,{children:[(0,n.jsxs)(w.wd,{children:[(0,n.jsx)(w.r7,{children:"Delete Account"}),(0,n.jsx)(w.$v,{children:"Are you sure you want to delete this account? This action cannot be undone."})]}),(0,n.jsxs)(w.ck,{children:[(0,n.jsx)(w.Zr,{onClick:()=>eL(!1),children:"Cancel"}),(0,n.jsx)(w.Rx,{asChild:!0,children:(0,n.jsx)(E.$,{variant:"destructive",disabled:eU,onClick:async()=>{if(eD){eG(!0);try{let e=await fetch("/api/courrier/account?accountId=".concat(eD.id),{method:"DELETE"}),t=await e.json();if(!e.ok)throw Error(t.error||"Failed to delete account");(0,N.oR)({title:"Account deleted",description:"The account was deleted successfully."}),eL(!1),window.location.reload()}catch(e){(0,N.oR)({title:"Error",description:e instanceof Error?e.message:"Failed to delete account",variant:"destructive"})}finally{eG(!1)}}},children:"Delete"})})]})]})})]})}},44232:(e,t,a)=>{Promise.resolve().then(a.bind(a,38128))},49026:(e,t,a)=>{"use strict";a.d(t,{Fc:()=>i,TN:()=>d,XL:()=>c});var n=a(95155),l=a(12115),r=a(74466),o=a(53999);let s=(0,r.F)("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),i=l.forwardRef((e,t)=>{let{className:a,variant:l,...r}=e;return(0,n.jsx)("div",{ref:t,role:"alert",className:(0,o.cn)(s({variant:l}),a),...r})});i.displayName="Alert";let c=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,n.jsx)("h5",{ref:t,className:(0,o.cn)("mb-1 font-medium leading-none tracking-tight",a),...l})});c.displayName="AlertTitle";let d=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,n.jsx)("div",{ref:t,className:(0,o.cn)("text-sm [&_p]:leading-relaxed",a),...l})});d.displayName="AlertDescription"},53580:(e,t,a)=>{"use strict";a.d(t,{dj:()=>u});var n=a(12115);let l=0,r=new Map,o=e=>{if(r.has(e))return;let t=setTimeout(()=>{r.delete(e),d({type:"REMOVE_TOAST",toastId:e})},1e6);r.set(e,t)},s=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case"DISMISS_TOAST":{let{toastId:a}=t;return a?o(a):e.toasts.forEach(e=>{o(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===a||void 0===a?{...e,open:!1}:e)}}case"REMOVE_TOAST":if(void 0===t.toastId)return{...e,toasts:[]};return{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},i=[],c={toasts:[]};function d(e){c=s(c,e),i.forEach(e=>{e(c)})}function m(e){let{...t}=e,a=(l=(l+1)%Number.MAX_SAFE_INTEGER).toString(),n=()=>d({type:"DISMISS_TOAST",toastId:a});return d({type:"ADD_TOAST",toast:{...t,id:a,open:!0,onOpenChange:e=>{e||n()}}}),{id:a,dismiss:n,update:e=>d({type:"UPDATE_TOAST",toast:{...e,id:a}})}}function u(){let[e,t]=n.useState(c);return n.useEffect(()=>(i.push(t),()=>{let e=i.indexOf(t);e>-1&&i.splice(e,1)}),[e]),{...e,toast:m,dismiss:e=>d({type:"DISMISS_TOAST",toastId:e})}}},69663:(e,t,a)=>{"use strict";a.d(t,{BK:()=>i,eu:()=>s,q5:()=>c});var n=a(95155),l=a(12115),r=a(44362),o=a(53999);let s=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,n.jsx)(r.bL,{ref:t,className:(0,o.cn)("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...l})});s.displayName=r.bL.displayName;let i=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,n.jsx)(r._V,{ref:t,className:(0,o.cn)("aspect-square h-full w-full",a),...l})});i.displayName=r._V.displayName;let c=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,n.jsx)(r.H4,{ref:t,className:(0,o.cn)("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...l})});c.displayName=r.H4.displayName},82714:(e,t,a)=>{"use strict";a.d(t,{J:()=>c});var n=a(95155),l=a(12115),r=a(72797),o=a(74466),s=a(53999);let i=(0,o.F)("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),c=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,n.jsx)(r.b,{ref:t,className:(0,s.cn)(i(),a),...l})});c.displayName=r.b.displayName},99840:(e,t,a)=>{"use strict";a.d(t,{Cf:()=>u,Es:()=>g,L3:()=>h,ZJ:()=>d,c7:()=>p,lG:()=>i,rr:()=>f,zM:()=>c});var n=a(95155),l=a(12115),r=a(45821),o=a(54416),s=a(53999);let i=r.bL,c=r.l9,d=r.ZL;r.bm;let m=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,n.jsx)(r.hJ,{ref:t,className:(0,s.cn)("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...l})});m.displayName=r.hJ.displayName;let u=l.forwardRef((e,t)=>{let{className:a,children:l,...i}=e;return(0,n.jsxs)(d,{children:[(0,n.jsx)(m,{}),(0,n.jsxs)(r.UC,{ref:t,className:(0,s.cn)("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-white p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",a),...i,children:[l,(0,n.jsxs)(r.bm,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[(0,n.jsx)(o.A,{className:"h-4 w-4"}),(0,n.jsx)("span",{className:"sr-only",children:"Close"})]})]})]})});u.displayName=r.UC.displayName;let p=e=>{let{className:t,...a}=e;return(0,n.jsx)("div",{className:(0,s.cn)("flex flex-col space-y-1.5 text-center sm:text-left",t),...a})};p.displayName="DialogHeader";let g=e=>{let{className:t,...a}=e;return(0,n.jsx)("div",{className:(0,s.cn)("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a})};g.displayName="DialogFooter";let h=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,n.jsx)(r.hE,{ref:t,className:(0,s.cn)("text-lg font-semibold leading-none tracking-tight",a),...l})});h.displayName=r.hE.displayName;let f=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,n.jsx)(r.VY,{ref:t,className:(0,s.cn)("text-sm text-muted-foreground",a),...l})});f.displayName=r.VY.displayName}},e=>{var t=t=>e(e.s=t);e.O(0,[5797,4277,2108,5685,8067,5652,1736,5004,873,1895,8441,1684,7358],()=>t(44232)),_N_E=e.O()}]); |