@realtimex/email-automator 2.9.0 → 2.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,7 +52,7 @@ export const ContextAwareAnalysisSchema = z.object({
52
52
  .describe('Actions to execute based on the matched rule'),
53
53
 
54
54
  // Intent-aware draft content (if draft action is included)
55
- draft_content: z.string().optional()
55
+ draft_content: z.string().nullable().optional()
56
56
  .describe('Generated draft reply if the action includes drafting'),
57
57
  });
58
58
 
@@ -689,8 +689,8 @@ export class EmailProcessorService {
689
689
  for (const action of analysis.actions_to_execute) {
690
690
  if (action === 'none') continue;
691
691
 
692
- // Use AI-generated draft content if available
693
- const draftContent = action === 'draft' ? analysis.draft_content : undefined;
692
+ // Use AI-generated draft content if available (handle null from AI)
693
+ const draftContent = action === 'draft' ? (analysis.draft_content || undefined) : undefined;
694
694
 
695
695
  await this.executeAction(
696
696
  account,
@@ -43,7 +43,7 @@ export const ContextAwareAnalysisSchema = z.object({
43
43
  actions_to_execute: z.array(z.enum(['none', 'delete', 'archive', 'draft', 'read', 'star']))
44
44
  .describe('Actions to execute based on the matched rule'),
45
45
  // Intent-aware draft content (if draft action is included)
46
- draft_content: z.string().optional()
46
+ draft_content: z.string().nullable().optional()
47
47
  .describe('Generated draft reply if the action includes drafting'),
48
48
  });
49
49
  export class IntelligenceService {
@@ -572,8 +572,8 @@ export class EmailProcessorService {
572
572
  for (const action of analysis.actions_to_execute) {
573
573
  if (action === 'none')
574
574
  continue;
575
- // Use AI-generated draft content if available
576
- const draftContent = action === 'draft' ? analysis.draft_content : undefined;
575
+ // Use AI-generated draft content if available (handle null from AI)
576
+ const draftContent = action === 'draft' ? (analysis.draft_content || undefined) : undefined;
577
577
  await this.executeAction(account, email, action, draftContent, eventLogger, `Rule: ${matchedRule?.name || analysis.matched_rule.rule_name}`, matchedRule?.attachments);
578
578
  }
579
579
  }
@@ -92,6 +92,6 @@ ${D}`}class ot extends Error{constructor({message:a,code:r,cause:l,name:c}){var
92
92
 
93
93
  If you want to hide the \`${a.titleName}\`, you can wrap it with our VisuallyHidden component.
94
94
 
95
- For more information, see https://radix-ui.com/primitives/docs/components/${a.docsSlug}`;return x.useEffect(()=>{s&&(document.getElementById(s)||console.error(r))},[r,s]),null},HE="DialogDescriptionWarning",VE=({contentRef:s,descriptionId:a})=>{const l=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${$v(HE).contentName}}.`;return x.useEffect(()=>{const c=s.current?.getAttribute("aria-describedby");a&&c&&(document.getElementById(a)||console.warn(l))},[l,s,a]),null},IE=Tv,GE=kv,PE=Ov,KE=Rv,YE=Mv,JE=Uv,XE=Bv;function gn({...s}){return o.jsx(IE,{"data-slot":"dialog",...s})}function QE({...s}){return o.jsx(GE,{"data-slot":"dialog-portal",...s})}function ZE({className:s,...a}){return o.jsx(PE,{"data-slot":"dialog-overlay",className:Oe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",s),...a})}function yn({className:s,children:a,...r}){return o.jsxs(QE,{"data-slot":"dialog-portal",children:[o.jsx(ZE,{}),o.jsxs(KE,{"data-slot":"dialog-content",className:Oe("bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",s),...r,children:[a,o.jsxs(XE,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(tl,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function ka({className:s,...a}){return o.jsx("div",{"data-slot":"dialog-header",className:Oe("flex flex-col gap-2 text-center sm:text-left",s),...a})}function Er({className:s,...a}){return o.jsx("div",{"data-slot":"dialog-footer",className:Oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",s),...a})}function Oa({className:s,...a}){return o.jsx(YE,{"data-slot":"dialog-title",className:Oe("text-lg leading-none font-semibold",s),...a})}function Ra({className:s,...a}){return o.jsx(JE,{"data-slot":"dialog-description",className:Oe("text-muted-foreground text-sm",s),...a})}const Se=x.forwardRef(({className:s,type:a,...r},l)=>o.jsx("input",{type:a,className:Oe("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",s),ref:l,...r}));Se.displayName="Input";var FE=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],WE=FE.reduce((s,a)=>{const r=_y(`Primitive.${a}`),l=x.forwardRef((c,d)=>{const{asChild:h,...m}=c,y=h?r:a;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(y,{...m,ref:d})});return l.displayName=`Primitive.${a}`,{...s,[a]:l}},{}),e2="Label",Hv=x.forwardRef((s,a)=>o.jsx(WE.label,{...s,ref:a,onMouseDown:r=>{r.target.closest("button, input, select, textarea")||(s.onMouseDown?.(r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));Hv.displayName=e2;var t2=Hv;function pa({className:s,...a}){return o.jsx(t2,{"data-slot":"label",className:Oe("flex items-center gap-2 text-sm leading-none font-medium select-none text-muted-foreground group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",s),...a})}const a2=Ny("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function Wi({className:s,variant:a,...r}){return o.jsx("div",{"data-slot":"alert",role:"alert",className:Oe(a2({variant:a}),s),...r})}function el({className:s,...a}){return o.jsx("div",{"data-slot":"alert-description",className:Oe("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",s),...a})}function vf({className:s}){return o.jsxs("svg",{width:"512",height:"512",viewBox:"0 0 512 512",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:Oe("w-9 h-9",s),children:[o.jsx("path",{d:"M112 112H400C426.51 112 448 133.49 448 160V352C448 378.51 426.51 400 400 400H112C85.4903 400 64 378.51 64 352V160C64 133.49 85.4903 112 112 112Z",className:"stroke-foreground",strokeWidth:"32",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M64 160 L200 270",className:"stroke-foreground",strokeWidth:"32",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M448 160 L312 270",className:"stroke-foreground",strokeWidth:"32",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M256 128 C256 128 276 170 306 178 C276 186 256 228 256 228 C256 228 236 186 206 178 C236 170 256 128 256 128 Z",fill:"#9333ea",children:o.jsx("animateTransform",{attributeName:"transform",type:"translate",values:"0 0; 0 -10; 0 0",dur:"3s",repeatCount:"indefinite"})})]})}function fy(s){const a=s.trim();return a?a.startsWith("http://")||a.startsWith("https://")?a:`https://${a}.supabase.co`:""}function s2(s){const a=s.trim();if(!a)return{valid:!1};if(a.startsWith("http://")||a.startsWith("https://"))try{return new URL(a).hostname.endsWith(".supabase.co")?{valid:!0,message:"Valid Supabase URL"}:{valid:!1,message:"URL must be a supabase.co domain"}}catch{return{valid:!1,message:"Invalid URL format"}}return/^[a-z0-9]+$/.test(a)?{valid:!0,message:"Project ID detected"}:{valid:!1,message:"Enter a URL or Project ID"}}function n2(s){const a=s.trim();return a?a.startsWith("sb_publishable_")?a.length>25?{valid:!0,message:"Valid Publishable Key"}:{valid:!1,message:"Incomplete Publishable Key"}:a.startsWith("eyJ")?a.length>50?{valid:!0,message:"Valid Anon Key"}:{valid:!1,message:"Incomplete Anon Key"}:{valid:!1,message:"Invalid API Key format"}:{valid:!1}}function Vv({onComplete:s,open:a=!0,canClose:r=!1}){const[l,c]=x.useState("welcome"),[d,h]=x.useState(""),[m,y]=x.useState(""),[p,g]=x.useState(null),[w,_]=x.useState(!1),[S,E]=x.useState(!1),j=async()=>{g(null),c("validating");const G=fy(d),W=m.trim(),J=await av(G,W);J.valid?(Bj({url:G,anonKey:W}),c("success"),setTimeout(()=>{window.location.reload()},1e3)):(g(J.error||"Connection failed. Please check your credentials."),c("credentials"))},R=d?s2(d):{valid:!1},D=m?n2(m):{valid:!1},q=d?fy(d):"",B=d&&!d.startsWith("http")&&R.valid;return o.jsx(gn,{open:a,onOpenChange:G=>{!G&&r&&s()},children:o.jsxs(yn,{className:"sm:max-w-md",onPointerDownOutside:G=>{r||G.preventDefault()},onEscapeKeyDown:G=>{r||G.preventDefault()},children:[l==="welcome"&&o.jsxs(o.Fragment,{children:[o.jsxs(ka,{children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx(vf,{className:"w-9 h-9"}),o.jsx(Oa,{children:"Welcome to Email Automator"})]}),o.jsx(Ra,{children:"This application requires a Supabase database to store your emails and automation rules."})]}),o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsx(Wi,{children:o.jsxs(el,{children:[o.jsx("strong",{children:"No Supabase Setup Detected"}),o.jsx("br",{}),"You can create a free project at"," ",o.jsxs("a",{href:"https://supabase.com",target:"_blank",rel:"noopener noreferrer",className:"underline text-primary inline-flex items-center gap-1",children:["supabase.com",o.jsx(Ii,{className:"h-3 w-3"})]})]})}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("h4",{className:"font-medium text-sm",children:"You will need:"}),o.jsxs("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:[o.jsx("li",{children:"Project URL"}),o.jsx("li",{children:"Anon Public Key"})]})]}),o.jsxs("div",{className:"flex gap-2",children:[r&&o.jsx(Z,{variant:"outline",onClick:s,className:"flex-1",children:"Close"}),o.jsx(Z,{onClick:()=>c("credentials"),className:"flex-1",children:"Continue Setup"})]})]})]}),l==="credentials"&&o.jsxs(o.Fragment,{children:[o.jsxs(ka,{children:[o.jsx(Oa,{children:"Connect to Supabase"}),o.jsx(Ra,{children:"Enter your connection details below."})]}),o.jsxs("div",{className:"space-y-4 py-4",children:[p&&o.jsxs(Wi,{variant:"destructive",children:[o.jsx(Dr,{className:"h-4 w-4"}),o.jsx(el,{children:p})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"supabase-url",children:"Project URL or ID"}),o.jsxs("div",{className:"relative",children:[o.jsx(Se,{id:"supabase-url",placeholder:"https://xxx.supabase.co or project-id",value:d,onChange:G=>{h(G.target.value),_(!0)},onBlur:()=>_(!0),className:w&&d?R.valid?"pr-8 border-green-500":"pr-8 border-destructive":""}),w&&d&&R.valid&&o.jsx(ja,{className:"absolute right-2 top-1/2 -translate-y-1/2 h-4 w-4 text-green-500"})]}),B&&o.jsxs("div",{className:"flex items-start gap-1.5 text-xs text-green-600 dark:text-green-400",children:[o.jsx(ja,{className:"h-3 w-3 mt-0.5 flex-shrink-0"}),o.jsxs("span",{children:["Will use: ",q]})]}),w&&d&&R.message&&!R.valid&&o.jsx("p",{className:"text-xs text-destructive",children:R.message})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"anon-key",children:"Anon Public Key"}),o.jsxs("div",{className:"relative",children:[o.jsx(Se,{id:"anon-key",type:"password",placeholder:"eyJ...",value:m,onChange:G=>{y(G.target.value),E(!0)},onBlur:()=>E(!0),className:S&&m?D.valid?"pr-8 border-green-500":"pr-8 border-destructive":""}),S&&m&&D.valid&&o.jsx(ja,{className:"absolute right-2 top-1/2 -translate-y-1/2 h-4 w-4 text-green-500"})]}),S&&m&&D.message&&o.jsx("p",{className:`text-xs ${D.valid?"text-green-600 dark:text-green-400":"text-destructive"}`,children:D.message})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{variant:"outline",onClick:()=>c("welcome"),className:"flex-1",children:"Back"}),r&&o.jsx(Z,{variant:"outline",onClick:s,className:"flex-1",children:"Close"}),o.jsx(Z,{onClick:j,disabled:!R.valid||!D.valid,className:"flex-1",children:"Connect"})]})]})]}),l==="validating"&&o.jsxs(o.Fragment,{children:[o.jsxs(ka,{children:[o.jsx(Oa,{children:"Validating Connection"}),o.jsx(Ra,{children:"Verifying your credentials with Supabase..."})]}),o.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[o.jsx($t,{className:"h-12 w-12 animate-spin text-primary mb-4"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Please wait..."})]})]}),l==="success"&&o.jsxs(o.Fragment,{children:[o.jsxs(ka,{children:[o.jsx(Oa,{children:"Success!"}),o.jsx(Ra,{children:"Your database is connected."})]}),o.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[o.jsx(Hi,{className:"h-12 w-12 text-green-500 mb-4"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Restarting application..."})]})]})]})})}function r2({email:s,isOpen:a,onOpenChange:r,onRetry:l}){const[c,d]=x.useState([]),[h,m]=x.useState(!1);x.useEffect(()=>{a&&s&&y()},[a,s]);const y=async()=>{if(s){m(!0);try{const g=await ze.getEmailEvents(s.id);g.data&&d(g.data.events)}catch(g){console.error("Failed to fetch trace:",g)}finally{m(!1)}}},p=g=>{switch(g){case"analysis":return o.jsx($i,{className:"w-4 h-4 text-purple-500"});case"action":return o.jsx(Lo,{className:"w-4 h-4 text-emerald-500"});case"error":return o.jsx(Dr,{className:"w-4 h-4 text-red-500"});default:return o.jsx(Or,{className:"w-4 h-4 text-blue-500"})}};return o.jsx(gn,{open:a,onOpenChange:r,children:o.jsxs(yn,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs(ka,{className:"p-6 border-b flex flex-row items-center justify-between",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(of,{className:"w-5 h-5 text-primary"}),o.jsx(Oa,{children:"AI Processing Trace"})]}),o.jsx(Ra,{children:"Step-by-step log of how the AI analyzed and acted on this email."})]}),s?.processing_status==="failed"&&l&&o.jsxs(Z,{size:"sm",variant:"outline",onClick:()=>{l(s),r(!1)},className:"gap-2 text-destructive border-destructive/20 hover:bg-destructive/10",children:[o.jsx(Bs,{className:"w-3.5 h-3.5"}),"Retry Job"]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:h?o.jsx("div",{className:"py-20 flex justify-center",children:o.jsx(mt,{})}):c.length===0?o.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:"No granular trace events found for this email."}):c.map((g,w)=>o.jsxs("div",{className:"relative pl-8",children:[w!==c.length-1&&o.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),o.jsx("div",{className:"absolute left-0 top-0 w-8 h-8 rounded-full border bg-background flex items-center justify-center z-10 shadow-sm",children:p(g.event_type)}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-foreground/70",children:g.agent_state}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(kr,{className:"w-3 h-3"}),new Date(g.created_at).toLocaleTimeString()]})]}),o.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[g.event_type==="info"&&o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-foreground/90",children:g.details?.message}),g.details?.system_prompt&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[o.jsx(Us,{className:"w-3 h-3"})," System Prompt"]}),o.jsx("pre",{className:"text-[10px] bg-secondary/50 p-2 rounded border overflow-x-auto whitespace-pre-wrap max-h-60 overflow-y-auto font-mono",children:g.details.system_prompt})]}),g.details?.content_preview&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Email Content (sent to LLM)"]}),o.jsx("pre",{className:"text-[10px] bg-blue-500/5 p-2 rounded border border-blue-500/10 overflow-x-auto whitespace-pre-wrap max-h-40 overflow-y-auto font-mono",children:g.details.content_preview})]})]}),g.event_type==="analysis"&&o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{className:"text-[10px] bg-secondary px-2 py-1 rounded",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Category:"}),o.jsx("span",{className:"font-bold uppercase",children:g.details?.category||"Analyzing..."})]}),o.jsxs("div",{className:"text-[10px] bg-secondary px-2 py-1 rounded",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Sentiment:"}),o.jsx("span",{className:"font-bold uppercase",children:g.details?.sentiment||"Analyzing..."})]})]}),g.details?.system_prompt&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[o.jsx(Us,{className:"w-3 h-3"})," System Prompt"]}),o.jsx("pre",{className:"text-[10px] bg-secondary/50 p-2 rounded border overflow-x-auto whitespace-pre-wrap max-h-40 overflow-y-auto font-mono",children:g.details?.system_prompt})]}),g.details?._raw_response&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Raw LLM Response"]}),o.jsx("pre",{className:"text-[10px] bg-emerald-500/5 p-2 rounded border border-emerald-500/10 overflow-x-auto font-mono",children:JSON.stringify(JSON.parse(g.details._raw_response),null,2)})]}),g.details?.usage&&o.jsxs("div",{className:"flex gap-4 pt-2 border-t border-border/50",children:[o.jsxs("div",{className:"text-[10px]",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Prompt:"}),o.jsx("span",{className:"font-mono font-bold",children:g.details.usage.prompt_tokens})]}),o.jsxs("div",{className:"text-[10px]",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Completion:"}),o.jsx("span",{className:"font-mono font-bold",children:g.details.usage.completion_tokens})]}),o.jsxs("div",{className:"text-[10px]",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Total:"}),o.jsx("span",{className:"font-mono font-bold text-primary",children:g.details.usage.total_tokens})]})]})]}),g.event_type==="action"&&o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:["Executed: ",g.details?.action]}),o.jsxs("p",{className:"text-xs text-muted-foreground italic",children:['"',g.details?.reason,'"']})]}),o.jsx(lf,{className:"w-5 h-5 text-emerald-500"})]}),g.event_type==="error"&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:typeof g.details?.error=="object"?g.details.error.message||JSON.stringify(g.details.error):g.details?.error}),g.details?.raw_response&&o.jsx("pre",{className:"text-[10px] bg-red-500/5 p-2 rounded border border-red-500/10 overflow-x-auto whitespace-pre-wrap font-mono",children:typeof g.details.raw_response=="object"?JSON.stringify(g.details.raw_response,null,2):g.details.raw_response})]})]})]})]},g.id))})]})})}const i2={spam:"bg-destructive/10 text-destructive",newsletter:"bg-blue-500/10 text-blue-600 dark:text-blue-400",support:"bg-orange-500/10 text-orange-600 dark:text-orange-400",client:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",internal:"bg-purple-500/10 text-purple-600 dark:text-purple-400",personal:"bg-pink-500/10 text-pink-600 dark:text-pink-400",other:"bg-gray-500/10 text-gray-600 dark:text-gray-400"};function l2(){const{state:s,actions:a,dispatch:r}=Br(),{openTerminal:l}=cv(),[c,d]=x.useState(!0),[h,m]=x.useState(!1),[y,p]=x.useState(""),[g,w]=x.useState(null),[_,S]=x.useState(null),[E,j]=x.useState({}),[R,D]=x.useState(null),[q,B]=x.useState(!1),[G,W]=x.useState(null);x.useEffect(()=>{s.isAuthenticated?(J(),a.fetchStats()):d(!1)},[g,s.isAuthenticated]);const J=async(C=0)=>{d(!0),await a.fetchEmails({category:g||void 0,search:y||void 0,offset:C,sortBy:s.sortBy,sortOrder:s.sortOrder}),d(!1)},P=C=>{a.fetchEmails({category:g||void 0,search:y||void 0,offset:0,sortBy:C,sortOrder:s.sortOrder})},Q=()=>{a.fetchEmails({category:g||void 0,search:y||void 0,offset:0,sortBy:s.sortBy,sortOrder:s.sortOrder==="asc"?"desc":"asc"})},ce=async()=>{if(s.accounts.length===0){te.warning("Please connect an email account first");return}Ea.playStart(),l(),m(!0);const C=await a.triggerSync();m(!1),C?(Ea.playSuccess(),te.success("Sync completed! Check your emails.")):te.error("Sync failed. Check account status for details.")},Je=async(C,Y)=>{if(Y==="delete"&&R!==C.id){D(C.id);return}D(null),j(_e=>({..._e,[C.id]:Y}));const K=await a.executeAction(C.id,Y);j(_e=>{const je={..._e};return delete je[C.id],je}),K&&(te.success(`Email ${Y==="delete"?"deleted":Y==="archive"?"archived":"updated"}`),Y==="delete"&&J(s.emailsOffset))},ve=()=>{D(null)},pe=C=>{C.preventDefault(),J()},Ze=C=>{const Y=C==="next"?s.emailsOffset+20:Math.max(0,s.emailsOffset-20);J(Y)},st=C=>{W(C),B(!0)},qe=async C=>{await a.retryProcessing(C.id)&&te.success("Retrying email processing...")};return o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 animate-in fade-in duration-500",children:[o.jsxs("section",{className:"lg:col-span-2 space-y-4",children:[o.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-4",children:[o.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[o.jsx(Bd,{className:"w-5 h-5 text-primary"}),"Recent Analysis"]}),o.jsxs("div",{className:"flex gap-2 w-full sm:w-auto",children:[o.jsxs(Z,{onClick:ce,size:"sm",variant:"default",className:"h-9 shadow-md px-4",disabled:h,children:[o.jsx(Bs,{className:Oe("w-3.5 h-3.5 mr-2",h&&"animate-spin")}),h?"Syncing...":"Sync Now"]}),o.jsxs("span",{className:"h-9 text-xs font-medium text-muted-foreground bg-secondary px-3 py-1 rounded-md border border-border flex items-center",children:[s.emailsTotal," emails"]})]})]}),h&&o.jsxs("div",{className:"bg-primary/5 border border-primary/20 p-4 rounded-lg flex items-center justify-between animate-in fade-in slide-in-from-top-2",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"bg-primary/10 p-2 rounded-full",children:o.jsx($t,{className:"w-5 h-5 text-primary animate-spin"})}),o.jsxs("div",{children:[o.jsx("h4",{className:"font-semibold text-sm",children:"Sync in progress..."}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Fetching and analyzing emails. New emails will appear below automatically."})]})]}),o.jsxs(Z,{variant:"outline",size:"sm",onClick:l,className:"h-8 text-xs",children:[o.jsx(of,{className:"w-3.5 h-3.5 mr-2"}),"View Logs"]})]}),o.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-center",children:[o.jsxs("form",{onSubmit:pe,className:"flex-1 flex gap-2 w-full",children:[o.jsxs("div",{className:"relative flex-1",children:[o.jsx(zw,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),o.jsx(Se,{placeholder:"Search emails...",value:y,onChange:C=>p(C.target.value),className:"pl-9 h-9"})]}),o.jsx(Z,{type:"submit",size:"sm",className:"h-9 px-4",children:"Search"})]}),o.jsxs("div",{className:"flex items-center gap-1 bg-secondary/30 p-1 rounded-md border border-border/50 h-9",children:[o.jsxs("select",{className:"bg-transparent text-xs font-medium border-none focus:ring-0 cursor-pointer pl-2 pr-8 h-full",value:s.sortBy,onChange:C=>P(C.target.value),children:[o.jsx("option",{value:"date",children:"Received Time"}),o.jsx("option",{value:"created_at",children:"Processed Time"})]}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-primary",onClick:Q,title:s.sortOrder==="asc"?"Sorting: Oldest First":"Sorting: Newest First",children:s.sortOrder==="asc"?o.jsx(Tx,{className:"w-3.5 h-3.5"}):o.jsx(Sx,{className:"w-3.5 h-3.5"})})]})]}),o.jsxs("div",{className:"flex gap-1 flex-wrap",children:[o.jsx(Z,{size:"sm",variant:s.activeCategory===null?"secondary":"ghost",onClick:()=>w(null),children:"All"}),["spam","client","newsletter","support"].map(C=>o.jsx(Z,{size:"sm",variant:s.activeCategory===C?"secondary":"ghost",onClick:()=>w(C),className:"capitalize",children:C},C))]}),c?o.jsx(sN,{}):s.emails.length===0?o.jsxs(At,{className:"p-20 text-center shadow-sm",children:[o.jsx("div",{className:"w-16 h-16 bg-primary/10 text-primary rounded-full flex items-center justify-center mx-auto mb-6",children:o.jsx(Bd,{className:"w-8 h-8"})}),o.jsx("h3",{className:"text-lg font-medium",children:"No emails found"}),o.jsx("p",{className:"text-muted-foreground mt-2 mb-6",children:s.accounts.length===0?"Connect your email account to get started.":"Try syncing or adjusting your filters."}),s.accounts.length>0&&o.jsxs(Z,{onClick:()=>{l(),ce()},disabled:h,children:[o.jsx(Bs,{className:Oe("w-4 h-4 mr-2",h&&"animate-spin")}),"Sync Now"]})]}):o.jsxs(o.Fragment,{children:[s.emails.map(C=>o.jsx(u2,{email:C,onAction:Je,onRetry:qe,onViewTrace:st,onSelect:()=>S(C),isSelected:_?.id===C.id,loadingAction:E[C.id],isDeletePending:R===C.id,onCancelDelete:ve},C.id)),o.jsx(r2,{isOpen:q,onOpenChange:B,email:G,onRetry:qe}),s.emailsTotal>20&&o.jsxs("div",{className:"flex items-center justify-between pt-4",children:[o.jsxs(Z,{variant:"outline",size:"sm",onClick:()=>Ze("prev"),disabled:s.emailsOffset===0,children:[o.jsx(Bx,{className:"w-4 h-4 mr-1"}),"Previous"]}),o.jsxs("span",{className:"text-sm text-muted-foreground",children:[s.emailsOffset+1," - ",Math.min(s.emailsOffset+20,s.emailsTotal)," of ",s.emailsTotal]}),o.jsxs(Z,{variant:"outline",size:"sm",onClick:()=>Ze("next"),disabled:s.emailsOffset+20>=s.emailsTotal,children:["Next",o.jsx($x,{className:"w-4 h-4 ml-1"})]})]})]})]}),o.jsxs("aside",{className:"space-y-6",children:[_&&o.jsxs(At,{className:"p-6 border-primary/20 bg-primary/5 animate-in slide-in-from-right-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("h3",{className:"font-semibold",children:"Email Details"}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>S(null),children:o.jsx(tl,{className:"w-4 h-4"})})]}),o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"From:"}),o.jsx("p",{className:"font-medium truncate",children:_.sender})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),o.jsx("p",{className:"font-medium",children:_.subject})]}),_.ai_analysis&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Summary:"}),o.jsx("p",{className:"text-xs mt-1",children:_.ai_analysis.summary})]}),_.ai_analysis.key_points&&o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Key Points:"}),o.jsx("ul",{className:"text-xs mt-1 list-disc list-inside",children:_.ai_analysis.key_points.map((C,Y)=>o.jsx("li",{children:C},Y))})]}),_.ai_analysis.draft_response&&o.jsxs("div",{className:"mt-4 p-3 bg-emerald-500/5 border border-emerald-500/20 rounded-lg",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2 text-emerald-600 dark:text-emerald-400",children:[o.jsx(Lw,{className:"w-3.5 h-3.5"}),o.jsx("span",{className:"text-xs font-bold uppercase",children:"AI Draft Reply"})]}),o.jsx("p",{className:"text-xs leading-relaxed whitespace-pre-wrap italic text-foreground/80",children:_.ai_analysis.draft_response}),o.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:["* This draft is already saved in your ",_.email_accounts?.provider==="gmail"?"Gmail":"Outlook"," Drafts folder."]})]})]})]})]}),o.jsx(o2,{accounts:s.accounts,onUpdate:a.updateAccount,onSync:a.triggerSync,settings:s.settings,onUpdateSettings:a.updateSettings,openTerminal:l}),o.jsxs(At,{className:"p-6",children:[o.jsxs("h3",{className:"font-semibold mb-4 flex items-center gap-2",children:[o.jsx(vy,{className:"w-4 h-4 text-primary"}),"Sync History"]}),o.jsx("div",{className:"space-y-4",children:!s.stats?.recentSyncs||s.stats.recentSyncs.length===0?o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No sync history available."}):s.stats.recentSyncs.slice(0,5).map(C=>o.jsxs("div",{className:"flex justify-between items-start text-sm border-b last:border-0 pb-3 last:pb-0",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:Oe("w-1.5 h-1.5 rounded-full",C.status==="success"?"bg-emerald-500":C.status==="running"?"bg-blue-500 animate-pulse":"bg-red-500")}),o.jsxs("p",{className:"font-medium text-xs",children:[new Date(C.started_at).toLocaleDateString()," ",new Date(C.started_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]}),o.jsxs("p",{className:"text-[10px] text-muted-foreground pl-3.5",children:["Processed: ",o.jsx("span",{className:"font-medium text-foreground",children:C.emails_processed})," • Actioned: ",o.jsx("span",{className:"font-medium text-foreground",children:C.emails_deleted+C.emails_drafted})]}),C.error_message&&o.jsx("p",{className:"text-[10px] text-destructive pl-3.5 line-clamp-1",title:C.error_message,children:C.error_message})]}),o.jsx("div",{className:"text-[10px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded",children:C.status==="running"?"Running":C.completed_at?`${Math.round((new Date(C.completed_at).getTime()-new Date(C.started_at).getTime())/1e3)}s`:"..."})]},C.id))})]}),o.jsxs(At,{className:"p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:"Quick Stats"}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Processed"}),o.jsx("span",{className:"font-medium",children:s.emailsTotal})]}),o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"Connected Accounts"}),o.jsx("span",{className:"font-medium",children:s.accounts.length})]}),o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Rules"}),o.jsx("span",{className:"font-medium",children:s.rules.filter(C=>C.is_enabled).length})]})]})]})]})]})}function o2({accounts:s,onUpdate:a,onSync:r,settings:l,onUpdateSettings:c,openTerminal:d}){return s.length===0?null:o.jsxs(At,{className:"p-6",children:[o.jsxs("h3",{className:"font-semibold mb-4 flex items-center gap-2",children:[o.jsx($w,{className:"w-4 h-4 text-primary"}),"Sync Scope"]}),o.jsx("div",{className:"space-y-6",children:s.map(h=>o.jsx(c2,{account:h,onUpdate:a,onSync:r,openTerminal:d},h.id))})]})}function c2({account:s,onUpdate:a,onSync:r,openTerminal:l}){const[c,d]=x.useState(!1),[h,m]=x.useState(""),[y,p]=x.useState(""),g=E=>{if(!E)return"";const j=typeof E=="string"&&/^\d+$/.test(E)?parseInt(E):E,R=new Date(j);if(isNaN(R.getTime()))return"";const D=q=>q<10?"0"+q:q;return R.getFullYear()+"-"+D(R.getMonth()+1)+"-"+D(R.getDate())+"T"+D(R.getHours())+":"+D(R.getMinutes())};x.useEffect(()=>{const E=s.sync_start_date||s.last_sync_checkpoint||s.last_sync_at;m(g(E)),p((s.sync_max_emails_per_run||50).toString())},[s.id,s.sync_start_date,s.last_sync_checkpoint,s.last_sync_at,s.sync_max_emails_per_run]);const w=async E=>{d(!0),await a(s.id,E),d(!1)},_=()=>{const E=s.sync_start_date?new Date(s.sync_start_date).toISOString():"",j=h?new Date(h).toISOString():"";j!==E&&w({sync_start_date:j||null})},S=()=>{const E=parseInt(y,10)||50;E!==s.sync_max_emails_per_run&&w({sync_max_emails_per_run:E})};return o.jsxs("div",{className:"space-y-3 pb-4 border-b last:border-0 last:pb-0",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-xs font-medium truncate max-w-[150px]",title:s.email_address,children:s.email_address}),o.jsxs("div",{className:"flex items-center gap-1",children:[s.last_sync_status==="syncing"?o.jsx($t,{className:"w-3 h-3 text-primary animate-spin"}):s.last_sync_status==="success"?o.jsx(lf,{className:"w-3 h-3 text-emerald-500"}):s.last_sync_status==="error"?o.jsx("span",{title:s.last_sync_error||"Error",children:o.jsx(Dr,{className:"w-3 h-3 text-destructive"})}):null,o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{l(),r(s.id)},disabled:s.last_sync_status==="syncing",children:o.jsx(Bs,{className:Oe("w-3 h-3",s.last_sync_status==="syncing"&&"animate-spin")})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground hover:text-orange-500",title:"Reset Checkpoint (Force Full Re-sync from Start Date)",onClick:()=>a(s.id,{last_sync_checkpoint:null}),disabled:s.last_sync_status==="syncing",children:o.jsx(vy,{className:"w-3 h-3"})})]})]}),o.jsxs("div",{className:"grid grid-cols-[1.5fr_1fr] gap-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("label",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(kx,{className:"w-2.5 h-2.5"})," Sync From"]}),o.jsx(Se,{type:"datetime-local",className:"h-7 text-[10px] px-2 py-0 w-full",value:h,onChange:E=>m(E.target.value),onBlur:_,disabled:c||s.last_sync_status==="syncing"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs("label",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(ow,{className:"w-2.5 h-2.5"})," Max Emails"]}),o.jsx(Se,{type:"number",className:"h-7 text-[10px] px-2 py-0",value:y,onChange:E=>p(E.target.value),onBlur:S,disabled:c||s.last_sync_status==="syncing"})]})]}),s.last_sync_at&&o.jsxs("p",{className:"text-[9px] text-muted-foreground",children:["Last sync: ",new Date(s.last_sync_at).toLocaleString()]}),s.last_sync_error&&o.jsxs("p",{className:"text-[9px] text-destructive italic line-clamp-1",title:s.last_sync_error,children:["Error: ",s.last_sync_error]})]})}function u2({email:s,onAction:a,onRetry:r,onViewTrace:l,onSelect:c,isSelected:d,loadingAction:h,isDeletePending:m,onCancelDelete:y}){if(!s)return null;const p=i2[s.category||"other"],g=!!h,w=()=>{if(!s.email_accounts)return"#";const{provider:_,email_address:S}=s.email_accounts;return _==="gmail"?`https://mail.google.com/mail/u/${S}/#all/${s.external_id}`:`https://outlook.office.com/mail/deeplink/read/${encodeURIComponent(s.external_id)}`};return o.jsx(At,{className:Oe("hover:shadow-md transition-shadow group cursor-pointer",d&&"ring-2 ring-primary"),onClick:c,children:o.jsxs("div",{className:"p-5",children:[o.jsxs("div",{className:"flex justify-between items-start mb-3 gap-4",children:[o.jsxs("div",{className:"flex gap-3 flex-1 min-w-0",children:[o.jsx("div",{className:Oe("w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center font-bold text-white text-xs",s.category==="spam"?"bg-destructive":"bg-primary"),children:s.sender?.[0]?.toUpperCase()||"?"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h3",{className:"font-semibold text-sm line-clamp-1 group-hover:text-primary transition-colors",children:s.subject||"No Subject"}),o.jsx("p",{className:"text-xs text-muted-foreground truncate",title:s.sender||"",children:s.sender})]})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[o.jsx("span",{className:Oe("px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",p),children:s.category||"unknown"}),o.jsxs("div",{className:"flex items-center justify-end gap-1",children:[s.processing_status==="pending"&&o.jsxs("span",{className:"text-[9px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx(kr,{className:"w-2.5 h-2.5"})," Queued"]}),s.processing_status==="processing"&&o.jsxs("span",{className:"text-[9px] text-blue-600 dark:text-blue-400 bg-blue-500/10 border border-blue-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx($t,{className:"w-2.5 h-2.5 animate-spin"})," Analyzing"]}),s.processing_status==="completed"&&o.jsxs("span",{className:"text-[9px] text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx($i,{className:"w-2.5 h-2.5"})," Analyzed"]}),s.processing_status==="failed"&&o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsxs("span",{className:"text-[9px] text-red-600 dark:text-red-400 bg-red-500/10 border border-red-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",title:s.processing_error||"Unknown error",children:[o.jsx(Dr,{className:"w-2.5 h-2.5"})," Failed"]}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-5 w-5 text-red-600 hover:bg-red-500/10",onClick:_=>{_.stopPropagation(),r(s)},title:"Retry Processing",children:o.jsx(Bs,{className:"w-2.5 h-2.5"})})]}),!s.processing_status&&!s.ai_analysis&&o.jsxs("span",{className:"text-[9px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx($t,{className:"w-2.5 h-2.5 animate-spin"})," Pending"]}),!s.processing_status&&s.ai_analysis&&o.jsxs("span",{className:"text-[9px] text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx($i,{className:"w-2.5 h-2.5"})," Analyzed"]})]}),o.jsxs("div",{className:"flex items-center justify-end gap-2 text-[10px] text-muted-foreground/80 leading-tight",children:[o.jsxs("span",{title:s.date?new Date(s.date).toLocaleString():"",className:"whitespace-nowrap",children:[o.jsx("span",{className:"opacity-70 text-[9px]",children:"REC:"})," ",s.date?new Date(s.date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"-"]}),o.jsx("span",{className:"opacity-30",children:"•"}),o.jsxs("span",{title:new Date(s.created_at).toLocaleString(),className:"whitespace-nowrap",children:[o.jsx("span",{className:"opacity-70 text-[9px]",children:"PROC:"})," ",new Date(s.created_at).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})]})]})]})]}),o.jsx("p",{className:"text-muted-foreground text-sm mb-4 line-clamp-2 leading-relaxed",children:s.body_snippet}),o.jsxs("div",{className:"bg-secondary/30 p-3 rounded-lg border border-border/50 flex justify-between items-center",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[o.jsx($d,{className:"w-3.5 h-3.5 text-emerald-500"}),"Suggested:",s.suggested_actions&&s.suggested_actions.length>0?o.jsx("div",{className:"flex gap-1 flex-wrap",children:s.suggested_actions.map(_=>o.jsx("span",{className:"text-foreground border border-border/50 px-1.5 py-0.5 rounded capitalize bg-background/50",children:_},_))}):o.jsx("span",{className:"text-foreground",children:s.suggested_action||"none"}),s.actions_taken&&s.actions_taken.length>0?o.jsxs("span",{className:"text-muted-foreground ml-2 truncate max-w-[100px]",title:s.actions_taken.join(", "),children:["(Done: ",s.actions_taken.join(", "),")"]}):s.action_taken?o.jsxs("span",{className:"text-muted-foreground ml-2",children:["(Done: ",s.action_taken,")"]}):null]}),o.jsx("div",{className:"flex gap-1 items-center",onClick:_=>_.stopPropagation(),children:m?o.jsxs("div",{className:"flex items-center gap-1 animate-in fade-in duration-200",children:[o.jsx("span",{className:"text-xs text-destructive mr-1",children:"Delete?"}),o.jsx(Z,{variant:"destructive",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>a(s,"delete"),disabled:g,children:h==="delete"?o.jsx($t,{className:"w-3 h-3 animate-spin"}):"Yes"}),o.jsx(Z,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:y,disabled:g,children:"No"})]}):o.jsxs(o.Fragment,{children:[o.jsx("a",{href:w(),target:"_blank",rel:"noreferrer",className:"inline-flex items-center justify-center h-7 w-7 rounded-md text-muted-foreground hover:text-primary hover:bg-secondary/50 transition-colors",title:`Open in ${s.email_accounts?.provider==="gmail"?"Gmail":"Outlook"}`,children:o.jsx(Ii,{className:"w-3.5 h-3.5"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-primary",onClick:()=>l(s),title:"View AI Trace (Prompt/Response)",children:o.jsx(nw,{className:"w-3.5 h-3.5"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-destructive",onClick:()=>a(s,"delete"),disabled:g,title:"Delete",children:h==="delete"?o.jsx($t,{className:"w-3.5 h-3.5 animate-spin"}):o.jsx(Uo,{className:"w-3.5 h-3.5"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-blue-500",onClick:()=>a(s,"archive"),disabled:g,title:"Archive",children:h==="archive"?o.jsx($t,{className:"w-3.5 h-3.5 animate-spin"}):o.jsx(wx,{className:"w-3.5 h-3.5"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-primary",onClick:()=>a(s,"flag"),disabled:g,title:"Flag",children:h==="flag"?o.jsx($t,{className:"w-3.5 h-3.5 animate-spin"}):o.jsx(iw,{className:"w-3.5 h-3.5"})})]})})]})]})})}function d2(){const{state:s,actions:a}=Br(),[r,l]=x.useState(!1),[c,d]=x.useState(!1),[h,m]=x.useState(null),[y,p]=x.useState(!1),[g,w]=x.useState(!1),[_,S]=x.useState({}),[E,j]=x.useState(!1),[R,D]=x.useState("credentials"),[q,B]=x.useState(""),[G,W]=x.useState(""),[J,P]=x.useState(""),[Q,ce]=x.useState(""),[Je,ve]=x.useState(!1),[pe,Ze]=x.useState(!1),[st,qe]=x.useState(!1),[C,Y]=x.useState("credentials"),[K,_e]=x.useState(""),[je,A]=x.useState(""),[V,X]=x.useState(!1),[F,de]=x.useState(!1),[ge,ue]=x.useState(""),[Ge,Ue]=x.useState("category"),[Ct,pt]=x.useState("newsletter"),[xt,ns]=x.useState(["archive"]),[la,rs]=x.useState(""),[xn,wn]=x.useState(""),[qr,is]=x.useState(""),[_n,ls]=x.useState(""),[sl,qs]=x.useState([]),[gt,nl]=x.useState(!1),[$r,Hr]=x.useState(!1),[Da,Sn]=x.useState(null),[ya,jn]=x.useState(null);x.useEffect(()=>{a.fetchAccounts(),a.fetchRules(),a.fetchSettings()},[]),x.useEffect(()=>{s.settings&&S(s.settings)},[s.settings]);const Zo=async()=>{const O=s.rules.find(ee=>ee.name==="Auto-Trash Spam");if(!O){te.error("System rule not found. Please sync your database.");return}Sn("auto_trash_spam"),await a.toggleRule(O.id),Sn(null)},$s=async()=>{const O=s.rules.find(ee=>ee.name==="Smart Drafts");if(!O){te.error("System rule not found. Please sync your database.");return}Sn("smart_drafts"),await a.toggleRule(O.id),Sn(null)},wt=O=>{jn(O),ue(O.name);const ee=O.condition,yt=Object.keys(ee).filter(Is=>Is!=="older_than_days")[0]||"category";Ue(yt),pt(ee[yt]||""),rs(ee.older_than_days?.toString()||"");const Vs=O.actions&&O.actions.length>0?O.actions:O.action?[O.action]:["archive"];ns(Vs),wn(O.instructions||""),is(O.description||""),ls(O.intent||""),qs(O.attachments||[]),de(!0)},va=x.useRef(null),Ot=()=>{D("credentials"),B(""),W(""),P(""),ce(""),j(!0)},Fo=O=>{B(O);try{const ee=JSON.parse(O),Ce=ee.installed||ee.web||ee;Ce.client_id&&W(Ce.client_id),Ce.client_secret&&P(Ce.client_secret),ee.installed?te.success("Detected Desktop app credentials"):ee.web&&te.info("Detected Web app - make sure redirect URI is configured in Google Cloud Console")}catch{}},Wo=async()=>{if(!G||!J){te.error("Please provide both Client ID and Client Secret");return}ve(!0);try{if(await a.updateSettings({..._,google_client_id:G,google_client_secret:J})){S(Ce=>({...Ce,google_client_id:G,google_client_secret:J}));const ee=await ze.getGmailAuthUrl();if(ee.data?.url)window.open(ee.data.url,"_blank"),D("code"),te.success("Please authorize in the opened tab, then paste the code here");else{const Ce=typeof ee.error=="string"?ee.error:ee.error?.message;te.error(Ce||"Failed to get OAuth URL")}}else te.error("Failed to save credentials")}catch{te.error("Failed to save credentials")}finally{ve(!1)}},ec=async()=>{if(!Q.trim()){te.error("Please paste the authorization code");return}Ze(!0);try{const O=await ze.connectGmail(Q.trim());if(O.data?.success)te.success("Gmail account connected successfully!"),j(!1),a.fetchAccounts();else{const ee=typeof O.error=="string"?O.error:O.error?.message;te.error(ee||"Failed to connect Gmail")}}catch{te.error("Failed to connect Gmail")}finally{Ze(!1)}},Nn=()=>{Y("credentials"),_e(""),A(""),qe(!0)},En=async()=>{if(!K){te.error("Please provide the Client ID");return}X(!0);try{if(await a.updateSettings({..._,microsoft_client_id:K,microsoft_tenant_id:je||"common"})){S(Ce=>({...Ce,microsoft_client_id:K,microsoft_tenant_id:je||"common"}));const ee=await ze.startMicrosoftDeviceFlow();if(ee.data)m(ee.data),Y("device-code"),Tn(ee.data.deviceCode,ee.data.interval);else{const Ce=typeof ee.error=="string"?ee.error:ee.error?.message;te.error(Ce||"Failed to start device flow")}}else te.error("Failed to save credentials")}catch{te.error("Failed to save credentials")}finally{X(!1)}},Tn=async(O,ee)=>{const Ce=setInterval(async()=>{try{const yt=await ze.pollMicrosoftDeviceCode(O);yt.data?.status==="completed"?(clearInterval(Ce),m(null),d(!1),qe(!1),te.success("Outlook account connected"),a.fetchAccounts()):yt.error&&typeof yt.error=="object"&&yt.error.code}catch{}},ee*1e3);setTimeout(()=>{clearInterval(Ce),c&&(m(null),d(!1),qe(!1),te.error("Connection timed out. Please try again."))},900*1e3)},Ma=async()=>{if(!ge){te.error("Please name your rule");return}if(xt.length===0){te.error("Please select at least one action");return}Hr(!0);try{const O={[Ge]:Ct};la&&(O.older_than_days=parseInt(la,10));const ee=xt.includes("draft"),Ce={name:ge,description:qr||void 0,intent:_n||void 0,condition:O,actions:xt,instructions:ee?xn:void 0,attachments:ee?sl:[],is_enabled:!0};let yt=!1;ya?yt=await a.updateRule(ya.id,Ce):yt=await a.createRule(Ce),yt?(te.success(ya?"Rule updated":"Rule created"),de(!1),jn(null),ue(""),ns(["archive"]),rs(""),wn(""),is(""),ls(""),qs([]),a.fetchRules()):te.error(`Failed to ${ya?"update":"create"} rule`)}catch{te.error("An error occurred while saving the rule")}finally{Hr(!1)}},An=async O=>{if(!confirm("Are you sure you want to disconnect this account?"))return;await a.disconnectAccount(O)&&te.success("Account disconnected")},os=async()=>{p(!0);const O=await a.updateSettings(_);p(!1),O&&te.success("Settings saved")},tc=async()=>{w(!0);try{const O=await ze.testLlm({llm_model:_.llm_model||null,llm_base_url:_.llm_base_url||null,llm_api_key:_.llm_api_key||null});O.data?.success?te.success(O.data.message):te.error(O.data?.message||"Connection test failed")}catch{te.error("Failed to test connection")}finally{w(!1)}},rl=async O=>{await a.toggleRule(O)},Vr=async O=>{const ee=O.target.files;if(!ee||ee.length===0)return;nl(!0);const Ce=ee[0],yt=Ce.name.split(".").pop(),Vs=`${Math.random().toString(36).substring(2)}.${yt}`,Is=`${s.user.id}/${Vs}`;try{const{error:Gs}=await ct.storage.from("rule-attachments").upload(Is,Ce);if(Gs)throw Gs;const ba={name:Ce.name,path:Is,type:Ce.type,size:Ce.size};qs(ut=>[...ut,ba]),te.success("File uploaded")}catch(Gs){console.error("Upload error:",Gs),te.error("Failed to upload file")}finally{nl(!1),O.target.value=""}},Hs=O=>{qs(ee=>ee.filter(Ce=>Ce.path!==O))},ac=O=>O==="gmail"?o.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center text-red-600 dark:text-red-400 font-bold",children:"G"}):o.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold",children:"O"});return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[o.jsx(gn,{open:E,onOpenChange:j,children:o.jsxs(yn,{className:"sm:max-w-lg",children:[o.jsxs(ka,{children:[o.jsxs(Oa,{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-8 h-8 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center text-red-600 dark:text-red-400 font-bold text-sm",children:"G"}),"Connect Gmail Account"]}),o.jsx(Ra,{children:R==="credentials"?"Enter your Google OAuth credentials to connect your Gmail account.":"Paste the authorization code from Google to complete the connection."})]}),R==="credentials"?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(Qw,{className:"w-4 h-4"}),"Paste credentials.json"]}),o.jsx("textarea",{className:"w-full h-24 p-3 text-xs font-mono border rounded-lg bg-secondary/30 resize-none focus:outline-none focus:ring-2 focus:ring-primary",placeholder:'{"installed":{"client_id":"...","client_secret":"..."}}',value:q,onChange:O=>Fo(O.target.value)}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Download from Google Cloud Console → APIs & Services → Credentials"})]}),o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("span",{className:"w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:o.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or enter manually"})})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),o.jsx(Se,{placeholder:"xxx.apps.googleusercontent.com",value:G,onChange:O=>W(O.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client Secret"}),o.jsx(Se,{type:"password",placeholder:"GOCSPX-...",value:J,onChange:O=>P(O.target.value)})]})]})]}),o.jsxs(Er,{children:[o.jsx(Z,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),o.jsxs(Z,{onClick:Wo,disabled:Je||!G||!J,children:[Je?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Save & Connect"]})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsx("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:o.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:["1. A new tab opened with Google Sign-In",o.jsx("br",{}),"2. Sign in and authorize the app",o.jsx("br",{}),"3. Copy the authorization code shown",o.jsx("br",{}),"4. Paste it below"]})}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Authorization Code"}),o.jsx(Se,{placeholder:"4/0AQlEd8x...",value:Q,onChange:O=>ce(O.target.value),className:"font-mono"})]})]}),o.jsxs(Er,{children:[o.jsx(Z,{variant:"outline",onClick:()=>D("credentials"),children:"Back"}),o.jsxs(Z,{onClick:ec,disabled:pe||!Q.trim(),children:[pe?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Connect"]})]})]})]})}),o.jsx(gn,{open:st,onOpenChange:qe,children:o.jsxs(yn,{className:"sm:max-w-lg",children:[o.jsxs(ka,{children:[o.jsxs(Oa,{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold text-sm",children:"O"}),"Connect Outlook Account"]}),o.jsx(Ra,{children:C==="credentials"?"Enter your Microsoft Azure App credentials to connect your Outlook account.":"Follow the instructions to authorize the application."})]}),C==="credentials"?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsx("div",{className:"p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg",children:o.jsx("p",{className:"text-sm text-yellow-800 dark:text-yellow-200",children:"Note: You need an Azure App Registration for this to work."})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client ID (Application ID)"}),o.jsx(Se,{placeholder:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",value:K,onChange:O=>_e(O.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Tenant ID (Optional)"}),o.jsx(Se,{placeholder:"common",value:je,onChange:O=>A(O.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:'Default is "common". Use your specific Tenant ID for organization accounts.'})]})]})]}),o.jsxs(Er,{children:[o.jsx(Z,{variant:"outline",onClick:()=>qe(!1),children:"Cancel"}),o.jsxs(Z,{onClick:En,disabled:V||!K,children:[V?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Save & Connect"]})]})]}):o.jsxs(o.Fragment,{children:[h&&o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:[o.jsx("h4",{className:"font-medium text-blue-900 dark:text-blue-100 mb-2",children:"Action Required"}),o.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200 mb-4",children:h.message}),o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx("div",{className:"flex items-center gap-2 bg-white dark:bg-black/20 p-2 rounded border border-blue-200 dark:border-blue-800",children:o.jsx("code",{className:"text-lg font-mono font-bold flex-1 text-center select-all",children:h.userCode})}),o.jsxs(Z,{variant:"default",className:"w-full bg-blue-600 hover:bg-blue-700",onClick:()=>window.open(h.verificationUri,"_blank"),children:["Open Microsoft Login",o.jsx(Ii,{className:"w-4 h-4 ml-2"})]})]})]}),o.jsx("div",{className:"flex justify-center",children:o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[o.jsx(mt,{size:"sm"}),"Waiting for authorization..."]})})]}),o.jsx(Er,{children:o.jsx(Z,{variant:"outline",onClick:()=>qe(!1),children:"Cancel"})})]})]})}),o.jsx(gn,{open:F,onOpenChange:O=>{de(O),O||jn(null)},children:o.jsxs(yn,{className:"sm:max-w-xl max-h-[90vh] flex flex-col p-0",children:[o.jsxs(ka,{className:"p-6 border-b",children:[o.jsx(Oa,{children:ya?"Edit Auto-Pilot Rule":"Create Auto-Pilot Rule"}),o.jsx(Ra,{children:"Define a condition based on AI analysis to trigger an action."})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Rule Name"}),o.jsx(Se,{placeholder:"e.g. Archive Newsletters",value:ge,onChange:O=>ue(O.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Description"}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[60px] text-sm",placeholder:"e.g. Handle all marketing newsletters and promotional content from subscription services",value:qr,onChange:O=>is(O.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Describe what this rule is for. The AI uses this to semantically match emails."})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Intent"}),o.jsx(Se,{placeholder:"e.g. Politely decline all sales pitches",value:_n,onChange:O=>ls(O.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"The goal of this rule. Used to generate appropriate draft replies."})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"If Condition Field"}),o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ge,onChange:O=>{Ue(O.target.value),O.target.value==="category"?pt("newsletter"):O.target.value==="sentiment"?pt("Positive"):O.target.value==="priority"?pt("High"):pt("")},children:[o.jsxs("optgroup",{label:"AI Analysis",children:[o.jsx("option",{value:"category",children:"Category"}),o.jsx("option",{value:"sentiment",children:"Sentiment"}),o.jsx("option",{value:"priority",children:"Priority"})]}),o.jsxs("optgroup",{label:"Metadata",children:[o.jsx("option",{value:"sender_email",children:"Specific Email (Exact)"}),o.jsx("option",{value:"sender_domain",children:"Email Domain (@...)"}),o.jsx("option",{value:"sender_contains",children:"Sender contains..."}),o.jsx("option",{value:"subject_contains",children:"Subject contains..."}),o.jsx("option",{value:"body_contains",children:"Body contains..."})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Equals Value"}),Ge==="category"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ct,onChange:O=>pt(O.target.value),children:[o.jsx("option",{value:"newsletter",children:"Newsletter"}),o.jsx("option",{value:"spam",children:"Spam"}),o.jsx("option",{value:"promotional",children:"Promotional"}),o.jsx("option",{value:"transactional",children:"Transactional"}),o.jsx("option",{value:"social",children:"Social"}),o.jsx("option",{value:"support",children:"Support"}),o.jsx("option",{value:"client",children:"Client"}),o.jsx("option",{value:"internal",children:"Internal"}),o.jsx("option",{value:"personal",children:"Personal"}),o.jsx("option",{value:"other",children:"Other"})]}):Ge==="sentiment"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ct,onChange:O=>pt(O.target.value),children:[o.jsx("option",{value:"Positive",children:"Positive"}),o.jsx("option",{value:"Neutral",children:"Neutral"}),o.jsx("option",{value:"Negative",children:"Negative"})]}):Ge==="priority"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ct,onChange:O=>pt(O.target.value),children:[o.jsx("option",{value:"High",children:"High"}),o.jsx("option",{value:"Medium",children:"Medium"}),o.jsx("option",{value:"Low",children:"Low"})]}):o.jsx(Se,{placeholder:Ge==="sender_domain"?"rta.vn":Ge==="sender_email"?"john@example.com":"Keywords...",value:Ct,onChange:O=>pt(O.target.value)})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(kr,{className:"w-4 h-4"}),"Only if email is older than... (Optional)"]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Se,{type:"number",min:"0",placeholder:"0",className:"w-24",value:la,onChange:O=>rs(O.target.value)}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Leave empty or 0 to apply rule immediately upon receipt."})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Then Perform Action(s)"}),o.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select one or more actions to execute when the rule matches"}),o.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"archive",label:"Archive Email"},{value:"delete",label:"Delete Email"},{value:"draft",label:"Draft Reply"},{value:"read",label:"Mark as Read"},{value:"star",label:"Star / Flag"}].map(O=>o.jsxs("label",{className:`flex items-center gap-2 p-2 border rounded-md cursor-pointer transition-colors ${xt.includes(O.value)?"bg-primary/10 border-primary":"bg-background hover:bg-secondary/50"}`,children:[o.jsx("input",{type:"checkbox",checked:xt.includes(O.value),onChange:ee=>{ee.target.checked?ns([...xt,O.value]):ns(xt.filter(Ce=>Ce!==O.value))},className:"rounded border-gray-300"}),o.jsx("span",{className:"text-sm",children:O.label})]},O.value))})]}),xt.includes("draft")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[o.jsx("label",{className:"text-sm font-medium",children:"Draft Instructions (Context)"}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[80px] text-sm",placeholder:"e.g. Tell them I'm busy until Friday, but interested in the proposal.",value:xn,onChange:O=>wn(O.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Specific context for the AI ghostwriter."})]}),o.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(xg,{className:"w-4 h-4"}),"Attachments (Optional)"]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[sl.map(O=>o.jsxs("div",{className:"flex items-center justify-between p-2 bg-secondary/50 rounded border text-xs",children:[o.jsx("span",{className:"truncate max-w-[200px]",children:O.name}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive",onClick:()=>Hs(O.path),children:o.jsx(tl,{className:"w-3 h-3"})})]},O.path)),o.jsxs("div",{className:"relative",children:[o.jsx("input",{type:"file",className:"absolute inset-0 opacity-0 cursor-pointer",onChange:Vr,disabled:gt}),o.jsxs(Z,{variant:"outline",size:"sm",className:"w-full border-dashed",disabled:gt,children:[gt?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Mi,{className:"w-3 h-3 mr-2"}),gt?"Uploading...":"Add Attachment"]})]})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Files will be attached to every draft generated by this rule."})]})]})]}),o.jsxs(Er,{className:"p-6 border-t bg-secondary/5",children:[o.jsx(Z,{variant:"outline",onClick:()=>de(!1),children:"Cancel"}),o.jsxs(Z,{onClick:Ma,disabled:$r,children:[$r?o.jsx(mt,{size:"sm",className:"mr-2"}):ya?o.jsx(ja,{className:"w-4 h-4 mr-2"}):o.jsx(Mi,{className:"w-4 h-4 mr-2"}),ya?"Save Changes":"Create Rule"]})]})]})}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx(Vi,{className:"w-5 h-5 text-primary"}),"Connected Accounts"]}),o.jsx(ts,{children:"Manage your email providers"})]}),o.jsxs(Ca,{className:"space-y-4",children:[s.accounts.length===0?o.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No accounts connected yet"}):s.accounts.map(O=>o.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg bg-card",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[ac(O.provider),o.jsxs("div",{children:[o.jsx("h4",{className:"font-medium capitalize",children:O.provider}),o.jsx("p",{className:"text-xs text-muted-foreground",children:O.email_address})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[O.is_active?o.jsx("span",{className:"text-xs text-emerald-600 bg-emerald-500/10 px-2 py-1 rounded-full",children:"Active"}):o.jsx("span",{className:"text-xs text-yellow-600 bg-yellow-500/10 px-2 py-1 rounded-full",children:"Inactive"}),o.jsx(Z,{variant:"outline",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>An(O.id),children:o.jsx(Uo,{className:"w-4 h-4"})})]})]},O.id)),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs(Z,{className:"w-full border-dashed",variant:"outline",onClick:Ot,disabled:r||c,children:[r?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Mi,{className:"w-4 h-4 mr-2"}),"Connect Gmail Account"]}),o.jsxs(Z,{className:"w-full border-dashed",variant:"outline",onClick:Nn,disabled:r||c,children:[c&&!h?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Mi,{className:"w-4 h-4 mr-2"}),"Connect Outlook Account"]})]}),h&&o.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg animate-in slide-in-from-top-2",children:[o.jsx("h4",{className:"font-medium text-blue-900 dark:text-blue-100 mb-2",children:"Microsoft Sign-In Required"}),o.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200 mb-4",children:h.message}),o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx("div",{className:"flex items-center gap-2 bg-white dark:bg-black/20 p-2 rounded border border-blue-200 dark:border-blue-800",children:o.jsx("code",{className:"text-lg font-mono font-bold flex-1 text-center select-all",children:h.userCode})}),o.jsxs(Z,{variant:"default",className:"w-full bg-blue-600 hover:bg-blue-700",onClick:()=>window.open(h.verificationUri,"_blank"),children:["Open Microsoft Login",o.jsx(Ii,{className:"w-4 h-4 ml-2"})]}),o.jsx("p",{className:"text-xs text-center text-muted-foreground mt-2",children:"Waiting for you to sign in..."})]})]})]})]}),o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx($d,{className:"w-5 h-5 text-emerald-500"}),"Auto-Pilot Rules"]}),o.jsx(ts,{children:"Configure AI automation behavior"})]}),o.jsxs(Ca,{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between items-center py-3 border-b border-border",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-medium text-sm",children:"Auto-Trash Spam"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically delete emails categorized as spam"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{const O=s.rules.find(ee=>ee.name==="Auto-Trash Spam");O&&wt(O)},title:"Edit Logic",children:o.jsx(vd,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs(Z,{variant:s.rules.find(O=>O.name==="Auto-Trash Spam")?.is_enabled?"default":"outline",size:"sm",onClick:Zo,disabled:Da==="auto_trash_spam",children:[Da==="auto_trash_spam"?o.jsx(mt,{size:"sm",className:"mr-1"}):o.jsx(bo,{className:"w-4 h-4 mr-1"}),s.rules.find(O=>O.name==="Auto-Trash Spam")?.is_enabled?"On":"Off"]})]})]}),o.jsxs("div",{className:"flex justify-between items-center py-3 border-b border-border",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-medium text-sm",children:"Smart Drafts"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Generate draft replies for important emails"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{const O=s.rules.find(ee=>ee.name==="Smart Drafts");O&&wt(O)},title:"Edit Logic",children:o.jsx(vd,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs(Z,{variant:s.rules.find(O=>O.name==="Smart Drafts")?.is_enabled?"default":"outline",size:"sm",onClick:$s,disabled:Da==="smart_drafts",children:[Da==="smart_drafts"?o.jsx(mt,{size:"sm",className:"mr-1"}):o.jsx(bo,{className:"w-4 h-4 mr-1"}),s.rules.find(O=>O.name==="Smart Drafts")?.is_enabled?"On":"Off"]})]})]}),o.jsxs("div",{className:"pt-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("h4",{className:"text-sm font-medium",children:"Custom Rules"}),o.jsxs(Z,{variant:"ghost",size:"sm",onClick:()=>{jn(null),ue(""),is(""),ls(""),ns(["archive"]),rs(""),wn(""),qs([]),de(!0)},children:[o.jsx(Mi,{className:"w-4 h-4 mr-1"})," Add Rule"]})]}),s.rules.length===0&&o.jsx("p",{className:"text-xs text-muted-foreground text-center py-2 border border-dashed rounded-lg",children:"No custom rules yet"}),s.rules.length>0&&s.rules.filter(O=>O.name!=="Auto-Trash Spam"&&O.name!=="Smart Drafts").map(O=>{const ee=O.actions&&O.actions.length>0?O.actions:O.action?[O.action]:[];return o.jsxs("div",{className:"p-3 bg-secondary/30 rounded-lg mb-2",children:[o.jsxs("div",{className:"flex justify-between items-center mb-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-sm font-medium",children:O.name}),o.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["→ ",ee.join(" + ")]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>wt(O),title:"Edit Rule",children:o.jsx(vd,{className:"w-3.5 h-3.5 text-muted-foreground"})}),o.jsxs(Z,{variant:O.is_enabled?"default":"outline",size:"sm",onClick:()=>rl(O.id),className:"h-7 px-2",children:[o.jsx(bo,{className:"w-3.5 h-3.5 mr-1"}),O.is_enabled?"On":"Off"]}),o.jsx(Z,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>a.deleteRule(O.id),children:o.jsx(Uo,{className:"w-3 h-3"})})]})]}),O.instructions&&o.jsxs("p",{className:"text-[10px] text-muted-foreground italic border-t border-border/50 pt-1 mt-1 truncate",children:['"',O.instructions,'"']}),O.attachments&&O.attachments.length>0&&o.jsx("div",{className:"flex gap-1 mt-1",children:O.attachments.map(Ce=>o.jsxs("div",{className:"flex items-center gap-1 text-[9px] bg-blue-500/10 text-blue-400 px-1.5 py-0.5 rounded border border-blue-500/20",children:[o.jsx(xg,{className:"w-2.5 h-2.5"}),Ce.name]},Ce.path))})]},O.id)})]})]})]})]}),o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx(Bs,{className:"w-5 h-5 text-indigo-500"}),"Model Configuration"]}),o.jsx(ts,{children:"Configure Local LLM or API settings"})]}),o.jsxs(Ca,{className:"space-y-4",children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Model Name"}),o.jsx(Se,{placeholder:"gpt-4o-mini",value:_.llm_model||"",onChange:O=>S(ee=>({...ee,llm_model:O.target.value}))})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Base URL"}),o.jsx(Se,{placeholder:"https://api.openai.com/v1",value:_.llm_base_url||"",onChange:O=>S(ee=>({...ee,llm_base_url:O.target.value}))}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Use http://localhost:11434/v1 for Ollama"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"API Key"}),o.jsx(Se,{type:"password",placeholder:"sk-...",value:_.llm_api_key||"",onChange:O=>S(ee=>({...ee,llm_api_key:O.target.value}))})]})]}),o.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(Vi,{className:"w-4 h-4"}),"Local Storage Path (.eml)"]}),o.jsx(Se,{placeholder:"e.g. ./data/emails or ~/.email-automator/emails",value:_.storage_path||"",onChange:O=>S(ee=>({...ee,storage_path:O.target.value}))}),o.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"Directory where raw emails (.eml) are saved. Default: ./data/emails (falls back to ~/.email-automator/emails if restricted)."})]}),o.jsxs("div",{className:"flex justify-between items-center py-3 border-t border-border/50",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-medium text-sm",children:"Intelligent Rename"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Use slugified-hyphenated filenames (e.g. 20240119-1430-subject-id.eml)"})]}),o.jsxs(Z,{variant:_.intelligent_rename?"default":"outline",size:"sm",onClick:()=>S(O=>({...O,intelligent_rename:!O.intelligent_rename})),children:[o.jsx(bo,{className:"w-4 h-4 mr-1"}),_.intelligent_rename?"On":"Off"]})]}),o.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(kr,{className:"w-4 h-4"}),"Background Sync Interval (minutes)"]}),o.jsx(Se,{type:"number",min:1,max:1440,value:_.sync_interval_minutes||5,onChange:O=>S(ee=>({...ee,sync_interval_minutes:parseInt(O.target.value,10)||5}))}),o.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"How often the system checks for new emails in the background."})]}),o.jsxs("div",{className:"flex justify-end mt-4 gap-2",children:[o.jsxs(Z,{variant:"outline",onClick:tc,disabled:g,children:[g?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Bs,{className:"w-4 h-4 mr-2"}),"Check Connection"]}),o.jsxs(Z,{onClick:os,disabled:y,children:[y?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Save Configuration"]})]})]})]}),o.jsx("div",{ref:va,children:o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx($d,{className:"w-5 h-5 text-orange-500"}),"Provider Credentials (Advanced)"]}),o.jsx(ts,{children:"Bring Your Own Keys (BYOK). Configure your own OAuth credentials here. Leave empty to use system defaults."})]}),o.jsxs(Ca,{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-4 border-b pb-4",children:[o.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[o.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"})," Google / Gmail"]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),o.jsx(Se,{type:"password",placeholder:"...apps.googleusercontent.com",value:_.google_client_id||"",onChange:O=>S(ee=>({...ee,google_client_id:O.target.value}))})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client Secret"}),o.jsx(Se,{type:"password",placeholder:"GOCSPX-...",value:_.google_client_secret||"",onChange:O=>S(ee=>({...ee,google_client_secret:O.target.value}))})]})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[o.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-500"})," Microsoft / Outlook"]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),o.jsx(Se,{type:"password",value:_.microsoft_client_id||"",onChange:O=>S(ee=>({...ee,microsoft_client_id:O.target.value}))})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client Secret (Optional)"}),o.jsx(Se,{type:"password",value:_.microsoft_client_secret||"",onChange:O=>S(ee=>({...ee,microsoft_client_secret:O.target.value}))})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Tenant ID"}),o.jsx(Se,{placeholder:"common",value:_.microsoft_tenant_id||"",onChange:O=>S(ee=>({...ee,microsoft_tenant_id:O.target.value}))})]})]})]}),o.jsx("div",{className:"flex justify-end mt-4",children:o.jsxs(Z,{onClick:os,disabled:y,variant:"secondary",children:[y?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Save Credentials"]})})]})]})})]})}const f2="modulepreload",h2=function(s){return"/"+s},hy={},m2=function(a,r,l){let c=Promise.resolve();if(r&&r.length>0){let p=function(g){return Promise.all(g.map(w=>Promise.resolve(w).then(_=>({status:"fulfilled",value:_}),_=>({status:"rejected",reason:_}))))};var h=p;document.getElementsByTagName("link");const m=document.querySelector("meta[property=csp-nonce]"),y=m?.nonce||m?.getAttribute("nonce");c=p(r.map(g=>{if(g=h2(g),g in hy)return;hy[g]=!0;const w=g.endsWith(".css"),_=w?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${g}"]${_}`))return;const S=document.createElement("link");if(S.rel=w?"stylesheet":f2,w||(S.as="script"),S.crossOrigin="",S.href=g,y&&S.setAttribute("nonce",y),document.head.appendChild(S),w)return new Promise((E,j)=>{S.addEventListener("load",E),S.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${g}`)))})}))}function d(m){const y=new Event("vite:preloadError",{cancelable:!0});if(y.payload=m,window.dispatchEvent(y),!y.defaultPrevented)throw m}return c.then(m=>{for(const y of m||[])y.status==="rejected"&&d(y.reason);return a().catch(d)})};function p2(){const[s,a]=x.useState("profile"),{state:r,actions:l}=Br();x.useEffect(()=>{l.fetchProfile()},[]);const c=[{id:"profile",label:"Profile",icon:by},{id:"security",label:"Security",icon:Iw},{id:"database",label:"Supabase",icon:Vi}];return o.jsxs("div",{className:"max-w-4xl mx-auto space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Account Settings"}),o.jsx("p",{className:"text-muted-foreground",children:"Manage your profile, security, and connection preferences."})]}),o.jsxs("div",{className:"flex flex-col md:flex-row gap-8",children:[o.jsxs("aside",{className:"w-full md:w-64 flex flex-col justify-between",children:[o.jsx("nav",{className:"space-y-1",children:c.map(d=>{const h=d.icon,m=s===d.id;return o.jsxs("button",{onClick:()=>a(d.id),className:`w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${m?"bg-primary text-primary-foreground":"hover:bg-secondary text-muted-foreground"}`,children:[o.jsx(h,{className:"w-4 h-4"}),d.label]},d.id)})}),o.jsxs("div",{className:"mt-8 px-4 py-4 border-t border-border/40 text-center md:text-left",children:[o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/50 uppercase tracking-widest mb-1",children:"Version"}),o.jsxs("p",{className:"text-xs font-mono text-muted-foreground/70",children:["v","2.9.0"]})]})]}),o.jsxs("div",{className:"flex-1 space-y-6",children:[s==="profile"&&o.jsx(g2,{}),s==="security"&&o.jsx(y2,{}),s==="database"&&o.jsx(v2,{})]})]})]})}function g2(){const{state:s,actions:a}=Br(),[r,l]=x.useState(""),[c,d]=x.useState(""),[h,m]=x.useState(!1),[y,p]=x.useState(!1),[g,w]=x.useState(Ea.isEnabled());x.useEffect(()=>{s.profile&&(l(s.profile.first_name||""),d(s.profile.last_name||""))},[s.profile]);const _=()=>{const j=!g;Ea.setEnabled(j),w(j),j?(Ea.playSuccess(),te.success("Sound effects enabled")):te.info("Sound effects disabled")},S=async()=>{m(!0);const j=await a.updateProfile({first_name:r,last_name:c});m(!1),j&&te.success("Profile updated")},E=async j=>{const R=j.target.files?.[0];if(!(!R||!s.user)){p(!0);try{const D=R.name.split(".").pop(),q=`${s.user.id}/avatar.${D}`,{data:B,error:G}=await ct.storage.from("avatars").upload(q,R,{upsert:!0});if(G)throw G;const{data:{publicUrl:W}}=ct.storage.from("avatars").getPublicUrl(q);await a.updateProfile({avatar_url:W}),te.success("Avatar updated")}catch(D){console.error("Avatar upload error:",D),te.error("Failed to upload avatar")}finally{p(!1)}}};return o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsx(Aa,{children:"Profile Information"}),o.jsx(ts,{children:"Update your personal details and avatar."})]}),o.jsxs(Ca,{className:"space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center sm:flex-row sm:items-start gap-6",children:[o.jsxs("div",{className:"relative group",children:[o.jsx("div",{className:"w-24 h-24 rounded-full bg-secondary overflow-hidden border-2 border-border flex items-center justify-center",children:s.profile?.avatar_url?o.jsx("img",{src:s.profile.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):o.jsx(by,{className:"w-12 h-12 text-muted-foreground"})}),o.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-full opacity-0 group-hover:opacity-100 cursor-pointer transition-opacity",children:[o.jsx(Rx,{className:"w-6 h-6 text-white"}),o.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:E,disabled:y})]}),y&&o.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 rounded-full",children:o.jsx(mt,{size:"sm"})})]}),o.jsxs("div",{className:"flex-1 space-y-4 w-full",children:[o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"first-name",children:"First Name"}),o.jsx(Se,{id:"first-name",value:r,onChange:j=>l(j.target.value),placeholder:"John"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"last-name",children:"Last Name"}),o.jsx(Se,{id:"last-name",value:c,onChange:j=>d(j.target.value),placeholder:"Doe"})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"email",children:"Email Address"}),o.jsx(Se,{id:"email",value:s.profile?.email||"",disabled:!0,className:"bg-secondary/50"}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Email cannot be changed directly."})]})]})]}),o.jsxs("div",{className:"pt-6 border-t flex items-center justify-between",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("label",{className:"text-sm font-medium",children:"Sound & Haptics"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Audio feedback when processing emails and completing tasks."})]}),o.jsxs(Z,{variant:g?"default":"outline",size:"sm",onClick:_,className:"gap-2",children:[g?o.jsx(t_,{className:"w-4 h-4"}):o.jsx(s_,{className:"w-4 h-4"}),g?"Enabled":"Disabled"]})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:S,disabled:h,children:[h?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Dw,{className:"w-4 h-4 mr-2"}),"Save Changes"]})})]})]})}function y2(){const[s,a]=x.useState(""),[r,l]=x.useState(""),[c,d]=x.useState(!1),h=async()=>{if(!s){te.error("Please enter a new password");return}if(s!==r){te.error("Passwords do not match");return}if(s.length<6){te.error("Password must be at least 6 characters");return}d(!0);try{const{api:m}=await m2(async()=>{const{api:p}=await Promise.resolve().then(()=>Ij);return{api:p}},void 0),y=await m.changePassword(s);y.success?(te.success("Password changed successfully"),a(""),l("")):te.error(y.error?.message||"Failed to change password")}catch{te.error("An error occurred")}finally{d(!1)}};return o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsx(Aa,{children:"Security"}),o.jsx(ts,{children:"Manage your password and account security."})]}),o.jsxs(Ca,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"new-password",children:"New Password"}),o.jsx(Se,{id:"new-password",type:"password",value:s,onChange:m=>a(m.target.value),placeholder:"••••••••"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"confirm-password",children:"Confirm New Password"}),o.jsx(Se,{id:"confirm-password",type:"password",value:r,onChange:m=>l(m.target.value),placeholder:"••••••••"})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:h,disabled:c,children:[c?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(hw,{className:"w-4 h-4 mr-2"}),"Update Password"]})})]})]})}function v2(){const[s,a]=x.useState(!1),r=Lr(),l=$j(),c=()=>{confirm("Are you sure you want to disconnect from this Supabase project? This will log you out and clear local configuration.")&&(qj(),window.location.reload())};return o.jsxs(o.Fragment,{children:[o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx(Vi,{className:"w-5 h-5 text-primary"}),"Supabase Connection"]}),o.jsx(ts,{children:"Manage your database configuration (BYOK - Bring Your Own Keys)."})]}),o.jsx(Ca,{className:"space-y-6",children:r?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-xl bg-emerald-500/5 border-emerald-500/20",children:[o.jsx(Hi,{className:"w-6 h-6 text-emerald-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-1",children:[o.jsx("p",{className:"font-semibold text-emerald-700 dark:text-emerald-400",children:"Connected"}),o.jsx("p",{className:"text-sm font-mono break-all opacity-80",children:r.url})]})]}),l==="env"&&o.jsxs(Wi,{className:"bg-amber-500/5 border-amber-500/20",children:[o.jsx(qd,{className:"h-4 w-4 text-amber-500"}),o.jsx(el,{className:"text-amber-700 dark:text-amber-400 text-xs",children:"Configuration is loaded from environment variables. Use the UI to override them."})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[o.jsxs(Z,{variant:"outline",onClick:()=>a(!0),className:"w-full",children:[o.jsx(qd,{className:"w-4 h-4 mr-2"}),"Change Connection"]}),l==="ui"&&o.jsxs(Z,{variant:"outline",onClick:c,className:"w-full text-destructive hover:bg-destructive/10",children:[o.jsx(Uo,{className:"w-4 h-4 mr-2"}),"Clear Config"]})]}),o.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[o.jsx(pa,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Anon Public Key"}),o.jsxs("div",{className:"p-2 bg-secondary/50 rounded-lg font-mono text-xs break-all",children:[r.anonKey.substring(0,20),"...",r.anonKey.substring(r.anonKey.length-10)]})]})]}):o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center space-y-4",children:[o.jsx(Xx,{className:"w-12 h-12 text-destructive opacity-20"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-medium",children:"No Connection Detected"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure a Supabase project to get started."})]}),o.jsxs(Z,{onClick:()=>a(!0),children:[o.jsx(Vi,{className:"w-4 h-4 mr-2"}),"Setup Supabase"]})]})})]}),o.jsx(Vv,{open:s,onComplete:()=>a(!1),canClose:!0})]})}function b2({length:s=6,value:a,onChange:r,onComplete:l,disabled:c=!1,error:d=!1}){const h=x.useRef([]),[m,y]=x.useState(null),p=(_,S)=>{const E=S.replace(/[^0-9]/g,"");if(E.length===0){const D=a.split("");D[_]=" ",a.split("");let q=a.split("");_<q.length&&q.splice(_,1);const B=q.join("");r(B),_>0&&h.current[_-1]?.focus();return}a.split("");const j=[...a];j[_]=E[0],r(j.join("")),_<s-1&&h.current[_+1]?.focus();const R=j.join("");R.length===s&&l&&l(R)},g=(_,S)=>{S.key==="Backspace"&&!a[_]&&_>0||S.key==="ArrowLeft"&&_>0?h.current[_-1]?.focus():S.key==="ArrowRight"&&_<s-1&&h.current[_+1]?.focus()},w=_=>{_.preventDefault();const E=_.clipboardData.getData("text/plain").replace(/[^0-9]/g,"").slice(0,s);r(E);const j=Math.min(E.length,s-1);h.current[j]?.focus(),E.length===s&&l&&l(E)};return o.jsx("div",{className:"flex gap-2 justify-center",children:Array.from({length:s}).map((_,S)=>o.jsx(Se,{ref:E=>{h.current[S]=E},type:"text",inputMode:"numeric",maxLength:1,value:a[S]||"",onChange:E=>p(S,E.target.value),onKeyDown:E=>g(S,E),onPaste:w,onFocus:()=>y(S),onBlur:()=>y(null),disabled:c,className:Oe("w-10 h-10 sm:w-12 sm:h-12 text-center text-lg font-semibold px-0",d&&"border-destructive focus-visible:ring-destructive",m===S&&"ring-2 ring-ring"),"aria-label":`Digit ${S+1}`},S))})}function x2({onSuccess:s,onConfigure:a}){const[r,l]=x.useState(""),[c,d]=x.useState(""),[h,m]=x.useState(""),[y,p]=x.useState(""),[g,w]=x.useState(!1),[_,S]=x.useState(!0),[E,j]=x.useState(!1),[R,D]=x.useState(""),[q,B]=x.useState("password"),[G,W]=x.useState("email"),[J,P]=x.useState("");x.useEffect(()=>{Q()},[]);const Q=async()=>{try{const{data:ve,error:pe}=await ct.from("init_state").select("is_initialized");if(pe){console.warn("[Login] Init check failed, defaulting to initialized (Login):",pe),j(!0);return}const Ze=ve?.[0]?.is_initialized>0;j(Ze)}catch(ve){if(console.warn("[Login] Init check exception, defaulting to initialized:",ve),ve.message?.includes("Invalid API key")||ve.status===401){console.warn("[Login] API Key invalid for REST check (likely Publishable Key). defaulting to Setup Mode (isInitialized=false)."),j(!1);return}j(!0)}finally{S(!1)}},ce=async ve=>{ve.preventDefault(),w(!0),D("");try{if(E){if(q==="password"){const{error:pe}=await ct.auth.signInWithPassword({email:r,password:c});if(pe)throw pe;te.success("Logged in successfully"),s?.()}else if(G==="email"){const{error:pe}=await ct.auth.signInWithOtp({email:r,options:{shouldCreateUser:!1}});if(pe)throw pe;W("verify"),te.success("Validation code sent to your email")}}else{const{data:pe,error:Ze}=await ct.functions.invoke("setup",{body:{email:r,password:c,first_name:h,last_name:y}});if(Ze||!pe){if(Ze?.message?.includes("First user already exists")){te.info("System already initialized. Please log in."),j(!0);return}throw new Error(Ze?.message||"Failed to create admin account")}te.success("Admin account created! Signing you in...");const{error:st}=await ct.auth.signInWithPassword({email:r,password:c});if(st)throw st;j(!0),s?.()}}catch(pe){D(pe?.message||"Authentication failed"),console.error("[Login] Error:",pe)}finally{w(!1)}},Je=async()=>{w(!0),D("");try{const{data:ve,error:pe}=await ct.auth.verifyOtp({email:r,token:J,type:"magiclink"});if(pe)throw pe;if(!ve.session)throw new Error("Failed to create session");te.success("Logged in successfully"),s?.()}catch(ve){D(ve?.message||"Invalid code")}finally{w(!1)}};return _?o.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:o.jsx($t,{className:"w-8 h-8 animate-spin text-primary"})}):o.jsxs("div",{className:"min-h-screen bg-background flex items-center justify-center p-8 relative",children:[o.jsx("div",{className:"absolute top-4 right-4",children:o.jsx(By,{})}),o.jsxs(At,{className:"w-full max-w-md shadow-2xl",children:[o.jsxs(Ta,{className:"text-center",children:[o.jsx("div",{className:"mx-auto bg-primary/10 p-4 rounded-full w-fit mb-4",children:o.jsx(vf,{className:"w-12 h-12"})}),o.jsx(Aa,{className:"text-2xl",children:E?"Welcome Back":"Welcome to Email Automator"}),o.jsx(ts,{children:E?q==="password"?"Sign in to access your email automation":G==="email"?"Receive a login code via email":`Enter code sent to ${r}`:"Create the first admin account to get started"})]}),o.jsxs("form",{onSubmit:ce,children:[o.jsxs(Ca,{className:"space-y-4",children:[!E&&o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"First Name"}),o.jsx(Se,{value:h,onChange:ve=>m(ve.target.value),required:!E,placeholder:"John"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Last Name"}),o.jsx(Se,{value:y,onChange:ve=>p(ve.target.value),required:!E,placeholder:"Doe"})]})]}),q==="password"||G==="email"?o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Email"}),o.jsx(Se,{type:"email",placeholder:"admin@example.com",value:r,onChange:ve=>l(ve.target.value),required:!0,autoComplete:"email",disabled:G==="verify"})]}):null,q==="password"&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Password"}),o.jsx(Se,{type:"password",placeholder:"••••••••",value:c,onChange:ve=>d(ve.target.value),required:!0,minLength:6,autoComplete:E?"current-password":"new-password"})]}),q==="otp"&&G==="verify"&&o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(b2,{value:J,onChange:P,length:6,onComplete:()=>{}})}),o.jsx(Z,{type:"button",variant:"link",className:"w-full text-xs text-muted-foreground",onClick:()=>W("email"),children:"Change email address"})]}),o.jsxs("div",{className:"bg-destructive/10 text-destructive text-sm p-3 rounded-md flex flex-col gap-2",children:[o.jsx("p",{children:R}),R.includes("configuration")||R.includes("Invalid API key")||R.includes("API key")&&a&&o.jsx(Z,{type:"button",variant:"outline",className:"w-full border-destructive/50 hover:bg-destructive/20 text-destructive",onClick:a,children:"Update Connection Settings"})]})]}),o.jsxs(uv,{className:"flex flex-col gap-3",children:[q==="otp"&&G==="verify"?o.jsx(Z,{type:"button",onClick:Je,disabled:g||J.length!==6,className:"w-full",children:g?o.jsxs(o.Fragment,{children:[o.jsx($t,{className:"w-4 h-4 mr-2 animate-spin"}),"Verifying..."]}):"Verify Code"}):o.jsx(Z,{type:"submit",disabled:g||!r||q==="password"&&!c,className:"w-full",children:g?o.jsxs(o.Fragment,{children:[o.jsx($t,{className:"w-4 h-4 mr-2 animate-spin"}),E?q==="otp"?"Send Code":"Signing in...":"Creating Account..."]}):o.jsxs(o.Fragment,{children:[E?q==="otp"?o.jsx(Bd,{className:"w-4 h-4 mr-2"}):o.jsx(vw,{className:"w-4 h-4 mr-2"}):o.jsx(Fw,{className:"w-4 h-4 mr-2"}),E?q==="otp"?"Send Login Code":"Sign In":"Create Admin Account"]})}),E&&o.jsx("div",{className:"flex flex-col gap-2 w-full",children:q==="password"?o.jsxs(Z,{type:"button",variant:"ghost",className:"w-full text-sm font-normal text-muted-foreground hover:text-primary",onClick:()=>{B("otp"),W("email"),D("")},children:[o.jsx(dw,{className:"w-4 h-4 mr-2"}),"Sign in with Code"]}):o.jsxs(Z,{type:"button",variant:"ghost",className:"w-full text-sm font-normal text-muted-foreground hover:text-primary",onClick:()=>{B("password"),D("")},children:[o.jsx(Nx,{className:"w-4 h-4 mr-2"}),"Sign in with Password"]})}),E&&o.jsx("p",{className:"text-xs text-center text-muted-foreground mt-2",children:"New users must be invited by an admin."})]})]})]})]})}const Iv=void 0,w2=void 0;function _2(s,a){const r=s.split(".").map(Number),l=a.split(".").map(Number);for(let c=0;c<Math.max(r.length,l.length);c++){const d=r[c]||0,h=l[c]||0;if(d>h)return 1;if(d<h)return-1}return 0}async function S2(s){try{const{data:a,error:r}=await s.rpc("get_latest_migration_timestamp");return r?(console.warn("Could not get latest migration timestamp:",r.message),{version:null,latestMigrationTimestamp:null}):{version:Iv,latestMigrationTimestamp:a||null}}catch(a){return console.error("Error checking database migration info:",a),{version:null,latestMigrationTimestamp:null}}}async function j2(s){const a=Iv,r=w2,l=await S2(s);if(console.log("[Migration Check]",{appVersion:a,appMigrationTimestamp:r,dbVersion:l.version,dbMigrationTimestamp:l.latestMigrationTimestamp}),l.latestMigrationTimestamp&&l.latestMigrationTimestamp.trim()!==""){const c=r,d=l.latestMigrationTimestamp;return c>d?{needsMigration:!0,appVersion:a,dbVersion:l.version,message:`New migrations available. Database is at ${d}, app has ${c}.`}:c<d?(console.warn("[Migration Check] DB is ahead of app - possible downgrade"),{needsMigration:!1,appVersion:a,dbVersion:l.version,message:`Database (${d}) is ahead of app (${c}).`}):(console.log("[Migration Check] Timestamps match - database is up-to-date"),{needsMigration:!1,appVersion:a,dbVersion:l.version,message:"Database schema is up-to-date."})}if(l.version){console.log("[Migration Check] Legacy DB detected (no timestamp). Falling back to SemVer.");const c=_2(a,l.version);return c>0?{needsMigration:!0,appVersion:a,dbVersion:l.version,message:`Database schema (v${l.version}) is outdated. Migration to v${a} required.`}:c===0?(console.warn("[Migration Check] Legacy DB with matching version - forcing migration to add timestamp tracking"),{needsMigration:!0,appVersion:a,dbVersion:l.version,message:`Database lacks timestamp tracking. Please run migration to upgrade to modern schema (v${a}).`}):{needsMigration:!1,appVersion:a,dbVersion:l.version,message:`Database version (v${l.version}) is ahead of app (v${a}).`}}return console.log("[Migration Check] No DB info found - assuming migration needed"),{needsMigration:!0,appVersion:a,dbVersion:null,message:`Database schema unknown. Migration required to v${a}.`}}const Gv="email_automator_migration_reminder_dismissed_at";function N2(s=24){try{const a=localStorage.getItem(Gv);if(!a)return!1;const r=new Date(a).getTime();return(Date.now()-r)/(1e3*60*60)<s}catch(a){return console.error("Error checking migration reminder:",a),!1}}function E2(){try{localStorage.setItem(Gv,new Date().toISOString())}catch(s){console.error("Error dismissing migration reminder:",s)}}function T2({status:s,onDismiss:a,onLearnMore:r}){const[l,c]=x.useState(!0);if(!l)return null;const d=()=>{E2(),c(!1),a?.()},h=()=>{r?r():(navigator.clipboard.writeText("npx email-automator migrate"),te.success("Command copied to clipboard"))};return o.jsx("div",{className:"fixed right-4 top-16 z-50 max-w-sm animate-in slide-in-from-top-5",children:o.jsx("div",{className:"rounded-lg border border-yellow-500 bg-yellow-50 p-4 shadow-lg dark:bg-yellow-950/90 dark:border-yellow-600",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Rr,{className:"h-5 w-5 flex-shrink-0 text-yellow-600 dark:text-yellow-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("p",{className:"text-sm font-medium text-yellow-900 dark:text-yellow-100",children:"Database Update Required"}),o.jsxs(Z,{size:"icon",variant:"ghost",className:"h-5 w-5 -mr-1 -mt-1 text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30",onClick:d,children:[o.jsx(tl,{className:"h-3 w-3"}),o.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),o.jsxs("p",{className:"text-xs text-yellow-800 dark:text-yellow-200",children:["Your app version (",s.appVersion,") requires a database schema update."]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",variant:"default",className:"h-7 text-xs bg-yellow-600 hover:bg-yellow-700 dark:bg-yellow-500 dark:hover:bg-yellow-600",onClick:h,children:"Update Now"}),o.jsx(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30",onClick:d,children:"Remind Later"})]})]})]})})})}function Ro({code:s,label:a}){const[r,l]=x.useState(!1),c=typeof navigator<"u"&&!!navigator.clipboard?.writeText,d=async()=>{if(!c){te.error("Clipboard not supported");return}try{await navigator.clipboard.writeText(s),l(!0),window.setTimeout(()=>l(!1),2e3),te.success("Copied to clipboard")}catch(h){console.error("Failed to copy:",h),te.error("Failed to copy to clipboard")}};return o.jsxs("div",{className:"relative",children:[a&&o.jsx("div",{className:"mb-2 text-sm font-medium text-muted-foreground",children:a}),o.jsxs("div",{className:"group relative",children:[o.jsx("pre",{className:"overflow-hidden rounded-md bg-muted p-3 pr-12 text-sm",children:o.jsx("code",{className:"block whitespace-pre-wrap break-all",children:s})}),o.jsxs(Z,{type:"button",size:"icon",variant:"ghost",className:"absolute right-2 top-2 h-8 w-8",onClick:d,disabled:!c,children:[r?o.jsx(ja,{className:"h-4 w-4 text-green-600"}):o.jsx(Wx,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:r?"Copied":"Copy code"})]})]})]})}function A2({open:s,onOpenChange:a,status:r}){const l=Lr(),[c,d]=x.useState(!0),[h,m]=x.useState(!1),[y,p]=x.useState([]),[g,w]=x.useState(""),[_,S]=x.useState(""),E=x.useRef(null),j=x.useMemo(()=>{const D=l?.url;if(!D)return"";try{return new URL(D).hostname.split(".")[0]||""}catch{return""}},[l?.url]);x.useEffect(()=>{E.current&&E.current.scrollIntoView({behavior:"smooth"})},[y]);const R=async()=>{if(!j){te.error("Missing Project ID");return}m(!0),p(["Initializing migration..."]);try{const D=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:j,dbPassword:g,accessToken:_})});if(!D.ok)throw new Error(`Server returned ${D.status}: ${D.statusText}`);const q=D.body?.getReader();if(!q)throw new Error("No response stream received.");const B=new TextDecoder;for(;;){const{done:G,value:W}=await q.read();if(G)break;const P=B.decode(W).split(`
95
+ For more information, see https://radix-ui.com/primitives/docs/components/${a.docsSlug}`;return x.useEffect(()=>{s&&(document.getElementById(s)||console.error(r))},[r,s]),null},HE="DialogDescriptionWarning",VE=({contentRef:s,descriptionId:a})=>{const l=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${$v(HE).contentName}}.`;return x.useEffect(()=>{const c=s.current?.getAttribute("aria-describedby");a&&c&&(document.getElementById(a)||console.warn(l))},[l,s,a]),null},IE=Tv,GE=kv,PE=Ov,KE=Rv,YE=Mv,JE=Uv,XE=Bv;function gn({...s}){return o.jsx(IE,{"data-slot":"dialog",...s})}function QE({...s}){return o.jsx(GE,{"data-slot":"dialog-portal",...s})}function ZE({className:s,...a}){return o.jsx(PE,{"data-slot":"dialog-overlay",className:Oe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",s),...a})}function yn({className:s,children:a,...r}){return o.jsxs(QE,{"data-slot":"dialog-portal",children:[o.jsx(ZE,{}),o.jsxs(KE,{"data-slot":"dialog-content",className:Oe("bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",s),...r,children:[a,o.jsxs(XE,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[o.jsx(tl,{}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function ka({className:s,...a}){return o.jsx("div",{"data-slot":"dialog-header",className:Oe("flex flex-col gap-2 text-center sm:text-left",s),...a})}function Er({className:s,...a}){return o.jsx("div",{"data-slot":"dialog-footer",className:Oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",s),...a})}function Oa({className:s,...a}){return o.jsx(YE,{"data-slot":"dialog-title",className:Oe("text-lg leading-none font-semibold",s),...a})}function Ra({className:s,...a}){return o.jsx(JE,{"data-slot":"dialog-description",className:Oe("text-muted-foreground text-sm",s),...a})}const Se=x.forwardRef(({className:s,type:a,...r},l)=>o.jsx("input",{type:a,className:Oe("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",s),ref:l,...r}));Se.displayName="Input";var FE=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],WE=FE.reduce((s,a)=>{const r=_y(`Primitive.${a}`),l=x.forwardRef((c,d)=>{const{asChild:h,...m}=c,y=h?r:a;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(y,{...m,ref:d})});return l.displayName=`Primitive.${a}`,{...s,[a]:l}},{}),e2="Label",Hv=x.forwardRef((s,a)=>o.jsx(WE.label,{...s,ref:a,onMouseDown:r=>{r.target.closest("button, input, select, textarea")||(s.onMouseDown?.(r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));Hv.displayName=e2;var t2=Hv;function pa({className:s,...a}){return o.jsx(t2,{"data-slot":"label",className:Oe("flex items-center gap-2 text-sm leading-none font-medium select-none text-muted-foreground group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",s),...a})}const a2=Ny("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function Wi({className:s,variant:a,...r}){return o.jsx("div",{"data-slot":"alert",role:"alert",className:Oe(a2({variant:a}),s),...r})}function el({className:s,...a}){return o.jsx("div",{"data-slot":"alert-description",className:Oe("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",s),...a})}function vf({className:s}){return o.jsxs("svg",{width:"512",height:"512",viewBox:"0 0 512 512",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:Oe("w-9 h-9",s),children:[o.jsx("path",{d:"M112 112H400C426.51 112 448 133.49 448 160V352C448 378.51 426.51 400 400 400H112C85.4903 400 64 378.51 64 352V160C64 133.49 85.4903 112 112 112Z",className:"stroke-foreground",strokeWidth:"32",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M64 160 L200 270",className:"stroke-foreground",strokeWidth:"32",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M448 160 L312 270",className:"stroke-foreground",strokeWidth:"32",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M256 128 C256 128 276 170 306 178 C276 186 256 228 256 228 C256 228 236 186 206 178 C236 170 256 128 256 128 Z",fill:"#9333ea",children:o.jsx("animateTransform",{attributeName:"transform",type:"translate",values:"0 0; 0 -10; 0 0",dur:"3s",repeatCount:"indefinite"})})]})}function fy(s){const a=s.trim();return a?a.startsWith("http://")||a.startsWith("https://")?a:`https://${a}.supabase.co`:""}function s2(s){const a=s.trim();if(!a)return{valid:!1};if(a.startsWith("http://")||a.startsWith("https://"))try{return new URL(a).hostname.endsWith(".supabase.co")?{valid:!0,message:"Valid Supabase URL"}:{valid:!1,message:"URL must be a supabase.co domain"}}catch{return{valid:!1,message:"Invalid URL format"}}return/^[a-z0-9]+$/.test(a)?{valid:!0,message:"Project ID detected"}:{valid:!1,message:"Enter a URL or Project ID"}}function n2(s){const a=s.trim();return a?a.startsWith("sb_publishable_")?a.length>25?{valid:!0,message:"Valid Publishable Key"}:{valid:!1,message:"Incomplete Publishable Key"}:a.startsWith("eyJ")?a.length>50?{valid:!0,message:"Valid Anon Key"}:{valid:!1,message:"Incomplete Anon Key"}:{valid:!1,message:"Invalid API Key format"}:{valid:!1}}function Vv({onComplete:s,open:a=!0,canClose:r=!1}){const[l,c]=x.useState("welcome"),[d,h]=x.useState(""),[m,y]=x.useState(""),[p,g]=x.useState(null),[w,_]=x.useState(!1),[S,E]=x.useState(!1),j=async()=>{g(null),c("validating");const G=fy(d),W=m.trim(),J=await av(G,W);J.valid?(Bj({url:G,anonKey:W}),c("success"),setTimeout(()=>{window.location.reload()},1e3)):(g(J.error||"Connection failed. Please check your credentials."),c("credentials"))},R=d?s2(d):{valid:!1},D=m?n2(m):{valid:!1},q=d?fy(d):"",B=d&&!d.startsWith("http")&&R.valid;return o.jsx(gn,{open:a,onOpenChange:G=>{!G&&r&&s()},children:o.jsxs(yn,{className:"sm:max-w-md",onPointerDownOutside:G=>{r||G.preventDefault()},onEscapeKeyDown:G=>{r||G.preventDefault()},children:[l==="welcome"&&o.jsxs(o.Fragment,{children:[o.jsxs(ka,{children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx(vf,{className:"w-9 h-9"}),o.jsx(Oa,{children:"Welcome to Email Automator"})]}),o.jsx(Ra,{children:"This application requires a Supabase database to store your emails and automation rules."})]}),o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsx(Wi,{children:o.jsxs(el,{children:[o.jsx("strong",{children:"No Supabase Setup Detected"}),o.jsx("br",{}),"You can create a free project at"," ",o.jsxs("a",{href:"https://supabase.com",target:"_blank",rel:"noopener noreferrer",className:"underline text-primary inline-flex items-center gap-1",children:["supabase.com",o.jsx(Ii,{className:"h-3 w-3"})]})]})}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("h4",{className:"font-medium text-sm",children:"You will need:"}),o.jsxs("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:[o.jsx("li",{children:"Project URL"}),o.jsx("li",{children:"Anon Public Key"})]})]}),o.jsxs("div",{className:"flex gap-2",children:[r&&o.jsx(Z,{variant:"outline",onClick:s,className:"flex-1",children:"Close"}),o.jsx(Z,{onClick:()=>c("credentials"),className:"flex-1",children:"Continue Setup"})]})]})]}),l==="credentials"&&o.jsxs(o.Fragment,{children:[o.jsxs(ka,{children:[o.jsx(Oa,{children:"Connect to Supabase"}),o.jsx(Ra,{children:"Enter your connection details below."})]}),o.jsxs("div",{className:"space-y-4 py-4",children:[p&&o.jsxs(Wi,{variant:"destructive",children:[o.jsx(Dr,{className:"h-4 w-4"}),o.jsx(el,{children:p})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"supabase-url",children:"Project URL or ID"}),o.jsxs("div",{className:"relative",children:[o.jsx(Se,{id:"supabase-url",placeholder:"https://xxx.supabase.co or project-id",value:d,onChange:G=>{h(G.target.value),_(!0)},onBlur:()=>_(!0),className:w&&d?R.valid?"pr-8 border-green-500":"pr-8 border-destructive":""}),w&&d&&R.valid&&o.jsx(ja,{className:"absolute right-2 top-1/2 -translate-y-1/2 h-4 w-4 text-green-500"})]}),B&&o.jsxs("div",{className:"flex items-start gap-1.5 text-xs text-green-600 dark:text-green-400",children:[o.jsx(ja,{className:"h-3 w-3 mt-0.5 flex-shrink-0"}),o.jsxs("span",{children:["Will use: ",q]})]}),w&&d&&R.message&&!R.valid&&o.jsx("p",{className:"text-xs text-destructive",children:R.message})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"anon-key",children:"Anon Public Key"}),o.jsxs("div",{className:"relative",children:[o.jsx(Se,{id:"anon-key",type:"password",placeholder:"eyJ...",value:m,onChange:G=>{y(G.target.value),E(!0)},onBlur:()=>E(!0),className:S&&m?D.valid?"pr-8 border-green-500":"pr-8 border-destructive":""}),S&&m&&D.valid&&o.jsx(ja,{className:"absolute right-2 top-1/2 -translate-y-1/2 h-4 w-4 text-green-500"})]}),S&&m&&D.message&&o.jsx("p",{className:`text-xs ${D.valid?"text-green-600 dark:text-green-400":"text-destructive"}`,children:D.message})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{variant:"outline",onClick:()=>c("welcome"),className:"flex-1",children:"Back"}),r&&o.jsx(Z,{variant:"outline",onClick:s,className:"flex-1",children:"Close"}),o.jsx(Z,{onClick:j,disabled:!R.valid||!D.valid,className:"flex-1",children:"Connect"})]})]})]}),l==="validating"&&o.jsxs(o.Fragment,{children:[o.jsxs(ka,{children:[o.jsx(Oa,{children:"Validating Connection"}),o.jsx(Ra,{children:"Verifying your credentials with Supabase..."})]}),o.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[o.jsx($t,{className:"h-12 w-12 animate-spin text-primary mb-4"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Please wait..."})]})]}),l==="success"&&o.jsxs(o.Fragment,{children:[o.jsxs(ka,{children:[o.jsx(Oa,{children:"Success!"}),o.jsx(Ra,{children:"Your database is connected."})]}),o.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[o.jsx(Hi,{className:"h-12 w-12 text-green-500 mb-4"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Restarting application..."})]})]})]})})}function r2({email:s,isOpen:a,onOpenChange:r,onRetry:l}){const[c,d]=x.useState([]),[h,m]=x.useState(!1);x.useEffect(()=>{a&&s&&y()},[a,s]);const y=async()=>{if(s){m(!0);try{const g=await ze.getEmailEvents(s.id);g.data&&d(g.data.events)}catch(g){console.error("Failed to fetch trace:",g)}finally{m(!1)}}},p=g=>{switch(g){case"analysis":return o.jsx($i,{className:"w-4 h-4 text-purple-500"});case"action":return o.jsx(Lo,{className:"w-4 h-4 text-emerald-500"});case"error":return o.jsx(Dr,{className:"w-4 h-4 text-red-500"});default:return o.jsx(Or,{className:"w-4 h-4 text-blue-500"})}};return o.jsx(gn,{open:a,onOpenChange:r,children:o.jsxs(yn,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs(ka,{className:"p-6 border-b flex flex-row items-center justify-between",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(of,{className:"w-5 h-5 text-primary"}),o.jsx(Oa,{children:"AI Processing Trace"})]}),o.jsx(Ra,{children:"Step-by-step log of how the AI analyzed and acted on this email."})]}),s?.processing_status==="failed"&&l&&o.jsxs(Z,{size:"sm",variant:"outline",onClick:()=>{l(s),r(!1)},className:"gap-2 text-destructive border-destructive/20 hover:bg-destructive/10",children:[o.jsx(Bs,{className:"w-3.5 h-3.5"}),"Retry Job"]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:h?o.jsx("div",{className:"py-20 flex justify-center",children:o.jsx(mt,{})}):c.length===0?o.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:"No granular trace events found for this email."}):c.map((g,w)=>o.jsxs("div",{className:"relative pl-8",children:[w!==c.length-1&&o.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),o.jsx("div",{className:"absolute left-0 top-0 w-8 h-8 rounded-full border bg-background flex items-center justify-center z-10 shadow-sm",children:p(g.event_type)}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-foreground/70",children:g.agent_state}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(kr,{className:"w-3 h-3"}),new Date(g.created_at).toLocaleTimeString()]})]}),o.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[g.event_type==="info"&&o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-foreground/90",children:g.details?.message}),g.details?.system_prompt&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[o.jsx(Us,{className:"w-3 h-3"})," System Prompt"]}),o.jsx("pre",{className:"text-[10px] bg-secondary/50 p-2 rounded border overflow-x-auto whitespace-pre-wrap max-h-60 overflow-y-auto font-mono",children:g.details.system_prompt})]}),g.details?.content_preview&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Email Content (sent to LLM)"]}),o.jsx("pre",{className:"text-[10px] bg-blue-500/5 p-2 rounded border border-blue-500/10 overflow-x-auto whitespace-pre-wrap max-h-40 overflow-y-auto font-mono",children:g.details.content_preview})]})]}),g.event_type==="analysis"&&o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{className:"text-[10px] bg-secondary px-2 py-1 rounded",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Category:"}),o.jsx("span",{className:"font-bold uppercase",children:g.details?.category||"Analyzing..."})]}),o.jsxs("div",{className:"text-[10px] bg-secondary px-2 py-1 rounded",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Sentiment:"}),o.jsx("span",{className:"font-bold uppercase",children:g.details?.sentiment||"Analyzing..."})]})]}),g.details?.system_prompt&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[o.jsx(Us,{className:"w-3 h-3"})," System Prompt"]}),o.jsx("pre",{className:"text-[10px] bg-secondary/50 p-2 rounded border overflow-x-auto whitespace-pre-wrap max-h-40 overflow-y-auto font-mono",children:g.details?.system_prompt})]}),g.details?._raw_response&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Raw LLM Response"]}),o.jsx("pre",{className:"text-[10px] bg-emerald-500/5 p-2 rounded border border-emerald-500/10 overflow-x-auto font-mono",children:JSON.stringify(JSON.parse(g.details._raw_response),null,2)})]}),g.details?.usage&&o.jsxs("div",{className:"flex gap-4 pt-2 border-t border-border/50",children:[o.jsxs("div",{className:"text-[10px]",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Prompt:"}),o.jsx("span",{className:"font-mono font-bold",children:g.details.usage.prompt_tokens})]}),o.jsxs("div",{className:"text-[10px]",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Completion:"}),o.jsx("span",{className:"font-mono font-bold",children:g.details.usage.completion_tokens})]}),o.jsxs("div",{className:"text-[10px]",children:[o.jsx("span",{className:"text-muted-foreground mr-1",children:"Total:"}),o.jsx("span",{className:"font-mono font-bold text-primary",children:g.details.usage.total_tokens})]})]})]}),g.event_type==="action"&&o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:["Executed: ",g.details?.action]}),o.jsxs("p",{className:"text-xs text-muted-foreground italic",children:['"',g.details?.reason,'"']})]}),o.jsx(lf,{className:"w-5 h-5 text-emerald-500"})]}),g.event_type==="error"&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:typeof g.details?.error=="object"?g.details.error.message||JSON.stringify(g.details.error):g.details?.error}),g.details?.raw_response&&o.jsx("pre",{className:"text-[10px] bg-red-500/5 p-2 rounded border border-red-500/10 overflow-x-auto whitespace-pre-wrap font-mono",children:typeof g.details.raw_response=="object"?JSON.stringify(g.details.raw_response,null,2):g.details.raw_response})]})]})]})]},g.id))})]})})}const i2={spam:"bg-destructive/10 text-destructive",newsletter:"bg-blue-500/10 text-blue-600 dark:text-blue-400",support:"bg-orange-500/10 text-orange-600 dark:text-orange-400",client:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",internal:"bg-purple-500/10 text-purple-600 dark:text-purple-400",personal:"bg-pink-500/10 text-pink-600 dark:text-pink-400",other:"bg-gray-500/10 text-gray-600 dark:text-gray-400"};function l2(){const{state:s,actions:a,dispatch:r}=Br(),{openTerminal:l}=cv(),[c,d]=x.useState(!0),[h,m]=x.useState(!1),[y,p]=x.useState(""),[g,w]=x.useState(null),[_,S]=x.useState(null),[E,j]=x.useState({}),[R,D]=x.useState(null),[q,B]=x.useState(!1),[G,W]=x.useState(null);x.useEffect(()=>{s.isAuthenticated?(J(),a.fetchStats()):d(!1)},[g,s.isAuthenticated]);const J=async(C=0)=>{d(!0),await a.fetchEmails({category:g||void 0,search:y||void 0,offset:C,sortBy:s.sortBy,sortOrder:s.sortOrder}),d(!1)},P=C=>{a.fetchEmails({category:g||void 0,search:y||void 0,offset:0,sortBy:C,sortOrder:s.sortOrder})},Q=()=>{a.fetchEmails({category:g||void 0,search:y||void 0,offset:0,sortBy:s.sortBy,sortOrder:s.sortOrder==="asc"?"desc":"asc"})},ce=async()=>{if(s.accounts.length===0){te.warning("Please connect an email account first");return}Ea.playStart(),l(),m(!0);const C=await a.triggerSync();m(!1),C?(Ea.playSuccess(),te.success("Sync completed! Check your emails.")):te.error("Sync failed. Check account status for details.")},Je=async(C,Y)=>{if(Y==="delete"&&R!==C.id){D(C.id);return}D(null),j(_e=>({..._e,[C.id]:Y}));const K=await a.executeAction(C.id,Y);j(_e=>{const je={..._e};return delete je[C.id],je}),K&&(te.success(`Email ${Y==="delete"?"deleted":Y==="archive"?"archived":"updated"}`),Y==="delete"&&J(s.emailsOffset))},ve=()=>{D(null)},pe=C=>{C.preventDefault(),J()},Ze=C=>{const Y=C==="next"?s.emailsOffset+20:Math.max(0,s.emailsOffset-20);J(Y)},st=C=>{W(C),B(!0)},qe=async C=>{await a.retryProcessing(C.id)&&te.success("Retrying email processing...")};return o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 animate-in fade-in duration-500",children:[o.jsxs("section",{className:"lg:col-span-2 space-y-4",children:[o.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-4",children:[o.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[o.jsx(Bd,{className:"w-5 h-5 text-primary"}),"Recent Analysis"]}),o.jsxs("div",{className:"flex gap-2 w-full sm:w-auto",children:[o.jsxs(Z,{onClick:ce,size:"sm",variant:"default",className:"h-9 shadow-md px-4",disabled:h,children:[o.jsx(Bs,{className:Oe("w-3.5 h-3.5 mr-2",h&&"animate-spin")}),h?"Syncing...":"Sync Now"]}),o.jsxs("span",{className:"h-9 text-xs font-medium text-muted-foreground bg-secondary px-3 py-1 rounded-md border border-border flex items-center",children:[s.emailsTotal," emails"]})]})]}),h&&o.jsxs("div",{className:"bg-primary/5 border border-primary/20 p-4 rounded-lg flex items-center justify-between animate-in fade-in slide-in-from-top-2",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"bg-primary/10 p-2 rounded-full",children:o.jsx($t,{className:"w-5 h-5 text-primary animate-spin"})}),o.jsxs("div",{children:[o.jsx("h4",{className:"font-semibold text-sm",children:"Sync in progress..."}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Fetching and analyzing emails. New emails will appear below automatically."})]})]}),o.jsxs(Z,{variant:"outline",size:"sm",onClick:l,className:"h-8 text-xs",children:[o.jsx(of,{className:"w-3.5 h-3.5 mr-2"}),"View Logs"]})]}),o.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-center",children:[o.jsxs("form",{onSubmit:pe,className:"flex-1 flex gap-2 w-full",children:[o.jsxs("div",{className:"relative flex-1",children:[o.jsx(zw,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),o.jsx(Se,{placeholder:"Search emails...",value:y,onChange:C=>p(C.target.value),className:"pl-9 h-9"})]}),o.jsx(Z,{type:"submit",size:"sm",className:"h-9 px-4",children:"Search"})]}),o.jsxs("div",{className:"flex items-center gap-1 bg-secondary/30 p-1 rounded-md border border-border/50 h-9",children:[o.jsxs("select",{className:"bg-transparent text-xs font-medium border-none focus:ring-0 cursor-pointer pl-2 pr-8 h-full",value:s.sortBy,onChange:C=>P(C.target.value),children:[o.jsx("option",{value:"date",children:"Received Time"}),o.jsx("option",{value:"created_at",children:"Processed Time"})]}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-primary",onClick:Q,title:s.sortOrder==="asc"?"Sorting: Oldest First":"Sorting: Newest First",children:s.sortOrder==="asc"?o.jsx(Tx,{className:"w-3.5 h-3.5"}):o.jsx(Sx,{className:"w-3.5 h-3.5"})})]})]}),o.jsxs("div",{className:"flex gap-1 flex-wrap",children:[o.jsx(Z,{size:"sm",variant:s.activeCategory===null?"secondary":"ghost",onClick:()=>w(null),children:"All"}),["spam","client","newsletter","support"].map(C=>o.jsx(Z,{size:"sm",variant:s.activeCategory===C?"secondary":"ghost",onClick:()=>w(C),className:"capitalize",children:C},C))]}),c?o.jsx(sN,{}):s.emails.length===0?o.jsxs(At,{className:"p-20 text-center shadow-sm",children:[o.jsx("div",{className:"w-16 h-16 bg-primary/10 text-primary rounded-full flex items-center justify-center mx-auto mb-6",children:o.jsx(Bd,{className:"w-8 h-8"})}),o.jsx("h3",{className:"text-lg font-medium",children:"No emails found"}),o.jsx("p",{className:"text-muted-foreground mt-2 mb-6",children:s.accounts.length===0?"Connect your email account to get started.":"Try syncing or adjusting your filters."}),s.accounts.length>0&&o.jsxs(Z,{onClick:()=>{l(),ce()},disabled:h,children:[o.jsx(Bs,{className:Oe("w-4 h-4 mr-2",h&&"animate-spin")}),"Sync Now"]})]}):o.jsxs(o.Fragment,{children:[s.emails.map(C=>o.jsx(u2,{email:C,onAction:Je,onRetry:qe,onViewTrace:st,onSelect:()=>S(C),isSelected:_?.id===C.id,loadingAction:E[C.id],isDeletePending:R===C.id,onCancelDelete:ve},C.id)),o.jsx(r2,{isOpen:q,onOpenChange:B,email:G,onRetry:qe}),s.emailsTotal>20&&o.jsxs("div",{className:"flex items-center justify-between pt-4",children:[o.jsxs(Z,{variant:"outline",size:"sm",onClick:()=>Ze("prev"),disabled:s.emailsOffset===0,children:[o.jsx(Bx,{className:"w-4 h-4 mr-1"}),"Previous"]}),o.jsxs("span",{className:"text-sm text-muted-foreground",children:[s.emailsOffset+1," - ",Math.min(s.emailsOffset+20,s.emailsTotal)," of ",s.emailsTotal]}),o.jsxs(Z,{variant:"outline",size:"sm",onClick:()=>Ze("next"),disabled:s.emailsOffset+20>=s.emailsTotal,children:["Next",o.jsx($x,{className:"w-4 h-4 ml-1"})]})]})]})]}),o.jsxs("aside",{className:"space-y-6",children:[_&&o.jsxs(At,{className:"p-6 border-primary/20 bg-primary/5 animate-in slide-in-from-right-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("h3",{className:"font-semibold",children:"Email Details"}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>S(null),children:o.jsx(tl,{className:"w-4 h-4"})})]}),o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"From:"}),o.jsx("p",{className:"font-medium truncate",children:_.sender})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),o.jsx("p",{className:"font-medium",children:_.subject})]}),_.ai_analysis&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Summary:"}),o.jsx("p",{className:"text-xs mt-1",children:_.ai_analysis.summary})]}),_.ai_analysis.key_points&&o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Key Points:"}),o.jsx("ul",{className:"text-xs mt-1 list-disc list-inside",children:_.ai_analysis.key_points.map((C,Y)=>o.jsx("li",{children:C},Y))})]}),_.ai_analysis.draft_response&&o.jsxs("div",{className:"mt-4 p-3 bg-emerald-500/5 border border-emerald-500/20 rounded-lg",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2 text-emerald-600 dark:text-emerald-400",children:[o.jsx(Lw,{className:"w-3.5 h-3.5"}),o.jsx("span",{className:"text-xs font-bold uppercase",children:"AI Draft Reply"})]}),o.jsx("p",{className:"text-xs leading-relaxed whitespace-pre-wrap italic text-foreground/80",children:_.ai_analysis.draft_response}),o.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:["* This draft is already saved in your ",_.email_accounts?.provider==="gmail"?"Gmail":"Outlook"," Drafts folder."]})]})]})]})]}),o.jsx(o2,{accounts:s.accounts,onUpdate:a.updateAccount,onSync:a.triggerSync,settings:s.settings,onUpdateSettings:a.updateSettings,openTerminal:l}),o.jsxs(At,{className:"p-6",children:[o.jsxs("h3",{className:"font-semibold mb-4 flex items-center gap-2",children:[o.jsx(vy,{className:"w-4 h-4 text-primary"}),"Sync History"]}),o.jsx("div",{className:"space-y-4",children:!s.stats?.recentSyncs||s.stats.recentSyncs.length===0?o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No sync history available."}):s.stats.recentSyncs.slice(0,5).map(C=>o.jsxs("div",{className:"flex justify-between items-start text-sm border-b last:border-0 pb-3 last:pb-0",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:Oe("w-1.5 h-1.5 rounded-full",C.status==="success"?"bg-emerald-500":C.status==="running"?"bg-blue-500 animate-pulse":"bg-red-500")}),o.jsxs("p",{className:"font-medium text-xs",children:[new Date(C.started_at).toLocaleDateString()," ",new Date(C.started_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]}),o.jsxs("p",{className:"text-[10px] text-muted-foreground pl-3.5",children:["Processed: ",o.jsx("span",{className:"font-medium text-foreground",children:C.emails_processed})," • Actioned: ",o.jsx("span",{className:"font-medium text-foreground",children:C.emails_deleted+C.emails_drafted})]}),C.error_message&&o.jsx("p",{className:"text-[10px] text-destructive pl-3.5 line-clamp-1",title:C.error_message,children:C.error_message})]}),o.jsx("div",{className:"text-[10px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded",children:C.status==="running"?"Running":C.completed_at?`${Math.round((new Date(C.completed_at).getTime()-new Date(C.started_at).getTime())/1e3)}s`:"..."})]},C.id))})]}),o.jsxs(At,{className:"p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:"Quick Stats"}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Processed"}),o.jsx("span",{className:"font-medium",children:s.emailsTotal})]}),o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"Connected Accounts"}),o.jsx("span",{className:"font-medium",children:s.accounts.length})]}),o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Rules"}),o.jsx("span",{className:"font-medium",children:s.rules.filter(C=>C.is_enabled).length})]})]})]})]})]})}function o2({accounts:s,onUpdate:a,onSync:r,settings:l,onUpdateSettings:c,openTerminal:d}){return s.length===0?null:o.jsxs(At,{className:"p-6",children:[o.jsxs("h3",{className:"font-semibold mb-4 flex items-center gap-2",children:[o.jsx($w,{className:"w-4 h-4 text-primary"}),"Sync Scope"]}),o.jsx("div",{className:"space-y-6",children:s.map(h=>o.jsx(c2,{account:h,onUpdate:a,onSync:r,openTerminal:d},h.id))})]})}function c2({account:s,onUpdate:a,onSync:r,openTerminal:l}){const[c,d]=x.useState(!1),[h,m]=x.useState(""),[y,p]=x.useState(""),g=E=>{if(!E)return"";const j=typeof E=="string"&&/^\d+$/.test(E)?parseInt(E):E,R=new Date(j);if(isNaN(R.getTime()))return"";const D=q=>q<10?"0"+q:q;return R.getFullYear()+"-"+D(R.getMonth()+1)+"-"+D(R.getDate())+"T"+D(R.getHours())+":"+D(R.getMinutes())};x.useEffect(()=>{const E=s.sync_start_date||s.last_sync_checkpoint||s.last_sync_at;m(g(E)),p((s.sync_max_emails_per_run||50).toString())},[s.id,s.sync_start_date,s.last_sync_checkpoint,s.last_sync_at,s.sync_max_emails_per_run]);const w=async E=>{d(!0),await a(s.id,E),d(!1)},_=()=>{const E=s.sync_start_date?new Date(s.sync_start_date).toISOString():"",j=h?new Date(h).toISOString():"";j!==E&&w({sync_start_date:j||null})},S=()=>{const E=parseInt(y,10)||50;E!==s.sync_max_emails_per_run&&w({sync_max_emails_per_run:E})};return o.jsxs("div",{className:"space-y-3 pb-4 border-b last:border-0 last:pb-0",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-xs font-medium truncate max-w-[150px]",title:s.email_address,children:s.email_address}),o.jsxs("div",{className:"flex items-center gap-1",children:[s.last_sync_status==="syncing"?o.jsx($t,{className:"w-3 h-3 text-primary animate-spin"}):s.last_sync_status==="success"?o.jsx(lf,{className:"w-3 h-3 text-emerald-500"}):s.last_sync_status==="error"?o.jsx("span",{title:s.last_sync_error||"Error",children:o.jsx(Dr,{className:"w-3 h-3 text-destructive"})}):null,o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{l(),r(s.id)},disabled:s.last_sync_status==="syncing",children:o.jsx(Bs,{className:Oe("w-3 h-3",s.last_sync_status==="syncing"&&"animate-spin")})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground hover:text-orange-500",title:"Reset Checkpoint (Force Full Re-sync from Start Date)",onClick:()=>a(s.id,{last_sync_checkpoint:null}),disabled:s.last_sync_status==="syncing",children:o.jsx(vy,{className:"w-3 h-3"})})]})]}),o.jsxs("div",{className:"grid grid-cols-[1.5fr_1fr] gap-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("label",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(kx,{className:"w-2.5 h-2.5"})," Sync From"]}),o.jsx(Se,{type:"datetime-local",className:"h-7 text-[10px] px-2 py-0 w-full",value:h,onChange:E=>m(E.target.value),onBlur:_,disabled:c||s.last_sync_status==="syncing"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs("label",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(ow,{className:"w-2.5 h-2.5"})," Max Emails"]}),o.jsx(Se,{type:"number",className:"h-7 text-[10px] px-2 py-0",value:y,onChange:E=>p(E.target.value),onBlur:S,disabled:c||s.last_sync_status==="syncing"})]})]}),s.last_sync_at&&o.jsxs("p",{className:"text-[9px] text-muted-foreground",children:["Last sync: ",new Date(s.last_sync_at).toLocaleString()]}),s.last_sync_error&&o.jsxs("p",{className:"text-[9px] text-destructive italic line-clamp-1",title:s.last_sync_error,children:["Error: ",s.last_sync_error]})]})}function u2({email:s,onAction:a,onRetry:r,onViewTrace:l,onSelect:c,isSelected:d,loadingAction:h,isDeletePending:m,onCancelDelete:y}){if(!s)return null;const p=i2[s.category||"other"],g=!!h,w=()=>{if(!s.email_accounts)return"#";const{provider:_,email_address:S}=s.email_accounts;return _==="gmail"?`https://mail.google.com/mail/u/${S}/#all/${s.external_id}`:`https://outlook.office.com/mail/deeplink/read/${encodeURIComponent(s.external_id)}`};return o.jsx(At,{className:Oe("hover:shadow-md transition-shadow group cursor-pointer",d&&"ring-2 ring-primary"),onClick:c,children:o.jsxs("div",{className:"p-5",children:[o.jsxs("div",{className:"flex justify-between items-start mb-3 gap-4",children:[o.jsxs("div",{className:"flex gap-3 flex-1 min-w-0",children:[o.jsx("div",{className:Oe("w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center font-bold text-white text-xs",s.category==="spam"?"bg-destructive":"bg-primary"),children:s.sender?.[0]?.toUpperCase()||"?"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h3",{className:"font-semibold text-sm line-clamp-1 group-hover:text-primary transition-colors",children:s.subject||"No Subject"}),o.jsx("p",{className:"text-xs text-muted-foreground truncate",title:s.sender||"",children:s.sender})]})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[o.jsx("span",{className:Oe("px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",p),children:s.category||"unknown"}),o.jsxs("div",{className:"flex items-center justify-end gap-1",children:[s.processing_status==="pending"&&o.jsxs("span",{className:"text-[9px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx(kr,{className:"w-2.5 h-2.5"})," Queued"]}),s.processing_status==="processing"&&o.jsxs("span",{className:"text-[9px] text-blue-600 dark:text-blue-400 bg-blue-500/10 border border-blue-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx($t,{className:"w-2.5 h-2.5 animate-spin"})," Analyzing"]}),s.processing_status==="completed"&&o.jsxs("span",{className:"text-[9px] text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx($i,{className:"w-2.5 h-2.5"})," Analyzed"]}),s.processing_status==="failed"&&o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsxs("span",{className:"text-[9px] text-red-600 dark:text-red-400 bg-red-500/10 border border-red-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",title:s.processing_error||"Unknown error",children:[o.jsx(Dr,{className:"w-2.5 h-2.5"})," Failed"]}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-5 w-5 text-red-600 hover:bg-red-500/10",onClick:_=>{_.stopPropagation(),r(s)},title:"Retry Processing",children:o.jsx(Bs,{className:"w-2.5 h-2.5"})})]}),!s.processing_status&&!s.ai_analysis&&o.jsxs("span",{className:"text-[9px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx($t,{className:"w-2.5 h-2.5 animate-spin"})," Pending"]}),!s.processing_status&&s.ai_analysis&&o.jsxs("span",{className:"text-[9px] text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[o.jsx($i,{className:"w-2.5 h-2.5"})," Analyzed"]})]}),o.jsxs("div",{className:"flex items-center justify-end gap-2 text-[10px] text-muted-foreground/80 leading-tight",children:[o.jsxs("span",{title:s.date?new Date(s.date).toLocaleString():"",className:"whitespace-nowrap",children:[o.jsx("span",{className:"opacity-70 text-[9px]",children:"REC:"})," ",s.date?new Date(s.date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"-"]}),o.jsx("span",{className:"opacity-30",children:"•"}),o.jsxs("span",{title:new Date(s.created_at).toLocaleString(),className:"whitespace-nowrap",children:[o.jsx("span",{className:"opacity-70 text-[9px]",children:"PROC:"})," ",new Date(s.created_at).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})]})]})]})]}),o.jsx("p",{className:"text-muted-foreground text-sm mb-4 line-clamp-2 leading-relaxed",children:s.body_snippet}),o.jsxs("div",{className:"bg-secondary/30 p-3 rounded-lg border border-border/50 flex justify-between items-center",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[o.jsx($d,{className:"w-3.5 h-3.5 text-emerald-500"}),"Suggested:",s.suggested_actions&&s.suggested_actions.length>0?o.jsx("div",{className:"flex gap-1 flex-wrap",children:s.suggested_actions.map(_=>o.jsx("span",{className:"text-foreground border border-border/50 px-1.5 py-0.5 rounded capitalize bg-background/50",children:_},_))}):o.jsx("span",{className:"text-foreground",children:s.suggested_action||"none"}),s.actions_taken&&s.actions_taken.length>0?o.jsxs("span",{className:"text-muted-foreground ml-2 truncate max-w-[100px]",title:s.actions_taken.join(", "),children:["(Done: ",s.actions_taken.join(", "),")"]}):s.action_taken?o.jsxs("span",{className:"text-muted-foreground ml-2",children:["(Done: ",s.action_taken,")"]}):null]}),o.jsx("div",{className:"flex gap-1 items-center",onClick:_=>_.stopPropagation(),children:m?o.jsxs("div",{className:"flex items-center gap-1 animate-in fade-in duration-200",children:[o.jsx("span",{className:"text-xs text-destructive mr-1",children:"Delete?"}),o.jsx(Z,{variant:"destructive",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>a(s,"delete"),disabled:g,children:h==="delete"?o.jsx($t,{className:"w-3 h-3 animate-spin"}):"Yes"}),o.jsx(Z,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:y,disabled:g,children:"No"})]}):o.jsxs(o.Fragment,{children:[o.jsx("a",{href:w(),target:"_blank",rel:"noreferrer",className:"inline-flex items-center justify-center h-7 w-7 rounded-md text-muted-foreground hover:text-primary hover:bg-secondary/50 transition-colors",title:`Open in ${s.email_accounts?.provider==="gmail"?"Gmail":"Outlook"}`,children:o.jsx(Ii,{className:"w-3.5 h-3.5"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-primary",onClick:()=>l(s),title:"View AI Trace (Prompt/Response)",children:o.jsx(nw,{className:"w-3.5 h-3.5"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-destructive",onClick:()=>a(s,"delete"),disabled:g,title:"Delete",children:h==="delete"?o.jsx($t,{className:"w-3.5 h-3.5 animate-spin"}):o.jsx(Uo,{className:"w-3.5 h-3.5"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-blue-500",onClick:()=>a(s,"archive"),disabled:g,title:"Archive",children:h==="archive"?o.jsx($t,{className:"w-3.5 h-3.5 animate-spin"}):o.jsx(wx,{className:"w-3.5 h-3.5"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-primary",onClick:()=>a(s,"flag"),disabled:g,title:"Flag",children:h==="flag"?o.jsx($t,{className:"w-3.5 h-3.5 animate-spin"}):o.jsx(iw,{className:"w-3.5 h-3.5"})})]})})]})]})})}function d2(){const{state:s,actions:a}=Br(),[r,l]=x.useState(!1),[c,d]=x.useState(!1),[h,m]=x.useState(null),[y,p]=x.useState(!1),[g,w]=x.useState(!1),[_,S]=x.useState({}),[E,j]=x.useState(!1),[R,D]=x.useState("credentials"),[q,B]=x.useState(""),[G,W]=x.useState(""),[J,P]=x.useState(""),[Q,ce]=x.useState(""),[Je,ve]=x.useState(!1),[pe,Ze]=x.useState(!1),[st,qe]=x.useState(!1),[C,Y]=x.useState("credentials"),[K,_e]=x.useState(""),[je,A]=x.useState(""),[V,X]=x.useState(!1),[F,de]=x.useState(!1),[ge,ue]=x.useState(""),[Ge,Ue]=x.useState("category"),[Ct,pt]=x.useState("newsletter"),[xt,ns]=x.useState(["archive"]),[la,rs]=x.useState(""),[xn,wn]=x.useState(""),[qr,is]=x.useState(""),[_n,ls]=x.useState(""),[sl,qs]=x.useState([]),[gt,nl]=x.useState(!1),[$r,Hr]=x.useState(!1),[Da,Sn]=x.useState(null),[ya,jn]=x.useState(null);x.useEffect(()=>{a.fetchAccounts(),a.fetchRules(),a.fetchSettings()},[]),x.useEffect(()=>{s.settings&&S(s.settings)},[s.settings]);const Zo=async()=>{const O=s.rules.find(ee=>ee.name==="Auto-Trash Spam");if(!O){te.error("System rule not found. Please sync your database.");return}Sn("auto_trash_spam"),await a.toggleRule(O.id),Sn(null)},$s=async()=>{const O=s.rules.find(ee=>ee.name==="Smart Drafts");if(!O){te.error("System rule not found. Please sync your database.");return}Sn("smart_drafts"),await a.toggleRule(O.id),Sn(null)},wt=O=>{jn(O),ue(O.name);const ee=O.condition,yt=Object.keys(ee).filter(Is=>Is!=="older_than_days")[0]||"category";Ue(yt),pt(ee[yt]||""),rs(ee.older_than_days?.toString()||"");const Vs=O.actions&&O.actions.length>0?O.actions:O.action?[O.action]:["archive"];ns(Vs),wn(O.instructions||""),is(O.description||""),ls(O.intent||""),qs(O.attachments||[]),de(!0)},va=x.useRef(null),Ot=()=>{D("credentials"),B(""),W(""),P(""),ce(""),j(!0)},Fo=O=>{B(O);try{const ee=JSON.parse(O),Ce=ee.installed||ee.web||ee;Ce.client_id&&W(Ce.client_id),Ce.client_secret&&P(Ce.client_secret),ee.installed?te.success("Detected Desktop app credentials"):ee.web&&te.info("Detected Web app - make sure redirect URI is configured in Google Cloud Console")}catch{}},Wo=async()=>{if(!G||!J){te.error("Please provide both Client ID and Client Secret");return}ve(!0);try{if(await a.updateSettings({..._,google_client_id:G,google_client_secret:J})){S(Ce=>({...Ce,google_client_id:G,google_client_secret:J}));const ee=await ze.getGmailAuthUrl();if(ee.data?.url)window.open(ee.data.url,"_blank"),D("code"),te.success("Please authorize in the opened tab, then paste the code here");else{const Ce=typeof ee.error=="string"?ee.error:ee.error?.message;te.error(Ce||"Failed to get OAuth URL")}}else te.error("Failed to save credentials")}catch{te.error("Failed to save credentials")}finally{ve(!1)}},ec=async()=>{if(!Q.trim()){te.error("Please paste the authorization code");return}Ze(!0);try{const O=await ze.connectGmail(Q.trim());if(O.data?.success)te.success("Gmail account connected successfully!"),j(!1),a.fetchAccounts();else{const ee=typeof O.error=="string"?O.error:O.error?.message;te.error(ee||"Failed to connect Gmail")}}catch{te.error("Failed to connect Gmail")}finally{Ze(!1)}},Nn=()=>{Y("credentials"),_e(""),A(""),qe(!0)},En=async()=>{if(!K){te.error("Please provide the Client ID");return}X(!0);try{if(await a.updateSettings({..._,microsoft_client_id:K,microsoft_tenant_id:je||"common"})){S(Ce=>({...Ce,microsoft_client_id:K,microsoft_tenant_id:je||"common"}));const ee=await ze.startMicrosoftDeviceFlow();if(ee.data)m(ee.data),Y("device-code"),Tn(ee.data.deviceCode,ee.data.interval);else{const Ce=typeof ee.error=="string"?ee.error:ee.error?.message;te.error(Ce||"Failed to start device flow")}}else te.error("Failed to save credentials")}catch{te.error("Failed to save credentials")}finally{X(!1)}},Tn=async(O,ee)=>{const Ce=setInterval(async()=>{try{const yt=await ze.pollMicrosoftDeviceCode(O);yt.data?.status==="completed"?(clearInterval(Ce),m(null),d(!1),qe(!1),te.success("Outlook account connected"),a.fetchAccounts()):yt.error&&typeof yt.error=="object"&&yt.error.code}catch{}},ee*1e3);setTimeout(()=>{clearInterval(Ce),c&&(m(null),d(!1),qe(!1),te.error("Connection timed out. Please try again."))},900*1e3)},Ma=async()=>{if(!ge){te.error("Please name your rule");return}if(xt.length===0){te.error("Please select at least one action");return}Hr(!0);try{const O={[Ge]:Ct};la&&(O.older_than_days=parseInt(la,10));const ee=xt.includes("draft"),Ce={name:ge,description:qr||void 0,intent:_n||void 0,condition:O,actions:xt,instructions:ee?xn:void 0,attachments:ee?sl:[],is_enabled:!0};let yt=!1;ya?yt=await a.updateRule(ya.id,Ce):yt=await a.createRule(Ce),yt?(te.success(ya?"Rule updated":"Rule created"),de(!1),jn(null),ue(""),ns(["archive"]),rs(""),wn(""),is(""),ls(""),qs([]),a.fetchRules()):te.error(`Failed to ${ya?"update":"create"} rule`)}catch{te.error("An error occurred while saving the rule")}finally{Hr(!1)}},An=async O=>{if(!confirm("Are you sure you want to disconnect this account?"))return;await a.disconnectAccount(O)&&te.success("Account disconnected")},os=async()=>{p(!0);const O=await a.updateSettings(_);p(!1),O&&te.success("Settings saved")},tc=async()=>{w(!0);try{const O=await ze.testLlm({llm_model:_.llm_model||null,llm_base_url:_.llm_base_url||null,llm_api_key:_.llm_api_key||null});O.data?.success?te.success(O.data.message):te.error(O.data?.message||"Connection test failed")}catch{te.error("Failed to test connection")}finally{w(!1)}},rl=async O=>{await a.toggleRule(O)},Vr=async O=>{const ee=O.target.files;if(!ee||ee.length===0)return;nl(!0);const Ce=ee[0],yt=Ce.name.split(".").pop(),Vs=`${Math.random().toString(36).substring(2)}.${yt}`,Is=`${s.user.id}/${Vs}`;try{const{error:Gs}=await ct.storage.from("rule-attachments").upload(Is,Ce);if(Gs)throw Gs;const ba={name:Ce.name,path:Is,type:Ce.type,size:Ce.size};qs(ut=>[...ut,ba]),te.success("File uploaded")}catch(Gs){console.error("Upload error:",Gs),te.error("Failed to upload file")}finally{nl(!1),O.target.value=""}},Hs=O=>{qs(ee=>ee.filter(Ce=>Ce.path!==O))},ac=O=>O==="gmail"?o.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center text-red-600 dark:text-red-400 font-bold",children:"G"}):o.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold",children:"O"});return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[o.jsx(gn,{open:E,onOpenChange:j,children:o.jsxs(yn,{className:"sm:max-w-lg",children:[o.jsxs(ka,{children:[o.jsxs(Oa,{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-8 h-8 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center text-red-600 dark:text-red-400 font-bold text-sm",children:"G"}),"Connect Gmail Account"]}),o.jsx(Ra,{children:R==="credentials"?"Enter your Google OAuth credentials to connect your Gmail account.":"Paste the authorization code from Google to complete the connection."})]}),R==="credentials"?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(Qw,{className:"w-4 h-4"}),"Paste credentials.json"]}),o.jsx("textarea",{className:"w-full h-24 p-3 text-xs font-mono border rounded-lg bg-secondary/30 resize-none focus:outline-none focus:ring-2 focus:ring-primary",placeholder:'{"installed":{"client_id":"...","client_secret":"..."}}',value:q,onChange:O=>Fo(O.target.value)}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Download from Google Cloud Console → APIs & Services → Credentials"})]}),o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("span",{className:"w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:o.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or enter manually"})})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),o.jsx(Se,{placeholder:"xxx.apps.googleusercontent.com",value:G,onChange:O=>W(O.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client Secret"}),o.jsx(Se,{type:"password",placeholder:"GOCSPX-...",value:J,onChange:O=>P(O.target.value)})]})]})]}),o.jsxs(Er,{children:[o.jsx(Z,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),o.jsxs(Z,{onClick:Wo,disabled:Je||!G||!J,children:[Je?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Save & Connect"]})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsx("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:o.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:["1. A new tab opened with Google Sign-In",o.jsx("br",{}),"2. Sign in and authorize the app",o.jsx("br",{}),"3. Copy the authorization code shown",o.jsx("br",{}),"4. Paste it below"]})}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Authorization Code"}),o.jsx(Se,{placeholder:"4/0AQlEd8x...",value:Q,onChange:O=>ce(O.target.value),className:"font-mono"})]})]}),o.jsxs(Er,{children:[o.jsx(Z,{variant:"outline",onClick:()=>D("credentials"),children:"Back"}),o.jsxs(Z,{onClick:ec,disabled:pe||!Q.trim(),children:[pe?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Connect"]})]})]})]})}),o.jsx(gn,{open:st,onOpenChange:qe,children:o.jsxs(yn,{className:"sm:max-w-lg",children:[o.jsxs(ka,{children:[o.jsxs(Oa,{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold text-sm",children:"O"}),"Connect Outlook Account"]}),o.jsx(Ra,{children:C==="credentials"?"Enter your Microsoft Azure App credentials to connect your Outlook account.":"Follow the instructions to authorize the application."})]}),C==="credentials"?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsx("div",{className:"p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg",children:o.jsx("p",{className:"text-sm text-yellow-800 dark:text-yellow-200",children:"Note: You need an Azure App Registration for this to work."})}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client ID (Application ID)"}),o.jsx(Se,{placeholder:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",value:K,onChange:O=>_e(O.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Tenant ID (Optional)"}),o.jsx(Se,{placeholder:"common",value:je,onChange:O=>A(O.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:'Default is "common". Use your specific Tenant ID for organization accounts.'})]})]})]}),o.jsxs(Er,{children:[o.jsx(Z,{variant:"outline",onClick:()=>qe(!1),children:"Cancel"}),o.jsxs(Z,{onClick:En,disabled:V||!K,children:[V?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Save & Connect"]})]})]}):o.jsxs(o.Fragment,{children:[h&&o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:[o.jsx("h4",{className:"font-medium text-blue-900 dark:text-blue-100 mb-2",children:"Action Required"}),o.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200 mb-4",children:h.message}),o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx("div",{className:"flex items-center gap-2 bg-white dark:bg-black/20 p-2 rounded border border-blue-200 dark:border-blue-800",children:o.jsx("code",{className:"text-lg font-mono font-bold flex-1 text-center select-all",children:h.userCode})}),o.jsxs(Z,{variant:"default",className:"w-full bg-blue-600 hover:bg-blue-700",onClick:()=>window.open(h.verificationUri,"_blank"),children:["Open Microsoft Login",o.jsx(Ii,{className:"w-4 h-4 ml-2"})]})]})]}),o.jsx("div",{className:"flex justify-center",children:o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[o.jsx(mt,{size:"sm"}),"Waiting for authorization..."]})})]}),o.jsx(Er,{children:o.jsx(Z,{variant:"outline",onClick:()=>qe(!1),children:"Cancel"})})]})]})}),o.jsx(gn,{open:F,onOpenChange:O=>{de(O),O||jn(null)},children:o.jsxs(yn,{className:"sm:max-w-xl max-h-[90vh] flex flex-col p-0",children:[o.jsxs(ka,{className:"p-6 border-b",children:[o.jsx(Oa,{children:ya?"Edit Auto-Pilot Rule":"Create Auto-Pilot Rule"}),o.jsx(Ra,{children:"Define a condition based on AI analysis to trigger an action."})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Rule Name"}),o.jsx(Se,{placeholder:"e.g. Archive Newsletters",value:ge,onChange:O=>ue(O.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Description"}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[60px] text-sm",placeholder:"e.g. Handle all marketing newsletters and promotional content from subscription services",value:qr,onChange:O=>is(O.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Describe what this rule is for. The AI uses this to semantically match emails."})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Intent"}),o.jsx(Se,{placeholder:"e.g. Politely decline all sales pitches",value:_n,onChange:O=>ls(O.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"The goal of this rule. Used to generate appropriate draft replies."})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"If Condition Field"}),o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ge,onChange:O=>{Ue(O.target.value),O.target.value==="category"?pt("newsletter"):O.target.value==="sentiment"?pt("Positive"):O.target.value==="priority"?pt("High"):pt("")},children:[o.jsxs("optgroup",{label:"AI Analysis",children:[o.jsx("option",{value:"category",children:"Category"}),o.jsx("option",{value:"sentiment",children:"Sentiment"}),o.jsx("option",{value:"priority",children:"Priority"})]}),o.jsxs("optgroup",{label:"Metadata",children:[o.jsx("option",{value:"sender_email",children:"Specific Email (Exact)"}),o.jsx("option",{value:"sender_domain",children:"Email Domain (@...)"}),o.jsx("option",{value:"sender_contains",children:"Sender contains..."}),o.jsx("option",{value:"subject_contains",children:"Subject contains..."}),o.jsx("option",{value:"body_contains",children:"Body contains..."})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Equals Value"}),Ge==="category"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ct,onChange:O=>pt(O.target.value),children:[o.jsx("option",{value:"newsletter",children:"Newsletter"}),o.jsx("option",{value:"spam",children:"Spam"}),o.jsx("option",{value:"promotional",children:"Promotional"}),o.jsx("option",{value:"transactional",children:"Transactional"}),o.jsx("option",{value:"social",children:"Social"}),o.jsx("option",{value:"support",children:"Support"}),o.jsx("option",{value:"client",children:"Client"}),o.jsx("option",{value:"internal",children:"Internal"}),o.jsx("option",{value:"personal",children:"Personal"}),o.jsx("option",{value:"other",children:"Other"})]}):Ge==="sentiment"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ct,onChange:O=>pt(O.target.value),children:[o.jsx("option",{value:"Positive",children:"Positive"}),o.jsx("option",{value:"Neutral",children:"Neutral"}),o.jsx("option",{value:"Negative",children:"Negative"})]}):Ge==="priority"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ct,onChange:O=>pt(O.target.value),children:[o.jsx("option",{value:"High",children:"High"}),o.jsx("option",{value:"Medium",children:"Medium"}),o.jsx("option",{value:"Low",children:"Low"})]}):o.jsx(Se,{placeholder:Ge==="sender_domain"?"rta.vn":Ge==="sender_email"?"john@example.com":"Keywords...",value:Ct,onChange:O=>pt(O.target.value)})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(kr,{className:"w-4 h-4"}),"Only if email is older than... (Optional)"]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Se,{type:"number",min:"0",placeholder:"0",className:"w-24",value:la,onChange:O=>rs(O.target.value)}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Leave empty or 0 to apply rule immediately upon receipt."})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Then Perform Action(s)"}),o.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select one or more actions to execute when the rule matches"}),o.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"archive",label:"Archive Email"},{value:"delete",label:"Delete Email"},{value:"draft",label:"Draft Reply"},{value:"read",label:"Mark as Read"},{value:"star",label:"Star / Flag"}].map(O=>o.jsxs("label",{className:`flex items-center gap-2 p-2 border rounded-md cursor-pointer transition-colors ${xt.includes(O.value)?"bg-primary/10 border-primary":"bg-background hover:bg-secondary/50"}`,children:[o.jsx("input",{type:"checkbox",checked:xt.includes(O.value),onChange:ee=>{ee.target.checked?ns([...xt,O.value]):ns(xt.filter(Ce=>Ce!==O.value))},className:"rounded border-gray-300"}),o.jsx("span",{className:"text-sm",children:O.label})]},O.value))})]}),xt.includes("draft")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[o.jsx("label",{className:"text-sm font-medium",children:"Draft Instructions (Context)"}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[80px] text-sm",placeholder:"e.g. Tell them I'm busy until Friday, but interested in the proposal.",value:xn,onChange:O=>wn(O.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Specific context for the AI ghostwriter."})]}),o.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(xg,{className:"w-4 h-4"}),"Attachments (Optional)"]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[sl.map(O=>o.jsxs("div",{className:"flex items-center justify-between p-2 bg-secondary/50 rounded border text-xs",children:[o.jsx("span",{className:"truncate max-w-[200px]",children:O.name}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive",onClick:()=>Hs(O.path),children:o.jsx(tl,{className:"w-3 h-3"})})]},O.path)),o.jsxs("div",{className:"relative",children:[o.jsx("input",{type:"file",className:"absolute inset-0 opacity-0 cursor-pointer",onChange:Vr,disabled:gt}),o.jsxs(Z,{variant:"outline",size:"sm",className:"w-full border-dashed",disabled:gt,children:[gt?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Mi,{className:"w-3 h-3 mr-2"}),gt?"Uploading...":"Add Attachment"]})]})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Files will be attached to every draft generated by this rule."})]})]})]}),o.jsxs(Er,{className:"p-6 border-t bg-secondary/5",children:[o.jsx(Z,{variant:"outline",onClick:()=>de(!1),children:"Cancel"}),o.jsxs(Z,{onClick:Ma,disabled:$r,children:[$r?o.jsx(mt,{size:"sm",className:"mr-2"}):ya?o.jsx(ja,{className:"w-4 h-4 mr-2"}):o.jsx(Mi,{className:"w-4 h-4 mr-2"}),ya?"Save Changes":"Create Rule"]})]})]})}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx(Vi,{className:"w-5 h-5 text-primary"}),"Connected Accounts"]}),o.jsx(ts,{children:"Manage your email providers"})]}),o.jsxs(Ca,{className:"space-y-4",children:[s.accounts.length===0?o.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No accounts connected yet"}):s.accounts.map(O=>o.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg bg-card",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[ac(O.provider),o.jsxs("div",{children:[o.jsx("h4",{className:"font-medium capitalize",children:O.provider}),o.jsx("p",{className:"text-xs text-muted-foreground",children:O.email_address})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[O.is_active?o.jsx("span",{className:"text-xs text-emerald-600 bg-emerald-500/10 px-2 py-1 rounded-full",children:"Active"}):o.jsx("span",{className:"text-xs text-yellow-600 bg-yellow-500/10 px-2 py-1 rounded-full",children:"Inactive"}),o.jsx(Z,{variant:"outline",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>An(O.id),children:o.jsx(Uo,{className:"w-4 h-4"})})]})]},O.id)),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs(Z,{className:"w-full border-dashed",variant:"outline",onClick:Ot,disabled:r||c,children:[r?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Mi,{className:"w-4 h-4 mr-2"}),"Connect Gmail Account"]}),o.jsxs(Z,{className:"w-full border-dashed",variant:"outline",onClick:Nn,disabled:r||c,children:[c&&!h?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Mi,{className:"w-4 h-4 mr-2"}),"Connect Outlook Account"]})]}),h&&o.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg animate-in slide-in-from-top-2",children:[o.jsx("h4",{className:"font-medium text-blue-900 dark:text-blue-100 mb-2",children:"Microsoft Sign-In Required"}),o.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200 mb-4",children:h.message}),o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx("div",{className:"flex items-center gap-2 bg-white dark:bg-black/20 p-2 rounded border border-blue-200 dark:border-blue-800",children:o.jsx("code",{className:"text-lg font-mono font-bold flex-1 text-center select-all",children:h.userCode})}),o.jsxs(Z,{variant:"default",className:"w-full bg-blue-600 hover:bg-blue-700",onClick:()=>window.open(h.verificationUri,"_blank"),children:["Open Microsoft Login",o.jsx(Ii,{className:"w-4 h-4 ml-2"})]}),o.jsx("p",{className:"text-xs text-center text-muted-foreground mt-2",children:"Waiting for you to sign in..."})]})]})]})]}),o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx($d,{className:"w-5 h-5 text-emerald-500"}),"Auto-Pilot Rules"]}),o.jsx(ts,{children:"Configure AI automation behavior"})]}),o.jsxs(Ca,{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between items-center py-3 border-b border-border",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-medium text-sm",children:"Auto-Trash Spam"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically delete emails categorized as spam"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{const O=s.rules.find(ee=>ee.name==="Auto-Trash Spam");O&&wt(O)},title:"Edit Logic",children:o.jsx(vd,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs(Z,{variant:s.rules.find(O=>O.name==="Auto-Trash Spam")?.is_enabled?"default":"outline",size:"sm",onClick:Zo,disabled:Da==="auto_trash_spam",children:[Da==="auto_trash_spam"?o.jsx(mt,{size:"sm",className:"mr-1"}):o.jsx(bo,{className:"w-4 h-4 mr-1"}),s.rules.find(O=>O.name==="Auto-Trash Spam")?.is_enabled?"On":"Off"]})]})]}),o.jsxs("div",{className:"flex justify-between items-center py-3 border-b border-border",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-medium text-sm",children:"Smart Drafts"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Generate draft replies for important emails"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{const O=s.rules.find(ee=>ee.name==="Smart Drafts");O&&wt(O)},title:"Edit Logic",children:o.jsx(vd,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs(Z,{variant:s.rules.find(O=>O.name==="Smart Drafts")?.is_enabled?"default":"outline",size:"sm",onClick:$s,disabled:Da==="smart_drafts",children:[Da==="smart_drafts"?o.jsx(mt,{size:"sm",className:"mr-1"}):o.jsx(bo,{className:"w-4 h-4 mr-1"}),s.rules.find(O=>O.name==="Smart Drafts")?.is_enabled?"On":"Off"]})]})]}),o.jsxs("div",{className:"pt-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("h4",{className:"text-sm font-medium",children:"Custom Rules"}),o.jsxs(Z,{variant:"ghost",size:"sm",onClick:()=>{jn(null),ue(""),is(""),ls(""),ns(["archive"]),rs(""),wn(""),qs([]),de(!0)},children:[o.jsx(Mi,{className:"w-4 h-4 mr-1"})," Add Rule"]})]}),s.rules.length===0&&o.jsx("p",{className:"text-xs text-muted-foreground text-center py-2 border border-dashed rounded-lg",children:"No custom rules yet"}),s.rules.length>0&&s.rules.filter(O=>O.name!=="Auto-Trash Spam"&&O.name!=="Smart Drafts").map(O=>{const ee=O.actions&&O.actions.length>0?O.actions:O.action?[O.action]:[];return o.jsxs("div",{className:"p-3 bg-secondary/30 rounded-lg mb-2",children:[o.jsxs("div",{className:"flex justify-between items-center mb-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-sm font-medium",children:O.name}),o.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["→ ",ee.join(" + ")]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>wt(O),title:"Edit Rule",children:o.jsx(vd,{className:"w-3.5 h-3.5 text-muted-foreground"})}),o.jsxs(Z,{variant:O.is_enabled?"default":"outline",size:"sm",onClick:()=>rl(O.id),className:"h-7 px-2",children:[o.jsx(bo,{className:"w-3.5 h-3.5 mr-1"}),O.is_enabled?"On":"Off"]}),o.jsx(Z,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>a.deleteRule(O.id),children:o.jsx(Uo,{className:"w-3 h-3"})})]})]}),O.instructions&&o.jsxs("p",{className:"text-[10px] text-muted-foreground italic border-t border-border/50 pt-1 mt-1 truncate",children:['"',O.instructions,'"']}),O.attachments&&O.attachments.length>0&&o.jsx("div",{className:"flex gap-1 mt-1",children:O.attachments.map(Ce=>o.jsxs("div",{className:"flex items-center gap-1 text-[9px] bg-blue-500/10 text-blue-400 px-1.5 py-0.5 rounded border border-blue-500/20",children:[o.jsx(xg,{className:"w-2.5 h-2.5"}),Ce.name]},Ce.path))})]},O.id)})]})]})]})]}),o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx(Bs,{className:"w-5 h-5 text-indigo-500"}),"Model Configuration"]}),o.jsx(ts,{children:"Configure Local LLM or API settings"})]}),o.jsxs(Ca,{className:"space-y-4",children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Model Name"}),o.jsx(Se,{placeholder:"gpt-4o-mini",value:_.llm_model||"",onChange:O=>S(ee=>({...ee,llm_model:O.target.value}))})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Base URL"}),o.jsx(Se,{placeholder:"https://api.openai.com/v1",value:_.llm_base_url||"",onChange:O=>S(ee=>({...ee,llm_base_url:O.target.value}))}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Use http://localhost:11434/v1 for Ollama"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"API Key"}),o.jsx(Se,{type:"password",placeholder:"sk-...",value:_.llm_api_key||"",onChange:O=>S(ee=>({...ee,llm_api_key:O.target.value}))})]})]}),o.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(Vi,{className:"w-4 h-4"}),"Local Storage Path (.eml)"]}),o.jsx(Se,{placeholder:"e.g. ./data/emails or ~/.email-automator/emails",value:_.storage_path||"",onChange:O=>S(ee=>({...ee,storage_path:O.target.value}))}),o.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"Directory where raw emails (.eml) are saved. Default: ./data/emails (falls back to ~/.email-automator/emails if restricted)."})]}),o.jsxs("div",{className:"flex justify-between items-center py-3 border-t border-border/50",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-medium text-sm",children:"Intelligent Rename"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Use slugified-hyphenated filenames (e.g. 20240119-1430-subject-id.eml)"})]}),o.jsxs(Z,{variant:_.intelligent_rename?"default":"outline",size:"sm",onClick:()=>S(O=>({...O,intelligent_rename:!O.intelligent_rename})),children:[o.jsx(bo,{className:"w-4 h-4 mr-1"}),_.intelligent_rename?"On":"Off"]})]}),o.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(kr,{className:"w-4 h-4"}),"Background Sync Interval (minutes)"]}),o.jsx(Se,{type:"number",min:1,max:1440,value:_.sync_interval_minutes||5,onChange:O=>S(ee=>({...ee,sync_interval_minutes:parseInt(O.target.value,10)||5}))}),o.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"How often the system checks for new emails in the background."})]}),o.jsxs("div",{className:"flex justify-end mt-4 gap-2",children:[o.jsxs(Z,{variant:"outline",onClick:tc,disabled:g,children:[g?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Bs,{className:"w-4 h-4 mr-2"}),"Check Connection"]}),o.jsxs(Z,{onClick:os,disabled:y,children:[y?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Save Configuration"]})]})]})]}),o.jsx("div",{ref:va,children:o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx($d,{className:"w-5 h-5 text-orange-500"}),"Provider Credentials (Advanced)"]}),o.jsx(ts,{children:"Bring Your Own Keys (BYOK). Configure your own OAuth credentials here. Leave empty to use system defaults."})]}),o.jsxs(Ca,{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-4 border-b pb-4",children:[o.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[o.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"})," Google / Gmail"]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),o.jsx(Se,{type:"password",placeholder:"...apps.googleusercontent.com",value:_.google_client_id||"",onChange:O=>S(ee=>({...ee,google_client_id:O.target.value}))})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client Secret"}),o.jsx(Se,{type:"password",placeholder:"GOCSPX-...",value:_.google_client_secret||"",onChange:O=>S(ee=>({...ee,google_client_secret:O.target.value}))})]})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[o.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-500"})," Microsoft / Outlook"]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),o.jsx(Se,{type:"password",value:_.microsoft_client_id||"",onChange:O=>S(ee=>({...ee,microsoft_client_id:O.target.value}))})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Client Secret (Optional)"}),o.jsx(Se,{type:"password",value:_.microsoft_client_secret||"",onChange:O=>S(ee=>({...ee,microsoft_client_secret:O.target.value}))})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Tenant ID"}),o.jsx(Se,{placeholder:"common",value:_.microsoft_tenant_id||"",onChange:O=>S(ee=>({...ee,microsoft_tenant_id:O.target.value}))})]})]})]}),o.jsx("div",{className:"flex justify-end mt-4",children:o.jsxs(Z,{onClick:os,disabled:y,variant:"secondary",children:[y?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(ja,{className:"w-4 h-4 mr-2"}),"Save Credentials"]})})]})]})})]})}const f2="modulepreload",h2=function(s){return"/"+s},hy={},m2=function(a,r,l){let c=Promise.resolve();if(r&&r.length>0){let p=function(g){return Promise.all(g.map(w=>Promise.resolve(w).then(_=>({status:"fulfilled",value:_}),_=>({status:"rejected",reason:_}))))};var h=p;document.getElementsByTagName("link");const m=document.querySelector("meta[property=csp-nonce]"),y=m?.nonce||m?.getAttribute("nonce");c=p(r.map(g=>{if(g=h2(g),g in hy)return;hy[g]=!0;const w=g.endsWith(".css"),_=w?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${g}"]${_}`))return;const S=document.createElement("link");if(S.rel=w?"stylesheet":f2,w||(S.as="script"),S.crossOrigin="",S.href=g,y&&S.setAttribute("nonce",y),document.head.appendChild(S),w)return new Promise((E,j)=>{S.addEventListener("load",E),S.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${g}`)))})}))}function d(m){const y=new Event("vite:preloadError",{cancelable:!0});if(y.payload=m,window.dispatchEvent(y),!y.defaultPrevented)throw m}return c.then(m=>{for(const y of m||[])y.status==="rejected"&&d(y.reason);return a().catch(d)})};function p2(){const[s,a]=x.useState("profile"),{state:r,actions:l}=Br();x.useEffect(()=>{l.fetchProfile()},[]);const c=[{id:"profile",label:"Profile",icon:by},{id:"security",label:"Security",icon:Iw},{id:"database",label:"Supabase",icon:Vi}];return o.jsxs("div",{className:"max-w-4xl mx-auto space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Account Settings"}),o.jsx("p",{className:"text-muted-foreground",children:"Manage your profile, security, and connection preferences."})]}),o.jsxs("div",{className:"flex flex-col md:flex-row gap-8",children:[o.jsxs("aside",{className:"w-full md:w-64 flex flex-col justify-between",children:[o.jsx("nav",{className:"space-y-1",children:c.map(d=>{const h=d.icon,m=s===d.id;return o.jsxs("button",{onClick:()=>a(d.id),className:`w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${m?"bg-primary text-primary-foreground":"hover:bg-secondary text-muted-foreground"}`,children:[o.jsx(h,{className:"w-4 h-4"}),d.label]},d.id)})}),o.jsxs("div",{className:"mt-8 px-4 py-4 border-t border-border/40 text-center md:text-left",children:[o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/50 uppercase tracking-widest mb-1",children:"Version"}),o.jsxs("p",{className:"text-xs font-mono text-muted-foreground/70",children:["v","2.9.3"]})]})]}),o.jsxs("div",{className:"flex-1 space-y-6",children:[s==="profile"&&o.jsx(g2,{}),s==="security"&&o.jsx(y2,{}),s==="database"&&o.jsx(v2,{})]})]})]})}function g2(){const{state:s,actions:a}=Br(),[r,l]=x.useState(""),[c,d]=x.useState(""),[h,m]=x.useState(!1),[y,p]=x.useState(!1),[g,w]=x.useState(Ea.isEnabled());x.useEffect(()=>{s.profile&&(l(s.profile.first_name||""),d(s.profile.last_name||""))},[s.profile]);const _=()=>{const j=!g;Ea.setEnabled(j),w(j),j?(Ea.playSuccess(),te.success("Sound effects enabled")):te.info("Sound effects disabled")},S=async()=>{m(!0);const j=await a.updateProfile({first_name:r,last_name:c});m(!1),j&&te.success("Profile updated")},E=async j=>{const R=j.target.files?.[0];if(!(!R||!s.user)){p(!0);try{const D=R.name.split(".").pop(),q=`${s.user.id}/avatar.${D}`,{data:B,error:G}=await ct.storage.from("avatars").upload(q,R,{upsert:!0});if(G)throw G;const{data:{publicUrl:W}}=ct.storage.from("avatars").getPublicUrl(q);await a.updateProfile({avatar_url:W}),te.success("Avatar updated")}catch(D){console.error("Avatar upload error:",D),te.error("Failed to upload avatar")}finally{p(!1)}}};return o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsx(Aa,{children:"Profile Information"}),o.jsx(ts,{children:"Update your personal details and avatar."})]}),o.jsxs(Ca,{className:"space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center sm:flex-row sm:items-start gap-6",children:[o.jsxs("div",{className:"relative group",children:[o.jsx("div",{className:"w-24 h-24 rounded-full bg-secondary overflow-hidden border-2 border-border flex items-center justify-center",children:s.profile?.avatar_url?o.jsx("img",{src:s.profile.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):o.jsx(by,{className:"w-12 h-12 text-muted-foreground"})}),o.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-full opacity-0 group-hover:opacity-100 cursor-pointer transition-opacity",children:[o.jsx(Rx,{className:"w-6 h-6 text-white"}),o.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:E,disabled:y})]}),y&&o.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 rounded-full",children:o.jsx(mt,{size:"sm"})})]}),o.jsxs("div",{className:"flex-1 space-y-4 w-full",children:[o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"first-name",children:"First Name"}),o.jsx(Se,{id:"first-name",value:r,onChange:j=>l(j.target.value),placeholder:"John"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"last-name",children:"Last Name"}),o.jsx(Se,{id:"last-name",value:c,onChange:j=>d(j.target.value),placeholder:"Doe"})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"email",children:"Email Address"}),o.jsx(Se,{id:"email",value:s.profile?.email||"",disabled:!0,className:"bg-secondary/50"}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Email cannot be changed directly."})]})]})]}),o.jsxs("div",{className:"pt-6 border-t flex items-center justify-between",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("label",{className:"text-sm font-medium",children:"Sound & Haptics"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Audio feedback when processing emails and completing tasks."})]}),o.jsxs(Z,{variant:g?"default":"outline",size:"sm",onClick:_,className:"gap-2",children:[g?o.jsx(t_,{className:"w-4 h-4"}):o.jsx(s_,{className:"w-4 h-4"}),g?"Enabled":"Disabled"]})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:S,disabled:h,children:[h?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(Dw,{className:"w-4 h-4 mr-2"}),"Save Changes"]})})]})]})}function y2(){const[s,a]=x.useState(""),[r,l]=x.useState(""),[c,d]=x.useState(!1),h=async()=>{if(!s){te.error("Please enter a new password");return}if(s!==r){te.error("Passwords do not match");return}if(s.length<6){te.error("Password must be at least 6 characters");return}d(!0);try{const{api:m}=await m2(async()=>{const{api:p}=await Promise.resolve().then(()=>Ij);return{api:p}},void 0),y=await m.changePassword(s);y.success?(te.success("Password changed successfully"),a(""),l("")):te.error(y.error?.message||"Failed to change password")}catch{te.error("An error occurred")}finally{d(!1)}};return o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsx(Aa,{children:"Security"}),o.jsx(ts,{children:"Manage your password and account security."})]}),o.jsxs(Ca,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"new-password",children:"New Password"}),o.jsx(Se,{id:"new-password",type:"password",value:s,onChange:m=>a(m.target.value),placeholder:"••••••••"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(pa,{htmlFor:"confirm-password",children:"Confirm New Password"}),o.jsx(Se,{id:"confirm-password",type:"password",value:r,onChange:m=>l(m.target.value),placeholder:"••••••••"})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:h,disabled:c,children:[c?o.jsx(mt,{size:"sm",className:"mr-2"}):o.jsx(hw,{className:"w-4 h-4 mr-2"}),"Update Password"]})})]})]})}function v2(){const[s,a]=x.useState(!1),r=Lr(),l=$j(),c=()=>{confirm("Are you sure you want to disconnect from this Supabase project? This will log you out and clear local configuration.")&&(qj(),window.location.reload())};return o.jsxs(o.Fragment,{children:[o.jsxs(At,{children:[o.jsxs(Ta,{children:[o.jsxs(Aa,{className:"flex items-center gap-2",children:[o.jsx(Vi,{className:"w-5 h-5 text-primary"}),"Supabase Connection"]}),o.jsx(ts,{children:"Manage your database configuration (BYOK - Bring Your Own Keys)."})]}),o.jsx(Ca,{className:"space-y-6",children:r?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-xl bg-emerald-500/5 border-emerald-500/20",children:[o.jsx(Hi,{className:"w-6 h-6 text-emerald-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-1",children:[o.jsx("p",{className:"font-semibold text-emerald-700 dark:text-emerald-400",children:"Connected"}),o.jsx("p",{className:"text-sm font-mono break-all opacity-80",children:r.url})]})]}),l==="env"&&o.jsxs(Wi,{className:"bg-amber-500/5 border-amber-500/20",children:[o.jsx(qd,{className:"h-4 w-4 text-amber-500"}),o.jsx(el,{className:"text-amber-700 dark:text-amber-400 text-xs",children:"Configuration is loaded from environment variables. Use the UI to override them."})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[o.jsxs(Z,{variant:"outline",onClick:()=>a(!0),className:"w-full",children:[o.jsx(qd,{className:"w-4 h-4 mr-2"}),"Change Connection"]}),l==="ui"&&o.jsxs(Z,{variant:"outline",onClick:c,className:"w-full text-destructive hover:bg-destructive/10",children:[o.jsx(Uo,{className:"w-4 h-4 mr-2"}),"Clear Config"]})]}),o.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[o.jsx(pa,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Anon Public Key"}),o.jsxs("div",{className:"p-2 bg-secondary/50 rounded-lg font-mono text-xs break-all",children:[r.anonKey.substring(0,20),"...",r.anonKey.substring(r.anonKey.length-10)]})]})]}):o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center space-y-4",children:[o.jsx(Xx,{className:"w-12 h-12 text-destructive opacity-20"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-medium",children:"No Connection Detected"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure a Supabase project to get started."})]}),o.jsxs(Z,{onClick:()=>a(!0),children:[o.jsx(Vi,{className:"w-4 h-4 mr-2"}),"Setup Supabase"]})]})})]}),o.jsx(Vv,{open:s,onComplete:()=>a(!1),canClose:!0})]})}function b2({length:s=6,value:a,onChange:r,onComplete:l,disabled:c=!1,error:d=!1}){const h=x.useRef([]),[m,y]=x.useState(null),p=(_,S)=>{const E=S.replace(/[^0-9]/g,"");if(E.length===0){const D=a.split("");D[_]=" ",a.split("");let q=a.split("");_<q.length&&q.splice(_,1);const B=q.join("");r(B),_>0&&h.current[_-1]?.focus();return}a.split("");const j=[...a];j[_]=E[0],r(j.join("")),_<s-1&&h.current[_+1]?.focus();const R=j.join("");R.length===s&&l&&l(R)},g=(_,S)=>{S.key==="Backspace"&&!a[_]&&_>0||S.key==="ArrowLeft"&&_>0?h.current[_-1]?.focus():S.key==="ArrowRight"&&_<s-1&&h.current[_+1]?.focus()},w=_=>{_.preventDefault();const E=_.clipboardData.getData("text/plain").replace(/[^0-9]/g,"").slice(0,s);r(E);const j=Math.min(E.length,s-1);h.current[j]?.focus(),E.length===s&&l&&l(E)};return o.jsx("div",{className:"flex gap-2 justify-center",children:Array.from({length:s}).map((_,S)=>o.jsx(Se,{ref:E=>{h.current[S]=E},type:"text",inputMode:"numeric",maxLength:1,value:a[S]||"",onChange:E=>p(S,E.target.value),onKeyDown:E=>g(S,E),onPaste:w,onFocus:()=>y(S),onBlur:()=>y(null),disabled:c,className:Oe("w-10 h-10 sm:w-12 sm:h-12 text-center text-lg font-semibold px-0",d&&"border-destructive focus-visible:ring-destructive",m===S&&"ring-2 ring-ring"),"aria-label":`Digit ${S+1}`},S))})}function x2({onSuccess:s,onConfigure:a}){const[r,l]=x.useState(""),[c,d]=x.useState(""),[h,m]=x.useState(""),[y,p]=x.useState(""),[g,w]=x.useState(!1),[_,S]=x.useState(!0),[E,j]=x.useState(!1),[R,D]=x.useState(""),[q,B]=x.useState("password"),[G,W]=x.useState("email"),[J,P]=x.useState("");x.useEffect(()=>{Q()},[]);const Q=async()=>{try{const{data:ve,error:pe}=await ct.from("init_state").select("is_initialized");if(pe){console.warn("[Login] Init check failed, defaulting to initialized (Login):",pe),j(!0);return}const Ze=ve?.[0]?.is_initialized>0;j(Ze)}catch(ve){if(console.warn("[Login] Init check exception, defaulting to initialized:",ve),ve.message?.includes("Invalid API key")||ve.status===401){console.warn("[Login] API Key invalid for REST check (likely Publishable Key). defaulting to Setup Mode (isInitialized=false)."),j(!1);return}j(!0)}finally{S(!1)}},ce=async ve=>{ve.preventDefault(),w(!0),D("");try{if(E){if(q==="password"){const{error:pe}=await ct.auth.signInWithPassword({email:r,password:c});if(pe)throw pe;te.success("Logged in successfully"),s?.()}else if(G==="email"){const{error:pe}=await ct.auth.signInWithOtp({email:r,options:{shouldCreateUser:!1}});if(pe)throw pe;W("verify"),te.success("Validation code sent to your email")}}else{const{data:pe,error:Ze}=await ct.functions.invoke("setup",{body:{email:r,password:c,first_name:h,last_name:y}});if(Ze||!pe){if(Ze?.message?.includes("First user already exists")){te.info("System already initialized. Please log in."),j(!0);return}throw new Error(Ze?.message||"Failed to create admin account")}te.success("Admin account created! Signing you in...");const{error:st}=await ct.auth.signInWithPassword({email:r,password:c});if(st)throw st;j(!0),s?.()}}catch(pe){D(pe?.message||"Authentication failed"),console.error("[Login] Error:",pe)}finally{w(!1)}},Je=async()=>{w(!0),D("");try{const{data:ve,error:pe}=await ct.auth.verifyOtp({email:r,token:J,type:"magiclink"});if(pe)throw pe;if(!ve.session)throw new Error("Failed to create session");te.success("Logged in successfully"),s?.()}catch(ve){D(ve?.message||"Invalid code")}finally{w(!1)}};return _?o.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:o.jsx($t,{className:"w-8 h-8 animate-spin text-primary"})}):o.jsxs("div",{className:"min-h-screen bg-background flex items-center justify-center p-8 relative",children:[o.jsx("div",{className:"absolute top-4 right-4",children:o.jsx(By,{})}),o.jsxs(At,{className:"w-full max-w-md shadow-2xl",children:[o.jsxs(Ta,{className:"text-center",children:[o.jsx("div",{className:"mx-auto bg-primary/10 p-4 rounded-full w-fit mb-4",children:o.jsx(vf,{className:"w-12 h-12"})}),o.jsx(Aa,{className:"text-2xl",children:E?"Welcome Back":"Welcome to Email Automator"}),o.jsx(ts,{children:E?q==="password"?"Sign in to access your email automation":G==="email"?"Receive a login code via email":`Enter code sent to ${r}`:"Create the first admin account to get started"})]}),o.jsxs("form",{onSubmit:ce,children:[o.jsxs(Ca,{className:"space-y-4",children:[!E&&o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"First Name"}),o.jsx(Se,{value:h,onChange:ve=>m(ve.target.value),required:!E,placeholder:"John"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Last Name"}),o.jsx(Se,{value:y,onChange:ve=>p(ve.target.value),required:!E,placeholder:"Doe"})]})]}),q==="password"||G==="email"?o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Email"}),o.jsx(Se,{type:"email",placeholder:"admin@example.com",value:r,onChange:ve=>l(ve.target.value),required:!0,autoComplete:"email",disabled:G==="verify"})]}):null,q==="password"&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:"Password"}),o.jsx(Se,{type:"password",placeholder:"••••••••",value:c,onChange:ve=>d(ve.target.value),required:!0,minLength:6,autoComplete:E?"current-password":"new-password"})]}),q==="otp"&&G==="verify"&&o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(b2,{value:J,onChange:P,length:6,onComplete:()=>{}})}),o.jsx(Z,{type:"button",variant:"link",className:"w-full text-xs text-muted-foreground",onClick:()=>W("email"),children:"Change email address"})]}),o.jsxs("div",{className:"bg-destructive/10 text-destructive text-sm p-3 rounded-md flex flex-col gap-2",children:[o.jsx("p",{children:R}),R.includes("configuration")||R.includes("Invalid API key")||R.includes("API key")&&a&&o.jsx(Z,{type:"button",variant:"outline",className:"w-full border-destructive/50 hover:bg-destructive/20 text-destructive",onClick:a,children:"Update Connection Settings"})]})]}),o.jsxs(uv,{className:"flex flex-col gap-3",children:[q==="otp"&&G==="verify"?o.jsx(Z,{type:"button",onClick:Je,disabled:g||J.length!==6,className:"w-full",children:g?o.jsxs(o.Fragment,{children:[o.jsx($t,{className:"w-4 h-4 mr-2 animate-spin"}),"Verifying..."]}):"Verify Code"}):o.jsx(Z,{type:"submit",disabled:g||!r||q==="password"&&!c,className:"w-full",children:g?o.jsxs(o.Fragment,{children:[o.jsx($t,{className:"w-4 h-4 mr-2 animate-spin"}),E?q==="otp"?"Send Code":"Signing in...":"Creating Account..."]}):o.jsxs(o.Fragment,{children:[E?q==="otp"?o.jsx(Bd,{className:"w-4 h-4 mr-2"}):o.jsx(vw,{className:"w-4 h-4 mr-2"}):o.jsx(Fw,{className:"w-4 h-4 mr-2"}),E?q==="otp"?"Send Login Code":"Sign In":"Create Admin Account"]})}),E&&o.jsx("div",{className:"flex flex-col gap-2 w-full",children:q==="password"?o.jsxs(Z,{type:"button",variant:"ghost",className:"w-full text-sm font-normal text-muted-foreground hover:text-primary",onClick:()=>{B("otp"),W("email"),D("")},children:[o.jsx(dw,{className:"w-4 h-4 mr-2"}),"Sign in with Code"]}):o.jsxs(Z,{type:"button",variant:"ghost",className:"w-full text-sm font-normal text-muted-foreground hover:text-primary",onClick:()=>{B("password"),D("")},children:[o.jsx(Nx,{className:"w-4 h-4 mr-2"}),"Sign in with Password"]})}),E&&o.jsx("p",{className:"text-xs text-center text-muted-foreground mt-2",children:"New users must be invited by an admin."})]})]})]})]})}const Iv=void 0,w2=void 0;function _2(s,a){const r=s.split(".").map(Number),l=a.split(".").map(Number);for(let c=0;c<Math.max(r.length,l.length);c++){const d=r[c]||0,h=l[c]||0;if(d>h)return 1;if(d<h)return-1}return 0}async function S2(s){try{const{data:a,error:r}=await s.rpc("get_latest_migration_timestamp");return r?(console.warn("Could not get latest migration timestamp:",r.message),{version:null,latestMigrationTimestamp:null}):{version:Iv,latestMigrationTimestamp:a||null}}catch(a){return console.error("Error checking database migration info:",a),{version:null,latestMigrationTimestamp:null}}}async function j2(s){const a=Iv,r=w2,l=await S2(s);if(console.log("[Migration Check]",{appVersion:a,appMigrationTimestamp:r,dbVersion:l.version,dbMigrationTimestamp:l.latestMigrationTimestamp}),l.latestMigrationTimestamp&&l.latestMigrationTimestamp.trim()!==""){const c=r,d=l.latestMigrationTimestamp;return c>d?{needsMigration:!0,appVersion:a,dbVersion:l.version,message:`New migrations available. Database is at ${d}, app has ${c}.`}:c<d?(console.warn("[Migration Check] DB is ahead of app - possible downgrade"),{needsMigration:!1,appVersion:a,dbVersion:l.version,message:`Database (${d}) is ahead of app (${c}).`}):(console.log("[Migration Check] Timestamps match - database is up-to-date"),{needsMigration:!1,appVersion:a,dbVersion:l.version,message:"Database schema is up-to-date."})}if(l.version){console.log("[Migration Check] Legacy DB detected (no timestamp). Falling back to SemVer.");const c=_2(a,l.version);return c>0?{needsMigration:!0,appVersion:a,dbVersion:l.version,message:`Database schema (v${l.version}) is outdated. Migration to v${a} required.`}:c===0?(console.warn("[Migration Check] Legacy DB with matching version - forcing migration to add timestamp tracking"),{needsMigration:!0,appVersion:a,dbVersion:l.version,message:`Database lacks timestamp tracking. Please run migration to upgrade to modern schema (v${a}).`}):{needsMigration:!1,appVersion:a,dbVersion:l.version,message:`Database version (v${l.version}) is ahead of app (v${a}).`}}return console.log("[Migration Check] No DB info found - assuming migration needed"),{needsMigration:!0,appVersion:a,dbVersion:null,message:`Database schema unknown. Migration required to v${a}.`}}const Gv="email_automator_migration_reminder_dismissed_at";function N2(s=24){try{const a=localStorage.getItem(Gv);if(!a)return!1;const r=new Date(a).getTime();return(Date.now()-r)/(1e3*60*60)<s}catch(a){return console.error("Error checking migration reminder:",a),!1}}function E2(){try{localStorage.setItem(Gv,new Date().toISOString())}catch(s){console.error("Error dismissing migration reminder:",s)}}function T2({status:s,onDismiss:a,onLearnMore:r}){const[l,c]=x.useState(!0);if(!l)return null;const d=()=>{E2(),c(!1),a?.()},h=()=>{r?r():(navigator.clipboard.writeText("npx email-automator migrate"),te.success("Command copied to clipboard"))};return o.jsx("div",{className:"fixed right-4 top-16 z-50 max-w-sm animate-in slide-in-from-top-5",children:o.jsx("div",{className:"rounded-lg border border-yellow-500 bg-yellow-50 p-4 shadow-lg dark:bg-yellow-950/90 dark:border-yellow-600",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Rr,{className:"h-5 w-5 flex-shrink-0 text-yellow-600 dark:text-yellow-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("p",{className:"text-sm font-medium text-yellow-900 dark:text-yellow-100",children:"Database Update Required"}),o.jsxs(Z,{size:"icon",variant:"ghost",className:"h-5 w-5 -mr-1 -mt-1 text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30",onClick:d,children:[o.jsx(tl,{className:"h-3 w-3"}),o.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),o.jsxs("p",{className:"text-xs text-yellow-800 dark:text-yellow-200",children:["Your app version (",s.appVersion,") requires a database schema update."]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",variant:"default",className:"h-7 text-xs bg-yellow-600 hover:bg-yellow-700 dark:bg-yellow-500 dark:hover:bg-yellow-600",onClick:h,children:"Update Now"}),o.jsx(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30",onClick:d,children:"Remind Later"})]})]})]})})})}function Ro({code:s,label:a}){const[r,l]=x.useState(!1),c=typeof navigator<"u"&&!!navigator.clipboard?.writeText,d=async()=>{if(!c){te.error("Clipboard not supported");return}try{await navigator.clipboard.writeText(s),l(!0),window.setTimeout(()=>l(!1),2e3),te.success("Copied to clipboard")}catch(h){console.error("Failed to copy:",h),te.error("Failed to copy to clipboard")}};return o.jsxs("div",{className:"relative",children:[a&&o.jsx("div",{className:"mb-2 text-sm font-medium text-muted-foreground",children:a}),o.jsxs("div",{className:"group relative",children:[o.jsx("pre",{className:"overflow-hidden rounded-md bg-muted p-3 pr-12 text-sm",children:o.jsx("code",{className:"block whitespace-pre-wrap break-all",children:s})}),o.jsxs(Z,{type:"button",size:"icon",variant:"ghost",className:"absolute right-2 top-2 h-8 w-8",onClick:d,disabled:!c,children:[r?o.jsx(ja,{className:"h-4 w-4 text-green-600"}):o.jsx(Wx,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:r?"Copied":"Copy code"})]})]})]})}function A2({open:s,onOpenChange:a,status:r}){const l=Lr(),[c,d]=x.useState(!0),[h,m]=x.useState(!1),[y,p]=x.useState([]),[g,w]=x.useState(""),[_,S]=x.useState(""),E=x.useRef(null),j=x.useMemo(()=>{const D=l?.url;if(!D)return"";try{return new URL(D).hostname.split(".")[0]||""}catch{return""}},[l?.url]);x.useEffect(()=>{E.current&&E.current.scrollIntoView({behavior:"smooth"})},[y]);const R=async()=>{if(!j){te.error("Missing Project ID");return}m(!0),p(["Initializing migration..."]);try{const D=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:j,dbPassword:g,accessToken:_})});if(!D.ok)throw new Error(`Server returned ${D.status}: ${D.statusText}`);const q=D.body?.getReader();if(!q)throw new Error("No response stream received.");const B=new TextDecoder;for(;;){const{done:G,value:W}=await q.read();if(G)break;const P=B.decode(W).split(`
96
96
  `).filter(Boolean);p(Q=>[...Q,...P])}}catch(D){console.error(D),p(q=>[...q,`Error: ${D instanceof Error?D.message:String(D)}`]),te.error("Migration failed. Check logs for details.")}finally{m(!1)}};return o.jsx(gn,{open:s,onOpenChange:D=>!h&&a(D),children:o.jsxs(yn,{className:"max-h-[90vh] sm:max-w-5xl overflow-y-auto",children:[o.jsxs(ka,{children:[o.jsxs(Oa,{className:"flex items-center gap-2 text-xl",children:[o.jsx(Rr,{className:"h-6 w-6 text-red-700 dark:text-red-600"}),"Database Migration Required"]}),o.jsxs(Ra,{children:["Your application version (",r.appVersion,") requires a database schema update to function correctly."]})]}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs(Wi,{children:[o.jsx(Or,{className:"h-4 w-4"}),o.jsxs(el,{children:[o.jsx("strong",{children:"Why is this needed?"}),o.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[o.jsxs("li",{children:["Updates your database schema to match version ",r.appVersion]}),o.jsx("li",{children:"Enables new features and performance improvements"}),o.jsx("li",{children:"Your existing data will be preserved (safe migration)"})]})]})]}),o.jsxs("div",{className:"flex border-b",children:[o.jsx("button",{className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${c?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>d(!0),children:"Automatic (Recommended)"}),o.jsx("button",{className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${c?"border-transparent text-muted-foreground hover:text-foreground":"border-primary text-primary"}`,onClick:()=>d(!1),children:"Manual CLI"})]}),c?o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"rounded-lg border bg-card text-card-foreground shadow-sm p-6",children:[o.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Automated Migration"}),o.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Run the migration directly from your browser. Requires your database password."}),o.jsxs("div",{className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(pa,{htmlFor:"project-id",children:"Supabase Project ID"}),o.jsx(Se,{id:"project-id",value:j,disabled:!0,readOnly:!0,className:"bg-muted"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx(pa,{htmlFor:"access-token",children:"Access Token (Optional)"}),o.jsxs("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Generate Token ",o.jsx(Ii,{className:"h-3 w-3"})]})]}),o.jsx(Se,{id:"access-token",type:"password",placeholder:"sbp_...",value:_,onChange:D=>S(D.target.value),disabled:h}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Recommended for more reliable authentication."})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(pa,{htmlFor:"db-password",children:"Database Password"}),o.jsx(Se,{id:"db-password",type:"password",placeholder:"Your database password",value:g,onChange:D=>w(D.target.value),disabled:h}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Required if no access token is provided."})]}),o.jsx(Z,{onClick:R,disabled:h,className:"w-full",children:h?o.jsxs(o.Fragment,{children:[o.jsx($t,{className:"mr-2 h-4 w-4 animate-spin"}),"Migrating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Hd,{className:"mr-2 h-4 w-4"}),"Start Migration"]})})]})]}),o.jsxs("div",{className:"rounded-lg border bg-black text-white font-mono text-xs p-4 h-64 overflow-y-auto",children:[y.length===0?o.jsx("div",{className:"text-gray-500 italic",children:"Waiting to start..."}):y.map((D,q)=>o.jsx("div",{className:"mb-1 whitespace-pre-wrap",children:D},q)),o.jsx("div",{ref:E})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsxs("h4",{className:"mb-3 flex items-center gap-2 font-semibold",children:[o.jsx("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:"1"}),"Prerequisites"]}),o.jsxs("div",{className:"ml-8 space-y-3",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"You will need the following before proceeding:"}),o.jsxs("ul",{className:"list-inside list-disc space-y-1 text-sm",children:[o.jsx("li",{children:"Supabase CLI installed"}),o.jsxs("li",{children:["Project ID:"," ",o.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:j||"your-project-id"})]}),o.jsx("li",{children:"Database Password"})]})]})]}),o.jsxs("div",{children:[o.jsxs("h4",{className:"mb-3 flex items-center gap-2 font-semibold",children:[o.jsx("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:"2"}),"Install Supabase CLI"]}),o.jsxs("div",{className:"ml-8 space-y-3",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-sm font-medium",children:"MacOS (Brew)"}),o.jsx(Ro,{code:"brew install supabase/tap/supabase"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-sm font-medium",children:"Windows (Scoop)"}),o.jsx(Ro,{code:`scoop bucket add supabase https://github.com/supabase/scoop-bucket.git
97
- scoop install supabase`})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-sm font-medium",children:"NPM (Universal)"}),o.jsx(Ro,{code:"npm install -g supabase"})]})]})]}),o.jsxs("div",{children:[o.jsxs("h4",{className:"mb-3 flex items-center gap-2 font-semibold",children:[o.jsx("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:"3"}),"Run Migration"]}),o.jsxs("div",{className:"ml-8 space-y-3",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"Run the built-in migration tool:"}),o.jsx(Ro,{code:"npx email-automator migrate"})]})]})]}),o.jsxs(Wi,{className:"border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/20",children:[o.jsx(Rr,{className:"h-4 w-4 text-red-700 dark:text-red-600"}),o.jsxs(el,{children:[o.jsx("strong",{children:"Troubleshooting"}),o.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[o.jsxs("li",{children:["Try logging out: ",o.jsx("code",{children:"supabase logout"})]}),o.jsx("li",{children:"Verify your database password is correct"})]})]})]})]}),o.jsx(Er,{children:o.jsx(Z,{type:"button",variant:"outline",onClick:()=>a(!1),disabled:h,children:"Close"})})]})})}function C2(){const[s,a]=x.useState([]),{isExpanded:r,setIsExpanded:l}=cv(),[c,d]=x.useState({});x.useEffect(()=>{h();const g=ct.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},w=>{const _=w.new;_.event_type==="error"&&d(S=>({...S,[_.id]:!0})),a(S=>{const E=[_,...S];return E.length>100?E.slice(0,100):E})}).subscribe();return()=>{ct.removeChannel(g)}},[]);const h=async()=>{const{data:g}=await ct.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(50);g&&a(g)},m=g=>{d(w=>({...w,[g]:!w[g]}))},y=g=>{if(g.details?.is_completion)return o.jsx(Hi,{className:"w-3 h-3 text-emerald-500"});switch(g.event_type){case"analysis":return o.jsx($i,{className:"w-3 h-3 text-purple-500"});case"action":return o.jsx(Lo,{className:"w-3 h-3 text-emerald-500"});case"error":return o.jsx(Rr,{className:"w-3 h-3 text-red-500"});default:return o.jsx(Or,{className:"w-3 h-3 text-blue-500"})}},p=g=>new Date(g).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});return r?o.jsxs(At,{className:"fixed bottom-4 right-4 z-50 w-[550px] h-[650px] flex flex-col shadow-2xl border-border bg-background/95 text-foreground backdrop-blur-md animate-in slide-in-from-bottom-10",children:[o.jsxs(Ta,{className:"py-3 px-4 border-b border-border flex flex-row items-center justify-between sticky top-0 bg-background/95 z-20",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Hd,{className:"w-4 h-4 text-primary"}),o.jsx(Aa,{className:"text-sm font-mono font-bold",children:"Agent Terminal"}),o.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-green-600 dark:text-green-400 bg-green-500/10 px-2 py-0.5 rounded-full border border-green-500/20 font-bold",children:[o.jsx(bx,{className:"w-3 h-3"}),"LIVE"]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 text-[10px] font-mono hover:bg-secondary",onClick:()=>a([]),children:"Clear"}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-secondary",onClick:()=>l(!1),children:o.jsx(Sw,{className:"w-4 h-4"})})]})]}),o.jsxs(Ca,{className:"flex-1 overflow-y-auto p-4 font-mono text-xs space-y-6 custom-scrollbar",children:[s.length===0&&o.jsx("div",{className:"text-center text-muted-foreground py-20 italic",children:"Waiting for agent activity..."}),s.map((g,w)=>o.jsxs("div",{className:"relative pl-8 animate-in fade-in slide-in-from-top-2 duration-300",children:[w!==s.length-1&&o.jsx("div",{className:"absolute left-[13px] top-7 bottom-[-24px] w-[1px] bg-border"}),o.jsx("div",{className:Oe("absolute left-0 top-0 w-7 h-7 rounded-full border border-border bg-card flex items-center justify-center z-10 shadow-sm",g.event_type==="error"&&"border-red-500/50 bg-red-500/5",g.event_type==="analysis"&&"border-purple-500/50 bg-purple-500/5",g.event_type==="action"&&"border-emerald-500/50 bg-emerald-500/5",g.details?.is_completion&&"border-emerald-500/50 bg-emerald-500/5"),children:y(g)}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs("div",{className:"flex items-center justify-between group",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:Oe("font-bold uppercase tracking-tight text-[10px]",g.event_type==="info"&&"text-muted-foreground",g.event_type==="analysis"&&"text-purple-600 dark:text-purple-400",g.event_type==="action"&&"text-emerald-600 dark:text-emerald-400",g.event_type==="error"&&"text-red-600 dark:text-red-400"),children:g.agent_state}),o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:p(g.created_at)})]}),(g.details?.system_prompt||g.details?._raw_response||g.details?.raw_response)&&o.jsxs(Z,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[9px] text-muted-foreground hover:text-primary opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>m(g.id),children:[c[g.id]?o.jsx(Vx,{className:"w-3 h-3 mr-1"}):o.jsx(Ux,{className:"w-3 h-3 mr-1"}),"Details"]})]}),g.event_type==="analysis"&&g.details?o.jsxs("div",{className:"bg-purple-500/5 border border-purple-500/10 rounded-lg p-3 space-y-2",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:Oe("px-1.5 py-0.5 rounded text-[9px] font-bold border",g.details.is_useless?"bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20":"bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/20"),children:g.details.is_useless?"USELESS":"RELEVANT"}),o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-bold border bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20 uppercase",children:g.details.category})]}),o.jsxs("p",{className:"text-foreground/90 italic leading-relaxed",children:['"',g.details.summary,'"']}),g.details.suggested_actions&&g.details.suggested_actions.length>0&&o.jsx("div",{className:"pt-1 flex items-center gap-2 flex-wrap",children:g.details.suggested_actions.map(_=>o.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-emerald-600 dark:text-emerald-400 font-bold bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20 uppercase",children:[o.jsx(Lo,{className:"w-2.5 h-2.5"}),_]},_))}),g.details.usage&&o.jsx("div",{className:"pt-1.5 flex items-center gap-3 text-[9px] text-muted-foreground/70 border-t border-purple-500/10 mt-1",children:o.jsxs("span",{children:["Tokens: ",g.details.usage.prompt_tokens," (in) + ",g.details.usage.completion_tokens," (out) = ",o.jsx("span",{className:"text-purple-500 font-bold",children:g.details.usage.total_tokens})]})})]}):g.event_type==="action"&&g.details?o.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/10 rounded-lg p-3",children:[o.jsx("p",{className:"text-emerald-600 dark:text-emerald-400 font-bold mb-1 uppercase text-[9px] tracking-widest",children:"Execution Complete"}),o.jsxs("p",{className:"text-foreground font-medium",children:[g.details.action==="delete"&&"Moved to Trash",g.details.action==="archive"&&"Archived Email",g.details.action==="draft"&&"Drafted Reply",g.details.action==="read"&&"Marked as Read",g.details.action==="star"&&"Starred Email",!["delete","archive","draft","read","star"].includes(g.details.action)&&g.details.action]}),g.details.reason&&o.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 flex items-center gap-1",children:[o.jsx(Or,{className:"w-3 h-3"}),g.details.reason]})]}):g.event_type==="error"&&g.details?o.jsx("div",{className:"bg-red-500/5 border border-red-500/10 rounded-lg p-2.5 text-red-600 dark:text-red-400 font-medium",children:typeof g.details.error=="object"?g.details.error.message||JSON.stringify(g.details.error):g.details.error}):g.details?.is_completion?o.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-lg p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 dark:text-emerald-400 font-bold uppercase text-[9px] tracking-[0.2em]",children:[o.jsx(Hi,{className:"w-3.5 h-3.5"}),"Batch Sync Finished"]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-1",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Processed"}),o.jsx("p",{className:"text-sm font-bold",children:g.details.total_processed||0})]}),o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Actions"}),o.jsx("p",{className:"text-sm font-bold text-emerald-500",children:(g.details.deleted||0)+(g.details.drafted||0)})]})]}),g.details.errors>0&&o.jsxs("p",{className:"text-[10px] text-red-500 font-bold pt-1 border-t border-emerald-500/10",children:["⚠️ ",g.details.errors," items failed to process."]})]}):o.jsx("p",{className:"text-muted-foreground leading-relaxed",children:g.details?.message||JSON.stringify(g.details)}),c[g.id]&&o.jsxs("div",{className:"mt-2 space-y-3 animate-in fade-in zoom-in-95 duration-200",children:[g.details?.system_prompt&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Us,{className:"w-3 h-3"})," System Prompt"]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"whitespace-pre-wrap break-words text-[10px] leading-normal text-muted-foreground select-all",children:g.details.system_prompt})})]}),g.details?.content_preview&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Input Content (Cleaned)"]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border",children:o.jsx("p",{className:"whitespace-pre-wrap break-words text-[10px] text-muted-foreground",children:g.details.content_preview})})]}),g.details?._raw_response&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Raw LLM JSON Output"]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"text-[10px] text-muted-foreground select-all",children:JSON.stringify(JSON.parse(g.details._raw_response),null,2)})})]}),g.details?.raw_response&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Raw Response (from Error)"]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"text-[10px] text-muted-foreground select-all whitespace-pre-wrap",children:typeof g.details.raw_response=="object"?JSON.stringify(g.details.raw_response,null,2):g.details.raw_response})})]})]})]})]},g.id))]})]}):o.jsx("div",{className:"fixed bottom-4 right-4 z-50",children:o.jsxs(Z,{onClick:()=>l(!0),className:"shadow-lg bg-primary text-primary-foreground hover:opacity-90 border border-border",children:[o.jsx(Hd,{className:"w-4 h-4 mr-2"}),"Live Activity",s.length>0&&o.jsxs("span",{className:"ml-2 flex h-2 w-2 relative",children:[o.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-green-500"})]})]})})}function k2(){const{state:s,isSubscribed:a,actions:r}=Br(),[l,c]=x.useState(!1),[d,h]=x.useState("dashboard"),[m,y]=x.useState(!0),[p,g]=x.useState(!1);if(x.useEffect(()=>{const J=()=>{if(Ea.isEnabled()){const P=new(window.AudioContext||window.webkitAudioContext);P.state==="suspended"&&P.resume()}window.removeEventListener("click",J),window.removeEventListener("keydown",J)};return window.addEventListener("click",J),window.addEventListener("keydown",J),()=>{window.removeEventListener("click",J),window.removeEventListener("keydown",J)}},[]),x.useEffect(()=>{const P=new URLSearchParams(window.location.search).get("code");P&&!p&&(async()=>{g(!0);try{const ce=await ze.connectGmail(P);if(ce.data?.success)te.success("Gmail connected successfully!"),window.opener?setTimeout(()=>window.close(),1500):(window.history.replaceState({},"",window.location.pathname),r.fetchAccounts());else{const Je=typeof ce.error=="string"?ce.error:ce.error?.message;te.error(Je||"Failed to connect Gmail")}}catch{te.error("Connection failed")}finally{g(!1)}})()},[]),p)return o.jsx(qi,{text:"Connecting account..."});const[w,_]=x.useState(null),[S,E]=x.useState(!1),[j,R]=x.useState(!1),[D,q]=x.useState(!1);x.useEffect(()=>{(async()=>{const P=Lr();if(!P){c(!0),y(!1);return}if((await av(P.url,P.anonKey)).valid)s.isInitialized&&s.isAuthenticated&&(r.fetchAccounts(),r.fetchRules(),r.fetchSettings(),r.fetchProfile(),j2(ct).then(ce=>{_(ce),ce.needsMigration&&!N2()&&E(!0)}));else{c(!0),y(!1);return}y(!1)})()},[s.isInitialized,s.isAuthenticated]);const B=()=>{R(!0),E(!1)},G={migrationStatus:w,showMigrationBanner:S,showMigrationModal:j,openMigrationModal:B,suppressMigrationBanner:D,setSuppressMigrationBanner:q};if(m)return o.jsx(qi,{text:"Checking configuration..."});if(l)return o.jsx(Vv,{onComplete:()=>{c(!1),window.location.reload()}});if(!s.isInitialized)return o.jsx(qi,{text:"Initializing..."});if(!s.isAuthenticated)return o.jsx(x2,{onConfigure:()=>c(!0)});const W=async()=>{await ct.auth.signOut(),te.success("Logged out successfully")};return o.jsx(eN,{value:G,children:o.jsxs("div",{className:"min-h-screen bg-background font-sans text-foreground transition-colors duration-300",children:[o.jsx("header",{className:"sticky top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60",children:o.jsxs("div",{className:"max-w-7xl mx-auto flex h-16 items-center justify-between px-4 sm:px-8",children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("button",{onClick:()=>h("dashboard"),className:"text-xl font-bold flex items-center gap-2 hover:opacity-80 transition-opacity",children:[o.jsx(vf,{className:"w-8 h-8"}),o.jsx("span",{className:"hidden sm:inline",children:"Email Automator"}),o.jsx("span",{className:"sm:hidden",children:"Email AI"})]}),o.jsxs("div",{className:Oe("flex items-center gap-1.5 px-2 h-6 rounded-full text-[10px] font-bold border transition-colors",a?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20 dark:text-emerald-400":"bg-yellow-500/10 text-yellow-600 border-yellow-500/20 dark:text-yellow-400"),children:[o.jsxs("div",{className:"relative flex items-center justify-center",children:[a&&o.jsx("span",{className:"absolute inline-flex h-3 w-3 rounded-full bg-emerald-500/40 animate-ping"}),o.jsx("div",{className:Oe("relative w-2 h-2 rounded-full",a?"bg-emerald-500":"bg-yellow-500")})]}),o.jsx("span",{className:"hidden xs:inline leading-none",children:a?"LIVE":"OFFLINE"})]})]}),o.jsxs("div",{className:"flex gap-4 items-center",children:[o.jsxs("nav",{className:"flex items-center gap-1 bg-secondary/50 p-1 rounded-lg",children:[o.jsxs(Z,{variant:d==="dashboard"?"secondary":"ghost",size:"sm",onClick:()=>h("dashboard"),className:"gap-2",children:[o.jsx(pw,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),o.jsxs(Z,{variant:d==="analytics"?"secondary":"ghost",size:"sm",onClick:()=>h("analytics"),className:"gap-2",children:[o.jsx(yy,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),o.jsxs(Z,{variant:d==="config"?"secondary":"ghost",size:"sm",onClick:()=>h("config"),className:"gap-2",children:[o.jsx(qd,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:"Configuration"})]})]}),o.jsx("div",{className:"h-6 w-px bg-border/50 mx-2 hidden sm:block"}),o.jsx(By,{}),o.jsx(Z,{variant:d==="account"?"secondary":"ghost",size:"sm",onClick:()=>h("account"),className:"text-muted-foreground hover:text-foreground p-0 w-8 h-8 rounded-full overflow-hidden border",title:"Account Settings",children:s.profile?.avatar_url?o.jsx("img",{src:s.profile.avatar_url,alt:"Profile",className:"w-full h-full object-cover"}):o.jsx(Yx,{className:"w-5 h-5"})}),o.jsx(Z,{variant:"ghost",size:"sm",onClick:W,className:"text-muted-foreground hover:text-foreground w-8 px-0",title:"Sign out",children:o.jsx(xw,{className:"w-4 h-4"})})]})]})}),o.jsxs("main",{className:"max-w-7xl mx-auto p-4 sm:p-8 mt-4 mb-12",children:[d==="dashboard"&&o.jsx(l2,{}),d==="config"&&o.jsx(d2,{}),d==="analytics"&&o.jsx(R2,{}),d==="account"&&o.jsx(p2,{})]}),o.jsx("footer",{className:"max-w-7xl mx-auto px-4 sm:px-8 pb-8 text-center sm:text-left",children:o.jsxs("p",{className:"text-[10px] font-medium text-muted-foreground/40 uppercase tracking-[0.2em]",children:["Email Automator ",o.jsx("span",{className:"mx-1",children:"•"})," v","2.9.0"]})}),s.error&&o.jsx("div",{className:"fixed bottom-20 left-4 right-4 sm:left-auto sm:right-4 sm:max-w-sm z-50",children:o.jsx("div",{className:"bg-destructive/10 border border-destructive/20 text-destructive p-4 rounded-lg",children:o.jsx("p",{className:"text-sm",children:s.error})})}),w&&S&&!D&&o.jsx(T2,{status:w,onDismiss:()=>E(!1),onLearnMore:B}),w&&o.jsx(A2,{open:j,onOpenChange:R,status:w}),o.jsx(C2,{})]})})}function O2({runId:s,accountEmail:a,isOpen:r,onOpenChange:l}){const[c,d]=x.useState([]),[h,m]=x.useState(!1);x.useEffect(()=>{r&&s&&y()},[r,s]);const y=async()=>{if(s){m(!0);try{const g=await ze.getRunEvents(s);g.data&&d(g.data.events)}catch(g){console.error("Failed to fetch run trace:",g)}finally{m(!1)}}},p=g=>{switch(g){case"analysis":return o.jsx($i,{className:"w-4 h-4 text-purple-500"});case"action":return o.jsx(Lo,{className:"w-4 h-4 text-emerald-500"});case"error":return o.jsx(Dr,{className:"w-4 h-4 text-red-500"});default:return o.jsx(Or,{className:"w-4 h-4 text-blue-500"})}};return o.jsx(gn,{open:r,onOpenChange:l,children:o.jsxs(yn,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs(ka,{className:"p-6 border-b",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(of,{className:"w-5 h-5 text-primary"}),o.jsx(Oa,{children:"Sync Run Trace"})]}),o.jsx(Ra,{children:a?`Full log for account: ${a}`:"Historical log for this synchronization run."})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:h?o.jsx("div",{className:"py-20 flex justify-center",children:o.jsx(qi,{text:"Loading trace..."})}):c.length===0?o.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:"No granular trace events found for this run."}):c.map((g,w)=>o.jsxs("div",{className:"relative pl-8",children:[w!==c.length-1&&o.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),o.jsx("div",{className:"absolute left-0 top-0 w-8 h-8 rounded-full border bg-background flex items-center justify-center z-10 shadow-sm",children:p(g.event_type)}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-foreground/70",children:g.agent_state}),g.emails?.subject&&o.jsxs("span",{className:"text-[10px] text-primary font-medium truncate max-w-[300px]",children:["Re: ",g.emails.subject]})]}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(kr,{className:"w-3 h-3"}),new Date(g.created_at).toLocaleTimeString()]})]}),o.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[g.event_type==="info"&&o.jsx("p",{className:"text-sm text-foreground/90",children:g.details?.message}),g.event_type==="analysis"&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("p",{className:"text-xs text-foreground italic leading-relaxed",children:['"',g.details?.summary,'"']}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:"text-[9px] bg-secondary px-1.5 py-0.5 rounded font-bold uppercase",children:g.details?.category}),g.details?.suggested_actions?.map(_=>o.jsx("span",{className:"text-[9px] bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 px-1.5 py-0.5 rounded border border-emerald-500/20 font-bold uppercase",children:_},_))]}),g.details?.usage&&o.jsxs("div",{className:"flex gap-3 pt-1.5 mt-1 border-t border-border/50 text-[9px] text-muted-foreground",children:[o.jsxs("span",{children:["In: ",o.jsx("b",{children:g.details.usage.prompt_tokens})]}),o.jsxs("span",{children:["Out: ",o.jsx("b",{children:g.details.usage.completion_tokens})]}),o.jsxs("span",{children:["Total: ",o.jsx("span",{className:"text-primary font-bold",children:g.details.usage.total_tokens})]})]})]}),g.event_type==="action"&&o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:["Executed: ",g.details?.action]}),o.jsx(lf,{className:"w-4 h-4 text-emerald-500"})]}),g.event_type==="error"&&o.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:g.details?.error})]})]})]},g.id))})]})})}function R2(){const{state:s,actions:a}=Br(),[r,l]=x.useState(null),[c,d]=x.useState(void 0),[h,m]=x.useState(!1);if(x.useEffect(()=>{a.fetchStats()},[]),!s.stats)return o.jsx(qi,{text:"Loading analytics..."});const y=(g,w)=>{l(g),d(w),m(!0)},{stats:p}=s;return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(yy,{className:"w-6 h-6 text-primary"}),"Analytics Dashboard"]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsx(Do,{title:"Total Emails",value:p.totalEmails,color:"primary"}),o.jsx(Do,{title:"Spam Caught",value:p.categoryCounts.spam||0,color:"destructive"}),o.jsx(Do,{title:"Actions Taken",value:Object.values(p.actionCounts).reduce((g,w)=>g+w,0)-(p.actionCounts.none||0),color:"emerald"}),o.jsx(Do,{title:"Accounts",value:p.accountCount,color:"blue"})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:"Email Categories"}),o.jsx("div",{className:"space-y-3",children:Object.entries(p.categoryCounts).map(([g,w])=>o.jsx("div",{className:"flex items-center gap-3",children:o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[o.jsx("span",{className:"capitalize",children:g}),o.jsx("span",{className:"text-muted-foreground",children:w})]}),o.jsx("div",{className:"h-2 bg-secondary rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${w/p.totalEmails*100}%`}})})]})},g))})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:"Actions Taken"}),o.jsx("div",{className:"space-y-3",children:Object.entries(p.actionCounts).map(([g,w])=>o.jsxs("div",{className:"flex items-center justify-between py-2 border-b last:border-0",children:[o.jsx("span",{className:"capitalize",children:g}),o.jsx("span",{className:"font-medium",children:w})]},g))})]})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:"Recent Sync Activity"}),p.recentSyncs.length===0?o.jsx("p",{className:"text-muted-foreground text-sm",children:"No sync activity yet"}):o.jsx("div",{className:"space-y-3",children:p.recentSyncs.map(g=>{const w=g.completed_at?Math.round((new Date(g.completed_at).getTime()-new Date(g.started_at).getTime())/1e3):null;return o.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between p-3 border rounded-lg hover:bg-secondary/30 transition-colors gap-3 cursor-pointer group",onClick:()=>y(g.id,g.email_accounts?.email_address),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:Oe("w-2.5 h-2.5 rounded-full",g.status==="success"?"bg-emerald-500":g.status==="failed"?"bg-destructive":"bg-yellow-500 shadow-[0_0_8px_rgba(234,179,8,0.5)] animate-pulse")}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"text-sm font-medium group-hover:text-primary transition-colors",children:g.email_accounts?.email_address||"System Sync"}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(kr,{className:"w-3 h-3"}),new Date(g.started_at).toLocaleString(),w!==null&&o.jsxs("span",{className:"ml-2 px-1.5 py-0.5 bg-secondary rounded-full",children:[w,"s"]})]})]})]}),o.jsx("div",{className:"flex items-center gap-4 text-xs",children:o.jsxs("div",{className:"flex flex-col items-end",children:[o.jsxs("span",{className:"font-bold text-primary",children:[g.emails_processed," emails"]}),o.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[g.emails_deleted," deleted, ",g.emails_drafted," drafted"]})]})})]},g.id)})})]}),o.jsx(O2,{runId:r,accountEmail:c,isOpen:h,onOpenChange:m})]})}function Do({title:s,value:a,color:r}){const l={primary:"bg-primary/10 text-primary",destructive:"bg-destructive/10 text-destructive",emerald:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",blue:"bg-blue-500/10 text-blue-600 dark:text-blue-400"};return o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:s}),o.jsx("p",{className:`text-3xl font-bold ${l[r]||""}`,children:a})]})}function D2(){return o.jsx(l_,{defaultTheme:"system",storageKey:"email-automator-theme",children:o.jsx(aN,{children:o.jsx(tN,{children:o.jsxs(Fj,{children:[o.jsx(k2,{}),o.jsx(Qj,{})]})})})})}fx.createRoot(document.getElementById("root")).render(o.jsx(my.StrictMode,{children:o.jsx(D2,{})}));
97
+ scoop install supabase`})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-sm font-medium",children:"NPM (Universal)"}),o.jsx(Ro,{code:"npm install -g supabase"})]})]})]}),o.jsxs("div",{children:[o.jsxs("h4",{className:"mb-3 flex items-center gap-2 font-semibold",children:[o.jsx("span",{className:"flex h-6 w-6 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:"3"}),"Run Migration"]}),o.jsxs("div",{className:"ml-8 space-y-3",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"Run the built-in migration tool:"}),o.jsx(Ro,{code:"npx email-automator migrate"})]})]})]}),o.jsxs(Wi,{className:"border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/20",children:[o.jsx(Rr,{className:"h-4 w-4 text-red-700 dark:text-red-600"}),o.jsxs(el,{children:[o.jsx("strong",{children:"Troubleshooting"}),o.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[o.jsxs("li",{children:["Try logging out: ",o.jsx("code",{children:"supabase logout"})]}),o.jsx("li",{children:"Verify your database password is correct"})]})]})]})]}),o.jsx(Er,{children:o.jsx(Z,{type:"button",variant:"outline",onClick:()=>a(!1),disabled:h,children:"Close"})})]})})}function C2(){const[s,a]=x.useState([]),{isExpanded:r,setIsExpanded:l}=cv(),[c,d]=x.useState({});x.useEffect(()=>{h();const g=ct.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},w=>{const _=w.new;_.event_type==="error"&&d(S=>({...S,[_.id]:!0})),a(S=>{const E=[_,...S];return E.length>100?E.slice(0,100):E})}).subscribe();return()=>{ct.removeChannel(g)}},[]);const h=async()=>{const{data:g}=await ct.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(50);g&&a(g)},m=g=>{d(w=>({...w,[g]:!w[g]}))},y=g=>{if(g.details?.is_completion)return o.jsx(Hi,{className:"w-3 h-3 text-emerald-500"});switch(g.event_type){case"analysis":return o.jsx($i,{className:"w-3 h-3 text-purple-500"});case"action":return o.jsx(Lo,{className:"w-3 h-3 text-emerald-500"});case"error":return o.jsx(Rr,{className:"w-3 h-3 text-red-500"});default:return o.jsx(Or,{className:"w-3 h-3 text-blue-500"})}},p=g=>new Date(g).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});return r?o.jsxs(At,{className:"fixed bottom-4 right-4 z-50 w-[550px] h-[650px] flex flex-col shadow-2xl border-border bg-background/95 text-foreground backdrop-blur-md animate-in slide-in-from-bottom-10",children:[o.jsxs(Ta,{className:"py-3 px-4 border-b border-border flex flex-row items-center justify-between sticky top-0 bg-background/95 z-20",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Hd,{className:"w-4 h-4 text-primary"}),o.jsx(Aa,{className:"text-sm font-mono font-bold",children:"Agent Terminal"}),o.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-green-600 dark:text-green-400 bg-green-500/10 px-2 py-0.5 rounded-full border border-green-500/20 font-bold",children:[o.jsx(bx,{className:"w-3 h-3"}),"LIVE"]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 text-[10px] font-mono hover:bg-secondary",onClick:()=>a([]),children:"Clear"}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-secondary",onClick:()=>l(!1),children:o.jsx(Sw,{className:"w-4 h-4"})})]})]}),o.jsxs(Ca,{className:"flex-1 overflow-y-auto p-4 font-mono text-xs space-y-6 custom-scrollbar",children:[s.length===0&&o.jsx("div",{className:"text-center text-muted-foreground py-20 italic",children:"Waiting for agent activity..."}),s.map((g,w)=>o.jsxs("div",{className:"relative pl-8 animate-in fade-in slide-in-from-top-2 duration-300",children:[w!==s.length-1&&o.jsx("div",{className:"absolute left-[13px] top-7 bottom-[-24px] w-[1px] bg-border"}),o.jsx("div",{className:Oe("absolute left-0 top-0 w-7 h-7 rounded-full border border-border bg-card flex items-center justify-center z-10 shadow-sm",g.event_type==="error"&&"border-red-500/50 bg-red-500/5",g.event_type==="analysis"&&"border-purple-500/50 bg-purple-500/5",g.event_type==="action"&&"border-emerald-500/50 bg-emerald-500/5",g.details?.is_completion&&"border-emerald-500/50 bg-emerald-500/5"),children:y(g)}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs("div",{className:"flex items-center justify-between group",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:Oe("font-bold uppercase tracking-tight text-[10px]",g.event_type==="info"&&"text-muted-foreground",g.event_type==="analysis"&&"text-purple-600 dark:text-purple-400",g.event_type==="action"&&"text-emerald-600 dark:text-emerald-400",g.event_type==="error"&&"text-red-600 dark:text-red-400"),children:g.agent_state}),o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:p(g.created_at)})]}),(g.details?.system_prompt||g.details?._raw_response||g.details?.raw_response)&&o.jsxs(Z,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[9px] text-muted-foreground hover:text-primary opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>m(g.id),children:[c[g.id]?o.jsx(Vx,{className:"w-3 h-3 mr-1"}):o.jsx(Ux,{className:"w-3 h-3 mr-1"}),"Details"]})]}),g.event_type==="analysis"&&g.details?o.jsxs("div",{className:"bg-purple-500/5 border border-purple-500/10 rounded-lg p-3 space-y-2",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:Oe("px-1.5 py-0.5 rounded text-[9px] font-bold border",g.details.is_useless?"bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20":"bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/20"),children:g.details.is_useless?"USELESS":"RELEVANT"}),o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-bold border bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20 uppercase",children:g.details.category})]}),o.jsxs("p",{className:"text-foreground/90 italic leading-relaxed",children:['"',g.details.summary,'"']}),g.details.suggested_actions&&g.details.suggested_actions.length>0&&o.jsx("div",{className:"pt-1 flex items-center gap-2 flex-wrap",children:g.details.suggested_actions.map(_=>o.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-emerald-600 dark:text-emerald-400 font-bold bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20 uppercase",children:[o.jsx(Lo,{className:"w-2.5 h-2.5"}),_]},_))}),g.details.usage&&o.jsx("div",{className:"pt-1.5 flex items-center gap-3 text-[9px] text-muted-foreground/70 border-t border-purple-500/10 mt-1",children:o.jsxs("span",{children:["Tokens: ",g.details.usage.prompt_tokens," (in) + ",g.details.usage.completion_tokens," (out) = ",o.jsx("span",{className:"text-purple-500 font-bold",children:g.details.usage.total_tokens})]})})]}):g.event_type==="action"&&g.details?o.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/10 rounded-lg p-3",children:[o.jsx("p",{className:"text-emerald-600 dark:text-emerald-400 font-bold mb-1 uppercase text-[9px] tracking-widest",children:"Execution Complete"}),o.jsxs("p",{className:"text-foreground font-medium",children:[g.details.action==="delete"&&"Moved to Trash",g.details.action==="archive"&&"Archived Email",g.details.action==="draft"&&"Drafted Reply",g.details.action==="read"&&"Marked as Read",g.details.action==="star"&&"Starred Email",!["delete","archive","draft","read","star"].includes(g.details.action)&&g.details.action]}),g.details.reason&&o.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 flex items-center gap-1",children:[o.jsx(Or,{className:"w-3 h-3"}),g.details.reason]})]}):g.event_type==="error"&&g.details?o.jsx("div",{className:"bg-red-500/5 border border-red-500/10 rounded-lg p-2.5 text-red-600 dark:text-red-400 font-medium",children:typeof g.details.error=="object"?g.details.error.message||JSON.stringify(g.details.error):g.details.error}):g.details?.is_completion?o.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-lg p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 dark:text-emerald-400 font-bold uppercase text-[9px] tracking-[0.2em]",children:[o.jsx(Hi,{className:"w-3.5 h-3.5"}),"Batch Sync Finished"]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-1",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Processed"}),o.jsx("p",{className:"text-sm font-bold",children:g.details.total_processed||0})]}),o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Actions"}),o.jsx("p",{className:"text-sm font-bold text-emerald-500",children:(g.details.deleted||0)+(g.details.drafted||0)})]})]}),g.details.errors>0&&o.jsxs("p",{className:"text-[10px] text-red-500 font-bold pt-1 border-t border-emerald-500/10",children:["⚠️ ",g.details.errors," items failed to process."]})]}):o.jsx("p",{className:"text-muted-foreground leading-relaxed",children:g.details?.message||JSON.stringify(g.details)}),c[g.id]&&o.jsxs("div",{className:"mt-2 space-y-3 animate-in fade-in zoom-in-95 duration-200",children:[g.details?.system_prompt&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Us,{className:"w-3 h-3"})," System Prompt"]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"whitespace-pre-wrap break-words text-[10px] leading-normal text-muted-foreground select-all",children:g.details.system_prompt})})]}),g.details?.content_preview&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Input Content (Cleaned)"]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border",children:o.jsx("p",{className:"whitespace-pre-wrap break-words text-[10px] text-muted-foreground",children:g.details.content_preview})})]}),g.details?._raw_response&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Raw LLM JSON Output"]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"text-[10px] text-muted-foreground select-all",children:JSON.stringify(JSON.parse(g.details._raw_response),null,2)})})]}),g.details?.raw_response&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Us,{className:"w-3 h-3"})," Raw Response (from Error)"]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"text-[10px] text-muted-foreground select-all whitespace-pre-wrap",children:typeof g.details.raw_response=="object"?JSON.stringify(g.details.raw_response,null,2):g.details.raw_response})})]})]})]})]},g.id))]})]}):o.jsx("div",{className:"fixed bottom-4 right-4 z-50",children:o.jsxs(Z,{onClick:()=>l(!0),className:"shadow-lg bg-primary text-primary-foreground hover:opacity-90 border border-border",children:[o.jsx(Hd,{className:"w-4 h-4 mr-2"}),"Live Activity",s.length>0&&o.jsxs("span",{className:"ml-2 flex h-2 w-2 relative",children:[o.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-green-500"})]})]})})}function k2(){const{state:s,isSubscribed:a,actions:r}=Br(),[l,c]=x.useState(!1),[d,h]=x.useState("dashboard"),[m,y]=x.useState(!0),[p,g]=x.useState(!1);if(x.useEffect(()=>{const J=()=>{if(Ea.isEnabled()){const P=new(window.AudioContext||window.webkitAudioContext);P.state==="suspended"&&P.resume()}window.removeEventListener("click",J),window.removeEventListener("keydown",J)};return window.addEventListener("click",J),window.addEventListener("keydown",J),()=>{window.removeEventListener("click",J),window.removeEventListener("keydown",J)}},[]),x.useEffect(()=>{const P=new URLSearchParams(window.location.search).get("code");P&&!p&&(async()=>{g(!0);try{const ce=await ze.connectGmail(P);if(ce.data?.success)te.success("Gmail connected successfully!"),window.opener?setTimeout(()=>window.close(),1500):(window.history.replaceState({},"",window.location.pathname),r.fetchAccounts());else{const Je=typeof ce.error=="string"?ce.error:ce.error?.message;te.error(Je||"Failed to connect Gmail")}}catch{te.error("Connection failed")}finally{g(!1)}})()},[]),p)return o.jsx(qi,{text:"Connecting account..."});const[w,_]=x.useState(null),[S,E]=x.useState(!1),[j,R]=x.useState(!1),[D,q]=x.useState(!1);x.useEffect(()=>{(async()=>{const P=Lr();if(!P){c(!0),y(!1);return}if((await av(P.url,P.anonKey)).valid)s.isInitialized&&s.isAuthenticated&&(r.fetchAccounts(),r.fetchRules(),r.fetchSettings(),r.fetchProfile(),j2(ct).then(ce=>{_(ce),ce.needsMigration&&!N2()&&E(!0)}));else{c(!0),y(!1);return}y(!1)})()},[s.isInitialized,s.isAuthenticated]);const B=()=>{R(!0),E(!1)},G={migrationStatus:w,showMigrationBanner:S,showMigrationModal:j,openMigrationModal:B,suppressMigrationBanner:D,setSuppressMigrationBanner:q};if(m)return o.jsx(qi,{text:"Checking configuration..."});if(l)return o.jsx(Vv,{onComplete:()=>{c(!1),window.location.reload()}});if(!s.isInitialized)return o.jsx(qi,{text:"Initializing..."});if(!s.isAuthenticated)return o.jsx(x2,{onConfigure:()=>c(!0)});const W=async()=>{await ct.auth.signOut(),te.success("Logged out successfully")};return o.jsx(eN,{value:G,children:o.jsxs("div",{className:"min-h-screen bg-background font-sans text-foreground transition-colors duration-300",children:[o.jsx("header",{className:"sticky top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60",children:o.jsxs("div",{className:"max-w-7xl mx-auto flex h-16 items-center justify-between px-4 sm:px-8",children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("button",{onClick:()=>h("dashboard"),className:"text-xl font-bold flex items-center gap-2 hover:opacity-80 transition-opacity",children:[o.jsx(vf,{className:"w-8 h-8"}),o.jsx("span",{className:"hidden sm:inline",children:"Email Automator"}),o.jsx("span",{className:"sm:hidden",children:"Email AI"})]}),o.jsxs("div",{className:Oe("flex items-center gap-1.5 px-2 h-6 rounded-full text-[10px] font-bold border transition-colors",a?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20 dark:text-emerald-400":"bg-yellow-500/10 text-yellow-600 border-yellow-500/20 dark:text-yellow-400"),children:[o.jsxs("div",{className:"relative flex items-center justify-center",children:[a&&o.jsx("span",{className:"absolute inline-flex h-3 w-3 rounded-full bg-emerald-500/40 animate-ping"}),o.jsx("div",{className:Oe("relative w-2 h-2 rounded-full",a?"bg-emerald-500":"bg-yellow-500")})]}),o.jsx("span",{className:"hidden xs:inline leading-none",children:a?"LIVE":"OFFLINE"})]})]}),o.jsxs("div",{className:"flex gap-4 items-center",children:[o.jsxs("nav",{className:"flex items-center gap-1 bg-secondary/50 p-1 rounded-lg",children:[o.jsxs(Z,{variant:d==="dashboard"?"secondary":"ghost",size:"sm",onClick:()=>h("dashboard"),className:"gap-2",children:[o.jsx(pw,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),o.jsxs(Z,{variant:d==="analytics"?"secondary":"ghost",size:"sm",onClick:()=>h("analytics"),className:"gap-2",children:[o.jsx(yy,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),o.jsxs(Z,{variant:d==="config"?"secondary":"ghost",size:"sm",onClick:()=>h("config"),className:"gap-2",children:[o.jsx(qd,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:"Configuration"})]})]}),o.jsx("div",{className:"h-6 w-px bg-border/50 mx-2 hidden sm:block"}),o.jsx(By,{}),o.jsx(Z,{variant:d==="account"?"secondary":"ghost",size:"sm",onClick:()=>h("account"),className:"text-muted-foreground hover:text-foreground p-0 w-8 h-8 rounded-full overflow-hidden border",title:"Account Settings",children:s.profile?.avatar_url?o.jsx("img",{src:s.profile.avatar_url,alt:"Profile",className:"w-full h-full object-cover"}):o.jsx(Yx,{className:"w-5 h-5"})}),o.jsx(Z,{variant:"ghost",size:"sm",onClick:W,className:"text-muted-foreground hover:text-foreground w-8 px-0",title:"Sign out",children:o.jsx(xw,{className:"w-4 h-4"})})]})]})}),o.jsxs("main",{className:"max-w-7xl mx-auto p-4 sm:p-8 mt-4 mb-12",children:[d==="dashboard"&&o.jsx(l2,{}),d==="config"&&o.jsx(d2,{}),d==="analytics"&&o.jsx(R2,{}),d==="account"&&o.jsx(p2,{})]}),o.jsx("footer",{className:"max-w-7xl mx-auto px-4 sm:px-8 pb-8 text-center sm:text-left",children:o.jsxs("p",{className:"text-[10px] font-medium text-muted-foreground/40 uppercase tracking-[0.2em]",children:["Email Automator ",o.jsx("span",{className:"mx-1",children:"•"})," v","2.9.3"]})}),s.error&&o.jsx("div",{className:"fixed bottom-20 left-4 right-4 sm:left-auto sm:right-4 sm:max-w-sm z-50",children:o.jsx("div",{className:"bg-destructive/10 border border-destructive/20 text-destructive p-4 rounded-lg",children:o.jsx("p",{className:"text-sm",children:s.error})})}),w&&S&&!D&&o.jsx(T2,{status:w,onDismiss:()=>E(!1),onLearnMore:B}),w&&o.jsx(A2,{open:j,onOpenChange:R,status:w}),o.jsx(C2,{})]})})}function O2({runId:s,accountEmail:a,isOpen:r,onOpenChange:l}){const[c,d]=x.useState([]),[h,m]=x.useState(!1);x.useEffect(()=>{r&&s&&y()},[r,s]);const y=async()=>{if(s){m(!0);try{const g=await ze.getRunEvents(s);g.data&&d(g.data.events)}catch(g){console.error("Failed to fetch run trace:",g)}finally{m(!1)}}},p=g=>{switch(g){case"analysis":return o.jsx($i,{className:"w-4 h-4 text-purple-500"});case"action":return o.jsx(Lo,{className:"w-4 h-4 text-emerald-500"});case"error":return o.jsx(Dr,{className:"w-4 h-4 text-red-500"});default:return o.jsx(Or,{className:"w-4 h-4 text-blue-500"})}};return o.jsx(gn,{open:r,onOpenChange:l,children:o.jsxs(yn,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs(ka,{className:"p-6 border-b",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(of,{className:"w-5 h-5 text-primary"}),o.jsx(Oa,{children:"Sync Run Trace"})]}),o.jsx(Ra,{children:a?`Full log for account: ${a}`:"Historical log for this synchronization run."})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:h?o.jsx("div",{className:"py-20 flex justify-center",children:o.jsx(qi,{text:"Loading trace..."})}):c.length===0?o.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:"No granular trace events found for this run."}):c.map((g,w)=>o.jsxs("div",{className:"relative pl-8",children:[w!==c.length-1&&o.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),o.jsx("div",{className:"absolute left-0 top-0 w-8 h-8 rounded-full border bg-background flex items-center justify-center z-10 shadow-sm",children:p(g.event_type)}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-foreground/70",children:g.agent_state}),g.emails?.subject&&o.jsxs("span",{className:"text-[10px] text-primary font-medium truncate max-w-[300px]",children:["Re: ",g.emails.subject]})]}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(kr,{className:"w-3 h-3"}),new Date(g.created_at).toLocaleTimeString()]})]}),o.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[g.event_type==="info"&&o.jsx("p",{className:"text-sm text-foreground/90",children:g.details?.message}),g.event_type==="analysis"&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("p",{className:"text-xs text-foreground italic leading-relaxed",children:['"',g.details?.summary,'"']}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:"text-[9px] bg-secondary px-1.5 py-0.5 rounded font-bold uppercase",children:g.details?.category}),g.details?.suggested_actions?.map(_=>o.jsx("span",{className:"text-[9px] bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 px-1.5 py-0.5 rounded border border-emerald-500/20 font-bold uppercase",children:_},_))]}),g.details?.usage&&o.jsxs("div",{className:"flex gap-3 pt-1.5 mt-1 border-t border-border/50 text-[9px] text-muted-foreground",children:[o.jsxs("span",{children:["In: ",o.jsx("b",{children:g.details.usage.prompt_tokens})]}),o.jsxs("span",{children:["Out: ",o.jsx("b",{children:g.details.usage.completion_tokens})]}),o.jsxs("span",{children:["Total: ",o.jsx("span",{className:"text-primary font-bold",children:g.details.usage.total_tokens})]})]})]}),g.event_type==="action"&&o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:["Executed: ",g.details?.action]}),o.jsx(lf,{className:"w-4 h-4 text-emerald-500"})]}),g.event_type==="error"&&o.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:g.details?.error})]})]})]},g.id))})]})})}function R2(){const{state:s,actions:a}=Br(),[r,l]=x.useState(null),[c,d]=x.useState(void 0),[h,m]=x.useState(!1);if(x.useEffect(()=>{a.fetchStats()},[]),!s.stats)return o.jsx(qi,{text:"Loading analytics..."});const y=(g,w)=>{l(g),d(w),m(!0)},{stats:p}=s;return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(yy,{className:"w-6 h-6 text-primary"}),"Analytics Dashboard"]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsx(Do,{title:"Total Emails",value:p.totalEmails,color:"primary"}),o.jsx(Do,{title:"Spam Caught",value:p.categoryCounts.spam||0,color:"destructive"}),o.jsx(Do,{title:"Actions Taken",value:Object.values(p.actionCounts).reduce((g,w)=>g+w,0)-(p.actionCounts.none||0),color:"emerald"}),o.jsx(Do,{title:"Accounts",value:p.accountCount,color:"blue"})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:"Email Categories"}),o.jsx("div",{className:"space-y-3",children:Object.entries(p.categoryCounts).map(([g,w])=>o.jsx("div",{className:"flex items-center gap-3",children:o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[o.jsx("span",{className:"capitalize",children:g}),o.jsx("span",{className:"text-muted-foreground",children:w})]}),o.jsx("div",{className:"h-2 bg-secondary rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${w/p.totalEmails*100}%`}})})]})},g))})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:"Actions Taken"}),o.jsx("div",{className:"space-y-3",children:Object.entries(p.actionCounts).map(([g,w])=>o.jsxs("div",{className:"flex items-center justify-between py-2 border-b last:border-0",children:[o.jsx("span",{className:"capitalize",children:g}),o.jsx("span",{className:"font-medium",children:w})]},g))})]})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:"Recent Sync Activity"}),p.recentSyncs.length===0?o.jsx("p",{className:"text-muted-foreground text-sm",children:"No sync activity yet"}):o.jsx("div",{className:"space-y-3",children:p.recentSyncs.map(g=>{const w=g.completed_at?Math.round((new Date(g.completed_at).getTime()-new Date(g.started_at).getTime())/1e3):null;return o.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between p-3 border rounded-lg hover:bg-secondary/30 transition-colors gap-3 cursor-pointer group",onClick:()=>y(g.id,g.email_accounts?.email_address),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:Oe("w-2.5 h-2.5 rounded-full",g.status==="success"?"bg-emerald-500":g.status==="failed"?"bg-destructive":"bg-yellow-500 shadow-[0_0_8px_rgba(234,179,8,0.5)] animate-pulse")}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"text-sm font-medium group-hover:text-primary transition-colors",children:g.email_accounts?.email_address||"System Sync"}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(kr,{className:"w-3 h-3"}),new Date(g.started_at).toLocaleString(),w!==null&&o.jsxs("span",{className:"ml-2 px-1.5 py-0.5 bg-secondary rounded-full",children:[w,"s"]})]})]})]}),o.jsx("div",{className:"flex items-center gap-4 text-xs",children:o.jsxs("div",{className:"flex flex-col items-end",children:[o.jsxs("span",{className:"font-bold text-primary",children:[g.emails_processed," emails"]}),o.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[g.emails_deleted," deleted, ",g.emails_drafted," drafted"]})]})})]},g.id)})})]}),o.jsx(O2,{runId:r,accountEmail:c,isOpen:h,onOpenChange:m})]})}function Do({title:s,value:a,color:r}){const l={primary:"bg-primary/10 text-primary",destructive:"bg-destructive/10 text-destructive",emerald:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",blue:"bg-blue-500/10 text-blue-600 dark:text-blue-400"};return o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:s}),o.jsx("p",{className:`text-3xl font-bold ${l[r]||""}`,children:a})]})}function D2(){return o.jsx(l_,{defaultTheme:"system",storageKey:"email-automator-theme",children:o.jsx(aN,{children:o.jsx(tN,{children:o.jsxs(Fj,{children:[o.jsx(k2,{}),o.jsx(Qj,{})]})})})})}fx.createRoot(document.getElementById("root")).render(o.jsx(my.StrictMode,{children:o.jsx(D2,{})}));
package/dist/index.html CHANGED
@@ -5,7 +5,7 @@
5
5
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>Email Automator</title>
8
- <script type="module" crossorigin src="/assets/index-fpSQFV7a.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-C05BXD6C.js"></script>
9
9
  <link rel="stylesheet" crossorigin href="/assets/index-BXVbfEhG.css">
10
10
  </head>
11
11
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@realtimex/email-automator",
3
- "version": "2.9.0",
3
+ "version": "2.9.3",
4
4
  "type": "module",
5
5
  "main": "dist/api/server.js",
6
6
  "bin": {