@realtimex/email-automator 2.22.1 → 2.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/api/src/lib/setup-knowledge.generated.ts +2 -1
  2. package/api/src/routes/agent.ts +1 -0
  3. package/api/src/services/AgentService.ts +2 -0
  4. package/api/src/services/RAGService.ts +26 -3
  5. package/dist/api/src/lib/setup-knowledge.generated.js +2 -1
  6. package/dist/api/src/routes/agent.js +1 -0
  7. package/dist/api/src/services/AgentService.js +1 -0
  8. package/dist/api/src/services/RAGService.js +23 -4
  9. package/dist/assets/es-NQpkAluz.js +49 -0
  10. package/dist/assets/fr-Dt1serdG.js +49 -0
  11. package/dist/assets/{index-y96M9yNt.js → index-DR7Pa16U.js} +51 -41
  12. package/dist/assets/ja-46nRzsm5.js +49 -0
  13. package/dist/assets/ko-DUNCzc8F.js +49 -0
  14. package/dist/assets/vi-CA9x3uPA.js +49 -0
  15. package/dist/index.html +1 -1
  16. package/docs/README.md +9 -18
  17. package/docs/en/README.md +23 -0
  18. package/docs/{marketplace → en/marketplace}/listing.md +1 -1
  19. package/docs/{user-guide → en/user-guide}/GETTING-STARTED.md +2 -1
  20. package/docs/en/user-guide/GLOSSARY.md +163 -0
  21. package/docs/es/README.md +23 -0
  22. package/docs/es/marketplace/listing.md +34 -0
  23. package/docs/es/user-guide/ACCOUNT.md +52 -0
  24. package/docs/es/user-guide/AUTOMATION.md +93 -0
  25. package/docs/es/user-guide/CONFIGURATION.md +61 -0
  26. package/docs/es/user-guide/DASHBOARD.md +71 -0
  27. package/docs/es/user-guide/GETTING-STARTED.md +61 -0
  28. package/docs/es/user-guide/GLOSSARY.md +160 -0
  29. package/docs/es/user-guide/TROUBLESHOOTING.md +65 -0
  30. package/docs/fr/README.md +23 -0
  31. package/docs/fr/marketplace/listing.md +34 -0
  32. package/docs/fr/user-guide/ACCOUNT.md +52 -0
  33. package/docs/fr/user-guide/AUTOMATION.md +93 -0
  34. package/docs/fr/user-guide/CONFIGURATION.md +61 -0
  35. package/docs/fr/user-guide/DASHBOARD.md +71 -0
  36. package/docs/fr/user-guide/GETTING-STARTED.md +61 -0
  37. package/docs/fr/user-guide/GLOSSARY.md +160 -0
  38. package/docs/fr/user-guide/TROUBLESHOOTING.md +65 -0
  39. package/docs/ja/README.md +23 -0
  40. package/docs/ja/marketplace/listing.md +34 -0
  41. package/docs/ja/user-guide/ACCOUNT.md +52 -0
  42. package/docs/ja/user-guide/AUTOMATION.md +93 -0
  43. package/docs/ja/user-guide/CONFIGURATION.md +61 -0
  44. package/docs/ja/user-guide/DASHBOARD.md +71 -0
  45. package/docs/ja/user-guide/GETTING-STARTED.md +61 -0
  46. package/docs/ja/user-guide/GLOSSARY.md +160 -0
  47. package/docs/ja/user-guide/TROUBLESHOOTING.md +65 -0
  48. package/docs/ko/README.md +23 -0
  49. package/docs/ko/marketplace/listing.md +34 -0
  50. package/docs/ko/user-guide/ACCOUNT.md +52 -0
  51. package/docs/ko/user-guide/AUTOMATION.md +93 -0
  52. package/docs/ko/user-guide/CONFIGURATION.md +61 -0
  53. package/docs/ko/user-guide/DASHBOARD.md +71 -0
  54. package/docs/ko/user-guide/GETTING-STARTED.md +61 -0
  55. package/docs/ko/user-guide/GLOSSARY.md +160 -0
  56. package/docs/ko/user-guide/TROUBLESHOOTING.md +65 -0
  57. package/docs/vi/README.md +23 -0
  58. package/docs/vi/marketplace/listing.md +34 -0
  59. package/docs/vi/user-guide/ACCOUNT.md +52 -0
  60. package/docs/vi/user-guide/AUTOMATION.md +93 -0
  61. package/docs/vi/user-guide/CONFIGURATION.md +61 -0
  62. package/docs/vi/user-guide/DASHBOARD.md +71 -0
  63. package/docs/vi/user-guide/GETTING-STARTED.md +61 -0
  64. package/docs/vi/user-guide/GLOSSARY.md +160 -0
  65. package/docs/vi/user-guide/TROUBLESHOOTING.md +65 -0
  66. package/package.json +1 -1
  67. package/scripts/build-setup-knowledge.ts +1 -1
  68. package/scripts/ingest-knowledge-rag.ts +42 -26
  69. package/supabase/migrations/20260203150000_add_lang_to_knowledge_chunks.sql +49 -0
  70. package/dist/assets/es-BySeIenb.js +0 -4
  71. package/dist/assets/fr-Cj4xUTOj.js +0 -4
  72. package/dist/assets/ja-DeBZHkY-.js +0 -4
  73. package/dist/assets/ko-CHMiWHbo.js +0 -4
  74. package/dist/assets/vi-B4Rp8hRI.js +0 -4
  75. /package/docs/{user-guide → en/user-guide}/ACCOUNT.md +0 -0
  76. /package/docs/{user-guide → en/user-guide}/AUTOMATION.md +0 -0
  77. /package/docs/{user-guide → en/user-guide}/CONFIGURATION.md +0 -0
  78. /package/docs/{user-guide → en/user-guide}/DASHBOARD.md +0 -0
  79. /package/docs/{user-guide → en/user-guide}/TROUBLESHOOTING.md +0 -0
@@ -56,11 +56,56 @@ ${N}`}class It extends Error{constructor({message:t,code:n,cause:s,name:a}){var
56
56
  ${N}px !important;
57
57
  ${R}px !important;
58
58
  }
59
- `),()=>{D.contains(T)&&D.removeChild(T)}},[t]),o.jsx(WP,{isPresent:t,childRef:u,sizeRef:d,children:S.cloneElement(e,{ref:p})})}const JP=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:a,presenceAffectsLayout:l,mode:u,anchorX:d,anchorY:h,root:m})=>{const p=Eg(QP),g=S.useId();let v=!0,b=S.useMemo(()=>(v=!1,{id:g,initial:t,isPresent:n,custom:a,onExitComplete:w=>{p.set(w,!0);for(const j of p.values())if(!j)return;s&&s()},register:w=>(p.set(w,!1),()=>p.delete(w))}),[n,p,s]);return l&&v&&(b={...b}),S.useMemo(()=>{p.forEach((w,j)=>p.set(j,!1))},[n]),S.useEffect(()=>{!n&&!p.size&&s&&s()},[n]),u==="popLayout"&&(e=o.jsx(XP,{isPresent:n,anchorX:d,anchorY:h,root:m,children:e})),o.jsx(jd.Provider,{value:b,children:e})};function QP(){return new Map}function hk(e=!0){const t=S.useContext(jd);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:a}=t,l=S.useId();S.useEffect(()=>{if(e)return a(l)},[e]);const u=S.useCallback(()=>e&&s&&s(l),[l,s,e]);return!n&&s?[!1,u]:[!0]}const ku=e=>e.key||"";function w1(e){const t=[];return S.Children.forEach(e,n=>{S.isValidElement(n)&&t.push(n)}),t}const mk=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:a=!0,mode:l="sync",propagate:u=!1,anchorX:d="left",anchorY:h="top",root:m})=>{const[p,g]=hk(u),v=S.useMemo(()=>w1(e),[e]),b=u&&!p?[]:v.map(ku),w=S.useRef(!0),j=S.useRef(v),k=Eg(()=>new Map),N=S.useRef(new Set),[R,T]=S.useState(v),[D,U]=S.useState(v);H_(()=>{w.current=!1,j.current=v;for(let P=0;P<D.length;P++){const H=ku(D[P]);b.includes(H)?(k.delete(H),N.current.delete(H)):k.get(H)!==!0&&k.set(H,!1)}},[D,b.length,b.join("-")]);const M=[];if(v!==R){let P=[...v];for(let H=0;H<D.length;H++){const O=D[H],Q=ku(O);b.includes(Q)||(P.splice(H,0,O),M.push(O))}return l==="wait"&&M.length&&(P=M),U(w1(P)),T(v),null}const{forceRender:B}=S.useContext(Tg);return o.jsx(o.Fragment,{children:D.map(P=>{const H=ku(P),O=u&&!p?!1:v===D||b.includes(H),Q=()=>{if(N.current.has(H))return;if(N.current.add(H),k.has(H))k.set(H,!0);else return;let G=!0;k.forEach(he=>{he||(G=!1)}),G&&(B?.(),U(j.current),u&&g?.(),s&&s())};return o.jsx(JP,{isPresent:O,initial:!w.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:l,root:m,onExitComplete:O?void 0:Q,anchorX:d,anchorY:h,children:P},H)})})},pk=S.createContext({strict:!1}),S1={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let _1=!1;function ZP(){if(_1)return;const e={};for(const t in S1)e[t]={isEnabled:n=>S1[t].some(s=>!!n[s])};qj(e),_1=!0}function gk(){return ZP(),U3()}function ez(e){const t=gk();for(const n in e)t[n]={...t[n],...e[n]};qj(t)}const tz=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function ud(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||tz.has(e)}let yk=e=>!ud(e);function nz(e){typeof e=="function"&&(yk=t=>t.startsWith("on")?!ud(t):e(t))}try{nz(require("@emotion/is-prop-valid").default)}catch{}function rz(e,t,n){const s={};for(const a in e)a==="values"&&typeof e.values=="object"||(yk(a)||n===!0&&ud(a)||!t&&!ud(a)||e.draggable&&a.startsWith("onDrag"))&&(s[a]=e[a]);return s}const Td=S.createContext({});function sz(e,t){if(Nd(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Bl(n)?n:void 0,animate:Bl(s)?s:void 0}}return e.inherit!==!1?t:{}}function iz(e){const{initial:t,animate:n}=sz(e,S.useContext(Td));return S.useMemo(()=>({initial:t,animate:n}),[j1(t),j1(n)])}function j1(e){return Array.isArray(e)?e.join(" "):e}const ry=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function xk(e,t,n){for(const s in t)!an(t[s])&&!Xj(s,n)&&(e[s]=t[s])}function az({transformTemplate:e},t){return S.useMemo(()=>{const n=ry();return ey(n,t,e),Object.assign({},n.vars,n.style)},[t])}function oz(e,t){const n=e.style||{},s={};return xk(s,n,e),Object.assign(s,az(e,t)),s}function lz(e,t){const n={},s=oz(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const vk=()=>({...ry(),attrs:{}});function cz(e,t,n,s){const a=S.useMemo(()=>{const l=vk();return Jj(l,t,Zj(s),e.transformTemplate,e.style),{...l.attrs,style:{...l.style}}},[t]);if(e.style){const l={};xk(l,e.style,e),a.style={...l,...a.style}}return a}const uz=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function sy(e){return typeof e!="string"||e.includes("-")?!1:!!(uz.indexOf(e)>-1||/[A-Z]/u.test(e))}function dz(e,t,n,{latestValues:s},a,l=!1,u){const h=(u??sy(e)?cz:lz)(t,s,a,e),m=rz(t,typeof e=="string",l),p=e!==S.Fragment?{...m,...h,ref:n}:{},{children:g}=t,v=S.useMemo(()=>an(g)?g.get():g,[g]);return S.createElement(e,{...p,children:v})}function fz({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,a){return{latestValues:hz(n,s,a,e),renderState:t()}}function hz(e,t,n,s){const a={},l=s(e,{});for(const v in l)a[v]=$u(l[v]);let{initial:u,animate:d}=e;const h=Nd(e),m=Fj(e);t&&m&&!h&&e.inherit!==!1&&(u===void 0&&(u=t.initial),d===void 0&&(d=t.animate));let p=n?n.initial===!1:!1;p=p||u===!1;const g=p?d:u;if(g&&typeof g!="boolean"&&!kd(g)){const v=Array.isArray(g)?g:[g];for(let b=0;b<v.length;b++){const w=Kg(e,v[b]);if(w){const{transitionEnd:j,transition:k,...N}=w;for(const R in N){let T=N[R];if(Array.isArray(T)){const D=p?T.length-1:0;T=T[D]}T!==null&&(a[R]=T)}for(const R in j)a[R]=j[R]}}}return a}const bk=e=>(t,n)=>{const s=S.useContext(Td),a=S.useContext(jd),l=()=>fz(e,t,s,a);return n?l():Eg(l)},mz=bk({scrapeMotionValuesFromProps:ty,createRenderState:ry}),pz=bk({scrapeMotionValuesFromProps:ek,createRenderState:vk}),gz=Symbol.for("motionComponentSymbol");function yz(e,t,n){const s=S.useRef(n);S.useInsertionEffect(()=>{s.current=n});const a=S.useRef(null);return S.useCallback(l=>{l&&e.onMount?.(l),t&&(l?t.mount(l):t.unmount());const u=s.current;if(typeof u=="function")if(l){const d=u(l);typeof d=="function"&&(a.current=d)}else a.current?(a.current(),a.current=null):u(l);else u&&(u.current=l)},[t])}const wk=S.createContext({});function yl(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function xz(e,t,n,s,a,l){const{visualElement:u}=S.useContext(Td),d=S.useContext(pk),h=S.useContext(jd),m=S.useContext(ny).reducedMotion,p=S.useRef(null),g=S.useRef(!1);s=s||d.renderer,!p.current&&s&&(p.current=s(e,{visualState:t,parent:u,props:n,presenceContext:h,blockInitialAnimation:h?h.initial===!1:!1,reducedMotionConfig:m,isSVG:l}),g.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const v=p.current,b=S.useContext(wk);v&&!v.projection&&a&&(v.type==="html"||v.type==="svg")&&vz(p.current,n,a,b);const w=S.useRef(!1);S.useInsertionEffect(()=>{v&&w.current&&v.update(n,h)});const j=n[Ej],k=S.useRef(!!j&&!window.MotionHandoffIsComplete?.(j)&&window.MotionHasOptimisedAnimation?.(j));return H_(()=>{g.current=!0,v&&(w.current=!0,window.MotionIsMounted=!0,v.updateFeatures(),v.scheduleRenderMicrotask(),k.current&&v.animationState&&v.animationState.animateChanges())}),S.useEffect(()=>{v&&(!k.current&&v.animationState&&v.animationState.animateChanges(),k.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(j)}),k.current=!1),v.enteringChildren=void 0)}),v}function vz(e,t,n,s){const{layoutId:a,layout:l,drag:u,dragConstraints:d,layoutScroll:h,layoutRoot:m,layoutCrossfade:p}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Sk(e.parent)),e.projection.setOptions({layoutId:a,layout:l,alwaysMeasureLayout:!!u||d&&yl(d),visualElement:e,animationType:typeof l=="string"?l:"both",initialPromotionConfig:s,crossfade:p,layoutScroll:h,layoutRoot:m})}function Sk(e){if(e)return e.options.allowProjection!==!1?e.projection:Sk(e.parent)}function jm(e,{forwardMotionProps:t=!1,type:n}={},s,a){s&&ez(s);const l=n?n==="svg":sy(e),u=l?pz:mz;function d(m,p){let g;const v={...S.useContext(ny),...m,layoutId:bz(m)},{isStatic:b}=v,w=iz(m),j=u(m,b);if(!b&&$_){wz();const k=Sz(v);g=k.MeasureLayout,w.visualElement=xz(e,j,v,a,k.ProjectionNode,l)}return o.jsxs(Td.Provider,{value:w,children:[g&&w.visualElement?o.jsx(g,{visualElement:w.visualElement,...v}):null,dz(e,m,yz(j,w.visualElement,p),j,b,t,l)]})}d.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const h=S.forwardRef(d);return h[gz]=e,h}function bz({layoutId:e}){const t=S.useContext(Tg).id;return t&&e!==void 0?t+"-"+e:e}function wz(e,t){S.useContext(pk).strict}function Sz(e){const t=gk(),{drag:n,layout:s}=t;if(!n&&!s)return{};const a={...n,...s};return{MeasureLayout:n?.isEnabled(e)||s?.isEnabled(e)?a.MeasureLayout:void 0,ProjectionNode:a.ProjectionNode}}function _z(e,t){if(typeof Proxy>"u")return jm;const n=new Map,s=(l,u)=>jm(l,u,e,t),a=(l,u)=>s(l,u);return new Proxy(a,{get:(l,u)=>u==="create"?s:(n.has(u)||n.set(u,jm(u,void 0,e,t)),n.get(u))})}const jz=(e,t)=>t.isSVG??sy(e)?new nP(t):new X3(t,{allowProjection:e!==S.Fragment});class kz extends Qs{constructor(t){super(t),t.animationState||(t.animationState=oP(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();kd(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Nz=0;class Tz extends Qs{constructor(){super(...arguments),this.id=Nz++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const a=this.node.animationState.setActive("exit",!t);n&&!t&&a.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const Ez={animation:{Feature:kz},exit:{Feature:Tz}};function Ql(e){return{point:{x:e.pageX,y:e.pageY}}}const Cz=e=>t=>Jg(t)&&e(t,Ql(t));function _l(e,t,n,s){return Vl(e,t,Cz(n),s)}const _k=({current:e})=>e?e.ownerDocument.defaultView:null,k1=(e,t)=>Math.abs(e-t);function Az(e,t){const n=k1(e.x,t.x),s=k1(e.y,t.y);return Math.sqrt(n**2+s**2)}const N1=new Set(["auto","scroll"]);class jk{constructor(t,n,{transformPagePoint:s,contextWindow:a=window,dragSnapToOrigin:l=!1,distanceThreshold:u=3,element:d}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=b=>{this.handleScroll(b.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=Nm(this.lastMoveEventInfo,this.history),w=this.startEvent!==null,j=Az(b.offset,{x:0,y:0})>=this.distanceThreshold;if(!w&&!j)return;const{point:k}=b,{timestamp:N}=nn;this.history.push({...k,timestamp:N});const{onStart:R,onMove:T}=this.handlers;w||(R&&R(this.lastMoveEvent,b),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,b)},this.handlePointerMove=(b,w)=>{this.lastMoveEvent=b,this.lastMoveEventInfo=km(w,this.transformPagePoint),gt.update(this.updatePoint,!0)},this.handlePointerUp=(b,w)=>{this.end();const{onEnd:j,onSessionEnd:k,resumeAnimation:N}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&N&&N(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const R=Nm(b.type==="pointercancel"?this.lastMoveEventInfo:km(w,this.transformPagePoint),this.history);this.startEvent&&j&&j(b,R),k&&k(b,R)},!Jg(t))return;this.dragSnapToOrigin=l,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=u,this.contextWindow=a||window;const h=Ql(t),m=km(h,this.transformPagePoint),{point:p}=m,{timestamp:g}=nn;this.history=[{...p,timestamp:g}];const{onSessionStart:v}=n;v&&v(t,Nm(m,this.history)),this.removeListeners=Wl(_l(this.contextWindow,"pointermove",this.handlePointerMove),_l(this.contextWindow,"pointerup",this.handlePointerUp),_l(this.contextWindow,"pointercancel",this.handlePointerUp)),d&&this.startScrollTracking(d)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(N1.has(s.overflowX)||N1.has(s.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener("scroll",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const s=t===window,a=s?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},l={x:a.x-n.x,y:a.y-n.y};l.x===0&&l.y===0||(s?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=l.x,this.lastMoveEventInfo.point.y+=l.y):this.history.length>0&&(this.history[0].x-=l.x,this.history[0].y-=l.y),this.scrollPositions.set(t,a),gt.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Ks(this.updatePoint)}}function km(e,t){return t?{point:t(e.point)}:e}function T1(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Nm({point:e},t){return{point:e,delta:T1(e,kk(t)),offset:T1(e,Rz(t)),velocity:Oz(t,.1)}}function Rz(e){return e[0]}function kk(e){return e[e.length-1]}function Oz(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const a=kk(e);for(;n>=0&&(s=e[n],!(a.timestamp-s.timestamp>is(t)));)n--;if(!s)return{x:0,y:0};const l=tr(a.timestamp-s.timestamp);if(l===0)return{x:0,y:0};const u={x:(a.x-s.x)/l,y:(a.y-s.y)/l};return u.x===1/0&&(u.x=0),u.y===1/0&&(u.y=0),u}function Dz(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?wt(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?wt(n,e,s.max):Math.min(e,n)),e}function E1(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function Mz(e,{top:t,left:n,bottom:s,right:a}){return{x:E1(e.x,n,a),y:E1(e.y,t,s)}}function C1(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function Pz(e,t){return{x:C1(e.x,t.x),y:C1(e.y,t.y)}}function zz(e,t){let n=.5;const s=hn(e),a=hn(t);return a>s?n=Ll(t.min,t.max-s,e.min):s>a&&(n=Ll(e.min,e.max-a,t.min)),Ar(0,1,n)}function Lz(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const Vp=.35;function Iz(e=Vp){return e===!1?e=0:e===!0&&(e=Vp),{x:A1(e,"left","right"),y:A1(e,"top","bottom")}}function A1(e,t,n){return{min:R1(e,t),max:R1(e,n)}}function R1(e,t){return typeof e=="number"?e:e[t]||0}const Uz=new WeakMap;class Bz{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=qt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const l=g=>{n?(this.stopAnimation(),this.snapToCursor(Ql(g).point)):this.pauseAnimation()},u=(g,v)=>{this.stopAnimation();const{drag:b,dragPropagation:w,onDragStart:j}=this.getProps();if(b&&!w&&(this.openDragLock&&this.openDragLock(),this.openDragLock=T3(b),!this.openDragLock))return;this.latestPointerEvent=g,this.latestPanInfo=v,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Zn(N=>{let R=this.getAxisMotionValue(N).get()||0;if(Er.test(R)){const{projection:T}=this.visualElement;if(T&&T.layout){const D=T.layout.layoutBox[N];D&&(R=hn(D)*(parseFloat(R)/100))}}this.originPoint[N]=R}),j&&gt.postRender(()=>j(g,v)),Dp(this.visualElement,"transform");const{animationState:k}=this.visualElement;k&&k.setActive("whileDrag",!0)},d=(g,v)=>{this.latestPointerEvent=g,this.latestPanInfo=v;const{dragPropagation:b,dragDirectionLock:w,onDirectionLock:j,onDrag:k}=this.getProps();if(!b&&!this.openDragLock)return;const{offset:N}=v;if(w&&this.currentDirection===null){this.currentDirection=Vz(N),this.currentDirection!==null&&j&&j(this.currentDirection);return}this.updateAxis("x",v.point,N),this.updateAxis("y",v.point,N),this.visualElement.render(),k&&k(g,v)},h=(g,v)=>{this.latestPointerEvent=g,this.latestPanInfo=v,this.stop(g,v),this.latestPointerEvent=null,this.latestPanInfo=null},m=()=>Zn(g=>this.getAnimationState(g)==="paused"&&this.getAxisMotionValue(g).animation?.play()),{dragSnapToOrigin:p}=this.getProps();this.panSession=new jk(t,{onSessionStart:l,onStart:u,onMove:d,onSessionEnd:h,resumeAnimation:m},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:p,distanceThreshold:s,contextWindow:_k(this.visualElement),element:this.visualElement.current})}stop(t,n){const s=t||this.latestPointerEvent,a=n||this.latestPanInfo,l=this.isDragging;if(this.cancel(),!l||!a||!s)return;const{velocity:u}=a;this.startAnimation(u);const{onDragEnd:d}=this.getProps();d&&gt.postRender(()=>d(s,a))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,s){const{drag:a}=this.getProps();if(!s||!Nu(t,a,this.currentDirection))return;const l=this.getAxisMotionValue(t);let u=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(u=Dz(u,this.constraints[t],this.elastic[t])),l.set(u)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,a=this.constraints;t&&yl(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=Mz(s.layoutBox,t):this.constraints=!1,this.elastic=Iz(n),a!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Zn(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=Lz(s.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!yl(t))return!1;const s=t.current,{projection:a}=this.visualElement;if(!a||!a.layout)return!1;const l=$3(s,a.root,this.visualElement.getTransformPagePoint());let u=Pz(a.layout.layoutBox,l);if(n){const d=n(V3(u));this.hasMutatedConstraints=!!d,d&&(u=Hj(d))}return u}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:a,dragTransition:l,dragSnapToOrigin:u,onDragTransitionEnd:d}=this.getProps(),h=this.constraints||{},m=Zn(p=>{if(!Nu(p,n,this.currentDirection))return;let g=h&&h[p]||{};u&&(g={min:0,max:0});const v=a?200:1e6,b=a?40:1e7,w={type:"inertia",velocity:s?t[p]:0,bounceStiffness:v,bounceDamping:b,timeConstant:750,restDelta:1,restSpeed:10,...l,...g};return this.startAxisValueAnimation(p,w)});return Promise.all(m).then(d)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return Dp(this.visualElement,t),s.start(Gg(t,s,0,n,this.visualElement,!1))}stopAnimation(){Zn(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Zn(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),a=s[n];return a||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){Zn(n=>{const{drag:s}=this.getProps();if(!Nu(n,s,this.currentDirection))return;const{projection:a}=this.visualElement,l=this.getAxisMotionValue(n);if(a&&a.layout){const{min:u,max:d}=a.layout.layoutBox[n],h=l.get()||0;l.set(t[n]-wt(u,d,.5)+h)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!yl(n)||!s||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};Zn(u=>{const d=this.getAxisMotionValue(u);if(d&&this.constraints!==!1){const h=d.get();a[u]=zz({min:h,max:h},this.constraints[u])}});const{transformTemplate:l}=this.visualElement.getProps();this.visualElement.current.style.transform=l?l({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),Zn(u=>{if(!Nu(u,t,null))return;const d=this.getAxisMotionValue(u),{min:h,max:m}=this.constraints[u];d.set(wt(h,m,a[u]))})}addListeners(){if(!this.visualElement.current)return;Uz.set(this.visualElement,this);const t=this.visualElement.current,n=_l(t,"pointerdown",h=>{const{drag:m,dragListener:p=!0}=this.getProps(),g=h.target,v=g!==t&&Uj(g);m&&p&&!v&&this.start(h)}),s=()=>{const{dragConstraints:h}=this.getProps();yl(h)&&h.current&&(this.constraints=this.resolveRefConstraints())},{projection:a}=this.visualElement,l=a.addEventListener("measure",s);a&&!a.layout&&(a.root&&a.root.updateScroll(),a.updateLayout()),gt.read(s);const u=Vl(window,"resize",()=>this.scalePositionWithinConstraints()),d=a.addEventListener("didUpdate",(({delta:h,hasLayoutChanged:m})=>{this.isDragging&&m&&(Zn(p=>{const g=this.getAxisMotionValue(p);g&&(this.originPoint[p]+=h[p].translate,g.set(g.get()+h[p].translate))}),this.visualElement.render())}));return()=>{u(),n(),l(),d&&d()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:a=!1,dragConstraints:l=!1,dragElastic:u=Vp,dragMomentum:d=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:a,dragConstraints:l,dragElastic:u,dragMomentum:d}}}function Nu(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Vz(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Fz extends Qs{constructor(t){super(t),this.removeGroupControls=nr,this.removeListeners=nr,this.controls=new Bz(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||nr}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const O1=e=>(t,n)=>{e&&gt.postRender(()=>e(t,n))};class qz extends Qs{constructor(){super(...arguments),this.removePointerDownListener=nr}onPointerDown(t){this.session=new jk(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:_k(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:a}=this.node.getProps();return{onSessionStart:O1(t),onStart:O1(n),onMove:s,onEnd:(l,u)=>{delete this.session,a&&gt.postRender(()=>a(l,u))}}}mount(){this.removePointerDownListener=_l(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let Tm=!1;class $z extends S.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:a}=this.props,{projection:l}=t;l&&(n.group&&n.group.add(l),s&&s.register&&a&&s.register(l),Tm&&l.root.didUpdate(),l.addEventListener("animationComplete",()=>{this.safeToRemove()}),l.setOptions({...l.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Hu.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:a,isPresent:l}=this.props,{projection:u}=s;return u&&(u.isPresent=l,t.layoutDependency!==n&&u.setOptions({...u.options,layoutDependency:n}),Tm=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==l?u.willUpdate():this.safeToRemove(),t.isPresent!==l&&(l?u.promote():u.relegate()||gt.postRender(()=>{const d=u.getStack();(!d||!d.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Xg.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:a}=t;Tm=!0,a&&(a.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(a),s&&s.deregister&&s.deregister(a))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Nk(e){const[t,n]=hk(),s=S.useContext(Tg);return o.jsx($z,{...e,layoutGroup:s,switchLayoutGroup:S.useContext(wk),isPresent:t,safeToRemove:n})}const Hz={pan:{Feature:qz},drag:{Feature:Fz,ProjectionNode:fk,MeasureLayout:Nk}};function D1(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const a="onHover"+n,l=s[a];l&&gt.postRender(()=>l(t,Ql(t)))}class Gz extends Qs{mount(){const{current:t}=this.node;t&&(this.unmount=E3(t,(n,s)=>(D1(this.node,s,"Start"),a=>D1(this.node,a,"End"))))}unmount(){}}class Kz extends Qs{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Wl(Vl(this.node.current,"focus",()=>this.onFocus()),Vl(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function M1(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const a="onTap"+(n==="End"?"":n),l=s[a];l&&gt.postRender(()=>l(t,Ql(t)))}class Yz extends Qs{mount(){const{current:t}=this.node;t&&(this.unmount=R3(t,(n,s)=>(M1(this.node,s,"Start"),(a,{success:l})=>M1(this.node,a,l?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Fp=new WeakMap,Em=new WeakMap,Wz=e=>{const t=Fp.get(e.target);t&&t(e)},Xz=e=>{e.forEach(Wz)};function Jz({root:e,...t}){const n=e||document;Em.has(n)||Em.set(n,{});const s=Em.get(n),a=JSON.stringify(t);return s[a]||(s[a]=new IntersectionObserver(Xz,{root:e,...t})),s[a]}function Qz(e,t,n){const s=Jz(t);return Fp.set(e,n),s.observe(e),()=>{Fp.delete(e),s.unobserve(e)}}const Zz={some:0,all:1};class eL extends Qs{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:a="some",once:l}=t,u={root:n?n.current:void 0,rootMargin:s,threshold:typeof a=="number"?a:Zz[a]},d=h=>{const{isIntersecting:m}=h;if(this.isInView===m||(this.isInView=m,l&&!m&&this.hasEnteredView))return;m&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",m);const{onViewportEnter:p,onViewportLeave:g}=this.node.getProps(),v=m?p:g;v&&v(h)};return Qz(this.node.current,u,d)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(tL(t,n))&&this.startObserver()}unmount(){}}function tL({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const nL={inView:{Feature:eL},tap:{Feature:Yz},focus:{Feature:Kz},hover:{Feature:Gz}},rL={layout:{ProjectionNode:fk,MeasureLayout:Nk}},sL={...Ez,...nL,...Hz,...rL},rs=_z(sL,jz),iL="modulepreload",aL=function(e){return"/"+e},P1={},Ni=function(t,n,s){let a=Promise.resolve();if(n&&n.length>0){let m=function(p){return Promise.all(p.map(g=>Promise.resolve(g).then(v=>({status:"fulfilled",value:v}),v=>({status:"rejected",reason:v}))))};var u=m;document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),h=d?.nonce||d?.getAttribute("nonce");a=m(n.map(p=>{if(p=aL(p),p in P1)return;P1[p]=!0;const g=p.endsWith(".css"),v=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${v}`))return;const b=document.createElement("link");if(b.rel=g?"stylesheet":iL,g||(b.as="script"),b.crossOrigin="",b.href=p,h&&b.setAttribute("nonce",h),document.head.appendChild(b),g)return new Promise((w,j)=>{b.addEventListener("load",w),b.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${p}`)))})}))}function l(d){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=d,window.dispatchEvent(h),!h.defaultPrevented)throw d}return a.then(d=>{for(const h of d||[])h.status==="rejected"&&l(h.reason);return t().catch(l)})},oL=(e,t,n)=>{const s=e[t];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((a,l)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(l.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Tk={"app.name":"Email Automator","app.connecting":"Connecting account...","app.loadingWorkspace":"Loading your workspace...","app.loggedOut":"Logged out successfully","app.statusLive":"LIVE","app.statusOffline":"OFFLINE","common.loading":"Loading...","common.save":"Save Changes","common.cancel":"Cancel","common.delete":"Delete","common.success":"Success","common.error":"Error","common.warning":"Warning","common.syncNow":"Sync Now","common.syncing":"Syncing...","common.stopSync":"Stop Sync","common.systemSync":"System Sync","common.viewLogs":"View Logs","common.saveChanges":"Save Changes","common.errorOccurred":"An error occurred","common.previous":"Previous","common.next":"Next","common.of":"of","common.yes":"Yes","common.no":"No","common.archive":"Archive","common.flag":"Flag","common.on":"On","common.off":"Off","common.enabled":"Enabled","common.disabled":"Disabled","common.active":"Active","common.inactive":"Inactive","common.draft":"Draft","common.star":"Star","nav.dashboard":"Dashboard","nav.drafts":"Drafts","nav.autopilot":"Auto-Pilot","nav.analytics":"Analytics","nav.configuration":"Configuration","nav.accountSettings":"Account Settings","nav.signOut":"Sign Out","drafts.title":"Draft Review Center","drafts.pending":"pending drafts","drafts.noDrafts":"No pending drafts","drafts.noDraftsDesc":"AI-generated draft replies will appear here for your review","drafts.send":"Send Now","drafts.preview":"Preview","drafts.dismiss":"Dismiss","drafts.regenerate":"Regenerate","drafts.selectAll":"Select All","drafts.sendSelected":"Send Selected","drafts.dismissSelected":"Dismiss Selected","drafts.filterByAccount":"All Accounts","drafts.filterByDate":"Filter by Date","drafts.originalEmail":"Original Email","drafts.aiReply":"AI-Generated Reply","drafts.createdBy":"Created by rule:","drafts.sendSuccess":"Draft sent successfully!","drafts.sendError":"Failed to send draft","drafts.dismissSuccess":"Draft dismissed","drafts.loadError":"Failed to load drafts","login.title":"Welcome Back","login.subtitle":"Sign in to your AI email agent","login.email":"Email Address","login.password":"Password","login.signIn":"Sign In","login.noAccount":"Don't have an account?","login.alreadyHaveAccount":"Already have an account?","login.signUp":"Sign Up","login.forgotPassword":"Forgot your password?","login.initialize":"Initialize Automator","login.secureLogin":"Secure Login","login.firstNamePlaceholder":"John","login.lastNamePlaceholder":"Doe","login.emailPlaceholder":"admin@automator.ai","login.initializeMaster":"Initialize Master","login.sendMagicLink":"Send Magic Link","login.openDashboard":"Open Dashboard","setup.title":"System Setup","setup.initiation":"Welcome","setup.coordinates":"Connection Details","setup.foundation":"Database Setup","setup.ignition":"Launch","setup.start":"Start Setup","setup.welcomeTitle":"Automator Initializing","setup.welcomeSubtitle":"Setting up your specialized environment for high-frequency inbox intelligence.","setup.encryptedTitle":"Encrypted","setup.encryptedDesc":"Self-hosted data security.","setup.turboTitle":"Turbo","setup.turboDesc":"Sub-second AI inference.","setup.getStarted":"Get Started","setup.connectionMode":"Connection Mode","setup.selectVector":"Select deployment mode","setup.quickIgnition":"Quick Start","setup.autoProvision":"Auto-provision via token","setup.manualSync":"Manual Sync","setup.existingCredentials":"Existing Credentials","setup.abortAccess":"Abort Access","setup.injectCoordinates":"Enter existing credentials","setup.platformUrl":"Platform URL","setup.urlHelp":"Enter full URL or just the Project ID","setup.anonMatrixKey":"Supabase Anon Key","setup.keyHelp":"Found in your Supabase project settings","setup.back":"Back","setup.engage":"Connect","setup.installation":"Installation","setup.applyingSchema":"Setting up database...","setup.emptyProject":"Empty project detected. Initialization is mandatory to install core AI systems.","setup.versionMismatch":"Version mismatch detected. Normalization recommended.","setup.tokenRequired":"Management Token Required","setup.migrateHelp":"Used once to run migrations on your backend.","setup.bypassRisk":"Bypass (Risky)","setup.installSystems":"Install Systems","setup.normalizeSystem":"Normalize System","setup.retryInstallation":"Retry Installation","setup.agent.systemInstruction":'You are the Setup Wizard assistant. Guide the user through connecting Supabase, choosing a setup mode, and completing migrations. Ask only for the next required input and provide step-by-step actions. If the user says "help me set up", immediately outline the steps in this wizard.',"dashboard.recentAnalysis":"Recent Analysis","dashboard.emails":"emails","dashboard.noEmails":"No emails found","dashboard.noEmailsConnected":"Connect your email account to get started.","dashboard.noEmailsFilters":"Try syncing or adjusting your filters.","dashboard.syncInProgress":"Sync in progress...","dashboard.syncInProgressDesc":"Fetching and analyzing emails. New emails will appear below automatically.","dashboard.aiTrace":"AI Processing Trace","dashboard.aiTraceDesc":"Step-by-step logs of how AI analyzed and actioned this email.","dashboard.noTrace":"No detailed trace events found for this email.","dashboard.syncNow":"Sync Now","dashboard.syncing":"Syncing...","dashboard.searchPlaceholder":"Search emails...","dashboard.search":"Search","dashboard.receivedTime":"Received Time","dashboard.processedTime":"Processed Time","dashboard.receivedAbbr":"REC","dashboard.processedAbbr":"PROC","dashboard.sortOldest":"Sorting: Oldest First","dashboard.sortNewest":"Sorting: Newest First","dashboard.category.all":"All","dashboard.category.none":"none","dashboard.emailDetails":"Email Details","dashboard.emailContent":"Email Content (sent to LLM)","dashboard.from":"From:","dashboard.subject":"Subject:","dashboard.summary":"Summary:","dashboard.keyPoints":"Key Points:","dashboard.aiDraftReply":"AI Draft Reply","dashboard.draftSavedHelp":"* This draft is already saved in your {provider} Drafts folder.","dashboard.syncScope":"Sync Scope","dashboard.syncFrom":"Sync From","dashboard.maxEmails":"Max Emails","dashboard.lastSync":"Last sync:","dashboard.error":"Error:","dashboard.resetCheckpoint":"Reset Checkpoint (Force Full Re-sync from Start Date)","dashboard.syncHistory":"Sync History","dashboard.noSyncHistory":"No sync history available.","dashboard.processed":"Processed:","dashboard.actioned":"Actioned:","dashboard.running":"Running","dashboard.quickStats":"Quick Stats","dashboard.totalProcessed":"Total Processed","dashboard.connectedAccounts":"Connected Accounts","dashboard.activeRules":"Active Rules","dashboard.noSubject":"No Subject","dashboard.queued":"Queued","dashboard.analyzing":"Analyzing","dashboard.analyzed":"Analyzed","dashboard.failed":"Failed","dashboard.retryProcessing":"Retry Processing","dashboard.suggested":"Suggested:","dashboard.done":"Done:","dashboard.deleteConfirm":"Delete?","dashboard.openIn":"Open in {provider}","dashboard.viewTraceTooltip":"View AI Trace (Prompt/Response)","dashboard.syncSuccess":"Sync completed! Check your emails.","dashboard.syncFailed":"Sync failed. Check account status for details.","config.title":"Automation & Rules","config.rules":"Automation Rules","config.createRule":"Create New Rule","config.llmSettings":"AI Intelligence Settings","config.accounts.title":"Email Accounts","config.accounts.desc":"Connect and manage your email accounts","config.accounts.addNew":"Add New Account","config.accounts.yourAccounts":"Your Connected Accounts","config.accounts.noAccounts":"No email accounts connected yet","config.accounts.connectHelp":"Connect your first email account to start automating","config.accounts.disconnect":"Disconnect","config.gmail.connect":"Connect Gmail","config.gmail.connectDesc":"OAuth 2.0 or Service Account","config.gmail.credentialsDesc":"Paste your Google Cloud credentials JSON","config.gmail.authCodeDesc":"Enter the authorization code from Google","config.gmail.pasteJson":"Paste credentials.json content","config.gmail.downloadHelp":"Download from Google Cloud Console → APIs & Services → Credentials","config.gmail.orEnterManually":"Or enter manually","config.outlook.connect":"Connect Outlook","config.outlook.connectDesc":"Microsoft 365 or Outlook.com","config.outlook.credentialsDesc":"Paste your Azure App credentials JSON","config.outlook.instructions":"Follow the OAuth flow to connect","config.outlook.signinRequired":"Sign-in Required","config.outlook.openLogin":"Open Microsoft Login","config.outlook.waitingSignin":"Waiting for sign-in...","config.outlook.note":"Note: You need an Azure App Registration for this to work.","config.outlook.clientId":"Client ID (Application ID)","config.outlook.tenantIdOptional":"Tenant ID (Optional)","config.outlook.tenantHelp":'Default is "common". Use your specific Tenant ID for organization accounts.',"config.outlook.saveConnect":"Save & Connect","config.outlook.actionRequired":"Action Required","config.outlook.waitingAuth":"Waiting for authorization...","config.outlook.tenantPlaceholder":"common","config.model.title":"AI Model Configuration","config.model.desc":"Configure your AI model and processing settings","config.llm.title":"LLM","config.model.provider":"LLM Provider","config.model.defaultProvider":"RealTimeX AI (Default)","config.model.discovering":"Discovering...","config.model.name":"Model Name","config.model.selectModel":"Select a model","config.model.modelPlaceholder":"e.g. gpt-4o-mini","config.model.storagePath":"Storage Path","config.model.storagePlaceholder":"Path for model storage","config.model.storageHelp":"Local directory for caching models","config.model.syncInterval":"Sync Interval (minutes)","config.model.syncHelp":"How often to check for new emails","config.model.intelligentRename":"Intelligent Rename","config.model.renameHelp":"Use AI to suggest better file names","config.model.checkConnection":"Check Connection","config.model.saveConfig":"Save Configuration","config.providers.gmail":"Gmail","config.providers.outlook":"Outlook","config.storage.title":"Storage Path","config.storage.desc":"Choose where raw email files are stored locally","config.storage.label":"Local Storage Path","config.storage.placeholder":"e.g. /Users/you/Documents/email-archive","config.storage.help":"Must be writable. Leave blank to use the default application folder.","config.rename.title":"Intelligent Rename","config.rename.desc":"Control filename formatting for stored emails","config.rename.label":"Enable intelligent rename","config.rename.help":"Creates readable, slugified filenames instead of raw message IDs.","config.sync.title":"Sync Interval (minutes)","config.sync.desc":"Controls how often background sync runs","config.sync.label":"Minutes between sync runs","config.sync.help":"Lower values increase freshness but may use more resources.","config.embed.title":"Embedding (RAG)","config.embed.desc":"Configure embeddings for knowledge base search (RAG).","config.embed.provider":"Embedding Provider","config.embed.model":"Embedding Model","config.embed.modelPlaceholder":"e.g. text-embedding-3-small","config.embed.autoModel":"Auto (text-embedding-3-small)","config.embed.help":"Used for semantic search in the knowledge base.","config.embed.discovering":"Discovering...","config.embed.defaultProvider":"RealTimeX AI (Default)","config.byok.title":"Bring Your Own Key (BYOK)","config.byok.desc":"Use your own API keys for AI providers","config.byok.systemDefault":"Use system default","config.byok.googleTitle":"Google / Gmail","config.byok.microsoftTitle":"Microsoft / Outlook","config.byok.clientId":"Client ID","config.byok.clientSecret":"Client Secret","config.byok.clientSecretOptional":"Client Secret (Optional)","config.byok.tenantId":"Tenant ID","config.byok.save":"Save API Key","config.gmail.authSteps":`1. A new tab opened with Google Sign-In
59
+ `),()=>{D.contains(T)&&D.removeChild(T)}},[t]),o.jsx(WP,{isPresent:t,childRef:u,sizeRef:d,children:S.cloneElement(e,{ref:p})})}const JP=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:a,presenceAffectsLayout:l,mode:u,anchorX:d,anchorY:h,root:m})=>{const p=Eg(QP),g=S.useId();let v=!0,b=S.useMemo(()=>(v=!1,{id:g,initial:t,isPresent:n,custom:a,onExitComplete:w=>{p.set(w,!0);for(const j of p.values())if(!j)return;s&&s()},register:w=>(p.set(w,!1),()=>p.delete(w))}),[n,p,s]);return l&&v&&(b={...b}),S.useMemo(()=>{p.forEach((w,j)=>p.set(j,!1))},[n]),S.useEffect(()=>{!n&&!p.size&&s&&s()},[n]),u==="popLayout"&&(e=o.jsx(XP,{isPresent:n,anchorX:d,anchorY:h,root:m,children:e})),o.jsx(jd.Provider,{value:b,children:e})};function QP(){return new Map}function hk(e=!0){const t=S.useContext(jd);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:a}=t,l=S.useId();S.useEffect(()=>{if(e)return a(l)},[e]);const u=S.useCallback(()=>e&&s&&s(l),[l,s,e]);return!n&&s?[!1,u]:[!0]}const ku=e=>e.key||"";function w1(e){const t=[];return S.Children.forEach(e,n=>{S.isValidElement(n)&&t.push(n)}),t}const mk=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:a=!0,mode:l="sync",propagate:u=!1,anchorX:d="left",anchorY:h="top",root:m})=>{const[p,g]=hk(u),v=S.useMemo(()=>w1(e),[e]),b=u&&!p?[]:v.map(ku),w=S.useRef(!0),j=S.useRef(v),k=Eg(()=>new Map),N=S.useRef(new Set),[R,T]=S.useState(v),[D,U]=S.useState(v);H_(()=>{w.current=!1,j.current=v;for(let P=0;P<D.length;P++){const H=ku(D[P]);b.includes(H)?(k.delete(H),N.current.delete(H)):k.get(H)!==!0&&k.set(H,!1)}},[D,b.length,b.join("-")]);const M=[];if(v!==R){let P=[...v];for(let H=0;H<D.length;H++){const O=D[H],Q=ku(O);b.includes(Q)||(P.splice(H,0,O),M.push(O))}return l==="wait"&&M.length&&(P=M),U(w1(P)),T(v),null}const{forceRender:B}=S.useContext(Tg);return o.jsx(o.Fragment,{children:D.map(P=>{const H=ku(P),O=u&&!p?!1:v===D||b.includes(H),Q=()=>{if(N.current.has(H))return;if(N.current.add(H),k.has(H))k.set(H,!0);else return;let G=!0;k.forEach(he=>{he||(G=!1)}),G&&(B?.(),U(j.current),u&&g?.(),s&&s())};return o.jsx(JP,{isPresent:O,initial:!w.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:l,root:m,onExitComplete:O?void 0:Q,anchorX:d,anchorY:h,children:P},H)})})},pk=S.createContext({strict:!1}),S1={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let _1=!1;function ZP(){if(_1)return;const e={};for(const t in S1)e[t]={isEnabled:n=>S1[t].some(s=>!!n[s])};qj(e),_1=!0}function gk(){return ZP(),U3()}function ez(e){const t=gk();for(const n in e)t[n]={...t[n],...e[n]};qj(t)}const tz=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function ud(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||tz.has(e)}let yk=e=>!ud(e);function nz(e){typeof e=="function"&&(yk=t=>t.startsWith("on")?!ud(t):e(t))}try{nz(require("@emotion/is-prop-valid").default)}catch{}function rz(e,t,n){const s={};for(const a in e)a==="values"&&typeof e.values=="object"||(yk(a)||n===!0&&ud(a)||!t&&!ud(a)||e.draggable&&a.startsWith("onDrag"))&&(s[a]=e[a]);return s}const Td=S.createContext({});function sz(e,t){if(Nd(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Bl(n)?n:void 0,animate:Bl(s)?s:void 0}}return e.inherit!==!1?t:{}}function iz(e){const{initial:t,animate:n}=sz(e,S.useContext(Td));return S.useMemo(()=>({initial:t,animate:n}),[j1(t),j1(n)])}function j1(e){return Array.isArray(e)?e.join(" "):e}const ry=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function xk(e,t,n){for(const s in t)!an(t[s])&&!Xj(s,n)&&(e[s]=t[s])}function az({transformTemplate:e},t){return S.useMemo(()=>{const n=ry();return ey(n,t,e),Object.assign({},n.vars,n.style)},[t])}function oz(e,t){const n=e.style||{},s={};return xk(s,n,e),Object.assign(s,az(e,t)),s}function lz(e,t){const n={},s=oz(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const vk=()=>({...ry(),attrs:{}});function cz(e,t,n,s){const a=S.useMemo(()=>{const l=vk();return Jj(l,t,Zj(s),e.transformTemplate,e.style),{...l.attrs,style:{...l.style}}},[t]);if(e.style){const l={};xk(l,e.style,e),a.style={...l,...a.style}}return a}const uz=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function sy(e){return typeof e!="string"||e.includes("-")?!1:!!(uz.indexOf(e)>-1||/[A-Z]/u.test(e))}function dz(e,t,n,{latestValues:s},a,l=!1,u){const h=(u??sy(e)?cz:lz)(t,s,a,e),m=rz(t,typeof e=="string",l),p=e!==S.Fragment?{...m,...h,ref:n}:{},{children:g}=t,v=S.useMemo(()=>an(g)?g.get():g,[g]);return S.createElement(e,{...p,children:v})}function fz({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,a){return{latestValues:hz(n,s,a,e),renderState:t()}}function hz(e,t,n,s){const a={},l=s(e,{});for(const v in l)a[v]=$u(l[v]);let{initial:u,animate:d}=e;const h=Nd(e),m=Fj(e);t&&m&&!h&&e.inherit!==!1&&(u===void 0&&(u=t.initial),d===void 0&&(d=t.animate));let p=n?n.initial===!1:!1;p=p||u===!1;const g=p?d:u;if(g&&typeof g!="boolean"&&!kd(g)){const v=Array.isArray(g)?g:[g];for(let b=0;b<v.length;b++){const w=Kg(e,v[b]);if(w){const{transitionEnd:j,transition:k,...N}=w;for(const R in N){let T=N[R];if(Array.isArray(T)){const D=p?T.length-1:0;T=T[D]}T!==null&&(a[R]=T)}for(const R in j)a[R]=j[R]}}}return a}const bk=e=>(t,n)=>{const s=S.useContext(Td),a=S.useContext(jd),l=()=>fz(e,t,s,a);return n?l():Eg(l)},mz=bk({scrapeMotionValuesFromProps:ty,createRenderState:ry}),pz=bk({scrapeMotionValuesFromProps:ek,createRenderState:vk}),gz=Symbol.for("motionComponentSymbol");function yz(e,t,n){const s=S.useRef(n);S.useInsertionEffect(()=>{s.current=n});const a=S.useRef(null);return S.useCallback(l=>{l&&e.onMount?.(l),t&&(l?t.mount(l):t.unmount());const u=s.current;if(typeof u=="function")if(l){const d=u(l);typeof d=="function"&&(a.current=d)}else a.current?(a.current(),a.current=null):u(l);else u&&(u.current=l)},[t])}const wk=S.createContext({});function yl(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function xz(e,t,n,s,a,l){const{visualElement:u}=S.useContext(Td),d=S.useContext(pk),h=S.useContext(jd),m=S.useContext(ny).reducedMotion,p=S.useRef(null),g=S.useRef(!1);s=s||d.renderer,!p.current&&s&&(p.current=s(e,{visualState:t,parent:u,props:n,presenceContext:h,blockInitialAnimation:h?h.initial===!1:!1,reducedMotionConfig:m,isSVG:l}),g.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const v=p.current,b=S.useContext(wk);v&&!v.projection&&a&&(v.type==="html"||v.type==="svg")&&vz(p.current,n,a,b);const w=S.useRef(!1);S.useInsertionEffect(()=>{v&&w.current&&v.update(n,h)});const j=n[Ej],k=S.useRef(!!j&&!window.MotionHandoffIsComplete?.(j)&&window.MotionHasOptimisedAnimation?.(j));return H_(()=>{g.current=!0,v&&(w.current=!0,window.MotionIsMounted=!0,v.updateFeatures(),v.scheduleRenderMicrotask(),k.current&&v.animationState&&v.animationState.animateChanges())}),S.useEffect(()=>{v&&(!k.current&&v.animationState&&v.animationState.animateChanges(),k.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(j)}),k.current=!1),v.enteringChildren=void 0)}),v}function vz(e,t,n,s){const{layoutId:a,layout:l,drag:u,dragConstraints:d,layoutScroll:h,layoutRoot:m,layoutCrossfade:p}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Sk(e.parent)),e.projection.setOptions({layoutId:a,layout:l,alwaysMeasureLayout:!!u||d&&yl(d),visualElement:e,animationType:typeof l=="string"?l:"both",initialPromotionConfig:s,crossfade:p,layoutScroll:h,layoutRoot:m})}function Sk(e){if(e)return e.options.allowProjection!==!1?e.projection:Sk(e.parent)}function jm(e,{forwardMotionProps:t=!1,type:n}={},s,a){s&&ez(s);const l=n?n==="svg":sy(e),u=l?pz:mz;function d(m,p){let g;const v={...S.useContext(ny),...m,layoutId:bz(m)},{isStatic:b}=v,w=iz(m),j=u(m,b);if(!b&&$_){wz();const k=Sz(v);g=k.MeasureLayout,w.visualElement=xz(e,j,v,a,k.ProjectionNode,l)}return o.jsxs(Td.Provider,{value:w,children:[g&&w.visualElement?o.jsx(g,{visualElement:w.visualElement,...v}):null,dz(e,m,yz(j,w.visualElement,p),j,b,t,l)]})}d.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const h=S.forwardRef(d);return h[gz]=e,h}function bz({layoutId:e}){const t=S.useContext(Tg).id;return t&&e!==void 0?t+"-"+e:e}function wz(e,t){S.useContext(pk).strict}function Sz(e){const t=gk(),{drag:n,layout:s}=t;if(!n&&!s)return{};const a={...n,...s};return{MeasureLayout:n?.isEnabled(e)||s?.isEnabled(e)?a.MeasureLayout:void 0,ProjectionNode:a.ProjectionNode}}function _z(e,t){if(typeof Proxy>"u")return jm;const n=new Map,s=(l,u)=>jm(l,u,e,t),a=(l,u)=>s(l,u);return new Proxy(a,{get:(l,u)=>u==="create"?s:(n.has(u)||n.set(u,jm(u,void 0,e,t)),n.get(u))})}const jz=(e,t)=>t.isSVG??sy(e)?new nP(t):new X3(t,{allowProjection:e!==S.Fragment});class kz extends Qs{constructor(t){super(t),t.animationState||(t.animationState=oP(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();kd(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Nz=0;class Tz extends Qs{constructor(){super(...arguments),this.id=Nz++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const a=this.node.animationState.setActive("exit",!t);n&&!t&&a.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const Ez={animation:{Feature:kz},exit:{Feature:Tz}};function Ql(e){return{point:{x:e.pageX,y:e.pageY}}}const Cz=e=>t=>Jg(t)&&e(t,Ql(t));function _l(e,t,n,s){return Vl(e,t,Cz(n),s)}const _k=({current:e})=>e?e.ownerDocument.defaultView:null,k1=(e,t)=>Math.abs(e-t);function Az(e,t){const n=k1(e.x,t.x),s=k1(e.y,t.y);return Math.sqrt(n**2+s**2)}const N1=new Set(["auto","scroll"]);class jk{constructor(t,n,{transformPagePoint:s,contextWindow:a=window,dragSnapToOrigin:l=!1,distanceThreshold:u=3,element:d}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=b=>{this.handleScroll(b.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=Nm(this.lastMoveEventInfo,this.history),w=this.startEvent!==null,j=Az(b.offset,{x:0,y:0})>=this.distanceThreshold;if(!w&&!j)return;const{point:k}=b,{timestamp:N}=nn;this.history.push({...k,timestamp:N});const{onStart:R,onMove:T}=this.handlers;w||(R&&R(this.lastMoveEvent,b),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,b)},this.handlePointerMove=(b,w)=>{this.lastMoveEvent=b,this.lastMoveEventInfo=km(w,this.transformPagePoint),gt.update(this.updatePoint,!0)},this.handlePointerUp=(b,w)=>{this.end();const{onEnd:j,onSessionEnd:k,resumeAnimation:N}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&N&&N(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const R=Nm(b.type==="pointercancel"?this.lastMoveEventInfo:km(w,this.transformPagePoint),this.history);this.startEvent&&j&&j(b,R),k&&k(b,R)},!Jg(t))return;this.dragSnapToOrigin=l,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=u,this.contextWindow=a||window;const h=Ql(t),m=km(h,this.transformPagePoint),{point:p}=m,{timestamp:g}=nn;this.history=[{...p,timestamp:g}];const{onSessionStart:v}=n;v&&v(t,Nm(m,this.history)),this.removeListeners=Wl(_l(this.contextWindow,"pointermove",this.handlePointerMove),_l(this.contextWindow,"pointerup",this.handlePointerUp),_l(this.contextWindow,"pointercancel",this.handlePointerUp)),d&&this.startScrollTracking(d)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(N1.has(s.overflowX)||N1.has(s.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener("scroll",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const s=t===window,a=s?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},l={x:a.x-n.x,y:a.y-n.y};l.x===0&&l.y===0||(s?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=l.x,this.lastMoveEventInfo.point.y+=l.y):this.history.length>0&&(this.history[0].x-=l.x,this.history[0].y-=l.y),this.scrollPositions.set(t,a),gt.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Ks(this.updatePoint)}}function km(e,t){return t?{point:t(e.point)}:e}function T1(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Nm({point:e},t){return{point:e,delta:T1(e,kk(t)),offset:T1(e,Rz(t)),velocity:Oz(t,.1)}}function Rz(e){return e[0]}function kk(e){return e[e.length-1]}function Oz(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const a=kk(e);for(;n>=0&&(s=e[n],!(a.timestamp-s.timestamp>is(t)));)n--;if(!s)return{x:0,y:0};const l=tr(a.timestamp-s.timestamp);if(l===0)return{x:0,y:0};const u={x:(a.x-s.x)/l,y:(a.y-s.y)/l};return u.x===1/0&&(u.x=0),u.y===1/0&&(u.y=0),u}function Dz(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?wt(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?wt(n,e,s.max):Math.min(e,n)),e}function E1(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function Mz(e,{top:t,left:n,bottom:s,right:a}){return{x:E1(e.x,n,a),y:E1(e.y,t,s)}}function C1(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function Pz(e,t){return{x:C1(e.x,t.x),y:C1(e.y,t.y)}}function zz(e,t){let n=.5;const s=hn(e),a=hn(t);return a>s?n=Ll(t.min,t.max-s,e.min):s>a&&(n=Ll(e.min,e.max-a,t.min)),Ar(0,1,n)}function Lz(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const Vp=.35;function Iz(e=Vp){return e===!1?e=0:e===!0&&(e=Vp),{x:A1(e,"left","right"),y:A1(e,"top","bottom")}}function A1(e,t,n){return{min:R1(e,t),max:R1(e,n)}}function R1(e,t){return typeof e=="number"?e:e[t]||0}const Uz=new WeakMap;class Bz{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=qt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const l=g=>{n?(this.stopAnimation(),this.snapToCursor(Ql(g).point)):this.pauseAnimation()},u=(g,v)=>{this.stopAnimation();const{drag:b,dragPropagation:w,onDragStart:j}=this.getProps();if(b&&!w&&(this.openDragLock&&this.openDragLock(),this.openDragLock=T3(b),!this.openDragLock))return;this.latestPointerEvent=g,this.latestPanInfo=v,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Zn(N=>{let R=this.getAxisMotionValue(N).get()||0;if(Er.test(R)){const{projection:T}=this.visualElement;if(T&&T.layout){const D=T.layout.layoutBox[N];D&&(R=hn(D)*(parseFloat(R)/100))}}this.originPoint[N]=R}),j&&gt.postRender(()=>j(g,v)),Dp(this.visualElement,"transform");const{animationState:k}=this.visualElement;k&&k.setActive("whileDrag",!0)},d=(g,v)=>{this.latestPointerEvent=g,this.latestPanInfo=v;const{dragPropagation:b,dragDirectionLock:w,onDirectionLock:j,onDrag:k}=this.getProps();if(!b&&!this.openDragLock)return;const{offset:N}=v;if(w&&this.currentDirection===null){this.currentDirection=Vz(N),this.currentDirection!==null&&j&&j(this.currentDirection);return}this.updateAxis("x",v.point,N),this.updateAxis("y",v.point,N),this.visualElement.render(),k&&k(g,v)},h=(g,v)=>{this.latestPointerEvent=g,this.latestPanInfo=v,this.stop(g,v),this.latestPointerEvent=null,this.latestPanInfo=null},m=()=>Zn(g=>this.getAnimationState(g)==="paused"&&this.getAxisMotionValue(g).animation?.play()),{dragSnapToOrigin:p}=this.getProps();this.panSession=new jk(t,{onSessionStart:l,onStart:u,onMove:d,onSessionEnd:h,resumeAnimation:m},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:p,distanceThreshold:s,contextWindow:_k(this.visualElement),element:this.visualElement.current})}stop(t,n){const s=t||this.latestPointerEvent,a=n||this.latestPanInfo,l=this.isDragging;if(this.cancel(),!l||!a||!s)return;const{velocity:u}=a;this.startAnimation(u);const{onDragEnd:d}=this.getProps();d&&gt.postRender(()=>d(s,a))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,s){const{drag:a}=this.getProps();if(!s||!Nu(t,a,this.currentDirection))return;const l=this.getAxisMotionValue(t);let u=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(u=Dz(u,this.constraints[t],this.elastic[t])),l.set(u)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,a=this.constraints;t&&yl(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=Mz(s.layoutBox,t):this.constraints=!1,this.elastic=Iz(n),a!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Zn(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=Lz(s.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!yl(t))return!1;const s=t.current,{projection:a}=this.visualElement;if(!a||!a.layout)return!1;const l=$3(s,a.root,this.visualElement.getTransformPagePoint());let u=Pz(a.layout.layoutBox,l);if(n){const d=n(V3(u));this.hasMutatedConstraints=!!d,d&&(u=Hj(d))}return u}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:a,dragTransition:l,dragSnapToOrigin:u,onDragTransitionEnd:d}=this.getProps(),h=this.constraints||{},m=Zn(p=>{if(!Nu(p,n,this.currentDirection))return;let g=h&&h[p]||{};u&&(g={min:0,max:0});const v=a?200:1e6,b=a?40:1e7,w={type:"inertia",velocity:s?t[p]:0,bounceStiffness:v,bounceDamping:b,timeConstant:750,restDelta:1,restSpeed:10,...l,...g};return this.startAxisValueAnimation(p,w)});return Promise.all(m).then(d)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return Dp(this.visualElement,t),s.start(Gg(t,s,0,n,this.visualElement,!1))}stopAnimation(){Zn(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Zn(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),a=s[n];return a||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){Zn(n=>{const{drag:s}=this.getProps();if(!Nu(n,s,this.currentDirection))return;const{projection:a}=this.visualElement,l=this.getAxisMotionValue(n);if(a&&a.layout){const{min:u,max:d}=a.layout.layoutBox[n],h=l.get()||0;l.set(t[n]-wt(u,d,.5)+h)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!yl(n)||!s||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};Zn(u=>{const d=this.getAxisMotionValue(u);if(d&&this.constraints!==!1){const h=d.get();a[u]=zz({min:h,max:h},this.constraints[u])}});const{transformTemplate:l}=this.visualElement.getProps();this.visualElement.current.style.transform=l?l({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),Zn(u=>{if(!Nu(u,t,null))return;const d=this.getAxisMotionValue(u),{min:h,max:m}=this.constraints[u];d.set(wt(h,m,a[u]))})}addListeners(){if(!this.visualElement.current)return;Uz.set(this.visualElement,this);const t=this.visualElement.current,n=_l(t,"pointerdown",h=>{const{drag:m,dragListener:p=!0}=this.getProps(),g=h.target,v=g!==t&&Uj(g);m&&p&&!v&&this.start(h)}),s=()=>{const{dragConstraints:h}=this.getProps();yl(h)&&h.current&&(this.constraints=this.resolveRefConstraints())},{projection:a}=this.visualElement,l=a.addEventListener("measure",s);a&&!a.layout&&(a.root&&a.root.updateScroll(),a.updateLayout()),gt.read(s);const u=Vl(window,"resize",()=>this.scalePositionWithinConstraints()),d=a.addEventListener("didUpdate",(({delta:h,hasLayoutChanged:m})=>{this.isDragging&&m&&(Zn(p=>{const g=this.getAxisMotionValue(p);g&&(this.originPoint[p]+=h[p].translate,g.set(g.get()+h[p].translate))}),this.visualElement.render())}));return()=>{u(),n(),l(),d&&d()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:a=!1,dragConstraints:l=!1,dragElastic:u=Vp,dragMomentum:d=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:a,dragConstraints:l,dragElastic:u,dragMomentum:d}}}function Nu(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Vz(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Fz extends Qs{constructor(t){super(t),this.removeGroupControls=nr,this.removeListeners=nr,this.controls=new Bz(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||nr}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const O1=e=>(t,n)=>{e&&gt.postRender(()=>e(t,n))};class qz extends Qs{constructor(){super(...arguments),this.removePointerDownListener=nr}onPointerDown(t){this.session=new jk(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:_k(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:a}=this.node.getProps();return{onSessionStart:O1(t),onStart:O1(n),onMove:s,onEnd:(l,u)=>{delete this.session,a&&gt.postRender(()=>a(l,u))}}}mount(){this.removePointerDownListener=_l(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let Tm=!1;class $z extends S.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:a}=this.props,{projection:l}=t;l&&(n.group&&n.group.add(l),s&&s.register&&a&&s.register(l),Tm&&l.root.didUpdate(),l.addEventListener("animationComplete",()=>{this.safeToRemove()}),l.setOptions({...l.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Hu.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:a,isPresent:l}=this.props,{projection:u}=s;return u&&(u.isPresent=l,t.layoutDependency!==n&&u.setOptions({...u.options,layoutDependency:n}),Tm=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==l?u.willUpdate():this.safeToRemove(),t.isPresent!==l&&(l?u.promote():u.relegate()||gt.postRender(()=>{const d=u.getStack();(!d||!d.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Xg.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:a}=t;Tm=!0,a&&(a.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(a),s&&s.deregister&&s.deregister(a))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Nk(e){const[t,n]=hk(),s=S.useContext(Tg);return o.jsx($z,{...e,layoutGroup:s,switchLayoutGroup:S.useContext(wk),isPresent:t,safeToRemove:n})}const Hz={pan:{Feature:qz},drag:{Feature:Fz,ProjectionNode:fk,MeasureLayout:Nk}};function D1(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const a="onHover"+n,l=s[a];l&&gt.postRender(()=>l(t,Ql(t)))}class Gz extends Qs{mount(){const{current:t}=this.node;t&&(this.unmount=E3(t,(n,s)=>(D1(this.node,s,"Start"),a=>D1(this.node,a,"End"))))}unmount(){}}class Kz extends Qs{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Wl(Vl(this.node.current,"focus",()=>this.onFocus()),Vl(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function M1(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const a="onTap"+(n==="End"?"":n),l=s[a];l&&gt.postRender(()=>l(t,Ql(t)))}class Yz extends Qs{mount(){const{current:t}=this.node;t&&(this.unmount=R3(t,(n,s)=>(M1(this.node,s,"Start"),(a,{success:l})=>M1(this.node,a,l?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Fp=new WeakMap,Em=new WeakMap,Wz=e=>{const t=Fp.get(e.target);t&&t(e)},Xz=e=>{e.forEach(Wz)};function Jz({root:e,...t}){const n=e||document;Em.has(n)||Em.set(n,{});const s=Em.get(n),a=JSON.stringify(t);return s[a]||(s[a]=new IntersectionObserver(Xz,{root:e,...t})),s[a]}function Qz(e,t,n){const s=Jz(t);return Fp.set(e,n),s.observe(e),()=>{Fp.delete(e),s.unobserve(e)}}const Zz={some:0,all:1};class eL extends Qs{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:a="some",once:l}=t,u={root:n?n.current:void 0,rootMargin:s,threshold:typeof a=="number"?a:Zz[a]},d=h=>{const{isIntersecting:m}=h;if(this.isInView===m||(this.isInView=m,l&&!m&&this.hasEnteredView))return;m&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",m);const{onViewportEnter:p,onViewportLeave:g}=this.node.getProps(),v=m?p:g;v&&v(h)};return Qz(this.node.current,u,d)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(tL(t,n))&&this.startObserver()}unmount(){}}function tL({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const nL={inView:{Feature:eL},tap:{Feature:Yz},focus:{Feature:Kz},hover:{Feature:Gz}},rL={layout:{ProjectionNode:fk,MeasureLayout:Nk}},sL={...Ez,...nL,...Hz,...rL},rs=_z(sL,jz),iL="modulepreload",aL=function(e){return"/"+e},P1={},Ni=function(t,n,s){let a=Promise.resolve();if(n&&n.length>0){let m=function(p){return Promise.all(p.map(g=>Promise.resolve(g).then(v=>({status:"fulfilled",value:v}),v=>({status:"rejected",reason:v}))))};var u=m;document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),h=d?.nonce||d?.getAttribute("nonce");a=m(n.map(p=>{if(p=aL(p),p in P1)return;P1[p]=!0;const g=p.endsWith(".css"),v=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${v}`))return;const b=document.createElement("link");if(b.rel=g?"stylesheet":iL,g||(b.as="script"),b.crossOrigin="",b.href=p,h&&b.setAttribute("nonce",h),document.head.appendChild(b),g)return new Promise((w,j)=>{b.addEventListener("load",w),b.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${p}`)))})}))}function l(d){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=d,window.dispatchEvent(h),!h.defaultPrevented)throw d}return a.then(d=>{for(const h of d||[])h.status==="rejected"&&l(h.reason);return t().catch(l)})},oL=(e,t,n)=>{const s=e[t];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((a,l)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(l.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Tk={"app.name":"Email Automator","app.connecting":"Connecting account...","app.loadingWorkspace":"Loading your workspace...","app.loggedOut":"Logged out successfully","app.statusLive":"LIVE","app.statusOffline":"OFFLINE","common.loading":"Loading...","common.save":"Save Changes","common.cancel":"Cancel","common.delete":"Delete","common.success":"Success","common.error":"Error","common.warning":"Warning","common.syncNow":"Sync Now","common.syncing":"Syncing...","common.stopSync":"Stop Sync","common.systemSync":"System Sync","common.viewLogs":"View Logs","common.saveChanges":"Save Changes","common.errorOccurred":"An error occurred","common.previous":"Previous","common.next":"Next","common.of":"of","common.yes":"Yes","common.no":"No","common.archive":"Archive","common.flag":"Flag","common.on":"On","common.off":"Off","common.enabled":"Enabled","common.disabled":"Disabled","common.active":"Active","common.inactive":"Inactive","common.draft":"Draft","common.star":"Star","nav.dashboard":"Dashboard","nav.drafts":"Drafts","nav.autopilot":"Auto-Pilot","nav.analytics":"Analytics","nav.configuration":"Configuration","nav.accountSettings":"Account Settings","nav.signOut":"Sign Out","drafts.title":"Draft Review Center","drafts.pending":"pending drafts","drafts.noDrafts":"No pending drafts","drafts.noDraftsDesc":"AI-generated draft replies will appear here for your review","drafts.send":"Send Now","drafts.preview":"Preview","drafts.dismiss":"Dismiss","drafts.regenerate":"Regenerate","drafts.selectAll":"Select All","drafts.sendSelected":"Send Selected","drafts.dismissSelected":"Dismiss Selected","drafts.filterByAccount":"All Accounts","drafts.filterByDate":"Filter by Date","drafts.originalEmail":"Original Email","drafts.aiReply":"AI-Generated Reply","drafts.createdBy":"Created by rule:","drafts.sendSuccess":"Draft sent successfully!","drafts.sendError":"Failed to send draft","drafts.dismissSuccess":"Draft dismissed","drafts.loadError":"Failed to load drafts","login.title":"Welcome Back","login.subtitle":"Sign in to your AI email agent","login.email":"Email Address","login.password":"Password","login.signIn":"Sign In","login.noAccount":"Don't have an account?","login.alreadyHaveAccount":"Already have an account?","login.signUp":"Sign Up","login.forgotPassword":"Forgot your password?","login.initialize":"Initialize Automator","login.secureLogin":"Secure Login","login.firstNamePlaceholder":"John","login.lastNamePlaceholder":"Doe","login.emailPlaceholder":"admin@automator.ai","login.initializeMaster":"Initialize Master","login.sendMagicLink":"Send Magic Link","login.openDashboard":"Open Dashboard","setup.title":"System Setup","setup.initiation":"Welcome","setup.coordinates":"Connection Details","setup.foundation":"Database Setup","setup.ignition":"Launch","setup.start":"Start Setup","setup.welcomeTitle":"Automator Initializing","setup.welcomeSubtitle":"Setting up your specialized environment for high-frequency inbox intelligence.","setup.encryptedTitle":"Encrypted","setup.encryptedDesc":"Self-hosted data security.","setup.turboTitle":"Turbo","setup.turboDesc":"Sub-second AI inference.","setup.getStarted":"Get Started","setup.connectionMode":"Connection Mode","setup.selectVector":"Select deployment mode","setup.quickIgnition":"Quick Start","setup.autoProvision":"Auto-provision via token","setup.manualSync":"Manual Sync","setup.existingCredentials":"Existing Credentials","setup.abortAccess":"Abort Access","setup.injectCoordinates":"Enter existing credentials","setup.platformUrl":"Platform URL","setup.urlHelp":"Enter full URL or just the Project ID","setup.anonMatrixKey":"Supabase Anon Key","setup.keyHelp":"Found in your Supabase project settings","setup.back":"Back","setup.engage":"Connect","setup.installation":"Installation","setup.applyingSchema":"Setting up database...","setup.emptyProject":"Empty project detected. Initialization is mandatory to install core AI systems.","setup.versionMismatch":"Version mismatch detected. Normalization recommended.","setup.tokenRequired":"Management Token Required","setup.migrateHelp":"Used once to run migrations on your backend.","setup.bypassRisk":"Bypass (Risky)","setup.installSystems":"Install Systems","setup.normalizeSystem":"Normalize System","setup.retryInstallation":"Retry Installation","setup.agent.systemInstruction":'You are the Setup Wizard assistant. Guide the user through connecting Supabase, choosing a setup mode, and completing migrations. Ask only for the next required input and provide step-by-step actions. If the user says "help me set up", immediately outline the steps in this wizard.',"agent.intro.setup":`👋 Welcome to Setup! I can help you:
60
+ • Choose Quick Start or Manual setup
61
+ • Connect your Supabase project
62
+ • Run database migrations
63
+ • Troubleshoot connection issues
64
+
65
+ Tell me what you want to do or say "help me set up".`,"agent.intro.configuration":`👋 Welcome to Configuration! I can help you:
66
+ • Connect email accounts ({accountsCount} connected)
67
+ • Set up automation rules ({rulesCount} active)
68
+ • Configure LLM & TTS settings
69
+ • Troubleshoot connection issues
70
+
71
+ What would you like to set up?`,"agent.intro.drafts.one":`📧 I'm your Draft Review Assistant!
72
+
73
+ You have {count} pending draft.
74
+
75
+ I can help you:
76
+ • Summarize all drafts
77
+ • Send or dismiss specific drafts
78
+ • Preview draft content
79
+ • Review recipients and subjects
80
+
81
+ Try: "Summarize my drafts" or "Send the draft to John"`,"agent.intro.drafts.other":`📧 I'm your Draft Review Assistant!
82
+
83
+ You have {count} pending drafts.
84
+
85
+ I can help you:
86
+ • Summarize all drafts
87
+ • Send or dismiss specific drafts
88
+ • Preview draft content
89
+ • Review recipients and subjects
90
+
91
+ Try: "Summarize my drafts" or "Send the draft to John"`,"agent.intro.explainer":`🌐 Translation & Explanation Helper
92
+
93
+ I can help you understand:
94
+ • What automation rules mean
95
+ • How settings affect your workflow
96
+ • Technical terms in plain language
97
+
98
+ Ask me anything about what you're seeing!`,"agent.intro.global":`👋 Hi! I'm your AI Assistant.
99
+
100
+ I can help you navigate and understand any part of the Email Automator.
101
+
102
+ What would you like to know?`,"agent.intro.default":`👋 Hi! I'm here to help with {page}.
103
+
104
+ What can I assist you with?`,"agent.composer.placeholder":"Ask a question, or click the mic...","agent.composer.listening":"Listening...","agent.title.setup":"Setup Wizard","agent.title.configuration":"Configuration Helper","agent.title.drafts":"Draft Assistant","agent.title.explainer":"Translation Helper","agent.title.global":"AI Assistant","agent.title.default":"{page} Assistant","agent.status.listening":"Listening...","agent.status.analyzing":"Analyzing","agent.status.speaking":"Speaking","agent.status.ready":"Ready","agent.recording":"Recording...","dashboard.recentAnalysis":"Recent Analysis","dashboard.emails":"emails","dashboard.noEmails":"No emails found","dashboard.noEmailsConnected":"Connect your email account to get started.","dashboard.noEmailsFilters":"Try syncing or adjusting your filters.","dashboard.syncInProgress":"Sync in progress...","dashboard.syncInProgressDesc":"Fetching and analyzing emails. New emails will appear below automatically.","dashboard.aiTrace":"AI Processing Trace","dashboard.aiTraceDesc":"Step-by-step logs of how AI analyzed and actioned this email.","dashboard.noTrace":"No detailed trace events found for this email.","dashboard.syncNow":"Sync Now","dashboard.syncing":"Syncing...","dashboard.searchPlaceholder":"Search emails...","dashboard.search":"Search","dashboard.receivedTime":"Received Time","dashboard.processedTime":"Processed Time","dashboard.receivedAbbr":"REC","dashboard.processedAbbr":"PROC","dashboard.sortOldest":"Sorting: Oldest First","dashboard.sortNewest":"Sorting: Newest First","dashboard.category.all":"All","dashboard.category.none":"none","dashboard.emailDetails":"Email Details","dashboard.emailContent":"Email Content (sent to LLM)","dashboard.from":"From:","dashboard.subject":"Subject:","dashboard.summary":"Summary:","dashboard.keyPoints":"Key Points:","dashboard.aiDraftReply":"AI Draft Reply","dashboard.draftSavedHelp":"* This draft is already saved in your {provider} Drafts folder.","dashboard.syncScope":"Sync Scope","dashboard.syncFrom":"Sync From","dashboard.maxEmails":"Max Emails","dashboard.lastSync":"Last sync:","dashboard.error":"Error:","dashboard.resetCheckpoint":"Reset Checkpoint (Force Full Re-sync from Start Date)","dashboard.syncHistory":"Sync History","dashboard.noSyncHistory":"No sync history available.","dashboard.processed":"Processed:","dashboard.actioned":"Actioned:","dashboard.running":"Running","dashboard.quickStats":"Quick Stats","dashboard.totalProcessed":"Total Processed","dashboard.connectedAccounts":"Connected Accounts","dashboard.activeRules":"Active Rules","dashboard.noSubject":"No Subject","dashboard.queued":"Queued","dashboard.analyzing":"Analyzing","dashboard.analyzed":"Analyzed","dashboard.failed":"Failed","dashboard.retryProcessing":"Retry Processing","dashboard.suggested":"Suggested:","dashboard.done":"Done:","dashboard.deleteConfirm":"Delete?","dashboard.openIn":"Open in {provider}","dashboard.viewTraceTooltip":"View AI Trace (Prompt/Response)","dashboard.syncSuccess":"Sync completed! Check your emails.","dashboard.syncFailed":"Sync failed. Check account status for details.","config.title":"Automation & Rules","config.rules":"Automation Rules","config.createRule":"Create New Rule","config.llmSettings":"AI Intelligence Settings","config.accounts.title":"Email Accounts","config.accounts.desc":"Connect and manage your email accounts","config.accounts.addNew":"Add New Account","config.accounts.yourAccounts":"Your Connected Accounts","config.accounts.noAccounts":"No email accounts connected yet","config.accounts.connectHelp":"Connect your first email account to start automating","config.accounts.disconnect":"Disconnect","config.gmail.connect":"Connect Gmail","config.gmail.connectDesc":"OAuth 2.0 or Service Account","config.gmail.credentialsDesc":"Paste your Google Cloud credentials JSON","config.gmail.authCodeDesc":"Enter the authorization code from Google","config.gmail.pasteJson":"Paste credentials.json content","config.gmail.downloadHelp":"Download from Google Cloud Console → APIs & Services → Credentials","config.gmail.orEnterManually":"Or enter manually","config.outlook.connect":"Connect Outlook","config.outlook.connectDesc":"Microsoft 365 or Outlook.com","config.outlook.credentialsDesc":"Paste your Azure App credentials JSON","config.outlook.instructions":"Follow the OAuth flow to connect","config.outlook.signinRequired":"Sign-in Required","config.outlook.openLogin":"Open Microsoft Login","config.outlook.waitingSignin":"Waiting for sign-in...","config.outlook.note":"Note: You need an Azure App Registration for this to work.","config.outlook.clientId":"Client ID (Application ID)","config.outlook.tenantIdOptional":"Tenant ID (Optional)","config.outlook.tenantHelp":'Default is "common". Use your specific Tenant ID for organization accounts.',"config.outlook.saveConnect":"Save & Connect","config.outlook.actionRequired":"Action Required","config.outlook.waitingAuth":"Waiting for authorization...","config.outlook.tenantPlaceholder":"common","config.model.title":"AI Model Configuration","config.model.desc":"Configure your AI model and processing settings","config.llm.title":"LLM","config.model.provider":"LLM Provider","config.model.defaultProvider":"RealTimeX AI (Default)","config.model.discovering":"Discovering...","config.model.name":"Model Name","config.model.selectModel":"Select a model","config.model.modelPlaceholder":"e.g. gpt-4o-mini","config.model.storagePath":"Storage Path","config.model.storagePlaceholder":"Path for model storage","config.model.storageHelp":"Local directory for caching models","config.model.syncInterval":"Sync Interval (minutes)","config.model.syncHelp":"How often to check for new emails","config.model.intelligentRename":"Intelligent Rename","config.model.renameHelp":"Use AI to suggest better file names","config.model.checkConnection":"Check Connection","config.model.saveConfig":"Save Configuration","config.providers.gmail":"Gmail","config.providers.outlook":"Outlook","config.storage.title":"Storage Path","config.storage.desc":"Choose where raw email files are stored locally","config.storage.label":"Local Storage Path","config.storage.placeholder":"e.g. /Users/you/Documents/email-archive","config.storage.help":"Must be writable. Leave blank to use the default application folder.","config.rename.title":"Intelligent Rename","config.rename.desc":"Control filename formatting for stored emails","config.rename.label":"Enable intelligent rename","config.rename.help":"Creates readable, slugified filenames instead of raw message IDs.","config.sync.title":"Sync Interval (minutes)","config.sync.desc":"Controls how often background sync runs","config.sync.label":"Minutes between sync runs","config.sync.help":"Lower values increase freshness but may use more resources.","config.embed.title":"Embedding (RAG)","config.embed.desc":"Configure embeddings for knowledge base search (RAG).","config.embed.provider":"Embedding Provider","config.embed.model":"Embedding Model","config.embed.modelPlaceholder":"e.g. text-embedding-3-small","config.embed.autoModel":"Auto (text-embedding-3-small)","config.embed.help":"Used for semantic search in the knowledge base.","config.embed.discovering":"Discovering...","config.embed.defaultProvider":"RealTimeX AI (Default)","config.byok.title":"Bring Your Own Key (BYOK)","config.byok.desc":"Use your own API keys for AI providers","config.byok.systemDefault":"Use system default","config.byok.googleTitle":"Google / Gmail","config.byok.microsoftTitle":"Microsoft / Outlook","config.byok.clientId":"Client ID","config.byok.clientSecret":"Client Secret","config.byok.clientSecretOptional":"Client Secret (Optional)","config.byok.tenantId":"Tenant ID","config.byok.save":"Save API Key","config.gmail.authSteps":`1. A new tab opened with Google Sign-In
60
105
  2. Sign in and authorize the app
61
106
  3. Copy the authorization code shown
62
- 4. Paste it below`,"config.gmail.authCode":"Authorization Code","config.gmail.clientIdPlaceholder":"xxx.apps.googleusercontent.com","config.gmail.clientSecretPlaceholder":"GOCSPX-...","config.gmail.authCodePlaceholder":"4/0AQlEd8x...","config.rules.actionsHelp":"Select one or more actions to execute when the rule matches","config.rules.instructionsPlaceholder":"e.g. Tell them I'm busy until Friday, but interested in the proposal.","config.rules.attachmentsOptional":"Attachments (Optional)","config.rules.days":"days","config.rules.placeholder.domain":"rta.vn","config.rules.placeholder.email":"john@example.com","config.rules.category.newsletter":"Newsletter","config.rules.category.spam":"Spam","config.rules.category.promotional":"Promotional","config.rules.category.transactional":"Transactional","config.rules.category.social":"Social","config.rules.category.support":"Support","config.rules.category.client":"Client","config.rules.category.internal":"Internal","config.rules.category.personal":"Personal","config.rules.category.other":"Other","config.rules.sentiment.positive":"Positive","config.rules.sentiment.neutral":"Neutral","config.rules.sentiment.negative":"Negative","config.rules.priority.high":"High","config.rules.priority.medium":"Medium","config.rules.priority.low":"Low","config.voice.title":"Voice & Speech","config.voice.desc":"Configure text-to-speech for AI responses","config.voice.autoTitle":"Auto-Speak AI Responses","config.voice.autoHelp":"Automatically read AI responses aloud using text-to-speech","config.voice.provider":"TTS Provider","config.voice.providerHelp":"Select the text-to-speech provider","config.voice.loadingProviders":"Loading providers...","config.voice.voice":"Voice","config.voice.selectVoice":"Select a voice","config.voice.noVoices":"No voices available","config.voice.voiceHelp":"Choose the voice personality for speech synthesis","config.voice.speed":"Speed","config.voice.speedSlow":"0.5x (Slower)","config.voice.speedFast":"2.0x (Faster)","config.voice.quality":"Quality","config.voice.qualityLow":"1 (Lower quality, faster)","config.voice.qualityHigh":"20 (Higher quality, slower)","config.voice.test":"Test","config.voice.save":"Save Settings","config.voice.testText":"Hello! This is a test of the text-to-speech system.","config.voice.piperLocal":"Piper (Local)","config.voice.toast.providersFailed":"Failed to load TTS providers. Ensure RealTimeX Desktop is running.","config.voice.toast.serviceFailed":"Failed to connect to TTS service","config.voice.toast.testFailed":"Failed to test text-to-speech","config.voice.toast.saved":"Voice & Speech settings saved","config.voice.toast.saveFailed":"Failed to save settings","config.voice.toast.autoOn":"Auto-speak AI responses enabled","config.voice.toast.autoOff":"Auto-speak AI responses disabled","config.voice.toast.updateFailed":"Failed to update setting","config.agent.systemInstruction":"You are the Configuration Wizard. Guide the user through setting up their accounts, rules, and system preferences. Explain what each setting does and help them troubleshoot connections.","config.toast.providersFailed":"Failed to load providers","config.toast.providersFailedFallback":"Failed to load providers. Using defaults.","config.toast.embedProvidersFailed":"Failed to load embedding providers","config.toast.embedProvidersFailedFallback":"Failed to load embedding providers. Using defaults.","config.toast.connectionFailed":"Connection failed","config.toast.systemRuleMissing":"System rule not found. Please sync your database.","config.toast.startConnectionFailed":"Failed to start connection. Please ensure you are logged in.","config.toast.startGmailFailed":"Failed to start Gmail connection","config.toast.detectedDesktopCreds":"Detected Desktop app credentials","config.toast.detectedWebCreds":"Detected Web app - make sure redirect URI is configured in Google Cloud Console","config.toast.missingGmailCreds":"Please provide both Client ID and Client Secret","config.toast.authorizeAndPaste":"Please authorize in the opened tab, then paste the code here","config.toast.oauthUrlFailed":"Failed to get OAuth URL","config.toast.saveCredsFailed":"Failed to save credentials","config.toast.missingAuthCode":"Please paste the authorization code","config.toast.gmailConnected":"Gmail account connected successfully!","config.toast.gmailConnectFailed":"Failed to connect Gmail","config.toast.missingOutlookClientId":"Please provide the Client ID","config.toast.deviceFlowFailed":"Failed to start device flow","config.toast.outlookStartFailed":"Failed to start Outlook connection","config.toast.outlookConnected":"Outlook account connected","config.toast.connectionTimedOut":"Connection timed out. Please try again.","config.toast.ruleNameRequired":"Please name your rule","config.toast.ruleActionRequired":"Please select at least one action","config.toast.ruleUpdated":"Rule updated","config.toast.ruleCreated":"Rule created","config.toast.ruleUpdateFailed":"Failed to update rule","config.toast.ruleCreateFailed":"Failed to create rule","config.toast.ruleSaveError":"An error occurred while saving the rule","config.toast.disconnectConfirm":"Are you sure you want to disconnect this account?","config.toast.accountDisconnected":"Account disconnected","config.toast.settingsSaved":"Settings saved","config.toast.fileUploaded":"File uploaded","config.toast.fileUploadFailed":"Failed to upload file","config.rules.edit":"Edit Rule","config.rules.create":"Create Rule","config.rules.createRule":"Create Rule","config.rules.desc":"Define conditions and actions for email automation","config.rules.name":"Rule Name","config.rules.namePlaceholder":"e.g., Archive Newsletters","config.rules.description":"Description","config.rules.descriptionPlaceholder":"What this rule does","config.rules.semanticHelp":"AI will match emails based on this description","config.rules.intent":"Intent","config.rules.intentPlaceholder":"What should happen when this rule triggers","config.rules.intentHelp":"Used to generate appropriate responses","config.rules.conditionField":"Condition Field","config.rules.aiAnalysis":"AI Analysis","config.rules.metadata":"Metadata","config.rules.category":"Category","config.rules.sentiment":"Sentiment","config.rules.priority":"Priority","config.rules.senderEmail":"Sender Email","config.rules.senderDomain":"Sender Domain","config.rules.senderContains":"Sender Contains","config.rules.subjectContains":"Subject Contains","config.rules.bodyContains":"Body Contains","config.rules.equalsValue":"Equals Value","config.rules.keywordsPlaceholder":"Enter keywords...","config.rules.olderThan":"Only if email is older than (days)","config.rules.olderThanHelp":"Leave empty or 0 to apply immediately","config.rules.performActions":"Then Perform Actions","config.rules.draftInstructions":"Draft Instructions","config.rules.contextHelp":"Specific context for AI to use when drafting","config.rules.addAttachment":"Add Attachment","config.rules.attachmentHelp":"Files will be attached to generated drafts","config.rules.uploading":"Uploading...","config.rules.saveChanges":"Save Changes","account.title":"Account Settings","account.subtitle":"Manage your profile and preferences","account.profile":"Profile","account.security":"Security","account.database":"Supabase","account.logout":"Logout","account.logoutSuccess":"Logged out successfully","account.version":"Version","account.profile.title":"Profile Information","account.profile.desc":"Update your personal information","account.profile.firstName":"First Name","account.profile.firstNamePlaceholder":"John","account.profile.lastName":"Last Name","account.profile.lastNamePlaceholder":"Doe","account.profile.email":"Email","account.profile.emailHelp":"This is your login email and cannot be changed","account.profile.sounds":"Sound & Haptic Feedback","account.profile.soundsHelp":"Play sounds for email notifications","account.profile.soundsEnabled":"Sounds enabled","account.profile.soundsDisabled":"Sounds disabled","account.profile.updated":"Profile updated successfully","account.profile.avatarUpdated":"Avatar updated successfully","account.profile.avatarError":"Failed to update avatar","account.security.title":"Security","account.security.desc":"Update your password","account.security.newPassword":"New Password","account.security.confirmPassword":"Confirm Password","account.security.updatePassword":"Update Password","account.security.enterPassword":"Please enter a password","account.security.passwordsMismatch":"Passwords do not match","account.security.passwordTooShort":"Password must be at least 6 characters","account.security.passwordChanged":"Password changed successfully","account.database.title":"Database Connection","account.database.desc":"Manage your Supabase connection","account.database.connected":"Connected","account.database.noConnection":"No Connection","account.database.configureHelp":"Configure your Supabase connection in the Setup Wizard","account.database.anonKey":"Anon Key","account.database.envAlert":"Connection configured via environment variables","account.database.changeConnection":"Change Connection","account.database.clearConfig":"Clear Configuration","account.database.clearConfirm":"Are you sure you want to clear your database configuration?","account.database.setup":"Setup Database","trace.runTrace":"Sync Run Trace","trace.fullLogFor":"Full log for account: {email}","trace.historicalLog":"Historical log for this synchronization run.","trace.loadingTrace":"Loading trace...","trace.noTraceEvents":"No granular trace events found for this run.","analytics.title":"Analytics Dashboard","analytics.totalEmails":"Total Emails","analytics.spamCaught":"Spam Caught","analytics.actionsTaken":"Actions Taken","analytics.accounts":"Accounts","analytics.categories":"Email Categories","analytics.recentActivity":"Recent Sync Activity","analytics.noActivity":"No sync activity yet","analytics.emails":"{count} emails","analytics.deleted":"{count} deleted","analytics.drafted":"{count} drafted","autopilot.title":"Auto-Pilot Rules","autopilot.rulesEnabled":"{enabled} of {total} rules enabled","autopilot.loadingRules":"Loading rules...","autopilot.loadError":"Failed to load rules","autopilot.deleteConfirm":"Are you sure you want to delete this rule?","autopilot.ruleDeleted":"Rule deleted","autopilot.ruleDeleteFailed":"Failed to delete rule","autopilot.ruleDeleteError":"An error occurred while deleting the rule","autopilot.ruleUpdated":"Rule updated","autopilot.ruleCreated":"Rule created","autopilot.ruleUpdateFailed":"Failed to update rule","autopilot.ruleCreateFailed":"Failed to create rule","autopilot.ruleSaveError":"An error occurred while saving the rule","autopilot.fileUploaded":"File uploaded","autopilot.fileUploadFailed":"Failed to upload file","autopilot.noRulesTitle":"No Rules Yet","autopilot.noRulesDesc":"Rules will be automatically created when you sign up or connect your first email account.","autopilot.addCustomRule":"Add Custom Rule","autopilot.refresh":"Refresh","autopilot.infoDesc":"Auto-Pilot rules use AI to automatically organize your inbox. Toggle any rule on or off to customize behavior.","autopilot.customRules":"Custom Rules","autopilot.customRulesDesc":"Rules you've created manually","autopilot.category.email_organization.label":"Email Organization","autopilot.category.email_organization.desc":"Automatically organize common email types","autopilot.category.priority_alerts.label":"Priority & Alerts","autopilot.category.priority_alerts.desc":"Surface urgent and important messages","autopilot.category.development.label":"Development","autopilot.category.development.desc":"GitHub, CI/CD, and dev tool notifications","autopilot.category.sales_business.label":"Sales & Business","autopilot.category.sales_business.desc":"Lead management and business communications","autopilot.category.operations.label":"Operations","autopilot.category.operations.desc":"Support, internal requests, and system alerts","autopilot.enabledCount":"({enabled}/{total} enabled)","autopilot.badge":"Auto-Pilot","autopilot.editRuleTooltip":"Edit Rule","autopilot.deleteRuleTooltip":"Delete Rule","autopilot.triggeredToday":"{count} today","autopilot.editDialog.editTitle":"Edit Rule","autopilot.editDialog.createTitle":"Create Custom Rule","autopilot.editDialog.desc":"Define a condition based on AI analysis to trigger an action.","autopilot.editDialog.ruleName":"Rule Name","autopilot.editDialog.namePlaceholder":"e.g. Archive Newsletters","autopilot.editDialog.description":"Description","autopilot.editDialog.descPlaceholder":"e.g. Handle all marketing newsletters and promotional content from subscription services","autopilot.editDialog.descriptionHelp":"Describe what this rule is for. The AI uses this to semantically match emails.","autopilot.editDialog.intent":"Intent","autopilot.editDialog.intentPlaceholder":"e.g. Politely decline all sales pitches","autopilot.editDialog.intentHelp":"The goal of this rule. Used to generate appropriate draft replies.","autopilot.editDialog.conditionField":"If Condition Field","autopilot.editDialog.aiAnalysisGroup":"AI Analysis","autopilot.editDialog.metadataGroup":"Metadata","autopilot.editDialog.category":"Category","autopilot.editDialog.sentiment":"Sentiment","autopilot.editDialog.priority":"Priority","autopilot.editDialog.senderEmail":"Specific Email (Exact)","autopilot.editDialog.senderDomain":"Email Domain (@...)","autopilot.editDialog.senderContains":"Sender contains...","autopilot.editDialog.subjectContains":"Subject contains...","autopilot.editDialog.bodyContains":"Body contains...","autopilot.editDialog.equalsValue":"Equals Value","autopilot.editDialog.cat.newsletter":"Newsletter","autopilot.editDialog.cat.news":"News","autopilot.editDialog.cat.spam":"Spam","autopilot.editDialog.cat.promotional":"Promotional","autopilot.editDialog.cat.transactional":"Transactional","autopilot.editDialog.cat.social":"Social","autopilot.editDialog.cat.support":"Support","autopilot.editDialog.cat.client":"Client","autopilot.editDialog.cat.internal":"Internal","autopilot.editDialog.cat.personal":"Personal","autopilot.editDialog.cat.other":"Other","autopilot.editDialog.sent.positive":"Positive","autopilot.editDialog.sent.neutral":"Neutral","autopilot.editDialog.sent.negative":"Negative","autopilot.editDialog.prio.high":"High","autopilot.editDialog.prio.medium":"Medium","autopilot.editDialog.prio.low":"Low","autopilot.editDialog.keywordsPlaceholder":"Keywords...","autopilot.editDialog.olderThan":"Only if email is older than... (Optional)","autopilot.editDialog.days":"days","autopilot.editDialog.olderThanHelp":"Leave empty or 0 to apply rule immediately upon receipt.","autopilot.editDialog.performActions":"Then Perform Action(s)","autopilot.editDialog.actionsDesc":"Select one or more actions to execute when the rule matches","autopilot.editDialog.action.archive":"Archive Email","autopilot.editDialog.action.delete":"Delete Email","autopilot.editDialog.action.draft":"Draft Reply","autopilot.editDialog.action.star":"Star / Flag","autopilot.editDialog.draftInstructions":"Draft Instructions (Context)","autopilot.editDialog.draftInstPlaceholder":"e.g. Tell them I'm busy until Friday, but interested in the proposal.","autopilot.editDialog.draftInstHelp":"Specific context for the AI ghostwriter.","autopilot.editDialog.attachments":"Attachments (Optional)","autopilot.editDialog.uploading":"Uploading...","autopilot.editDialog.addAttachment":"Add Attachment","autopilot.editDialog.attachmentsHelp":"Files will be attached to every draft generated by this rule.","autopilot.onboarding.allSet":"All Set!","autopilot.onboarding.enabledDesc":"We've enabled {count} automation rules for you","autopilot.onboarding.rules":"rules","autopilot.onboarding.universalDesc":"Essential rules that help everyone stay organized","autopilot.onboarding.executiveDesc":"Focus on high-priority communications and strategic matters","autopilot.onboarding.developerDesc":"Surface critical alerts and filter tool noise","autopilot.onboarding.salesDesc":"Prioritize leads and customer communications","autopilot.onboarding.operationsDesc":"Organize tickets and internal communications","autopilot.onboarding.tip":"Tip: All rules are enabled by default, but you can customize or disable them anytime in the Auto-Pilot section.","autopilot.onboarding.start":"Start Using Email Automator →","autopilot.role.title":"One Last Step!","autopilot.role.subtitle":"What best describes your role? We'll set up the right automation rules for you.","autopilot.role.executive.label":"Executive / Leadership","autopilot.role.executive.desc":"Focus on VIPs, contracts, and strategic communications","autopilot.role.executive.preview":"VIP Client Prioritizer;Travel Organizer;Legal & Contracts","autopilot.role.sales.label":"Sales / Business Development","autopilot.role.sales.desc":"Prioritize leads and customer communications","autopilot.role.sales.preview":"Customer Questions;CRM Organizer;Proposal Tracker","autopilot.role.developer.label":"Developer / Engineer","autopilot.role.developer.desc":"Surface critical alerts and filter tool noise","autopilot.role.developer.preview":"System Alerts;Code Reviews;Project Management","autopilot.role.operations.label":"Operations / Support","autopilot.role.operations.desc":"Organize tickets and internal communications","autopilot.role.operations.preview":"Support Tickets;System Monitoring;Internal Comms","autopilot.role.marketing.label":"Marketing","autopilot.role.marketing.desc":"Track campaigns and customer engagement","autopilot.role.marketing.preview":"Campaign Tracking;Analytics Reports;Social Media","autopilot.role.other.label":"Other / Manual Setup","autopilot.role.other.desc":"I'll configure my own automation rules","autopilot.role.includes":"Includes:","autopilot.role.skip":"Skip for now","autopilot.role.settingUp":"Setting up...","autopilot.role.continue":"Continue →","terminal.title":"Agent Terminal","terminal.liveActivity":"Live Activity","terminal.syncing":"SYNCING","terminal.live":"LIVE","terminal.stopSync":"STOP SYNC","terminal.clear":"Clear","terminal.waiting":"Waiting for agent activity...","terminal.details":"Details","terminal.useless":"USELESS","terminal.relevant":"RELEVANT","terminal.executionComplete":"Execution Complete","terminal.batchFinished":"Batch Sync Finished","terminal.processed":"Processed","terminal.actions":"Actions","terminal.action.delete":"Moved to Trash","terminal.action.archive":"Archived Email","terminal.action.draft":"Drafted Reply","terminal.action.star":"Starred Email","persona.title":"Digital Persona","persona.subtitle":"Manage how your AI assistant represents you.","persona.identity":"Identity","persona.communication":"Communication","persona.automation":"Automation","persona.network":"Network","persona.edit.title":"Edit Persona","persona.edit.desc":"Update your digital assistant preferences.","common.edit":"Edit"},lL=Object.freeze(Object.defineProperty({__proto__:null,default:Tk},Symbol.toStringTag,{value:"Module"})),z1={en:{name:"English",flag:"🇺🇸"},fr:{name:"Français",flag:"🇫🇷"},es:{name:"Español",flag:"🇪🇸"},ja:{name:"日本語",flag:"🇯🇵"},ko:{name:"한국어",flag:"🇰🇷"},vi:{name:"Tiếng Việt",flag:"🇻🇳"}},Tu=Tk,Ek=S.createContext(void 0);function cL({children:e}){const[t,n]=S.useState(()=>localStorage.getItem("app_language")||"en"),[s,a]=S.useState(t==="en"?Tu:{}),[l,u]=S.useState(t!=="en");S.useEffect(()=>{localStorage.setItem("app_language",t),document.documentElement.lang=t,(async()=>{if(t==="en"){a(Tu),u(!1);return}u(!0);try{const p=await oL(Object.assign({"../locales/languages/en.json":()=>Ni(()=>Promise.resolve().then(()=>lL),void 0),"../locales/languages/es.json":()=>Ni(()=>import("./es-BySeIenb.js"),[]),"../locales/languages/fr.json":()=>Ni(()=>import("./fr-Cj4xUTOj.js"),[]),"../locales/languages/ja.json":()=>Ni(()=>import("./ja-DeBZHkY-.js"),[]),"../locales/languages/ko.json":()=>Ni(()=>import("./ko-CHMiWHbo.js"),[]),"../locales/languages/vi.json":()=>Ni(()=>import("./vi-B4Rp8hRI.js"),[])}),`../locales/languages/${t}.json`,4);a(p.default)}catch(p){console.error(`Failed to load translations for ${t}:`,p),a(Tu)}finally{u(!1)}})()},[t]);const d=m=>{n(m)},h=m=>s[m]||Tu[m]||m;return o.jsx(Ek.Provider,{value:{language:t,setLanguage:d,t:h,isLoading:l},children:e})}function tt(){const e=S.useContext(Ek);if(e===void 0)throw new Error("useLanguage must be used within a LanguageProvider");return e}function iy({className:e}){const{language:t,setLanguage:n}=tt(),[s,a]=S.useState(!1),l=S.useRef(null);S.useEffect(()=>{function d(h){l.current&&!l.current.contains(h.target)&&a(!1)}return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[]);const u=z1[t];return o.jsxs("div",{className:me("relative z-50",e),ref:l,children:[o.jsxs("button",{onClick:()=>a(!s),className:me("flex items-center gap-2 px-3 py-2 rounded-lg transition-all duration-200","bg-secondary/50 hover:bg-secondary border border-border/50 hover:border-border shadow-sm",s&&"ring-2 ring-primary/20 border-primary/50"),children:[o.jsx("span",{className:"text-lg leading-none",children:u.flag}),o.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:t}),o.jsx(XS,{className:me("w-3 h-3 transition-transform duration-200",s&&"rotate-180")})]}),s&&o.jsxs("div",{className:me("absolute right-0 mt-2 w-48 rounded-xl border border-border bg-card p-1.5 shadow-xl animate-in fade-in zoom-in duration-200","backdrop-blur-xl"),children:[o.jsx("div",{className:"px-2 py-1.5 mb-1 text-[10px] font-bold text-muted-foreground uppercase tracking-widest",children:"Choose Language"}),Object.entries(z1).map(([d,{name:h,flag:m}])=>o.jsxs("button",{onClick:()=>{n(d),a(!1)},className:me("flex items-center justify-between w-full px-3 py-2 rounded-lg text-sm transition-colors",t===d?"bg-primary/10 text-primary font-bold":"hover:bg-secondary text-muted-foreground hover:text-foreground"),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-lg leading-none",children:m}),o.jsx("span",{children:h})]}),t===d&&o.jsx(Ti,{className:"w-4 h-4"})]},d))]})]})}const Ck=S.createContext(void 0);function uL({children:e}){const[t,n]=S.useState(!1),[s,a]=S.useState(!1),[l,u]=S.useState(null),d=S.useRef(null),h=S.useRef(null),m=S.useRef(null),p=S.useRef(null),g=S.useRef(0),v=S.useCallback(()=>{if(p.current&&(p.current.cancel().catch(()=>{}),p.current=null),m.current){try{m.current.stop(),m.current.disconnect()}catch{}m.current=null}d.current&&(d.current.pause(),d.current.currentTime=0,d.current=null),n(!1),a(!1),u(null),g.current++},[]),b=S.useCallback((k,N)=>new Promise((R,T)=>{k.decodeAudioData(N,D=>{const U=k.createBufferSource();U.buffer=D,U.connect(k.destination),U.onended=()=>R(),U.start(0),m.current=U},D=>T(D))}),[]),w=S.useCallback(async(k,N,R={})=>{v();const T=g.current;a(!0),u(N||null);const D={text:k,...R};console.log("[TTSContext] Sending TTS request:",D);try{const U=await fetch("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!U.ok)throw new Error("TTS generation failed");const M=await U.blob(),B=URL.createObjectURL(M),P=new Audio(B);d.current=P,P.onplay=()=>n(!0),P.onended=()=>{g.current===T&&(n(!1),a(!1),u(null),URL.revokeObjectURL(B))},P.onerror=()=>{g.current===T&&(n(!1),a(!1),u(null),URL.revokeObjectURL(B),console.error("[TTSContext] Audio playback failed"))},await P.play()}catch(U){console.error("[TTSContext] Speak failed:",U),g.current===T&&(a(!1),u(null))}},[v]),j=S.useCallback(async(k,N,R={})=>{v();const T=g.current;a(!0),u(N||null);try{const D=await fetch("/api/tts/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:k,...R})});if(!D.ok)throw new Error("TTS streaming failed");const U=D.body?.getReader();if(!U)throw new Error("No response body");p.current=U;const M=new TextDecoder;let B="";const P=[];h.current||(h.current=new(window.AudioContext||window.webkitAudioContext));const H=h.current;for(;g.current===T;){const{done:O,value:Q}=await U.read();if(O)break;B+=M.decode(Q,{stream:!0});const G=B.split(`
63
- `);B=G.pop()||"";for(const he of G){const se=he.trim();if(!se||!se.startsWith("data:"))continue;const ae=se.slice(5).trim();if(ae)try{const L=JSON.parse(ae);if(L.audio){const V=atob(L.audio),q=new Uint8Array(V.length);for(let de=0;de<V.length;de++)q[de]=V.charCodeAt(de);P.push(q.buffer),P.length===1&&(n(!0),await b(H,q.buffer))}}catch{}}}if(g.current===T)for(let O=1;O<P.length&&g.current===T;O++)await b(H,P[O]);g.current===T&&(n(!1),a(!1),u(null))}catch(D){console.error("[TTSContext] Stream failed:",D),g.current===T&&(n(!1),a(!1),u(null))}},[v,b]);return o.jsx(Ck.Provider,{value:{isPlaying:t,isSpeaking:s,speakingId:l,currentAudio:d.current,speak:w,speakStream:j,stop:v},children:e})}function Ak(){const e=S.useContext(Ck);if(e===void 0)throw new Error("useTTSContext must be used within a TTSProvider");return e}function ay(){const{speak:e,speakStream:t,stop:n,isPlaying:s,isSpeaking:a,speakingId:l}=Ak(),u=S.useCallback(async(h,m,p={})=>e(h,m,p),[e]),d=S.useCallback(async(h,m,p={})=>t(h,m,p),[t]);return{speak:u,speakStream:d,stop:n,isPlaying:s,isSpeaking:a,speakingId:l}}const Rk=S.createContext(void 0),L1={page_id:"global",system_instruction:"You are a helpful Email Assistant. Use general knowledge to help the user."};function I1(){return vp().autoPlay}function dL({children:e}){const[t,n]=S.useState(L1),[s,a]=S.useState([]),[l,u]=S.useState("idle"),{speak:d}=ay(),h=S.useCallback(g=>{n(v=>v.page_id===g.page_id&&JSON.stringify(v.data)===JSON.stringify(g.data)?v:(console.log(`[AgentContext] Registering new agent context: ${g.page_id}`),g))},[]),m=S.useCallback(()=>{n(L1)},[]),p=S.useCallback(async g=>{u("thinking");const v={role:"user",content:g};a(b=>[...b,v]);try{const b="/api/agent/chat",w=localStorage.getItem("supabase.auth.token"),j=gp(),k={...t,tools:t.tools?.map(D=>({name:D.name,description:D.description,parameters:D.parameters}))},N={message:g,context:k,history:s.slice(-10)},R=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w||""}`,"X-Supabase-Url":j.edgeFunctionsUrl.replace("/functions/v1",""),"X-Supabase-Anon-Key":j.anonKey},body:JSON.stringify(N)});if(!R.ok)throw new Error(`API request failed: ${R.status} ${R.statusText}`);const T=await R.json();if(T.success&&T.response){const D=T.response.content,U=T.response.action,M={role:"assistant",content:D};if(a(B=>[...B,M]),D&&I1()&&(u("speaking"),await d(D,void 0,vp())),U&&t.tools){console.log(`[AgentContext] Executing tool: ${U.name}`,U.args);const B=t.tools.find(P=>P.name===U.name);if(B)try{if(B.parameters?.required){const O=B.parameters.required.filter(Q=>!(Q in(U.args||{})));if(O.length>0)throw new Error(`Missing required parameters: ${O.join(", ")}`)}const P=await B.callback(U.args),H=P?.message||`✓ Action completed: ${U.name}`;a(O=>[...O,{role:"system",content:H}]),console.log("[AgentContext] Tool executed successfully:",P)}catch(P){console.error("[AgentContext] Tool execution failed:",P);const H=P?.message||"Unknown error occurred";a(O=>[...O,{role:"system",content:`⚠️ Error: ${H}`}]),I1()&&await d(`Error: ${H}`,void 0,vp())}else{const P=`Tool "${U.name}" not found. Available tools: ${t.tools.map(H=>H.name).join(", ")}`;console.warn(`[AgentContext] ${P}`),a(H=>[...H,{role:"system",content:`⚠️ ${P}`}])}}u("idle")}else{const D=T.error||"Sorry, I encountered an error processing your request.";console.error("[AgentContext] API error:",T.error),a(U=>[...U,{role:"assistant",content:`⚠️ ${D}`}]),u("idle")}}catch(b){console.error("[AgentContext] Chat failed:",b);let w="Network error. Please try again.";b.message?.includes("Failed to fetch")?w="Cannot connect to the AI service. Please ensure the API server is running.":b.message&&(w=b.message),a(j=>[...j,{role:"system",content:`⚠️ ${w}`}]),u("idle")}},[t,s,d]);return o.jsx(Rk.Provider,{value:{currentConfig:t,registerAgent:h,chatHistory:s,agentState:l,sendMessage:p,resetAgent:m},children:e})}function Ok(){const e=S.useContext(Rk);if(e===void 0)throw new Error("useAgentContext must be used within an AgentProvider");return e}function oy(e){const{registerAgent:t,resetAgent:n}=Ok();S.useRef(e);const s=JSON.stringify(e);S.useEffect(()=>(t(e),()=>{n()}),[s,t,n])}const Xa="2.22.1",fL="20260203145936";function hL(e,t){const n=e.split(".").map(Number),s=t.split(".").map(Number);for(let a=0;a<Math.max(n.length,s.length);a++){const l=n[a]||0,u=s[a]||0;if(l>u)return 1;if(l<u)return-1}return 0}async function mL(e){try{const{data:t,error:n}=await e.rpc("get_latest_migration_timestamp");return n?n.code==="42883"?(console.info("[Migration Check] RPC function missing - assuming fresh DB."),{version:null,latestMigrationTimestamp:"0"}):(console.warn("Could not get latest migration timestamp:",n.message),{version:null,latestMigrationTimestamp:null}):{version:Xa,latestMigrationTimestamp:t||null}}catch(t){return console.error("Error checking database migration info:",t),{version:null,latestMigrationTimestamp:null}}}async function ly(e){const t=Xa,n=fL,s=await mL(e);if(console.log("[Migration Check]",{appVersion:t,appMigrationTimestamp:n,dbVersion:s.version,dbMigrationTimestamp:s.latestMigrationTimestamp}),s.latestMigrationTimestamp&&s.latestMigrationTimestamp.trim()!==""){const a=n,l=s.latestMigrationTimestamp;return a>l?{needsMigration:!0,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:l,message:`New migrations available. Database is at ${l}, app has ${a}.`}:a<l?(console.warn("[Migration Check] DB is ahead of app - possible downgrade"),{needsMigration:!1,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:l,message:`Database (${l}) is ahead of app (${a}).`}):(console.log("[Migration Check] Timestamps match - database is up-to-date"),{needsMigration:!1,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:l,message:"Database schema is up-to-date."})}if(s.version){console.log("[Migration Check] Legacy DB detected (no timestamp). Falling back to SemVer.");const a=hL(t,s.version);return a>0?{needsMigration:!0,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:null,message:`Database schema (v${s.version}) is outdated. Migration to v${t} required.`}:a===0?(console.warn("[Migration Check] Legacy DB with matching version - forcing migration to add timestamp tracking"),{needsMigration:!0,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:null,message:`Database lacks timestamp tracking. Please run migration to upgrade to modern schema (v${t}).`}):{needsMigration:!1,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:null,message:`Database version (v${s.version}) is ahead of app (v${t}).`}}return console.log("[Migration Check] No DB info found - assuming migration needed"),{needsMigration:!0,appVersion:t,dbVersion:null,latestMigrationTimestamp:null,message:`Database schema unknown. Migration required to v${t}.`}}const Dk="email_automator_migration_reminder_dismissed_at";function pL(e=24){try{const t=localStorage.getItem(Dk);if(!t)return!1;const n=new Date(t).getTime();return(Date.now()-n)/(1e3*60*60)<e}catch(t){return console.error("Error checking migration reminder:",t),!1}}function gL(){try{localStorage.setItem(Dk,new Date().toISOString())}catch(e){console.error("Error dismissing migration reminder:",e)}}const qp={step:"welcome",managed:{accessToken:"",organizations:[],selectedOrg:"",projectName:"Email-Automator-AI",region:"us-east-1",isFetchingOrgs:!1},manual:{url:"",anonKey:""},projectId:"",logs:[],error:null,isMigrating:!1,migrationStatus:null};function yL(e,t){switch(t.type){case"SET_STEP":return{...e,step:t.payload,error:null};case"SET_ACCESS_TOKEN":return{...e,managed:{...e.managed,accessToken:t.payload}};case"SET_ORGANIZATIONS":return{...e,managed:{...e.managed,organizations:t.payload,selectedOrg:t.payload.length>0?t.payload[0].id:""}};case"SET_SELECTED_ORG":return{...e,managed:{...e.managed,selectedOrg:t.payload}};case"SET_PROJECT_NAME":return{...e,managed:{...e.managed,projectName:t.payload}};case"SET_REGION":return{...e,managed:{...e.managed,region:t.payload}};case"SET_FETCHING_ORGS":return{...e,managed:{...e.managed,isFetchingOrgs:t.payload}};case"SET_MANUAL_URL":return{...e,manual:{...e.manual,url:t.payload}};case"SET_MANUAL_ANON_KEY":return{...e,manual:{...e.manual,anonKey:t.payload}};case"SET_PROJECT_ID":return{...e,projectId:t.payload};case"ADD_LOG":return{...e,logs:[...e.logs,{...t.payload,timestamp:Date.now()}].slice(-500)};case"CLEAR_LOGS":return{...e,logs:[]};case"SET_ERROR":return{...e,error:t.payload};case"SET_MIGRATING":return{...e,isMigrating:t.payload};case"SET_MIGRATION_STATUS":return{...e,migrationStatus:t.payload};case"RESET_MANAGED_FLOW":return{...e,managed:{...qp.managed},error:null};case"RESET_MANUAL_FLOW":return{...e,manual:{...qp.manual},error:null};default:return e}}function Cm(e){const t=e.trim();return t?t.startsWith("http://")||t.startsWith("https://")?t:`https://${t}.supabase.co`:""}function Mk(e){const t=e.trim();return t?t.startsWith("sbp_")?t.length<20?{valid:!1,message:"Token is too short"}:{valid:!0,message:"Valid access token"}:{valid:!1,message:"Token must start with sbp_"}:{valid:!1,message:"Access token is required"}}function U1(e){const t=e.trim();if(!t)return null;if(!t.includes(".")&&!t.includes("/"))return t;try{return new URL(t.startsWith("http")?t:`https://${t}`).hostname.split(".")[0]||null}catch{return null}}class xL{buffer="";processChunk(t){const n=[];this.buffer+=t;const s=this.buffer.split(`
107
+ 4. Paste it below`,"config.gmail.authCode":"Authorization Code","config.gmail.clientIdPlaceholder":"xxx.apps.googleusercontent.com","config.gmail.clientSecretPlaceholder":"GOCSPX-...","config.gmail.authCodePlaceholder":"4/0AQlEd8x...","config.rules.actionsHelp":"Select one or more actions to execute when the rule matches","config.rules.instructionsPlaceholder":"e.g. Tell them I'm busy until Friday, but interested in the proposal.","config.rules.attachmentsOptional":"Attachments (Optional)","config.rules.days":"days","config.rules.placeholder.domain":"rta.vn","config.rules.placeholder.email":"john@example.com","config.rules.category.newsletter":"Newsletter","config.rules.category.spam":"Spam","config.rules.category.promotional":"Promotional","config.rules.category.transactional":"Transactional","config.rules.category.social":"Social","config.rules.category.support":"Support","config.rules.category.client":"Client","config.rules.category.internal":"Internal","config.rules.category.personal":"Personal","config.rules.category.other":"Other","config.rules.sentiment.positive":"Positive","config.rules.sentiment.neutral":"Neutral","config.rules.sentiment.negative":"Negative","config.rules.priority.high":"High","config.rules.priority.medium":"Medium","config.rules.priority.low":"Low","config.voice.title":"Voice & Speech","config.voice.desc":"Configure text-to-speech for AI responses","config.voice.autoTitle":"Auto-Speak AI Responses","config.voice.autoHelp":"Automatically read AI responses aloud using text-to-speech","config.voice.provider":"TTS Provider","config.voice.providerHelp":"Select the text-to-speech provider","config.voice.loadingProviders":"Loading providers...","config.voice.voice":"Voice","config.voice.selectVoice":"Select a voice","config.voice.noVoices":"No voices available","config.voice.voiceHelp":"Choose the voice personality for speech synthesis","config.voice.speed":"Speed","config.voice.speedSlow":"0.5x (Slower)","config.voice.speedFast":"2.0x (Faster)","config.voice.quality":"Quality","config.voice.qualityLow":"1 (Lower quality, faster)","config.voice.qualityHigh":"20 (Higher quality, slower)","config.voice.test":"Test","config.voice.save":"Save Settings","config.voice.testText":"Hello! This is a test of the text-to-speech system.","config.voice.piperLocal":"Piper (Local)","config.voice.toast.providersFailed":"Failed to load TTS providers. Ensure RealTimeX Desktop is running.","config.voice.toast.serviceFailed":"Failed to connect to TTS service","config.voice.toast.testFailed":"Failed to test text-to-speech","config.voice.toast.saved":"Voice & Speech settings saved","config.voice.toast.saveFailed":"Failed to save settings","config.voice.toast.autoOn":"Auto-speak AI responses enabled","config.voice.toast.autoOff":"Auto-speak AI responses disabled","config.voice.toast.updateFailed":"Failed to update setting","config.agent.systemInstruction":"You are the Configuration Wizard. Guide the user through setting up their accounts, rules, and system preferences. Explain what each setting does and help them troubleshoot connections.","config.toast.providersFailed":"Failed to load providers","config.toast.providersFailedFallback":"Failed to load providers. Using defaults.","config.toast.embedProvidersFailed":"Failed to load embedding providers","config.toast.embedProvidersFailedFallback":"Failed to load embedding providers. Using defaults.","config.toast.connectionFailed":"Connection failed","config.toast.systemRuleMissing":"System rule not found. Please sync your database.","config.toast.startConnectionFailed":"Failed to start connection. Please ensure you are logged in.","config.toast.startGmailFailed":"Failed to start Gmail connection","config.toast.detectedDesktopCreds":"Detected Desktop app credentials","config.toast.detectedWebCreds":"Detected Web app - make sure redirect URI is configured in Google Cloud Console","config.toast.missingGmailCreds":"Please provide both Client ID and Client Secret","config.toast.authorizeAndPaste":"Please authorize in the opened tab, then paste the code here","config.toast.oauthUrlFailed":"Failed to get OAuth URL","config.toast.saveCredsFailed":"Failed to save credentials","config.toast.missingAuthCode":"Please paste the authorization code","config.toast.gmailConnected":"Gmail account connected successfully!","config.toast.gmailConnectFailed":"Failed to connect Gmail","config.toast.missingOutlookClientId":"Please provide the Client ID","config.toast.deviceFlowFailed":"Failed to start device flow","config.toast.outlookStartFailed":"Failed to start Outlook connection","config.toast.outlookConnected":"Outlook account connected","config.toast.connectionTimedOut":"Connection timed out. Please try again.","config.toast.ruleNameRequired":"Please name your rule","config.toast.ruleActionRequired":"Please select at least one action","config.toast.ruleUpdated":"Rule updated","config.toast.ruleCreated":"Rule created","config.toast.ruleUpdateFailed":"Failed to update rule","config.toast.ruleCreateFailed":"Failed to create rule","config.toast.ruleSaveError":"An error occurred while saving the rule","config.toast.disconnectConfirm":"Are you sure you want to disconnect this account?","config.toast.accountDisconnected":"Account disconnected","config.toast.settingsSaved":"Settings saved","config.toast.fileUploaded":"File uploaded","config.toast.fileUploadFailed":"Failed to upload file","config.rules.edit":"Edit Rule","config.rules.create":"Create Rule","config.rules.createRule":"Create Rule","config.rules.desc":"Define conditions and actions for email automation","config.rules.name":"Rule Name","config.rules.namePlaceholder":"e.g., Archive Newsletters","config.rules.description":"Description","config.rules.descriptionPlaceholder":"What this rule does","config.rules.semanticHelp":"AI will match emails based on this description","config.rules.intent":"Intent","config.rules.intentPlaceholder":"What should happen when this rule triggers","config.rules.intentHelp":"Used to generate appropriate responses","config.rules.conditionField":"Condition Field","config.rules.aiAnalysis":"AI Analysis","config.rules.metadata":"Metadata","config.rules.category":"Category","config.rules.sentiment":"Sentiment","config.rules.priority":"Priority","config.rules.senderEmail":"Sender Email","config.rules.senderDomain":"Sender Domain","config.rules.senderContains":"Sender Contains","config.rules.subjectContains":"Subject Contains","config.rules.bodyContains":"Body Contains","config.rules.equalsValue":"Equals Value","config.rules.keywordsPlaceholder":"Enter keywords...","config.rules.olderThan":"Only if email is older than (days)","config.rules.olderThanHelp":"Leave empty or 0 to apply immediately","config.rules.performActions":"Then Perform Actions","config.rules.draftInstructions":"Draft Instructions","config.rules.contextHelp":"Specific context for AI to use when drafting","config.rules.addAttachment":"Add Attachment","config.rules.attachmentHelp":"Files will be attached to generated drafts","config.rules.uploading":"Uploading...","config.rules.saveChanges":"Save Changes","account.title":"Account Settings","account.subtitle":"Manage your profile and preferences","account.profile":"Profile","account.security":"Security","account.database":"Supabase","account.logout":"Logout","account.logoutSuccess":"Logged out successfully","account.version":"Version","account.profile.title":"Profile Information","account.profile.desc":"Update your personal information","account.profile.firstName":"First Name","account.profile.firstNamePlaceholder":"John","account.profile.lastName":"Last Name","account.profile.lastNamePlaceholder":"Doe","account.profile.email":"Email","account.profile.emailHelp":"This is your login email and cannot be changed","account.profile.sounds":"Sound & Haptic Feedback","account.profile.soundsHelp":"Play sounds for email notifications","account.profile.soundsEnabled":"Sounds enabled","account.profile.soundsDisabled":"Sounds disabled","account.profile.updated":"Profile updated successfully","account.profile.avatarUpdated":"Avatar updated successfully","account.profile.avatarError":"Failed to update avatar","account.security.title":"Security","account.security.desc":"Update your password","account.security.newPassword":"New Password","account.security.confirmPassword":"Confirm Password","account.security.updatePassword":"Update Password","account.security.enterPassword":"Please enter a password","account.security.passwordsMismatch":"Passwords do not match","account.security.passwordTooShort":"Password must be at least 6 characters","account.security.passwordChanged":"Password changed successfully","account.database.title":"Database Connection","account.database.desc":"Manage your Supabase connection","account.database.connected":"Connected","account.database.noConnection":"No Connection","account.database.configureHelp":"Configure your Supabase connection in the Setup Wizard","account.database.anonKey":"Anon Key","account.database.envAlert":"Connection configured via environment variables","account.database.changeConnection":"Change Connection","account.database.clearConfig":"Clear Configuration","account.database.clearConfirm":"Are you sure you want to clear your database configuration?","account.database.setup":"Setup Database","trace.runTrace":"Sync Run Trace","trace.fullLogFor":"Full log for account: {email}","trace.historicalLog":"Historical log for this synchronization run.","trace.loadingTrace":"Loading trace...","trace.noTraceEvents":"No granular trace events found for this run.","analytics.title":"Analytics Dashboard","analytics.totalEmails":"Total Emails","analytics.spamCaught":"Spam Caught","analytics.actionsTaken":"Actions Taken","analytics.accounts":"Accounts","analytics.categories":"Email Categories","analytics.recentActivity":"Recent Sync Activity","analytics.noActivity":"No sync activity yet","analytics.emails":"{count} emails","analytics.deleted":"{count} deleted","analytics.drafted":"{count} drafted","autopilot.title":"Auto-Pilot Rules","autopilot.rulesEnabled":"{enabled} of {total} rules enabled","autopilot.loadingRules":"Loading rules...","autopilot.loadError":"Failed to load rules","autopilot.deleteConfirm":"Are you sure you want to delete this rule?","autopilot.ruleDeleted":"Rule deleted","autopilot.ruleDeleteFailed":"Failed to delete rule","autopilot.ruleDeleteError":"An error occurred while deleting the rule","autopilot.ruleUpdated":"Rule updated","autopilot.ruleCreated":"Rule created","autopilot.ruleUpdateFailed":"Failed to update rule","autopilot.ruleCreateFailed":"Failed to create rule","autopilot.ruleSaveError":"An error occurred while saving the rule","autopilot.fileUploaded":"File uploaded","autopilot.fileUploadFailed":"Failed to upload file","autopilot.noRulesTitle":"No Rules Yet","autopilot.noRulesDesc":"Rules will be automatically created when you sign up or connect your first email account.","autopilot.addCustomRule":"Add Custom Rule","autopilot.refresh":"Refresh","autopilot.infoDesc":"Auto-Pilot rules use AI to automatically organize your inbox. Toggle any rule on or off to customize behavior.","autopilot.customRules":"Custom Rules","autopilot.customRulesDesc":"Rules you've created manually","autopilot.category.email_organization.label":"Email Organization","autopilot.category.email_organization.desc":"Automatically organize common email types","autopilot.category.priority_alerts.label":"Priority & Alerts","autopilot.category.priority_alerts.desc":"Surface urgent and important messages","autopilot.category.development.label":"Development","autopilot.category.development.desc":"GitHub, CI/CD, and dev tool notifications","autopilot.category.sales_business.label":"Sales & Business","autopilot.category.sales_business.desc":"Lead management and business communications","autopilot.category.operations.label":"Operations","autopilot.category.operations.desc":"Support, internal requests, and system alerts","autopilot.enabledCount":"({enabled}/{total} enabled)","autopilot.badge":"Auto-Pilot","autopilot.editRuleTooltip":"Edit Rule","autopilot.deleteRuleTooltip":"Delete Rule","autopilot.triggeredToday":"{count} today","autopilot.editDialog.editTitle":"Edit Rule","autopilot.editDialog.createTitle":"Create Custom Rule","autopilot.editDialog.desc":"Define a condition based on AI analysis to trigger an action.","autopilot.editDialog.ruleName":"Rule Name","autopilot.editDialog.namePlaceholder":"e.g. Archive Newsletters","autopilot.editDialog.description":"Description","autopilot.editDialog.descPlaceholder":"e.g. Handle all marketing newsletters and promotional content from subscription services","autopilot.editDialog.descriptionHelp":"Describe what this rule is for. The AI uses this to semantically match emails.","autopilot.editDialog.intent":"Intent","autopilot.editDialog.intentPlaceholder":"e.g. Politely decline all sales pitches","autopilot.editDialog.intentHelp":"The goal of this rule. Used to generate appropriate draft replies.","autopilot.editDialog.conditionField":"If Condition Field","autopilot.editDialog.aiAnalysisGroup":"AI Analysis","autopilot.editDialog.metadataGroup":"Metadata","autopilot.editDialog.category":"Category","autopilot.editDialog.sentiment":"Sentiment","autopilot.editDialog.priority":"Priority","autopilot.editDialog.senderEmail":"Specific Email (Exact)","autopilot.editDialog.senderDomain":"Email Domain (@...)","autopilot.editDialog.senderContains":"Sender contains...","autopilot.editDialog.subjectContains":"Subject contains...","autopilot.editDialog.bodyContains":"Body contains...","autopilot.editDialog.equalsValue":"Equals Value","autopilot.editDialog.cat.newsletter":"Newsletter","autopilot.editDialog.cat.news":"News","autopilot.editDialog.cat.spam":"Spam","autopilot.editDialog.cat.promotional":"Promotional","autopilot.editDialog.cat.transactional":"Transactional","autopilot.editDialog.cat.social":"Social","autopilot.editDialog.cat.support":"Support","autopilot.editDialog.cat.client":"Client","autopilot.editDialog.cat.internal":"Internal","autopilot.editDialog.cat.personal":"Personal","autopilot.editDialog.cat.other":"Other","autopilot.editDialog.sent.positive":"Positive","autopilot.editDialog.sent.neutral":"Neutral","autopilot.editDialog.sent.negative":"Negative","autopilot.editDialog.prio.high":"High","autopilot.editDialog.prio.medium":"Medium","autopilot.editDialog.prio.low":"Low","autopilot.editDialog.keywordsPlaceholder":"Keywords...","autopilot.editDialog.olderThan":"Only if email is older than... (Optional)","autopilot.editDialog.days":"days","autopilot.editDialog.olderThanHelp":"Leave empty or 0 to apply rule immediately upon receipt.","autopilot.editDialog.performActions":"Then Perform Action(s)","autopilot.editDialog.actionsDesc":"Select one or more actions to execute when the rule matches","autopilot.editDialog.action.archive":"Archive Email","autopilot.editDialog.action.delete":"Delete Email","autopilot.editDialog.action.draft":"Draft Reply","autopilot.editDialog.action.star":"Star / Flag","autopilot.editDialog.draftInstructions":"Draft Instructions (Context)","autopilot.editDialog.draftInstPlaceholder":"e.g. Tell them I'm busy until Friday, but interested in the proposal.","autopilot.editDialog.draftInstHelp":"Specific context for the AI ghostwriter.","autopilot.editDialog.attachments":"Attachments (Optional)","autopilot.editDialog.uploading":"Uploading...","autopilot.editDialog.addAttachment":"Add Attachment","autopilot.editDialog.attachmentsHelp":"Files will be attached to every draft generated by this rule.","autopilot.onboarding.allSet":"All Set!","autopilot.onboarding.enabledDesc":"We've enabled {count} automation rules for you","autopilot.onboarding.rules":"rules","autopilot.onboarding.universalDesc":"Essential rules that help everyone stay organized","autopilot.onboarding.executiveDesc":"Focus on high-priority communications and strategic matters","autopilot.onboarding.developerDesc":"Surface critical alerts and filter tool noise","autopilot.onboarding.salesDesc":"Prioritize leads and customer communications","autopilot.onboarding.operationsDesc":"Organize tickets and internal communications","autopilot.onboarding.tip":"Tip: All rules are enabled by default, but you can customize or disable them anytime in the Auto-Pilot section.","autopilot.onboarding.start":"Start Using Email Automator →","autopilot.role.title":"One Last Step!","autopilot.role.subtitle":"What best describes your role? We'll set up the right automation rules for you.","autopilot.role.executive.label":"Executive / Leadership","autopilot.role.executive.desc":"Focus on VIPs, contracts, and strategic communications","autopilot.role.executive.preview":"VIP Client Prioritizer;Travel Organizer;Legal & Contracts","autopilot.role.sales.label":"Sales / Business Development","autopilot.role.sales.desc":"Prioritize leads and customer communications","autopilot.role.sales.preview":"Customer Questions;CRM Organizer;Proposal Tracker","autopilot.role.developer.label":"Developer / Engineer","autopilot.role.developer.desc":"Surface critical alerts and filter tool noise","autopilot.role.developer.preview":"System Alerts;Code Reviews;Project Management","autopilot.role.operations.label":"Operations / Support","autopilot.role.operations.desc":"Organize tickets and internal communications","autopilot.role.operations.preview":"Support Tickets;System Monitoring;Internal Comms","autopilot.role.marketing.label":"Marketing","autopilot.role.marketing.desc":"Track campaigns and customer engagement","autopilot.role.marketing.preview":"Campaign Tracking;Analytics Reports;Social Media","autopilot.role.other.label":"Other / Manual Setup","autopilot.role.other.desc":"I'll configure my own automation rules","autopilot.role.includes":"Includes:","autopilot.role.skip":"Skip for now","autopilot.role.settingUp":"Setting up...","autopilot.role.continue":"Continue →","terminal.title":"Agent Terminal","terminal.liveActivity":"Live Activity","terminal.syncing":"SYNCING","terminal.live":"LIVE","terminal.stopSync":"STOP SYNC","terminal.clear":"Clear","terminal.waiting":"Waiting for agent activity...","terminal.details":"Details","terminal.useless":"USELESS","terminal.relevant":"RELEVANT","terminal.executionComplete":"Execution Complete","terminal.batchFinished":"Batch Sync Finished","terminal.processed":"Processed","terminal.actions":"Actions","terminal.action.delete":"Moved to Trash","terminal.action.archive":"Archived Email","terminal.action.draft":"Drafted Reply","terminal.action.star":"Starred Email","persona.title":"Digital Persona","persona.subtitle":"Manage how your AI assistant represents you.","persona.identity":"Identity","persona.communication":"Communication","persona.automation":"Automation","persona.network":"Network","persona.edit.title":"Edit Persona","persona.edit.desc":"Update your digital assistant preferences.","common.edit":"Edit"},lL=Object.freeze(Object.defineProperty({__proto__:null,default:Tk},Symbol.toStringTag,{value:"Module"})),z1={en:{name:"English",flag:"🇺🇸"},fr:{name:"Français",flag:"🇫🇷"},es:{name:"Español",flag:"🇪🇸"},ja:{name:"日本語",flag:"🇯🇵"},ko:{name:"한국어",flag:"🇰🇷"},vi:{name:"Tiếng Việt",flag:"🇻🇳"}},Tu=Tk,Ek=S.createContext(void 0);function cL({children:e}){const[t,n]=S.useState(()=>localStorage.getItem("app_language")||"en"),[s,a]=S.useState(t==="en"?Tu:{}),[l,u]=S.useState(t!=="en");S.useEffect(()=>{localStorage.setItem("app_language",t),document.documentElement.lang=t,(async()=>{if(t==="en"){a(Tu),u(!1);return}u(!0);try{const p=await oL(Object.assign({"../locales/languages/en.json":()=>Ni(()=>Promise.resolve().then(()=>lL),void 0),"../locales/languages/es.json":()=>Ni(()=>import("./es-NQpkAluz.js"),[]),"../locales/languages/fr.json":()=>Ni(()=>import("./fr-Dt1serdG.js"),[]),"../locales/languages/ja.json":()=>Ni(()=>import("./ja-46nRzsm5.js"),[]),"../locales/languages/ko.json":()=>Ni(()=>import("./ko-DUNCzc8F.js"),[]),"../locales/languages/vi.json":()=>Ni(()=>import("./vi-CA9x3uPA.js"),[])}),`../locales/languages/${t}.json`,4);a(p.default)}catch(p){console.error(`Failed to load translations for ${t}:`,p),a(Tu)}finally{u(!1)}})()},[t]);const d=m=>{n(m)},h=m=>s[m]||Tu[m]||m;return o.jsx(Ek.Provider,{value:{language:t,setLanguage:d,t:h,isLoading:l},children:e})}function tt(){const e=S.useContext(Ek);if(e===void 0)throw new Error("useLanguage must be used within a LanguageProvider");return e}function iy({className:e}){const{language:t,setLanguage:n}=tt(),[s,a]=S.useState(!1),l=S.useRef(null);S.useEffect(()=>{function d(h){l.current&&!l.current.contains(h.target)&&a(!1)}return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[]);const u=z1[t];return o.jsxs("div",{className:me("relative z-50",e),ref:l,children:[o.jsxs("button",{onClick:()=>a(!s),className:me("flex items-center gap-2 px-3 py-2 rounded-lg transition-all duration-200","bg-secondary/50 hover:bg-secondary border border-border/50 hover:border-border shadow-sm",s&&"ring-2 ring-primary/20 border-primary/50"),children:[o.jsx("span",{className:"text-lg leading-none",children:u.flag}),o.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:t}),o.jsx(XS,{className:me("w-3 h-3 transition-transform duration-200",s&&"rotate-180")})]}),s&&o.jsxs("div",{className:me("absolute right-0 mt-2 w-48 rounded-xl border border-border bg-card p-1.5 shadow-xl animate-in fade-in zoom-in duration-200","backdrop-blur-xl"),children:[o.jsx("div",{className:"px-2 py-1.5 mb-1 text-[10px] font-bold text-muted-foreground uppercase tracking-widest",children:"Choose Language"}),Object.entries(z1).map(([d,{name:h,flag:m}])=>o.jsxs("button",{onClick:()=>{n(d),a(!1)},className:me("flex items-center justify-between w-full px-3 py-2 rounded-lg text-sm transition-colors",t===d?"bg-primary/10 text-primary font-bold":"hover:bg-secondary text-muted-foreground hover:text-foreground"),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-lg leading-none",children:m}),o.jsx("span",{children:h})]}),t===d&&o.jsx(Ti,{className:"w-4 h-4"})]},d))]})]})}const Ck=S.createContext(void 0);function uL({children:e}){const[t,n]=S.useState(!1),[s,a]=S.useState(!1),[l,u]=S.useState(null),d=S.useRef(null),h=S.useRef(null),m=S.useRef(null),p=S.useRef(null),g=S.useRef(0),v=S.useCallback(()=>{if(p.current&&(p.current.cancel().catch(()=>{}),p.current=null),m.current){try{m.current.stop(),m.current.disconnect()}catch{}m.current=null}d.current&&(d.current.pause(),d.current.currentTime=0,d.current=null),n(!1),a(!1),u(null),g.current++},[]),b=S.useCallback((k,N)=>new Promise((R,T)=>{k.decodeAudioData(N,D=>{const U=k.createBufferSource();U.buffer=D,U.connect(k.destination),U.onended=()=>R(),U.start(0),m.current=U},D=>T(D))}),[]),w=S.useCallback(async(k,N,R={})=>{v();const T=g.current;a(!0),u(N||null);const D={text:k,...R};console.log("[TTSContext] Sending TTS request:",D);try{const U=await fetch("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!U.ok)throw new Error("TTS generation failed");const M=await U.blob(),B=URL.createObjectURL(M),P=new Audio(B);d.current=P,P.onplay=()=>n(!0),P.onended=()=>{g.current===T&&(n(!1),a(!1),u(null),URL.revokeObjectURL(B))},P.onerror=()=>{g.current===T&&(n(!1),a(!1),u(null),URL.revokeObjectURL(B),console.error("[TTSContext] Audio playback failed"))},await P.play()}catch(U){console.error("[TTSContext] Speak failed:",U),g.current===T&&(a(!1),u(null))}},[v]),j=S.useCallback(async(k,N,R={})=>{v();const T=g.current;a(!0),u(N||null);try{const D=await fetch("/api/tts/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:k,...R})});if(!D.ok)throw new Error("TTS streaming failed");const U=D.body?.getReader();if(!U)throw new Error("No response body");p.current=U;const M=new TextDecoder;let B="";const P=[];h.current||(h.current=new(window.AudioContext||window.webkitAudioContext));const H=h.current;for(;g.current===T;){const{done:O,value:Q}=await U.read();if(O)break;B+=M.decode(Q,{stream:!0});const G=B.split(`
108
+ `);B=G.pop()||"";for(const he of G){const se=he.trim();if(!se||!se.startsWith("data:"))continue;const ae=se.slice(5).trim();if(ae)try{const L=JSON.parse(ae);if(L.audio){const V=atob(L.audio),q=new Uint8Array(V.length);for(let de=0;de<V.length;de++)q[de]=V.charCodeAt(de);P.push(q.buffer),P.length===1&&(n(!0),await b(H,q.buffer))}}catch{}}}if(g.current===T)for(let O=1;O<P.length&&g.current===T;O++)await b(H,P[O]);g.current===T&&(n(!1),a(!1),u(null))}catch(D){console.error("[TTSContext] Stream failed:",D),g.current===T&&(n(!1),a(!1),u(null))}},[v,b]);return o.jsx(Ck.Provider,{value:{isPlaying:t,isSpeaking:s,speakingId:l,currentAudio:d.current,speak:w,speakStream:j,stop:v},children:e})}function Ak(){const e=S.useContext(Ck);if(e===void 0)throw new Error("useTTSContext must be used within a TTSProvider");return e}function ay(){const{speak:e,speakStream:t,stop:n,isPlaying:s,isSpeaking:a,speakingId:l}=Ak(),u=S.useCallback(async(h,m,p={})=>e(h,m,p),[e]),d=S.useCallback(async(h,m,p={})=>t(h,m,p),[t]);return{speak:u,speakStream:d,stop:n,isPlaying:s,isSpeaking:a,speakingId:l}}const Rk=S.createContext(void 0),L1={page_id:"global",system_instruction:"You are a helpful Email Assistant. Use general knowledge to help the user."};function I1(){return vp().autoPlay}function dL({children:e}){const[t,n]=S.useState(L1),[s,a]=S.useState([]),[l,u]=S.useState("idle"),{speak:d}=ay(),h=S.useCallback(g=>{n(v=>v.page_id===g.page_id&&JSON.stringify(v.data)===JSON.stringify(g.data)?v:(console.log(`[AgentContext] Registering new agent context: ${g.page_id}`),g))},[]),m=S.useCallback(()=>{n(L1)},[]),p=S.useCallback(async g=>{u("thinking");const v={role:"user",content:g};a(b=>[...b,v]);try{const b="/api/agent/chat",w=localStorage.getItem("supabase.auth.token"),j=gp(),k={...t,lang:localStorage.getItem("app_language")||"en",tools:t.tools?.map(D=>({name:D.name,description:D.description,parameters:D.parameters}))},N={message:g,context:k,history:s.slice(-10)},R=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w||""}`,"X-Supabase-Url":j.edgeFunctionsUrl.replace("/functions/v1",""),"X-Supabase-Anon-Key":j.anonKey},body:JSON.stringify(N)});if(!R.ok)throw new Error(`API request failed: ${R.status} ${R.statusText}`);const T=await R.json();if(T.success&&T.response){const D=T.response.content,U=T.response.action,M={role:"assistant",content:D};if(a(B=>[...B,M]),D&&I1()&&(u("speaking"),await d(D,void 0,vp())),U&&t.tools){console.log(`[AgentContext] Executing tool: ${U.name}`,U.args);const B=t.tools.find(P=>P.name===U.name);if(B)try{if(B.parameters?.required){const O=B.parameters.required.filter(Q=>!(Q in(U.args||{})));if(O.length>0)throw new Error(`Missing required parameters: ${O.join(", ")}`)}const P=await B.callback(U.args),H=P?.message||`✓ Action completed: ${U.name}`;a(O=>[...O,{role:"system",content:H}]),console.log("[AgentContext] Tool executed successfully:",P)}catch(P){console.error("[AgentContext] Tool execution failed:",P);const H=P?.message||"Unknown error occurred";a(O=>[...O,{role:"system",content:`⚠️ Error: ${H}`}]),I1()&&await d(`Error: ${H}`,void 0,vp())}else{const P=`Tool "${U.name}" not found. Available tools: ${t.tools.map(H=>H.name).join(", ")}`;console.warn(`[AgentContext] ${P}`),a(H=>[...H,{role:"system",content:`⚠️ ${P}`}])}}u("idle")}else{const D=T.error||"Sorry, I encountered an error processing your request.";console.error("[AgentContext] API error:",T.error),a(U=>[...U,{role:"assistant",content:`⚠️ ${D}`}]),u("idle")}}catch(b){console.error("[AgentContext] Chat failed:",b);let w="Network error. Please try again.";b.message?.includes("Failed to fetch")?w="Cannot connect to the AI service. Please ensure the API server is running.":b.message&&(w=b.message),a(j=>[...j,{role:"system",content:`⚠️ ${w}`}]),u("idle")}},[t,s,d]);return o.jsx(Rk.Provider,{value:{currentConfig:t,registerAgent:h,chatHistory:s,agentState:l,sendMessage:p,resetAgent:m},children:e})}function Ok(){const e=S.useContext(Rk);if(e===void 0)throw new Error("useAgentContext must be used within an AgentProvider");return e}function oy(e){const{registerAgent:t,resetAgent:n}=Ok();S.useRef(e);const s=JSON.stringify(e);S.useEffect(()=>(t(e),()=>{n()}),[s,t,n])}const Xa="2.22.2",fL="20260203150000";function hL(e,t){const n=e.split(".").map(Number),s=t.split(".").map(Number);for(let a=0;a<Math.max(n.length,s.length);a++){const l=n[a]||0,u=s[a]||0;if(l>u)return 1;if(l<u)return-1}return 0}async function mL(e){try{const{data:t,error:n}=await e.rpc("get_latest_migration_timestamp");return n?n.code==="42883"?(console.info("[Migration Check] RPC function missing - assuming fresh DB."),{version:null,latestMigrationTimestamp:"0"}):(console.warn("Could not get latest migration timestamp:",n.message),{version:null,latestMigrationTimestamp:null}):{version:Xa,latestMigrationTimestamp:t||null}}catch(t){return console.error("Error checking database migration info:",t),{version:null,latestMigrationTimestamp:null}}}async function ly(e){const t=Xa,n=fL,s=await mL(e);if(console.log("[Migration Check]",{appVersion:t,appMigrationTimestamp:n,dbVersion:s.version,dbMigrationTimestamp:s.latestMigrationTimestamp}),s.latestMigrationTimestamp&&s.latestMigrationTimestamp.trim()!==""){const a=n,l=s.latestMigrationTimestamp;return a>l?{needsMigration:!0,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:l,message:`New migrations available. Database is at ${l}, app has ${a}.`}:a<l?(console.warn("[Migration Check] DB is ahead of app - possible downgrade"),{needsMigration:!1,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:l,message:`Database (${l}) is ahead of app (${a}).`}):(console.log("[Migration Check] Timestamps match - database is up-to-date"),{needsMigration:!1,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:l,message:"Database schema is up-to-date."})}if(s.version){console.log("[Migration Check] Legacy DB detected (no timestamp). Falling back to SemVer.");const a=hL(t,s.version);return a>0?{needsMigration:!0,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:null,message:`Database schema (v${s.version}) is outdated. Migration to v${t} required.`}:a===0?(console.warn("[Migration Check] Legacy DB with matching version - forcing migration to add timestamp tracking"),{needsMigration:!0,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:null,message:`Database lacks timestamp tracking. Please run migration to upgrade to modern schema (v${t}).`}):{needsMigration:!1,appVersion:t,dbVersion:s.version,latestMigrationTimestamp:null,message:`Database version (v${s.version}) is ahead of app (v${t}).`}}return console.log("[Migration Check] No DB info found - assuming migration needed"),{needsMigration:!0,appVersion:t,dbVersion:null,latestMigrationTimestamp:null,message:`Database schema unknown. Migration required to v${t}.`}}const Dk="email_automator_migration_reminder_dismissed_at";function pL(e=24){try{const t=localStorage.getItem(Dk);if(!t)return!1;const n=new Date(t).getTime();return(Date.now()-n)/(1e3*60*60)<e}catch(t){return console.error("Error checking migration reminder:",t),!1}}function gL(){try{localStorage.setItem(Dk,new Date().toISOString())}catch(e){console.error("Error dismissing migration reminder:",e)}}const qp={step:"welcome",managed:{accessToken:"",organizations:[],selectedOrg:"",projectName:"Email-Automator-AI",region:"us-east-1",isFetchingOrgs:!1},manual:{url:"",anonKey:""},projectId:"",logs:[],error:null,isMigrating:!1,migrationStatus:null};function yL(e,t){switch(t.type){case"SET_STEP":return{...e,step:t.payload,error:null};case"SET_ACCESS_TOKEN":return{...e,managed:{...e.managed,accessToken:t.payload}};case"SET_ORGANIZATIONS":return{...e,managed:{...e.managed,organizations:t.payload,selectedOrg:t.payload.length>0?t.payload[0].id:""}};case"SET_SELECTED_ORG":return{...e,managed:{...e.managed,selectedOrg:t.payload}};case"SET_PROJECT_NAME":return{...e,managed:{...e.managed,projectName:t.payload}};case"SET_REGION":return{...e,managed:{...e.managed,region:t.payload}};case"SET_FETCHING_ORGS":return{...e,managed:{...e.managed,isFetchingOrgs:t.payload}};case"SET_MANUAL_URL":return{...e,manual:{...e.manual,url:t.payload}};case"SET_MANUAL_ANON_KEY":return{...e,manual:{...e.manual,anonKey:t.payload}};case"SET_PROJECT_ID":return{...e,projectId:t.payload};case"ADD_LOG":return{...e,logs:[...e.logs,{...t.payload,timestamp:Date.now()}].slice(-500)};case"CLEAR_LOGS":return{...e,logs:[]};case"SET_ERROR":return{...e,error:t.payload};case"SET_MIGRATING":return{...e,isMigrating:t.payload};case"SET_MIGRATION_STATUS":return{...e,migrationStatus:t.payload};case"RESET_MANAGED_FLOW":return{...e,managed:{...qp.managed},error:null};case"RESET_MANUAL_FLOW":return{...e,manual:{...qp.manual},error:null};default:return e}}function Cm(e){const t=e.trim();return t?t.startsWith("http://")||t.startsWith("https://")?t:`https://${t}.supabase.co`:""}function Mk(e){const t=e.trim();return t?t.startsWith("sbp_")?t.length<20?{valid:!1,message:"Token is too short"}:{valid:!0,message:"Valid access token"}:{valid:!1,message:"Token must start with sbp_"}:{valid:!1,message:"Access token is required"}}function U1(e){const t=e.trim();if(!t)return null;if(!t.includes(".")&&!t.includes("/"))return t;try{return new URL(t.startsWith("http")?t:`https://${t}`).hostname.split(".")[0]||null}catch{return null}}class xL{buffer="";processChunk(t){const n=[];this.buffer+=t;const s=this.buffer.split(`
64
109
  `);this.buffer=s.pop()||"";for(const a of s)if(a.startsWith("data: "))try{const l=a.slice(6),u=JSON.parse(l);n.push(u)}catch(l){console.warn("[SSEParser] Failed to parse event:",a,l)}return n}flush(){if(!this.buffer.trim())return[];const t=[];if(this.buffer.startsWith("data: "))try{const n=this.buffer.slice(6),s=JSON.parse(n);t.push(s)}catch(n){console.warn("[SSEParser] Failed to parse final buffer:",this.buffer,n)}return this.buffer="",t}reset(){this.buffer=""}}async function Pk(e,t,n={}){const{timeout:s=3e5,onError:a}=n;if(!e.body)throw new Error("Response body is empty");const l=e.body.getReader(),u=new TextDecoder,d=new xL,h=setTimeout(()=>{l.cancel("Timeout")},s);try{for(;;){const{value:m,done:p}=await l.read();if(p){d.flush().forEach(t);break}const g=u.decode(m,{stream:!0});d.processChunk(g).forEach(t)}}catch(m){const p=m instanceof Error?m:new Error(String(m));if(a)a(p);else throw p}finally{clearTimeout(h),d.reset()}}class qs extends Error{constructor(t,n,s){super(t),this.code=n,this.status=s,this.name="SetupApiError"}}async function vL(e){const t=await fetch("/api/setup/organizations",{headers:{Authorization:`Bearer ${e}`}}),n=await t.json();if(!t.ok)throw new qs(n.error||"Failed to fetch organizations","FETCH_ORGS_FAILED",t.status);return n}async function bL(e,t){const n=await fetch("/api/setup/auto-provision",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`},body:JSON.stringify({orgId:e.orgId,projectName:e.projectName,region:e.region})});if(!n.ok){const s=await n.json().catch(()=>({}));throw new qs(s.error||"Failed to provision project","PROVISION_FAILED",n.status)}await Pk(n,t,{timeout:3e5,onError:s=>{throw new qs(`Provisioning stream error: ${s.message}`,"STREAM_ERROR")}})}async function wL(e,t){const n=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:e.projectRef,dbPassword:e.dbPassword,accessToken:e.accessToken,anonKey:e.anonKey})});if(!n.ok){const s=await n.json().catch(()=>({}));throw new qs(s.error||"Failed to start migration","MIGRATION_FAILED",n.status)}await Pk(n,t,{timeout:6e5,onError:s=>{throw new qs(`Migration stream error: ${s.message}`,"STREAM_ERROR")}})}function SL({onNext:e}){const{t}=tt();return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-8",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("h2",{className:"text-4xl font-black italic tracking-tighter uppercase leading-none",children:t("setup.welcomeTitle")}),o.jsx("p",{className:"text-sm text-muted-foreground font-medium max-w-sm",children:t("setup.welcomeSubtitle")})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"p-4 rounded-2xl bg-muted/40 border border-border/50 flex flex-col gap-2 group hover:bg-primary/5 hover:border-primary/20 transition-all",children:[o.jsx(xg,{className:"w-5 h-5 text-primary","aria-hidden":"true"}),o.jsx("p",{className:"text-[10px] font-bold uppercase tracking-widest",children:t("setup.encryptedTitle")}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:t("setup.encryptedDesc")})]}),o.jsxs("div",{className:"p-4 rounded-2xl bg-muted/40 border border-border/50 flex flex-col gap-2 group hover:bg-primary/5 hover:border-primary/20 transition-all",children:[o.jsx(eo,{className:"w-5 h-5 text-primary","aria-hidden":"true"}),o.jsx("p",{className:"text-[10px] font-bold uppercase tracking-widest",children:t("setup.turboTitle")}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:t("setup.turboDesc")})]})]}),o.jsxs(Z,{onClick:e,size:"lg",className:"h-14 rounded-2xl text-md font-bold uppercase tracking-widest group shadow-xl hover:shadow-primary/20 transition-all active:scale-95 bg-primary text-primary-foreground hover:bg-primary/90",children:[t("setup.getStarted"),o.jsx(dg,{className:"w-5 h-5 ml-4 rotate-180 group-hover:translate-x-1 transition-transform","aria-hidden":"true"})]})]})}function _L({onManaged:e,onManual:t,onBack:n}){const{t:s}=tt();return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:s("setup.connectionMode")}),o.jsx("p",{className:"text-xs text-muted-foreground font-bold tracking-widest uppercase",children:s("setup.selectVector")})]}),o.jsxs("div",{className:"grid gap-4",children:[o.jsxs("button",{onClick:e,className:"group relative flex items-center justify-between p-6 rounded-2xl bg-primary/5 border border-primary/20 hover:bg-primary/10 hover:border-primary/40 transition-all text-left","aria-label":"Quick Ignition - Auto-provision via token",children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsx("div",{className:"p-3 bg-primary rounded-xl shadow-lg ring-4 ring-primary/10",children:o.jsx(CA,{className:"w-6 h-6 text-primary-foreground","aria-hidden":"true"})}),o.jsxs("div",{children:[o.jsx("p",{className:"font-black uppercase italic text-sm tracking-tight",children:s("setup.quickIgnition")}),o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-widest",children:s("setup.autoProvision")})]})]}),o.jsx(Wu,{className:"w-5 h-5 text-primary opacity-50 group-hover:opacity-100 transition-all group-hover:translate-x-1"})]}),o.jsxs("button",{onClick:t,className:"group relative flex items-center justify-between p-6 rounded-2xl border border-border hover:bg-muted/50 transition-all text-left","aria-label":"Manual Sync - Use existing credentials",children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsx("div",{className:"p-3 bg-muted rounded-xl",children:o.jsx(gd,{className:"w-6 h-6 text-muted-foreground","aria-hidden":"true"})}),o.jsxs("div",{children:[o.jsx("p",{className:"font-black uppercase italic text-sm tracking-tight text-foreground/80",children:s("setup.manualSync")}),o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-widest",children:s("setup.existingCredentials")})]})]}),o.jsx(Wu,{className:"w-5 h-5 text-muted-foreground opacity-50 group-hover:opacity-100 transition-all group-hover:translate-x-1"})]})]}),o.jsxs("button",{onClick:n,className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2 hover:text-primary pt-4 transition-colors","aria-label":"Go back to welcome screen",children:[o.jsx(dg,{size:12,"aria-hidden":"true"})," ",s("setup.abortAccess")]})]})}const Re=S.forwardRef(({className:e,type:t,...n},s)=>o.jsx("input",{type:t,className:me("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",e),ref:s,...n}));Re.displayName="Input";var zk=HS();const jL=Gl(zk);var kL=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],NL=kL.reduce((e,t)=>{const n=s_(`Primitive.${t}`),s=S.forwardRef((a,l)=>{const{asChild:u,...d}=a,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...d,ref:l})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{}),TL="Label",Lk=S.forwardRef((e,t)=>o.jsx(NL.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));Lk.displayName=TL;var EL=Lk;function $e({className:e,...t}){return o.jsx(EL,{"data-slot":"label",className:me("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",e),...t})}const CL=bg("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 Pi({className:e,variant:t,...n}){return o.jsx("div",{"data-slot":"alert",role:"alert",className:me(CL({variant:t}),e),...n})}function zi({className:e,...t}){return o.jsx("div",{"data-slot":"alert-description",className:me("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",e),...t})}function AL({accessToken:e,error:t,isFetching:n,onTokenChange:s,onFetchOrgs:a,onBack:l}){const d=Mk(e).valid;return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Forge Token"}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Supabase API coordinates"})]}),t&&o.jsxs(Pi,{variant:"destructive",className:"rounded-xl bg-destructive/5 text-destructive border-destructive/20 text-[11px] font-bold",children:[o.jsx(mr,{className:"h-4 w-4"}),o.jsx(zi,{children:t})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"access-token",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Personal Access Token"}),o.jsxs("div",{className:"relative",children:[o.jsx(pg,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:14,"aria-hidden":"true"}),o.jsx(Re,{id:"access-token",type:"password",placeholder:"sbp_xxxxxxxxxxxxxxxx",value:e,onChange:h=>s(h.target.value),className:"pl-10 h-12 bg-muted/20 border-border/50 rounded-xl","aria-describedby":"token-help","aria-invalid":t?"true":"false"})]}),o.jsxs("p",{id:"token-help",className:"text-[9px] text-muted-foreground/60 px-1 italic",children:["Generate at"," ",o.jsx("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"supabase.com/dashboard/tokens"})]})]}),o.jsxs("div",{className:"flex gap-3 pt-4",children:[o.jsx(Z,{variant:"outline",onClick:l,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",disabled:n,children:"Back"}),o.jsx(Z,{onClick:a,disabled:!d||n,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest group shadow-lg hover:shadow-primary/20",children:n?o.jsx(Nt,{className:"w-4 h-4 animate-spin"}):o.jsxs(o.Fragment,{children:["Scan Organizations"," ",o.jsx(Wu,{size:14,className:"ml-2 group-hover:translate-x-1 transition-transform"})]})})]})]})]})}function RL({organizations:e,selectedOrg:t,projectName:n,region:s,onOrgSelect:a,onProjectNameChange:l,onRegionChange:u,onProvision:d,onBack:h}){return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Project Config"}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Engine parameters"})]}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx($e,{htmlFor:"project-name",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Project Name"}),o.jsx(Re,{id:"project-name",value:n,onChange:m=>l(m.target.value),className:"bg-muted/20 border-border/50 rounded-xl text-[11px]"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx($e,{htmlFor:"region",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Hosting Sector"}),o.jsxs("select",{id:"region",value:s,onChange:m=>u(m.target.value),className:"w-full h-10 bg-muted/20 border border-border/50 rounded-xl px-3 text-[11px] font-sans focus:outline-none focus:ring-1 focus:ring-primary/50",children:[o.jsx("option",{value:"us-east-1",children:"US East (N. Virginia)"}),o.jsx("option",{value:"us-west-1",children:"US West (N. California)"}),o.jsx("option",{value:"eu-central-1",children:"Europe (Frankfurt)"}),o.jsx("option",{value:"ap-southeast-1",children:"Asia Pacific (Singapore)"})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Vessel (Organization)"}),o.jsx("div",{className:"max-h-[160px] overflow-y-auto space-y-2 pr-1 custom-scrollbar",role:"radiogroup","aria-label":"Select organization",children:e.map(m=>o.jsxs("button",{onClick:()=>a(m.id),role:"radio","aria-checked":t===m.id,className:me("w-full flex items-center justify-between p-3 rounded-xl border text-[11px] font-bold transition-all",t===m.id?"border-primary bg-primary/5 ring-1 ring-primary":"hover:bg-muted/30 border-border/50"),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(JS,{className:me("w-3.5 h-3.5",t===m.id?"text-primary":"text-muted-foreground/50"),"aria-hidden":"true"}),o.jsx("span",{children:m.name})]}),t===m.id&&o.jsx("div",{className:"w-2 h-2 rounded-full bg-primary animate-pulse","aria-hidden":"true"})]},m.id))})]}),o.jsxs("div",{className:"flex gap-3 pt-2",children:[o.jsx(Z,{variant:"outline",onClick:h,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Back"}),o.jsx(Z,{onClick:d,disabled:!t,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest shadow-md",children:"Initialize System"})]})]})]})}function Ik({logs:e,className:t}){const n=S.useRef(null);return S.useEffect(()=>{n.current?.scrollIntoView({behavior:"smooth"})},[e]),o.jsxs("div",{className:me("bg-slate-950 rounded-2xl p-4 font-mono text-[10px] h-[240px] overflow-y-auto border border-white/5 shadow-inner custom-scrollbar relative",t),role:"log","aria-live":"polite","aria-label":"Setup progress logs",children:[o.jsxs("div",{className:"absolute top-2 right-4 flex items-center gap-2 text-[9px] font-bold text-muted-foreground/30 uppercase tracking-widest pointer-events-none",children:[o.jsx(Ju,{size:10,"aria-hidden":"true"}),o.jsx("span",{children:"Live Feed"})]}),e.length===0?o.jsx("div",{className:"text-slate-600 italic animate-pulse",role:"status",children:"Awaiting kernel signals..."}):o.jsxs(o.Fragment,{children:[e.map((s,a)=>o.jsxs("div",{className:me("mb-1 break-all transition-all duration-300",s.type==="error"&&"text-red-400 font-bold",s.type==="success"&&"text-green-400 font-bold",s.type==="info"&&"text-blue-300",s.type==="stdout"&&"text-slate-400",s.type==="stderr"&&"text-yellow-400"),children:[o.jsxs("span",{className:"text-slate-600 mr-2 tabular-nums",children:["[",new Date(s.timestamp).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}),"]"]}),s.message]},`${s.timestamp}-${a}`)),o.jsx("div",{ref:n})]})]})}function OL({logs:e,error:t,onRetry:n}){return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(Nt,{className:"w-5 h-5 animate-spin text-primary","aria-hidden":"true"}),o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Provisioning"})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Assembling infrastructure..."})]}),o.jsx(Ik,{logs:e}),t&&o.jsx(Z,{variant:"destructive",onClick:n,className:"w-full h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Re-Initialize Engine"})]})}function DL({url:e,anonKey:t,error:n,onUrlChange:s,onAnonKeyChange:a,onSave:l,onBack:u}){const{t:d}=tt(),h=e.trim().length>0&&t.trim().length>0;return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:d("setup.manualSync")}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:d("setup.injectCoordinates")})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx($e,{htmlFor:"platform-url",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:d("setup.platformUrl")}),o.jsx(Re,{id:"platform-url",placeholder:"https://xyz.supabase.co",value:e,onChange:m=>s(m.target.value),className:"bg-muted/20 border-border/50 rounded-xl h-12","aria-describedby":"url-help","aria-invalid":n?"true":"false"}),o.jsx("p",{id:"url-help",className:"text-[9px] text-muted-foreground/60 px-1 italic",children:d("setup.urlHelp")})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx($e,{htmlFor:"anon-key",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:d("setup.anonMatrixKey")}),o.jsx(Re,{id:"anon-key",type:"password",placeholder:"eyJ...",value:t,onChange:m=>a(m.target.value),className:"bg-muted/20 border-border/50 rounded-xl h-12","aria-describedby":"key-help","aria-invalid":n?"true":"false"}),o.jsx("p",{id:"key-help",className:"text-[9px] text-muted-foreground/60 px-1 italic",children:d("setup.keyHelp")})]})]}),n&&o.jsxs(rs.div,{initial:{y:5,opacity:0},animate:{y:0,opacity:1},className:"p-3 bg-destructive/5 border border-destructive/20 text-destructive text-[11px] font-bold rounded-xl flex items-center gap-2",role:"alert",children:[o.jsx(mr,{size:14,"aria-hidden":"true"}),o.jsx("span",{children:n})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3 pt-4",children:[o.jsx(Z,{variant:"outline",onClick:u,className:"h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:d("setup.back")}),o.jsx(Z,{onClick:l,disabled:!h,className:"h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest bg-primary shadow-lg hover:shadow-primary/20",children:d("setup.engage")})]})]})}function ML({logs:e,error:t,isMigrating:n,migrationStatus:s,accessToken:a,onTokenChange:l,onRunMigration:u,onBypass:d}){const h=!a,m=s?.dbVersion!==null&&!s?.isUnknown,p=s?.dbVersion===null||s?.isUnknown;return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[n?o.jsx(Nt,{className:"w-5 h-5 animate-spin text-primary","aria-hidden":"true"}):o.jsx(dC,{className:"w-5 h-5 text-primary","aria-hidden":"true"}),o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Installation"})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Applying schema DNA..."})]}),o.jsx(Ik,{logs:e}),!n&&o.jsxs(rs.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},className:"p-5 bg-primary/5 rounded-2xl space-y-4 border border-primary/20",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed font-medium",children:p?"Empty project detected. Initialization is mandatory to install core AI systems.":`Version mismatch detected (v${s?.dbVersion||"?.?"} → v${s?.appVersion||Xa}). Normalization is recommended.`}),h&&o.jsxs("div",{className:"space-y-2 pt-2 border-t border-primary/10",children:[o.jsx($e,{htmlFor:"migration-token",className:"text-[10px] font-bold uppercase tracking-widest text-primary/60",children:"Management Token Required"}),o.jsxs("div",{className:"relative",children:[o.jsx(pg,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-primary/30",size:12,"aria-hidden":"true"}),o.jsx(Re,{id:"migration-token",type:"password",placeholder:"sbp_xxxxxxxxxxxxxxxx",value:a,onChange:g=>l(g.target.value),className:"pl-9 h-10 bg-background/50 border-primary/20 rounded-xl text-[11px]","aria-describedby":"migration-token-help"})]}),o.jsxs("p",{id:"migration-token-help",className:"text-[9px] text-muted-foreground/60 italic px-1",children:["Used once to run ",o.jsx("code",{className:"text-primary/70",children:"migrate.sh"})," on your backend."]})]})]}),o.jsxs("div",{className:"flex gap-3",children:[m&&o.jsx(Z,{variant:"ghost",onClick:d,className:"flex-1 h-11 text-[10px] font-bold uppercase tracking-widest opacity-60 hover:opacity-100","aria-label":"Skip migration (risky)",children:"Bypass (Risk)"}),o.jsx(Z,{onClick:u,disabled:h,className:"flex-1 h-11 bg-primary text-[10px] font-bold uppercase tracking-widest shadow-lg hover:shadow-primary/30",children:p?"Install Systems":"Normalize System"})]})]}),t&&o.jsxs("div",{className:"space-y-3",children:[o.jsxs(Pi,{variant:"destructive",className:"rounded-xl border-destructive/20 bg-destructive/5 text-destructive font-bold text-[11px]",children:[o.jsx(mr,{className:"h-4 w-4"}),o.jsx(zi,{children:t})]}),o.jsx(Z,{variant:"outline",onClick:u,className:"w-full h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Retry Installation"})]})]})}function Eu({step:e,currentStep:t,label:n}){const s=Array.isArray(e)?e.includes(t):t===e;return o.jsx("div",{className:me("px-3 py-1.5 rounded-full text-[9px] font-black uppercase tracking-[0.2em] transition-all duration-500",s?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground opacity-40"),role:"status","aria-current":s,children:n})}function cy({className:e}){return o.jsxs("svg",{width:"512",height:"512",viewBox:"0 0 512 512",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:me("w-9 h-9",e),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",stroke:"currentColor",strokeWidth:"32",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M64 160 L240 290 C250 295 262 295 272 290 L448 160",stroke:"currentColor",strokeWidth:"28",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M256 160 C256 160 270 190 290 195 C270 200 256 230 256 230 C256 230 242 200 222 195 C242 190 256 160 256 160 Z",fill:"currentColor",className:"opacity-50"})]})}function Uk({onComplete:e,open:t=!0,canClose:n=!1}){const[s,a]=S.useReducer(yL,qp),{t:l}=tt();oy({page_id:"setup_wizard",system_instruction:l("setup.agent.systemInstruction"),data:{step:s.step,managedFlow:["managed-token","managed-org","provisioning","validating"].includes(s.step),projectId:s.projectId||null,hasAccessToken:!!s.managed.accessToken}});const u=S.useRef(""),d=S.useRef("");S.useEffect(()=>()=>{u.current="",d.current=""},[]);const h=S.useCallback((w,j)=>{a({type:"ADD_LOG",payload:{type:w,message:j}})},[]),m=S.useCallback(async()=>{a({type:"SET_ERROR",payload:null}),a({type:"SET_FETCHING_ORGS",payload:!0});const w=s.managed.accessToken.trim(),j=Mk(w);if(!j.valid){a({type:"SET_ERROR",payload:j.message||"Invalid token"}),a({type:"SET_FETCHING_ORGS",payload:!1});return}try{u.current=w;const k=await vL(w);a({type:"SET_ORGANIZATIONS",payload:k}),a({type:"SET_STEP",payload:"managed-org"})}catch(k){const N=k instanceof qs?k:new Error(String(k));a({type:"SET_ERROR",payload:N.message})}finally{a({type:"SET_FETCHING_ORGS",payload:!1})}},[s.managed.accessToken]),p=S.useCallback(async()=>{a({type:"SET_ERROR",payload:null}),a({type:"SET_STEP",payload:"provisioning"}),a({type:"CLEAR_LOGS"}),h("info","Connecting to Supabase provisioning engine...");const w=u.current||s.managed.accessToken.trim();let j=null;try{if(await bL({accessToken:w,orgId:s.managed.selectedOrg,projectName:s.managed.projectName,region:s.managed.region},k=>{switch(k.type){case"info":h("info",k.data);break;case"project_id":a({type:"SET_PROJECT_ID",payload:k.data});break;case"success":j=k.data,h("success","✨ Project ready! Initializing database..."),fm({url:Cm(j.url),anonKey:j.anonKey.trim()}),d.current=j.dbPass,a({type:"SET_MIGRATION_STATUS",payload:{needsMigration:!0,dbVersion:null,appVersion:Xa,isUnknown:!0}});break;case"error":a({type:"SET_ERROR",payload:k.data}),h("error",k.data);break}}),j){const k=j;await g(k.projectId,w,k.url,k.anonKey)}}catch(k){const N=k instanceof qs?k:new Error(String(k));a({type:"SET_ERROR",payload:N.message}),h("error",`Provisioning failed: ${N.message}`)}},[s.managed.selectedOrg,s.managed.projectName,s.managed.region,s.managed.accessToken,h]),g=S.useCallback(async(w,j,k,N)=>{const R=w||s.projectId||U1(s.manual.url),T=j||u.current||s.managed.accessToken.trim(),D=k||s.manual.url,U=N||s.manual.anonKey;if(!R||!T){a({type:"SET_ERROR",payload:"Project ID and Access Token are required for migration."});return}a({type:"SET_STEP",payload:"migration"}),a({type:"SET_ERROR",payload:null}),a({type:"SET_MIGRATING",payload:!0}),a({type:"CLEAR_LOGS"}),h("info","📦 Preparing database schema initialization...");try{let M=!1;if(await wL({projectRef:R,dbPassword:d.current,accessToken:T,anonKey:U},B=>{switch(B.type){case"stdout":h("stdout",B.data);break;case"stderr":h("stderr",`⚠️ ${B.data}`);break;case"info":h("info",B.data);break;case"error":h("error",B.data);break;case"done":B.data==="success"?(M=!0,h("success","✅ Database setup complete!"),D&&U&&fm({url:Cm(D),anonKey:U.trim()}),u.current="",d.current="",setTimeout(()=>{e(),window.location.reload()},2e3)):a({type:"SET_ERROR",payload:"Migration failed. Check terminal logs for details."});break}}),!M)throw new Error("Migration did not complete successfully")}catch(M){const B=M instanceof qs?M:new Error(String(M));a({type:"SET_ERROR",payload:B.message}),h("error",`Migration failed: ${B.message}`)}finally{a({type:"SET_MIGRATING",payload:!1})}},[s.projectId,s.manual.url,s.manual.anonKey,s.managed.accessToken,h,e]),v=S.useCallback(async()=>{a({type:"SET_ERROR",payload:null}),a({type:"SET_STEP",payload:"validating"});const w=Cm(s.manual.url),j=s.manual.anonKey.trim(),k=await r5(w,j);if(k.valid){a({type:"SET_MANUAL_URL",payload:w});const N=U1(w);N&&a({type:"SET_PROJECT_ID",payload:N}),fm({url:w,anonKey:j});try{const R=pp(w,j),T=await ly(R);a({type:"SET_MIGRATION_STATUS",payload:T}),T.needsMigration?a({type:"SET_STEP",payload:"migration"}):(h("success","✨ Database is already up-to-date! Redirecting..."),setTimeout(()=>{e(),window.location.reload()},2e3))}catch(R){console.warn("[SetupWizard] Migration check failed:",R),a({type:"SET_MIGRATION_STATUS",payload:{needsMigration:!0,dbVersion:null,appVersion:Xa,isUnknown:!0}}),a({type:"SET_STEP",payload:"migration"})}}else a({type:"SET_ERROR",payload:k.error||"Connection failed"}),a({type:"SET_STEP",payload:"credentials"})},[s.manual.url,s.manual.anonKey,h,e]);if(!t)return null;const b={initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20}};return o.jsx("div",{className:"fixed inset-0 z-50 bg-background flex flex-col items-center justify-center p-0 md:p-8",children:o.jsxs("div",{className:"w-full h-full max-w-6xl mx-auto overflow-hidden bg-background/80 backdrop-blur-xl border border-border/50 shadow-2xl rounded-3xl flex",children:[o.jsxs("div",{className:"w-[280px] bg-muted/30 border-r border-border/10 p-8 flex flex-col justify-between relative overflow-hidden hidden md:flex shrink-0",children:[o.jsxs("div",{className:"space-y-8 relative z-10",children:[o.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[o.jsx("div",{className:"p-2 bg-primary rounded-lg flex-shrink-0",children:o.jsx(cy,{className:"w-5 h-5 text-primary-foreground"})}),o.jsx("span",{className:"font-black italic tracking-tighter uppercase text-xs truncate",children:"Automator Forge"})]}),o.jsxs("div",{className:"space-y-6",children:[o.jsx("p",{className:"text-[9px] font-black uppercase tracking-[0.4em] text-muted-foreground/30 ml-1",children:"Assembly Phase"}),o.jsxs("div",{className:"space-y-4 px-1",children:[o.jsx(Eu,{step:"welcome",currentStep:s.step,label:l("setup.initiation")}),o.jsx(Eu,{step:["type","managed-token","credentials"],currentStep:s.step,label:l("setup.coordinates")}),o.jsx(Eu,{step:["managed-org","provisioning","validating"],currentStep:s.step,label:l("setup.foundation")}),o.jsx(Eu,{step:"migration",currentStep:s.step,label:l("setup.ignition")})]})]})]}),o.jsx("div",{className:"relative z-10 space-y-4",children:o.jsxs("p",{className:"text-[9px] font-bold text-muted-foreground/30 uppercase tracking-[0.4em] px-2 text-center",children:["v",Xa," // Stable Build"]})})]}),o.jsxs("div",{className:"flex-1 p-8 md:p-12 flex flex-col relative",children:[n&&o.jsx("button",{onClick:e,className:"absolute top-6 right-6 p-2 rounded-full hover:bg-secondary transition-colors z-[60]","aria-label":"Close setup wizard",children:o.jsx(mn,{className:"w-5 h-5 text-muted-foreground opacity-40 hover:opacity-100 transition-opacity"})}),o.jsx("div",{className:"absolute top-6 right-6 flex items-center gap-4 z-50",children:o.jsx(iy,{})}),o.jsx(mk,{mode:"wait",children:o.jsxs(rs.div,{initial:"initial",animate:"animate",exit:"exit",variants:b,transition:{type:"spring",damping:25,stiffness:200},className:"flex-1 flex flex-col",children:[s.step==="welcome"&&o.jsx(SL,{onNext:()=>a({type:"SET_STEP",payload:"type"})}),s.step==="type"&&o.jsx(_L,{onManaged:()=>{a({type:"RESET_MANUAL_FLOW"}),a({type:"SET_STEP",payload:"managed-token"})},onManual:()=>{a({type:"RESET_MANAGED_FLOW"}),a({type:"SET_STEP",payload:"credentials"})},onBack:()=>a({type:"SET_STEP",payload:"welcome"})}),s.step==="managed-token"&&o.jsx(AL,{accessToken:s.managed.accessToken,error:s.error,isFetching:s.managed.isFetchingOrgs,onTokenChange:w=>a({type:"SET_ACCESS_TOKEN",payload:w}),onFetchOrgs:m,onBack:()=>a({type:"SET_STEP",payload:"type"})}),s.step==="managed-org"&&o.jsx(RL,{organizations:s.managed.organizations,selectedOrg:s.managed.selectedOrg,projectName:s.managed.projectName,region:s.managed.region,onOrgSelect:w=>a({type:"SET_SELECTED_ORG",payload:w}),onProjectNameChange:w=>a({type:"SET_PROJECT_NAME",payload:w}),onRegionChange:w=>a({type:"SET_REGION",payload:w}),onProvision:p,onBack:()=>a({type:"SET_STEP",payload:"managed-token"})}),s.step==="provisioning"&&o.jsx(OL,{logs:s.logs,error:s.error,onRetry:()=>a({type:"SET_STEP",payload:"managed-token"})}),s.step==="credentials"&&o.jsx(DL,{url:s.manual.url,anonKey:s.manual.anonKey,error:s.error,onUrlChange:w=>a({type:"SET_MANUAL_URL",payload:w}),onAnonKeyChange:w=>a({type:"SET_MANUAL_ANON_KEY",payload:w}),onSave:v,onBack:()=>a({type:"SET_STEP",payload:"type"})}),s.step==="migration"&&o.jsx(ML,{logs:s.logs,error:s.error,isMigrating:s.isMigrating,migrationStatus:s.migrationStatus,accessToken:s.managed.accessToken,onTokenChange:w=>a({type:"SET_ACCESS_TOKEN",payload:w}),onRunMigration:()=>g(),onBypass:()=>{e(),window.location.reload()}})]},s.step)})]})]})})}function $s(e,t,{checkForDefaultPrevented:n=!0}={}){return function(a){if(e?.(a),n===!1||!a.defaultPrevented)return t?.(a)}}function PL(e,t){const n=S.createContext(t),s=l=>{const{children:u,...d}=l,h=S.useMemo(()=>d,Object.values(d));return o.jsx(n.Provider,{value:h,children:u})};s.displayName=e+"Provider";function a(l){const u=S.useContext(n);if(u)return u;if(t!==void 0)return t;throw new Error(`\`${l}\` must be used within \`${e}\``)}return[s,a]}function zL(e,t=[]){let n=[];function s(l,u){const d=S.createContext(u),h=n.length;n=[...n,u];const m=g=>{const{scope:v,children:b,...w}=g,j=v?.[e]?.[h]||d,k=S.useMemo(()=>w,Object.values(w));return o.jsx(j.Provider,{value:k,children:b})};m.displayName=l+"Provider";function p(g,v){const b=v?.[e]?.[h]||d,w=S.useContext(b);if(w)return w;if(u!==void 0)return u;throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,p]}const a=()=>{const l=n.map(u=>S.createContext(u));return function(d){const h=d?.[e]||l;return S.useMemo(()=>({[`__scope${e}`]:{...d,[e]:h}}),[d,h])}};return a.scopeName=e,[s,LL(a,...t)]}function LL(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const s=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(l){const u=s.reduce((d,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...d,...g}},{});return S.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}var Fl=globalThis?.document?S.useLayoutEffect:()=>{},IL=ug[" useId ".trim().toString()]||(()=>{}),UL=0;function Am(e){const[t,n]=S.useState(IL());return Fl(()=>{n(s=>s??String(UL++))},[e]),e||(t?`radix-${t}`:"")}var BL=ug[" useInsertionEffect ".trim().toString()]||Fl;function VL({prop:e,defaultProp:t,onChange:n=()=>{},caller:s}){const[a,l,u]=FL({defaultProp:t,onChange:n}),d=e!==void 0,h=d?e:a;{const p=S.useRef(e!==void 0);S.useEffect(()=>{const g=p.current;g!==d&&console.warn(`${s} is changing from ${g?"controlled":"uncontrolled"} to ${d?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),p.current=d},[d,s])}const m=S.useCallback(p=>{if(d){const g=qL(p)?p(e):p;g!==e&&u.current?.(g)}else l(p)},[d,e,l,u]);return[h,m]}function FL({defaultProp:e,onChange:t}){const[n,s]=S.useState(e),a=S.useRef(n),l=S.useRef(t);return BL(()=>{l.current=t},[t]),S.useEffect(()=>{a.current!==n&&(l.current?.(n),a.current=n)},[n,a]),[n,s,l]}function qL(e){return typeof e=="function"}function $L(e){const t=HL(e),n=S.forwardRef((s,a)=>{const{children:l,...u}=s,d=S.Children.toArray(l),h=d.find(KL);if(h){const m=h.props.children,p=d.map(g=>g===h?S.Children.count(m)>1?S.Children.only(null):S.isValidElement(m)?m.props.children:null:g);return o.jsx(t,{...u,ref:a,children:S.isValidElement(m)?S.cloneElement(m,void 0,p):null})}return o.jsx(t,{...u,ref:a,children:l})});return n.displayName=`${e}.Slot`,n}function HL(e){const t=S.forwardRef((n,s)=>{const{children:a,...l}=n;if(S.isValidElement(a)){const u=WL(a),d=YL(l,a.props);return a.type!==S.Fragment&&(d.ref=s?bd(s,u):u),S.cloneElement(a,d)}return S.Children.count(a)>1?S.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var GL=Symbol("radix.slottable");function KL(e){return S.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===GL}function YL(e,t){const n={...t};for(const s in t){const a=e[s],l=t[s];/^on[A-Z]/.test(s)?a&&l?n[s]=(...d)=>{const h=l(...d);return a(...d),h}:a&&(n[s]=a):s==="style"?n[s]={...a,...l}:s==="className"&&(n[s]=[a,l].filter(Boolean).join(" "))}return{...e,...n}}function WL(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var XL=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ls=XL.reduce((e,t)=>{const n=$L(`Primitive.${t}`),s=S.forwardRef((a,l)=>{const{asChild:u,...d}=a,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...d,ref:l})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{});function JL(e,t){e&&zk.flushSync(()=>e.dispatchEvent(t))}function ql(e){const t=S.useRef(e);return S.useEffect(()=>{t.current=e}),S.useMemo(()=>(...n)=>t.current?.(...n),[])}function QL(e,t=globalThis?.document){const n=ql(e);S.useEffect(()=>{const s=a=>{a.key==="Escape"&&n(a)};return t.addEventListener("keydown",s,{capture:!0}),()=>t.removeEventListener("keydown",s,{capture:!0})},[n,t])}var ZL="DismissableLayer",$p="dismissableLayer.update",e6="dismissableLayer.pointerDownOutside",t6="dismissableLayer.focusOutside",B1,Bk=S.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Vk=S.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:s,onPointerDownOutside:a,onFocusOutside:l,onInteractOutside:u,onDismiss:d,...h}=e,m=S.useContext(Bk),[p,g]=S.useState(null),v=p?.ownerDocument??globalThis?.document,[,b]=S.useState({}),w=Ui(t,B=>g(B)),j=Array.from(m.layers),[k]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),N=j.indexOf(k),R=p?j.indexOf(p):-1,T=m.layersWithOutsidePointerEventsDisabled.size>0,D=R>=N,U=s6(B=>{const P=B.target,H=[...m.branches].some(O=>O.contains(P));!D||H||(a?.(B),u?.(B),B.defaultPrevented||d?.())},v),M=i6(B=>{const P=B.target;[...m.branches].some(O=>O.contains(P))||(l?.(B),u?.(B),B.defaultPrevented||d?.())},v);return QL(B=>{R===m.layers.size-1&&(s?.(B),!B.defaultPrevented&&d&&(B.preventDefault(),d()))},v),S.useEffect(()=>{if(p)return n&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(B1=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),V1(),()=>{n&&m.layersWithOutsidePointerEventsDisabled.size===1&&(v.body.style.pointerEvents=B1)}},[p,v,n,m]),S.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),V1())},[p,m]),S.useEffect(()=>{const B=()=>b({});return document.addEventListener($p,B),()=>document.removeEventListener($p,B)},[]),o.jsx(ls.div,{...h,ref:w,style:{pointerEvents:T?D?"auto":"none":void 0,...e.style},onFocusCapture:$s(e.onFocusCapture,M.onFocusCapture),onBlurCapture:$s(e.onBlurCapture,M.onBlurCapture),onPointerDownCapture:$s(e.onPointerDownCapture,U.onPointerDownCapture)})});Vk.displayName=ZL;var n6="DismissableLayerBranch",r6=S.forwardRef((e,t)=>{const n=S.useContext(Bk),s=S.useRef(null),a=Ui(t,s);return S.useEffect(()=>{const l=s.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(ls.div,{...e,ref:a})});r6.displayName=n6;function s6(e,t=globalThis?.document){const n=ql(e),s=S.useRef(!1),a=S.useRef(()=>{});return S.useEffect(()=>{const l=d=>{if(d.target&&!s.current){let h=function(){Fk(e6,n,m,{discrete:!0})};const m={originalEvent:d};d.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=h,t.addEventListener("click",a.current,{once:!0})):h()}else t.removeEventListener("click",a.current);s.current=!1},u=window.setTimeout(()=>{t.addEventListener("pointerdown",l)},0);return()=>{window.clearTimeout(u),t.removeEventListener("pointerdown",l),t.removeEventListener("click",a.current)}},[t,n]),{onPointerDownCapture:()=>s.current=!0}}function i6(e,t=globalThis?.document){const n=ql(e),s=S.useRef(!1);return S.useEffect(()=>{const a=l=>{l.target&&!s.current&&Fk(t6,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function V1(){const e=new CustomEvent($p);document.dispatchEvent(e)}function Fk(e,t,n,{discrete:s}){const a=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&a.addEventListener(e,t,{once:!0}),s?JL(a,l):a.dispatchEvent(l)}var Rm="focusScope.autoFocusOnMount",Om="focusScope.autoFocusOnUnmount",F1={bubbles:!1,cancelable:!0},a6="FocusScope",qk=S.forwardRef((e,t)=>{const{loop:n=!1,trapped:s=!1,onMountAutoFocus:a,onUnmountAutoFocus:l,...u}=e,[d,h]=S.useState(null),m=ql(a),p=ql(l),g=S.useRef(null),v=Ui(t,j=>h(j)),b=S.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;S.useEffect(()=>{if(s){let j=function(T){if(b.paused||!d)return;const D=T.target;d.contains(D)?g.current=D:Is(g.current,{select:!0})},k=function(T){if(b.paused||!d)return;const D=T.relatedTarget;D!==null&&(d.contains(D)||Is(g.current,{select:!0}))},N=function(T){if(document.activeElement===document.body)for(const U of T)U.removedNodes.length>0&&Is(d)};document.addEventListener("focusin",j),document.addEventListener("focusout",k);const R=new MutationObserver(N);return d&&R.observe(d,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",j),document.removeEventListener("focusout",k),R.disconnect()}}},[s,d,b.paused]),S.useEffect(()=>{if(d){$1.add(b);const j=document.activeElement;if(!d.contains(j)){const N=new CustomEvent(Rm,F1);d.addEventListener(Rm,m),d.dispatchEvent(N),N.defaultPrevented||(o6(f6($k(d)),{select:!0}),document.activeElement===j&&Is(d))}return()=>{d.removeEventListener(Rm,m),setTimeout(()=>{const N=new CustomEvent(Om,F1);d.addEventListener(Om,p),d.dispatchEvent(N),N.defaultPrevented||Is(j??document.body,{select:!0}),d.removeEventListener(Om,p),$1.remove(b)},0)}}},[d,m,p,b]);const w=S.useCallback(j=>{if(!n&&!s||b.paused)return;const k=j.key==="Tab"&&!j.altKey&&!j.ctrlKey&&!j.metaKey,N=document.activeElement;if(k&&N){const R=j.currentTarget,[T,D]=l6(R);T&&D?!j.shiftKey&&N===D?(j.preventDefault(),n&&Is(T,{select:!0})):j.shiftKey&&N===T&&(j.preventDefault(),n&&Is(D,{select:!0})):N===R&&j.preventDefault()}},[n,s,b.paused]);return o.jsx(ls.div,{tabIndex:-1,...u,ref:v,onKeyDown:w})});qk.displayName=a6;function o6(e,{select:t=!1}={}){const n=document.activeElement;for(const s of e)if(Is(s,{select:t}),document.activeElement!==n)return}function l6(e){const t=$k(e),n=q1(t,e),s=q1(t.reverse(),e);return[n,s]}function $k(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const a=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||a?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function q1(e,t){for(const n of e)if(!c6(n,{upTo:t}))return n}function c6(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function u6(e){return e instanceof HTMLInputElement&&"select"in e}function Is(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&u6(e)&&t&&e.select()}}var $1=d6();function d6(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=H1(e,t),e.unshift(t)},remove(t){e=H1(e,t),e[0]?.resume()}}}function H1(e,t){const n=[...e],s=n.indexOf(t);return s!==-1&&n.splice(s,1),n}function f6(e){return e.filter(t=>t.tagName!=="A")}var h6="Portal",Hk=S.forwardRef((e,t)=>{const{container:n,...s}=e,[a,l]=S.useState(!1);Fl(()=>l(!0),[]);const u=n||a&&globalThis?.document?.body;return u?jL.createPortal(o.jsx(ls.div,{...s,ref:t}),u):null});Hk.displayName=h6;function m6(e,t){return S.useReducer((n,s)=>t[n][s]??n,e)}var Ed=e=>{const{present:t,children:n}=e,s=p6(t),a=typeof n=="function"?n({present:s.isPresent}):S.Children.only(n),l=Ui(s.ref,g6(a));return typeof n=="function"||s.isPresent?S.cloneElement(a,{ref:l}):null};Ed.displayName="Presence";function p6(e){const[t,n]=S.useState(),s=S.useRef(null),a=S.useRef(e),l=S.useRef("none"),u=e?"mounted":"unmounted",[d,h]=m6(u,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return S.useEffect(()=>{const m=Cu(s.current);l.current=d==="mounted"?m:"none"},[d]),Fl(()=>{const m=s.current,p=a.current;if(p!==e){const v=l.current,b=Cu(m);e?h("MOUNT"):b==="none"||m?.display==="none"?h("UNMOUNT"):h(p&&v!==b?"ANIMATION_OUT":"UNMOUNT"),a.current=e}},[e,h]),Fl(()=>{if(t){let m;const p=t.ownerDocument.defaultView??window,g=b=>{const j=Cu(s.current).includes(CSS.escape(b.animationName));if(b.target===t&&j&&(h("ANIMATION_END"),!a.current)){const k=t.style.animationFillMode;t.style.animationFillMode="forwards",m=p.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=k)})}},v=b=>{b.target===t&&(l.current=Cu(s.current))};return t.addEventListener("animationstart",v),t.addEventListener("animationcancel",g),t.addEventListener("animationend",g),()=>{p.clearTimeout(m),t.removeEventListener("animationstart",v),t.removeEventListener("animationcancel",g),t.removeEventListener("animationend",g)}}else h("ANIMATION_END")},[t,h]),{isPresent:["mounted","unmountSuspended"].includes(d),ref:S.useCallback(m=>{s.current=m?getComputedStyle(m):null,n(m)},[])}}function Cu(e){return e?.animationName||"none"}function g6(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Dm=0;function y6(){S.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??G1()),document.body.insertAdjacentElement("beforeend",e[1]??G1()),Dm++,()=>{Dm===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Dm--}},[])}function G1(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Gu="right-scroll-bar-position",Ku="width-before-scroll-bar",x6="with-scroll-bars-hidden",v6="--removed-body-scroll-bar-size";function Mm(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function b6(e,t){var n=S.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(s){var a=n.value;a!==s&&(n.value=s,n.callback(s,a))}}}})[0];return n.callback=t,n.facade}var w6=typeof window<"u"?S.useLayoutEffect:S.useEffect,K1=new WeakMap;function S6(e,t){var n=b6(null,function(s){return e.forEach(function(a){return Mm(a,s)})});return w6(function(){var s=K1.get(n);if(s){var a=new Set(s),l=new Set(e),u=n.current;a.forEach(function(d){l.has(d)||Mm(d,null)}),l.forEach(function(d){a.has(d)||Mm(d,u)})}K1.set(n,e)},[e]),n}function _6(e){return e}function j6(e,t){t===void 0&&(t=_6);var n=[],s=!1,a={read:function(){if(s)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(l){var u=t(l,s);return n.push(u),function(){n=n.filter(function(d){return d!==u})}},assignSyncMedium:function(l){for(s=!0;n.length;){var u=n;n=[],u.forEach(l)}n={push:function(d){return l(d)},filter:function(){return n}}},assignMedium:function(l){s=!0;var u=[];if(n.length){var d=n;n=[],d.forEach(l),u=n}var h=function(){var p=u;u=[],p.forEach(l)},m=function(){return Promise.resolve().then(h)};m(),n={push:function(p){u.push(p),m()},filter:function(p){return u=u.filter(p),n}}}};return a}function k6(e){e===void 0&&(e={});var t=j6(null);return t.options=Nr({async:!0,ssr:!1},e),t}var Gk=function(e){var t=e.sideCar,n=io(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var s=t.read();if(!s)throw new Error("Sidecar medium not found");return S.createElement(s,Nr({},n))};Gk.isSideCarExport=!0;function N6(e,t){return e.useMedium(t),Gk}var Kk=k6(),Pm=function(){},Cd=S.forwardRef(function(e,t){var n=S.useRef(null),s=S.useState({onScrollCapture:Pm,onWheelCapture:Pm,onTouchMoveCapture:Pm}),a=s[0],l=s[1],u=e.forwardProps,d=e.children,h=e.className,m=e.removeScrollBar,p=e.enabled,g=e.shards,v=e.sideCar,b=e.noRelative,w=e.noIsolation,j=e.inert,k=e.allowPinchZoom,N=e.as,R=N===void 0?"div":N,T=e.gapMode,D=io(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),U=v,M=S6([n,t]),B=Nr(Nr({},D),a);return S.createElement(S.Fragment,null,p&&S.createElement(U,{sideCar:Kk,removeScrollBar:m,shards:g,noRelative:b,noIsolation:w,inert:j,setCallbacks:l,allowPinchZoom:!!k,lockRef:n,gapMode:T}),u?S.cloneElement(S.Children.only(d),Nr(Nr({},B),{ref:M})):S.createElement(R,Nr({},B,{className:h,ref:M}),d))});Cd.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Cd.classNames={fullWidth:Ku,zeroRight:Gu};var T6=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function E6(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=T6();return t&&e.setAttribute("nonce",t),e}function C6(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function A6(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var R6=function(){var e=0,t=null;return{add:function(n){e==0&&(t=E6())&&(C6(t,n),A6(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},O6=function(){var e=R6();return function(t,n){S.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Yk=function(){var e=O6(),t=function(n){var s=n.styles,a=n.dynamic;return e(s,a),null};return t},D6={left:0,top:0,right:0,gap:0},zm=function(e){return parseInt(e||"",10)||0},M6=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],s=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return[zm(n),zm(s),zm(a)]},P6=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return D6;var t=M6(e),n=document.documentElement.clientWidth,s=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,s-n+t[2]-t[0])}},z6=Yk(),Ja="data-scroll-locked",L6=function(e,t,n,s){var a=e.left,l=e.top,u=e.right,d=e.gap;return n===void 0&&(n="margin"),`
65
110
  .`.concat(x6,` {
66
111
  overflow: hidden `).concat(s,`;
@@ -132,8 +177,8 @@ Overall it looks solid, though I have a few minor questions about the timeline.
132
177
  I've analyzed the key points and everything aligns with our objectives. Specifically, the timeline looks realistic and the budget is within scope. I do have a couple of questions regarding the implementation phase, but we can cover those in our next sync.`,p+=`
133
178
 
134
179
  ${m}`,p};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"✍️ How do you communicate?"}),o.jsx("p",{className:"text-muted-foreground",children:"We'll adjust all drafts to match your natural style."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx($e,{children:"Default Tone"}),o.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:YI.map(d=>o.jsx(Ie,{className:me("cursor-pointer transition-all hover:bg-accent/50",e.preferred_tone===d.id?"border-primary bg-accent":""),onClick:()=>t({preferred_tone:d.id}),children:o.jsxs(ft,{className:"p-3",children:[o.jsx("p",{className:"font-medium text-sm",children:d.label}),o.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:d.example})]})},d.id))})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx($e,{children:"Response Length"}),o.jsx("span",{className:"text-sm text-muted-foreground capitalize",children:e.preferred_length||"medium"})]}),o.jsx("input",{type:"range",min:"1",max:"3",step:"1",className:"w-full h-2 bg-secondary rounded-lg appearance-none cursor-pointer accent-primary",value:e.preferred_length==="brief"?1:e.preferred_length==="detailed"?3:2,onChange:d=>{const h=parseInt(d.target.value);t({preferred_length:h===1?"brief":h===3?"detailed":"medium"})}}),o.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:"Brief"}),o.jsx("span",{children:"Medium"}),o.jsx("span",{children:"Detailed"})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"signature",children:"Signature"}),o.jsx("textarea",{id:"signature",className:"flex min-h-[60px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",rows:2,placeholder:`Best,
135
- Trung Le`,value:e.signature||"",onChange:d=>t({signature:d.target.value})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{children:"Common Phrases"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Re,{placeholder:"e.g., Thanks for reaching out",value:n,onChange:d=>s(d.target.value),onKeyDown:d=>d.key==="Enter"&&a()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:a,children:o.jsx(Gs,{className:"h-4 w-4"})})]}),o.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:e.common_phrases?.map((d,h)=>o.jsxs("div",{className:"bg-secondary text-secondary-foreground px-2 py-1 rounded-md text-xs flex items-center gap-1",children:[d,o.jsx(mn,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>l(d)})]},h))})]}),o.jsxs("div",{className:"mt-6 pt-4 border-t",children:[o.jsx($e,{className:"text-muted-foreground mb-2 block",children:"Preview: How your drafts will look"}),o.jsx("div",{className:"bg-muted/30 border rounded-lg p-4 font-mono text-sm whitespace-pre-wrap",children:u()})]})]})}function XI({data:e,updateData:t}){const[n,s]=S.useState(""),[a,l]=S.useState(""),u=()=>{if(n.trim()){const g=e.vip_senders||[];g.includes(n.trim())||t({vip_senders:[...g,n.trim()]}),s("")}},d=g=>{const v=e.vip_senders||[];t({vip_senders:v.filter(b=>b!==g)})},h=()=>{if(a.trim()){let g=a.trim();g.startsWith("@")&&(g=g.substring(1));const v=e.trusted_domains||[];v.includes(g)||t({trusted_domains:[...v,g]}),l("")}},m=g=>{const v=e.trusted_domains||[];t({trusted_domains:v.filter(b=>b!==g)})},p=[{id:"newsletters",label:"Newsletters"},{id:"social_media",label:"Social media"},{id:"marketing",label:"Marketing emails"}];return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"⭐ Who's important to you?"}),o.jsx("p",{className:"text-muted-foreground",children:"We'll prioritize emails from these people and domains."})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(np,{className:"h-4 w-4 text-yellow-500"}),o.jsx($e,{children:"VIPs (Always High Priority)"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Re,{placeholder:"investor@vc.com",value:n,onChange:g=>s(g.target.value),onKeyDown:g=>g.key==="Enter"&&u()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:u,children:o.jsx(Gs,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:[e.vip_senders?.map((g,v)=>o.jsxs("div",{className:"flex items-center justify-between bg-secondary/50 p-2 rounded-md text-sm",children:[o.jsx("span",{children:g}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>d(g),children:o.jsx(mn,{className:"h-3 w-3"})})]},v)),(!e.vip_senders||e.vip_senders.length===0)&&o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No VIPs added yet"})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(vR,{className:"h-4 w-4 text-blue-500"}),o.jsx($e,{children:"Team & Trusted Domains"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Re,{placeholder:"company.com",value:a,onChange:g=>l(g.target.value),onKeyDown:g=>g.key==="Enter"&&h()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:h,children:o.jsx(Gs,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:[e.trusted_domains?.map((g,v)=>o.jsxs("div",{className:"flex items-center justify-between bg-secondary/50 p-2 rounded-md text-sm",children:[o.jsxs("span",{children:["@",g]}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>m(g),children:o.jsx(mn,{className:"h-3 w-3"})})]},v)),(!e.trusted_domains||e.trusted_domains.length===0)&&o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No domains added yet"})]})]})]}),o.jsxs("div",{className:"p-4 bg-muted/30 rounded-lg space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(KS,{className:"h-4 w-4 text-muted-foreground"}),o.jsx($e,{children:"Low Priority (Auto-Archive)"})]}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:p.map(g=>o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",id:g.id,className:"accent-primary h-4 w-4",defaultChecked:!0}),o.jsx("label",{htmlFor:g.id,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:g.label})]},g.id))})]}),o.jsxs("div",{className:"bg-blue-500/10 text-blue-500 text-sm p-4 rounded-lg flex items-start gap-2",children:[o.jsx(gg,{className:"h-4 w-4 mt-0.5 shrink-0"}),o.jsx("p",{children:'Tip: Adding your own company domain (@realtimex.ai) to "Team" ensures internal emails are never missed.'})]})]})}const JI=[{id:"inbox_zero",label:"Inbox Zero Daily",icon:eA},{id:"respond_faster",label:"Respond Faster",icon:sR},{id:"focus",label:"Focus on Important",icon:t_},{id:"reduce_time",label:"Reduce Email Time",icon:Js}],QI=[{id:"legal",label:"Legal documents"},{id:"hr",label:"HR & payroll"},{id:"financial",label:"Financial transactions"},{id:"security",label:"Security alerts"}];function ZI({data:e,updateData:t}){const n=s=>{const a=e.never_automate_categories||[];a.includes(s)?t({never_automate_categories:a.filter(l=>l!==s)}):t({never_automate_categories:[...a,s]})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"🎯 What are your email goals?"}),o.jsx("p",{className:"text-muted-foreground",children:"Let's set up automation that works for your specific targets."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx($e,{children:"Primary Goal"}),o.jsx("div",{className:"grid grid-cols-2 gap-3",children:JI.map(s=>o.jsx(Ie,{className:me("cursor-pointer transition-all hover:bg-accent/50",e.primary_goal===s.id?"border-primary bg-accent":""),onClick:()=>t({primary_goal:s.id}),children:o.jsxs(ft,{className:"flex flex-col items-center justify-center p-4 text-center space-y-2",children:[o.jsx(s.icon,{className:me("h-6 w-6",e.primary_goal===s.id?"text-primary":"text-muted-foreground")}),o.jsx("span",{className:"font-medium text-sm",children:s.label})]})},s.id))})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx($e,{children:"Time Budget"}),o.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.time_budget_minutes||30," minutes / day"]})]}),o.jsx("input",{type:"range",min:"15",max:"120",step:"15",className:"w-full h-2 bg-secondary rounded-lg appearance-none cursor-pointer accent-primary",value:e.time_budget_minutes||30,onChange:s=>t({time_budget_minutes:parseInt(s.target.value)})}),o.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:"15 min"}),o.jsx("span",{children:"1 hour"}),o.jsx("span",{children:"2 hours"})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx($e,{children:"Automation Level"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:!e.automation_level||e.automation_level<=3?"Conservative":e.automation_level<=7?"Balanced":"Aggressive"})]}),o.jsxs("div",{className:"relative pt-6",children:[o.jsxs("div",{className:"absolute top-0 w-full flex justify-between text-xs font-medium text-muted-foreground px-1",children:[o.jsx("span",{children:"Manual"}),o.jsx("span",{children:"Fully Automated"})]}),o.jsx("input",{type:"range",min:"1",max:"10",step:"1",className:"w-full h-2 bg-gradient-to-r from-blue-500/20 to-blue-500 rounded-lg appearance-none cursor-pointer accent-primary",value:e.automation_level||5,onChange:s=>t({automation_level:parseInt(s.target.value)})}),o.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:e.automation_level&&e.automation_level>7?"AI drafts and organizes aggressively. You review key items.":"AI suggests drafts. You maintain full control."})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(BA,{className:"h-4 w-4 text-destructive"}),o.jsx($e,{children:"Never Automate (Safety)"})]}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:QI.map(s=>o.jsxs("div",{className:"flex items-center space-x-2 border p-3 rounded-md bg-background",children:[o.jsx(hy,{id:`safety-${s.id}`,checked:e.never_automate_categories?.includes(s.id),onCheckedChange:()=>n(s.id)}),o.jsx($e,{htmlFor:`safety-${s.id}`,className:"cursor-pointer",children:s.label})]},s.id))})]}),o.jsxs("div",{className:"bg-emerald-500/10 border border-emerald-500/20 text-emerald-600 dark:text-emerald-400 p-4 rounded-lg",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2 font-medium",children:[o.jsx(fg,{className:"h-4 w-4"}),"Expected Results"]}),o.jsxs("ul",{className:"text-sm space-y-1 list-disc list-inside opacity-90",children:[o.jsx("li",{children:"Save ~2 hours per week"}),o.jsx("li",{children:"Respond 50% faster to clients"}),o.jsx("li",{children:"Zero missed important emails"})]})]})]})}const Mu=4;function yN({onComplete:e,onClose:t,initialData:n,className:s}){const{t:a}=tt(),{state:l}=In(),{user:u}=l,[d,h]=S.useState(1),[m,p]=S.useState(!1),[g,v]=S.useState(n||{work_style:"startup",preferred_tone:"professional",preferred_length:"medium",primary_goal:"inbox_zero",vip_senders:[],trusted_domains:[],blocked_domains:[],never_automate_categories:["legal","hr","financial"],automation_level:5,time_budget_minutes:30}),b=()=>{d<Mu?h(T=>T+1):j()},w=()=>{d>1?h(T=>T-1):t&&t()},j=async()=>{if(u){p(!0);try{const{error:T}=await pt.from("user_settings").update({...g,persona_completed:!0,persona_completed_at:new Date().toISOString()}).eq("user_id",u.id);if(T)throw T;ue.success("Persona saved successfully!"),e()}catch(T){console.error("Failed to save persona:",T),ue.error("Failed to save persona. Please try again.")}finally{p(!1)}}},k=T=>{v(D=>({...D,...T}))},N=()=>{switch(d){case 1:return o.jsx(KI,{data:g,updateData:k});case 2:return o.jsx(WI,{data:g,updateData:k});case 3:return o.jsx(XI,{data:g,updateData:k});case 4:return o.jsx(ZI,{data:g,updateData:k});default:return null}},R=d/Mu*100;return o.jsxs(Ie,{className:me("w-full max-w-2xl mx-auto border-none shadow-none md:border md:shadow-lg",s),children:[o.jsxs(bt,{children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("span",{className:"text-sm text-muted-foreground",children:["Step ",d," of ",Mu]}),t&&o.jsx(Z,{variant:"ghost",size:"sm",onClick:t,children:"Skip"})]}),o.jsx(my,{value:R,className:"h-2"})]}),o.jsx(ft,{className:"py-4 max-h-[60vh] overflow-y-auto",children:N()}),o.jsxs(q_,{className:"flex justify-between",children:[o.jsx(Z,{variant:"outline",onClick:w,disabled:m,children:d===1&&t?"Cancel":"Back"}),o.jsxs(Z,{onClick:b,disabled:m,children:[m&&o.jsx(Nt,{className:"mr-2 h-4 w-4 animate-spin"}),d===Mu?"Complete Setup":"Next"]})]})]})}function eU(){const{t:e}=tt(),{state:t,actions:n}=In(),[s,a]=S.useState(!1),l=t.settings||{persona_completed:!1},u=async()=>{a(!1),await n.fetchSettings()};return s?o.jsx(Rr,{open:!0,onOpenChange:a,children:o.jsxs(Or,{className:"max-w-5xl sm:max-w-5xl h-[80vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs("div",{className:"p-6 pb-0",children:[o.jsx(Dr,{children:e("persona.edit.title")||"Edit Persona"}),o.jsx(Xs,{children:e("persona.edit.desc")||"Update your digital assistant preferences."})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 pt-2",children:o.jsx(yN,{initialData:l,onComplete:u,onClose:()=>a(!1),className:"max-w-none shadow-none border-0 p-0"})})]})}):o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-medium",children:e("persona.title")||"Digital Persona"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("persona.subtitle")||"Manage how your AI assistant represents you."})]}),o.jsxs(Z,{onClick:()=>a(!0),className:"gap-2",children:[o.jsx(ZS,{className:"w-4 h-4"}),e("common.edit")||"Edit Persona"]})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[o.jsxs(Ie,{children:[o.jsx(bt,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(vd,{className:"w-5 h-5 text-primary"}),o.jsx(Tt,{className:"text-base",children:e("persona.identity")||"Identity"})]})}),o.jsx(ft,{className:"space-y-4 text-sm",children:o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Role:"}),o.jsx("span",{className:"font-medium text-right",children:l.role||"Not set"}),o.jsx("span",{className:"text-muted-foreground",children:"Industry:"}),o.jsx("span",{className:"font-medium text-right",children:l.industry||"Not set"}),o.jsx("span",{className:"text-muted-foreground",children:"Style:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.work_style||"Not set"})]})})]}),o.jsxs(Ie,{children:[o.jsx(bt,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(yd,{className:"w-5 h-5 text-indigo-500"}),o.jsx(Tt,{className:"text-base",children:e("persona.communication")||"Communication"})]})}),o.jsx(ft,{className:"space-y-4 text-sm",children:o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Tone:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.preferred_tone||"Professional"}),o.jsx("span",{className:"text-muted-foreground",children:"Length:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.preferred_length||"Medium"}),o.jsx("span",{className:"text-muted-foreground",children:"Languages:"}),o.jsx("div",{className:"flex justify-end gap-1 flex-wrap",children:(l.common_phrases?.length||0)>0?o.jsx(jl,{variant:"secondary",className:"text-xs",children:"Custom Phrases Active"}):o.jsx("span",{className:"text-muted-foreground italic",children:"None"})})]})})]}),o.jsxs(Ie,{children:[o.jsx(bt,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(t_,{className:"w-5 h-5 text-emerald-500"}),o.jsx(Tt,{className:"text-base",children:e("persona.automation")||"Automation"})]})}),o.jsxs(ft,{className:"space-y-4 text-sm",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Primary Goal:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.primary_goal?.replace("_"," ")||"Inbox Zero"}),o.jsx("span",{className:"text-muted-foreground",children:"Auto Level:"}),o.jsx("div",{className:"flex items-center justify-end gap-2",children:o.jsxs("span",{className:"font-medium",children:[l.automation_level||5,"/10"]})})]}),(l.never_automate_categories?.length||0)>0&&o.jsxs("div",{className:"pt-2",children:[o.jsx("span",{className:"text-xs text-muted-foreground block mb-1",children:"Never Automate:"}),o.jsx("div",{className:"flex flex-wrap gap-1",children:l.never_automate_categories?.map(d=>o.jsx(jl,{variant:"outline",className:"text-xs py-0 h-5 bg-background",children:d},d))})]})]})]}),o.jsxs(Ie,{children:[o.jsx(bt,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(JS,{className:"w-5 h-5 text-sky-500"}),o.jsx(Tt,{className:"text-base",children:e("persona.network")||"Network"})]})}),o.jsxs(ft,{className:"space-y-4 text-sm",children:[o.jsxs("div",{children:[o.jsxs("span",{className:"text-xs text-muted-foreground block mb-2",children:["VIP Senders (",l.vip_senders?.length||0,")"]}),o.jsxs("div",{className:"flex flex-wrap gap-1 max-h-[60px] overflow-hidden",children:[l.vip_senders?.slice(0,3).map(d=>o.jsx(jl,{variant:"secondary",className:"text-xs py-0 h-5 truncate max-w-[150px]",children:d},d)),(l.vip_senders?.length||0)>3&&o.jsxs("span",{className:"text-xs text-muted-foreground flex items-center",children:["+",l.vip_senders.length-3," more"]})]})]}),o.jsx("div",{className:"pt-2 border-t mt-2",children:o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-muted-foreground",children:"Trusted Domains:"}),o.jsx("span",{className:"font-medium",children:l.trusted_domains?.length||0})]})})]})]})]})]})}function tU(){const{t:e}=tt(),[t,n]=S.useState("profile"),{state:s,actions:a}=In();S.useEffect(()=>{a.fetchProfile()},[]);const l=[{id:"profile",label:e("account.profile"),icon:vd},{id:"persona",label:e("persona.title")||"Persona",icon:mR},{id:"security",label:e("account.security"),icon:xg},{id:"database",label:e("account.database"),icon:Ka}];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:e("account.title")}),o.jsx("p",{className:"text-muted-foreground",children:e("account.subtitle")})]}),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:l.map(u=>{const d=u.icon,h=t===u.id;return o.jsxs("button",{onClick:()=>n(u.id),className:`w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${h?"bg-primary text-primary-foreground":"hover:bg-secondary text-muted-foreground"}`,children:[o.jsx(d,{className:"w-4 h-4"}),u.label]},u.id)})}),o.jsxs("div",{className:"mt-auto space-y-1",children:[o.jsxs("button",{onClick:async()=>{await pt.auth.signOut(),g5(),ue.success(e("account.logoutSuccess")),window.location.reload()},className:"w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors hover:bg-destructive/10 text-destructive",children:[o.jsx(dA,{className:"w-4 h-4"}),e("account.logout")]}),o.jsxs("div",{className:"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:e("account.version")}),o.jsxs("p",{className:"text-xs font-mono text-muted-foreground/70",children:["v","2.22.1"]})]})]})]}),o.jsxs("div",{className:"flex-1 space-y-6",children:[t==="profile"&&o.jsx(nU,{}),t==="persona"&&o.jsx(eU,{}),t==="security"&&o.jsx(rU,{}),t==="database"&&o.jsx(sU,{})]})]})]})}function nU(){const{t:e}=tt(),{state:t,actions:n}=In(),[s,a]=S.useState(""),[l,u]=S.useState(""),[d,h]=S.useState(!1),[m,p]=S.useState(!1),[g,v]=S.useState(Tr.isEnabled());S.useEffect(()=>{t.profile&&(a(t.profile.first_name||""),u(t.profile.last_name||""))},[t.profile]);const b=()=>{const k=!g;Tr.setEnabled(k),v(k),k?(Tr.playSuccess(),ue.success(e("account.profile.soundsEnabled"))):ue.info(e("account.profile.soundsDisabled"))},w=async()=>{h(!0);const k=await n.updateProfile({first_name:s,last_name:l});h(!1),k&&ue.success(e("account.profile.updated"))},j=async k=>{const N=k.target.files?.[0];if(!(!N||!t.user)){p(!0);try{const R=N.name.split(".").pop(),T=`${t.user.id}/avatar.${R}`,{data:D,error:U}=await pt.storage.from("avatars").upload(T,N,{upsert:!0});if(U)throw U;const{data:{publicUrl:M}}=pt.storage.from("avatars").getPublicUrl(T);await n.updateProfile({avatar_url:M}),ue.success(e("account.profile.avatarUpdated"))}catch(R){console.error("Avatar upload error:",R),ue.error(e("account.profile.avatarError"))}finally{p(!1)}}};return o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsx(Tt,{children:e("account.profile.title")}),o.jsx(Mn,{children:e("account.profile.desc")})]}),o.jsxs(ft,{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:t.profile?.avatar_url?o.jsx("img",{src:t.profile.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):o.jsx(vd,{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(xC,{className:"w-6 h-6 text-white"}),o.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:j,disabled:m})]}),m&&o.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 rounded-full",children:o.jsx(vt,{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($e,{htmlFor:"first-name",children:e("account.profile.firstName")}),o.jsx(Re,{id:"first-name",value:s,onChange:k=>a(k.target.value),placeholder:e("account.profile.firstNamePlaceholder")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"last-name",children:e("account.profile.lastName")}),o.jsx(Re,{id:"last-name",value:l,onChange:k=>u(k.target.value),placeholder:e("account.profile.lastNamePlaceholder")})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"email",children:e("account.profile.email")}),o.jsx(Re,{id:"email",value:t.profile?.email||"",disabled:!0,className:"bg-secondary/50"}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:e("account.profile.emailHelp")})]})]})]}),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:e("account.profile.sounds")}),o.jsx("p",{className:"text-xs text-muted-foreground",children:e("account.profile.soundsHelp")})]}),o.jsxs(Z,{variant:g?"default":"outline",size:"sm",onClick:b,className:"gap-2",children:[g?o.jsx(Al,{className:"w-4 h-4"}):o.jsx(vg,{className:"w-4 h-4"}),e(g?"common.enabled":"common.disabled")]})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:w,disabled:d,children:[d?o.jsx(vt,{size:"sm",className:"mr-2"}):o.jsx(OA,{className:"w-4 h-4 mr-2"}),e("common.saveChanges")]})})]})]})}function rU(){const{t:e}=tt(),[t,n]=S.useState(""),[s,a]=S.useState(""),[l,u]=S.useState(!1),d=async()=>{if(!t){ue.error(e("account.security.enterPassword"));return}if(t!==s){ue.error(e("account.security.passwordsMismatch"));return}if(t.length<6){ue.error(e("account.security.passwordTooShort"));return}u(!0);try{const{api:h}=await Ni(async()=>{const{api:p}=await Promise.resolve().then(()=>o5);return{api:p}},void 0),m=await h.changePassword(t);m.success?(ue.success(e("account.security.passwordChanged")),n(""),a("")):ue.error(m.error?.message||"Failed to change password")}catch{ue.error(e("common.errorOccurred"))}finally{u(!1)}};return o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsx(Tt,{children:e("account.security.title")}),o.jsx(Mn,{children:e("account.security.desc")})]}),o.jsxs(ft,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"new-password",children:e("account.security.newPassword")}),o.jsx(Re,{id:"new-password",type:"password",value:t,onChange:h=>n(h.target.value),placeholder:"••••••••"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"confirm-password",children:e("account.security.confirmPassword")}),o.jsx(Re,{id:"confirm-password",type:"password",value:s,onChange:h=>a(h.target.value),placeholder:"••••••••"})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:d,disabled:l,children:[l?o.jsx(vt,{size:"sm",className:"mr-2"}):o.jsx(pg,{className:"w-4 h-4 mr-2"}),e("account.security.updatePassword")]})})]})]})}function sU(){const{t:e}=tt(),[t,n]=S.useState(!1),[s,a]=S.useState(null),l=ao(),u=s5();S.useEffect(()=>{l&&ly(pt).then(a)},[]);const d=()=>{confirm(e("account.database.clearConfirm"))&&(n5(),window.location.reload())};return o.jsxs(o.Fragment,{children:[o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsxs(Tt,{className:"flex items-center gap-2",children:[o.jsx(Ka,{className:"w-5 h-5 text-primary"}),e("account.database.title")]}),o.jsx(Mn,{children:e("account.database.desc")})]}),o.jsx(ft,{className:"space-y-6",children:l?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(Xu,{className:"w-6 h-6 text-emerald-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("p",{className:"font-semibold text-emerald-700 dark:text-emerald-400",children:e("account.database.connected")}),s?.latestMigrationTimestamp&&o.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-600 px-1.5 py-0.5 rounded border border-emerald-500/20",title:"Database Schema Version",children:["Schema ",s.latestMigrationTimestamp]})]}),o.jsx("p",{className:"text-sm font-mono break-all opacity-80",children:l.url})]})]}),u==="env"&&o.jsxs(Pi,{className:"bg-amber-500/5 border-amber-500/20",children:[o.jsx(Cl,{className:"h-4 w-4 text-amber-500"}),o.jsx(zi,{className:"text-amber-700 dark:text-amber-400 text-xs",children:e("account.database.envAlert")})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[o.jsxs(Z,{variant:"outline",onClick:()=>n(!0),className:"w-full",children:[o.jsx(Cl,{className:"w-4 h-4 mr-2"}),e("account.database.changeConnection")]}),u==="ui"&&o.jsxs(Z,{variant:"outline",onClick:d,className:"w-full text-destructive hover:bg-destructive/10",children:[o.jsx(xd,{className:"w-4 h-4 mr-2"}),e("account.database.clearConfig")]})]}),o.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[o.jsx($e,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:e("account.database.anonKey")}),o.jsxs("div",{className:"p-2 bg-secondary/50 rounded-lg font-mono text-xs break-all",children:[l.anonKey.substring(0,20),"...",l.anonKey.substring(l.anonKey.length-10)]})]})]}):o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center space-y-4",children:[o.jsx(DC,{className:"w-12 h-12 text-destructive opacity-20"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-medium",children:e("account.database.noConnection")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("account.database.configureHelp")})]}),o.jsxs(Z,{onClick:()=>n(!0),children:[o.jsx(Ka,{className:"w-4 h-4 mr-2"}),e("account.database.setup")]})]})})]}),o.jsx(Uk,{open:t,onComplete:()=>n(!1),canClose:!0})]})}function iU(){const{t:e}=tt();return o.jsx("span",{className:"inline-flex items-center text-xs px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-950/70 text-blue-700 dark:text-blue-200 border border-blue-200 dark:border-blue-700 shrink-0 font-medium",children:e("autopilot.badge")})}function Z1({rules:e,onToggleRule:t,onEditRule:n,onDeleteRule:s}){const{t:a}=tt(),l={email_organization:{label:a("autopilot.category.email_organization.label"),icon:Cr,emoji:"📧",description:a("autopilot.category.email_organization.desc")},priority_alerts:{label:a("autopilot.category.priority_alerts.label"),icon:mr,emoji:"🚨",description:a("autopilot.category.priority_alerts.desc")},development:{label:a("autopilot.category.development.label"),icon:ss,emoji:"💻",description:a("autopilot.category.development.desc")},sales_business:{label:a("autopilot.category.sales_business.label"),icon:YS,emoji:"💼",description:a("autopilot.category.sales_business.desc")},operations:{label:a("autopilot.category.operations.label"),icon:Cl,emoji:"⚙️",description:a("autopilot.category.operations.desc")}},u=e.reduce((m,p)=>{const g=p.category||"email_organization";return m[g]||(m[g]=[]),m[g].push(p),m},{}),d=m=>{const p=m.filter(v=>v.is_enabled).length,g=m.length;return{enabled:p,total:g}},h=m=>!m||m.length===0?"":m.map(p=>p.startsWith("label:")?`label:${p.substring(6)}`:p).join(" + ");return o.jsx("div",{className:"space-y-8",children:Object.entries(l).map(([m,p])=>{const g=u[m]||[];if(g.length===0)return null;const v=d(g);return o.jsxs("div",{className:"space-y-3",children:[o.jsx("div",{className:"flex items-center justify-between",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg bg-secondary/50 flex items-center justify-center text-primary",children:o.jsx(p.icon,{className:"w-5 h-5"})}),o.jsxs("div",{children:[o.jsxs("h3",{className:"font-semibold text-base flex items-center gap-2",children:[p.label,o.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:a("autopilot.enabledCount").replace("{enabled}",v.enabled.toString()).replace("{total}",v.total.toString())})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:p.description})]})]})}),o.jsx("div",{className:"space-y-1",children:g.map(b=>o.jsxs("div",{className:"flex items-center justify-between py-3 px-4 rounded-lg hover:bg-secondary/30 transition-colors",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h4",{className:"font-medium text-sm truncate",children:b.name}),b.is_system_managed&&o.jsx(iU,{})]}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[b.intent&&o.jsx("p",{className:"text-xs text-muted-foreground truncate",children:b.intent}),b.actions&&b.actions.length>0&&o.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:["→ ",h(b.actions)]})]})]}),o.jsxs("div",{className:"flex items-center gap-2 ml-4 shrink-0",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(b.id),title:a("autopilot.editRuleTooltip"),children:o.jsx(ZS,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs(Z,{variant:b.is_enabled?"default":"outline",size:"sm",onClick:()=>t(b.id,!b.is_enabled),className:"h-8 px-3",children:[o.jsx(tp,{className:"w-4 h-4 mr-1"}),b.is_enabled?a("common.on"):a("common.off")]}),!b.is_system_managed&&s&&o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive",onClick:()=>s(b.id),title:a("autopilot.deleteRuleTooltip"),children:o.jsx(xd,{className:"w-4 h-4"})})]})]},b.id))})]},m)})})}function aU({open:e,rule:t,onClose:n,onSave:s,onFileUpload:a,onRemoveAttachment:l}){const{t:u}=tt(),[d,h]=S.useState(!1),[m,p]=S.useState(!1),[g,v]=S.useState(""),[b,w]=S.useState(""),[j,k]=S.useState(""),[N,R]=S.useState("category"),[T,D]=S.useState("newsletter"),[U,M]=S.useState(""),[B,P]=S.useState(["archive"]),[H,O]=S.useState(""),[Q,G]=S.useState([]);S.useEffect(()=>{if(t){v(t.name||""),w(t.description||""),k(t.intent||""),P(t.actions||["archive"]),O(t.instructions||""),G(t.attachments||[]);const L=t.condition||{},V=Object.keys(L).filter(q=>q!=="older_than_days");V.length>0&&(R(V[0]),D(L[V[0]])),L.older_than_days&&M(String(L.older_than_days))}else v(""),w(""),k(""),R("category"),D("newsletter"),M(""),P(["archive"]),O(""),G([])},[t,e]);const he=async()=>{if(g.trim()&&B.length!==0){h(!0);try{const L={[N]:T};U&&(L.older_than_days=parseInt(U,10));const V=B.includes("draft"),q={name:g.trim(),description:b.trim()||void 0,intent:j.trim()||void 0,condition:L,actions:B,instructions:V?H:void 0,attachments:V?Q:[],is_enabled:!0};await s(q)&&n()}finally{h(!1)}}},se=async L=>{if(!a)return;const V=L.target.files;if(!(!V||V.length===0)){p(!0);try{const q=await a(V[0]);q&&G(de=>[...de,q])}finally{p(!1),L.target.value=""}}},ae=L=>{G(V=>V.filter(q=>q.path!==L)),l&&l(L)};return o.jsx(Rr,{open:e,onOpenChange:L=>!L&&n(),children:o.jsxs(Or,{className:"sm:max-w-xl max-h-[90vh] flex flex-col p-0",children:[o.jsxs(Ws,{className:"p-6 border-b",children:[o.jsx(Dr,{children:u(t?"autopilot.editDialog.editTitle":"autopilot.editDialog.createTitle")}),o.jsx(Xs,{children:u("autopilot.editDialog.desc")})]}),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:u("autopilot.editDialog.ruleName")}),o.jsx(Re,{placeholder:u("autopilot.editDialog.namePlaceholder"),value:g,onChange:L=>v(L.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.description")}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[60px] text-sm",placeholder:u("autopilot.editDialog.descPlaceholder"),value:b,onChange:L=>w(L.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.descriptionHelp")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.intent")}),o.jsx(Re,{placeholder:u("autopilot.editDialog.intentPlaceholder"),value:j,onChange:L=>k(L.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.intentHelp")})]}),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:u("autopilot.editDialog.conditionField")}),o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:N,onChange:L=>{R(L.target.value),L.target.value==="category"?D("newsletter"):L.target.value==="sentiment"?D("Positive"):L.target.value==="priority"?D("High"):D("")},children:[o.jsxs("optgroup",{label:u("autopilot.editDialog.aiAnalysisGroup"),children:[o.jsx("option",{value:"category",children:u("autopilot.editDialog.category")}),o.jsx("option",{value:"sentiment",children:u("autopilot.editDialog.sentiment")}),o.jsx("option",{value:"priority",children:u("autopilot.editDialog.priority")})]}),o.jsxs("optgroup",{label:u("autopilot.editDialog.metadataGroup"),children:[o.jsx("option",{value:"sender_email",children:u("autopilot.editDialog.senderEmail")}),o.jsx("option",{value:"sender_domain",children:u("autopilot.editDialog.senderDomain")}),o.jsx("option",{value:"sender_contains",children:u("autopilot.editDialog.senderContains")}),o.jsx("option",{value:"subject_contains",children:u("autopilot.editDialog.subjectContains")}),o.jsx("option",{value:"body_contains",children:u("autopilot.editDialog.bodyContains")})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.equalsValue")}),N==="category"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:L=>D(L.target.value),children:[o.jsx("option",{value:"newsletter",children:u("autopilot.editDialog.cat.newsletter")}),o.jsx("option",{value:"news",children:u("autopilot.editDialog.cat.news")}),o.jsx("option",{value:"spam",children:u("autopilot.editDialog.cat.spam")}),o.jsx("option",{value:"promotional",children:u("autopilot.editDialog.cat.promotional")}),o.jsx("option",{value:"transactional",children:u("autopilot.editDialog.cat.transactional")}),o.jsx("option",{value:"social",children:u("autopilot.editDialog.cat.social")}),o.jsx("option",{value:"support",children:u("autopilot.editDialog.cat.support")}),o.jsx("option",{value:"client",children:u("autopilot.editDialog.cat.client")}),o.jsx("option",{value:"internal",children:u("autopilot.editDialog.cat.internal")}),o.jsx("option",{value:"personal",children:u("autopilot.editDialog.cat.personal")}),o.jsx("option",{value:"other",children:u("autopilot.editDialog.cat.other")})]}):N==="sentiment"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:L=>D(L.target.value),children:[o.jsx("option",{value:"Positive",children:u("autopilot.editDialog.sent.positive")}),o.jsx("option",{value:"Neutral",children:u("autopilot.editDialog.sent.neutral")}),o.jsx("option",{value:"Negative",children:u("autopilot.editDialog.sent.negative")})]}):N==="priority"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:L=>D(L.target.value),children:[o.jsx("option",{value:"High",children:u("autopilot.editDialog.prio.high")}),o.jsx("option",{value:"Medium",children:u("autopilot.editDialog.prio.medium")}),o.jsx("option",{value:"Low",children:u("autopilot.editDialog.prio.low")})]}):o.jsx(Re,{placeholder:N==="sender_domain"?"rta.vn":N==="sender_email"?"john@example.com":u("autopilot.editDialog.keywordsPlaceholder"),value:T,onChange:L=>D(L.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(Js,{className:"w-4 h-4"}),u("autopilot.editDialog.olderThan")]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Re,{type:"number",min:"0",placeholder:"0",className:"w-24",value:U,onChange:L=>M(L.target.value)}),o.jsx("span",{className:"text-sm text-muted-foreground",children:u("autopilot.editDialog.days")})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.olderThanHelp")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.performActions")}),o.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:u("autopilot.editDialog.actionsDesc")}),o.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"archive",label:u("autopilot.editDialog.action.archive")},{value:"delete",label:u("autopilot.editDialog.action.delete")},{value:"draft",label:u("autopilot.editDialog.action.draft")},{value:"star",label:u("autopilot.editDialog.action.star")}].map(L=>o.jsxs("label",{className:`flex items-center gap-2 p-2 border rounded-md cursor-pointer transition-colors ${B.includes(L.value)?"bg-primary/10 border-primary":"bg-background hover:bg-secondary/50"}`,children:[o.jsx("input",{type:"checkbox",checked:B.includes(L.value),onChange:V=>{V.target.checked?P([...B,L.value]):P(B.filter(q=>q!==L.value))},className:"rounded border-gray-300"}),o.jsx("span",{className:"text-sm",children:L.label})]},L.value))})]}),B.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:u("autopilot.editDialog.draftInstructions")}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[80px] text-sm",placeholder:u("autopilot.editDialog.draftInstPlaceholder"),value:H,onChange:L=>O(L.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.draftInstHelp")})]}),a&&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(_A,{className:"w-4 h-4"}),u("autopilot.editDialog.attachments")]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[Q.map(L=>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:L.name}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive",onClick:()=>ae(L.path),children:o.jsx(mn,{className:"w-3 h-3"})})]},L.path)),o.jsxs("div",{className:"relative",children:[o.jsx("input",{type:"file",className:"absolute inset-0 opacity-0 cursor-pointer",onChange:se,disabled:m}),o.jsxs(Z,{variant:"outline",size:"sm",className:"w-full border-dashed",disabled:m,children:[m?o.jsx(vt,{size:"sm",className:"mr-2"}):o.jsx(Gs,{className:"w-3 h-3 mr-2"}),u(m?"autopilot.editDialog.uploading":"autopilot.editDialog.addAttachment")]})]})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.attachmentsHelp")})]})]})]}),o.jsxs(Fs,{className:"p-6 border-t bg-secondary/5",children:[o.jsx(Z,{variant:"outline",onClick:n,children:u("common.cancel")}),o.jsxs(Z,{onClick:he,disabled:d||!g.trim()||B.length===0,children:[d?o.jsx(vt,{size:"sm",className:"mr-2"}):t?o.jsx(Ti,{className:"w-4 h-4 mr-2"}):o.jsx(Gs,{className:"w-4 h-4 mr-2"}),u(t?"common.saveChanges":"autopilot.addCustomRule")]})]})]})})}function oU(){const{state:e,actions:t}=In(),{t:n}=tt(),[s,a]=S.useState([]),[l,u]=S.useState(!0),[d,h]=S.useState(null),[m,p]=S.useState(!1),[g,v]=S.useState(null),b=async()=>{u(!0),h(null);try{const P=await De.getRules();if(P.error)throw new Error(typeof P.error=="string"?P.error:P.error.message);a(P.data?.rules||[])}catch(P){h(P instanceof Error?P.message:n("autopilot.loadError")),console.error("Error fetching rules:",P)}finally{u(!1)}};S.useEffect(()=>{b()},[]);const w=async(P,H)=>{try{const O=await De.updateRule(P,{is_enabled:H});if(O.error)throw new Error(typeof O.error=="string"?O.error:O.error.message);a(Q=>Q.map(G=>G.id===P?{...G,is_enabled:H}:G))}catch(O){console.error("Error toggling rule:",O),await b()}},j=P=>{const H=s.find(O=>O.id===P);H&&(v(H),p(!0))},k=async P=>{if(confirm(n("autopilot.deleteConfirm")))try{await t.deleteRule(P)?(ue.success(n("autopilot.ruleDeleted")),a(O=>O.filter(Q=>Q.id!==P))):ue.error(n("autopilot.ruleDeleteFailed"))}catch(H){console.error("Error deleting rule:",H),ue.error(n("autopilot.ruleDeleteError"))}},N=()=>{v(null),p(!0)},R=async P=>{try{let H=!1;return g?H=await t.updateRule(g.id,P):H=await t.createRule(P),H?(ue.success(n(g?"autopilot.ruleUpdated":"autopilot.ruleCreated")),await b(),!0):(ue.error(n(g?"autopilot.ruleUpdateFailed":"autopilot.ruleCreateFailed")),!1)}catch(H){return console.error("Error saving rule:",H),ue.error(n("autopilot.ruleSaveError")),!1}},T=async P=>{try{const H=P.name.split(".").pop(),O=`${Math.random().toString(36).substring(2)}.${H}`,Q=`${e.user.id}/${O}`,{error:G}=await pt.storage.from("rule-attachments").upload(Q,P);if(G)throw G;return ue.success(n("autopilot.fileUploaded")),{name:P.name,path:Q,type:P.type,size:P.size}}catch(H){return console.error("Upload error:",H),ue.error(n("autopilot.fileUploadFailed")),null}},D=()=>{p(!1),v(null)};if(l)return o.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(Gt,{className:"w-8 h-8 animate-spin text-gray-400"}),o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("autopilot.loadingRules")})]})});if(d)return o.jsxs(Pi,{variant:"destructive",children:[o.jsx(mr,{className:"h-4 w-4"}),o.jsxs(zi,{children:[d,o.jsxs(Z,{variant:"outline",size:"sm",onClick:b,className:"ml-4",children:[o.jsx(Gt,{className:"w-4 h-4 mr-2"}),n("autopilot.refresh")]})]})]});const U=s.filter(P=>P.is_system_managed),M=s.filter(P=>!P.is_system_managed),B=U.filter(P=>P.is_enabled).length;return s.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[400px] p-8",children:[o.jsx(Vu,{className:"w-16 h-16 text-gray-300 dark:text-gray-700 mb-4"}),o.jsx("h3",{className:"text-lg font-semibold mb-2",children:n("autopilot.noRulesTitle")}),o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 text-center max-w-md mb-4",children:n("autopilot.noRulesDesc")})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-8",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(Vu,{className:"w-6 h-6 text-blue-500"}),n("autopilot.title")]}),o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:n("autopilot.rulesEnabled").replace("{enabled}",B.toString()).replace("{total}",U.length.toString())})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(Z,{variant:"default",size:"sm",onClick:N,children:[o.jsx(Gs,{className:"w-4 h-4 mr-2"}),n("autopilot.addCustomRule")]}),o.jsxs(Z,{variant:"outline",size:"sm",onClick:b,disabled:l,children:[o.jsx(Gt,{className:`w-4 h-4 mr-2 ${l?"animate-spin":""}`}),n("autopilot.refresh")]})]})]}),U.length>0&&o.jsxs(Pi,{children:[o.jsx(Vu,{className:"h-4 w-4"}),o.jsx(zi,{children:n("autopilot.infoDesc")})]}),U.length>0&&o.jsx(Z1,{rules:U,onToggleRule:w,onEditRule:j,onDeleteRule:k}),M.length>0&&o.jsxs("div",{className:"space-y-4 pt-4 border-t",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-semibold",children:n("autopilot.customRules")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:n("autopilot.customRulesDesc")})]}),o.jsx(Z1,{rules:M,onToggleRule:w,onEditRule:j,onDeleteRule:k})]})]}),o.jsx(aU,{open:m,rule:g,onClose:D,onSave:R,onFileUpload:T})]})}function lU({length:e=6,value:t,onChange:n,onComplete:s,disabled:a=!1,error:l=!1}){const u=S.useRef([]),[d,h]=S.useState(null),m=(v,b)=>{const w=b.replace(/[^0-9]/g,"");if(w.length===0){const N=t.split("");N[v]=" ",t.split("");let R=t.split("");v<R.length&&R.splice(v,1);const T=R.join("");n(T),v>0&&u.current[v-1]?.focus();return}t.split("");const j=[...t];j[v]=w[0],n(j.join("")),v<e-1&&u.current[v+1]?.focus();const k=j.join("");k.length===e&&s&&s(k)},p=(v,b)=>{b.key==="Backspace"&&!t[v]&&v>0||b.key==="ArrowLeft"&&v>0?u.current[v-1]?.focus():b.key==="ArrowRight"&&v<e-1&&u.current[v+1]?.focus()},g=v=>{v.preventDefault();const w=v.clipboardData.getData("text/plain").replace(/[^0-9]/g,"").slice(0,e);n(w);const j=Math.min(w.length,e-1);u.current[j]?.focus(),w.length===e&&s&&s(w)};return o.jsx("div",{className:"flex gap-2 justify-center",children:Array.from({length:e}).map((v,b)=>o.jsx(Re,{ref:w=>{u.current[b]=w},type:"text",inputMode:"numeric",maxLength:1,value:t[b]||"",onChange:w=>m(b,w.target.value),onKeyDown:w=>p(b,w),onPaste:g,onFocus:()=>h(b),onBlur:()=>h(null),disabled:a,className:me("w-10 h-10 sm:w-12 sm:h-12 text-center text-lg font-semibold px-0",l&&"border-destructive focus-visible:ring-destructive",d===b&&"ring-2 ring-ring"),"aria-label":`Digit ${b+1}`},b))})}function cU({onSuccess:e,onConfigure:t,isInitialized:n}){const{t:s}=tt(),[a,l]=S.useState(""),[u,d]=S.useState(""),[h,m]=S.useState(""),[p,g]=S.useState(""),[v,b]=S.useState(!1),[w,j]=S.useState(n===void 0),[k,N]=S.useState(n??!1),[R,T]=S.useState(""),[D,U]=S.useState(!1),[M,B]=S.useState("password"),[P,H]=S.useState("email"),[O,Q]=S.useState(""),[G,he]=S.useState(!1);S.useEffect(()=>{n===void 0?se():he(!n)},[n]);const se=async()=>{try{const{data:V,error:q}=await pt.from("init_state").select("is_initialized");if(q){if(q.code==="42P01"){console.info("[Login] init_state relation missing - fresh database detected."),N(!1),he(!0);return}console.warn("[Login] Init check error:",q),N(!1),he(!0),T(q.message);return}const de=V&&V.length>0&&V[0].is_initialized>0;N(de),he(!de)}catch(V){console.warn("[Login] Init check exception:",V),N(!1),he(!0),T(V.message||"Connection failed")}finally{j(!1)}},ae=async V=>{V.preventDefault(),b(!0),T("");try{if(k){if(M==="password"){const{error:q}=await pt.auth.signInWithPassword({email:a,password:u});if(q)throw q;ue.success("Logged in successfully"),e?.()}else if(P==="email"){const{error:q}=await pt.auth.signInWithOtp({email:a,options:{shouldCreateUser:!1}});if(q)throw q;H("verify"),ue.success("Validation code sent to your email")}}else{const{data:q,error:de}=await pt.functions.invoke("setup",{body:{email:a,password:u,first_name:h,last_name:p}});if(de||!q){if(de?.message?.includes("First user already exists")){ue.info("System already initialized. Please log in."),N(!0);return}throw new Error(de?.message||"Failed to create admin account")}ue.success("Admin account created! Signing you in...");const{error:C}=await pt.auth.signInWithPassword({email:a,password:u});if(C)throw C;N(!0),e?.()}}catch(q){T(q?.message||"Authentication failed"),console.error("[Login] Error:",q)}finally{b(!1)}},L=async()=>{b(!0),T("");try{const{data:V,error:q}=await pt.auth.verifyOtp({email:a,token:O,type:"magiclink"});if(q)throw q;if(!V.session)throw new Error("Failed to create session");ue.success("Logged in successfully"),e?.()}catch(V){T(V?.message||"Invalid code")}finally{b(!1)}};return w?o.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(Nt,{className:"w-10 h-10 animate-spin text-primary"}),o.jsx("p",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground",children:"Initializing Engine..."})]})}):o.jsxs("div",{className:"min-h-screen bg-background flex items-center justify-center p-8 relative overflow-hidden",children:[o.jsxs("div",{className:"absolute top-6 right-6 flex items-center gap-4 z-50",children:[t&&o.jsxs(Z,{variant:"ghost",size:"sm",onClick:t,className:"text-xs font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all",children:[o.jsx(Cl,{className:"w-3.5 h-3.5 mr-2"}),"Configure"]}),o.jsx(v_,{}),o.jsx(iy,{})]}),o.jsxs(rs.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full max-w-md relative z-10",children:[o.jsxs("div",{className:"glass p-10 space-y-8 relative overflow-hidden",children:[o.jsxs("div",{className:"text-center space-y-3",children:[o.jsx("div",{className:"mx-auto w-16 h-16 bg-primary rounded-2xl flex items-center justify-center mb-6",children:o.jsx(cy,{className:"w-10 h-10 text-primary-foreground"})}),o.jsx("h2",{className:"text-3xl font-black italic tracking-tighter uppercase text-foreground",children:s(G?"login.initialize":"login.secureLogin")}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-[0.2em] uppercase",children:G?"Create your primary administrator account":M==="otp"?"Magic link authentication":"Personal Access Key Required"})]}),o.jsxs("form",{onSubmit:ae,className:"space-y-4",children:[o.jsxs(mk,{mode:"wait",children:[G&&o.jsxs(rs.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"First Name"}),o.jsx(Re,{value:h,onChange:V=>m(V.target.value),required:G,placeholder:s("login.firstNamePlaceholder"),className:"bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Last Name"}),o.jsx(Re,{value:p,onChange:V=>g(V.target.value),required:G,placeholder:s("login.lastNamePlaceholder"),className:"bg-background"})]})]},"signup-fields"),M==="password"||P==="email"?o.jsxs(rs.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Email Coordinates"}),o.jsxs("div",{className:"relative",children:[o.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),o.jsx(Re,{type:"email",placeholder:s("login.emailPlaceholder"),value:a,onChange:V=>l(V.target.value),required:!0,className:"pl-10 bg-background",autoComplete:"email",disabled:P==="verify"})]})]},"email-field"):null,M==="password"&&o.jsxs(rs.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Access Password"}),o.jsxs("div",{className:"relative",children:[o.jsx(V0,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),o.jsx(Re,{type:D?"text":"password",placeholder:"••••••••",value:u,onChange:V=>d(V.target.value),required:!0,minLength:6,className:"pl-10 pr-10 bg-background",autoComplete:G?"new-password":"current-password"}),o.jsx("button",{type:"button",onClick:()=>U(!D),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground/30 hover:text-primary transition-colors",children:D?o.jsx(BC,{size:16}):o.jsx(mg,{size:16})})]})]},"password-field"),M==="otp"&&P==="verify"&&o.jsxs(rs.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"space-y-6 py-4",children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(lU,{value:O,onChange:Q,length:6,onComplete:()=>{}})}),o.jsx(Z,{type:"button",variant:"link",className:"w-full text-[10px] font-bold uppercase tracking-widest text-primary/60",onClick:()=>H("email"),children:"Change Coordinates"}),o.jsxs(Z,{type:"button",onClick:L,disabled:v||O.length!==6,className:"w-full h-12 shadow-md",children:[v?o.jsx(Nt,{className:"w-5 h-5 animate-spin mr-2"}):o.jsx(xg,{size:18,className:"mr-2"}),"Verify Access"]})]},"otp-field")]}),R&&o.jsxs(rs.div,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"bg-destructive/10 text-destructive text-[11px] font-bold p-3 rounded-xl border border-destructive/20 flex items-start gap-2",children:[o.jsx(mr,{size:14,className:"mt-0.5 shrink-0"}),o.jsx("p",{children:R})]}),M!=="otp"||P==="email"?o.jsx(Z,{type:"submit",disabled:v||!a||M==="password"&&!u,className:"w-full h-12 shadow-md mt-4",children:v?o.jsx(Nt,{className:"w-5 h-5 animate-spin"}):o.jsxs(o.Fragment,{children:[G?o.jsx(gR,{className:"w-5 h-5 mr-2"}):M==="otp"?o.jsx(Cr,{className:"w-5 h-5 mr-2"}):o.jsx(cA,{className:"w-5 h-5 mr-2"}),s(G?"login.initializeMaster":M==="otp"?"login.sendMagicLink":"login.openDashboard")]})}):null]}),o.jsxs("div",{className:"space-y-4 pt-4 border-t border-border/10",children:[!G&&o.jsx("div",{className:"flex flex-col gap-2",children:M==="password"?o.jsxs("button",{type:"button",onClick:()=>{B("otp"),H("email"),T("")},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-white/5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all rounded-xl",children:[o.jsx(V0,{size:14})," Magic Link Login"]}):o.jsxs("button",{type:"button",onClick:()=>{B("password"),T("")},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-white/5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all rounded-xl",children:[o.jsx(dg,{size:14})," Password Access"]})}),o.jsxs("p",{className:"text-center text-[10px] text-muted-foreground font-bold uppercase tracking-wider",children:[G?"Already have an account?":"Need a new account?"," "," ",o.jsx("button",{onClick:()=>{he(!G),B("password"),T("")},className:"text-primary hover:underline ml-1",children:G?"Login Instead":"Create Account"})]})]})]}),o.jsx("div",{className:"mt-8 text-center",children:o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/30 uppercase tracking-[0.4em]",children:"Powered by RealTimeX Intelligence"})})]})]})}function uU({status:e,onDismiss:t,onLearnMore:n}){const[s,a]=S.useState(!0);if(!s)return null;const l=()=>{gL(),a(!1),t?.()},u=()=>{n?n():(navigator.clipboard.writeText("npx email-automator migrate"),ue.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(Mi,{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:l,children:[o.jsx(mn,{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 (",e.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:u,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:l,children:"Remind Later"})]})]})]})})})}function dU({open:e,onOpenChange:t,status:n}){const s=ao(),[a,l]=S.useState(!1),[u,d]=S.useState([]),[h,m]=S.useState(""),p=S.useRef(null),g=S.useMemo(()=>{const b=s?.url;if(!b)return"";try{return new URL(b).hostname.split(".")[0]||""}catch{return""}},[s?.url]);S.useEffect(()=>{p.current&&p.current.scrollIntoView({behavior:"smooth"})},[u]);const v=async()=>{if(!g){ue.error("Missing Project ID");return}if(!h){ue.error("Provide a Supabase Personal Access Token.");return}l(!0),d(["Initializing migration..."]);try{const b=async N=>{const R=new TextDecoder;let T="",D=null;const U=M=>{const B=M.trim();if(!(!B||!B.startsWith("data: ")))try{const P=B.substring(6),H=JSON.parse(P);H.type==="done"?(H.data==="success"||H.data==="failed")&&(D=H.data==="success"?"success":"failure"):H.data&&d(O=>[...O,H.data])}catch(P){console.error("Failed to parse SSE line:",B,P)}};for(;;){const{done:M,value:B}=await N.read();if(M)break;T+=R.decode(B,{stream:!0});const P=T.split(`
136
- `);T=P.pop()||"",P.forEach(U)}return T+=R.decode(),T&&U(T),D};d(N=>[...N,"","📦 Database Migration & Edge Functions Deployment"]);const w=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:g,accessToken:h})});if(!w.ok)throw new Error(`Migration failed: ${w.status} ${w.statusText}`);const j=w.body?.getReader();if(!j)throw new Error("No migration response stream received.");if(await b(j)!=="success")throw new Error("Migration did not complete successfully");d(N=>[...N,"","═".repeat(60),"✅ Setup Complete!","","✓ Database schema updated","✓ Edge Functions deployed","","🎉 Your Email Automator is ready to use!","📝 The application will reload automatically...","═".repeat(60)]),setTimeout(()=>{window.location.reload()},3e3)}catch(b){console.error(b),d(w=>[...w,"",`❌ Error: ${b instanceof Error?b.message:String(b)}`]),ue.error("Setup failed. Check logs for details.")}finally{l(!1)}};return o.jsx(Rr,{open:e,onOpenChange:b=>!a&&t(b),children:o.jsxs(Or,{className:"max-h-[90vh] sm:max-w-5xl overflow-y-auto",children:[o.jsxs(Ws,{children:[o.jsxs(Dr,{className:"flex items-center gap-2 text-xl",children:[o.jsx(Mi,{className:"h-6 w-6 text-red-700 dark:text-red-600"}),"Database Setup Required"]}),o.jsxs(Xs,{children:["Your application version (",n.appVersion,") requires database migration and Edge Functions deployment to function correctly."]})]}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs(Pi,{children:[o.jsx(Za,{className:"h-4 w-4"}),o.jsxs(zi,{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 ",n.appVersion]}),o.jsx("li",{children:"Deploys Edge Functions (API endpoints) to your Supabase project"}),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:"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 Setup"}),o.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Run database migration and deploy Edge Functions directly from your browser. A Supabase Personal Access Token is required to authenticate with your project."}),o.jsxs("div",{className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx($e,{htmlFor:"project-id",children:"Supabase Project ID"}),o.jsx(Re,{id:"project-id",value:g,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($e,{htmlFor:"access-token",children:"Access Token"}),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(El,{className:"h-3 w-3"})]})]}),o.jsx(Re,{id:"access-token",type:"password",placeholder:"sbp_...",value:h,onChange:b=>m(b.target.value),disabled:a}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"This token is used only for this migration and is not stored."})]}),o.jsx(Z,{onClick:v,disabled:a||!h,className:"w-full",children:a?o.jsxs(o.Fragment,{children:[o.jsx(Nt,{className:"mr-2 h-4 w-4 animate-spin"}),"Running Setup..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Ju,{className:"mr-2 h-4 w-4"}),"Start Setup"]})})]})]}),o.jsxs("div",{className:"rounded-lg border bg-black text-white font-mono text-xs p-4 h-64 overflow-y-auto",children:[u.length===0?o.jsx("div",{className:"text-gray-500 italic",children:"Waiting to start..."}):u.map((b,w)=>o.jsx("div",{className:"mb-1 whitespace-pre-wrap",children:b},w)),o.jsx("div",{ref:p})]})]}),o.jsxs(Pi,{className:"border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/20",children:[o.jsx(Mi,{className:"h-4 w-4 text-red-700 dark:text-red-600"}),o.jsxs(zi,{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:["Ensure your Access Token has ",o.jsx("code",{children:"read"})," and ",o.jsx("code",{children:"write"})," permissions."]}),o.jsx("li",{children:"Verify that your Supabase Project ID is correct and active."})]})]})]})]}),o.jsx(Fs,{children:o.jsx(Z,{type:"button",variant:"outline",onClick:()=>t(!1),disabled:a,children:"Close"})})]})})}const fU="https://registry.npmjs.org/@realtimex/email-automator/latest",hU=300*1e3,xN="email_automator_last_version_check",vN="email_automator_update_dismissed";function mU(){return"2.22.1"}async function pU(){try{const e=await fetch(fU,{cache:"no-store"});return e.ok?(await e.json()).version||null:(console.warn("[Version Check] Failed to fetch latest version"),null)}catch(e){return console.error("[Version Check] Error fetching latest version:",e),null}}function gU(e,t){if(t==="unknown")return!1;const n=m=>m.replace(/^v/,"").split(".").map(g=>parseInt(g,10)||0),[s,a,l]=n(e),[u,d,h]=n(t);return u>s?!0:u<s?!1:d>a?!0:d<a?!1:h>l}function yU(){try{const e=localStorage.getItem(xN);if(!e)return!0;const t=new Date(e).getTime();return Date.now()-t>hU}catch{return!0}}function xU(){try{localStorage.setItem(xN,new Date().toISOString())}catch(e){console.error("[Version Check] Error saving check timestamp:",e)}}function vU(e=24){try{const t=localStorage.getItem(vN);if(!t)return!1;const n=new Date(t).getTime();return(Date.now()-n)/(1e3*60*60)<e}catch{return!1}}function bU(){try{localStorage.setItem(vN,new Date().toISOString())}catch(e){console.error("[Version Check] Error dismissing update prompt:",e)}}async function wU(){if(!yU())return console.log("[Version Check] Skipping (throttled)"),null;const e=mU(),t=await pU();if(xU(),!t)return console.warn("[Version Check] Could not determine latest version"),null;const n=gU(e,t);return console.log("[Version Check]",{current:e,latest:t,updateAvailable:n}),n?{current:e,latest:t,updateAvailable:!0,updateUrl:"https://github.com/realtimex/email-automator/releases/latest"}:null}function SU(){typeof window<"u"&&window.location.reload(),window.electron?.ipcRenderer&&window.electron.ipcRenderer.send("restart-app")}function _U({versionInfo:e,onDismiss:t}){const[n,s]=S.useState(!0),[a,l]=S.useState(!1);if(!n)return null;const u=()=>{bU(),s(!1),t?.()},d=()=>{l(!0),setTimeout(()=>{SU()},500)},h=()=>{e.updateUrl&&window.open(e.updateUrl,"_blank")};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-blue-500 bg-blue-50 p-4 shadow-lg dark:bg-blue-950/90 dark:border-blue-600",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Gt,{className:"h-5 w-5 flex-shrink-0 text-blue-600 dark:text-blue-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-blue-900 dark:text-blue-100",children:"Update Available"}),o.jsxs(Z,{size:"icon",variant:"ghost",className:"h-5 w-5 -mr-1 -mt-1 text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:u,children:[o.jsx(mn,{className:"h-3 w-3"}),o.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),o.jsxs("p",{className:"text-xs text-blue-800 dark:text-blue-200",children:["Version ",e.latest," is now available (you're on ",e.current,")"]}),o.jsxs("div",{className:"flex gap-2 flex-wrap",children:[o.jsx(Z,{size:"sm",variant:"default",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600",onClick:d,disabled:a,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Gt,{className:"h-3 w-3 mr-1 animate-spin"}),"Updating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Gt,{className:"h-3 w-3 mr-1"}),"Update Now"]})}),e.updateUrl&&o.jsxs(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:h,children:[o.jsx(El,{className:"h-3 w-3 mr-1"}),"What's New"]}),o.jsx(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:u,children:"Later"})]})]})]})})})}function jU(){const{t:e}=tt(),[t,n]=S.useState([]),{isExpanded:s,setIsExpanded:a}=F_(),{state:l,actions:u}=In(),{isSyncing:d}=l,[h,m]=S.useState({});S.useEffect(()=>{p();const w=pt.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},j=>{const k=j.new;k.event_type==="error"&&m(N=>({...N,[k.id]:!0})),n(N=>{const R=[k,...N];return k.details?.is_completion&&s&&setTimeout(()=>{a(!1)},3e3),R.length>100?R.slice(0,100):R})}).subscribe();return()=>{pt.removeChannel(w)}},[s,a]);const p=async()=>{const{data:w}=await pt.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(50);w&&n(w)},g=w=>{m(j=>({...j,[w]:!j[w]}))},v=w=>{if(w.details?.is_completion)return o.jsx(Xu,{className:"w-3 h-3 text-emerald-500"});switch(w.event_type){case"analysis":return o.jsx(Hs,{className:"w-3 h-3 text-purple-500"});case"action":return o.jsx(eo,{className:"w-3 h-3 text-emerald-500"});case"error":return o.jsx(Mi,{className:"w-3 h-3 text-red-500"});default:return o.jsx(Za,{className:"w-3 h-3 text-blue-500"})}},b=w=>new Date(w).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});return s?o.jsxs(Ie,{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(bt,{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(Ju,{className:"w-4 h-4 text-primary"}),o.jsx(Tt,{className:"text-sm font-mono font-bold",children:e("terminal.title")}),o.jsxs("div",{className:me("flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full border font-bold animate-pulse transition-colors duration-500",d?"text-red-600 dark:text-red-400 bg-red-500/10 border-red-500/20":"text-green-600 dark:text-green-400 bg-green-500/10 border-green-500/20"),children:[o.jsx(rC,{className:"w-3 h-3"}),e(d?"terminal.syncing":"terminal.live")]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[d&&o.jsxs(Z,{variant:"destructive",size:"sm",className:"h-7 text-[10px] font-mono font-bold bg-red-600 hover:bg-red-700 animate-in fade-in zoom-in duration-300",onClick:()=>u.stopSync(),children:[o.jsx(KA,{className:"w-3 h-3 mr-1 fill-current"}),e("terminal.stopSync")]}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 text-[10px] font-mono hover:bg-secondary",onClick:()=>n([]),children:e("terminal.clear")}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-secondary",onClick:()=>a(!1),children:o.jsx(QS,{className:"w-4 h-4"})})]})]}),o.jsxs(ft,{className:"flex-1 overflow-y-auto p-4 font-mono text-xs space-y-6 custom-scrollbar",children:[t.length===0&&o.jsx("div",{className:"text-center text-muted-foreground py-20 italic",children:e("terminal.waiting")}),t.map((w,j)=>o.jsxs("div",{className:"relative pl-8 animate-in fade-in slide-in-from-top-2 duration-300",children:[j!==t.length-1&&o.jsx("div",{className:"absolute left-[13px] top-7 bottom-[-24px] w-[1px] bg-border"}),o.jsx("div",{className:me("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",w.event_type==="error"&&"border-red-500/50 bg-red-500/5",w.event_type==="analysis"&&"border-purple-500/50 bg-purple-500/5",w.event_type==="action"&&"border-emerald-500/50 bg-emerald-500/5",w.details?.is_completion&&"border-emerald-500/50 bg-emerald-500/5"),children:v(w)}),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:me("font-bold uppercase tracking-tight text-[10px]",w.event_type==="info"&&"text-muted-foreground",w.event_type==="analysis"&&"text-purple-600 dark:text-purple-400",w.event_type==="action"&&"text-emerald-600 dark:text-emerald-400",w.event_type==="error"&&"text-red-600 dark:text-red-400"),children:w.agent_state}),o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:b(w.created_at)})]}),(w.details?.system_prompt||w.details?._raw_response||w.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:()=>g(w.id),children:[h[w.id]?o.jsx(NC,{className:"w-3 h-3 mr-1"}):o.jsx(XS,{className:"w-3 h-3 mr-1"}),e("terminal.details")]})]}),w.event_type==="analysis"&&w.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:me("px-1.5 py-0.5 rounded text-[9px] font-bold border",w.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:w.details.is_useless?e("terminal.useless"):e("terminal.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:w.details.category})]}),o.jsxs("p",{className:"text-foreground/90 italic leading-relaxed",children:['"',w.details.summary,'"']}),w.details.suggested_actions&&w.details.suggested_actions.length>0&&o.jsx("div",{className:"pt-1 flex items-center gap-2 flex-wrap",children:w.details.suggested_actions.map(k=>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(eo,{className:"w-2.5 h-2.5"}),k]},k))}),w.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: ",w.details.usage.prompt_tokens," (in) + ",w.details.usage.completion_tokens," (out) = ",o.jsx("span",{className:"text-purple-500 font-bold",children:w.details.usage.total_tokens})]})})]}):w.event_type==="action"&&w.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:e("terminal.executionComplete")}),o.jsxs("p",{className:"text-foreground font-medium",children:[w.details.action==="delete"&&e("terminal.action.delete"),w.details.action==="archive"&&e("terminal.action.archive"),w.details.action==="draft"&&e("terminal.action.draft"),w.details.action==="star"&&e("terminal.action.star"),!["delete","archive","draft","star"].includes(w.details.action)&&w.details.action]}),w.details.reason&&o.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 flex items-center gap-1",children:[o.jsx(Za,{className:"w-3 h-3"}),w.details.reason]})]}):w.event_type==="error"&&w.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 w.details.error=="object"?w.details.error.message||JSON.stringify(w.details.error):w.details.error}):w.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(Xu,{className:"w-3.5 h-3.5"}),e("terminal.batchFinished")]}),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:e("terminal.processed")}),o.jsx("p",{className:"text-sm font-bold",children:w.details.total_processed||0})]}),o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:e("terminal.actions")}),o.jsx("p",{className:"text-sm font-bold text-emerald-500",children:(w.details.deleted||0)+(w.details.drafted||0)})]})]}),w.details.errors>0&&o.jsxs("p",{className:"text-[10px] text-red-500 font-bold pt-1 border-t border-emerald-500/10",children:["⚠️ ",w.details.errors," items failed to process."]})]}):o.jsx("p",{className:"text-muted-foreground leading-relaxed",children:w.details?.message||JSON.stringify(w.details)}),h[w.id]&&o.jsxs("div",{className:"mt-2 space-y-3 animate-in fade-in zoom-in-95 duration-200",children:[w.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(ss,{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:w.details.system_prompt})})]}),w.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(ss,{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:w.details.content_preview})})]}),w.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(ss,{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(w.details._raw_response),null,2)})})]}),w.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(ss,{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 w.details.raw_response=="object"?JSON.stringify(w.details.raw_response,null,2):w.details.raw_response})})]})]})]})]},w.id))]})]}):o.jsx("div",{className:"fixed bottom-4 right-4 z-50",children:o.jsxs(Z,{onClick:()=>a(!0),className:"shadow-lg bg-primary text-primary-foreground hover:opacity-90 border border-border",children:[o.jsx(Ju,{className:"w-4 h-4 mr-2"}),e("terminal.liveActivity"),(t.length>0||d)&&o.jsxs("span",{className:"ml-2 flex h-2 w-2 relative",children:[o.jsx("span",{className:me("animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",d?"bg-red-400":"bg-green-400")}),o.jsx("span",{className:me("relative inline-flex rounded-full h-2 w-2",d?"bg-red-500":"bg-green-500")})]})]})})}const py=S.createContext(null),bN=S.forwardRef(({className:e,defaultValue:t,value:n,onValueChange:s,...a},l)=>{const[u,d]=S.useState(t||""),h=n!==void 0?n:u,m=S.useCallback(p=>{s&&s(p),n===void 0&&d(p)},[s,n]);return o.jsx(py.Provider,{value:{value:h,onValueChange:m},children:o.jsx("div",{ref:l,className:e,...a})})});bN.displayName="Tabs";const wN=S.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,className:me("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));wN.displayName="TabsList";const Xp=S.forwardRef(({className:e,value:t,onClick:n,...s},a)=>{const l=S.useContext(py);if(!l)throw new Error("TabsTrigger must be used within Tabs");const u=l.value===t;return o.jsx("button",{ref:a,type:"button",role:"tab","aria-selected":u,"data-state":u?"active":"inactive",className:me("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),onClick:d=>{l.onValueChange(t),n?.(d)},...s})});Xp.displayName="TabsTrigger";const Jp=S.forwardRef(({className:e,value:t,...n},s)=>{const a=S.useContext(py);if(!a)throw new Error("TabsContent must be used within Tabs");return a.value!==t?null:o.jsx("div",{ref:s,role:"tabpanel","data-state":"active",className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...n})});Jp.displayName="TabsContent";const kU=()=>{const[e,t]=S.useState(null),[n,s]=S.useState(!0),a=S.useCallback(async()=>{try{const h=(await De.getLearningMetrics()).data;t(h?{total_classifications:h.total_classifications||0,correct_classifications:h.correct_classifications||0,drafts_generated:h.drafts_generated||0,drafts_edited:h.drafts_edited||0,category_patterns:h.category_patterns||{},vip_senders:h.vip_senders||[]}:{total_classifications:0,correct_classifications:0,drafts_generated:0,drafts_edited:0,category_patterns:{},vip_senders:[]})}catch(d){console.error("Failed to load learning metrics",d)}finally{s(!1)}},[]);if(S.useEffect(()=>{a()},[a]),n)return o.jsxs("div",{className:"p-8 text-center text-muted-foreground flex items-center justify-center gap-2",children:[o.jsx(Hs,{className:"w-5 h-5 animate-pulse text-primary"})," Loading AI DNA..."]});if(!e)return null;const l=e.total_classifications>0?Math.round(e.correct_classifications/e.total_classifications*100):100,u=Math.round(e.drafts_generated*5);return e.drafts_generated>0&&Math.round((e.drafts_generated-e.drafts_edited)/e.drafts_generated*100),o.jsxs("div",{className:"space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[o.jsxs(Ie,{children:[o.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Tt,{className:"text-sm font-medium",children:"AI Accuracy"}),o.jsx(Hs,{className:"h-4 w-4 text-primary"})]}),o.jsxs(ft,{children:[o.jsxs("div",{className:"text-2xl font-bold",children:[l,"%"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Classification confidence"}),o.jsx(my,{value:l,className:"mt-3 h-2"})]})]}),o.jsxs(Ie,{children:[o.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Tt,{className:"text-sm font-medium",children:"Time Saved"}),o.jsx(oR,{className:"h-4 w-4 text-green-500"})]}),o.jsxs(ft,{children:[o.jsxs("div",{className:"text-2xl font-bold",children:[u,"m"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Est. minutes saved drafting"})]})]}),o.jsxs(Ie,{children:[o.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Tt,{className:"text-sm font-medium",children:"Learned Patterns"}),o.jsx(yg,{className:"h-4 w-4 text-blue-500"})]}),o.jsxs(ft,{children:[o.jsx("div",{className:"text-2xl font-bold",children:Object.keys(e.category_patterns).length}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Domain rules learned"})]})]}),o.jsxs(Ie,{children:[o.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Tt,{className:"text-sm font-medium",children:"VIP Network"}),o.jsx(np,{className:"h-4 w-4 text-yellow-500"})]}),o.jsxs(ft,{children:[o.jsx("div",{className:"text-2xl font-bold",children:e.vip_senders.length}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"High-priority contacts"})]})]})]}),o.jsxs(bN,{defaultValue:"patterns",className:"w-full",children:[o.jsxs(wN,{children:[o.jsx(Xp,{value:"patterns",children:"Domain Patterns"}),o.jsx(Xp,{value:"vips",children:"VIP Senders"})]}),o.jsx(Jp,{value:"patterns",className:"space-y-4 pt-4",children:o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsx(Tt,{className:"text-lg",children:"Learned Categorization Rules"}),o.jsx(Mn,{children:"The AI automatically learns to classify emails from these domains based on your corrections."})]}),o.jsx(ft,{children:o.jsx("div",{className:"space-y-4",children:Object.entries(e.category_patterns).length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground border border-dashed rounded-lg bg-secondary/10",children:[o.jsx(eo,{className:"h-10 w-10 mb-4 opacity-50"}),o.jsx("p",{children:"No patterns learned yet."}),o.jsx("p",{className:"text-xs mt-1",children:"Correct some email categories in the Dashboard to teach the AI!"})]}):o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Object.entries(e.category_patterns).map(([d,h])=>o.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),o.jsx("span",{className:"font-mono text-sm",children:d})]}),o.jsx(jl,{variant:"secondary",className:"capitalize",children:h})]},d))})})})]})}),o.jsx(Jp,{value:"vips",className:"pt-4",children:o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsx(Tt,{className:"text-lg",children:"Identified VIP Senders"}),o.jsx(Mn,{children:"Contacts that are automatically flagged as High Priority."})]}),o.jsx(ft,{children:o.jsx("div",{className:"space-y-4",children:e.vip_senders.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground border border-dashed rounded-lg bg-secondary/10",children:[o.jsx(fR,{className:"h-10 w-10 mb-4 opacity-50"}),o.jsx("p",{children:"No VIPs identified yet."}),o.jsx("p",{className:"text-xs mt-1",children:"Interacting frequently with contacts will elevate them to VIP status."})]}):o.jsx("div",{className:"flex flex-wrap gap-2",children:e.vip_senders.map(d=>o.jsxs(jl,{variant:"outline",className:"pl-1 pr-3 py-1.5 text-sm flex items-center gap-2 bg-secondary/20",children:[o.jsx("div",{className:"w-5 h-5 rounded-full bg-yellow-500/10 flex items-center justify-center",children:o.jsx(np,{className:"w-3 h-3 text-yellow-500 fill-yellow-500"})}),d]},d))})})})]})})]})]})},SN=S.forwardRef(({className:e,...t},n)=>o.jsx("span",{ref:n,className:me("absolute h-px w-px overflow-hidden whitespace-nowrap border-0 p-0","[clip:rect(0,0,0,0)]",e),...t}));SN.displayName="VisuallyHidden";function NU(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const TU=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,EU=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,CU={};function eS(e,t){return(CU.jsx?EU:TU).test(e)}const AU=/[ \t\n\f\r]/g;function RU(e){return typeof e=="object"?e.type==="text"?tS(e.value):!1:tS(e)}function tS(e){return e.replace(AU,"")===""}class ec{constructor(t,n,s){this.normal=n,this.property=t,s&&(this.space=s)}}ec.prototype.normal={};ec.prototype.property={};ec.prototype.space=void 0;function _N(e,t){const n={},s={};for(const a of e)Object.assign(n,a.property),Object.assign(s,a.normal);return new ec(n,s,t)}function Qp(e){return e.toLowerCase()}class _n{constructor(t,n){this.attribute=n,this.property=t}}_n.prototype.attribute="";_n.prototype.booleanish=!1;_n.prototype.boolean=!1;_n.prototype.commaOrSpaceSeparated=!1;_n.prototype.commaSeparated=!1;_n.prototype.defined=!1;_n.prototype.mustUseProperty=!1;_n.prototype.number=!1;_n.prototype.overloadedBoolean=!1;_n.prototype.property="";_n.prototype.spaceSeparated=!1;_n.prototype.space=void 0;let OU=0;const ze=Bi(),Lt=Bi(),Zp=Bi(),le=Bi(),dt=Bi(),Qa=Bi(),Dn=Bi();function Bi(){return 2**++OU}const eg=Object.freeze(Object.defineProperty({__proto__:null,boolean:ze,booleanish:Lt,commaOrSpaceSeparated:Dn,commaSeparated:Qa,number:le,overloadedBoolean:Zp,spaceSeparated:dt},Symbol.toStringTag,{value:"Module"})),Im=Object.keys(eg);class gy extends _n{constructor(t,n,s,a){let l=-1;if(super(t,n),nS(this,"space",a),typeof s=="number")for(;++l<Im.length;){const u=Im[l];nS(this,Im[l],(s&eg[u])===eg[u])}}}gy.prototype.defined=!0;function nS(e,t,n){n&&(e[t]=n)}function uo(e){const t={},n={};for(const[s,a]of Object.entries(e.properties)){const l=new gy(s,e.transform(e.attributes||{},s),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(l.mustUseProperty=!0),t[s]=l,n[Qp(s)]=s,n[Qp(l.attribute)]=s}return new ec(t,n,e.space)}const jN=uo({properties:{ariaActiveDescendant:null,ariaAtomic:Lt,ariaAutoComplete:null,ariaBusy:Lt,ariaChecked:Lt,ariaColCount:le,ariaColIndex:le,ariaColSpan:le,ariaControls:dt,ariaCurrent:null,ariaDescribedBy:dt,ariaDetails:null,ariaDisabled:Lt,ariaDropEffect:dt,ariaErrorMessage:null,ariaExpanded:Lt,ariaFlowTo:dt,ariaGrabbed:Lt,ariaHasPopup:null,ariaHidden:Lt,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:dt,ariaLevel:le,ariaLive:null,ariaModal:Lt,ariaMultiLine:Lt,ariaMultiSelectable:Lt,ariaOrientation:null,ariaOwns:dt,ariaPlaceholder:null,ariaPosInSet:le,ariaPressed:Lt,ariaReadOnly:Lt,ariaRelevant:null,ariaRequired:Lt,ariaRoleDescription:dt,ariaRowCount:le,ariaRowIndex:le,ariaRowSpan:le,ariaSelected:Lt,ariaSetSize:le,ariaSort:null,ariaValueMax:le,ariaValueMin:le,ariaValueNow:le,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function kN(e,t){return t in e?e[t]:t}function NN(e,t){return kN(e,t.toLowerCase())}const DU=uo({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Qa,acceptCharset:dt,accessKey:dt,action:null,allow:null,allowFullScreen:ze,allowPaymentRequest:ze,allowUserMedia:ze,alt:null,as:null,async:ze,autoCapitalize:null,autoComplete:dt,autoFocus:ze,autoPlay:ze,blocking:dt,capture:null,charSet:null,checked:ze,cite:null,className:dt,cols:le,colSpan:null,content:null,contentEditable:Lt,controls:ze,controlsList:dt,coords:le|Qa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ze,defer:ze,dir:null,dirName:null,disabled:ze,download:Zp,draggable:Lt,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ze,formTarget:null,headers:dt,height:le,hidden:Zp,high:le,href:null,hrefLang:null,htmlFor:dt,httpEquiv:dt,id:null,imageSizes:null,imageSrcSet:null,inert:ze,inputMode:null,integrity:null,is:null,isMap:ze,itemId:null,itemProp:dt,itemRef:dt,itemScope:ze,itemType:dt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ze,low:le,manifest:null,max:null,maxLength:le,media:null,method:null,min:null,minLength:le,multiple:ze,muted:ze,name:null,nonce:null,noModule:ze,noValidate:ze,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:ze,optimum:le,pattern:null,ping:dt,placeholder:null,playsInline:ze,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ze,referrerPolicy:null,rel:dt,required:ze,reversed:ze,rows:le,rowSpan:le,sandbox:dt,scope:null,scoped:ze,seamless:ze,selected:ze,shadowRootClonable:ze,shadowRootDelegatesFocus:ze,shadowRootMode:null,shape:null,size:le,sizes:null,slot:null,span:le,spellCheck:Lt,src:null,srcDoc:null,srcLang:null,srcSet:null,start:le,step:null,style:null,tabIndex:le,target:null,title:null,translate:null,type:null,typeMustMatch:ze,useMap:null,value:Lt,width:le,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:dt,axis:null,background:null,bgColor:null,border:le,borderColor:null,bottomMargin:le,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ze,declare:ze,event:null,face:null,frame:null,frameBorder:null,hSpace:le,leftMargin:le,link:null,longDesc:null,lowSrc:null,marginHeight:le,marginWidth:le,noResize:ze,noHref:ze,noShade:ze,noWrap:ze,object:null,profile:null,prompt:null,rev:null,rightMargin:le,rules:null,scheme:null,scrolling:Lt,standby:null,summary:null,text:null,topMargin:le,valueType:null,version:null,vAlign:null,vLink:null,vSpace:le,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ze,disableRemotePlayback:ze,prefix:null,property:null,results:le,security:null,unselectable:null},space:"html",transform:NN}),MU=uo({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Dn,accentHeight:le,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:le,amplitude:le,arabicForm:null,ascent:le,attributeName:null,attributeType:null,azimuth:le,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:le,by:null,calcMode:null,capHeight:le,className:dt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:le,diffuseConstant:le,direction:null,display:null,dur:null,divisor:le,dominantBaseline:null,download:ze,dx:null,dy:null,edgeMode:null,editable:null,elevation:le,enableBackground:null,end:null,event:null,exponent:le,externalResourcesRequired:null,fill:null,fillOpacity:le,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Qa,g2:Qa,glyphName:Qa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:le,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:le,horizOriginX:le,horizOriginY:le,id:null,ideographic:le,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:le,k:le,k1:le,k2:le,k3:le,k4:le,kernelMatrix:Dn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:le,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:le,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:le,overlineThickness:le,paintOrder:null,panose1:null,path:null,pathLength:le,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:dt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:le,pointsAtY:le,pointsAtZ:le,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Dn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Dn,rev:Dn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Dn,requiredFeatures:Dn,requiredFonts:Dn,requiredFormats:Dn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:le,specularExponent:le,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:le,strikethroughThickness:le,string:null,stroke:null,strokeDashArray:Dn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:le,strokeOpacity:le,strokeWidth:null,style:null,surfaceScale:le,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Dn,tabIndex:le,tableValues:null,target:null,targetX:le,targetY:le,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Dn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:le,underlineThickness:le,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:le,values:null,vAlphabetic:le,vMathematical:le,vectorEffect:null,vHanging:le,vIdeographic:le,version:null,vertAdvY:le,vertOriginX:le,vertOriginY:le,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:le,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:kN}),TN=uo({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),EN=uo({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:NN}),CN=uo({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),PU={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},zU=/[A-Z]/g,rS=/-[a-z]/g,LU=/^data[-\w.:]+$/i;function IU(e,t){const n=Qp(t);let s=t,a=_n;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&LU.test(t)){if(t.charAt(4)==="-"){const l=t.slice(5).replace(rS,BU);s="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=t.slice(4);if(!rS.test(l)){let u=l.replace(zU,UU);u.charAt(0)!=="-"&&(u="-"+u),t="data"+u}}a=gy}return new a(s,t)}function UU(e){return"-"+e.toLowerCase()}function BU(e){return e.charAt(1).toUpperCase()}const VU=_N([jN,DU,TN,EN,CN],"html"),yy=_N([jN,MU,TN,EN,CN],"svg");function FU(e){return e.join(" ").trim()}var za={},Um,sS;function qU(){if(sS)return Um;sS=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,l=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,u=/^[;\s]*/,d=/^\s+|\s+$/g,h=`
180
+ Trung Le`,value:e.signature||"",onChange:d=>t({signature:d.target.value})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{children:"Common Phrases"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Re,{placeholder:"e.g., Thanks for reaching out",value:n,onChange:d=>s(d.target.value),onKeyDown:d=>d.key==="Enter"&&a()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:a,children:o.jsx(Gs,{className:"h-4 w-4"})})]}),o.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:e.common_phrases?.map((d,h)=>o.jsxs("div",{className:"bg-secondary text-secondary-foreground px-2 py-1 rounded-md text-xs flex items-center gap-1",children:[d,o.jsx(mn,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>l(d)})]},h))})]}),o.jsxs("div",{className:"mt-6 pt-4 border-t",children:[o.jsx($e,{className:"text-muted-foreground mb-2 block",children:"Preview: How your drafts will look"}),o.jsx("div",{className:"bg-muted/30 border rounded-lg p-4 font-mono text-sm whitespace-pre-wrap",children:u()})]})]})}function XI({data:e,updateData:t}){const[n,s]=S.useState(""),[a,l]=S.useState(""),u=()=>{if(n.trim()){const g=e.vip_senders||[];g.includes(n.trim())||t({vip_senders:[...g,n.trim()]}),s("")}},d=g=>{const v=e.vip_senders||[];t({vip_senders:v.filter(b=>b!==g)})},h=()=>{if(a.trim()){let g=a.trim();g.startsWith("@")&&(g=g.substring(1));const v=e.trusted_domains||[];v.includes(g)||t({trusted_domains:[...v,g]}),l("")}},m=g=>{const v=e.trusted_domains||[];t({trusted_domains:v.filter(b=>b!==g)})},p=[{id:"newsletters",label:"Newsletters"},{id:"social_media",label:"Social media"},{id:"marketing",label:"Marketing emails"}];return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"⭐ Who's important to you?"}),o.jsx("p",{className:"text-muted-foreground",children:"We'll prioritize emails from these people and domains."})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(np,{className:"h-4 w-4 text-yellow-500"}),o.jsx($e,{children:"VIPs (Always High Priority)"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Re,{placeholder:"investor@vc.com",value:n,onChange:g=>s(g.target.value),onKeyDown:g=>g.key==="Enter"&&u()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:u,children:o.jsx(Gs,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:[e.vip_senders?.map((g,v)=>o.jsxs("div",{className:"flex items-center justify-between bg-secondary/50 p-2 rounded-md text-sm",children:[o.jsx("span",{children:g}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>d(g),children:o.jsx(mn,{className:"h-3 w-3"})})]},v)),(!e.vip_senders||e.vip_senders.length===0)&&o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No VIPs added yet"})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(vR,{className:"h-4 w-4 text-blue-500"}),o.jsx($e,{children:"Team & Trusted Domains"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Re,{placeholder:"company.com",value:a,onChange:g=>l(g.target.value),onKeyDown:g=>g.key==="Enter"&&h()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:h,children:o.jsx(Gs,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:[e.trusted_domains?.map((g,v)=>o.jsxs("div",{className:"flex items-center justify-between bg-secondary/50 p-2 rounded-md text-sm",children:[o.jsxs("span",{children:["@",g]}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>m(g),children:o.jsx(mn,{className:"h-3 w-3"})})]},v)),(!e.trusted_domains||e.trusted_domains.length===0)&&o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No domains added yet"})]})]})]}),o.jsxs("div",{className:"p-4 bg-muted/30 rounded-lg space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(KS,{className:"h-4 w-4 text-muted-foreground"}),o.jsx($e,{children:"Low Priority (Auto-Archive)"})]}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:p.map(g=>o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",id:g.id,className:"accent-primary h-4 w-4",defaultChecked:!0}),o.jsx("label",{htmlFor:g.id,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:g.label})]},g.id))})]}),o.jsxs("div",{className:"bg-blue-500/10 text-blue-500 text-sm p-4 rounded-lg flex items-start gap-2",children:[o.jsx(gg,{className:"h-4 w-4 mt-0.5 shrink-0"}),o.jsx("p",{children:'Tip: Adding your own company domain (@realtimex.ai) to "Team" ensures internal emails are never missed.'})]})]})}const JI=[{id:"inbox_zero",label:"Inbox Zero Daily",icon:eA},{id:"respond_faster",label:"Respond Faster",icon:sR},{id:"focus",label:"Focus on Important",icon:t_},{id:"reduce_time",label:"Reduce Email Time",icon:Js}],QI=[{id:"legal",label:"Legal documents"},{id:"hr",label:"HR & payroll"},{id:"financial",label:"Financial transactions"},{id:"security",label:"Security alerts"}];function ZI({data:e,updateData:t}){const n=s=>{const a=e.never_automate_categories||[];a.includes(s)?t({never_automate_categories:a.filter(l=>l!==s)}):t({never_automate_categories:[...a,s]})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"🎯 What are your email goals?"}),o.jsx("p",{className:"text-muted-foreground",children:"Let's set up automation that works for your specific targets."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx($e,{children:"Primary Goal"}),o.jsx("div",{className:"grid grid-cols-2 gap-3",children:JI.map(s=>o.jsx(Ie,{className:me("cursor-pointer transition-all hover:bg-accent/50",e.primary_goal===s.id?"border-primary bg-accent":""),onClick:()=>t({primary_goal:s.id}),children:o.jsxs(ft,{className:"flex flex-col items-center justify-center p-4 text-center space-y-2",children:[o.jsx(s.icon,{className:me("h-6 w-6",e.primary_goal===s.id?"text-primary":"text-muted-foreground")}),o.jsx("span",{className:"font-medium text-sm",children:s.label})]})},s.id))})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx($e,{children:"Time Budget"}),o.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.time_budget_minutes||30," minutes / day"]})]}),o.jsx("input",{type:"range",min:"15",max:"120",step:"15",className:"w-full h-2 bg-secondary rounded-lg appearance-none cursor-pointer accent-primary",value:e.time_budget_minutes||30,onChange:s=>t({time_budget_minutes:parseInt(s.target.value)})}),o.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:"15 min"}),o.jsx("span",{children:"1 hour"}),o.jsx("span",{children:"2 hours"})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx($e,{children:"Automation Level"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:!e.automation_level||e.automation_level<=3?"Conservative":e.automation_level<=7?"Balanced":"Aggressive"})]}),o.jsxs("div",{className:"relative pt-6",children:[o.jsxs("div",{className:"absolute top-0 w-full flex justify-between text-xs font-medium text-muted-foreground px-1",children:[o.jsx("span",{children:"Manual"}),o.jsx("span",{children:"Fully Automated"})]}),o.jsx("input",{type:"range",min:"1",max:"10",step:"1",className:"w-full h-2 bg-gradient-to-r from-blue-500/20 to-blue-500 rounded-lg appearance-none cursor-pointer accent-primary",value:e.automation_level||5,onChange:s=>t({automation_level:parseInt(s.target.value)})}),o.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:e.automation_level&&e.automation_level>7?"AI drafts and organizes aggressively. You review key items.":"AI suggests drafts. You maintain full control."})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(BA,{className:"h-4 w-4 text-destructive"}),o.jsx($e,{children:"Never Automate (Safety)"})]}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:QI.map(s=>o.jsxs("div",{className:"flex items-center space-x-2 border p-3 rounded-md bg-background",children:[o.jsx(hy,{id:`safety-${s.id}`,checked:e.never_automate_categories?.includes(s.id),onCheckedChange:()=>n(s.id)}),o.jsx($e,{htmlFor:`safety-${s.id}`,className:"cursor-pointer",children:s.label})]},s.id))})]}),o.jsxs("div",{className:"bg-emerald-500/10 border border-emerald-500/20 text-emerald-600 dark:text-emerald-400 p-4 rounded-lg",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2 font-medium",children:[o.jsx(fg,{className:"h-4 w-4"}),"Expected Results"]}),o.jsxs("ul",{className:"text-sm space-y-1 list-disc list-inside opacity-90",children:[o.jsx("li",{children:"Save ~2 hours per week"}),o.jsx("li",{children:"Respond 50% faster to clients"}),o.jsx("li",{children:"Zero missed important emails"})]})]})]})}const Mu=4;function yN({onComplete:e,onClose:t,initialData:n,className:s}){const{t:a}=tt(),{state:l}=In(),{user:u}=l,[d,h]=S.useState(1),[m,p]=S.useState(!1),[g,v]=S.useState(n||{work_style:"startup",preferred_tone:"professional",preferred_length:"medium",primary_goal:"inbox_zero",vip_senders:[],trusted_domains:[],blocked_domains:[],never_automate_categories:["legal","hr","financial"],automation_level:5,time_budget_minutes:30}),b=()=>{d<Mu?h(T=>T+1):j()},w=()=>{d>1?h(T=>T-1):t&&t()},j=async()=>{if(u){p(!0);try{const{error:T}=await pt.from("user_settings").update({...g,persona_completed:!0,persona_completed_at:new Date().toISOString()}).eq("user_id",u.id);if(T)throw T;ue.success("Persona saved successfully!"),e()}catch(T){console.error("Failed to save persona:",T),ue.error("Failed to save persona. Please try again.")}finally{p(!1)}}},k=T=>{v(D=>({...D,...T}))},N=()=>{switch(d){case 1:return o.jsx(KI,{data:g,updateData:k});case 2:return o.jsx(WI,{data:g,updateData:k});case 3:return o.jsx(XI,{data:g,updateData:k});case 4:return o.jsx(ZI,{data:g,updateData:k});default:return null}},R=d/Mu*100;return o.jsxs(Ie,{className:me("w-full max-w-2xl mx-auto border-none shadow-none md:border md:shadow-lg",s),children:[o.jsxs(bt,{children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("span",{className:"text-sm text-muted-foreground",children:["Step ",d," of ",Mu]}),t&&o.jsx(Z,{variant:"ghost",size:"sm",onClick:t,children:"Skip"})]}),o.jsx(my,{value:R,className:"h-2"})]}),o.jsx(ft,{className:"py-4 max-h-[60vh] overflow-y-auto",children:N()}),o.jsxs(q_,{className:"flex justify-between",children:[o.jsx(Z,{variant:"outline",onClick:w,disabled:m,children:d===1&&t?"Cancel":"Back"}),o.jsxs(Z,{onClick:b,disabled:m,children:[m&&o.jsx(Nt,{className:"mr-2 h-4 w-4 animate-spin"}),d===Mu?"Complete Setup":"Next"]})]})]})}function eU(){const{t:e}=tt(),{state:t,actions:n}=In(),[s,a]=S.useState(!1),l=t.settings||{persona_completed:!1},u=async()=>{a(!1),await n.fetchSettings()};return s?o.jsx(Rr,{open:!0,onOpenChange:a,children:o.jsxs(Or,{className:"max-w-5xl sm:max-w-5xl h-[80vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs("div",{className:"p-6 pb-0",children:[o.jsx(Dr,{children:e("persona.edit.title")||"Edit Persona"}),o.jsx(Xs,{children:e("persona.edit.desc")||"Update your digital assistant preferences."})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 pt-2",children:o.jsx(yN,{initialData:l,onComplete:u,onClose:()=>a(!1),className:"max-w-none shadow-none border-0 p-0"})})]})}):o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-medium",children:e("persona.title")||"Digital Persona"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("persona.subtitle")||"Manage how your AI assistant represents you."})]}),o.jsxs(Z,{onClick:()=>a(!0),className:"gap-2",children:[o.jsx(ZS,{className:"w-4 h-4"}),e("common.edit")||"Edit Persona"]})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[o.jsxs(Ie,{children:[o.jsx(bt,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(vd,{className:"w-5 h-5 text-primary"}),o.jsx(Tt,{className:"text-base",children:e("persona.identity")||"Identity"})]})}),o.jsx(ft,{className:"space-y-4 text-sm",children:o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Role:"}),o.jsx("span",{className:"font-medium text-right",children:l.role||"Not set"}),o.jsx("span",{className:"text-muted-foreground",children:"Industry:"}),o.jsx("span",{className:"font-medium text-right",children:l.industry||"Not set"}),o.jsx("span",{className:"text-muted-foreground",children:"Style:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.work_style||"Not set"})]})})]}),o.jsxs(Ie,{children:[o.jsx(bt,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(yd,{className:"w-5 h-5 text-indigo-500"}),o.jsx(Tt,{className:"text-base",children:e("persona.communication")||"Communication"})]})}),o.jsx(ft,{className:"space-y-4 text-sm",children:o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Tone:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.preferred_tone||"Professional"}),o.jsx("span",{className:"text-muted-foreground",children:"Length:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.preferred_length||"Medium"}),o.jsx("span",{className:"text-muted-foreground",children:"Languages:"}),o.jsx("div",{className:"flex justify-end gap-1 flex-wrap",children:(l.common_phrases?.length||0)>0?o.jsx(jl,{variant:"secondary",className:"text-xs",children:"Custom Phrases Active"}):o.jsx("span",{className:"text-muted-foreground italic",children:"None"})})]})})]}),o.jsxs(Ie,{children:[o.jsx(bt,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(t_,{className:"w-5 h-5 text-emerald-500"}),o.jsx(Tt,{className:"text-base",children:e("persona.automation")||"Automation"})]})}),o.jsxs(ft,{className:"space-y-4 text-sm",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Primary Goal:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.primary_goal?.replace("_"," ")||"Inbox Zero"}),o.jsx("span",{className:"text-muted-foreground",children:"Auto Level:"}),o.jsx("div",{className:"flex items-center justify-end gap-2",children:o.jsxs("span",{className:"font-medium",children:[l.automation_level||5,"/10"]})})]}),(l.never_automate_categories?.length||0)>0&&o.jsxs("div",{className:"pt-2",children:[o.jsx("span",{className:"text-xs text-muted-foreground block mb-1",children:"Never Automate:"}),o.jsx("div",{className:"flex flex-wrap gap-1",children:l.never_automate_categories?.map(d=>o.jsx(jl,{variant:"outline",className:"text-xs py-0 h-5 bg-background",children:d},d))})]})]})]}),o.jsxs(Ie,{children:[o.jsx(bt,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(JS,{className:"w-5 h-5 text-sky-500"}),o.jsx(Tt,{className:"text-base",children:e("persona.network")||"Network"})]})}),o.jsxs(ft,{className:"space-y-4 text-sm",children:[o.jsxs("div",{children:[o.jsxs("span",{className:"text-xs text-muted-foreground block mb-2",children:["VIP Senders (",l.vip_senders?.length||0,")"]}),o.jsxs("div",{className:"flex flex-wrap gap-1 max-h-[60px] overflow-hidden",children:[l.vip_senders?.slice(0,3).map(d=>o.jsx(jl,{variant:"secondary",className:"text-xs py-0 h-5 truncate max-w-[150px]",children:d},d)),(l.vip_senders?.length||0)>3&&o.jsxs("span",{className:"text-xs text-muted-foreground flex items-center",children:["+",l.vip_senders.length-3," more"]})]})]}),o.jsx("div",{className:"pt-2 border-t mt-2",children:o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-muted-foreground",children:"Trusted Domains:"}),o.jsx("span",{className:"font-medium",children:l.trusted_domains?.length||0})]})})]})]})]})]})}function tU(){const{t:e}=tt(),[t,n]=S.useState("profile"),{state:s,actions:a}=In();S.useEffect(()=>{a.fetchProfile()},[]);const l=[{id:"profile",label:e("account.profile"),icon:vd},{id:"persona",label:e("persona.title")||"Persona",icon:mR},{id:"security",label:e("account.security"),icon:xg},{id:"database",label:e("account.database"),icon:Ka}];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:e("account.title")}),o.jsx("p",{className:"text-muted-foreground",children:e("account.subtitle")})]}),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:l.map(u=>{const d=u.icon,h=t===u.id;return o.jsxs("button",{onClick:()=>n(u.id),className:`w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${h?"bg-primary text-primary-foreground":"hover:bg-secondary text-muted-foreground"}`,children:[o.jsx(d,{className:"w-4 h-4"}),u.label]},u.id)})}),o.jsxs("div",{className:"mt-auto space-y-1",children:[o.jsxs("button",{onClick:async()=>{await pt.auth.signOut(),g5(),ue.success(e("account.logoutSuccess")),window.location.reload()},className:"w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors hover:bg-destructive/10 text-destructive",children:[o.jsx(dA,{className:"w-4 h-4"}),e("account.logout")]}),o.jsxs("div",{className:"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:e("account.version")}),o.jsxs("p",{className:"text-xs font-mono text-muted-foreground/70",children:["v","2.22.2"]})]})]})]}),o.jsxs("div",{className:"flex-1 space-y-6",children:[t==="profile"&&o.jsx(nU,{}),t==="persona"&&o.jsx(eU,{}),t==="security"&&o.jsx(rU,{}),t==="database"&&o.jsx(sU,{})]})]})]})}function nU(){const{t:e}=tt(),{state:t,actions:n}=In(),[s,a]=S.useState(""),[l,u]=S.useState(""),[d,h]=S.useState(!1),[m,p]=S.useState(!1),[g,v]=S.useState(Tr.isEnabled());S.useEffect(()=>{t.profile&&(a(t.profile.first_name||""),u(t.profile.last_name||""))},[t.profile]);const b=()=>{const k=!g;Tr.setEnabled(k),v(k),k?(Tr.playSuccess(),ue.success(e("account.profile.soundsEnabled"))):ue.info(e("account.profile.soundsDisabled"))},w=async()=>{h(!0);const k=await n.updateProfile({first_name:s,last_name:l});h(!1),k&&ue.success(e("account.profile.updated"))},j=async k=>{const N=k.target.files?.[0];if(!(!N||!t.user)){p(!0);try{const R=N.name.split(".").pop(),T=`${t.user.id}/avatar.${R}`,{data:D,error:U}=await pt.storage.from("avatars").upload(T,N,{upsert:!0});if(U)throw U;const{data:{publicUrl:M}}=pt.storage.from("avatars").getPublicUrl(T);await n.updateProfile({avatar_url:M}),ue.success(e("account.profile.avatarUpdated"))}catch(R){console.error("Avatar upload error:",R),ue.error(e("account.profile.avatarError"))}finally{p(!1)}}};return o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsx(Tt,{children:e("account.profile.title")}),o.jsx(Mn,{children:e("account.profile.desc")})]}),o.jsxs(ft,{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:t.profile?.avatar_url?o.jsx("img",{src:t.profile.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):o.jsx(vd,{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(xC,{className:"w-6 h-6 text-white"}),o.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:j,disabled:m})]}),m&&o.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 rounded-full",children:o.jsx(vt,{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($e,{htmlFor:"first-name",children:e("account.profile.firstName")}),o.jsx(Re,{id:"first-name",value:s,onChange:k=>a(k.target.value),placeholder:e("account.profile.firstNamePlaceholder")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"last-name",children:e("account.profile.lastName")}),o.jsx(Re,{id:"last-name",value:l,onChange:k=>u(k.target.value),placeholder:e("account.profile.lastNamePlaceholder")})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"email",children:e("account.profile.email")}),o.jsx(Re,{id:"email",value:t.profile?.email||"",disabled:!0,className:"bg-secondary/50"}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:e("account.profile.emailHelp")})]})]})]}),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:e("account.profile.sounds")}),o.jsx("p",{className:"text-xs text-muted-foreground",children:e("account.profile.soundsHelp")})]}),o.jsxs(Z,{variant:g?"default":"outline",size:"sm",onClick:b,className:"gap-2",children:[g?o.jsx(Al,{className:"w-4 h-4"}):o.jsx(vg,{className:"w-4 h-4"}),e(g?"common.enabled":"common.disabled")]})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:w,disabled:d,children:[d?o.jsx(vt,{size:"sm",className:"mr-2"}):o.jsx(OA,{className:"w-4 h-4 mr-2"}),e("common.saveChanges")]})})]})]})}function rU(){const{t:e}=tt(),[t,n]=S.useState(""),[s,a]=S.useState(""),[l,u]=S.useState(!1),d=async()=>{if(!t){ue.error(e("account.security.enterPassword"));return}if(t!==s){ue.error(e("account.security.passwordsMismatch"));return}if(t.length<6){ue.error(e("account.security.passwordTooShort"));return}u(!0);try{const{api:h}=await Ni(async()=>{const{api:p}=await Promise.resolve().then(()=>o5);return{api:p}},void 0),m=await h.changePassword(t);m.success?(ue.success(e("account.security.passwordChanged")),n(""),a("")):ue.error(m.error?.message||"Failed to change password")}catch{ue.error(e("common.errorOccurred"))}finally{u(!1)}};return o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsx(Tt,{children:e("account.security.title")}),o.jsx(Mn,{children:e("account.security.desc")})]}),o.jsxs(ft,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"new-password",children:e("account.security.newPassword")}),o.jsx(Re,{id:"new-password",type:"password",value:t,onChange:h=>n(h.target.value),placeholder:"••••••••"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx($e,{htmlFor:"confirm-password",children:e("account.security.confirmPassword")}),o.jsx(Re,{id:"confirm-password",type:"password",value:s,onChange:h=>a(h.target.value),placeholder:"••••••••"})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:d,disabled:l,children:[l?o.jsx(vt,{size:"sm",className:"mr-2"}):o.jsx(pg,{className:"w-4 h-4 mr-2"}),e("account.security.updatePassword")]})})]})]})}function sU(){const{t:e}=tt(),[t,n]=S.useState(!1),[s,a]=S.useState(null),l=ao(),u=s5();S.useEffect(()=>{l&&ly(pt).then(a)},[]);const d=()=>{confirm(e("account.database.clearConfirm"))&&(n5(),window.location.reload())};return o.jsxs(o.Fragment,{children:[o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsxs(Tt,{className:"flex items-center gap-2",children:[o.jsx(Ka,{className:"w-5 h-5 text-primary"}),e("account.database.title")]}),o.jsx(Mn,{children:e("account.database.desc")})]}),o.jsx(ft,{className:"space-y-6",children:l?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(Xu,{className:"w-6 h-6 text-emerald-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("p",{className:"font-semibold text-emerald-700 dark:text-emerald-400",children:e("account.database.connected")}),s?.latestMigrationTimestamp&&o.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-600 px-1.5 py-0.5 rounded border border-emerald-500/20",title:"Database Schema Version",children:["Schema ",s.latestMigrationTimestamp]})]}),o.jsx("p",{className:"text-sm font-mono break-all opacity-80",children:l.url})]})]}),u==="env"&&o.jsxs(Pi,{className:"bg-amber-500/5 border-amber-500/20",children:[o.jsx(Cl,{className:"h-4 w-4 text-amber-500"}),o.jsx(zi,{className:"text-amber-700 dark:text-amber-400 text-xs",children:e("account.database.envAlert")})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[o.jsxs(Z,{variant:"outline",onClick:()=>n(!0),className:"w-full",children:[o.jsx(Cl,{className:"w-4 h-4 mr-2"}),e("account.database.changeConnection")]}),u==="ui"&&o.jsxs(Z,{variant:"outline",onClick:d,className:"w-full text-destructive hover:bg-destructive/10",children:[o.jsx(xd,{className:"w-4 h-4 mr-2"}),e("account.database.clearConfig")]})]}),o.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[o.jsx($e,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:e("account.database.anonKey")}),o.jsxs("div",{className:"p-2 bg-secondary/50 rounded-lg font-mono text-xs break-all",children:[l.anonKey.substring(0,20),"...",l.anonKey.substring(l.anonKey.length-10)]})]})]}):o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center space-y-4",children:[o.jsx(DC,{className:"w-12 h-12 text-destructive opacity-20"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-medium",children:e("account.database.noConnection")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("account.database.configureHelp")})]}),o.jsxs(Z,{onClick:()=>n(!0),children:[o.jsx(Ka,{className:"w-4 h-4 mr-2"}),e("account.database.setup")]})]})})]}),o.jsx(Uk,{open:t,onComplete:()=>n(!1),canClose:!0})]})}function iU(){const{t:e}=tt();return o.jsx("span",{className:"inline-flex items-center text-xs px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-950/70 text-blue-700 dark:text-blue-200 border border-blue-200 dark:border-blue-700 shrink-0 font-medium",children:e("autopilot.badge")})}function Z1({rules:e,onToggleRule:t,onEditRule:n,onDeleteRule:s}){const{t:a}=tt(),l={email_organization:{label:a("autopilot.category.email_organization.label"),icon:Cr,emoji:"📧",description:a("autopilot.category.email_organization.desc")},priority_alerts:{label:a("autopilot.category.priority_alerts.label"),icon:mr,emoji:"🚨",description:a("autopilot.category.priority_alerts.desc")},development:{label:a("autopilot.category.development.label"),icon:ss,emoji:"💻",description:a("autopilot.category.development.desc")},sales_business:{label:a("autopilot.category.sales_business.label"),icon:YS,emoji:"💼",description:a("autopilot.category.sales_business.desc")},operations:{label:a("autopilot.category.operations.label"),icon:Cl,emoji:"⚙️",description:a("autopilot.category.operations.desc")}},u=e.reduce((m,p)=>{const g=p.category||"email_organization";return m[g]||(m[g]=[]),m[g].push(p),m},{}),d=m=>{const p=m.filter(v=>v.is_enabled).length,g=m.length;return{enabled:p,total:g}},h=m=>!m||m.length===0?"":m.map(p=>p.startsWith("label:")?`label:${p.substring(6)}`:p).join(" + ");return o.jsx("div",{className:"space-y-8",children:Object.entries(l).map(([m,p])=>{const g=u[m]||[];if(g.length===0)return null;const v=d(g);return o.jsxs("div",{className:"space-y-3",children:[o.jsx("div",{className:"flex items-center justify-between",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg bg-secondary/50 flex items-center justify-center text-primary",children:o.jsx(p.icon,{className:"w-5 h-5"})}),o.jsxs("div",{children:[o.jsxs("h3",{className:"font-semibold text-base flex items-center gap-2",children:[p.label,o.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:a("autopilot.enabledCount").replace("{enabled}",v.enabled.toString()).replace("{total}",v.total.toString())})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:p.description})]})]})}),o.jsx("div",{className:"space-y-1",children:g.map(b=>o.jsxs("div",{className:"flex items-center justify-between py-3 px-4 rounded-lg hover:bg-secondary/30 transition-colors",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h4",{className:"font-medium text-sm truncate",children:b.name}),b.is_system_managed&&o.jsx(iU,{})]}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[b.intent&&o.jsx("p",{className:"text-xs text-muted-foreground truncate",children:b.intent}),b.actions&&b.actions.length>0&&o.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:["→ ",h(b.actions)]})]})]}),o.jsxs("div",{className:"flex items-center gap-2 ml-4 shrink-0",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(b.id),title:a("autopilot.editRuleTooltip"),children:o.jsx(ZS,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs(Z,{variant:b.is_enabled?"default":"outline",size:"sm",onClick:()=>t(b.id,!b.is_enabled),className:"h-8 px-3",children:[o.jsx(tp,{className:"w-4 h-4 mr-1"}),b.is_enabled?a("common.on"):a("common.off")]}),!b.is_system_managed&&s&&o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive",onClick:()=>s(b.id),title:a("autopilot.deleteRuleTooltip"),children:o.jsx(xd,{className:"w-4 h-4"})})]})]},b.id))})]},m)})})}function aU({open:e,rule:t,onClose:n,onSave:s,onFileUpload:a,onRemoveAttachment:l}){const{t:u}=tt(),[d,h]=S.useState(!1),[m,p]=S.useState(!1),[g,v]=S.useState(""),[b,w]=S.useState(""),[j,k]=S.useState(""),[N,R]=S.useState("category"),[T,D]=S.useState("newsletter"),[U,M]=S.useState(""),[B,P]=S.useState(["archive"]),[H,O]=S.useState(""),[Q,G]=S.useState([]);S.useEffect(()=>{if(t){v(t.name||""),w(t.description||""),k(t.intent||""),P(t.actions||["archive"]),O(t.instructions||""),G(t.attachments||[]);const L=t.condition||{},V=Object.keys(L).filter(q=>q!=="older_than_days");V.length>0&&(R(V[0]),D(L[V[0]])),L.older_than_days&&M(String(L.older_than_days))}else v(""),w(""),k(""),R("category"),D("newsletter"),M(""),P(["archive"]),O(""),G([])},[t,e]);const he=async()=>{if(g.trim()&&B.length!==0){h(!0);try{const L={[N]:T};U&&(L.older_than_days=parseInt(U,10));const V=B.includes("draft"),q={name:g.trim(),description:b.trim()||void 0,intent:j.trim()||void 0,condition:L,actions:B,instructions:V?H:void 0,attachments:V?Q:[],is_enabled:!0};await s(q)&&n()}finally{h(!1)}}},se=async L=>{if(!a)return;const V=L.target.files;if(!(!V||V.length===0)){p(!0);try{const q=await a(V[0]);q&&G(de=>[...de,q])}finally{p(!1),L.target.value=""}}},ae=L=>{G(V=>V.filter(q=>q.path!==L)),l&&l(L)};return o.jsx(Rr,{open:e,onOpenChange:L=>!L&&n(),children:o.jsxs(Or,{className:"sm:max-w-xl max-h-[90vh] flex flex-col p-0",children:[o.jsxs(Ws,{className:"p-6 border-b",children:[o.jsx(Dr,{children:u(t?"autopilot.editDialog.editTitle":"autopilot.editDialog.createTitle")}),o.jsx(Xs,{children:u("autopilot.editDialog.desc")})]}),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:u("autopilot.editDialog.ruleName")}),o.jsx(Re,{placeholder:u("autopilot.editDialog.namePlaceholder"),value:g,onChange:L=>v(L.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.description")}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[60px] text-sm",placeholder:u("autopilot.editDialog.descPlaceholder"),value:b,onChange:L=>w(L.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.descriptionHelp")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.intent")}),o.jsx(Re,{placeholder:u("autopilot.editDialog.intentPlaceholder"),value:j,onChange:L=>k(L.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.intentHelp")})]}),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:u("autopilot.editDialog.conditionField")}),o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:N,onChange:L=>{R(L.target.value),L.target.value==="category"?D("newsletter"):L.target.value==="sentiment"?D("Positive"):L.target.value==="priority"?D("High"):D("")},children:[o.jsxs("optgroup",{label:u("autopilot.editDialog.aiAnalysisGroup"),children:[o.jsx("option",{value:"category",children:u("autopilot.editDialog.category")}),o.jsx("option",{value:"sentiment",children:u("autopilot.editDialog.sentiment")}),o.jsx("option",{value:"priority",children:u("autopilot.editDialog.priority")})]}),o.jsxs("optgroup",{label:u("autopilot.editDialog.metadataGroup"),children:[o.jsx("option",{value:"sender_email",children:u("autopilot.editDialog.senderEmail")}),o.jsx("option",{value:"sender_domain",children:u("autopilot.editDialog.senderDomain")}),o.jsx("option",{value:"sender_contains",children:u("autopilot.editDialog.senderContains")}),o.jsx("option",{value:"subject_contains",children:u("autopilot.editDialog.subjectContains")}),o.jsx("option",{value:"body_contains",children:u("autopilot.editDialog.bodyContains")})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.equalsValue")}),N==="category"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:L=>D(L.target.value),children:[o.jsx("option",{value:"newsletter",children:u("autopilot.editDialog.cat.newsletter")}),o.jsx("option",{value:"news",children:u("autopilot.editDialog.cat.news")}),o.jsx("option",{value:"spam",children:u("autopilot.editDialog.cat.spam")}),o.jsx("option",{value:"promotional",children:u("autopilot.editDialog.cat.promotional")}),o.jsx("option",{value:"transactional",children:u("autopilot.editDialog.cat.transactional")}),o.jsx("option",{value:"social",children:u("autopilot.editDialog.cat.social")}),o.jsx("option",{value:"support",children:u("autopilot.editDialog.cat.support")}),o.jsx("option",{value:"client",children:u("autopilot.editDialog.cat.client")}),o.jsx("option",{value:"internal",children:u("autopilot.editDialog.cat.internal")}),o.jsx("option",{value:"personal",children:u("autopilot.editDialog.cat.personal")}),o.jsx("option",{value:"other",children:u("autopilot.editDialog.cat.other")})]}):N==="sentiment"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:L=>D(L.target.value),children:[o.jsx("option",{value:"Positive",children:u("autopilot.editDialog.sent.positive")}),o.jsx("option",{value:"Neutral",children:u("autopilot.editDialog.sent.neutral")}),o.jsx("option",{value:"Negative",children:u("autopilot.editDialog.sent.negative")})]}):N==="priority"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:L=>D(L.target.value),children:[o.jsx("option",{value:"High",children:u("autopilot.editDialog.prio.high")}),o.jsx("option",{value:"Medium",children:u("autopilot.editDialog.prio.medium")}),o.jsx("option",{value:"Low",children:u("autopilot.editDialog.prio.low")})]}):o.jsx(Re,{placeholder:N==="sender_domain"?"rta.vn":N==="sender_email"?"john@example.com":u("autopilot.editDialog.keywordsPlaceholder"),value:T,onChange:L=>D(L.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(Js,{className:"w-4 h-4"}),u("autopilot.editDialog.olderThan")]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Re,{type:"number",min:"0",placeholder:"0",className:"w-24",value:U,onChange:L=>M(L.target.value)}),o.jsx("span",{className:"text-sm text-muted-foreground",children:u("autopilot.editDialog.days")})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.olderThanHelp")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.performActions")}),o.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:u("autopilot.editDialog.actionsDesc")}),o.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"archive",label:u("autopilot.editDialog.action.archive")},{value:"delete",label:u("autopilot.editDialog.action.delete")},{value:"draft",label:u("autopilot.editDialog.action.draft")},{value:"star",label:u("autopilot.editDialog.action.star")}].map(L=>o.jsxs("label",{className:`flex items-center gap-2 p-2 border rounded-md cursor-pointer transition-colors ${B.includes(L.value)?"bg-primary/10 border-primary":"bg-background hover:bg-secondary/50"}`,children:[o.jsx("input",{type:"checkbox",checked:B.includes(L.value),onChange:V=>{V.target.checked?P([...B,L.value]):P(B.filter(q=>q!==L.value))},className:"rounded border-gray-300"}),o.jsx("span",{className:"text-sm",children:L.label})]},L.value))})]}),B.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:u("autopilot.editDialog.draftInstructions")}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[80px] text-sm",placeholder:u("autopilot.editDialog.draftInstPlaceholder"),value:H,onChange:L=>O(L.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.draftInstHelp")})]}),a&&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(_A,{className:"w-4 h-4"}),u("autopilot.editDialog.attachments")]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[Q.map(L=>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:L.name}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive",onClick:()=>ae(L.path),children:o.jsx(mn,{className:"w-3 h-3"})})]},L.path)),o.jsxs("div",{className:"relative",children:[o.jsx("input",{type:"file",className:"absolute inset-0 opacity-0 cursor-pointer",onChange:se,disabled:m}),o.jsxs(Z,{variant:"outline",size:"sm",className:"w-full border-dashed",disabled:m,children:[m?o.jsx(vt,{size:"sm",className:"mr-2"}):o.jsx(Gs,{className:"w-3 h-3 mr-2"}),u(m?"autopilot.editDialog.uploading":"autopilot.editDialog.addAttachment")]})]})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.attachmentsHelp")})]})]})]}),o.jsxs(Fs,{className:"p-6 border-t bg-secondary/5",children:[o.jsx(Z,{variant:"outline",onClick:n,children:u("common.cancel")}),o.jsxs(Z,{onClick:he,disabled:d||!g.trim()||B.length===0,children:[d?o.jsx(vt,{size:"sm",className:"mr-2"}):t?o.jsx(Ti,{className:"w-4 h-4 mr-2"}):o.jsx(Gs,{className:"w-4 h-4 mr-2"}),u(t?"common.saveChanges":"autopilot.addCustomRule")]})]})]})})}function oU(){const{state:e,actions:t}=In(),{t:n}=tt(),[s,a]=S.useState([]),[l,u]=S.useState(!0),[d,h]=S.useState(null),[m,p]=S.useState(!1),[g,v]=S.useState(null),b=async()=>{u(!0),h(null);try{const P=await De.getRules();if(P.error)throw new Error(typeof P.error=="string"?P.error:P.error.message);a(P.data?.rules||[])}catch(P){h(P instanceof Error?P.message:n("autopilot.loadError")),console.error("Error fetching rules:",P)}finally{u(!1)}};S.useEffect(()=>{b()},[]);const w=async(P,H)=>{try{const O=await De.updateRule(P,{is_enabled:H});if(O.error)throw new Error(typeof O.error=="string"?O.error:O.error.message);a(Q=>Q.map(G=>G.id===P?{...G,is_enabled:H}:G))}catch(O){console.error("Error toggling rule:",O),await b()}},j=P=>{const H=s.find(O=>O.id===P);H&&(v(H),p(!0))},k=async P=>{if(confirm(n("autopilot.deleteConfirm")))try{await t.deleteRule(P)?(ue.success(n("autopilot.ruleDeleted")),a(O=>O.filter(Q=>Q.id!==P))):ue.error(n("autopilot.ruleDeleteFailed"))}catch(H){console.error("Error deleting rule:",H),ue.error(n("autopilot.ruleDeleteError"))}},N=()=>{v(null),p(!0)},R=async P=>{try{let H=!1;return g?H=await t.updateRule(g.id,P):H=await t.createRule(P),H?(ue.success(n(g?"autopilot.ruleUpdated":"autopilot.ruleCreated")),await b(),!0):(ue.error(n(g?"autopilot.ruleUpdateFailed":"autopilot.ruleCreateFailed")),!1)}catch(H){return console.error("Error saving rule:",H),ue.error(n("autopilot.ruleSaveError")),!1}},T=async P=>{try{const H=P.name.split(".").pop(),O=`${Math.random().toString(36).substring(2)}.${H}`,Q=`${e.user.id}/${O}`,{error:G}=await pt.storage.from("rule-attachments").upload(Q,P);if(G)throw G;return ue.success(n("autopilot.fileUploaded")),{name:P.name,path:Q,type:P.type,size:P.size}}catch(H){return console.error("Upload error:",H),ue.error(n("autopilot.fileUploadFailed")),null}},D=()=>{p(!1),v(null)};if(l)return o.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(Gt,{className:"w-8 h-8 animate-spin text-gray-400"}),o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("autopilot.loadingRules")})]})});if(d)return o.jsxs(Pi,{variant:"destructive",children:[o.jsx(mr,{className:"h-4 w-4"}),o.jsxs(zi,{children:[d,o.jsxs(Z,{variant:"outline",size:"sm",onClick:b,className:"ml-4",children:[o.jsx(Gt,{className:"w-4 h-4 mr-2"}),n("autopilot.refresh")]})]})]});const U=s.filter(P=>P.is_system_managed),M=s.filter(P=>!P.is_system_managed),B=U.filter(P=>P.is_enabled).length;return s.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[400px] p-8",children:[o.jsx(Vu,{className:"w-16 h-16 text-gray-300 dark:text-gray-700 mb-4"}),o.jsx("h3",{className:"text-lg font-semibold mb-2",children:n("autopilot.noRulesTitle")}),o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 text-center max-w-md mb-4",children:n("autopilot.noRulesDesc")})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-8",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(Vu,{className:"w-6 h-6 text-blue-500"}),n("autopilot.title")]}),o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:n("autopilot.rulesEnabled").replace("{enabled}",B.toString()).replace("{total}",U.length.toString())})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(Z,{variant:"default",size:"sm",onClick:N,children:[o.jsx(Gs,{className:"w-4 h-4 mr-2"}),n("autopilot.addCustomRule")]}),o.jsxs(Z,{variant:"outline",size:"sm",onClick:b,disabled:l,children:[o.jsx(Gt,{className:`w-4 h-4 mr-2 ${l?"animate-spin":""}`}),n("autopilot.refresh")]})]})]}),U.length>0&&o.jsxs(Pi,{children:[o.jsx(Vu,{className:"h-4 w-4"}),o.jsx(zi,{children:n("autopilot.infoDesc")})]}),U.length>0&&o.jsx(Z1,{rules:U,onToggleRule:w,onEditRule:j,onDeleteRule:k}),M.length>0&&o.jsxs("div",{className:"space-y-4 pt-4 border-t",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-semibold",children:n("autopilot.customRules")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:n("autopilot.customRulesDesc")})]}),o.jsx(Z1,{rules:M,onToggleRule:w,onEditRule:j,onDeleteRule:k})]})]}),o.jsx(aU,{open:m,rule:g,onClose:D,onSave:R,onFileUpload:T})]})}function lU({length:e=6,value:t,onChange:n,onComplete:s,disabled:a=!1,error:l=!1}){const u=S.useRef([]),[d,h]=S.useState(null),m=(v,b)=>{const w=b.replace(/[^0-9]/g,"");if(w.length===0){const N=t.split("");N[v]=" ",t.split("");let R=t.split("");v<R.length&&R.splice(v,1);const T=R.join("");n(T),v>0&&u.current[v-1]?.focus();return}t.split("");const j=[...t];j[v]=w[0],n(j.join("")),v<e-1&&u.current[v+1]?.focus();const k=j.join("");k.length===e&&s&&s(k)},p=(v,b)=>{b.key==="Backspace"&&!t[v]&&v>0||b.key==="ArrowLeft"&&v>0?u.current[v-1]?.focus():b.key==="ArrowRight"&&v<e-1&&u.current[v+1]?.focus()},g=v=>{v.preventDefault();const w=v.clipboardData.getData("text/plain").replace(/[^0-9]/g,"").slice(0,e);n(w);const j=Math.min(w.length,e-1);u.current[j]?.focus(),w.length===e&&s&&s(w)};return o.jsx("div",{className:"flex gap-2 justify-center",children:Array.from({length:e}).map((v,b)=>o.jsx(Re,{ref:w=>{u.current[b]=w},type:"text",inputMode:"numeric",maxLength:1,value:t[b]||"",onChange:w=>m(b,w.target.value),onKeyDown:w=>p(b,w),onPaste:g,onFocus:()=>h(b),onBlur:()=>h(null),disabled:a,className:me("w-10 h-10 sm:w-12 sm:h-12 text-center text-lg font-semibold px-0",l&&"border-destructive focus-visible:ring-destructive",d===b&&"ring-2 ring-ring"),"aria-label":`Digit ${b+1}`},b))})}function cU({onSuccess:e,onConfigure:t,isInitialized:n}){const{t:s}=tt(),[a,l]=S.useState(""),[u,d]=S.useState(""),[h,m]=S.useState(""),[p,g]=S.useState(""),[v,b]=S.useState(!1),[w,j]=S.useState(n===void 0),[k,N]=S.useState(n??!1),[R,T]=S.useState(""),[D,U]=S.useState(!1),[M,B]=S.useState("password"),[P,H]=S.useState("email"),[O,Q]=S.useState(""),[G,he]=S.useState(!1);S.useEffect(()=>{n===void 0?se():he(!n)},[n]);const se=async()=>{try{const{data:V,error:q}=await pt.from("init_state").select("is_initialized");if(q){if(q.code==="42P01"){console.info("[Login] init_state relation missing - fresh database detected."),N(!1),he(!0);return}console.warn("[Login] Init check error:",q),N(!1),he(!0),T(q.message);return}const de=V&&V.length>0&&V[0].is_initialized>0;N(de),he(!de)}catch(V){console.warn("[Login] Init check exception:",V),N(!1),he(!0),T(V.message||"Connection failed")}finally{j(!1)}},ae=async V=>{V.preventDefault(),b(!0),T("");try{if(k){if(M==="password"){const{error:q}=await pt.auth.signInWithPassword({email:a,password:u});if(q)throw q;ue.success("Logged in successfully"),e?.()}else if(P==="email"){const{error:q}=await pt.auth.signInWithOtp({email:a,options:{shouldCreateUser:!1}});if(q)throw q;H("verify"),ue.success("Validation code sent to your email")}}else{const{data:q,error:de}=await pt.functions.invoke("setup",{body:{email:a,password:u,first_name:h,last_name:p}});if(de||!q){if(de?.message?.includes("First user already exists")){ue.info("System already initialized. Please log in."),N(!0);return}throw new Error(de?.message||"Failed to create admin account")}ue.success("Admin account created! Signing you in...");const{error:C}=await pt.auth.signInWithPassword({email:a,password:u});if(C)throw C;N(!0),e?.()}}catch(q){T(q?.message||"Authentication failed"),console.error("[Login] Error:",q)}finally{b(!1)}},L=async()=>{b(!0),T("");try{const{data:V,error:q}=await pt.auth.verifyOtp({email:a,token:O,type:"magiclink"});if(q)throw q;if(!V.session)throw new Error("Failed to create session");ue.success("Logged in successfully"),e?.()}catch(V){T(V?.message||"Invalid code")}finally{b(!1)}};return w?o.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(Nt,{className:"w-10 h-10 animate-spin text-primary"}),o.jsx("p",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground",children:"Initializing Engine..."})]})}):o.jsxs("div",{className:"min-h-screen bg-background flex items-center justify-center p-8 relative overflow-hidden",children:[o.jsxs("div",{className:"absolute top-6 right-6 flex items-center gap-4 z-50",children:[t&&o.jsxs(Z,{variant:"ghost",size:"sm",onClick:t,className:"text-xs font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all",children:[o.jsx(Cl,{className:"w-3.5 h-3.5 mr-2"}),"Configure"]}),o.jsx(v_,{}),o.jsx(iy,{})]}),o.jsxs(rs.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full max-w-md relative z-10",children:[o.jsxs("div",{className:"glass p-10 space-y-8 relative overflow-hidden",children:[o.jsxs("div",{className:"text-center space-y-3",children:[o.jsx("div",{className:"mx-auto w-16 h-16 bg-primary rounded-2xl flex items-center justify-center mb-6",children:o.jsx(cy,{className:"w-10 h-10 text-primary-foreground"})}),o.jsx("h2",{className:"text-3xl font-black italic tracking-tighter uppercase text-foreground",children:s(G?"login.initialize":"login.secureLogin")}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-[0.2em] uppercase",children:G?"Create your primary administrator account":M==="otp"?"Magic link authentication":"Personal Access Key Required"})]}),o.jsxs("form",{onSubmit:ae,className:"space-y-4",children:[o.jsxs(mk,{mode:"wait",children:[G&&o.jsxs(rs.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"First Name"}),o.jsx(Re,{value:h,onChange:V=>m(V.target.value),required:G,placeholder:s("login.firstNamePlaceholder"),className:"bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Last Name"}),o.jsx(Re,{value:p,onChange:V=>g(V.target.value),required:G,placeholder:s("login.lastNamePlaceholder"),className:"bg-background"})]})]},"signup-fields"),M==="password"||P==="email"?o.jsxs(rs.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Email Coordinates"}),o.jsxs("div",{className:"relative",children:[o.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),o.jsx(Re,{type:"email",placeholder:s("login.emailPlaceholder"),value:a,onChange:V=>l(V.target.value),required:!0,className:"pl-10 bg-background",autoComplete:"email",disabled:P==="verify"})]})]},"email-field"):null,M==="password"&&o.jsxs(rs.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Access Password"}),o.jsxs("div",{className:"relative",children:[o.jsx(V0,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),o.jsx(Re,{type:D?"text":"password",placeholder:"••••••••",value:u,onChange:V=>d(V.target.value),required:!0,minLength:6,className:"pl-10 pr-10 bg-background",autoComplete:G?"new-password":"current-password"}),o.jsx("button",{type:"button",onClick:()=>U(!D),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground/30 hover:text-primary transition-colors",children:D?o.jsx(BC,{size:16}):o.jsx(mg,{size:16})})]})]},"password-field"),M==="otp"&&P==="verify"&&o.jsxs(rs.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"space-y-6 py-4",children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(lU,{value:O,onChange:Q,length:6,onComplete:()=>{}})}),o.jsx(Z,{type:"button",variant:"link",className:"w-full text-[10px] font-bold uppercase tracking-widest text-primary/60",onClick:()=>H("email"),children:"Change Coordinates"}),o.jsxs(Z,{type:"button",onClick:L,disabled:v||O.length!==6,className:"w-full h-12 shadow-md",children:[v?o.jsx(Nt,{className:"w-5 h-5 animate-spin mr-2"}):o.jsx(xg,{size:18,className:"mr-2"}),"Verify Access"]})]},"otp-field")]}),R&&o.jsxs(rs.div,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"bg-destructive/10 text-destructive text-[11px] font-bold p-3 rounded-xl border border-destructive/20 flex items-start gap-2",children:[o.jsx(mr,{size:14,className:"mt-0.5 shrink-0"}),o.jsx("p",{children:R})]}),M!=="otp"||P==="email"?o.jsx(Z,{type:"submit",disabled:v||!a||M==="password"&&!u,className:"w-full h-12 shadow-md mt-4",children:v?o.jsx(Nt,{className:"w-5 h-5 animate-spin"}):o.jsxs(o.Fragment,{children:[G?o.jsx(gR,{className:"w-5 h-5 mr-2"}):M==="otp"?o.jsx(Cr,{className:"w-5 h-5 mr-2"}):o.jsx(cA,{className:"w-5 h-5 mr-2"}),s(G?"login.initializeMaster":M==="otp"?"login.sendMagicLink":"login.openDashboard")]})}):null]}),o.jsxs("div",{className:"space-y-4 pt-4 border-t border-border/10",children:[!G&&o.jsx("div",{className:"flex flex-col gap-2",children:M==="password"?o.jsxs("button",{type:"button",onClick:()=>{B("otp"),H("email"),T("")},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-white/5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all rounded-xl",children:[o.jsx(V0,{size:14})," Magic Link Login"]}):o.jsxs("button",{type:"button",onClick:()=>{B("password"),T("")},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-white/5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all rounded-xl",children:[o.jsx(dg,{size:14})," Password Access"]})}),o.jsxs("p",{className:"text-center text-[10px] text-muted-foreground font-bold uppercase tracking-wider",children:[G?"Already have an account?":"Need a new account?"," "," ",o.jsx("button",{onClick:()=>{he(!G),B("password"),T("")},className:"text-primary hover:underline ml-1",children:G?"Login Instead":"Create Account"})]})]})]}),o.jsx("div",{className:"mt-8 text-center",children:o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/30 uppercase tracking-[0.4em]",children:"Powered by RealTimeX Intelligence"})})]})]})}function uU({status:e,onDismiss:t,onLearnMore:n}){const[s,a]=S.useState(!0);if(!s)return null;const l=()=>{gL(),a(!1),t?.()},u=()=>{n?n():(navigator.clipboard.writeText("npx email-automator migrate"),ue.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(Mi,{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:l,children:[o.jsx(mn,{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 (",e.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:u,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:l,children:"Remind Later"})]})]})]})})})}function dU({open:e,onOpenChange:t,status:n}){const s=ao(),[a,l]=S.useState(!1),[u,d]=S.useState([]),[h,m]=S.useState(""),p=S.useRef(null),g=S.useMemo(()=>{const b=s?.url;if(!b)return"";try{return new URL(b).hostname.split(".")[0]||""}catch{return""}},[s?.url]);S.useEffect(()=>{p.current&&p.current.scrollIntoView({behavior:"smooth"})},[u]);const v=async()=>{if(!g){ue.error("Missing Project ID");return}if(!h){ue.error("Provide a Supabase Personal Access Token.");return}l(!0),d(["Initializing migration..."]);try{const b=async N=>{const R=new TextDecoder;let T="",D=null;const U=M=>{const B=M.trim();if(!(!B||!B.startsWith("data: ")))try{const P=B.substring(6),H=JSON.parse(P);H.type==="done"?(H.data==="success"||H.data==="failed")&&(D=H.data==="success"?"success":"failure"):H.data&&d(O=>[...O,H.data])}catch(P){console.error("Failed to parse SSE line:",B,P)}};for(;;){const{done:M,value:B}=await N.read();if(M)break;T+=R.decode(B,{stream:!0});const P=T.split(`
181
+ `);T=P.pop()||"",P.forEach(U)}return T+=R.decode(),T&&U(T),D};d(N=>[...N,"","📦 Database Migration & Edge Functions Deployment"]);const w=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:g,accessToken:h})});if(!w.ok)throw new Error(`Migration failed: ${w.status} ${w.statusText}`);const j=w.body?.getReader();if(!j)throw new Error("No migration response stream received.");if(await b(j)!=="success")throw new Error("Migration did not complete successfully");d(N=>[...N,"","═".repeat(60),"✅ Setup Complete!","","✓ Database schema updated","✓ Edge Functions deployed","","🎉 Your Email Automator is ready to use!","📝 The application will reload automatically...","═".repeat(60)]),setTimeout(()=>{window.location.reload()},3e3)}catch(b){console.error(b),d(w=>[...w,"",`❌ Error: ${b instanceof Error?b.message:String(b)}`]),ue.error("Setup failed. Check logs for details.")}finally{l(!1)}};return o.jsx(Rr,{open:e,onOpenChange:b=>!a&&t(b),children:o.jsxs(Or,{className:"max-h-[90vh] sm:max-w-5xl overflow-y-auto",children:[o.jsxs(Ws,{children:[o.jsxs(Dr,{className:"flex items-center gap-2 text-xl",children:[o.jsx(Mi,{className:"h-6 w-6 text-red-700 dark:text-red-600"}),"Database Setup Required"]}),o.jsxs(Xs,{children:["Your application version (",n.appVersion,") requires database migration and Edge Functions deployment to function correctly."]})]}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs(Pi,{children:[o.jsx(Za,{className:"h-4 w-4"}),o.jsxs(zi,{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 ",n.appVersion]}),o.jsx("li",{children:"Deploys Edge Functions (API endpoints) to your Supabase project"}),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:"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 Setup"}),o.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Run database migration and deploy Edge Functions directly from your browser. A Supabase Personal Access Token is required to authenticate with your project."}),o.jsxs("div",{className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx($e,{htmlFor:"project-id",children:"Supabase Project ID"}),o.jsx(Re,{id:"project-id",value:g,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($e,{htmlFor:"access-token",children:"Access Token"}),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(El,{className:"h-3 w-3"})]})]}),o.jsx(Re,{id:"access-token",type:"password",placeholder:"sbp_...",value:h,onChange:b=>m(b.target.value),disabled:a}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"This token is used only for this migration and is not stored."})]}),o.jsx(Z,{onClick:v,disabled:a||!h,className:"w-full",children:a?o.jsxs(o.Fragment,{children:[o.jsx(Nt,{className:"mr-2 h-4 w-4 animate-spin"}),"Running Setup..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Ju,{className:"mr-2 h-4 w-4"}),"Start Setup"]})})]})]}),o.jsxs("div",{className:"rounded-lg border bg-black text-white font-mono text-xs p-4 h-64 overflow-y-auto",children:[u.length===0?o.jsx("div",{className:"text-gray-500 italic",children:"Waiting to start..."}):u.map((b,w)=>o.jsx("div",{className:"mb-1 whitespace-pre-wrap",children:b},w)),o.jsx("div",{ref:p})]})]}),o.jsxs(Pi,{className:"border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/20",children:[o.jsx(Mi,{className:"h-4 w-4 text-red-700 dark:text-red-600"}),o.jsxs(zi,{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:["Ensure your Access Token has ",o.jsx("code",{children:"read"})," and ",o.jsx("code",{children:"write"})," permissions."]}),o.jsx("li",{children:"Verify that your Supabase Project ID is correct and active."})]})]})]})]}),o.jsx(Fs,{children:o.jsx(Z,{type:"button",variant:"outline",onClick:()=>t(!1),disabled:a,children:"Close"})})]})})}const fU="https://registry.npmjs.org/@realtimex/email-automator/latest",hU=300*1e3,xN="email_automator_last_version_check",vN="email_automator_update_dismissed";function mU(){return"2.22.2"}async function pU(){try{const e=await fetch(fU,{cache:"no-store"});return e.ok?(await e.json()).version||null:(console.warn("[Version Check] Failed to fetch latest version"),null)}catch(e){return console.error("[Version Check] Error fetching latest version:",e),null}}function gU(e,t){if(t==="unknown")return!1;const n=m=>m.replace(/^v/,"").split(".").map(g=>parseInt(g,10)||0),[s,a,l]=n(e),[u,d,h]=n(t);return u>s?!0:u<s?!1:d>a?!0:d<a?!1:h>l}function yU(){try{const e=localStorage.getItem(xN);if(!e)return!0;const t=new Date(e).getTime();return Date.now()-t>hU}catch{return!0}}function xU(){try{localStorage.setItem(xN,new Date().toISOString())}catch(e){console.error("[Version Check] Error saving check timestamp:",e)}}function vU(e=24){try{const t=localStorage.getItem(vN);if(!t)return!1;const n=new Date(t).getTime();return(Date.now()-n)/(1e3*60*60)<e}catch{return!1}}function bU(){try{localStorage.setItem(vN,new Date().toISOString())}catch(e){console.error("[Version Check] Error dismissing update prompt:",e)}}async function wU(){if(!yU())return console.log("[Version Check] Skipping (throttled)"),null;const e=mU(),t=await pU();if(xU(),!t)return console.warn("[Version Check] Could not determine latest version"),null;const n=gU(e,t);return console.log("[Version Check]",{current:e,latest:t,updateAvailable:n}),n?{current:e,latest:t,updateAvailable:!0,updateUrl:"https://github.com/realtimex/email-automator/releases/latest"}:null}function SU(){typeof window<"u"&&window.location.reload(),window.electron?.ipcRenderer&&window.electron.ipcRenderer.send("restart-app")}function _U({versionInfo:e,onDismiss:t}){const[n,s]=S.useState(!0),[a,l]=S.useState(!1);if(!n)return null;const u=()=>{bU(),s(!1),t?.()},d=()=>{l(!0),setTimeout(()=>{SU()},500)},h=()=>{e.updateUrl&&window.open(e.updateUrl,"_blank")};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-blue-500 bg-blue-50 p-4 shadow-lg dark:bg-blue-950/90 dark:border-blue-600",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Gt,{className:"h-5 w-5 flex-shrink-0 text-blue-600 dark:text-blue-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-blue-900 dark:text-blue-100",children:"Update Available"}),o.jsxs(Z,{size:"icon",variant:"ghost",className:"h-5 w-5 -mr-1 -mt-1 text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:u,children:[o.jsx(mn,{className:"h-3 w-3"}),o.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),o.jsxs("p",{className:"text-xs text-blue-800 dark:text-blue-200",children:["Version ",e.latest," is now available (you're on ",e.current,")"]}),o.jsxs("div",{className:"flex gap-2 flex-wrap",children:[o.jsx(Z,{size:"sm",variant:"default",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600",onClick:d,disabled:a,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Gt,{className:"h-3 w-3 mr-1 animate-spin"}),"Updating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Gt,{className:"h-3 w-3 mr-1"}),"Update Now"]})}),e.updateUrl&&o.jsxs(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:h,children:[o.jsx(El,{className:"h-3 w-3 mr-1"}),"What's New"]}),o.jsx(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:u,children:"Later"})]})]})]})})})}function jU(){const{t:e}=tt(),[t,n]=S.useState([]),{isExpanded:s,setIsExpanded:a}=F_(),{state:l,actions:u}=In(),{isSyncing:d}=l,[h,m]=S.useState({});S.useEffect(()=>{p();const w=pt.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},j=>{const k=j.new;k.event_type==="error"&&m(N=>({...N,[k.id]:!0})),n(N=>{const R=[k,...N];return k.details?.is_completion&&s&&setTimeout(()=>{a(!1)},3e3),R.length>100?R.slice(0,100):R})}).subscribe();return()=>{pt.removeChannel(w)}},[s,a]);const p=async()=>{const{data:w}=await pt.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(50);w&&n(w)},g=w=>{m(j=>({...j,[w]:!j[w]}))},v=w=>{if(w.details?.is_completion)return o.jsx(Xu,{className:"w-3 h-3 text-emerald-500"});switch(w.event_type){case"analysis":return o.jsx(Hs,{className:"w-3 h-3 text-purple-500"});case"action":return o.jsx(eo,{className:"w-3 h-3 text-emerald-500"});case"error":return o.jsx(Mi,{className:"w-3 h-3 text-red-500"});default:return o.jsx(Za,{className:"w-3 h-3 text-blue-500"})}},b=w=>new Date(w).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});return s?o.jsxs(Ie,{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(bt,{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(Ju,{className:"w-4 h-4 text-primary"}),o.jsx(Tt,{className:"text-sm font-mono font-bold",children:e("terminal.title")}),o.jsxs("div",{className:me("flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full border font-bold animate-pulse transition-colors duration-500",d?"text-red-600 dark:text-red-400 bg-red-500/10 border-red-500/20":"text-green-600 dark:text-green-400 bg-green-500/10 border-green-500/20"),children:[o.jsx(rC,{className:"w-3 h-3"}),e(d?"terminal.syncing":"terminal.live")]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[d&&o.jsxs(Z,{variant:"destructive",size:"sm",className:"h-7 text-[10px] font-mono font-bold bg-red-600 hover:bg-red-700 animate-in fade-in zoom-in duration-300",onClick:()=>u.stopSync(),children:[o.jsx(KA,{className:"w-3 h-3 mr-1 fill-current"}),e("terminal.stopSync")]}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 text-[10px] font-mono hover:bg-secondary",onClick:()=>n([]),children:e("terminal.clear")}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-secondary",onClick:()=>a(!1),children:o.jsx(QS,{className:"w-4 h-4"})})]})]}),o.jsxs(ft,{className:"flex-1 overflow-y-auto p-4 font-mono text-xs space-y-6 custom-scrollbar",children:[t.length===0&&o.jsx("div",{className:"text-center text-muted-foreground py-20 italic",children:e("terminal.waiting")}),t.map((w,j)=>o.jsxs("div",{className:"relative pl-8 animate-in fade-in slide-in-from-top-2 duration-300",children:[j!==t.length-1&&o.jsx("div",{className:"absolute left-[13px] top-7 bottom-[-24px] w-[1px] bg-border"}),o.jsx("div",{className:me("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",w.event_type==="error"&&"border-red-500/50 bg-red-500/5",w.event_type==="analysis"&&"border-purple-500/50 bg-purple-500/5",w.event_type==="action"&&"border-emerald-500/50 bg-emerald-500/5",w.details?.is_completion&&"border-emerald-500/50 bg-emerald-500/5"),children:v(w)}),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:me("font-bold uppercase tracking-tight text-[10px]",w.event_type==="info"&&"text-muted-foreground",w.event_type==="analysis"&&"text-purple-600 dark:text-purple-400",w.event_type==="action"&&"text-emerald-600 dark:text-emerald-400",w.event_type==="error"&&"text-red-600 dark:text-red-400"),children:w.agent_state}),o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:b(w.created_at)})]}),(w.details?.system_prompt||w.details?._raw_response||w.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:()=>g(w.id),children:[h[w.id]?o.jsx(NC,{className:"w-3 h-3 mr-1"}):o.jsx(XS,{className:"w-3 h-3 mr-1"}),e("terminal.details")]})]}),w.event_type==="analysis"&&w.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:me("px-1.5 py-0.5 rounded text-[9px] font-bold border",w.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:w.details.is_useless?e("terminal.useless"):e("terminal.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:w.details.category})]}),o.jsxs("p",{className:"text-foreground/90 italic leading-relaxed",children:['"',w.details.summary,'"']}),w.details.suggested_actions&&w.details.suggested_actions.length>0&&o.jsx("div",{className:"pt-1 flex items-center gap-2 flex-wrap",children:w.details.suggested_actions.map(k=>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(eo,{className:"w-2.5 h-2.5"}),k]},k))}),w.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: ",w.details.usage.prompt_tokens," (in) + ",w.details.usage.completion_tokens," (out) = ",o.jsx("span",{className:"text-purple-500 font-bold",children:w.details.usage.total_tokens})]})})]}):w.event_type==="action"&&w.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:e("terminal.executionComplete")}),o.jsxs("p",{className:"text-foreground font-medium",children:[w.details.action==="delete"&&e("terminal.action.delete"),w.details.action==="archive"&&e("terminal.action.archive"),w.details.action==="draft"&&e("terminal.action.draft"),w.details.action==="star"&&e("terminal.action.star"),!["delete","archive","draft","star"].includes(w.details.action)&&w.details.action]}),w.details.reason&&o.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 flex items-center gap-1",children:[o.jsx(Za,{className:"w-3 h-3"}),w.details.reason]})]}):w.event_type==="error"&&w.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 w.details.error=="object"?w.details.error.message||JSON.stringify(w.details.error):w.details.error}):w.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(Xu,{className:"w-3.5 h-3.5"}),e("terminal.batchFinished")]}),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:e("terminal.processed")}),o.jsx("p",{className:"text-sm font-bold",children:w.details.total_processed||0})]}),o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:e("terminal.actions")}),o.jsx("p",{className:"text-sm font-bold text-emerald-500",children:(w.details.deleted||0)+(w.details.drafted||0)})]})]}),w.details.errors>0&&o.jsxs("p",{className:"text-[10px] text-red-500 font-bold pt-1 border-t border-emerald-500/10",children:["⚠️ ",w.details.errors," items failed to process."]})]}):o.jsx("p",{className:"text-muted-foreground leading-relaxed",children:w.details?.message||JSON.stringify(w.details)}),h[w.id]&&o.jsxs("div",{className:"mt-2 space-y-3 animate-in fade-in zoom-in-95 duration-200",children:[w.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(ss,{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:w.details.system_prompt})})]}),w.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(ss,{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:w.details.content_preview})})]}),w.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(ss,{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(w.details._raw_response),null,2)})})]}),w.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(ss,{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 w.details.raw_response=="object"?JSON.stringify(w.details.raw_response,null,2):w.details.raw_response})})]})]})]})]},w.id))]})]}):o.jsx("div",{className:"fixed bottom-4 right-4 z-50",children:o.jsxs(Z,{onClick:()=>a(!0),className:"shadow-lg bg-primary text-primary-foreground hover:opacity-90 border border-border",children:[o.jsx(Ju,{className:"w-4 h-4 mr-2"}),e("terminal.liveActivity"),(t.length>0||d)&&o.jsxs("span",{className:"ml-2 flex h-2 w-2 relative",children:[o.jsx("span",{className:me("animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",d?"bg-red-400":"bg-green-400")}),o.jsx("span",{className:me("relative inline-flex rounded-full h-2 w-2",d?"bg-red-500":"bg-green-500")})]})]})})}const py=S.createContext(null),bN=S.forwardRef(({className:e,defaultValue:t,value:n,onValueChange:s,...a},l)=>{const[u,d]=S.useState(t||""),h=n!==void 0?n:u,m=S.useCallback(p=>{s&&s(p),n===void 0&&d(p)},[s,n]);return o.jsx(py.Provider,{value:{value:h,onValueChange:m},children:o.jsx("div",{ref:l,className:e,...a})})});bN.displayName="Tabs";const wN=S.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,className:me("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));wN.displayName="TabsList";const Xp=S.forwardRef(({className:e,value:t,onClick:n,...s},a)=>{const l=S.useContext(py);if(!l)throw new Error("TabsTrigger must be used within Tabs");const u=l.value===t;return o.jsx("button",{ref:a,type:"button",role:"tab","aria-selected":u,"data-state":u?"active":"inactive",className:me("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),onClick:d=>{l.onValueChange(t),n?.(d)},...s})});Xp.displayName="TabsTrigger";const Jp=S.forwardRef(({className:e,value:t,...n},s)=>{const a=S.useContext(py);if(!a)throw new Error("TabsContent must be used within Tabs");return a.value!==t?null:o.jsx("div",{ref:s,role:"tabpanel","data-state":"active",className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...n})});Jp.displayName="TabsContent";const kU=()=>{const[e,t]=S.useState(null),[n,s]=S.useState(!0),a=S.useCallback(async()=>{try{const h=(await De.getLearningMetrics()).data;t(h?{total_classifications:h.total_classifications||0,correct_classifications:h.correct_classifications||0,drafts_generated:h.drafts_generated||0,drafts_edited:h.drafts_edited||0,category_patterns:h.category_patterns||{},vip_senders:h.vip_senders||[]}:{total_classifications:0,correct_classifications:0,drafts_generated:0,drafts_edited:0,category_patterns:{},vip_senders:[]})}catch(d){console.error("Failed to load learning metrics",d)}finally{s(!1)}},[]);if(S.useEffect(()=>{a()},[a]),n)return o.jsxs("div",{className:"p-8 text-center text-muted-foreground flex items-center justify-center gap-2",children:[o.jsx(Hs,{className:"w-5 h-5 animate-pulse text-primary"})," Loading AI DNA..."]});if(!e)return null;const l=e.total_classifications>0?Math.round(e.correct_classifications/e.total_classifications*100):100,u=Math.round(e.drafts_generated*5);return e.drafts_generated>0&&Math.round((e.drafts_generated-e.drafts_edited)/e.drafts_generated*100),o.jsxs("div",{className:"space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[o.jsxs(Ie,{children:[o.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Tt,{className:"text-sm font-medium",children:"AI Accuracy"}),o.jsx(Hs,{className:"h-4 w-4 text-primary"})]}),o.jsxs(ft,{children:[o.jsxs("div",{className:"text-2xl font-bold",children:[l,"%"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Classification confidence"}),o.jsx(my,{value:l,className:"mt-3 h-2"})]})]}),o.jsxs(Ie,{children:[o.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Tt,{className:"text-sm font-medium",children:"Time Saved"}),o.jsx(oR,{className:"h-4 w-4 text-green-500"})]}),o.jsxs(ft,{children:[o.jsxs("div",{className:"text-2xl font-bold",children:[u,"m"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Est. minutes saved drafting"})]})]}),o.jsxs(Ie,{children:[o.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Tt,{className:"text-sm font-medium",children:"Learned Patterns"}),o.jsx(yg,{className:"h-4 w-4 text-blue-500"})]}),o.jsxs(ft,{children:[o.jsx("div",{className:"text-2xl font-bold",children:Object.keys(e.category_patterns).length}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Domain rules learned"})]})]}),o.jsxs(Ie,{children:[o.jsxs(bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Tt,{className:"text-sm font-medium",children:"VIP Network"}),o.jsx(np,{className:"h-4 w-4 text-yellow-500"})]}),o.jsxs(ft,{children:[o.jsx("div",{className:"text-2xl font-bold",children:e.vip_senders.length}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"High-priority contacts"})]})]})]}),o.jsxs(bN,{defaultValue:"patterns",className:"w-full",children:[o.jsxs(wN,{children:[o.jsx(Xp,{value:"patterns",children:"Domain Patterns"}),o.jsx(Xp,{value:"vips",children:"VIP Senders"})]}),o.jsx(Jp,{value:"patterns",className:"space-y-4 pt-4",children:o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsx(Tt,{className:"text-lg",children:"Learned Categorization Rules"}),o.jsx(Mn,{children:"The AI automatically learns to classify emails from these domains based on your corrections."})]}),o.jsx(ft,{children:o.jsx("div",{className:"space-y-4",children:Object.entries(e.category_patterns).length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground border border-dashed rounded-lg bg-secondary/10",children:[o.jsx(eo,{className:"h-10 w-10 mb-4 opacity-50"}),o.jsx("p",{children:"No patterns learned yet."}),o.jsx("p",{className:"text-xs mt-1",children:"Correct some email categories in the Dashboard to teach the AI!"})]}):o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Object.entries(e.category_patterns).map(([d,h])=>o.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),o.jsx("span",{className:"font-mono text-sm",children:d})]}),o.jsx(jl,{variant:"secondary",className:"capitalize",children:h})]},d))})})})]})}),o.jsx(Jp,{value:"vips",className:"pt-4",children:o.jsxs(Ie,{children:[o.jsxs(bt,{children:[o.jsx(Tt,{className:"text-lg",children:"Identified VIP Senders"}),o.jsx(Mn,{children:"Contacts that are automatically flagged as High Priority."})]}),o.jsx(ft,{children:o.jsx("div",{className:"space-y-4",children:e.vip_senders.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground border border-dashed rounded-lg bg-secondary/10",children:[o.jsx(fR,{className:"h-10 w-10 mb-4 opacity-50"}),o.jsx("p",{children:"No VIPs identified yet."}),o.jsx("p",{className:"text-xs mt-1",children:"Interacting frequently with contacts will elevate them to VIP status."})]}):o.jsx("div",{className:"flex flex-wrap gap-2",children:e.vip_senders.map(d=>o.jsxs(jl,{variant:"outline",className:"pl-1 pr-3 py-1.5 text-sm flex items-center gap-2 bg-secondary/20",children:[o.jsx("div",{className:"w-5 h-5 rounded-full bg-yellow-500/10 flex items-center justify-center",children:o.jsx(np,{className:"w-3 h-3 text-yellow-500 fill-yellow-500"})}),d]},d))})})})]})})]})]})},SN=S.forwardRef(({className:e,...t},n)=>o.jsx("span",{ref:n,className:me("absolute h-px w-px overflow-hidden whitespace-nowrap border-0 p-0","[clip:rect(0,0,0,0)]",e),...t}));SN.displayName="VisuallyHidden";function NU(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const TU=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,EU=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,CU={};function eS(e,t){return(CU.jsx?EU:TU).test(e)}const AU=/[ \t\n\f\r]/g;function RU(e){return typeof e=="object"?e.type==="text"?tS(e.value):!1:tS(e)}function tS(e){return e.replace(AU,"")===""}class ec{constructor(t,n,s){this.normal=n,this.property=t,s&&(this.space=s)}}ec.prototype.normal={};ec.prototype.property={};ec.prototype.space=void 0;function _N(e,t){const n={},s={};for(const a of e)Object.assign(n,a.property),Object.assign(s,a.normal);return new ec(n,s,t)}function Qp(e){return e.toLowerCase()}class _n{constructor(t,n){this.attribute=n,this.property=t}}_n.prototype.attribute="";_n.prototype.booleanish=!1;_n.prototype.boolean=!1;_n.prototype.commaOrSpaceSeparated=!1;_n.prototype.commaSeparated=!1;_n.prototype.defined=!1;_n.prototype.mustUseProperty=!1;_n.prototype.number=!1;_n.prototype.overloadedBoolean=!1;_n.prototype.property="";_n.prototype.spaceSeparated=!1;_n.prototype.space=void 0;let OU=0;const ze=Bi(),Lt=Bi(),Zp=Bi(),le=Bi(),dt=Bi(),Qa=Bi(),Dn=Bi();function Bi(){return 2**++OU}const eg=Object.freeze(Object.defineProperty({__proto__:null,boolean:ze,booleanish:Lt,commaOrSpaceSeparated:Dn,commaSeparated:Qa,number:le,overloadedBoolean:Zp,spaceSeparated:dt},Symbol.toStringTag,{value:"Module"})),Im=Object.keys(eg);class gy extends _n{constructor(t,n,s,a){let l=-1;if(super(t,n),nS(this,"space",a),typeof s=="number")for(;++l<Im.length;){const u=Im[l];nS(this,Im[l],(s&eg[u])===eg[u])}}}gy.prototype.defined=!0;function nS(e,t,n){n&&(e[t]=n)}function uo(e){const t={},n={};for(const[s,a]of Object.entries(e.properties)){const l=new gy(s,e.transform(e.attributes||{},s),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(l.mustUseProperty=!0),t[s]=l,n[Qp(s)]=s,n[Qp(l.attribute)]=s}return new ec(t,n,e.space)}const jN=uo({properties:{ariaActiveDescendant:null,ariaAtomic:Lt,ariaAutoComplete:null,ariaBusy:Lt,ariaChecked:Lt,ariaColCount:le,ariaColIndex:le,ariaColSpan:le,ariaControls:dt,ariaCurrent:null,ariaDescribedBy:dt,ariaDetails:null,ariaDisabled:Lt,ariaDropEffect:dt,ariaErrorMessage:null,ariaExpanded:Lt,ariaFlowTo:dt,ariaGrabbed:Lt,ariaHasPopup:null,ariaHidden:Lt,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:dt,ariaLevel:le,ariaLive:null,ariaModal:Lt,ariaMultiLine:Lt,ariaMultiSelectable:Lt,ariaOrientation:null,ariaOwns:dt,ariaPlaceholder:null,ariaPosInSet:le,ariaPressed:Lt,ariaReadOnly:Lt,ariaRelevant:null,ariaRequired:Lt,ariaRoleDescription:dt,ariaRowCount:le,ariaRowIndex:le,ariaRowSpan:le,ariaSelected:Lt,ariaSetSize:le,ariaSort:null,ariaValueMax:le,ariaValueMin:le,ariaValueNow:le,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function kN(e,t){return t in e?e[t]:t}function NN(e,t){return kN(e,t.toLowerCase())}const DU=uo({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Qa,acceptCharset:dt,accessKey:dt,action:null,allow:null,allowFullScreen:ze,allowPaymentRequest:ze,allowUserMedia:ze,alt:null,as:null,async:ze,autoCapitalize:null,autoComplete:dt,autoFocus:ze,autoPlay:ze,blocking:dt,capture:null,charSet:null,checked:ze,cite:null,className:dt,cols:le,colSpan:null,content:null,contentEditable:Lt,controls:ze,controlsList:dt,coords:le|Qa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ze,defer:ze,dir:null,dirName:null,disabled:ze,download:Zp,draggable:Lt,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ze,formTarget:null,headers:dt,height:le,hidden:Zp,high:le,href:null,hrefLang:null,htmlFor:dt,httpEquiv:dt,id:null,imageSizes:null,imageSrcSet:null,inert:ze,inputMode:null,integrity:null,is:null,isMap:ze,itemId:null,itemProp:dt,itemRef:dt,itemScope:ze,itemType:dt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ze,low:le,manifest:null,max:null,maxLength:le,media:null,method:null,min:null,minLength:le,multiple:ze,muted:ze,name:null,nonce:null,noModule:ze,noValidate:ze,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:ze,optimum:le,pattern:null,ping:dt,placeholder:null,playsInline:ze,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ze,referrerPolicy:null,rel:dt,required:ze,reversed:ze,rows:le,rowSpan:le,sandbox:dt,scope:null,scoped:ze,seamless:ze,selected:ze,shadowRootClonable:ze,shadowRootDelegatesFocus:ze,shadowRootMode:null,shape:null,size:le,sizes:null,slot:null,span:le,spellCheck:Lt,src:null,srcDoc:null,srcLang:null,srcSet:null,start:le,step:null,style:null,tabIndex:le,target:null,title:null,translate:null,type:null,typeMustMatch:ze,useMap:null,value:Lt,width:le,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:dt,axis:null,background:null,bgColor:null,border:le,borderColor:null,bottomMargin:le,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ze,declare:ze,event:null,face:null,frame:null,frameBorder:null,hSpace:le,leftMargin:le,link:null,longDesc:null,lowSrc:null,marginHeight:le,marginWidth:le,noResize:ze,noHref:ze,noShade:ze,noWrap:ze,object:null,profile:null,prompt:null,rev:null,rightMargin:le,rules:null,scheme:null,scrolling:Lt,standby:null,summary:null,text:null,topMargin:le,valueType:null,version:null,vAlign:null,vLink:null,vSpace:le,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ze,disableRemotePlayback:ze,prefix:null,property:null,results:le,security:null,unselectable:null},space:"html",transform:NN}),MU=uo({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Dn,accentHeight:le,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:le,amplitude:le,arabicForm:null,ascent:le,attributeName:null,attributeType:null,azimuth:le,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:le,by:null,calcMode:null,capHeight:le,className:dt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:le,diffuseConstant:le,direction:null,display:null,dur:null,divisor:le,dominantBaseline:null,download:ze,dx:null,dy:null,edgeMode:null,editable:null,elevation:le,enableBackground:null,end:null,event:null,exponent:le,externalResourcesRequired:null,fill:null,fillOpacity:le,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Qa,g2:Qa,glyphName:Qa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:le,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:le,horizOriginX:le,horizOriginY:le,id:null,ideographic:le,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:le,k:le,k1:le,k2:le,k3:le,k4:le,kernelMatrix:Dn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:le,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:le,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:le,overlineThickness:le,paintOrder:null,panose1:null,path:null,pathLength:le,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:dt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:le,pointsAtY:le,pointsAtZ:le,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Dn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Dn,rev:Dn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Dn,requiredFeatures:Dn,requiredFonts:Dn,requiredFormats:Dn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:le,specularExponent:le,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:le,strikethroughThickness:le,string:null,stroke:null,strokeDashArray:Dn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:le,strokeOpacity:le,strokeWidth:null,style:null,surfaceScale:le,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Dn,tabIndex:le,tableValues:null,target:null,targetX:le,targetY:le,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Dn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:le,underlineThickness:le,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:le,values:null,vAlphabetic:le,vMathematical:le,vectorEffect:null,vHanging:le,vIdeographic:le,version:null,vertAdvY:le,vertOriginX:le,vertOriginY:le,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:le,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:kN}),TN=uo({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),EN=uo({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:NN}),CN=uo({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),PU={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},zU=/[A-Z]/g,rS=/-[a-z]/g,LU=/^data[-\w.:]+$/i;function IU(e,t){const n=Qp(t);let s=t,a=_n;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&LU.test(t)){if(t.charAt(4)==="-"){const l=t.slice(5).replace(rS,BU);s="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=t.slice(4);if(!rS.test(l)){let u=l.replace(zU,UU);u.charAt(0)!=="-"&&(u="-"+u),t="data"+u}}a=gy}return new a(s,t)}function UU(e){return"-"+e.toLowerCase()}function BU(e){return e.charAt(1).toUpperCase()}const VU=_N([jN,DU,TN,EN,CN],"html"),yy=_N([jN,MU,TN,EN,CN],"svg");function FU(e){return e.join(" ").trim()}var za={},Um,sS;function qU(){if(sS)return Um;sS=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,l=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,u=/^[;\s]*/,d=/^\s+|\s+$/g,h=`
137
182
  `,m="/",p="*",g="",v="comment",b="declaration";function w(k,N){if(typeof k!="string")throw new TypeError("First argument must be a string");if(!k)return[];N=N||{};var R=1,T=1;function D(se){var ae=se.match(t);ae&&(R+=ae.length);var L=se.lastIndexOf(h);T=~L?se.length-L:T+se.length}function U(){var se={line:R,column:T};return function(ae){return ae.position=new M(se),H(),ae}}function M(se){this.start=se,this.end={line:R,column:T},this.source=N.source}M.prototype.content=k;function B(se){var ae=new Error(N.source+":"+R+":"+T+": "+se);if(ae.reason=se,ae.filename=N.source,ae.line=R,ae.column=T,ae.source=k,!N.silent)throw ae}function P(se){var ae=se.exec(k);if(ae){var L=ae[0];return D(L),k=k.slice(L.length),ae}}function H(){P(n)}function O(se){var ae;for(se=se||[];ae=Q();)ae!==!1&&se.push(ae);return se}function Q(){var se=U();if(!(m!=k.charAt(0)||p!=k.charAt(1))){for(var ae=2;g!=k.charAt(ae)&&(p!=k.charAt(ae)||m!=k.charAt(ae+1));)++ae;if(ae+=2,g===k.charAt(ae-1))return B("End of comment missing");var L=k.slice(2,ae-2);return T+=2,D(L),k=k.slice(ae),T+=2,se({type:v,comment:L})}}function G(){var se=U(),ae=P(s);if(ae){if(Q(),!P(a))return B("property missing ':'");var L=P(l),V=se({type:b,property:j(ae[0].replace(e,g)),value:L?j(L[0].replace(e,g)):g});return P(u),V}}function he(){var se=[];O(se);for(var ae;ae=G();)ae!==!1&&(se.push(ae),O(se));return se}return H(),he()}function j(k){return k?k.replace(d,g):g}return Um=w,Um}var iS;function $U(){if(iS)return za;iS=1;var e=za&&za.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(za,"__esModule",{value:!0}),za.default=n;const t=e(qU());function n(s,a){let l=null;if(!s||typeof s!="string")return l;const u=(0,t.default)(s),d=typeof a=="function";return u.forEach(h=>{if(h.type!=="declaration")return;const{property:m,value:p}=h;d?a(m,p,h):p&&(l=l||{},l[m]=p)}),l}return za}var dl={},aS;function HU(){if(aS)return dl;aS=1,Object.defineProperty(dl,"__esModule",{value:!0}),dl.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,l=function(m){return!m||n.test(m)||e.test(m)},u=function(m,p){return p.toUpperCase()},d=function(m,p){return"".concat(p,"-")},h=function(m,p){return p===void 0&&(p={}),l(m)?m:(m=m.toLowerCase(),p.reactCompat?m=m.replace(a,d):m=m.replace(s,d),m.replace(t,u))};return dl.camelCase=h,dl}var fl,oS;function GU(){if(oS)return fl;oS=1;var e=fl&&fl.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e($U()),n=HU();function s(a,l){var u={};return!a||typeof a!="string"||(0,t.default)(a,function(d,h){d&&h&&(u[(0,n.camelCase)(d,l)]=h)}),u}return s.default=s,fl=s,fl}var KU=GU();const YU=Gl(KU),AN=RN("end"),xy=RN("start");function RN(e){return t;function t(n){const s=n&&n.position&&n.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function WU(e){const t=xy(e),n=AN(e);if(t&&n)return{start:t,end:n}}function kl(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?lS(e.position):"start"in e||"end"in e?lS(e):"line"in e||"column"in e?tg(e):""}function tg(e){return cS(e&&e.line)+":"+cS(e&&e.column)}function lS(e){return tg(e&&e.start)+"-"+tg(e&&e.end)}function cS(e){return e&&typeof e=="number"?e:1}class ln extends Error{constructor(t,n,s){super(),typeof n=="string"&&(s=n,n=void 0);let a="",l={},u=!1;if(n&&("line"in n&&"column"in n?l={place:n}:"start"in n&&"end"in n?l={place:n}:"type"in n?l={ancestors:[n],place:n.position}:l={...n}),typeof t=="string"?a=t:!l.cause&&t&&(u=!0,a=t.message,l.cause=t),!l.ruleId&&!l.source&&typeof s=="string"){const h=s.indexOf(":");h===-1?l.ruleId=s:(l.source=s.slice(0,h),l.ruleId=s.slice(h+1))}if(!l.place&&l.ancestors&&l.ancestors){const h=l.ancestors[l.ancestors.length-1];h&&(l.place=h.position)}const d=l.place&&"start"in l.place?l.place.start:l.place;this.ancestors=l.ancestors||void 0,this.cause=l.cause||void 0,this.column=d?d.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=d?d.line:void 0,this.name=kl(l.place)||"1:1",this.place=l.place||void 0,this.reason=this.message,this.ruleId=l.ruleId||void 0,this.source=l.source||void 0,this.stack=u&&l.cause&&typeof l.cause.stack=="string"?l.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}ln.prototype.file="";ln.prototype.name="";ln.prototype.reason="";ln.prototype.message="";ln.prototype.stack="";ln.prototype.column=void 0;ln.prototype.line=void 0;ln.prototype.ancestors=void 0;ln.prototype.cause=void 0;ln.prototype.fatal=void 0;ln.prototype.place=void 0;ln.prototype.ruleId=void 0;ln.prototype.source=void 0;const vy={}.hasOwnProperty,XU=new Map,JU=/[A-Z]/g,QU=new Set(["table","tbody","thead","tfoot","tr"]),ZU=new Set(["td","th"]),ON="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function e8(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=l8(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=o8(n,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?yy:VU,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},l=DN(a,e,void 0);return l&&typeof l!="string"?l:a.create(e,a.Fragment,{children:l||void 0},void 0)}function DN(e,t,n){if(t.type==="element")return t8(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return n8(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return s8(e,t,n);if(t.type==="mdxjsEsm")return r8(e,t);if(t.type==="root")return i8(e,t,n);if(t.type==="text")return a8(e,t)}function t8(e,t,n){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=yy,e.schema=a),e.ancestors.push(t);const l=PN(e,t.tagName,!1),u=c8(e,t);let d=wy(e,t);return QU.has(t.tagName)&&(d=d.filter(function(h){return typeof h=="string"?!RU(h):!0})),MN(e,u,l,t),by(u,d),e.ancestors.pop(),e.schema=s,e.create(t,l,u,n)}function n8(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}$l(e,t.position)}function r8(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);$l(e,t.position)}function s8(e,t,n){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=yy,e.schema=a),e.ancestors.push(t);const l=t.name===null?e.Fragment:PN(e,t.name,!0),u=u8(e,t),d=wy(e,t);return MN(e,u,l,t),by(u,d),e.ancestors.pop(),e.schema=s,e.create(t,l,u,n)}function i8(e,t,n){const s={};return by(s,wy(e,t)),e.create(t,e.Fragment,s,n)}function a8(e,t){return t.value}function MN(e,t,n,s){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=s)}function by(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function o8(e,t,n){return s;function s(a,l,u,d){const m=Array.isArray(u.children)?n:t;return d?m(l,u,d):m(l,u)}}function l8(e,t){return n;function n(s,a,l,u){const d=Array.isArray(l.children),h=xy(s);return t(a,l,u,d,{columnNumber:h?h.column-1:void 0,fileName:e,lineNumber:h?h.line:void 0},void 0)}}function c8(e,t){const n={};let s,a;for(a in t.properties)if(a!=="children"&&vy.call(t.properties,a)){const l=d8(e,a,t.properties[a]);if(l){const[u,d]=l;e.tableCellAlignToStyle&&u==="align"&&typeof d=="string"&&ZU.has(t.tagName)?s=d:n[u]=d}}if(s){const l=n.style||(n.style={});l[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return n}function u8(e,t){const n={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const l=s.data.estree.body[0];l.type;const u=l.expression;u.type;const d=u.properties[0];d.type,Object.assign(n,e.evaluater.evaluateExpression(d.argument))}else $l(e,t.position);else{const a=s.name;let l;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const d=s.value.data.estree.body[0];d.type,l=e.evaluater.evaluateExpression(d.expression)}else $l(e,t.position);else l=s.value===null?!0:s.value;n[a]=l}return n}function wy(e,t){const n=[];let s=-1;const a=e.passKeys?new Map:XU;for(;++s<t.children.length;){const l=t.children[s];let u;if(e.passKeys){const h=l.type==="element"?l.tagName:l.type==="mdxJsxFlowElement"||l.type==="mdxJsxTextElement"?l.name:void 0;if(h){const m=a.get(h)||0;u=h+"-"+m,a.set(h,m+1)}}const d=DN(e,l,u);d!==void 0&&n.push(d)}return n}function d8(e,t,n){const s=IU(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=s.commaSeparated?NU(n):FU(n)),s.property==="style"){let a=typeof n=="object"?n:f8(e,String(n));return e.stylePropertyNameCase==="css"&&(a=h8(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&s.space?PU[s.property]||s.property:s.attribute,n]}}function f8(e,t){try{return YU(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const s=n,a=new ln("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:s,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=e.filePath||void 0,a.url=ON+"#cannot-parse-style-attribute",a}}function PN(e,t,n){let s;if(!n)s={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let l=-1,u;for(;++l<a.length;){const d=eS(a[l])?{type:"Identifier",name:a[l]}:{type:"Literal",value:a[l]};u=u?{type:"MemberExpression",object:u,property:d,computed:!!(l&&d.type==="Literal"),optional:!1}:d}s=u}else s=eS(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const a=s.value;return vy.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(s);$l(e)}function $l(e,t){const n=new ln("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=ON+"#cannot-handle-mdx-estrees-without-createevaluater",n}function h8(e){const t={};let n;for(n in e)vy.call(e,n)&&(t[m8(n)]=e[n]);return t}function m8(e){let t=e.replace(JU,p8);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function p8(e){return"-"+e.toLowerCase()}const Bm={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},g8={};function Sy(e,t){const n=g8,s=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,a=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return zN(e,s,a)}function zN(e,t,n){if(y8(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return uS(e.children,t,n)}return Array.isArray(e)?uS(e,t,n):""}function uS(e,t,n){const s=[];let a=-1;for(;++a<e.length;)s[a]=zN(e[a],t,n);return s.join("")}function y8(e){return!!(e&&typeof e=="object")}const dS=document.createElement("i");function _y(e){const t="&"+e+";";dS.innerHTML=t;const n=dS.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function Ln(e,t,n,s){const a=e.length;let l=0,u;if(t<0?t=-t>a?0:a+t:t=t>a?a:t,n=n>0?n:0,s.length<1e4)u=Array.from(s),u.unshift(t,n),e.splice(...u);else for(n&&e.splice(t,n);l<s.length;)u=s.slice(l,l+1e4),u.unshift(t,0),e.splice(...u),l+=1e4,t+=1e4}function er(e,t){return e.length>0?(Ln(e,e.length,0,t),e):t}const fS={}.hasOwnProperty;function LN(e){const t={};let n=-1;for(;++n<e.length;)x8(t,e[n]);return t}function x8(e,t){let n;for(n in t){const a=(fS.call(e,n)?e[n]:void 0)||(e[n]={}),l=t[n];let u;if(l)for(u in l){fS.call(a,u)||(a[u]=[]);const d=l[u];v8(a[u],Array.isArray(d)?d:d?[d]:[])}}}function v8(e,t){let n=-1;const s=[];for(;++n<t.length;)(t[n].add==="after"?e:s).push(t[n]);Ln(e,0,0,s)}function IN(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function hr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const dn=Zs(/[A-Za-z]/),on=Zs(/[\dA-Za-z]/),b8=Zs(/[#-'*+\--9=?A-Z^-~]/);function fd(e){return e!==null&&(e<32||e===127)}const ng=Zs(/\d/),w8=Zs(/[\dA-Fa-f]/),S8=Zs(/[!-/:-@[-`{-~]/);function Ne(e){return e!==null&&e<-2}function ct(e){return e!==null&&(e<0||e===32)}function qe(e){return e===-2||e===-1||e===32}const Rd=Zs(new RegExp("\\p{P}|\\p{S}","u")),Ii=Zs(/\s/);function Zs(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function fo(e){const t=[];let n=-1,s=0,a=0;for(;++n<e.length;){const l=e.charCodeAt(n);let u="";if(l===37&&on(e.charCodeAt(n+1))&&on(e.charCodeAt(n+2)))a=2;else if(l<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(l))||(u=String.fromCharCode(l));else if(l>55295&&l<57344){const d=e.charCodeAt(n+1);l<56320&&d>56319&&d<57344?(u=String.fromCharCode(l,d),a=1):u="�"}else u=String.fromCharCode(l);u&&(t.push(e.slice(s,n),encodeURIComponent(u)),s=n+a+1,u=""),a&&(n+=a,a=0)}return t.join("")+e.slice(s)}function Xe(e,t,n,s){const a=s?s-1:Number.POSITIVE_INFINITY;let l=0;return u;function u(h){return qe(h)?(e.enter(n),d(h)):t(h)}function d(h){return qe(h)&&l++<a?(e.consume(h),d):(e.exit(n),t(h))}}const _8={tokenize:j8};function j8(e){const t=e.attempt(this.parser.constructs.contentInitial,s,a);let n;return t;function s(d){if(d===null){e.consume(d);return}return e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),Xe(e,t,"linePrefix")}function a(d){return e.enter("paragraph"),l(d)}function l(d){const h=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=h),n=h,u(d)}function u(d){if(d===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(d);return}return Ne(d)?(e.consume(d),e.exit("chunkText"),l):(e.consume(d),u)}}const k8={tokenize:N8},hS={tokenize:T8};function N8(e){const t=this,n=[];let s=0,a,l,u;return d;function d(T){if(s<n.length){const D=n[s];return t.containerState=D[1],e.attempt(D[0].continuation,h,m)(T)}return m(T)}function h(T){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&R();const D=t.events.length;let U=D,M;for(;U--;)if(t.events[U][0]==="exit"&&t.events[U][1].type==="chunkFlow"){M=t.events[U][1].end;break}N(s);let B=D;for(;B<t.events.length;)t.events[B][1].end={...M},B++;return Ln(t.events,U+1,0,t.events.slice(D)),t.events.length=B,m(T)}return d(T)}function m(T){if(s===n.length){if(!a)return v(T);if(a.currentConstruct&&a.currentConstruct.concrete)return w(T);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(hS,p,g)(T)}function p(T){return a&&R(),N(s),v(T)}function g(T){return t.parser.lazy[t.now().line]=s!==n.length,u=t.now().offset,w(T)}function v(T){return t.containerState={},e.attempt(hS,b,w)(T)}function b(T){return s++,n.push([t.currentConstruct,t.containerState]),v(T)}function w(T){if(T===null){a&&R(),N(0),e.consume(T);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:l}),j(T)}function j(T){if(T===null){k(e.exit("chunkFlow"),!0),N(0),e.consume(T);return}return Ne(T)?(e.consume(T),k(e.exit("chunkFlow")),s=0,t.interrupt=void 0,d):(e.consume(T),j)}function k(T,D){const U=t.sliceStream(T);if(D&&U.push(null),T.previous=l,l&&(l.next=T),l=T,a.defineSkip(T.start),a.write(U),t.parser.lazy[T.start.line]){let M=a.events.length;for(;M--;)if(a.events[M][1].start.offset<u&&(!a.events[M][1].end||a.events[M][1].end.offset>u))return;const B=t.events.length;let P=B,H,O;for(;P--;)if(t.events[P][0]==="exit"&&t.events[P][1].type==="chunkFlow"){if(H){O=t.events[P][1].end;break}H=!0}for(N(s),M=B;M<t.events.length;)t.events[M][1].end={...O},M++;Ln(t.events,P+1,0,t.events.slice(B)),t.events.length=M}}function N(T){let D=n.length;for(;D-- >T;){const U=n[D];t.containerState=U[1],U[0].exit.call(t,e)}n.length=T}function R(){a.write([null]),l=void 0,a=void 0,t.containerState._closeFlow=void 0}}function T8(e,t,n){return Xe(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function no(e){if(e===null||ct(e)||Ii(e))return 1;if(Rd(e))return 2}function Od(e,t,n){const s=[];let a=-1;for(;++a<e.length;){const l=e[a].resolveAll;l&&!s.includes(l)&&(t=l(t,n),s.push(l))}return t}const rg={name:"attention",resolveAll:E8,tokenize:C8};function E8(e,t){let n=-1,s,a,l,u,d,h,m,p;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(s=n;s--;)if(e[s][0]==="exit"&&e[s][1].type==="attentionSequence"&&e[s][1]._open&&t.sliceSerialize(e[s][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[s][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[s][1].end.offset-e[s][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;h=e[s][1].end.offset-e[s][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const g={...e[s][1].end},v={...e[n][1].start};mS(g,-h),mS(v,h),u={type:h>1?"strongSequence":"emphasisSequence",start:g,end:{...e[s][1].end}},d={type:h>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:v},l={type:h>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[n][1].start}},a={type:h>1?"strong":"emphasis",start:{...u.start},end:{...d.end}},e[s][1].end={...u.start},e[n][1].start={...d.end},m=[],e[s][1].end.offset-e[s][1].start.offset&&(m=er(m,[["enter",e[s][1],t],["exit",e[s][1],t]])),m=er(m,[["enter",a,t],["enter",u,t],["exit",u,t],["enter",l,t]]),m=er(m,Od(t.parser.constructs.insideSpan.null,e.slice(s+1,n),t)),m=er(m,[["exit",l,t],["enter",d,t],["exit",d,t],["exit",a,t]]),e[n][1].end.offset-e[n][1].start.offset?(p=2,m=er(m,[["enter",e[n][1],t],["exit",e[n][1],t]])):p=0,Ln(e,s-1,n-s+3,m),n=s+m.length-p-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function C8(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,a=no(s);let l;return u;function u(h){return l=h,e.enter("attentionSequence"),d(h)}function d(h){if(h===l)return e.consume(h),d;const m=e.exit("attentionSequence"),p=no(h),g=!p||p===2&&a||n.includes(h),v=!a||a===2&&p||n.includes(s);return m._open=!!(l===42?g:g&&(a||!v)),m._close=!!(l===42?v:v&&(p||!g)),t(h)}}function mS(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const A8={name:"autolink",tokenize:R8};function R8(e,t,n){let s=0;return a;function a(b){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(b),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),l}function l(b){return dn(b)?(e.consume(b),u):b===64?n(b):m(b)}function u(b){return b===43||b===45||b===46||on(b)?(s=1,d(b)):m(b)}function d(b){return b===58?(e.consume(b),s=0,h):(b===43||b===45||b===46||on(b))&&s++<32?(e.consume(b),d):(s=0,m(b))}function h(b){return b===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(b),e.exit("autolinkMarker"),e.exit("autolink"),t):b===null||b===32||b===60||fd(b)?n(b):(e.consume(b),h)}function m(b){return b===64?(e.consume(b),p):b8(b)?(e.consume(b),m):n(b)}function p(b){return on(b)?g(b):n(b)}function g(b){return b===46?(e.consume(b),s=0,p):b===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(b),e.exit("autolinkMarker"),e.exit("autolink"),t):v(b)}function v(b){if((b===45||on(b))&&s++<63){const w=b===45?v:g;return e.consume(b),w}return n(b)}}const tc={partial:!0,tokenize:O8};function O8(e,t,n){return s;function s(l){return qe(l)?Xe(e,a,"linePrefix")(l):a(l)}function a(l){return l===null||Ne(l)?t(l):n(l)}}const UN={continuation:{tokenize:M8},exit:P8,name:"blockQuote",tokenize:D8};function D8(e,t,n){const s=this;return a;function a(u){if(u===62){const d=s.containerState;return d.open||(e.enter("blockQuote",{_container:!0}),d.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(u),e.exit("blockQuoteMarker"),l}return n(u)}function l(u){return qe(u)?(e.enter("blockQuotePrefixWhitespace"),e.consume(u),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(u))}}function M8(e,t,n){const s=this;return a;function a(u){return qe(u)?Xe(e,l,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(u):l(u)}function l(u){return e.attempt(UN,t,n)(u)}}function P8(e){e.exit("blockQuote")}const BN={name:"characterEscape",tokenize:z8};function z8(e,t,n){return s;function s(l){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(l),e.exit("escapeMarker"),a}function a(l){return S8(l)?(e.enter("characterEscapeValue"),e.consume(l),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(l)}}const VN={name:"characterReference",tokenize:L8};function L8(e,t,n){const s=this;let a=0,l,u;return d;function d(g){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(g),e.exit("characterReferenceMarker"),h}function h(g){return g===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(g),e.exit("characterReferenceMarkerNumeric"),m):(e.enter("characterReferenceValue"),l=31,u=on,p(g))}function m(g){return g===88||g===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(g),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),l=6,u=w8,p):(e.enter("characterReferenceValue"),l=7,u=ng,p(g))}function p(g){if(g===59&&a){const v=e.exit("characterReferenceValue");return u===on&&!_y(s.sliceSerialize(v))?n(g):(e.enter("characterReferenceMarker"),e.consume(g),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return u(g)&&a++<l?(e.consume(g),p):n(g)}}const pS={partial:!0,tokenize:U8},gS={concrete:!0,name:"codeFenced",tokenize:I8};function I8(e,t,n){const s=this,a={partial:!0,tokenize:U};let l=0,u=0,d;return h;function h(M){return m(M)}function m(M){const B=s.events[s.events.length-1];return l=B&&B[1].type==="linePrefix"?B[2].sliceSerialize(B[1],!0).length:0,d=M,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),p(M)}function p(M){return M===d?(u++,e.consume(M),p):u<3?n(M):(e.exit("codeFencedFenceSequence"),qe(M)?Xe(e,g,"whitespace")(M):g(M))}function g(M){return M===null||Ne(M)?(e.exit("codeFencedFence"),s.interrupt?t(M):e.check(pS,j,D)(M)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),v(M))}function v(M){return M===null||Ne(M)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),g(M)):qe(M)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Xe(e,b,"whitespace")(M)):M===96&&M===d?n(M):(e.consume(M),v)}function b(M){return M===null||Ne(M)?g(M):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),w(M))}function w(M){return M===null||Ne(M)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),g(M)):M===96&&M===d?n(M):(e.consume(M),w)}function j(M){return e.attempt(a,D,k)(M)}function k(M){return e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),N}function N(M){return l>0&&qe(M)?Xe(e,R,"linePrefix",l+1)(M):R(M)}function R(M){return M===null||Ne(M)?e.check(pS,j,D)(M):(e.enter("codeFlowValue"),T(M))}function T(M){return M===null||Ne(M)?(e.exit("codeFlowValue"),R(M)):(e.consume(M),T)}function D(M){return e.exit("codeFenced"),t(M)}function U(M,B,P){let H=0;return O;function O(ae){return M.enter("lineEnding"),M.consume(ae),M.exit("lineEnding"),Q}function Q(ae){return M.enter("codeFencedFence"),qe(ae)?Xe(M,G,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(ae):G(ae)}function G(ae){return ae===d?(M.enter("codeFencedFenceSequence"),he(ae)):P(ae)}function he(ae){return ae===d?(H++,M.consume(ae),he):H>=u?(M.exit("codeFencedFenceSequence"),qe(ae)?Xe(M,se,"whitespace")(ae):se(ae)):P(ae)}function se(ae){return ae===null||Ne(ae)?(M.exit("codeFencedFence"),B(ae)):P(ae)}}}function U8(e,t,n){const s=this;return a;function a(u){return u===null?n(u):(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),l)}function l(u){return s.parser.lazy[s.now().line]?n(u):t(u)}}const Vm={name:"codeIndented",tokenize:V8},B8={partial:!0,tokenize:F8};function V8(e,t,n){const s=this;return a;function a(m){return e.enter("codeIndented"),Xe(e,l,"linePrefix",5)(m)}function l(m){const p=s.events[s.events.length-1];return p&&p[1].type==="linePrefix"&&p[2].sliceSerialize(p[1],!0).length>=4?u(m):n(m)}function u(m){return m===null?h(m):Ne(m)?e.attempt(B8,u,h)(m):(e.enter("codeFlowValue"),d(m))}function d(m){return m===null||Ne(m)?(e.exit("codeFlowValue"),u(m)):(e.consume(m),d)}function h(m){return e.exit("codeIndented"),t(m)}}function F8(e,t,n){const s=this;return a;function a(u){return s.parser.lazy[s.now().line]?n(u):Ne(u)?(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),a):Xe(e,l,"linePrefix",5)(u)}function l(u){const d=s.events[s.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?t(u):Ne(u)?a(u):n(u)}}const q8={name:"codeText",previous:H8,resolve:$8,tokenize:G8};function $8(e){let t=e.length-4,n=3,s,a;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=n;++s<t;)if(e[s][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(s=n-1,t++;++s<=t;)a===void 0?s!==t&&e[s][1].type!=="lineEnding"&&(a=s):(s===t||e[s][1].type==="lineEnding")&&(e[a][1].type="codeTextData",s!==a+2&&(e[a][1].end=e[s-1][1].end,e.splice(a+2,s-a-2),t-=s-a-2,s=a+2),a=void 0);return e}function H8(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function G8(e,t,n){let s=0,a,l;return u;function u(g){return e.enter("codeText"),e.enter("codeTextSequence"),d(g)}function d(g){return g===96?(e.consume(g),s++,d):(e.exit("codeTextSequence"),h(g))}function h(g){return g===null?n(g):g===32?(e.enter("space"),e.consume(g),e.exit("space"),h):g===96?(l=e.enter("codeTextSequence"),a=0,p(g)):Ne(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),h):(e.enter("codeTextData"),m(g))}function m(g){return g===null||g===32||g===96||Ne(g)?(e.exit("codeTextData"),h(g)):(e.consume(g),m)}function p(g){return g===96?(e.consume(g),a++,p):a===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(g)):(l.type="codeTextData",m(g))}}class K8{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const s=n??Number.POSITIVE_INFINITY;return s<this.left.length?this.left.slice(t,s):t>this.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,n,s){const a=n||0;this.setCursor(Math.trunc(t));const l=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&hl(this.left,s),l.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),hl(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),hl(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);hl(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);hl(this.left,n.reverse())}}}function hl(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function FN(e){const t={};let n=-1,s,a,l,u,d,h,m;const p=new K8(e);for(;++n<p.length;){for(;n in t;)n=t[n];if(s=p.get(n),n&&s[1].type==="chunkFlow"&&p.get(n-1)[1].type==="listItemPrefix"&&(h=s[1]._tokenizer.events,l=0,l<h.length&&h[l][1].type==="lineEndingBlank"&&(l+=2),l<h.length&&h[l][1].type==="content"))for(;++l<h.length&&h[l][1].type!=="content";)h[l][1].type==="chunkText"&&(h[l][1]._isInFirstContentOfListItem=!0,l++);if(s[0]==="enter")s[1].contentType&&(Object.assign(t,Y8(p,n)),n=t[n],m=!0);else if(s[1]._container){for(l=n,a=void 0;l--;)if(u=p.get(l),u[1].type==="lineEnding"||u[1].type==="lineEndingBlank")u[0]==="enter"&&(a&&(p.get(a)[1].type="lineEndingBlank"),u[1].type="lineEnding",a=l);else if(!(u[1].type==="linePrefix"||u[1].type==="listItemIndent"))break;a&&(s[1].end={...p.get(a)[1].start},d=p.slice(a,n),d.unshift(s),p.splice(a,n-a+1,d))}}return Ln(e,0,Number.POSITIVE_INFINITY,p.slice(0)),!m}function Y8(e,t){const n=e.get(t)[1],s=e.get(t)[2];let a=t-1;const l=[];let u=n._tokenizer;u||(u=s.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(u._contentTypeTextTrailing=!0));const d=u.events,h=[],m={};let p,g,v=-1,b=n,w=0,j=0;const k=[j];for(;b;){for(;e.get(++a)[1]!==b;);l.push(a),b._tokenizer||(p=s.sliceStream(b),b.next||p.push(null),g&&u.defineSkip(b.start),b._isInFirstContentOfListItem&&(u._gfmTasklistFirstContentOfListItem=!0),u.write(p),b._isInFirstContentOfListItem&&(u._gfmTasklistFirstContentOfListItem=void 0)),g=b,b=b.next}for(b=n;++v<d.length;)d[v][0]==="exit"&&d[v-1][0]==="enter"&&d[v][1].type===d[v-1][1].type&&d[v][1].start.line!==d[v][1].end.line&&(j=v+1,k.push(j),b._tokenizer=void 0,b.previous=void 0,b=b.next);for(u.events=[],b?(b._tokenizer=void 0,b.previous=void 0):k.pop(),v=k.length;v--;){const N=d.slice(k[v],k[v+1]),R=l.pop();h.push([R,R+N.length-1]),e.splice(R,2,N)}for(h.reverse(),v=-1;++v<h.length;)m[w+h[v][0]]=w+h[v][1],w+=h[v][1]-h[v][0]-1;return m}const W8={resolve:J8,tokenize:Q8},X8={partial:!0,tokenize:Z8};function J8(e){return FN(e),e}function Q8(e,t){let n;return s;function s(d){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),a(d)}function a(d){return d===null?l(d):Ne(d)?e.check(X8,u,l)(d):(e.consume(d),a)}function l(d){return e.exit("chunkContent"),e.exit("content"),t(d)}function u(d){return e.consume(d),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,a}}function Z8(e,t,n){const s=this;return a;function a(u){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),Xe(e,l,"linePrefix")}function l(u){if(u===null||Ne(u))return n(u);const d=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?t(u):e.interrupt(s.parser.constructs.flow,n,t)(u)}}function qN(e,t,n,s,a,l,u,d,h){const m=h||Number.POSITIVE_INFINITY;let p=0;return g;function g(N){return N===60?(e.enter(s),e.enter(a),e.enter(l),e.consume(N),e.exit(l),v):N===null||N===32||N===41||fd(N)?n(N):(e.enter(s),e.enter(u),e.enter(d),e.enter("chunkString",{contentType:"string"}),j(N))}function v(N){return N===62?(e.enter(l),e.consume(N),e.exit(l),e.exit(a),e.exit(s),t):(e.enter(d),e.enter("chunkString",{contentType:"string"}),b(N))}function b(N){return N===62?(e.exit("chunkString"),e.exit(d),v(N)):N===null||N===60||Ne(N)?n(N):(e.consume(N),N===92?w:b)}function w(N){return N===60||N===62||N===92?(e.consume(N),b):b(N)}function j(N){return!p&&(N===null||N===41||ct(N))?(e.exit("chunkString"),e.exit(d),e.exit(u),e.exit(s),t(N)):p<m&&N===40?(e.consume(N),p++,j):N===41?(e.consume(N),p--,j):N===null||N===32||N===40||fd(N)?n(N):(e.consume(N),N===92?k:j)}function k(N){return N===40||N===41||N===92?(e.consume(N),j):j(N)}}function $N(e,t,n,s,a,l){const u=this;let d=0,h;return m;function m(b){return e.enter(s),e.enter(a),e.consume(b),e.exit(a),e.enter(l),p}function p(b){return d>999||b===null||b===91||b===93&&!h||b===94&&!d&&"_hiddenFootnoteSupport"in u.parser.constructs?n(b):b===93?(e.exit(l),e.enter(a),e.consume(b),e.exit(a),e.exit(s),t):Ne(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),p):(e.enter("chunkString",{contentType:"string"}),g(b))}function g(b){return b===null||b===91||b===93||Ne(b)||d++>999?(e.exit("chunkString"),p(b)):(e.consume(b),h||(h=!qe(b)),b===92?v:g)}function v(b){return b===91||b===92||b===93?(e.consume(b),d++,g):g(b)}}function HN(e,t,n,s,a,l){let u;return d;function d(v){return v===34||v===39||v===40?(e.enter(s),e.enter(a),e.consume(v),e.exit(a),u=v===40?41:v,h):n(v)}function h(v){return v===u?(e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):(e.enter(l),m(v))}function m(v){return v===u?(e.exit(l),h(u)):v===null?n(v):Ne(v)?(e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),Xe(e,m,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===u||v===null||Ne(v)?(e.exit("chunkString"),m(v)):(e.consume(v),v===92?g:p)}function g(v){return v===u||v===92?(e.consume(v),p):p(v)}}function Nl(e,t){let n;return s;function s(a){return Ne(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),n=!0,s):qe(a)?Xe(e,s,n?"linePrefix":"lineSuffix")(a):t(a)}}const eB={name:"definition",tokenize:nB},tB={partial:!0,tokenize:rB};function nB(e,t,n){const s=this;let a;return l;function l(b){return e.enter("definition"),u(b)}function u(b){return $N.call(s,e,d,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(b)}function d(b){return a=hr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),b===58?(e.enter("definitionMarker"),e.consume(b),e.exit("definitionMarker"),h):n(b)}function h(b){return ct(b)?Nl(e,m)(b):m(b)}function m(b){return qN(e,p,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(b)}function p(b){return e.attempt(tB,g,g)(b)}function g(b){return qe(b)?Xe(e,v,"whitespace")(b):v(b)}function v(b){return b===null||Ne(b)?(e.exit("definition"),s.parser.defined.push(a),t(b)):n(b)}}function rB(e,t,n){return s;function s(d){return ct(d)?Nl(e,a)(d):n(d)}function a(d){return HN(e,l,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(d)}function l(d){return qe(d)?Xe(e,u,"whitespace")(d):u(d)}function u(d){return d===null||Ne(d)?t(d):n(d)}}const sB={name:"hardBreakEscape",tokenize:iB};function iB(e,t,n){return s;function s(l){return e.enter("hardBreakEscape"),e.consume(l),a}function a(l){return Ne(l)?(e.exit("hardBreakEscape"),t(l)):n(l)}}const aB={name:"headingAtx",resolve:oB,tokenize:lB};function oB(e,t){let n=e.length-2,s=3,a,l;return e[s][1].type==="whitespace"&&(s+=2),n-2>s&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(s===n-1||n-4>s&&e[n-2][1].type==="whitespace")&&(n-=s+1===n?2:4),n>s&&(a={type:"atxHeadingText",start:e[s][1].start,end:e[n][1].end},l={type:"chunkText",start:e[s][1].start,end:e[n][1].end,contentType:"text"},Ln(e,s,n-s+1,[["enter",a,t],["enter",l,t],["exit",l,t],["exit",a,t]])),e}function lB(e,t,n){let s=0;return a;function a(p){return e.enter("atxHeading"),l(p)}function l(p){return e.enter("atxHeadingSequence"),u(p)}function u(p){return p===35&&s++<6?(e.consume(p),u):p===null||ct(p)?(e.exit("atxHeadingSequence"),d(p)):n(p)}function d(p){return p===35?(e.enter("atxHeadingSequence"),h(p)):p===null||Ne(p)?(e.exit("atxHeading"),t(p)):qe(p)?Xe(e,d,"whitespace")(p):(e.enter("atxHeadingText"),m(p))}function h(p){return p===35?(e.consume(p),h):(e.exit("atxHeadingSequence"),d(p))}function m(p){return p===null||p===35||ct(p)?(e.exit("atxHeadingText"),d(p)):(e.consume(p),m)}}const cB=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],yS=["pre","script","style","textarea"],uB={concrete:!0,name:"htmlFlow",resolveTo:hB,tokenize:mB},dB={partial:!0,tokenize:gB},fB={partial:!0,tokenize:pB};function hB(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function mB(e,t,n){const s=this;let a,l,u,d,h;return m;function m(A){return p(A)}function p(A){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(A),g}function g(A){return A===33?(e.consume(A),v):A===47?(e.consume(A),l=!0,j):A===63?(e.consume(A),a=3,s.interrupt?t:C):dn(A)?(e.consume(A),u=String.fromCharCode(A),k):n(A)}function v(A){return A===45?(e.consume(A),a=2,b):A===91?(e.consume(A),a=5,d=0,w):dn(A)?(e.consume(A),a=4,s.interrupt?t:C):n(A)}function b(A){return A===45?(e.consume(A),s.interrupt?t:C):n(A)}function w(A){const oe="CDATA[";return A===oe.charCodeAt(d++)?(e.consume(A),d===oe.length?s.interrupt?t:G:w):n(A)}function j(A){return dn(A)?(e.consume(A),u=String.fromCharCode(A),k):n(A)}function k(A){if(A===null||A===47||A===62||ct(A)){const oe=A===47,pe=u.toLowerCase();return!oe&&!l&&yS.includes(pe)?(a=1,s.interrupt?t(A):G(A)):cB.includes(u.toLowerCase())?(a=6,oe?(e.consume(A),N):s.interrupt?t(A):G(A)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(A):l?R(A):T(A))}return A===45||on(A)?(e.consume(A),u+=String.fromCharCode(A),k):n(A)}function N(A){return A===62?(e.consume(A),s.interrupt?t:G):n(A)}function R(A){return qe(A)?(e.consume(A),R):O(A)}function T(A){return A===47?(e.consume(A),O):A===58||A===95||dn(A)?(e.consume(A),D):qe(A)?(e.consume(A),T):O(A)}function D(A){return A===45||A===46||A===58||A===95||on(A)?(e.consume(A),D):U(A)}function U(A){return A===61?(e.consume(A),M):qe(A)?(e.consume(A),U):T(A)}function M(A){return A===null||A===60||A===61||A===62||A===96?n(A):A===34||A===39?(e.consume(A),h=A,B):qe(A)?(e.consume(A),M):P(A)}function B(A){return A===h?(e.consume(A),h=null,H):A===null||Ne(A)?n(A):(e.consume(A),B)}function P(A){return A===null||A===34||A===39||A===47||A===60||A===61||A===62||A===96||ct(A)?U(A):(e.consume(A),P)}function H(A){return A===47||A===62||qe(A)?T(A):n(A)}function O(A){return A===62?(e.consume(A),Q):n(A)}function Q(A){return A===null||Ne(A)?G(A):qe(A)?(e.consume(A),Q):n(A)}function G(A){return A===45&&a===2?(e.consume(A),L):A===60&&a===1?(e.consume(A),V):A===62&&a===4?(e.consume(A),z):A===63&&a===3?(e.consume(A),C):A===93&&a===5?(e.consume(A),de):Ne(A)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(dB,J,he)(A)):A===null||Ne(A)?(e.exit("htmlFlowData"),he(A)):(e.consume(A),G)}function he(A){return e.check(fB,se,J)(A)}function se(A){return e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),ae}function ae(A){return A===null||Ne(A)?he(A):(e.enter("htmlFlowData"),G(A))}function L(A){return A===45?(e.consume(A),C):G(A)}function V(A){return A===47?(e.consume(A),u="",q):G(A)}function q(A){if(A===62){const oe=u.toLowerCase();return yS.includes(oe)?(e.consume(A),z):G(A)}return dn(A)&&u.length<8?(e.consume(A),u+=String.fromCharCode(A),q):G(A)}function de(A){return A===93?(e.consume(A),C):G(A)}function C(A){return A===62?(e.consume(A),z):A===45&&a===2?(e.consume(A),C):G(A)}function z(A){return A===null||Ne(A)?(e.exit("htmlFlowData"),J(A)):(e.consume(A),z)}function J(A){return e.exit("htmlFlow"),t(A)}}function pB(e,t,n){const s=this;return a;function a(u){return Ne(u)?(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),l):n(u)}function l(u){return s.parser.lazy[s.now().line]?n(u):t(u)}}function gB(e,t,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(tc,t,n)}}const yB={name:"htmlText",tokenize:xB};function xB(e,t,n){const s=this;let a,l,u;return d;function d(C){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(C),h}function h(C){return C===33?(e.consume(C),m):C===47?(e.consume(C),U):C===63?(e.consume(C),T):dn(C)?(e.consume(C),P):n(C)}function m(C){return C===45?(e.consume(C),p):C===91?(e.consume(C),l=0,w):dn(C)?(e.consume(C),R):n(C)}function p(C){return C===45?(e.consume(C),b):n(C)}function g(C){return C===null?n(C):C===45?(e.consume(C),v):Ne(C)?(u=g,V(C)):(e.consume(C),g)}function v(C){return C===45?(e.consume(C),b):g(C)}function b(C){return C===62?L(C):C===45?v(C):g(C)}function w(C){const z="CDATA[";return C===z.charCodeAt(l++)?(e.consume(C),l===z.length?j:w):n(C)}function j(C){return C===null?n(C):C===93?(e.consume(C),k):Ne(C)?(u=j,V(C)):(e.consume(C),j)}function k(C){return C===93?(e.consume(C),N):j(C)}function N(C){return C===62?L(C):C===93?(e.consume(C),N):j(C)}function R(C){return C===null||C===62?L(C):Ne(C)?(u=R,V(C)):(e.consume(C),R)}function T(C){return C===null?n(C):C===63?(e.consume(C),D):Ne(C)?(u=T,V(C)):(e.consume(C),T)}function D(C){return C===62?L(C):T(C)}function U(C){return dn(C)?(e.consume(C),M):n(C)}function M(C){return C===45||on(C)?(e.consume(C),M):B(C)}function B(C){return Ne(C)?(u=B,V(C)):qe(C)?(e.consume(C),B):L(C)}function P(C){return C===45||on(C)?(e.consume(C),P):C===47||C===62||ct(C)?H(C):n(C)}function H(C){return C===47?(e.consume(C),L):C===58||C===95||dn(C)?(e.consume(C),O):Ne(C)?(u=H,V(C)):qe(C)?(e.consume(C),H):L(C)}function O(C){return C===45||C===46||C===58||C===95||on(C)?(e.consume(C),O):Q(C)}function Q(C){return C===61?(e.consume(C),G):Ne(C)?(u=Q,V(C)):qe(C)?(e.consume(C),Q):H(C)}function G(C){return C===null||C===60||C===61||C===62||C===96?n(C):C===34||C===39?(e.consume(C),a=C,he):Ne(C)?(u=G,V(C)):qe(C)?(e.consume(C),G):(e.consume(C),se)}function he(C){return C===a?(e.consume(C),a=void 0,ae):C===null?n(C):Ne(C)?(u=he,V(C)):(e.consume(C),he)}function se(C){return C===null||C===34||C===39||C===60||C===61||C===96?n(C):C===47||C===62||ct(C)?H(C):(e.consume(C),se)}function ae(C){return C===47||C===62||ct(C)?H(C):n(C)}function L(C){return C===62?(e.consume(C),e.exit("htmlTextData"),e.exit("htmlText"),t):n(C)}function V(C){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),q}function q(C){return qe(C)?Xe(e,de,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):de(C)}function de(C){return e.enter("htmlTextData"),u(C)}}const jy={name:"labelEnd",resolveAll:SB,resolveTo:_B,tokenize:jB},vB={tokenize:kB},bB={tokenize:NB},wB={tokenize:TB};function SB(e){let t=-1;const n=[];for(;++t<e.length;){const s=e[t][1];if(n.push(e[t]),s.type==="labelImage"||s.type==="labelLink"||s.type==="labelEnd"){const a=s.type==="labelImage"?4:2;s.type="data",t+=a}}return e.length!==n.length&&Ln(e,0,e.length,n),e}function _B(e,t){let n=e.length,s=0,a,l,u,d;for(;n--;)if(a=e[n][1],l){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[n][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(u){if(e[n][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(l=n,a.type!=="labelLink")){s=2;break}}else a.type==="labelEnd"&&(u=n);const h={type:e[l][1].type==="labelLink"?"link":"image",start:{...e[l][1].start},end:{...e[e.length-1][1].end}},m={type:"label",start:{...e[l][1].start},end:{...e[u][1].end}},p={type:"labelText",start:{...e[l+s+2][1].end},end:{...e[u-2][1].start}};return d=[["enter",h,t],["enter",m,t]],d=er(d,e.slice(l+1,l+s+3)),d=er(d,[["enter",p,t]]),d=er(d,Od(t.parser.constructs.insideSpan.null,e.slice(l+s+4,u-3),t)),d=er(d,[["exit",p,t],e[u-2],e[u-1],["exit",m,t]]),d=er(d,e.slice(u+1)),d=er(d,[["exit",h,t]]),Ln(e,l,e.length,d),e}function jB(e,t,n){const s=this;let a=s.events.length,l,u;for(;a--;)if((s.events[a][1].type==="labelImage"||s.events[a][1].type==="labelLink")&&!s.events[a][1]._balanced){l=s.events[a][1];break}return d;function d(v){return l?l._inactive?g(v):(u=s.parser.defined.includes(hr(s.sliceSerialize({start:l.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(v),e.exit("labelMarker"),e.exit("labelEnd"),h):n(v)}function h(v){return v===40?e.attempt(vB,p,u?p:g)(v):v===91?e.attempt(bB,p,u?m:g)(v):u?p(v):g(v)}function m(v){return e.attempt(wB,p,g)(v)}function p(v){return t(v)}function g(v){return l._balanced=!0,n(v)}}function kB(e,t,n){return s;function s(g){return e.enter("resource"),e.enter("resourceMarker"),e.consume(g),e.exit("resourceMarker"),a}function a(g){return ct(g)?Nl(e,l)(g):l(g)}function l(g){return g===41?p(g):qN(e,u,d,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(g)}function u(g){return ct(g)?Nl(e,h)(g):p(g)}function d(g){return n(g)}function h(g){return g===34||g===39||g===40?HN(e,m,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(g):p(g)}function m(g){return ct(g)?Nl(e,p)(g):p(g)}function p(g){return g===41?(e.enter("resourceMarker"),e.consume(g),e.exit("resourceMarker"),e.exit("resource"),t):n(g)}}function NB(e,t,n){const s=this;return a;function a(d){return $N.call(s,e,l,u,"reference","referenceMarker","referenceString")(d)}function l(d){return s.parser.defined.includes(hr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(d):n(d)}function u(d){return n(d)}}function TB(e,t,n){return s;function s(l){return e.enter("reference"),e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),a}function a(l){return l===93?(e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),e.exit("reference"),t):n(l)}}const EB={name:"labelStartImage",resolveAll:jy.resolveAll,tokenize:CB};function CB(e,t,n){const s=this;return a;function a(d){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(d),e.exit("labelImageMarker"),l}function l(d){return d===91?(e.enter("labelMarker"),e.consume(d),e.exit("labelMarker"),e.exit("labelImage"),u):n(d)}function u(d){return d===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(d):t(d)}}const AB={name:"labelStartLink",resolveAll:jy.resolveAll,tokenize:RB};function RB(e,t,n){const s=this;return a;function a(u){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(u),e.exit("labelMarker"),e.exit("labelLink"),l}function l(u){return u===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(u):t(u)}}const Fm={name:"lineEnding",tokenize:OB};function OB(e,t){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),Xe(e,t,"linePrefix")}}const Yu={name:"thematicBreak",tokenize:DB};function DB(e,t,n){let s=0,a;return l;function l(m){return e.enter("thematicBreak"),u(m)}function u(m){return a=m,d(m)}function d(m){return m===a?(e.enter("thematicBreakSequence"),h(m)):s>=3&&(m===null||Ne(m))?(e.exit("thematicBreak"),t(m)):n(m)}function h(m){return m===a?(e.consume(m),s++,h):(e.exit("thematicBreakSequence"),qe(m)?Xe(e,d,"whitespace")(m):d(m))}}const Sn={continuation:{tokenize:LB},exit:UB,name:"list",tokenize:zB},MB={partial:!0,tokenize:BB},PB={partial:!0,tokenize:IB};function zB(e,t,n){const s=this,a=s.events[s.events.length-1];let l=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,u=0;return d;function d(b){const w=s.containerState.type||(b===42||b===43||b===45?"listUnordered":"listOrdered");if(w==="listUnordered"?!s.containerState.marker||b===s.containerState.marker:ng(b)){if(s.containerState.type||(s.containerState.type=w,e.enter(w,{_container:!0})),w==="listUnordered")return e.enter("listItemPrefix"),b===42||b===45?e.check(Yu,n,m)(b):m(b);if(!s.interrupt||b===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),h(b)}return n(b)}function h(b){return ng(b)&&++u<10?(e.consume(b),h):(!s.interrupt||u<2)&&(s.containerState.marker?b===s.containerState.marker:b===41||b===46)?(e.exit("listItemValue"),m(b)):n(b)}function m(b){return e.enter("listItemMarker"),e.consume(b),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||b,e.check(tc,s.interrupt?n:p,e.attempt(MB,v,g))}function p(b){return s.containerState.initialBlankLine=!0,l++,v(b)}function g(b){return qe(b)?(e.enter("listItemPrefixWhitespace"),e.consume(b),e.exit("listItemPrefixWhitespace"),v):n(b)}function v(b){return s.containerState.size=l+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(b)}}function LB(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(tc,a,l);function a(d){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Xe(e,t,"listItemIndent",s.containerState.size+1)(d)}function l(d){return s.containerState.furtherBlankLines||!qe(d)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,u(d)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(PB,t,u)(d))}function u(d){return s.containerState._closeFlow=!0,s.interrupt=void 0,Xe(e,e.attempt(Sn,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(d)}}function IB(e,t,n){const s=this;return Xe(e,a,"listItemIndent",s.containerState.size+1);function a(l){const u=s.events[s.events.length-1];return u&&u[1].type==="listItemIndent"&&u[2].sliceSerialize(u[1],!0).length===s.containerState.size?t(l):n(l)}}function UB(e){e.exit(this.containerState.type)}function BB(e,t,n){const s=this;return Xe(e,a,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(l){const u=s.events[s.events.length-1];return!qe(l)&&u&&u[1].type==="listItemPrefixWhitespace"?t(l):n(l)}}const xS={name:"setextUnderline",resolveTo:VB,tokenize:FB};function VB(e,t){let n=e.length,s,a,l;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){s=n;break}e[n][1].type==="paragraph"&&(a=n)}else e[n][1].type==="content"&&e.splice(n,1),!l&&e[n][1].type==="definition"&&(l=n);const u={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",l?(e.splice(a,0,["enter",u,t]),e.splice(l+1,0,["exit",e[s][1],t]),e[s][1].end={...e[l][1].end}):e[s][1]=u,e.push(["exit",u,t]),e}function FB(e,t,n){const s=this;let a;return l;function l(m){let p=s.events.length,g;for(;p--;)if(s.events[p][1].type!=="lineEnding"&&s.events[p][1].type!=="linePrefix"&&s.events[p][1].type!=="content"){g=s.events[p][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||g)?(e.enter("setextHeadingLine"),a=m,u(m)):n(m)}function u(m){return e.enter("setextHeadingLineSequence"),d(m)}function d(m){return m===a?(e.consume(m),d):(e.exit("setextHeadingLineSequence"),qe(m)?Xe(e,h,"lineSuffix")(m):h(m))}function h(m){return m===null||Ne(m)?(e.exit("setextHeadingLine"),t(m)):n(m)}}const qB={tokenize:$B};function $B(e){const t=this,n=e.attempt(tc,s,e.attempt(this.parser.constructs.flowInitial,a,Xe(e,e.attempt(this.parser.constructs.flow,a,e.attempt(W8,a)),"linePrefix")));return n;function s(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function a(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const HB={resolveAll:KN()},GB=GN("string"),KB=GN("text");function GN(e){return{resolveAll:KN(e==="text"?YB:void 0),tokenize:t};function t(n){const s=this,a=this.parser.constructs[e],l=n.attempt(a,u,d);return u;function u(p){return m(p)?l(p):d(p)}function d(p){if(p===null){n.consume(p);return}return n.enter("data"),n.consume(p),h}function h(p){return m(p)?(n.exit("data"),l(p)):(n.consume(p),h)}function m(p){if(p===null)return!0;const g=a[p];let v=-1;if(g)for(;++v<g.length;){const b=g[v];if(!b.previous||b.previous.call(s,s.previous))return!0}return!1}}}function KN(e){return t;function t(n,s){let a=-1,l;for(;++a<=n.length;)l===void 0?n[a]&&n[a][1].type==="data"&&(l=a,a++):(!n[a]||n[a][1].type!=="data")&&(a!==l+2&&(n[l][1].end=n[a-1][1].end,n.splice(l+2,a-l-2),a=l+2),l=void 0);return e?e(n,s):n}}function YB(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const s=e[n-1][1],a=t.sliceStream(s);let l=a.length,u=-1,d=0,h;for(;l--;){const m=a[l];if(typeof m=="string"){for(u=m.length;m.charCodeAt(u-1)===32;)d++,u--;if(u)break;u=-1}else if(m===-2)h=!0,d++;else if(m!==-1){l++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(d=0),d){const m={type:n===e.length||h||d<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:l?u:s.start._bufferIndex+u,_index:s.start._index+l,line:s.end.line,column:s.end.column-d,offset:s.end.offset-d},end:{...s.end}};s.end={...m.start},s.start.offset===s.end.offset?Object.assign(s,m):(e.splice(n,0,["enter",m,t],["exit",m,t]),n+=2)}n++}return e}const WB={42:Sn,43:Sn,45:Sn,48:Sn,49:Sn,50:Sn,51:Sn,52:Sn,53:Sn,54:Sn,55:Sn,56:Sn,57:Sn,62:UN},XB={91:eB},JB={[-2]:Vm,[-1]:Vm,32:Vm},QB={35:aB,42:Yu,45:[xS,Yu],60:uB,61:xS,95:Yu,96:gS,126:gS},ZB={38:VN,92:BN},eV={[-5]:Fm,[-4]:Fm,[-3]:Fm,33:EB,38:VN,42:rg,60:[A8,yB],91:AB,92:[sB,BN],93:jy,95:rg,96:q8},tV={null:[rg,HB]},nV={null:[42,95]},rV={null:[]},sV=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:nV,contentInitial:XB,disable:rV,document:WB,flow:QB,flowInitial:JB,insideSpan:tV,string:ZB,text:eV},Symbol.toStringTag,{value:"Module"}));function iV(e,t,n){let s={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const a={},l=[];let u=[],d=[];const h={attempt:B(U),check:B(M),consume:R,enter:T,exit:D,interrupt:B(M,{interrupt:!0})},m={code:null,containerState:{},defineSkip:j,events:[],now:w,parser:e,previous:null,sliceSerialize:v,sliceStream:b,write:g};let p=t.tokenize.call(m,h);return t.resolveAll&&l.push(t),m;function g(Q){return u=er(u,Q),k(),u[u.length-1]!==null?[]:(P(t,0),m.events=Od(l,m.events,m),m.events)}function v(Q,G){return oV(b(Q),G)}function b(Q){return aV(u,Q)}function w(){const{_bufferIndex:Q,_index:G,line:he,column:se,offset:ae}=s;return{_bufferIndex:Q,_index:G,line:he,column:se,offset:ae}}function j(Q){a[Q.line]=Q.column,O()}function k(){let Q;for(;s._index<u.length;){const G=u[s._index];if(typeof G=="string")for(Q=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===Q&&s._bufferIndex<G.length;)N(G.charCodeAt(s._bufferIndex));else N(G)}}function N(Q){p=p(Q)}function R(Q){Ne(Q)?(s.line++,s.column=1,s.offset+=Q===-3?2:1,O()):Q!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===u[s._index].length&&(s._bufferIndex=-1,s._index++)),m.previous=Q}function T(Q,G){const he=G||{};return he.type=Q,he.start=w(),m.events.push(["enter",he,m]),d.push(he),he}function D(Q){const G=d.pop();return G.end=w(),m.events.push(["exit",G,m]),G}function U(Q,G){P(Q,G.from)}function M(Q,G){G.restore()}function B(Q,G){return he;function he(se,ae,L){let V,q,de,C;return Array.isArray(se)?J(se):"tokenize"in se?J([se]):z(se);function z(we){return Se;function Se(We){const He=We!==null&&we[We],Et=We!==null&&we.null,Ct=[...Array.isArray(He)?He:He?[He]:[],...Array.isArray(Et)?Et:Et?[Et]:[]];return J(Ct)(We)}}function J(we){return V=we,q=0,we.length===0?L:A(we[q])}function A(we){return Se;function Se(We){return C=H(),de=we,we.partial||(m.currentConstruct=we),we.name&&m.parser.constructs.disable.null.includes(we.name)?pe():we.tokenize.call(G?Object.assign(Object.create(m),G):m,h,oe,pe)(We)}}function oe(we){return Q(de,C),ae}function pe(we){return C.restore(),++q<V.length?A(V[q]):L}}}function P(Q,G){Q.resolveAll&&!l.includes(Q)&&l.push(Q),Q.resolve&&Ln(m.events,G,m.events.length-G,Q.resolve(m.events.slice(G),m)),Q.resolveTo&&(m.events=Q.resolveTo(m.events,m))}function H(){const Q=w(),G=m.previous,he=m.currentConstruct,se=m.events.length,ae=Array.from(d);return{from:se,restore:L};function L(){s=Q,m.previous=G,m.currentConstruct=he,m.events.length=se,d=ae,O()}}function O(){s.line in a&&s.column<2&&(s.column=a[s.line],s.offset+=a[s.line]-1)}}function aV(e,t){const n=t.start._index,s=t.start._bufferIndex,a=t.end._index,l=t.end._bufferIndex;let u;if(n===a)u=[e[n].slice(s,l)];else{if(u=e.slice(n,a),s>-1){const d=u[0];typeof d=="string"?u[0]=d.slice(s):u.shift()}l>0&&u.push(e[a].slice(0,l))}return u}function oV(e,t){let n=-1;const s=[];let a;for(;++n<e.length;){const l=e[n];let u;if(typeof l=="string")u=l;else switch(l){case-5:{u="\r";break}case-4:{u=`
138
183
  `;break}case-3:{u=`\r
139
184
  `;break}case-2:{u=t?" ":" ";break}case-1:{if(!t&&a)continue;u=" ";break}default:u=String.fromCharCode(l)}a=l===-2,s.push(u)}return s.join("")}function lV(e){const s={constructs:LN([sV,...(e||{}).extensions||[]]),content:a(_8),defined:[],document:a(k8),flow:a(qB),lazy:{},string:a(GB),text:a(KB)};return s;function a(l){return u;function u(d){return iV(s,l,d)}}}function cV(e){for(;!FN(e););return e}const vS=/[\0\t\n\r]/g;function uV(){let e=1,t="",n=!0,s;return a;function a(l,u,d){const h=[];let m,p,g,v,b;for(l=t+(typeof l=="string"?l.toString():new TextDecoder(u||void 0).decode(l)),g=0,t="",n&&(l.charCodeAt(0)===65279&&g++,n=void 0);g<l.length;){if(vS.lastIndex=g,m=vS.exec(l),v=m&&m.index!==void 0?m.index:l.length,b=l.charCodeAt(v),!m){t=l.slice(g);break}if(b===10&&g===v&&s)h.push(-3),s=void 0;else switch(s&&(h.push(-5),s=void 0),g<v&&(h.push(l.slice(g,v)),e+=v-g),b){case 0:{h.push(65533),e++;break}case 9:{for(p=Math.ceil(e/4)*4,h.push(-2);e++<p;)h.push(-1);break}case 10:{h.push(-4),e=1;break}default:s=!0,e=1}g=v+1}return d&&(s&&h.push(-5),t&&h.push(t),h.push(null)),h}}const dV=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function fV(e){return e.replace(dV,hV)}function hV(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const a=n.charCodeAt(1),l=a===120||a===88;return IN(n.slice(l?2:1),l?16:10)}return _y(n)||e}const YN={}.hasOwnProperty;function mV(e,t,n){return typeof t!="string"&&(n=t,t=void 0),pV(n)(cV(lV(n).document().write(uV()(e,t,!0))))}function pV(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l(ei),autolinkProtocol:H,autolinkEmail:H,atxHeading:l(zr),blockQuote:l(Et),characterEscape:H,characterReference:H,codeFenced:l(Ct),codeFencedFenceInfo:u,codeFencedFenceMeta:u,codeIndented:l(Ct,u),codeText:l(Un,u),codeTextData:H,data:H,codeFlowValue:H,definition:l(Pr),definitionDestinationString:u,definitionLabelString:u,definitionTitleString:u,emphasis:l(Bn),hardBreakEscape:l(gr),hardBreakTrailing:l(gr),htmlFlow:l(ho,u),htmlFlowData:H,htmlText:l(ho,u),htmlTextData:H,image:l(yr),label:u,link:l(ei),listItem:l(us),listItemValue:v,listOrdered:l(Vn,g),listUnordered:l(Vn),paragraph:l(mo),reference:A,referenceString:u,resourceDestinationString:u,resourceTitleString:u,setextHeading:l(zr),strong:l(Vi),thematicBreak:l(po)},exit:{atxHeading:h(),atxHeadingSequence:U,autolink:h(),autolinkEmail:He,autolinkProtocol:We,blockQuote:h(),characterEscapeValue:O,characterReferenceMarkerHexadecimal:pe,characterReferenceMarkerNumeric:pe,characterReferenceValue:we,characterReference:Se,codeFenced:h(k),codeFencedFence:j,codeFencedFenceInfo:b,codeFencedFenceMeta:w,codeFlowValue:O,codeIndented:h(N),codeText:h(ae),codeTextData:O,data:O,definition:h(),definitionDestinationString:D,definitionLabelString:R,definitionTitleString:T,emphasis:h(),hardBreakEscape:h(G),hardBreakTrailing:h(G),htmlFlow:h(he),htmlFlowData:O,htmlText:h(se),htmlTextData:O,image:h(V),label:de,labelText:q,lineEnding:Q,link:h(L),listItem:h(),listOrdered:h(),listUnordered:h(),paragraph:h(),referenceString:oe,resourceDestinationString:C,resourceTitleString:z,resource:J,setextHeading:h(P),setextHeadingLineSequence:B,setextHeadingText:M,strong:h(),thematicBreak:h()}};WN(t,(e||{}).mdastExtensions||[]);const n={};return s;function s(te){let fe={type:"root",children:[]};const Ee={stack:[fe],tokenStack:[],config:t,enter:d,exit:m,buffer:u,resume:p,data:n},Ue=[];let Je=-1;for(;++Je<te.length;)if(te[Je][1].type==="listOrdered"||te[Je][1].type==="listUnordered")if(te[Je][0]==="enter")Ue.push(Je);else{const cn=Ue.pop();Je=a(te,cn,Je)}for(Je=-1;++Je<te.length;){const cn=t[te[Je][0]];YN.call(cn,te[Je][1].type)&&cn[te[Je][1].type].call(Object.assign({sliceSerialize:te[Je][2].sliceSerialize},Ee),te[Je][1])}if(Ee.tokenStack.length>0){const cn=Ee.tokenStack[Ee.tokenStack.length-1];(cn[1]||bS).call(Ee,void 0,cn[0])}for(fe.position={start:zs(te.length>0?te[0][1].start:{line:1,column:1,offset:0}),end:zs(te.length>0?te[te.length-2][1].end:{line:1,column:1,offset:0})},Je=-1;++Je<t.transforms.length;)fe=t.transforms[Je](fe)||fe;return fe}function a(te,fe,Ee){let Ue=fe-1,Je=-1,cn=!1,rr,Yt,At,rn;for(;++Ue<=Ee;){const nt=te[Ue];switch(nt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{nt[0]==="enter"?Je++:Je--,rn=void 0;break}case"lineEndingBlank":{nt[0]==="enter"&&(rr&&!rn&&!Je&&!At&&(At=Ue),rn=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:rn=void 0}if(!Je&&nt[0]==="enter"&&nt[1].type==="listItemPrefix"||Je===-1&&nt[0]==="exit"&&(nt[1].type==="listUnordered"||nt[1].type==="listOrdered")){if(rr){let sr=Ue;for(Yt=void 0;sr--;){const jn=te[sr];if(jn[1].type==="lineEnding"||jn[1].type==="lineEndingBlank"){if(jn[0]==="exit")continue;Yt&&(te[Yt][1].type="lineEndingBlank",cn=!0),jn[1].type="lineEnding",Yt=sr}else if(!(jn[1].type==="linePrefix"||jn[1].type==="blockQuotePrefix"||jn[1].type==="blockQuotePrefixWhitespace"||jn[1].type==="blockQuoteMarker"||jn[1].type==="listItemIndent"))break}At&&(!Yt||At<Yt)&&(rr._spread=!0),rr.end=Object.assign({},Yt?te[Yt][1].start:nt[1].end),te.splice(Yt||Ue,0,["exit",rr,nt[2]]),Ue++,Ee++}if(nt[1].type==="listItemPrefix"){const sr={type:"listItem",_spread:!1,start:Object.assign({},nt[1].start),end:void 0};rr=sr,te.splice(Ue,0,["enter",sr,nt[2]]),Ue++,Ee++,At=void 0,rn=!0}}}return te[fe][1]._spread=cn,Ee}function l(te,fe){return Ee;function Ee(Ue){d.call(this,te(Ue),Ue),fe&&fe.call(this,Ue)}}function u(){this.stack.push({type:"fragment",children:[]})}function d(te,fe,Ee){this.stack[this.stack.length-1].children.push(te),this.stack.push(te),this.tokenStack.push([fe,Ee||void 0]),te.position={start:zs(fe.start),end:void 0}}function h(te){return fe;function fe(Ee){te&&te.call(this,Ee),m.call(this,Ee)}}function m(te,fe){const Ee=this.stack.pop(),Ue=this.tokenStack.pop();if(Ue)Ue[0].type!==te.type&&(fe?fe.call(this,te,Ue[0]):(Ue[1]||bS).call(this,te,Ue[0]));else throw new Error("Cannot close `"+te.type+"` ("+kl({start:te.start,end:te.end})+"): it’s not open");Ee.position.end=zs(te.end)}function p(){return Sy(this.stack.pop())}function g(){this.data.expectingFirstListItemValue=!0}function v(te){if(this.data.expectingFirstListItemValue){const fe=this.stack[this.stack.length-2];fe.start=Number.parseInt(this.sliceSerialize(te),10),this.data.expectingFirstListItemValue=void 0}}function b(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.lang=te}function w(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.meta=te}function j(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function k(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.value=te.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function N(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.value=te.replace(/(\r?\n|\r)$/g,"")}function R(te){const fe=this.resume(),Ee=this.stack[this.stack.length-1];Ee.label=fe,Ee.identifier=hr(this.sliceSerialize(te)).toLowerCase()}function T(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.title=te}function D(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.url=te}function U(te){const fe=this.stack[this.stack.length-1];if(!fe.depth){const Ee=this.sliceSerialize(te).length;fe.depth=Ee}}function M(){this.data.setextHeadingSlurpLineEnding=!0}function B(te){const fe=this.stack[this.stack.length-1];fe.depth=this.sliceSerialize(te).codePointAt(0)===61?1:2}function P(){this.data.setextHeadingSlurpLineEnding=void 0}function H(te){const Ee=this.stack[this.stack.length-1].children;let Ue=Ee[Ee.length-1];(!Ue||Ue.type!=="text")&&(Ue=Kt(),Ue.position={start:zs(te.start),end:void 0},Ee.push(Ue)),this.stack.push(Ue)}function O(te){const fe=this.stack.pop();fe.value+=this.sliceSerialize(te),fe.position.end=zs(te.end)}function Q(te){const fe=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Ee=fe.children[fe.children.length-1];Ee.position.end=zs(te.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(fe.type)&&(H.call(this,te),O.call(this,te))}function G(){this.data.atHardBreak=!0}function he(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.value=te}function se(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.value=te}function ae(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.value=te}function L(){const te=this.stack[this.stack.length-1];if(this.data.inReference){const fe=this.data.referenceType||"shortcut";te.type+="Reference",te.referenceType=fe,delete te.url,delete te.title}else delete te.identifier,delete te.label;this.data.referenceType=void 0}function V(){const te=this.stack[this.stack.length-1];if(this.data.inReference){const fe=this.data.referenceType||"shortcut";te.type+="Reference",te.referenceType=fe,delete te.url,delete te.title}else delete te.identifier,delete te.label;this.data.referenceType=void 0}function q(te){const fe=this.sliceSerialize(te),Ee=this.stack[this.stack.length-2];Ee.label=fV(fe),Ee.identifier=hr(fe).toLowerCase()}function de(){const te=this.stack[this.stack.length-1],fe=this.resume(),Ee=this.stack[this.stack.length-1];if(this.data.inReference=!0,Ee.type==="link"){const Ue=te.children;Ee.children=Ue}else Ee.alt=fe}function C(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.url=te}function z(){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.title=te}function J(){this.data.inReference=void 0}function A(){this.data.referenceType="collapsed"}function oe(te){const fe=this.resume(),Ee=this.stack[this.stack.length-1];Ee.label=fe,Ee.identifier=hr(this.sliceSerialize(te)).toLowerCase(),this.data.referenceType="full"}function pe(te){this.data.characterReferenceType=te.type}function we(te){const fe=this.sliceSerialize(te),Ee=this.data.characterReferenceType;let Ue;Ee?(Ue=IN(fe,Ee==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ue=_y(fe);const Je=this.stack[this.stack.length-1];Je.value+=Ue}function Se(te){const fe=this.stack.pop();fe.position.end=zs(te.end)}function We(te){O.call(this,te);const fe=this.stack[this.stack.length-1];fe.url=this.sliceSerialize(te)}function He(te){O.call(this,te);const fe=this.stack[this.stack.length-1];fe.url="mailto:"+this.sliceSerialize(te)}function Et(){return{type:"blockquote",children:[]}}function Ct(){return{type:"code",lang:null,meta:null,value:""}}function Un(){return{type:"inlineCode",value:""}}function Pr(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Bn(){return{type:"emphasis",children:[]}}function zr(){return{type:"heading",depth:0,children:[]}}function gr(){return{type:"break"}}function ho(){return{type:"html",value:""}}function yr(){return{type:"image",title:null,url:"",alt:null}}function ei(){return{type:"link",title:null,url:"",children:[]}}function Vn(te){return{type:"list",ordered:te.type==="listOrdered",start:null,spread:te._spread,children:[]}}function us(te){return{type:"listItem",spread:te._spread,checked:null,children:[]}}function mo(){return{type:"paragraph",children:[]}}function Vi(){return{type:"strong",children:[]}}function Kt(){return{type:"text",value:""}}function po(){return{type:"thematicBreak"}}}function zs(e){return{line:e.line,column:e.column,offset:e.offset}}function WN(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?WN(e,s):gV(e,s)}}function gV(e,t){let n;for(n in t)if(YN.call(t,n))switch(n){case"canContainEols":{const s=t[n];s&&e[n].push(...s);break}case"transforms":{const s=t[n];s&&e[n].push(...s);break}case"enter":case"exit":{const s=t[n];s&&Object.assign(e[n],s);break}}}function bS(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+kl({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+kl({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+kl({start:t.start,end:t.end})+") is still open")}function yV(e){const t=this;t.parser=n;function n(s){return mV(s,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function xV(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function vV(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
@@ -161,39 +206,4 @@ Trung Le`,value:e.signature||"",onChange:d=>t({signature:d.target.value})})]}),o
161
206
  `))+1))}const u="#".repeat(a),d=n.enter("headingAtx"),h=n.enter("phrasing");l.move(u+" ");let m=n.containerPhrasing(e,{before:"# ",after:`
162
207
  `,...l.current()});return/^[\t ]/.test(m)&&(m=Hl(m.charCodeAt(0))+m.slice(1)),m=m?u+" "+m:u,n.options.closeAtx&&(m+=" "+u),h(),d(),m}cT.peek=IF;function cT(e){return e.value||""}function IF(){return"<"}uT.peek=UF;function uT(e,t,n,s){const a=Ry(n),l=a==='"'?"Quote":"Apostrophe",u=n.enter("image");let d=n.enter("label");const h=n.createTracker(s);let m=h.move("![");return m+=h.move(n.safe(e.alt,{before:m,after:"]",...h.current()})),m+=h.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=n.enter("destinationLiteral"),m+=h.move("<"),m+=h.move(n.safe(e.url,{before:m,after:">",...h.current()})),m+=h.move(">")):(d=n.enter("destinationRaw"),m+=h.move(n.safe(e.url,{before:m,after:e.title?" ":")",...h.current()}))),d(),e.title&&(d=n.enter(`title${l}`),m+=h.move(" "+a),m+=h.move(n.safe(e.title,{before:m,after:a,...h.current()})),m+=h.move(a),d()),m+=h.move(")"),u(),m}function UF(){return"!"}dT.peek=BF;function dT(e,t,n,s){const a=e.referenceType,l=n.enter("imageReference");let u=n.enter("label");const d=n.createTracker(s);let h=d.move("![");const m=n.safe(e.alt,{before:h,after:"]",...d.current()});h+=d.move(m+"]["),u();const p=n.stack;n.stack=[],u=n.enter("reference");const g=n.safe(n.associationId(e),{before:h,after:"]",...d.current()});return u(),n.stack=p,l(),a==="full"||!m||m!==g?h+=d.move(g+"]"):a==="shortcut"?h=h.slice(0,-1):h+=d.move("]"),h}function BF(){return"!"}fT.peek=VF;function fT(e,t,n){let s=e.value||"",a="`",l=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(s);)a+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++l<n.unsafe.length;){const u=n.unsafe[l],d=n.compilePattern(u);let h;if(u.atBreak)for(;h=d.exec(s);){let m=h.index;s.charCodeAt(m)===10&&s.charCodeAt(m-1)===13&&m--,s=s.slice(0,m)+" "+s.slice(h.index+1)}}return a+s+a}function VF(){return"`"}function hT(e,t){const n=Sy(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}mT.peek=FF;function mT(e,t,n,s){const a=Ry(n),l=a==='"'?"Quote":"Apostrophe",u=n.createTracker(s);let d,h;if(hT(e,n)){const p=n.stack;n.stack=[],d=n.enter("autolink");let g=u.move("<");return g+=u.move(n.containerPhrasing(e,{before:g,after:">",...u.current()})),g+=u.move(">"),d(),n.stack=p,g}d=n.enter("link"),h=n.enter("label");let m=u.move("[");return m+=u.move(n.containerPhrasing(e,{before:m,after:"](",...u.current()})),m+=u.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=n.enter("destinationLiteral"),m+=u.move("<"),m+=u.move(n.safe(e.url,{before:m,after:">",...u.current()})),m+=u.move(">")):(h=n.enter("destinationRaw"),m+=u.move(n.safe(e.url,{before:m,after:e.title?" ":")",...u.current()}))),h(),e.title&&(h=n.enter(`title${l}`),m+=u.move(" "+a),m+=u.move(n.safe(e.title,{before:m,after:a,...u.current()})),m+=u.move(a),h()),m+=u.move(")"),d(),m}function FF(e,t,n){return hT(e,n)?"<":"["}pT.peek=qF;function pT(e,t,n,s){const a=e.referenceType,l=n.enter("linkReference");let u=n.enter("label");const d=n.createTracker(s);let h=d.move("[");const m=n.containerPhrasing(e,{before:h,after:"]",...d.current()});h+=d.move(m+"]["),u();const p=n.stack;n.stack=[],u=n.enter("reference");const g=n.safe(n.associationId(e),{before:h,after:"]",...d.current()});return u(),n.stack=p,l(),a==="full"||!m||m!==g?h+=d.move(g+"]"):a==="shortcut"?h=h.slice(0,-1):h+=d.move("]"),h}function qF(){return"["}function Oy(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function $F(e){const t=Oy(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function HF(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function gT(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function GF(e,t,n,s){const a=n.enter("list"),l=n.bulletCurrent;let u=e.ordered?HF(n):Oy(n);const d=e.ordered?u==="."?")":".":$F(n);let h=t&&n.bulletLastUsed?u===n.bulletLastUsed:!1;if(!e.ordered){const p=e.children?e.children[0]:void 0;if((u==="*"||u==="-")&&p&&(!p.children||!p.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(h=!0),gT(n)===u&&p){let g=-1;for(;++g<e.children.length;){const v=e.children[g];if(v&&v.type==="listItem"&&v.children&&v.children[0]&&v.children[0].type==="thematicBreak"){h=!0;break}}}}h&&(u=d),n.bulletCurrent=u;const m=n.containerFlow(e,s);return n.bulletLastUsed=u,n.bulletCurrent=l,a(),m}function KF(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function YF(e,t,n,s){const a=KF(n);let l=n.bulletCurrent||Oy(n);t&&t.type==="list"&&t.ordered&&(l=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+l);let u=l.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(u=Math.ceil(u/4)*4);const d=n.createTracker(s);d.move(l+" ".repeat(u-l.length)),d.shift(u);const h=n.enter("listItem"),m=n.indentLines(n.containerFlow(e,d.current()),p);return h(),m;function p(g,v,b){return v?(b?"":" ".repeat(u))+g:(b?l:l+" ".repeat(u-l.length))+g}}function WF(e,t,n,s){const a=n.enter("paragraph"),l=n.enter("phrasing"),u=n.containerPhrasing(e,s);return l(),a(),u}const XF=Md(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function JF(e,t,n,s){return(e.children.some(function(u){return XF(u)})?n.containerPhrasing:n.containerFlow).call(n,e,s)}function QF(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}yT.peek=ZF;function yT(e,t,n,s){const a=QF(n),l=n.enter("strong"),u=n.createTracker(s),d=u.move(a+a);let h=u.move(n.containerPhrasing(e,{after:a,before:d,...u.current()}));const m=h.charCodeAt(0),p=pd(s.before.charCodeAt(s.before.length-1),m,a);p.inside&&(h=Hl(m)+h.slice(1));const g=h.charCodeAt(h.length-1),v=pd(s.after.charCodeAt(0),g,a);v.inside&&(h=h.slice(0,-1)+Hl(g));const b=u.move(a+a);return l(),n.attentionEncodeSurroundingInfo={after:v.outside,before:p.outside},d+h+b}function ZF(e,t,n){return n.options.strong||"*"}function e7(e,t,n,s){return n.safe(e.value,s)}function t7(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function n7(e,t,n){const s=(gT(n)+(n.options.ruleSpaces?" ":"")).repeat(t7(n));return n.options.ruleSpaces?s.slice(0,-1):s}const xT={blockquote:kF,break:US,code:RF,definition:DF,emphasis:lT,hardBreak:US,heading:LF,html:cT,image:uT,imageReference:dT,inlineCode:fT,link:mT,linkReference:pT,list:GF,listItem:YF,paragraph:WF,root:JF,strong:yT,text:e7,thematicBreak:n7};function r7(){return{enter:{table:s7,tableData:BS,tableHeader:BS,tableRow:a7},exit:{codeText:o7,table:i7,tableData:ep,tableHeader:ep,tableRow:ep}}}function s7(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function i7(e){this.exit(e),this.data.inTable=void 0}function a7(e){this.enter({type:"tableRow",children:[]},e)}function ep(e){this.exit(e)}function BS(e){this.enter({type:"tableCell",children:[]},e)}function o7(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,l7));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function l7(e,t){return t==="|"?t:e}function c7(e){const t=e||{},n=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,l=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
163
208
  `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:v,table:u,tableCell:h,tableRow:d}};function u(b,w,j,k){return m(p(b,j,k),b.align)}function d(b,w,j,k){const N=g(b,j,k),R=m([N]);return R.slice(0,R.indexOf(`
164
- `))}function h(b,w,j,k){const N=j.enter("tableCell"),R=j.enter("phrasing"),T=j.containerPhrasing(b,{...k,before:l,after:l});return R(),N(),T}function m(b,w){return _F(b,{align:w,alignDelimiters:s,padding:n,stringLength:a})}function p(b,w,j){const k=b.children;let N=-1;const R=[],T=w.enter("table");for(;++N<k.length;)R[N]=g(k[N],w,j);return T(),R}function g(b,w,j){const k=b.children;let N=-1;const R=[],T=w.enter("tableRow");for(;++N<k.length;)R[N]=h(k[N],b,w,j);return T(),R}function v(b,w,j){let k=xT.inlineCode(b,w,j);return j.stack.includes("tableCell")&&(k=k.replace(/\|/g,"\\$&")),k}}function u7(){return{exit:{taskListCheckValueChecked:VS,taskListCheckValueUnchecked:VS,paragraph:f7}}}function d7(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:h7}}}function VS(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function f7(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const s=n.children[0];if(s&&s.type==="text"){const a=t.children;let l=-1,u;for(;++l<a.length;){const d=a[l];if(d.type==="paragraph"){u=d;break}}u===n&&(s.value=s.value.slice(1),s.value.length===0?n.children.shift():n.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,n.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function h7(e,t,n,s){const a=e.children[0],l=typeof e.checked=="boolean"&&a&&a.type==="paragraph",u="["+(e.checked?"x":" ")+"] ",d=n.createTracker(s);l&&d.move(u);let h=xT.listItem(e,t,n,{...s,...d.current()});return l&&(h=h.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),h;function m(p){return p+u}}function m7(){return[G9(),hF(),yF(),r7(),u7()]}function p7(e){return{extensions:[K9(),mF(e),xF(),c7(e),d7()]}}const g7={tokenize:S7,partial:!0},vT={tokenize:_7,partial:!0},bT={tokenize:j7,partial:!0},wT={tokenize:k7,partial:!0},y7={tokenize:N7,partial:!0},ST={name:"wwwAutolink",tokenize:b7,previous:jT},_T={name:"protocolAutolink",tokenize:w7,previous:kT},cs={name:"emailAutolink",tokenize:v7,previous:NT},Mr={};function x7(){return{text:Mr}}let _i=48;for(;_i<123;)Mr[_i]=cs,_i++,_i===58?_i=65:_i===91&&(_i=97);Mr[43]=cs;Mr[45]=cs;Mr[46]=cs;Mr[95]=cs;Mr[72]=[cs,_T];Mr[104]=[cs,_T];Mr[87]=[cs,ST];Mr[119]=[cs,ST];function v7(e,t,n){const s=this;let a,l;return u;function u(g){return!lg(g)||!NT.call(s,s.previous)||Dy(s.events)?n(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),d(g))}function d(g){return lg(g)?(e.consume(g),d):g===64?(e.consume(g),h):n(g)}function h(g){return g===46?e.check(y7,p,m)(g):g===45||g===95||on(g)?(l=!0,e.consume(g),h):p(g)}function m(g){return e.consume(g),a=!0,h}function p(g){return l&&a&&dn(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):n(g)}}function b7(e,t,n){const s=this;return a;function a(u){return u!==87&&u!==119||!jT.call(s,s.previous)||Dy(s.events)?n(u):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(g7,e.attempt(vT,e.attempt(bT,l),n),n)(u))}function l(u){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(u)}}function w7(e,t,n){const s=this;let a="",l=!1;return u;function u(g){return(g===72||g===104)&&kT.call(s,s.previous)&&!Dy(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(g),e.consume(g),d):n(g)}function d(g){if(dn(g)&&a.length<5)return a+=String.fromCodePoint(g),e.consume(g),d;if(g===58){const v=a.toLowerCase();if(v==="http"||v==="https")return e.consume(g),h}return n(g)}function h(g){return g===47?(e.consume(g),l?m:(l=!0,h)):n(g)}function m(g){return g===null||fd(g)||ct(g)||Ii(g)||Rd(g)?n(g):e.attempt(vT,e.attempt(bT,p),n)(g)}function p(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function S7(e,t,n){let s=0;return a;function a(u){return(u===87||u===119)&&s<3?(s++,e.consume(u),a):u===46&&s===3?(e.consume(u),l):n(u)}function l(u){return u===null?n(u):t(u)}}function _7(e,t,n){let s,a,l;return u;function u(m){return m===46||m===95?e.check(wT,h,d)(m):m===null||ct(m)||Ii(m)||m!==45&&Rd(m)?h(m):(l=!0,e.consume(m),u)}function d(m){return m===95?s=!0:(a=s,s=void 0),e.consume(m),u}function h(m){return a||s||!l?n(m):t(m)}}function j7(e,t){let n=0,s=0;return a;function a(u){return u===40?(n++,e.consume(u),a):u===41&&s<n?l(u):u===33||u===34||u===38||u===39||u===41||u===42||u===44||u===46||u===58||u===59||u===60||u===63||u===93||u===95||u===126?e.check(wT,t,l)(u):u===null||ct(u)||Ii(u)?t(u):(e.consume(u),a)}function l(u){return u===41&&s++,e.consume(u),a}}function k7(e,t,n){return s;function s(d){return d===33||d===34||d===39||d===41||d===42||d===44||d===46||d===58||d===59||d===63||d===95||d===126?(e.consume(d),s):d===38?(e.consume(d),l):d===93?(e.consume(d),a):d===60||d===null||ct(d)||Ii(d)?t(d):n(d)}function a(d){return d===null||d===40||d===91||ct(d)||Ii(d)?t(d):s(d)}function l(d){return dn(d)?u(d):n(d)}function u(d){return d===59?(e.consume(d),s):dn(d)?(e.consume(d),u):n(d)}}function N7(e,t,n){return s;function s(l){return e.consume(l),a}function a(l){return on(l)?n(l):t(l)}}function jT(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ct(e)}function kT(e){return!dn(e)}function NT(e){return!(e===47||lg(e))}function lg(e){return e===43||e===45||e===46||e===95||on(e)}function Dy(e){let t=e.length,n=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){n=!0;break}if(s._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const T7={tokenize:P7,partial:!0};function E7(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:O7,continuation:{tokenize:D7},exit:M7}},text:{91:{name:"gfmFootnoteCall",tokenize:R7},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:C7,resolveTo:A7}}}}function C7(e,t,n){const s=this;let a=s.events.length;const l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u;for(;a--;){const h=s.events[a][1];if(h.type==="labelImage"){u=h;break}if(h.type==="gfmFootnoteCall"||h.type==="labelLink"||h.type==="label"||h.type==="image"||h.type==="link")break}return d;function d(h){if(!u||!u._balanced)return n(h);const m=hr(s.sliceSerialize({start:u.end,end:s.now()}));return m.codePointAt(0)!==94||!l.includes(m.slice(1))?n(h):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),t(h))}}function A7(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const l={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},u={type:"chunkString",contentType:"string",start:Object.assign({},l.start),end:Object.assign({},l.end)},d=[e[n+1],e[n+2],["enter",s,t],e[n+3],e[n+4],["enter",a,t],["exit",a,t],["enter",l,t],["enter",u,t],["exit",u,t],["exit",l,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(n,e.length-n+1,...d),e}function R7(e,t,n){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let l=0,u;return d;function d(g){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),h}function h(g){return g!==94?n(g):(e.enter("gfmFootnoteCallMarker"),e.consume(g),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",m)}function m(g){if(l>999||g===93&&!u||g===null||g===91||ct(g))return n(g);if(g===93){e.exit("chunkString");const v=e.exit("gfmFootnoteCallString");return a.includes(hr(s.sliceSerialize(v)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(g)}return ct(g)||(u=!0),l++,e.consume(g),g===92?p:m}function p(g){return g===91||g===92||g===93?(e.consume(g),l++,m):m(g)}}function O7(e,t,n){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let l,u=0,d;return h;function h(w){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(w),e.exit("gfmFootnoteDefinitionLabelMarker"),m}function m(w){return w===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(w),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",p):n(w)}function p(w){if(u>999||w===93&&!d||w===null||w===91||ct(w))return n(w);if(w===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return l=hr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(w),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),v}return ct(w)||(d=!0),u++,e.consume(w),w===92?g:p}function g(w){return w===91||w===92||w===93?(e.consume(w),u++,p):p(w)}function v(w){return w===58?(e.enter("definitionMarker"),e.consume(w),e.exit("definitionMarker"),a.includes(l)||a.push(l),Xe(e,b,"gfmFootnoteDefinitionWhitespace")):n(w)}function b(w){return t(w)}}function D7(e,t,n){return e.check(tc,t,e.attempt(T7,t,n))}function M7(e){e.exit("gfmFootnoteDefinition")}function P7(e,t,n){const s=this;return Xe(e,a,"gfmFootnoteDefinitionIndent",5);function a(l){const u=s.events[s.events.length-1];return u&&u[1].type==="gfmFootnoteDefinitionIndent"&&u[2].sliceSerialize(u[1],!0).length===4?t(l):n(l)}}function z7(e){let n=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:l,resolveAll:a};return n==null&&(n=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(u,d){let h=-1;for(;++h<u.length;)if(u[h][0]==="enter"&&u[h][1].type==="strikethroughSequenceTemporary"&&u[h][1]._close){let m=h;for(;m--;)if(u[m][0]==="exit"&&u[m][1].type==="strikethroughSequenceTemporary"&&u[m][1]._open&&u[h][1].end.offset-u[h][1].start.offset===u[m][1].end.offset-u[m][1].start.offset){u[h][1].type="strikethroughSequence",u[m][1].type="strikethroughSequence";const p={type:"strikethrough",start:Object.assign({},u[m][1].start),end:Object.assign({},u[h][1].end)},g={type:"strikethroughText",start:Object.assign({},u[m][1].end),end:Object.assign({},u[h][1].start)},v=[["enter",p,d],["enter",u[m][1],d],["exit",u[m][1],d],["enter",g,d]],b=d.parser.constructs.insideSpan.null;b&&Ln(v,v.length,0,Od(b,u.slice(m+1,h),d)),Ln(v,v.length,0,[["exit",g,d],["enter",u[h][1],d],["exit",u[h][1],d],["exit",p,d]]),Ln(u,m-1,h-m+3,v),h=m+v.length-2;break}}for(h=-1;++h<u.length;)u[h][1].type==="strikethroughSequenceTemporary"&&(u[h][1].type="data");return u}function l(u,d,h){const m=this.previous,p=this.events;let g=0;return v;function v(w){return m===126&&p[p.length-1][1].type!=="characterEscape"?h(w):(u.enter("strikethroughSequenceTemporary"),b(w))}function b(w){const j=no(m);if(w===126)return g>1?h(w):(u.consume(w),g++,b);if(g<2&&!n)return h(w);const k=u.exit("strikethroughSequenceTemporary"),N=no(w);return k._open=!N||N===2&&!!j,k._close=!j||j===2&&!!N,d(w)}}}class L7{constructor(){this.map=[]}add(t,n,s){I7(this,t,n,s)}consume(t){if(this.map.sort(function(l,u){return l[0]-u[0]}),this.map.length===0)return;let n=this.map.length;const s=[];for(;n>0;)n-=1,s.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const l of a)t.push(l);a=s.pop()}this.map.length=0}}function I7(e,t,n,s){let a=0;if(!(n===0&&s.length===0)){for(;a<e.map.length;){if(e.map[a][0]===t){e.map[a][1]+=n,e.map[a][2].push(...s);return}a+=1}e.map.push([t,n,s])}}function U7(e,t){let n=!1;const s=[];for(;t<e.length;){const a=e[t];if(n){if(a[0]==="enter")a[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(a[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const l=s.length-1;s[l]=s[l]==="left"?"center":"right"}}else if(a[1].type==="tableDelimiterRow")break}else a[0]==="enter"&&a[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return s}function B7(){return{flow:{null:{name:"table",tokenize:V7,resolveAll:F7}}}}function V7(e,t,n){const s=this;let a=0,l=0,u;return d;function d(O){let Q=s.events.length-1;for(;Q>-1;){const se=s.events[Q][1].type;if(se==="lineEnding"||se==="linePrefix")Q--;else break}const G=Q>-1?s.events[Q][1].type:null,he=G==="tableHead"||G==="tableRow"?M:h;return he===M&&s.parser.lazy[s.now().line]?n(O):he(O)}function h(O){return e.enter("tableHead"),e.enter("tableRow"),m(O)}function m(O){return O===124||(u=!0,l+=1),p(O)}function p(O){return O===null?n(O):Ne(O)?l>1?(l=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(O),e.exit("lineEnding"),b):n(O):qe(O)?Xe(e,p,"whitespace")(O):(l+=1,u&&(u=!1,a+=1),O===124?(e.enter("tableCellDivider"),e.consume(O),e.exit("tableCellDivider"),u=!0,p):(e.enter("data"),g(O)))}function g(O){return O===null||O===124||ct(O)?(e.exit("data"),p(O)):(e.consume(O),O===92?v:g)}function v(O){return O===92||O===124?(e.consume(O),g):g(O)}function b(O){return s.interrupt=!1,s.parser.lazy[s.now().line]?n(O):(e.enter("tableDelimiterRow"),u=!1,qe(O)?Xe(e,w,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(O):w(O))}function w(O){return O===45||O===58?k(O):O===124?(u=!0,e.enter("tableCellDivider"),e.consume(O),e.exit("tableCellDivider"),j):U(O)}function j(O){return qe(O)?Xe(e,k,"whitespace")(O):k(O)}function k(O){return O===58?(l+=1,u=!0,e.enter("tableDelimiterMarker"),e.consume(O),e.exit("tableDelimiterMarker"),N):O===45?(l+=1,N(O)):O===null||Ne(O)?D(O):U(O)}function N(O){return O===45?(e.enter("tableDelimiterFiller"),R(O)):U(O)}function R(O){return O===45?(e.consume(O),R):O===58?(u=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(O),e.exit("tableDelimiterMarker"),T):(e.exit("tableDelimiterFiller"),T(O))}function T(O){return qe(O)?Xe(e,D,"whitespace")(O):D(O)}function D(O){return O===124?w(O):O===null||Ne(O)?!u||a!==l?U(O):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(O)):U(O)}function U(O){return n(O)}function M(O){return e.enter("tableRow"),B(O)}function B(O){return O===124?(e.enter("tableCellDivider"),e.consume(O),e.exit("tableCellDivider"),B):O===null||Ne(O)?(e.exit("tableRow"),t(O)):qe(O)?Xe(e,B,"whitespace")(O):(e.enter("data"),P(O))}function P(O){return O===null||O===124||ct(O)?(e.exit("data"),B(O)):(e.consume(O),O===92?H:P)}function H(O){return O===92||O===124?(e.consume(O),P):P(O)}}function F7(e,t){let n=-1,s=!0,a=0,l=[0,0,0,0],u=[0,0,0,0],d=!1,h=0,m,p,g;const v=new L7;for(;++n<e.length;){const b=e[n],w=b[1];b[0]==="enter"?w.type==="tableHead"?(d=!1,h!==0&&(FS(v,t,h,m,p),p=void 0,h=0),m={type:"table",start:Object.assign({},w.start),end:Object.assign({},w.end)},v.add(n,0,[["enter",m,t]])):w.type==="tableRow"||w.type==="tableDelimiterRow"?(s=!0,g=void 0,l=[0,0,0,0],u=[0,n+1,0,0],d&&(d=!1,p={type:"tableBody",start:Object.assign({},w.start),end:Object.assign({},w.end)},v.add(n,0,[["enter",p,t]])),a=w.type==="tableDelimiterRow"?2:p?3:1):a&&(w.type==="data"||w.type==="tableDelimiterMarker"||w.type==="tableDelimiterFiller")?(s=!1,u[2]===0&&(l[1]!==0&&(u[0]=u[1],g=Iu(v,t,l,a,void 0,g),l=[0,0,0,0]),u[2]=n)):w.type==="tableCellDivider"&&(s?s=!1:(l[1]!==0&&(u[0]=u[1],g=Iu(v,t,l,a,void 0,g)),l=u,u=[l[1],n,0,0])):w.type==="tableHead"?(d=!0,h=n):w.type==="tableRow"||w.type==="tableDelimiterRow"?(h=n,l[1]!==0?(u[0]=u[1],g=Iu(v,t,l,a,n,g)):u[1]!==0&&(g=Iu(v,t,u,a,n,g)),a=0):a&&(w.type==="data"||w.type==="tableDelimiterMarker"||w.type==="tableDelimiterFiller")&&(u[3]=n)}for(h!==0&&FS(v,t,h,m,p),v.consume(t.events),n=-1;++n<t.events.length;){const b=t.events[n];b[0]==="enter"&&b[1].type==="table"&&(b[1]._align=U7(t.events,n))}return e}function Iu(e,t,n,s,a,l){const u=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",d="tableContent";n[0]!==0&&(l.end=Object.assign({},Va(t.events,n[0])),e.add(n[0],0,[["exit",l,t]]));const h=Va(t.events,n[1]);if(l={type:u,start:Object.assign({},h),end:Object.assign({},h)},e.add(n[1],0,[["enter",l,t]]),n[2]!==0){const m=Va(t.events,n[2]),p=Va(t.events,n[3]),g={type:d,start:Object.assign({},m),end:Object.assign({},p)};if(e.add(n[2],0,[["enter",g,t]]),s!==2){const v=t.events[n[2]],b=t.events[n[3]];if(v[1].end=Object.assign({},b[1].end),v[1].type="chunkText",v[1].contentType="text",n[3]>n[2]+1){const w=n[2]+1,j=n[3]-n[2]-1;e.add(w,j,[])}}e.add(n[3]+1,0,[["exit",g,t]])}return a!==void 0&&(l.end=Object.assign({},Va(t.events,a)),e.add(a,0,[["exit",l,t]]),l=void 0),l}function FS(e,t,n,s,a){const l=[],u=Va(t.events,n);a&&(a.end=Object.assign({},u),l.push(["exit",a,t])),s.end=Object.assign({},u),l.push(["exit",s,t]),e.add(n+1,0,l)}function Va(e,t){const n=e[t],s=n[0]==="enter"?"start":"end";return n[1][s]}const q7={name:"tasklistCheck",tokenize:H7};function $7(){return{text:{91:q7}}}function H7(e,t,n){const s=this;return a;function a(h){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?n(h):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(h),e.exit("taskListCheckMarker"),l)}function l(h){return ct(h)?(e.enter("taskListCheckValueUnchecked"),e.consume(h),e.exit("taskListCheckValueUnchecked"),u):h===88||h===120?(e.enter("taskListCheckValueChecked"),e.consume(h),e.exit("taskListCheckValueChecked"),u):n(h)}function u(h){return h===93?(e.enter("taskListCheckMarker"),e.consume(h),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),d):n(h)}function d(h){return Ne(h)?t(h):qe(h)?e.check({tokenize:G7},t,n)(h):n(h)}}function G7(e,t,n){return Xe(e,s,"whitespace");function s(a){return a===null?n(a):t(a)}}function K7(e){return LN([x7(),E7(),z7(e),B7(),$7()])}const Y7={};function W7(e){const t=this,n=e||Y7,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),l=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),u=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(K7(n)),l.push(m7()),u.push(p7(n))}function X7(e={}){const[t,n]=S.useState(!1),[s,a]=S.useState(""),[l,u]=S.useState(""),[d,h]=S.useState(!1),m=S.useRef(null);S.useEffect(()=>{const b=window.SpeechRecognition||window.webkitSpeechRecognition;return h(!!b),b&&(m.current=new b,m.current.continuous=e.continuous??!1,m.current.interimResults=e.interimResults??!0,m.current.lang=e.lang||"en-US",m.current.onresult=w=>{let j="",k="";for(let N=w.resultIndex;N<w.results.length;N++){const R=w.results[N][0].transcript;w.results[N].isFinal?k+=R:j+=R}k&&a(N=>N+" "+k),u(j)},m.current.onend=()=>{n(!1)},m.current.onerror=w=>{console.error("[SpeechRecognition] Error:",w.error),n(!1)}),()=>{m.current&&m.current.stop()}},[e.continuous,e.interimResults,e.lang]);const p=S.useCallback(()=>{m.current&&!t&&(a(""),u(""),m.current.start(),n(!0))},[t]),g=S.useCallback(()=>{m.current&&t&&(m.current.stop(),n(!1))},[t]),v=S.useCallback(()=>{a(""),u("")},[]);return{isListening:t,transcript:s,interimTranscript:l,isSupported:d,startListening:p,stopListening:g,resetTranscript:v}}const J7=e=>({setup_wizard:"Setup Wizard",configuration_wizard:"Configuration Helper",draft_review:"Draft Assistant",explainer:"Translation Helper",global:"AI Assistant"})[e]||`${e.replace(/_/g," ")} Assistant`,qS=(e,t)=>{switch(e){case"setup_wizard":return`👋 Welcome to Setup! I can help you:
165
- • Choose Quick Start or Manual setup
166
- • Connect your Supabase project
167
- • Run database migrations
168
- • Troubleshoot connection issues
169
-
170
- Tell me what you want to do or say "help me set up".`;case"configuration_wizard":const n=t?.accounts_count||0,s=t?.rules_count||0;return`👋 Welcome to Configuration! I can help you:
171
- • Connect email accounts (${n} connected)
172
- • Set up automation rules (${s} active)
173
- • Configure LLM & TTS settings
174
- • Troubleshoot connection issues
175
-
176
- What would you like to set up?`;case"draft_review":const a=t?.count||0;return`📧 I'm your Draft Review Assistant!
177
-
178
- You have ${a} pending draft${a!==1?"s":""}.
179
-
180
- I can help you:
181
- • Summarize all drafts
182
- • Send or dismiss specific drafts
183
- • Preview draft content
184
- • Review recipients and subjects
185
-
186
- Try: "Summarize my drafts" or "Send the draft to John"`;case"explainer":return`🌐 Translation & Explanation Helper
187
-
188
- I can help you understand:
189
- • What automation rules mean
190
- • How settings affect your workflow
191
- • Technical terms in plain language
192
-
193
- Ask me anything about what you're seeing!`;case"global":return`👋 Hi! I'm your AI Assistant.
194
-
195
- I can help you navigate and understand any part of the Email Automator.
196
-
197
- What would you like to know?`;default:return`👋 Hi! I'm here to help with ${e.replace(/_/g," ")}.
198
-
199
- What can I assist you with?`}};function Uu({className:e}){const{currentConfig:t,chatHistory:n,agentState:s,sendMessage:a}=Ok(),{state:l}=In(),{speak:u}=ay(),{speakingId:d,stop:h}=Ak(),{t:m}=tt(),[p,g]=S.useState(!1),[v,b]=S.useState(""),[w,j]=S.useState(!1),[k,N]=S.useState(!1),R=S.useRef(null),T=S.useRef(t.page_id),{isListening:D,transcript:U,interimTranscript:M,isSupported:B,startListening:P,stopListening:H,resetTranscript:O}=X7({continuous:!1,interimResults:!0});S.useEffect(()=>{const V=()=>{try{const C=localStorage.getItem("auto_speak_enabled");return C===null?!0:C==="true"}catch{return!0}},q=p&&n.length===0&&!w&&V(),de=t.page_id!==T.current;if(q||p&&de&&n.length===0){const C=qS(t.page_id,t.data),z={provider:l.settings?.tts_provider||void 0,voice:l.settings?.tts_voice||void 0,speed:l.settings?.tts_speed!==void 0?l.settings.tts_speed:1,quality:l.settings?.tts_quality!==void 0?l.settings.tts_quality:10};console.log("[AgentOverlay] Intro speaking with TTS options:",z),u(C,`intro-${t.page_id}`,z),j(!0),T.current=t.page_id}p||j(!1)},[p,n.length,t.page_id,w,u]),S.useEffect(()=>{R.current&&(R.current.scrollTop=R.current.scrollHeight)},[n,p]),S.useEffect(()=>{U&&!D&&(b(U.trim()),O())},[U,D,O]),S.useEffect(()=>{D&&(U||M)&&b((U+" "+M).trim())},[U,M,D]);const Q=async()=>{if(!v.trim())return;const V=v;b(""),O(),await a(V)},G=V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Q())},he=()=>{D?H():P()},se=async(V,q)=>{const de=`msg-${q}`;if(d===de){h();return}const C={provider:l.settings?.tts_provider||void 0,voice:l.settings?.tts_voice||void 0,speed:l.settings?.tts_speed!==void 0?l.settings.tts_speed:1,quality:l.settings?.tts_quality!==void 0?l.settings.tts_quality:10};console.log("[AgentOverlay] Speaking with TTS options:",C),await u(V,de,C)},ae={p:({children:V})=>o.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:V}),ul:({children:V})=>o.jsx("ul",{className:"list-disc pl-4 space-y-1 text-sm",children:V}),ol:({children:V})=>o.jsx("ol",{className:"list-decimal pl-4 space-y-1 text-sm",children:V}),li:({children:V})=>o.jsx("li",{className:"text-sm",children:V}),a:({href:V,children:q})=>o.jsx("a",{href:V,target:"_blank",rel:"noreferrer",className:"text-primary underline underline-offset-2",children:q}),code:V=>{const{inline:q,children:de}=V;return q?o.jsx("code",{className:"px-1 py-0.5 rounded bg-background/60 text-[12px] font-mono",children:de}):o.jsx("code",{className:"text-[12px] font-mono",children:de})},pre:({children:V})=>o.jsx("pre",{className:"mt-2 overflow-x-auto rounded bg-background/60 p-2 text-[12px] font-mono",children:V}),blockquote:({children:V})=>o.jsx("blockquote",{className:"border-l-2 border-border pl-3 text-sm text-muted-foreground",children:V}),strong:({children:V})=>o.jsx("strong",{className:"font-semibold",children:V}),em:({children:V})=>o.jsx("em",{className:"italic",children:V})},L=me("fixed bottom-6 left-6 z-50",e);return o.jsxs(o.Fragment,{children:[p&&o.jsx("div",{className:L,children:o.jsxs("div",{className:me(k?"w-[calc(100vw-2rem)] sm:w-[33vw] sm:max-w-[560px] h-[90vh] max-h-[calc(100vh-6rem)]":"w-[360px] sm:w-[380px] h-[520px] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-6rem)]","bg-background border border-border/60 rounded-2xl shadow-2xl","flex flex-col overflow-hidden","animate-in slide-in-from-bottom-10 fade-in duration-200","transition-[width,height] duration-200 ease-out","motion-reduce:transition-none motion-reduce:animate-none"),children:[o.jsxs("div",{className:"p-3 border-b bg-muted/40 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:me("w-2.5 h-2.5 rounded-full",D?"bg-red-500 animate-pulse":s==="idle"?"bg-muted-foreground":s==="thinking"?"bg-yellow-500 animate-pulse":s==="speaking"?"bg-emerald-500 animate-pulse":"bg-red-500")}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"font-semibold text-sm leading-tight",children:D?"Listening...":J7(t.page_id)}),o.jsx("span",{className:"text-[10px] text-muted-foreground",children:s==="thinking"?"Analyzing":s==="speaking"?"Speaking":"Ready"})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>N(V=>!V),"aria-label":k?"Collapse assistant":"Expand assistant",title:k?"Collapse":"Expand",children:k?o.jsx(QS,{className:"w-4 h-4"}):o.jsx(mA,{className:"w-4 h-4"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(!1),"aria-label":"Close assistant",children:o.jsx(mn,{className:"w-4 h-4"})})]})]}),o.jsxs("div",{ref:R,className:"flex-1 overflow-y-auto p-4 space-y-4 bg-background",children:[n.length===0&&o.jsx("div",{className:"text-center text-muted-foreground text-xs mt-10 whitespace-pre-line",children:qS(t.page_id,t.data)}),n.map((V,q)=>{const de=`msg-${q}`,C=d===de,z=V.role!=="user";return o.jsx("div",{className:me("flex flex-col max-w-[85%] rounded-2xl p-3 text-sm relative group",V.role==="user"?"self-end bg-primary/10 text-foreground ml-auto rounded-br-md":"self-start bg-secondary text-secondary-foreground rounded-bl-md"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx("div",{className:"flex-1",children:V.role==="user"?V.content:o.jsx(z9,{remarkPlugins:[W7],components:ae,children:V.content})}),z&&o.jsx("button",{onClick:()=>se(V.content,q),className:me("shrink-0 p-1.5 rounded-md hover:bg-background/60 transition-colors","opacity-0 group-hover:opacity-100",C&&"opacity-100"),title:C?"Stop speaking":"Speak message",children:C?o.jsx(vg,{className:"w-3.5 h-3.5 text-muted-foreground animate-pulse"}):o.jsx(Al,{className:"w-3.5 h-3.5 text-muted-foreground"})})]})},q)}),s==="thinking"&&o.jsxs("div",{className:"self-start bg-secondary/50 rounded-lg p-3 flex gap-1",children:[o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce [animation-delay:-0.3s]"}),o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce [animation-delay:-0.15s]"}),o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce"})]}),D&&o.jsxs("div",{className:"self-start bg-red-500/10 border border-red-500/30 rounded-lg p-4 flex flex-col gap-2 animate-pulse",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(F0,{className:"w-4 h-4 text-red-500 animate-pulse"}),o.jsx("span",{className:"text-xs font-semibold text-red-500",children:"Recording..."})]}),o.jsx("div",{className:"flex items-center justify-center gap-1 h-8",children:[...Array(12)].map((V,q)=>o.jsx("div",{className:"w-1 bg-red-500 rounded-full animate-pulse",style:{height:`${20+Math.sin(q)*15}px`,animationDelay:`${q*.1}s`,animationDuration:"0.8s"}},q))}),M&&o.jsxs("div",{className:"text-xs text-muted-foreground italic",children:['"',M,'..."']})]})]}),o.jsxs("div",{className:"p-3 border-t bg-background flex gap-2",children:[o.jsx("input",{className:"flex-1 bg-secondary/40 border border-border/50 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/40 outline-none",placeholder:D?"Listening...":"Ask a question, or click the mic...",value:v,onChange:V=>b(V.target.value),onKeyDown:G,disabled:s==="thinking"||s==="speaking"||D}),B&&o.jsx(Z,{size:"icon",variant:D?"default":"outline",className:me("h-9 w-9 shrink-0",D&&"bg-red-500 hover:bg-red-600 animate-pulse"),onClick:he,disabled:s==="thinking"||s==="speaking","aria-label":D?"Stop listening":"Start listening",children:D?o.jsx(yA,{className:"w-4 h-4"}):o.jsx(F0,{className:"w-4 h-4"})}),o.jsx(Z,{size:"icon",className:"h-9 w-9 shrink-0",onClick:Q,disabled:!v.trim()||s==="thinking"||D,"aria-label":"Send message",children:s==="thinking"?o.jsx(Nt,{className:"w-4 h-4 animate-spin"}):o.jsx(Kl,{className:"w-4 h-4"})})]})]})}),o.jsx("div",{className:L,children:o.jsx(Z,{size:"icon",className:me("relative rounded-full h-11 w-11 border border-border/60 bg-primary text-primary-foreground shadow-md","transition-all duration-200 ease-out","hover:bg-primary/90 hover:shadow-lg hover:-translate-y-0.5","active:translate-y-0 active:shadow-md active:scale-95","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-2 focus-visible:ring-offset-background","motion-reduce:transition-none motion-reduce:hover:transform-none",p?"rotate-0 scale-0 opacity-0":"scale-100 opacity-100",s==="speaking"&&"ring-4 ring-emerald-500/30 animate-pulse"),onClick:()=>g(!0),"aria-label":"Open assistant chat",title:"Open assistant chat",children:s==="speaking"?o.jsx(Al,{className:"w-5 h-5 animate-pulse"}):o.jsx(yd,{className:"w-5 h-5"})})})]})}function Q7(){const{state:e,isSubscribed:t,actions:n}=In(),{t:s}=tt(),[a,l]=S.useState(null),[u,d]=S.useState(!0),[h,m]=S.useState(!1),[p,g]=S.useState(!0),[v,b]=S.useState("dashboard"),[w,j]=S.useState(!1),[k,N]=S.useState(null),[R,T]=S.useState(!1),[D,U]=S.useState(!1),[M,B]=S.useState(!1),[P,H]=S.useState(null),[O,Q]=S.useState(!1),[G,he]=S.useState(null),[se,ae]=S.useState(!1),[L,V]=S.useState(!1);if(S.useEffect(()=>{if(e.isInitialized&&e.isAuthenticated&&e.settings&&!e.isLoading&&!e.settings.persona_completed&&!se&&!L){const C=setTimeout(()=>{ae(!0)},2e3);return()=>clearTimeout(C)}},[e.isInitialized,e.isAuthenticated,e.settings,e.isLoading,L]),S.useEffect(()=>{const z=new URLSearchParams(window.location.search).get("code");z&&!w&&(async()=>{j(!0);try{const A=await De.connectGmail(z);if(A.data?.success)ue.success("Gmail connected successfully!"),window.opener?setTimeout(()=>window.close(),1500):(window.history.replaceState({},"",window.location.pathname),n.fetchAccounts());else{const oe=typeof A.error=="string"?A.error:A.error?.message;ue.error(oe||"Failed to connect Gmail")}}catch{ue.error("Connection failed")}finally{j(!1)}})()},[]),w)return o.jsx(rd,{text:s("app.connecting")});S.useEffect(()=>{(async()=>{if(!ao()){m(!0),d(!1);return}try{const{data:oe,error:pe}=await pt.from("init_state").select("is_initialized").single();pe?(console.warn("[App] Init check error (might be fresh DB):",pe),pe.code==="42P01"&&g(!1)):g(oe.is_initialized>0);const{data:{session:we}}=await pt.auth.getSession();if(l(we?.user??null),we?.user){const We=await ly(pt);N(We.needsMigration?We:null),We.needsMigration&&!pL()&&T(!0)}const Se=await wU();Se&&!vU()&&(H(Se),Q(!0))}catch(oe){console.error("[App] Status check failed:",oe),oe instanceof Error&&oe.message.includes("Invalid API key")&&m(!0)}finally{d(!1)}})();const{data:{subscription:z}}=pt.auth.onAuthStateChange((A,oe)=>{l(oe?.user??null),oe||(N(null),T(!1))}),J=()=>{if(Tr.isEnabled()){const A=new(window.AudioContext||window.webkitAudioContext);A.state==="suspended"&&A.resume()}window.removeEventListener("click",J),window.removeEventListener("keydown",J)};return window.addEventListener("click",J),window.addEventListener("keydown",J),()=>{z.unsubscribe(),window.removeEventListener("click",J),window.removeEventListener("keydown",J)}},[]),S.useEffect(()=>{a&&(n.fetchAccounts(),n.fetchRules(),n.fetchSettings(),n.fetchProfile())},[a]),S.useEffect(()=>{const C=async()=>{try{await De.healthCheck()}catch{console.warn("[App] Keep-alive ping failed")}};C();const z=setInterval(C,3e4);return()=>clearInterval(z)},[]);const q=()=>{U(!0),T(!1)},de={migrationStatus:k,showMigrationBanner:R,showMigrationModal:D,openMigrationModal:q,suppressMigrationBanner:M,setSuppressMigrationBanner:B};return u?o.jsxs(o.Fragment,{children:[o.jsx(rd,{text:s("app.loadingWorkspace")}),o.jsx(Uu,{className:"z-[80]"})]}):h?o.jsxs(o.Fragment,{children:[o.jsx(Uk,{onComplete:()=>m(!1)}),o.jsx(Uu,{className:"z-[80]"})]}):a?o.jsx(b5,{value:de,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:()=>b("dashboard"),className:"text-xl font-bold flex items-center gap-2 hover:opacity-80 transition-opacity",children:[o.jsx(cy,{className:"w-8 h-8"}),o.jsx("span",{className:"hidden sm:inline",children:s("app.name")}),o.jsx("span",{className:"sm:hidden",children:"Email AI"})]}),o.jsxs("div",{className:me("flex items-center gap-1.5 px-2 h-6 rounded-full text-[10px] font-bold border transition-colors",t?"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:[t&&o.jsx("span",{className:"absolute inline-flex h-3 w-3 rounded-full bg-emerald-500/40 animate-ping"}),o.jsx("div",{className:me("relative w-2 h-2 rounded-full",t?"bg-emerald-500":"bg-yellow-500")})]}),o.jsx("span",{className:"hidden xs:inline leading-none",children:s(t?"app.statusLive":"app.statusOffline")})]})]}),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:v==="dashboard"?"secondary":"ghost",size:"sm",onClick:()=>b("dashboard"),className:"gap-2",children:[o.jsx(iA,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.dashboard")})]}),o.jsxs(Z,{variant:v==="drafts"?"secondary":"ghost",size:"sm",onClick:()=>b("drafts"),className:"gap-2",children:[o.jsx(qC,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.drafts")||"Drafts"})]}),o.jsxs(Z,{variant:v==="autopilot"?"secondary":"ghost",size:"sm",onClick:()=>b("autopilot"),className:"gap-2",children:[o.jsx(Vu,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.autopilot")})]}),o.jsxs(Z,{variant:v==="analytics"?"secondary":"ghost",size:"sm",onClick:()=>b("analytics"),className:"gap-2",children:[o.jsx(fg,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.analytics")})]}),o.jsxs(Z,{variant:v==="config"?"secondary":"ghost",size:"sm",onClick:()=>b("config"),className:"gap-2",children:[o.jsx(Cl,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.configuration")})]})]}),o.jsx("div",{className:"h-6 w-px bg-border/50 mx-2 hidden sm:block"}),o.jsx(iy,{}),o.jsx(v_,{}),o.jsx(Z,{variant:v==="account"?"secondary":"ghost",size:"sm",onClick:()=>b("account"),className:"text-muted-foreground hover:text-foreground p-0 w-8 h-8 rounded-full overflow-hidden border",title:s("nav.accountSettings"),children:e.profile?.avatar_url?o.jsx("img",{src:e.profile.avatar_url,alt:"Profile",className:"w-full h-full object-cover"}):o.jsx(RC,{className:"w-5 h-5"})})]})]})}),o.jsxs("main",{className:"max-w-7xl mx-auto p-4 sm:p-8 mt-4 mb-12",children:[v==="dashboard"&&o.jsx(DI,{}),v==="drafts"&&o.jsx(UI,{onPreview:he}),v==="autopilot"&&o.jsx(oU,{}),v==="config"&&o.jsx($I,{}),v==="analytics"&&o.jsx(eq,{}),v==="account"&&o.jsx(tU,{})]}),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.22.1"]})}),e.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:e.error})})}),k&&R&&!M&&o.jsx(uU,{status:k,onDismiss:()=>T(!1),onLearnMore:q}),P&&O&&o.jsx(_U,{versionInfo:P,onDismiss:()=>Q(!1)}),k&&o.jsx(dU,{open:D,onOpenChange:U,status:k}),G&&o.jsx(FI,{email:G,onClose:()=>he(null),onSend:async C=>{(await fetch(`/api/v1/drafts/${C}/send`,{method:"POST",headers:{Authorization:`Bearer ${localStorage.getItem("supabase.auth.token")}`}})).ok?ue.success(s("drafts.sendSuccess")||"Draft sent successfully!"):ue.error(s("drafts.sendError")||"Failed to send draft")},onDismiss:async C=>{(await fetch(`/api/v1/drafts/${C}/dismiss`,{method:"POST",headers:{Authorization:`Bearer ${localStorage.getItem("supabase.auth.token")}`}})).ok&&ue.success(s("drafts.dismissSuccess")||"Draft dismissed")}}),o.jsx(jU,{}),o.jsx(Uu,{}),o.jsx(Rr,{open:se,onOpenChange:C=>{C||V(!0),ae(C)},children:o.jsxs(Or,{className:"max-w-3xl border-none bg-transparent shadow-none p-0 sm:max-w-3xl",children:[o.jsx(SN,{children:o.jsx(Dr,{children:"Persona Setup Wizard"})}),o.jsx(yN,{onComplete:()=>{ae(!1),n.fetchSettings()},onClose:()=>{ae(!1),V(!0)}})]})})]})}):o.jsxs(o.Fragment,{children:[o.jsx(cU,{onSuccess:()=>n.fetchProfile(),onConfigure:()=>m(!0),isInitialized:p}),o.jsx(Uu,{className:"z-[80]"})]})}function Z7({runId:e,accountEmail:t,isOpen:n,onOpenChange:s}){const{t:a}=tt(),[l,u]=S.useState([]),[d,h]=S.useState(!1);S.useEffect(()=>{n&&e&&m()},[n,e]);const m=async()=>{if(e){h(!0);try{const g=await De.getRunEvents(e);g.data&&u(g.data.events)}catch(g){console.error("Failed to fetch run trace:",g)}finally{h(!1)}}},p=g=>{switch(g){case"analysis":return o.jsx(Hs,{className:"w-4 h-4 text-purple-500"});case"action":return o.jsx(eo,{className:"w-4 h-4 text-emerald-500"});case"error":return o.jsx(mr,{className:"w-4 h-4 text-red-500"});default:return o.jsx(Za,{className:"w-4 h-4 text-blue-500"})}};return o.jsx(Rr,{open:n,onOpenChange:s,children:o.jsxs(Or,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs(Ws,{className:"p-6 border-b",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(gd,{className:"w-5 h-5 text-primary"}),o.jsx(Dr,{children:a("trace.runTrace")})]}),o.jsx(Xs,{children:t?a("trace.fullLogFor").replace("{email}",t):a("trace.historicalLog")})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:d?o.jsx("div",{className:"py-20 flex justify-center",children:o.jsx(rd,{text:a("trace.loadingTrace")})}):l.length===0?o.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:a("trace.noTraceEvents")}):l.map((g,v)=>o.jsxs("div",{className:"relative pl-8",children:[v!==l.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(Js,{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(b=>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:b},b))]}),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:[a("dashboard.done")," ",g.details?.action]}),o.jsx(hg,{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 eq(){const{state:e,actions:t}=In(),{t:n}=tt(),[s,a]=S.useState(null),[l,u]=S.useState(void 0),[d,h]=S.useState(!1),[m,p]=S.useState("overview");if(S.useEffect(()=>{t.fetchStats()},[]),!e.stats)return o.jsx(rd,{text:n("common.loading")});const g=(b,w)=>{a(b),u(w),h(!0)},{stats:v}=e;return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(fg,{className:"w-6 h-6 text-primary"}),n("analytics.title")]}),o.jsxs("div",{className:"flex p-1 bg-muted rounded-lg w-full md:w-auto",children:[o.jsx("button",{onClick:()=>p("overview"),className:`flex-1 md:w-32 px-3 py-1.5 text-sm font-medium rounded-md transition-all ${m==="overview"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/50"}`,children:"Overview"}),o.jsxs("button",{onClick:()=>p("learning"),className:`flex-1 md:w-32 px-3 py-1.5 text-sm font-medium rounded-md transition-all flex items-center justify-center gap-2 ${m==="learning"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/50"}`,children:[o.jsx(Hs,{className:"w-3.5 h-3.5"}),"Learning"]})]})]}),m==="learning"?o.jsx(kU,{}):o.jsxs("div",{className:"space-y-8",children:[o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsx(Bu,{title:n("analytics.totalEmails"),value:v.totalEmails,color:"primary"}),o.jsx(Bu,{title:n("analytics.spamCaught"),value:v.categoryCounts.spam||0,color:"destructive"}),o.jsx(Bu,{title:n("analytics.actionsTaken"),value:Object.values(v.actionCounts).reduce((b,w)=>b+w,0)-(v.actionCounts.none||0),color:"emerald"}),o.jsx(Bu,{title:n("analytics.accounts"),value:v.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:n("analytics.categories")}),o.jsx("div",{className:"space-y-3",children:Object.entries(v.categoryCounts).map(([b,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:b}),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/v.totalEmails*100}%`}})})]})},b))})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.actionsTaken")}),o.jsx("div",{className:"space-y-3",children:Object.entries(v.actionCounts).map(([b,w])=>o.jsxs("div",{className:"flex items-center justify-between py-2 border-b last:border-0",children:[o.jsx("span",{className:"capitalize",children:b}),o.jsx("span",{className:"font-medium",children:w})]},b))})]})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.recentActivity")}),v.recentSyncs.length===0?o.jsx("p",{className:"text-muted-foreground text-sm",children:n("analytics.noActivity")}):o.jsx("div",{className:"space-y-3",children:v.recentSyncs.map(b=>{const w=b.completed_at?Math.round((new Date(b.completed_at).getTime()-new Date(b.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:()=>g(b.id,b.email_accounts?.email_address),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:me("w-2.5 h-2.5 rounded-full",b.status==="success"?"bg-emerald-500":b.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:b.email_accounts?.email_address||n("common.systemSync")}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(Js,{className:"w-3 h-3"}),new Date(b.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.jsx("span",{className:"font-bold text-primary",children:n("analytics.emails").replace("{count}",b.emails_processed.toString())}),o.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[n("analytics.deleted").replace("{count}",b.emails_deleted.toString()),", ",n("analytics.drafted").replace("{count}",b.emails_drafted.toString())]})]})})]},b.id)})})]})]}),o.jsx(Z7,{runId:s,accountEmail:l,isOpen:d,onOpenChange:h})]})}function Bu({title:e,value:t,color:n}){const s={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:e}),o.jsx("p",{className:`text-3xl font-bold ${s[n]||""}`,children:t})]})}function tq(){return o.jsx(cL,{children:o.jsx(kR,{defaultTheme:"system",storageKey:"email-automator-theme",children:o.jsx(S5,{children:o.jsx(w5,{children:o.jsx(uL,{children:o.jsx(dL,{children:o.jsxs(x5,{children:[o.jsx(Q7,{}),o.jsx(m5,{})]})})})})})})})}XE.createRoot(document.getElementById("root")).render(o.jsx($S.StrictMode,{children:o.jsx(tq,{})}));
209
+ `))}function h(b,w,j,k){const N=j.enter("tableCell"),R=j.enter("phrasing"),T=j.containerPhrasing(b,{...k,before:l,after:l});return R(),N(),T}function m(b,w){return _F(b,{align:w,alignDelimiters:s,padding:n,stringLength:a})}function p(b,w,j){const k=b.children;let N=-1;const R=[],T=w.enter("table");for(;++N<k.length;)R[N]=g(k[N],w,j);return T(),R}function g(b,w,j){const k=b.children;let N=-1;const R=[],T=w.enter("tableRow");for(;++N<k.length;)R[N]=h(k[N],b,w,j);return T(),R}function v(b,w,j){let k=xT.inlineCode(b,w,j);return j.stack.includes("tableCell")&&(k=k.replace(/\|/g,"\\$&")),k}}function u7(){return{exit:{taskListCheckValueChecked:VS,taskListCheckValueUnchecked:VS,paragraph:f7}}}function d7(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:h7}}}function VS(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function f7(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const s=n.children[0];if(s&&s.type==="text"){const a=t.children;let l=-1,u;for(;++l<a.length;){const d=a[l];if(d.type==="paragraph"){u=d;break}}u===n&&(s.value=s.value.slice(1),s.value.length===0?n.children.shift():n.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,n.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function h7(e,t,n,s){const a=e.children[0],l=typeof e.checked=="boolean"&&a&&a.type==="paragraph",u="["+(e.checked?"x":" ")+"] ",d=n.createTracker(s);l&&d.move(u);let h=xT.listItem(e,t,n,{...s,...d.current()});return l&&(h=h.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),h;function m(p){return p+u}}function m7(){return[G9(),hF(),yF(),r7(),u7()]}function p7(e){return{extensions:[K9(),mF(e),xF(),c7(e),d7()]}}const g7={tokenize:S7,partial:!0},vT={tokenize:_7,partial:!0},bT={tokenize:j7,partial:!0},wT={tokenize:k7,partial:!0},y7={tokenize:N7,partial:!0},ST={name:"wwwAutolink",tokenize:b7,previous:jT},_T={name:"protocolAutolink",tokenize:w7,previous:kT},cs={name:"emailAutolink",tokenize:v7,previous:NT},Mr={};function x7(){return{text:Mr}}let _i=48;for(;_i<123;)Mr[_i]=cs,_i++,_i===58?_i=65:_i===91&&(_i=97);Mr[43]=cs;Mr[45]=cs;Mr[46]=cs;Mr[95]=cs;Mr[72]=[cs,_T];Mr[104]=[cs,_T];Mr[87]=[cs,ST];Mr[119]=[cs,ST];function v7(e,t,n){const s=this;let a,l;return u;function u(g){return!lg(g)||!NT.call(s,s.previous)||Dy(s.events)?n(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),d(g))}function d(g){return lg(g)?(e.consume(g),d):g===64?(e.consume(g),h):n(g)}function h(g){return g===46?e.check(y7,p,m)(g):g===45||g===95||on(g)?(l=!0,e.consume(g),h):p(g)}function m(g){return e.consume(g),a=!0,h}function p(g){return l&&a&&dn(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):n(g)}}function b7(e,t,n){const s=this;return a;function a(u){return u!==87&&u!==119||!jT.call(s,s.previous)||Dy(s.events)?n(u):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(g7,e.attempt(vT,e.attempt(bT,l),n),n)(u))}function l(u){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(u)}}function w7(e,t,n){const s=this;let a="",l=!1;return u;function u(g){return(g===72||g===104)&&kT.call(s,s.previous)&&!Dy(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(g),e.consume(g),d):n(g)}function d(g){if(dn(g)&&a.length<5)return a+=String.fromCodePoint(g),e.consume(g),d;if(g===58){const v=a.toLowerCase();if(v==="http"||v==="https")return e.consume(g),h}return n(g)}function h(g){return g===47?(e.consume(g),l?m:(l=!0,h)):n(g)}function m(g){return g===null||fd(g)||ct(g)||Ii(g)||Rd(g)?n(g):e.attempt(vT,e.attempt(bT,p),n)(g)}function p(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function S7(e,t,n){let s=0;return a;function a(u){return(u===87||u===119)&&s<3?(s++,e.consume(u),a):u===46&&s===3?(e.consume(u),l):n(u)}function l(u){return u===null?n(u):t(u)}}function _7(e,t,n){let s,a,l;return u;function u(m){return m===46||m===95?e.check(wT,h,d)(m):m===null||ct(m)||Ii(m)||m!==45&&Rd(m)?h(m):(l=!0,e.consume(m),u)}function d(m){return m===95?s=!0:(a=s,s=void 0),e.consume(m),u}function h(m){return a||s||!l?n(m):t(m)}}function j7(e,t){let n=0,s=0;return a;function a(u){return u===40?(n++,e.consume(u),a):u===41&&s<n?l(u):u===33||u===34||u===38||u===39||u===41||u===42||u===44||u===46||u===58||u===59||u===60||u===63||u===93||u===95||u===126?e.check(wT,t,l)(u):u===null||ct(u)||Ii(u)?t(u):(e.consume(u),a)}function l(u){return u===41&&s++,e.consume(u),a}}function k7(e,t,n){return s;function s(d){return d===33||d===34||d===39||d===41||d===42||d===44||d===46||d===58||d===59||d===63||d===95||d===126?(e.consume(d),s):d===38?(e.consume(d),l):d===93?(e.consume(d),a):d===60||d===null||ct(d)||Ii(d)?t(d):n(d)}function a(d){return d===null||d===40||d===91||ct(d)||Ii(d)?t(d):s(d)}function l(d){return dn(d)?u(d):n(d)}function u(d){return d===59?(e.consume(d),s):dn(d)?(e.consume(d),u):n(d)}}function N7(e,t,n){return s;function s(l){return e.consume(l),a}function a(l){return on(l)?n(l):t(l)}}function jT(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ct(e)}function kT(e){return!dn(e)}function NT(e){return!(e===47||lg(e))}function lg(e){return e===43||e===45||e===46||e===95||on(e)}function Dy(e){let t=e.length,n=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){n=!0;break}if(s._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const T7={tokenize:P7,partial:!0};function E7(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:O7,continuation:{tokenize:D7},exit:M7}},text:{91:{name:"gfmFootnoteCall",tokenize:R7},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:C7,resolveTo:A7}}}}function C7(e,t,n){const s=this;let a=s.events.length;const l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u;for(;a--;){const h=s.events[a][1];if(h.type==="labelImage"){u=h;break}if(h.type==="gfmFootnoteCall"||h.type==="labelLink"||h.type==="label"||h.type==="image"||h.type==="link")break}return d;function d(h){if(!u||!u._balanced)return n(h);const m=hr(s.sliceSerialize({start:u.end,end:s.now()}));return m.codePointAt(0)!==94||!l.includes(m.slice(1))?n(h):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),t(h))}}function A7(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const l={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},u={type:"chunkString",contentType:"string",start:Object.assign({},l.start),end:Object.assign({},l.end)},d=[e[n+1],e[n+2],["enter",s,t],e[n+3],e[n+4],["enter",a,t],["exit",a,t],["enter",l,t],["enter",u,t],["exit",u,t],["exit",l,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(n,e.length-n+1,...d),e}function R7(e,t,n){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let l=0,u;return d;function d(g){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),h}function h(g){return g!==94?n(g):(e.enter("gfmFootnoteCallMarker"),e.consume(g),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",m)}function m(g){if(l>999||g===93&&!u||g===null||g===91||ct(g))return n(g);if(g===93){e.exit("chunkString");const v=e.exit("gfmFootnoteCallString");return a.includes(hr(s.sliceSerialize(v)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(g)}return ct(g)||(u=!0),l++,e.consume(g),g===92?p:m}function p(g){return g===91||g===92||g===93?(e.consume(g),l++,m):m(g)}}function O7(e,t,n){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let l,u=0,d;return h;function h(w){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(w),e.exit("gfmFootnoteDefinitionLabelMarker"),m}function m(w){return w===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(w),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",p):n(w)}function p(w){if(u>999||w===93&&!d||w===null||w===91||ct(w))return n(w);if(w===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return l=hr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(w),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),v}return ct(w)||(d=!0),u++,e.consume(w),w===92?g:p}function g(w){return w===91||w===92||w===93?(e.consume(w),u++,p):p(w)}function v(w){return w===58?(e.enter("definitionMarker"),e.consume(w),e.exit("definitionMarker"),a.includes(l)||a.push(l),Xe(e,b,"gfmFootnoteDefinitionWhitespace")):n(w)}function b(w){return t(w)}}function D7(e,t,n){return e.check(tc,t,e.attempt(T7,t,n))}function M7(e){e.exit("gfmFootnoteDefinition")}function P7(e,t,n){const s=this;return Xe(e,a,"gfmFootnoteDefinitionIndent",5);function a(l){const u=s.events[s.events.length-1];return u&&u[1].type==="gfmFootnoteDefinitionIndent"&&u[2].sliceSerialize(u[1],!0).length===4?t(l):n(l)}}function z7(e){let n=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:l,resolveAll:a};return n==null&&(n=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(u,d){let h=-1;for(;++h<u.length;)if(u[h][0]==="enter"&&u[h][1].type==="strikethroughSequenceTemporary"&&u[h][1]._close){let m=h;for(;m--;)if(u[m][0]==="exit"&&u[m][1].type==="strikethroughSequenceTemporary"&&u[m][1]._open&&u[h][1].end.offset-u[h][1].start.offset===u[m][1].end.offset-u[m][1].start.offset){u[h][1].type="strikethroughSequence",u[m][1].type="strikethroughSequence";const p={type:"strikethrough",start:Object.assign({},u[m][1].start),end:Object.assign({},u[h][1].end)},g={type:"strikethroughText",start:Object.assign({},u[m][1].end),end:Object.assign({},u[h][1].start)},v=[["enter",p,d],["enter",u[m][1],d],["exit",u[m][1],d],["enter",g,d]],b=d.parser.constructs.insideSpan.null;b&&Ln(v,v.length,0,Od(b,u.slice(m+1,h),d)),Ln(v,v.length,0,[["exit",g,d],["enter",u[h][1],d],["exit",u[h][1],d],["exit",p,d]]),Ln(u,m-1,h-m+3,v),h=m+v.length-2;break}}for(h=-1;++h<u.length;)u[h][1].type==="strikethroughSequenceTemporary"&&(u[h][1].type="data");return u}function l(u,d,h){const m=this.previous,p=this.events;let g=0;return v;function v(w){return m===126&&p[p.length-1][1].type!=="characterEscape"?h(w):(u.enter("strikethroughSequenceTemporary"),b(w))}function b(w){const j=no(m);if(w===126)return g>1?h(w):(u.consume(w),g++,b);if(g<2&&!n)return h(w);const k=u.exit("strikethroughSequenceTemporary"),N=no(w);return k._open=!N||N===2&&!!j,k._close=!j||j===2&&!!N,d(w)}}}class L7{constructor(){this.map=[]}add(t,n,s){I7(this,t,n,s)}consume(t){if(this.map.sort(function(l,u){return l[0]-u[0]}),this.map.length===0)return;let n=this.map.length;const s=[];for(;n>0;)n-=1,s.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const l of a)t.push(l);a=s.pop()}this.map.length=0}}function I7(e,t,n,s){let a=0;if(!(n===0&&s.length===0)){for(;a<e.map.length;){if(e.map[a][0]===t){e.map[a][1]+=n,e.map[a][2].push(...s);return}a+=1}e.map.push([t,n,s])}}function U7(e,t){let n=!1;const s=[];for(;t<e.length;){const a=e[t];if(n){if(a[0]==="enter")a[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(a[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const l=s.length-1;s[l]=s[l]==="left"?"center":"right"}}else if(a[1].type==="tableDelimiterRow")break}else a[0]==="enter"&&a[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return s}function B7(){return{flow:{null:{name:"table",tokenize:V7,resolveAll:F7}}}}function V7(e,t,n){const s=this;let a=0,l=0,u;return d;function d(O){let Q=s.events.length-1;for(;Q>-1;){const se=s.events[Q][1].type;if(se==="lineEnding"||se==="linePrefix")Q--;else break}const G=Q>-1?s.events[Q][1].type:null,he=G==="tableHead"||G==="tableRow"?M:h;return he===M&&s.parser.lazy[s.now().line]?n(O):he(O)}function h(O){return e.enter("tableHead"),e.enter("tableRow"),m(O)}function m(O){return O===124||(u=!0,l+=1),p(O)}function p(O){return O===null?n(O):Ne(O)?l>1?(l=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(O),e.exit("lineEnding"),b):n(O):qe(O)?Xe(e,p,"whitespace")(O):(l+=1,u&&(u=!1,a+=1),O===124?(e.enter("tableCellDivider"),e.consume(O),e.exit("tableCellDivider"),u=!0,p):(e.enter("data"),g(O)))}function g(O){return O===null||O===124||ct(O)?(e.exit("data"),p(O)):(e.consume(O),O===92?v:g)}function v(O){return O===92||O===124?(e.consume(O),g):g(O)}function b(O){return s.interrupt=!1,s.parser.lazy[s.now().line]?n(O):(e.enter("tableDelimiterRow"),u=!1,qe(O)?Xe(e,w,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(O):w(O))}function w(O){return O===45||O===58?k(O):O===124?(u=!0,e.enter("tableCellDivider"),e.consume(O),e.exit("tableCellDivider"),j):U(O)}function j(O){return qe(O)?Xe(e,k,"whitespace")(O):k(O)}function k(O){return O===58?(l+=1,u=!0,e.enter("tableDelimiterMarker"),e.consume(O),e.exit("tableDelimiterMarker"),N):O===45?(l+=1,N(O)):O===null||Ne(O)?D(O):U(O)}function N(O){return O===45?(e.enter("tableDelimiterFiller"),R(O)):U(O)}function R(O){return O===45?(e.consume(O),R):O===58?(u=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(O),e.exit("tableDelimiterMarker"),T):(e.exit("tableDelimiterFiller"),T(O))}function T(O){return qe(O)?Xe(e,D,"whitespace")(O):D(O)}function D(O){return O===124?w(O):O===null||Ne(O)?!u||a!==l?U(O):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(O)):U(O)}function U(O){return n(O)}function M(O){return e.enter("tableRow"),B(O)}function B(O){return O===124?(e.enter("tableCellDivider"),e.consume(O),e.exit("tableCellDivider"),B):O===null||Ne(O)?(e.exit("tableRow"),t(O)):qe(O)?Xe(e,B,"whitespace")(O):(e.enter("data"),P(O))}function P(O){return O===null||O===124||ct(O)?(e.exit("data"),B(O)):(e.consume(O),O===92?H:P)}function H(O){return O===92||O===124?(e.consume(O),P):P(O)}}function F7(e,t){let n=-1,s=!0,a=0,l=[0,0,0,0],u=[0,0,0,0],d=!1,h=0,m,p,g;const v=new L7;for(;++n<e.length;){const b=e[n],w=b[1];b[0]==="enter"?w.type==="tableHead"?(d=!1,h!==0&&(FS(v,t,h,m,p),p=void 0,h=0),m={type:"table",start:Object.assign({},w.start),end:Object.assign({},w.end)},v.add(n,0,[["enter",m,t]])):w.type==="tableRow"||w.type==="tableDelimiterRow"?(s=!0,g=void 0,l=[0,0,0,0],u=[0,n+1,0,0],d&&(d=!1,p={type:"tableBody",start:Object.assign({},w.start),end:Object.assign({},w.end)},v.add(n,0,[["enter",p,t]])),a=w.type==="tableDelimiterRow"?2:p?3:1):a&&(w.type==="data"||w.type==="tableDelimiterMarker"||w.type==="tableDelimiterFiller")?(s=!1,u[2]===0&&(l[1]!==0&&(u[0]=u[1],g=Iu(v,t,l,a,void 0,g),l=[0,0,0,0]),u[2]=n)):w.type==="tableCellDivider"&&(s?s=!1:(l[1]!==0&&(u[0]=u[1],g=Iu(v,t,l,a,void 0,g)),l=u,u=[l[1],n,0,0])):w.type==="tableHead"?(d=!0,h=n):w.type==="tableRow"||w.type==="tableDelimiterRow"?(h=n,l[1]!==0?(u[0]=u[1],g=Iu(v,t,l,a,n,g)):u[1]!==0&&(g=Iu(v,t,u,a,n,g)),a=0):a&&(w.type==="data"||w.type==="tableDelimiterMarker"||w.type==="tableDelimiterFiller")&&(u[3]=n)}for(h!==0&&FS(v,t,h,m,p),v.consume(t.events),n=-1;++n<t.events.length;){const b=t.events[n];b[0]==="enter"&&b[1].type==="table"&&(b[1]._align=U7(t.events,n))}return e}function Iu(e,t,n,s,a,l){const u=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",d="tableContent";n[0]!==0&&(l.end=Object.assign({},Va(t.events,n[0])),e.add(n[0],0,[["exit",l,t]]));const h=Va(t.events,n[1]);if(l={type:u,start:Object.assign({},h),end:Object.assign({},h)},e.add(n[1],0,[["enter",l,t]]),n[2]!==0){const m=Va(t.events,n[2]),p=Va(t.events,n[3]),g={type:d,start:Object.assign({},m),end:Object.assign({},p)};if(e.add(n[2],0,[["enter",g,t]]),s!==2){const v=t.events[n[2]],b=t.events[n[3]];if(v[1].end=Object.assign({},b[1].end),v[1].type="chunkText",v[1].contentType="text",n[3]>n[2]+1){const w=n[2]+1,j=n[3]-n[2]-1;e.add(w,j,[])}}e.add(n[3]+1,0,[["exit",g,t]])}return a!==void 0&&(l.end=Object.assign({},Va(t.events,a)),e.add(a,0,[["exit",l,t]]),l=void 0),l}function FS(e,t,n,s,a){const l=[],u=Va(t.events,n);a&&(a.end=Object.assign({},u),l.push(["exit",a,t])),s.end=Object.assign({},u),l.push(["exit",s,t]),e.add(n+1,0,l)}function Va(e,t){const n=e[t],s=n[0]==="enter"?"start":"end";return n[1][s]}const q7={name:"tasklistCheck",tokenize:H7};function $7(){return{text:{91:q7}}}function H7(e,t,n){const s=this;return a;function a(h){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?n(h):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(h),e.exit("taskListCheckMarker"),l)}function l(h){return ct(h)?(e.enter("taskListCheckValueUnchecked"),e.consume(h),e.exit("taskListCheckValueUnchecked"),u):h===88||h===120?(e.enter("taskListCheckValueChecked"),e.consume(h),e.exit("taskListCheckValueChecked"),u):n(h)}function u(h){return h===93?(e.enter("taskListCheckMarker"),e.consume(h),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),d):n(h)}function d(h){return Ne(h)?t(h):qe(h)?e.check({tokenize:G7},t,n)(h):n(h)}}function G7(e,t,n){return Xe(e,s,"whitespace");function s(a){return a===null?n(a):t(a)}}function K7(e){return LN([x7(),E7(),z7(e),B7(),$7()])}const Y7={};function W7(e){const t=this,n=e||Y7,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),l=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),u=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(K7(n)),l.push(m7()),u.push(p7(n))}function X7(e={}){const[t,n]=S.useState(!1),[s,a]=S.useState(""),[l,u]=S.useState(""),[d,h]=S.useState(!1),m=S.useRef(null);S.useEffect(()=>{const b=window.SpeechRecognition||window.webkitSpeechRecognition;return h(!!b),b&&(m.current=new b,m.current.continuous=e.continuous??!1,m.current.interimResults=e.interimResults??!0,m.current.lang=e.lang||"en-US",m.current.onresult=w=>{let j="",k="";for(let N=w.resultIndex;N<w.results.length;N++){const R=w.results[N][0].transcript;w.results[N].isFinal?k+=R:j+=R}k&&a(N=>N+" "+k),u(j)},m.current.onend=()=>{n(!1)},m.current.onerror=w=>{console.error("[SpeechRecognition] Error:",w.error),n(!1)}),()=>{m.current&&m.current.stop()}},[e.continuous,e.interimResults,e.lang]);const p=S.useCallback(()=>{m.current&&!t&&(a(""),u(""),m.current.start(),n(!0))},[t]),g=S.useCallback(()=>{m.current&&t&&(m.current.stop(),n(!1))},[t]),v=S.useCallback(()=>{a(""),u("")},[]);return{isListening:t,transcript:s,interimTranscript:l,isSupported:d,startListening:p,stopListening:g,resetTranscript:v}}const J7=(e,t)=>{const n={setup_wizard:"agent.title.setup",configuration_wizard:"agent.title.configuration",draft_review:"agent.title.drafts",explainer:"agent.title.explainer",global:"agent.title.global"};return n[e]?t(n[e]):t("agent.title.default").replace("{page}",e.replace(/_/g," "))},qS=(e,t,n)=>{switch(e){case"setup_wizard":return t("agent.intro.setup");case"configuration_wizard":return t("agent.intro.configuration").replace("{accountsCount}",String(n?.accounts_count||0)).replace("{rulesCount}",String(n?.rules_count||0));case"draft_review":{const s=n?.count||0;return t(s===1?"agent.intro.drafts.one":"agent.intro.drafts.other").replace("{count}",String(s))}case"explainer":return t("agent.intro.explainer");case"global":return t("agent.intro.global");default:return t("agent.intro.default").replace("{page}",e.replace(/_/g," "))}};function Uu({className:e}){const{currentConfig:t,chatHistory:n,agentState:s,sendMessage:a}=Ok(),{state:l}=In(),{speak:u}=ay(),{speakingId:d,stop:h}=Ak(),{t:m}=tt(),[p,g]=S.useState(!1),[v,b]=S.useState(""),[w,j]=S.useState(!1),[k,N]=S.useState(!1),R=S.useRef(null),T=S.useRef(t.page_id),{isListening:D,transcript:U,interimTranscript:M,isSupported:B,startListening:P,stopListening:H,resetTranscript:O}=X7({continuous:!1,interimResults:!0});S.useEffect(()=>{const V=()=>{try{const C=localStorage.getItem("auto_speak_enabled");return C===null?!0:C==="true"}catch{return!0}},q=p&&n.length===0&&!w&&V(),de=t.page_id!==T.current;if(q||p&&de&&n.length===0){const C=qS(t.page_id,m,t.data),z={provider:l.settings?.tts_provider||void 0,voice:l.settings?.tts_voice||void 0,speed:l.settings?.tts_speed!==void 0?l.settings.tts_speed:1,quality:l.settings?.tts_quality!==void 0?l.settings.tts_quality:10};console.log("[AgentOverlay] Intro speaking with TTS options:",z),u(C,`intro-${t.page_id}`,z),j(!0),T.current=t.page_id}p||j(!1)},[p,n.length,t.page_id,w,u]),S.useEffect(()=>{R.current&&(R.current.scrollTop=R.current.scrollHeight)},[n,p]),S.useEffect(()=>{U&&!D&&(b(U.trim()),O())},[U,D,O]),S.useEffect(()=>{D&&(U||M)&&b((U+" "+M).trim())},[U,M,D]);const Q=async()=>{if(!v.trim())return;const V=v;b(""),O(),await a(V)},G=V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Q())},he=()=>{D?H():P()},se=async(V,q)=>{const de=`msg-${q}`;if(d===de){h();return}const C={provider:l.settings?.tts_provider||void 0,voice:l.settings?.tts_voice||void 0,speed:l.settings?.tts_speed!==void 0?l.settings.tts_speed:1,quality:l.settings?.tts_quality!==void 0?l.settings.tts_quality:10};console.log("[AgentOverlay] Speaking with TTS options:",C),await u(V,de,C)},ae={p:({children:V})=>o.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:V}),ul:({children:V})=>o.jsx("ul",{className:"list-disc pl-4 space-y-1 text-sm",children:V}),ol:({children:V})=>o.jsx("ol",{className:"list-decimal pl-4 space-y-1 text-sm",children:V}),li:({children:V})=>o.jsx("li",{className:"text-sm",children:V}),a:({href:V,children:q})=>o.jsx("a",{href:V,target:"_blank",rel:"noreferrer",className:"text-primary underline underline-offset-2",children:q}),code:V=>{const{inline:q,children:de}=V;return q?o.jsx("code",{className:"px-1 py-0.5 rounded bg-background/60 text-[12px] font-mono",children:de}):o.jsx("code",{className:"text-[12px] font-mono",children:de})},pre:({children:V})=>o.jsx("pre",{className:"mt-2 overflow-x-auto rounded bg-background/60 p-2 text-[12px] font-mono",children:V}),blockquote:({children:V})=>o.jsx("blockquote",{className:"border-l-2 border-border pl-3 text-sm text-muted-foreground",children:V}),strong:({children:V})=>o.jsx("strong",{className:"font-semibold",children:V}),em:({children:V})=>o.jsx("em",{className:"italic",children:V})},L=me("fixed bottom-6 left-6 z-50",e);return o.jsxs(o.Fragment,{children:[p&&o.jsx("div",{className:L,children:o.jsxs("div",{className:me(k?"w-[calc(100vw-2rem)] sm:w-[33vw] sm:max-w-[560px] h-[90vh] max-h-[calc(100vh-6rem)]":"w-[360px] sm:w-[380px] h-[520px] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-6rem)]","bg-background border border-border/60 rounded-2xl shadow-2xl","flex flex-col overflow-hidden","animate-in slide-in-from-bottom-10 fade-in duration-200","transition-[width,height] duration-200 ease-out","motion-reduce:transition-none motion-reduce:animate-none"),children:[o.jsxs("div",{className:"p-3 border-b bg-muted/40 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:me("w-2.5 h-2.5 rounded-full",D?"bg-red-500 animate-pulse":s==="idle"?"bg-muted-foreground":s==="thinking"?"bg-yellow-500 animate-pulse":s==="speaking"?"bg-emerald-500 animate-pulse":"bg-red-500")}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"font-semibold text-sm leading-tight",children:D?m("agent.status.listening"):J7(t.page_id,m)}),o.jsx("span",{className:"text-[10px] text-muted-foreground",children:m(s==="thinking"?"agent.status.analyzing":s==="speaking"?"agent.status.speaking":"agent.status.ready")})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>N(V=>!V),"aria-label":k?"Collapse assistant":"Expand assistant",title:k?"Collapse":"Expand",children:k?o.jsx(QS,{className:"w-4 h-4"}):o.jsx(mA,{className:"w-4 h-4"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(!1),"aria-label":"Close assistant",children:o.jsx(mn,{className:"w-4 h-4"})})]})]}),o.jsxs("div",{ref:R,className:"flex-1 overflow-y-auto p-4 space-y-4 bg-background",children:[n.length===0&&o.jsx("div",{className:"text-center text-muted-foreground text-xs mt-10 whitespace-pre-line",children:qS(t.page_id,m,t.data)}),n.map((V,q)=>{const de=`msg-${q}`,C=d===de,z=V.role!=="user";return o.jsx("div",{className:me("flex flex-col max-w-[85%] rounded-2xl p-3 text-sm relative group",V.role==="user"?"self-end bg-primary/10 text-foreground ml-auto rounded-br-md":"self-start bg-secondary text-secondary-foreground rounded-bl-md"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx("div",{className:"flex-1",children:V.role==="user"?V.content:o.jsx(z9,{remarkPlugins:[W7],components:ae,children:V.content})}),z&&o.jsx("button",{onClick:()=>se(V.content,q),className:me("shrink-0 p-1.5 rounded-md hover:bg-background/60 transition-colors","opacity-0 group-hover:opacity-100",C&&"opacity-100"),title:C?"Stop speaking":"Speak message",children:C?o.jsx(vg,{className:"w-3.5 h-3.5 text-muted-foreground animate-pulse"}):o.jsx(Al,{className:"w-3.5 h-3.5 text-muted-foreground"})})]})},q)}),s==="thinking"&&o.jsxs("div",{className:"self-start bg-secondary/50 rounded-lg p-3 flex gap-1",children:[o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce [animation-delay:-0.3s]"}),o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce [animation-delay:-0.15s]"}),o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce"})]}),D&&o.jsxs("div",{className:"self-start bg-red-500/10 border border-red-500/30 rounded-lg p-4 flex flex-col gap-2 animate-pulse",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(F0,{className:"w-4 h-4 text-red-500 animate-pulse"}),o.jsx("span",{className:"text-xs font-semibold text-red-500",children:m("agent.recording")})]}),o.jsx("div",{className:"flex items-center justify-center gap-1 h-8",children:[...Array(12)].map((V,q)=>o.jsx("div",{className:"w-1 bg-red-500 rounded-full animate-pulse",style:{height:`${20+Math.sin(q)*15}px`,animationDelay:`${q*.1}s`,animationDuration:"0.8s"}},q))}),M&&o.jsxs("div",{className:"text-xs text-muted-foreground italic",children:['"',M,'..."']})]})]}),o.jsxs("div",{className:"p-3 border-t bg-background flex gap-2",children:[o.jsx("input",{className:"flex-1 bg-secondary/40 border border-border/50 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/40 outline-none",placeholder:m(D?"agent.composer.listening":"agent.composer.placeholder"),value:v,onChange:V=>b(V.target.value),onKeyDown:G,disabled:s==="thinking"||s==="speaking"||D}),B&&o.jsx(Z,{size:"icon",variant:D?"default":"outline",className:me("h-9 w-9 shrink-0",D&&"bg-red-500 hover:bg-red-600 animate-pulse"),onClick:he,disabled:s==="thinking"||s==="speaking","aria-label":D?"Stop listening":"Start listening",children:D?o.jsx(yA,{className:"w-4 h-4"}):o.jsx(F0,{className:"w-4 h-4"})}),o.jsx(Z,{size:"icon",className:"h-9 w-9 shrink-0",onClick:Q,disabled:!v.trim()||s==="thinking"||D,"aria-label":"Send message",children:s==="thinking"?o.jsx(Nt,{className:"w-4 h-4 animate-spin"}):o.jsx(Kl,{className:"w-4 h-4"})})]})]})}),o.jsx("div",{className:L,children:o.jsx(Z,{size:"icon",className:me("relative rounded-full h-11 w-11 border border-border/60 bg-primary text-primary-foreground shadow-md","transition-all duration-200 ease-out","hover:bg-primary/90 hover:shadow-lg hover:-translate-y-0.5","active:translate-y-0 active:shadow-md active:scale-95","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-2 focus-visible:ring-offset-background","motion-reduce:transition-none motion-reduce:hover:transform-none",p?"rotate-0 scale-0 opacity-0":"scale-100 opacity-100",s==="speaking"&&"ring-4 ring-emerald-500/30 animate-pulse"),onClick:()=>g(!0),"aria-label":"Open assistant chat",title:"Open assistant chat",children:s==="speaking"?o.jsx(Al,{className:"w-5 h-5 animate-pulse"}):o.jsx(yd,{className:"w-5 h-5"})})})]})}function Q7(){const{state:e,isSubscribed:t,actions:n}=In(),{t:s}=tt(),[a,l]=S.useState(null),[u,d]=S.useState(!0),[h,m]=S.useState(!1),[p,g]=S.useState(!0),[v,b]=S.useState("dashboard"),[w,j]=S.useState(!1),[k,N]=S.useState(null),[R,T]=S.useState(!1),[D,U]=S.useState(!1),[M,B]=S.useState(!1),[P,H]=S.useState(null),[O,Q]=S.useState(!1),[G,he]=S.useState(null),[se,ae]=S.useState(!1),[L,V]=S.useState(!1);if(S.useEffect(()=>{if(e.isInitialized&&e.isAuthenticated&&e.settings&&!e.isLoading&&!e.settings.persona_completed&&!se&&!L){const C=setTimeout(()=>{ae(!0)},2e3);return()=>clearTimeout(C)}},[e.isInitialized,e.isAuthenticated,e.settings,e.isLoading,L]),S.useEffect(()=>{const z=new URLSearchParams(window.location.search).get("code");z&&!w&&(async()=>{j(!0);try{const A=await De.connectGmail(z);if(A.data?.success)ue.success("Gmail connected successfully!"),window.opener?setTimeout(()=>window.close(),1500):(window.history.replaceState({},"",window.location.pathname),n.fetchAccounts());else{const oe=typeof A.error=="string"?A.error:A.error?.message;ue.error(oe||"Failed to connect Gmail")}}catch{ue.error("Connection failed")}finally{j(!1)}})()},[]),w)return o.jsx(rd,{text:s("app.connecting")});S.useEffect(()=>{(async()=>{if(!ao()){m(!0),d(!1);return}try{const{data:oe,error:pe}=await pt.from("init_state").select("is_initialized").single();pe?(console.warn("[App] Init check error (might be fresh DB):",pe),pe.code==="42P01"&&g(!1)):g(oe.is_initialized>0);const{data:{session:we}}=await pt.auth.getSession();if(l(we?.user??null),we?.user){const We=await ly(pt);N(We.needsMigration?We:null),We.needsMigration&&!pL()&&T(!0)}const Se=await wU();Se&&!vU()&&(H(Se),Q(!0))}catch(oe){console.error("[App] Status check failed:",oe),oe instanceof Error&&oe.message.includes("Invalid API key")&&m(!0)}finally{d(!1)}})();const{data:{subscription:z}}=pt.auth.onAuthStateChange((A,oe)=>{l(oe?.user??null),oe||(N(null),T(!1))}),J=()=>{if(Tr.isEnabled()){const A=new(window.AudioContext||window.webkitAudioContext);A.state==="suspended"&&A.resume()}window.removeEventListener("click",J),window.removeEventListener("keydown",J)};return window.addEventListener("click",J),window.addEventListener("keydown",J),()=>{z.unsubscribe(),window.removeEventListener("click",J),window.removeEventListener("keydown",J)}},[]),S.useEffect(()=>{a&&(n.fetchAccounts(),n.fetchRules(),n.fetchSettings(),n.fetchProfile())},[a]),S.useEffect(()=>{const C=async()=>{try{await De.healthCheck()}catch{console.warn("[App] Keep-alive ping failed")}};C();const z=setInterval(C,3e4);return()=>clearInterval(z)},[]);const q=()=>{U(!0),T(!1)},de={migrationStatus:k,showMigrationBanner:R,showMigrationModal:D,openMigrationModal:q,suppressMigrationBanner:M,setSuppressMigrationBanner:B};return u?o.jsxs(o.Fragment,{children:[o.jsx(rd,{text:s("app.loadingWorkspace")}),o.jsx(Uu,{className:"z-[80]"})]}):h?o.jsxs(o.Fragment,{children:[o.jsx(Uk,{onComplete:()=>m(!1)}),o.jsx(Uu,{className:"z-[80]"})]}):a?o.jsx(b5,{value:de,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:()=>b("dashboard"),className:"text-xl font-bold flex items-center gap-2 hover:opacity-80 transition-opacity",children:[o.jsx(cy,{className:"w-8 h-8"}),o.jsx("span",{className:"hidden sm:inline",children:s("app.name")}),o.jsx("span",{className:"sm:hidden",children:"Email AI"})]}),o.jsxs("div",{className:me("flex items-center gap-1.5 px-2 h-6 rounded-full text-[10px] font-bold border transition-colors",t?"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:[t&&o.jsx("span",{className:"absolute inline-flex h-3 w-3 rounded-full bg-emerald-500/40 animate-ping"}),o.jsx("div",{className:me("relative w-2 h-2 rounded-full",t?"bg-emerald-500":"bg-yellow-500")})]}),o.jsx("span",{className:"hidden xs:inline leading-none",children:s(t?"app.statusLive":"app.statusOffline")})]})]}),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:v==="dashboard"?"secondary":"ghost",size:"sm",onClick:()=>b("dashboard"),className:"gap-2",children:[o.jsx(iA,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.dashboard")})]}),o.jsxs(Z,{variant:v==="drafts"?"secondary":"ghost",size:"sm",onClick:()=>b("drafts"),className:"gap-2",children:[o.jsx(qC,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.drafts")||"Drafts"})]}),o.jsxs(Z,{variant:v==="autopilot"?"secondary":"ghost",size:"sm",onClick:()=>b("autopilot"),className:"gap-2",children:[o.jsx(Vu,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.autopilot")})]}),o.jsxs(Z,{variant:v==="analytics"?"secondary":"ghost",size:"sm",onClick:()=>b("analytics"),className:"gap-2",children:[o.jsx(fg,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.analytics")})]}),o.jsxs(Z,{variant:v==="config"?"secondary":"ghost",size:"sm",onClick:()=>b("config"),className:"gap-2",children:[o.jsx(Cl,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:s("nav.configuration")})]})]}),o.jsx("div",{className:"h-6 w-px bg-border/50 mx-2 hidden sm:block"}),o.jsx(iy,{}),o.jsx(v_,{}),o.jsx(Z,{variant:v==="account"?"secondary":"ghost",size:"sm",onClick:()=>b("account"),className:"text-muted-foreground hover:text-foreground p-0 w-8 h-8 rounded-full overflow-hidden border",title:s("nav.accountSettings"),children:e.profile?.avatar_url?o.jsx("img",{src:e.profile.avatar_url,alt:"Profile",className:"w-full h-full object-cover"}):o.jsx(RC,{className:"w-5 h-5"})})]})]})}),o.jsxs("main",{className:"max-w-7xl mx-auto p-4 sm:p-8 mt-4 mb-12",children:[v==="dashboard"&&o.jsx(DI,{}),v==="drafts"&&o.jsx(UI,{onPreview:he}),v==="autopilot"&&o.jsx(oU,{}),v==="config"&&o.jsx($I,{}),v==="analytics"&&o.jsx(eq,{}),v==="account"&&o.jsx(tU,{})]}),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.22.2"]})}),e.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:e.error})})}),k&&R&&!M&&o.jsx(uU,{status:k,onDismiss:()=>T(!1),onLearnMore:q}),P&&O&&o.jsx(_U,{versionInfo:P,onDismiss:()=>Q(!1)}),k&&o.jsx(dU,{open:D,onOpenChange:U,status:k}),G&&o.jsx(FI,{email:G,onClose:()=>he(null),onSend:async C=>{(await fetch(`/api/v1/drafts/${C}/send`,{method:"POST",headers:{Authorization:`Bearer ${localStorage.getItem("supabase.auth.token")}`}})).ok?ue.success(s("drafts.sendSuccess")||"Draft sent successfully!"):ue.error(s("drafts.sendError")||"Failed to send draft")},onDismiss:async C=>{(await fetch(`/api/v1/drafts/${C}/dismiss`,{method:"POST",headers:{Authorization:`Bearer ${localStorage.getItem("supabase.auth.token")}`}})).ok&&ue.success(s("drafts.dismissSuccess")||"Draft dismissed")}}),o.jsx(jU,{}),o.jsx(Uu,{}),o.jsx(Rr,{open:se,onOpenChange:C=>{C||V(!0),ae(C)},children:o.jsxs(Or,{className:"max-w-3xl border-none bg-transparent shadow-none p-0 sm:max-w-3xl",children:[o.jsx(SN,{children:o.jsx(Dr,{children:"Persona Setup Wizard"})}),o.jsx(yN,{onComplete:()=>{ae(!1),n.fetchSettings()},onClose:()=>{ae(!1),V(!0)}})]})})]})}):o.jsxs(o.Fragment,{children:[o.jsx(cU,{onSuccess:()=>n.fetchProfile(),onConfigure:()=>m(!0),isInitialized:p}),o.jsx(Uu,{className:"z-[80]"})]})}function Z7({runId:e,accountEmail:t,isOpen:n,onOpenChange:s}){const{t:a}=tt(),[l,u]=S.useState([]),[d,h]=S.useState(!1);S.useEffect(()=>{n&&e&&m()},[n,e]);const m=async()=>{if(e){h(!0);try{const g=await De.getRunEvents(e);g.data&&u(g.data.events)}catch(g){console.error("Failed to fetch run trace:",g)}finally{h(!1)}}},p=g=>{switch(g){case"analysis":return o.jsx(Hs,{className:"w-4 h-4 text-purple-500"});case"action":return o.jsx(eo,{className:"w-4 h-4 text-emerald-500"});case"error":return o.jsx(mr,{className:"w-4 h-4 text-red-500"});default:return o.jsx(Za,{className:"w-4 h-4 text-blue-500"})}};return o.jsx(Rr,{open:n,onOpenChange:s,children:o.jsxs(Or,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs(Ws,{className:"p-6 border-b",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(gd,{className:"w-5 h-5 text-primary"}),o.jsx(Dr,{children:a("trace.runTrace")})]}),o.jsx(Xs,{children:t?a("trace.fullLogFor").replace("{email}",t):a("trace.historicalLog")})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:d?o.jsx("div",{className:"py-20 flex justify-center",children:o.jsx(rd,{text:a("trace.loadingTrace")})}):l.length===0?o.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:a("trace.noTraceEvents")}):l.map((g,v)=>o.jsxs("div",{className:"relative pl-8",children:[v!==l.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(Js,{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(b=>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:b},b))]}),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:[a("dashboard.done")," ",g.details?.action]}),o.jsx(hg,{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 eq(){const{state:e,actions:t}=In(),{t:n}=tt(),[s,a]=S.useState(null),[l,u]=S.useState(void 0),[d,h]=S.useState(!1),[m,p]=S.useState("overview");if(S.useEffect(()=>{t.fetchStats()},[]),!e.stats)return o.jsx(rd,{text:n("common.loading")});const g=(b,w)=>{a(b),u(w),h(!0)},{stats:v}=e;return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(fg,{className:"w-6 h-6 text-primary"}),n("analytics.title")]}),o.jsxs("div",{className:"flex p-1 bg-muted rounded-lg w-full md:w-auto",children:[o.jsx("button",{onClick:()=>p("overview"),className:`flex-1 md:w-32 px-3 py-1.5 text-sm font-medium rounded-md transition-all ${m==="overview"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/50"}`,children:"Overview"}),o.jsxs("button",{onClick:()=>p("learning"),className:`flex-1 md:w-32 px-3 py-1.5 text-sm font-medium rounded-md transition-all flex items-center justify-center gap-2 ${m==="learning"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/50"}`,children:[o.jsx(Hs,{className:"w-3.5 h-3.5"}),"Learning"]})]})]}),m==="learning"?o.jsx(kU,{}):o.jsxs("div",{className:"space-y-8",children:[o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsx(Bu,{title:n("analytics.totalEmails"),value:v.totalEmails,color:"primary"}),o.jsx(Bu,{title:n("analytics.spamCaught"),value:v.categoryCounts.spam||0,color:"destructive"}),o.jsx(Bu,{title:n("analytics.actionsTaken"),value:Object.values(v.actionCounts).reduce((b,w)=>b+w,0)-(v.actionCounts.none||0),color:"emerald"}),o.jsx(Bu,{title:n("analytics.accounts"),value:v.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:n("analytics.categories")}),o.jsx("div",{className:"space-y-3",children:Object.entries(v.categoryCounts).map(([b,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:b}),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/v.totalEmails*100}%`}})})]})},b))})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.actionsTaken")}),o.jsx("div",{className:"space-y-3",children:Object.entries(v.actionCounts).map(([b,w])=>o.jsxs("div",{className:"flex items-center justify-between py-2 border-b last:border-0",children:[o.jsx("span",{className:"capitalize",children:b}),o.jsx("span",{className:"font-medium",children:w})]},b))})]})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.recentActivity")}),v.recentSyncs.length===0?o.jsx("p",{className:"text-muted-foreground text-sm",children:n("analytics.noActivity")}):o.jsx("div",{className:"space-y-3",children:v.recentSyncs.map(b=>{const w=b.completed_at?Math.round((new Date(b.completed_at).getTime()-new Date(b.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:()=>g(b.id,b.email_accounts?.email_address),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:me("w-2.5 h-2.5 rounded-full",b.status==="success"?"bg-emerald-500":b.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:b.email_accounts?.email_address||n("common.systemSync")}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(Js,{className:"w-3 h-3"}),new Date(b.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.jsx("span",{className:"font-bold text-primary",children:n("analytics.emails").replace("{count}",b.emails_processed.toString())}),o.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[n("analytics.deleted").replace("{count}",b.emails_deleted.toString()),", ",n("analytics.drafted").replace("{count}",b.emails_drafted.toString())]})]})})]},b.id)})})]})]}),o.jsx(Z7,{runId:s,accountEmail:l,isOpen:d,onOpenChange:h})]})}function Bu({title:e,value:t,color:n}){const s={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:e}),o.jsx("p",{className:`text-3xl font-bold ${s[n]||""}`,children:t})]})}function tq(){return o.jsx(cL,{children:o.jsx(kR,{defaultTheme:"system",storageKey:"email-automator-theme",children:o.jsx(S5,{children:o.jsx(w5,{children:o.jsx(uL,{children:o.jsx(dL,{children:o.jsxs(x5,{children:[o.jsx(Q7,{}),o.jsx(m5,{})]})})})})})})})}XE.createRoot(document.getElementById("root")).render(o.jsx($S.StrictMode,{children:o.jsx(tq,{})}));