@realtimex/email-automator 2.11.2 → 2.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/api/src/services/SDKService.ts +18 -7
- package/api/src/services/intelligence.ts +160 -22
- package/api/src/services/processor.ts +9 -2
- package/dist/api/src/services/SDKService.js +18 -7
- package/dist/api/src/services/intelligence.js +153 -21
- package/dist/api/src/services/processor.js +8 -2
- package/dist/assets/{index-BuWrl4UD.js → index-BgMWzGP9.js} +3 -3
- package/dist/index.html +1 -1
- package/package.json +1 -1
|
@@ -56,7 +56,7 @@ ${C}`}class mt extends Error{constructor({message:e,code:a,cause:r,name:o}){var
|
|
|
56
56
|
${C}px !important;
|
|
57
57
|
${M}px !important;
|
|
58
58
|
}
|
|
59
|
-
`),()=>{V.contains(k)&&V.removeChild(k)}},[e]),c.jsx(j4,{isPresent:e,childRef:d,sizeRef:f,children:w.cloneElement(t,{ref:y})})}const E4=({children:t,initial:e,isPresent:a,onExitComplete:r,custom:o,presenceAffectsLayout:u,mode:d,anchorX:f,anchorY:p,root:g})=>{const y=Um(N4),v=w.useId();let b=!0,S=w.useMemo(()=>(b=!1,{id:v,initial:e,isPresent:a,custom:o,onExitComplete:T=>{y.set(T,!0);for(const j of y.values())if(!j)return;r&&r()},register:T=>(y.set(T,!1),()=>y.delete(T))}),[a,y,r]);return u&&b&&(S={...S}),w.useMemo(()=>{y.forEach((T,j)=>y.set(j,!1))},[a]),w.useEffect(()=>{!a&&!y.size&&r&&r()},[a]),d==="popLayout"&&(t=c.jsx(T4,{isPresent:a,anchorX:f,anchorY:p,root:g,children:t})),c.jsx(ju.Provider,{value:S,children:t})};function N4(){return new Map}function G1(t=!0){const e=w.useContext(ju);if(e===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:o}=e,u=w.useId();w.useEffect(()=>{if(t)return o(u)},[t]);const d=w.useCallback(()=>t&&r&&r(u),[u,r,t]);return!a&&r?[!1,d]:[!0]}const Lc=t=>t.key||"";function Qx(t){const e=[];return w.Children.forEach(t,a=>{w.isValidElement(a)&&e.push(a)}),e}const K1=({children:t,custom:e,initial:a=!0,onExitComplete:r,presenceAffectsLayout:o=!0,mode:u="sync",propagate:d=!1,anchorX:f="left",anchorY:p="top",root:g})=>{const[y,v]=G1(d),b=w.useMemo(()=>Qx(t),[t]),S=d&&!y?[]:b.map(Lc),T=w.useRef(!0),j=w.useRef(b),E=Um(()=>new Map),C=w.useRef(new Set),[M,k]=w.useState(b),[V,q]=w.useState(b);_w(()=>{T.current=!1,j.current=b;for(let B=0;B<V.length;B++){const W=Lc(V[B]);S.includes(W)?(E.delete(W),C.current.delete(W)):E.get(W)!==!0&&E.set(W,!1)}},[V,S.length,S.join("-")]);const G=[];if(b!==M){let B=[...b];for(let W=0;W<V.length;W++){const me=V[W],ue=Lc(me);S.includes(ue)||(B.splice(W,0,me),G.push(me))}return u==="wait"&&G.length&&(B=G),q(Qx(B)),k(b),null}const{forceRender:$}=w.useContext(zm);return c.jsx(c.Fragment,{children:V.map(B=>{const W=Lc(B),me=d&&!y?!1:b===V||S.includes(W),ue=()=>{if(C.current.has(W))return;if(C.current.add(W),E.has(W))E.set(W,!0);else return;let pe=!0;E.forEach(ze=>{ze||(pe=!1)}),pe&&($?.(),q(j.current),d&&v?.(),r&&r())};return c.jsx(E4,{isPresent:me,initial:!T.current||a?void 0:!1,custom:e,presenceAffectsLayout:o,mode:u,root:g,onExitComplete:me?void 0:ue,anchorX:f,anchorY:p,children:B},W)})})},F1=w.createContext({strict:!1}),eb={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 tb=!1;function A4(){if(tb)return;const t={};for(const e in eb)t[e]={isEnabled:a=>eb[e].some(r=>!!a[r])};w1(t),tb=!0}function Y1(){return A4(),mO()}function C4(t){const e=Y1();for(const a in t)e[a]={...e[a],...t[a]};w1(e)}const k4=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 yu(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||k4.has(t)}let X1=t=>!yu(t);function R4(t){typeof t=="function"&&(X1=e=>e.startsWith("on")?!yu(e):t(e))}try{R4(require("@emotion/is-prop-valid").default)}catch{}function O4(t,e,a){const r={};for(const o in t)o==="values"&&typeof t.values=="object"||(X1(o)||a===!0&&yu(o)||!e&&!yu(o)||t.draggable&&o.startsWith("onDrag"))&&(r[o]=t[o]);return r}const Nu=w.createContext({});function D4(t,e){if(Eu(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Xo(a)?a:void 0,animate:Xo(r)?r:void 0}}return t.inherit!==!1?e:{}}function M4(t){const{initial:e,animate:a}=D4(t,w.useContext(Nu));return w.useMemo(()=>({initial:e,animate:a}),[nb(e),nb(a)])}function nb(t){return Array.isArray(t)?t.join(" "):t}const dp=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function J1(t,e,a){for(const r in e)!Bt(e[r])&&!A1(r,a)&&(t[r]=e[r])}function z4({transformTemplate:t},e){return w.useMemo(()=>{const a=dp();return lp(a,e,t),Object.assign({},a.vars,a.style)},[e])}function U4(t,e){const a=t.style||{},r={};return J1(r,a,t),Object.assign(r,z4(t,e)),r}function L4(t,e){const a={},r=U4(t,e);return t.drag&&t.dragListener!==!1&&(a.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(a.tabIndex=0),a.style=r,a}const W1=()=>({...dp(),attrs:{}});function P4(t,e,a,r){const o=w.useMemo(()=>{const u=W1();return C1(u,e,R1(r),t.transformTemplate,t.style),{...u.attrs,style:{...u.style}}},[e]);if(t.style){const u={};J1(u,t.style,t),o.style={...u,...o.style}}return o}const V4=["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 hp(t){return typeof t!="string"||t.includes("-")?!1:!!(V4.indexOf(t)>-1||/[A-Z]/u.test(t))}function B4(t,e,a,{latestValues:r},o,u=!1,d){const p=(d??hp(t)?P4:L4)(e,r,o,t),g=O4(e,typeof t=="string",u),y=t!==w.Fragment?{...g,...p,ref:a}:{},{children:v}=e,b=w.useMemo(()=>Bt(v)?v.get():v,[v]);return w.createElement(t,{...y,children:b})}function I4({scrapeMotionValuesFromProps:t,createRenderState:e},a,r,o){return{latestValues:$4(a,r,o,t),renderState:e()}}function $4(t,e,a,r){const o={},u=r(t,{});for(const b in u)o[b]=Yc(u[b]);let{initial:d,animate:f}=t;const p=Eu(t),g=b1(t);e&&g&&!p&&t.inherit!==!1&&(d===void 0&&(d=e.initial),f===void 0&&(f=e.animate));let y=a?a.initial===!1:!1;y=y||d===!1;const v=y?f:d;if(v&&typeof v!="boolean"&&!Tu(v)){const b=Array.isArray(v)?v:[v];for(let S=0;S<b.length;S++){const T=tp(t,b[S]);if(T){const{transitionEnd:j,transition:E,...C}=T;for(const M in C){let k=C[M];if(Array.isArray(k)){const V=y?k.length-1:0;k=k[V]}k!==null&&(o[M]=k)}for(const M in j)o[M]=j[M]}}}return o}const Z1=t=>(e,a)=>{const r=w.useContext(Nu),o=w.useContext(ju),u=()=>I4(t,e,r,o);return a?u():Um(u)},q4=Z1({scrapeMotionValuesFromProps:cp,createRenderState:dp}),H4=Z1({scrapeMotionValuesFromProps:O1,createRenderState:W1}),G4=Symbol.for("motionComponentSymbol");function K4(t,e,a){const r=w.useRef(a);w.useInsertionEffect(()=>{r.current=a});const o=w.useRef(null);return w.useCallback(u=>{u&&t.onMount?.(u),e&&(u?e.mount(u):e.unmount());const d=r.current;if(typeof d=="function")if(u){const f=d(u);typeof f=="function"&&(o.current=f)}else o.current?(o.current(),o.current=null):d(u);else d&&(d.current=u)},[e])}const Q1=w.createContext({});function ko(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function F4(t,e,a,r,o,u){const{visualElement:d}=w.useContext(Nu),f=w.useContext(F1),p=w.useContext(ju),g=w.useContext(up).reducedMotion,y=w.useRef(null),v=w.useRef(!1);r=r||f.renderer,!y.current&&r&&(y.current=r(t,{visualState:e,parent:d,props:a,presenceContext:p,blockInitialAnimation:p?p.initial===!1:!1,reducedMotionConfig:g,isSVG:u}),v.current&&y.current&&(y.current.manuallyAnimateOnMount=!0));const b=y.current,S=w.useContext(Q1);b&&!b.projection&&o&&(b.type==="html"||b.type==="svg")&&Y4(y.current,a,o,S);const T=w.useRef(!1);w.useInsertionEffect(()=>{b&&T.current&&b.update(a,p)});const j=a[i1],E=w.useRef(!!j&&!window.MotionHandoffIsComplete?.(j)&&window.MotionHasOptimisedAnimation?.(j));return _w(()=>{v.current=!0,b&&(T.current=!0,window.MotionIsMounted=!0,b.updateFeatures(),b.scheduleRenderMicrotask(),E.current&&b.animationState&&b.animationState.animateChanges())}),w.useEffect(()=>{b&&(!E.current&&b.animationState&&b.animationState.animateChanges(),E.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(j)}),E.current=!1),b.enteringChildren=void 0)}),b}function Y4(t,e,a,r){const{layoutId:o,layout:u,drag:d,dragConstraints:f,layoutScroll:p,layoutRoot:g,layoutCrossfade:y}=e;t.projection=new a(t.latestValues,e["data-framer-portal-id"]?void 0:eS(t.parent)),t.projection.setOptions({layoutId:o,layout:u,alwaysMeasureLayout:!!d||f&&ko(f),visualElement:t,animationType:typeof u=="string"?u:"both",initialPromotionConfig:r,crossfade:y,layoutScroll:p,layoutRoot:g})}function eS(t){if(t)return t.options.allowProjection!==!1?t.projection:eS(t.parent)}function bf(t,{forwardMotionProps:e=!1,type:a}={},r,o){r&&C4(r);const u=a?a==="svg":hp(t),d=u?H4:q4;function f(g,y){let v;const b={...w.useContext(up),...g,layoutId:X4(g)},{isStatic:S}=b,T=M4(g),j=d(g,S);if(!S&&Sw){J4();const E=W4(b);v=E.MeasureLayout,T.visualElement=F4(t,j,b,o,E.ProjectionNode,u)}return c.jsxs(Nu.Provider,{value:T,children:[v&&T.visualElement?c.jsx(v,{visualElement:T.visualElement,...b}):null,B4(t,g,K4(j,T.visualElement,y),j,S,e,u)]})}f.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const p=w.forwardRef(f);return p[G4]=t,p}function X4({layoutId:t}){const e=w.useContext(zm).id;return e&&t!==void 0?e+"-"+t:t}function J4(t,e){w.useContext(F1).strict}function W4(t){const e=Y1(),{drag:a,layout:r}=e;if(!a&&!r)return{};const o={...a,...r};return{MeasureLayout:a?.isEnabled(t)||r?.isEnabled(t)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function Z4(t,e){if(typeof Proxy>"u")return bf;const a=new Map,r=(u,d)=>bf(u,d,t,e),o=(u,d)=>r(u,d);return new Proxy(o,{get:(u,d)=>d==="create"?r:(a.has(d)||a.set(d,bf(d,void 0,t,e)),a.get(d))})}const Q4=(t,e)=>e.isSVG??hp(t)?new RO(e):new TO(e,{allowProjection:t!==w.Fragment});class e5 extends ga{constructor(e){super(e),e.animationState||(e.animationState=UO(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Tu(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:a}=this.node.prevProps||{};e!==a&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let t5=0;class n5 extends ga{constructor(){super(...arguments),this.id=t5++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:a}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===r)return;const o=this.node.animationState.setActive("exit",!e);a&&!e&&o.then(()=>{a(this.id)})}mount(){const{register:e,onExitComplete:a}=this.node.presenceContext||{};a&&a(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const s5={animation:{Feature:e5},exit:{Feature:n5}};function rl(t){return{point:{x:t.pageX,y:t.pageY}}}const a5=t=>e=>rp(e)&&t(e,rl(e));function Uo(t,e,a,r){return Jo(t,e,a5(a),r)}const tS=({current:t})=>t?t.ownerDocument.defaultView:null,sb=(t,e)=>Math.abs(t-e);function r5(t,e){const a=sb(t.x,e.x),r=sb(t.y,e.y);return Math.sqrt(a**2+r**2)}const ab=new Set(["auto","scroll"]);class nS{constructor(e,a,{transformPagePoint:r,contextWindow:o=window,dragSnapToOrigin:u=!1,distanceThreshold:d=3,element:f}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=Sf(this.lastMoveEventInfo,this.history),T=this.startEvent!==null,j=r5(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!T&&!j)return;const{point:E}=S,{timestamp:C}=Dt;this.history.push({...E,timestamp:C});const{onStart:M,onMove:k}=this.handlers;T||(M&&M(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),k&&k(this.lastMoveEvent,S)},this.handlePointerMove=(S,T)=>{this.lastMoveEvent=S,this.lastMoveEventInfo=wf(T,this.transformPagePoint),Ze.update(this.updatePoint,!0)},this.handlePointerUp=(S,T)=>{this.end();const{onEnd:j,onSessionEnd:E,resumeAnimation:C}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&C&&C(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const M=Sf(S.type==="pointercancel"?this.lastMoveEventInfo:wf(T,this.transformPagePoint),this.history);this.startEvent&&j&&j(S,M),E&&E(S,M)},!rp(e))return;this.dragSnapToOrigin=u,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=d,this.contextWindow=o||window;const p=rl(e),g=wf(p,this.transformPagePoint),{point:y}=g,{timestamp:v}=Dt;this.history=[{...y,timestamp:v}];const{onSessionStart:b}=a;b&&b(e,Sf(g,this.history)),this.removeListeners=nl(Uo(this.contextWindow,"pointermove",this.handlePointerMove),Uo(this.contextWindow,"pointerup",this.handlePointerUp),Uo(this.contextWindow,"pointercancel",this.handlePointerUp)),f&&this.startScrollTracking(f)}startScrollTracking(e){let a=e.parentElement;for(;a;){const r=getComputedStyle(a);(ab.has(r.overflowX)||ab.has(r.overflowY))&&this.scrollPositions.set(a,{x:a.scrollLeft,y:a.scrollTop}),a=a.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(e){const a=this.scrollPositions.get(e);if(!a)return;const r=e===window,o=r?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},u={x:o.x-a.x,y:o.y-a.y};u.x===0&&u.y===0||(r?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=u.x,this.lastMoveEventInfo.point.y+=u.y):this.history.length>0&&(this.history[0].x-=u.x,this.history[0].y-=u.y),this.scrollPositions.set(e,o),Ze.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),ma(this.updatePoint)}}function wf(t,e){return e?{point:e(t.point)}:t}function rb(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Sf({point:t},e){return{point:t,delta:rb(t,sS(e)),offset:rb(t,i5(e)),velocity:o5(e,.1)}}function i5(t){return t[0]}function sS(t){return t[t.length-1]}function o5(t,e){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const o=sS(t);for(;a>=0&&(r=t[a],!(o.timestamp-r.timestamp>Ss(e)));)a--;if(!r)return{x:0,y:0};const u=jn(o.timestamp-r.timestamp);if(u===0)return{x:0,y:0};const d={x:(o.x-r.x)/u,y:(o.y-r.y)/u};return d.x===1/0&&(d.x=0),d.y===1/0&&(d.y=0),d}function l5(t,{min:e,max:a},r){return e!==void 0&&t<e?t=r?nt(e,t,r.min):Math.max(t,e):a!==void 0&&t>a&&(t=r?nt(a,t,r.max):Math.min(t,a)),t}function ib(t,e,a){return{min:e!==void 0?t.min+e:void 0,max:a!==void 0?t.max+a-(t.max-t.min):void 0}}function c5(t,{top:e,left:a,bottom:r,right:o}){return{x:ib(t.x,a,o),y:ib(t.y,e,r)}}function ob(t,e){let a=e.min-t.min,r=e.max-t.max;return e.max-e.min<t.max-t.min&&([a,r]=[r,a]),{min:a,max:r}}function u5(t,e){return{x:ob(t.x,e.x),y:ob(t.y,e.y)}}function d5(t,e){let a=.5;const r=qt(t),o=qt(e);return o>r?a=Ko(e.min,e.max-r,t.min):r>o&&(a=Ko(t.min,t.max-o,e.min)),Fn(0,1,a)}function h5(t,e){const a={};return e.min!==void 0&&(a.min=e.min-t.min),e.max!==void 0&&(a.max=e.max-t.min),a}const ym=.35;function f5(t=ym){return t===!1?t=0:t===!0&&(t=ym),{x:lb(t,"left","right"),y:lb(t,"top","bottom")}}function lb(t,e,a){return{min:cb(t,e),max:cb(t,a)}}function cb(t,e){return typeof t=="number"?t:t[e]||0}const m5=new WeakMap;class p5{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=bt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const u=v=>{a?(this.stopAnimation(),this.snapToCursor(rl(v).point)):this.pauseAnimation()},d=(v,b)=>{this.stopAnimation();const{drag:S,dragPropagation:T,onDragStart:j}=this.getProps();if(S&&!T&&(this.openDragLock&&this.openDragLock(),this.openDragLock=nO(S),!this.openDragLock))return;this.latestPointerEvent=v,this.latestPanInfo=b,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),_n(C=>{let M=this.getAxisMotionValue(C).get()||0;if(Kn.test(M)){const{projection:k}=this.visualElement;if(k&&k.layout){const V=k.layout.layoutBox[C];V&&(M=qt(V)*(parseFloat(M)/100))}}this.originPoint[C]=M}),j&&Ze.postRender(()=>j(v,b)),cm(this.visualElement,"transform");const{animationState:E}=this.visualElement;E&&E.setActive("whileDrag",!0)},f=(v,b)=>{this.latestPointerEvent=v,this.latestPanInfo=b;const{dragPropagation:S,dragDirectionLock:T,onDirectionLock:j,onDrag:E}=this.getProps();if(!S&&!this.openDragLock)return;const{offset:C}=b;if(T&&this.currentDirection===null){this.currentDirection=g5(C),this.currentDirection!==null&&j&&j(this.currentDirection);return}this.updateAxis("x",b.point,C),this.updateAxis("y",b.point,C),this.visualElement.render(),E&&E(v,b)},p=(v,b)=>{this.latestPointerEvent=v,this.latestPanInfo=b,this.stop(v,b),this.latestPointerEvent=null,this.latestPanInfo=null},g=()=>_n(v=>this.getAnimationState(v)==="paused"&&this.getAxisMotionValue(v).animation?.play()),{dragSnapToOrigin:y}=this.getProps();this.panSession=new nS(e,{onSessionStart:u,onStart:d,onMove:f,onSessionEnd:p,resumeAnimation:g},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:y,distanceThreshold:r,contextWindow:tS(this.visualElement),element:this.visualElement.current})}stop(e,a){const r=e||this.latestPointerEvent,o=a||this.latestPanInfo,u=this.isDragging;if(this.cancel(),!u||!o||!r)return;const{velocity:d}=o;this.startAnimation(d);const{onDragEnd:f}=this.getProps();f&&Ze.postRender(()=>f(r,o))}cancel(){this.isDragging=!1;const{projection:e,animationState:a}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),a&&a.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,a,r){const{drag:o}=this.getProps();if(!r||!Pc(e,o,this.currentDirection))return;const u=this.getAxisMotionValue(e);let d=this.originPoint[e]+r[e];this.constraints&&this.constraints[e]&&(d=l5(d,this.constraints[e],this.elastic[e])),u.set(d)}resolveConstraints(){const{dragConstraints:e,dragElastic:a}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;e&&ko(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&r?this.constraints=c5(r.layoutBox,e):this.constraints=!1,this.elastic=f5(a),o!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&_n(u=>{this.constraints!==!1&&this.getAxisMotionValue(u)&&(this.constraints[u]=h5(r.layoutBox[u],this.constraints[u]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:a}=this.getProps();if(!e||!ko(e))return!1;const r=e.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const u=xO(r,o.root,this.visualElement.getTransformPagePoint());let d=u5(o.layout.layoutBox,u);if(a){const f=a(gO(d));this.hasMutatedConstraints=!!f,f&&(d=_1(f))}return d}startAnimation(e){const{drag:a,dragMomentum:r,dragElastic:o,dragTransition:u,dragSnapToOrigin:d,onDragTransitionEnd:f}=this.getProps(),p=this.constraints||{},g=_n(y=>{if(!Pc(y,a,this.currentDirection))return;let v=p&&p[y]||{};d&&(v={min:0,max:0});const b=o?200:1e6,S=o?40:1e7,T={type:"inertia",velocity:r?e[y]:0,bounceStiffness:b,bounceDamping:S,timeConstant:750,restDelta:1,restSpeed:10,...u,...v};return this.startAxisValueAnimation(y,T)});return Promise.all(g).then(f)}startAxisValueAnimation(e,a){const r=this.getAxisMotionValue(e);return cm(this.visualElement,e),r.start(ep(e,r,0,a,this.visualElement,!1))}stopAnimation(){_n(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){_n(e=>this.getAxisMotionValue(e).animation?.pause())}getAnimationState(e){return this.getAxisMotionValue(e).animation?.state}getAxisMotionValue(e){const a=`_drag${e.toUpperCase()}`,r=this.visualElement.getProps(),o=r[a];return o||this.visualElement.getValue(e,(r.initial?r.initial[e]:void 0)||0)}snapToCursor(e){_n(a=>{const{drag:r}=this.getProps();if(!Pc(a,r,this.currentDirection))return;const{projection:o}=this.visualElement,u=this.getAxisMotionValue(a);if(o&&o.layout){const{min:d,max:f}=o.layout.layoutBox[a],p=u.get()||0;u.set(e[a]-nt(d,f,.5)+p)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!ko(a)||!r||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};_n(d=>{const f=this.getAxisMotionValue(d);if(f&&this.constraints!==!1){const p=f.get();o[d]=d5({min:p,max:p},this.constraints[d])}});const{transformTemplate:u}=this.visualElement.getProps();this.visualElement.current.style.transform=u?u({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),_n(d=>{if(!Pc(d,e,null))return;const f=this.getAxisMotionValue(d),{min:p,max:g}=this.constraints[d];f.set(nt(p,g,o[d]))})}addListeners(){if(!this.visualElement.current)return;m5.set(this.visualElement,this);const e=this.visualElement.current,a=Uo(e,"pointerdown",p=>{const{drag:g,dragListener:y=!0}=this.getProps(),v=p.target,b=v!==e&&y1(v);g&&y&&!b&&this.start(p)}),r=()=>{const{dragConstraints:p}=this.getProps();ko(p)&&p.current&&(this.constraints=this.resolveRefConstraints())},{projection:o}=this.visualElement,u=o.addEventListener("measure",r);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),Ze.read(r);const d=Jo(window,"resize",()=>this.scalePositionWithinConstraints()),f=o.addEventListener("didUpdate",(({delta:p,hasLayoutChanged:g})=>{this.isDragging&&g&&(_n(y=>{const v=this.getAxisMotionValue(y);v&&(this.originPoint[y]+=p[y].translate,v.set(v.get()+p[y].translate))}),this.visualElement.render())}));return()=>{d(),a(),u(),f&&f()}}getProps(){const e=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:o=!1,dragConstraints:u=!1,dragElastic:d=ym,dragMomentum:f=!0}=e;return{...e,drag:a,dragDirectionLock:r,dragPropagation:o,dragConstraints:u,dragElastic:d,dragMomentum:f}}}function Pc(t,e,a){return(e===!0||e===t)&&(a===null||a===t)}function g5(t,e=10){let a=null;return Math.abs(t.y)>e?a="y":Math.abs(t.x)>e&&(a="x"),a}class y5 extends ga{constructor(e){super(e),this.removeGroupControls=Tn,this.removeListeners=Tn,this.controls=new p5(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Tn}update(){const{dragControls:e}=this.node.getProps(),{dragControls:a}=this.node.prevProps||{};e!==a&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const ub=t=>(e,a)=>{t&&Ze.postRender(()=>t(e,a))};class v5 extends ga{constructor(){super(...arguments),this.removePointerDownListener=Tn}onPointerDown(e){this.session=new nS(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:tS(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:a,onPan:r,onPanEnd:o}=this.node.getProps();return{onSessionStart:ub(e),onStart:ub(a),onMove:r,onEnd:(u,d)=>{delete this.session,o&&Ze.postRender(()=>o(u,d))}}}mount(){this.removePointerDownListener=Uo(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let _f=!1;class x5 extends w.Component{componentDidMount(){const{visualElement:e,layoutGroup:a,switchLayoutGroup:r,layoutId:o}=this.props,{projection:u}=e;u&&(a.group&&a.group.add(u),r&&r.register&&o&&r.register(u),_f&&u.root.didUpdate(),u.addEventListener("animationComplete",()=>{this.safeToRemove()}),u.setOptions({...u.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Xc.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:a,visualElement:r,drag:o,isPresent:u}=this.props,{projection:d}=r;return d&&(d.isPresent=u,e.layoutDependency!==a&&d.setOptions({...d.options,layoutDependency:a}),_f=!0,o||e.layoutDependency!==a||a===void 0||e.isPresent!==u?d.willUpdate():this.safeToRemove(),e.isPresent!==u&&(u?d.promote():d.relegate()||Ze.postRender(()=>{const f=d.getStack();(!f||!f.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),ap.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:o}=e;_f=!0,o&&(o.scheduleCheckAfterUnmount(),a&&a.group&&a.group.remove(o),r&&r.deregister&&r.deregister(o))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function aS(t){const[e,a]=G1(),r=w.useContext(zm);return c.jsx(x5,{...t,layoutGroup:r,switchLayoutGroup:w.useContext(Q1),isPresent:e,safeToRemove:a})}const b5={pan:{Feature:v5},drag:{Feature:y5,ProjectionNode:H1,MeasureLayout:aS}};function db(t,e,a){const{props:r}=t;t.animationState&&r.whileHover&&t.animationState.setActive("whileHover",a==="Start");const o="onHover"+a,u=r[o];u&&Ze.postRender(()=>u(e,rl(e)))}class w5 extends ga{mount(){const{current:e}=this.node;e&&(this.unmount=sO(e,(a,r)=>(db(this.node,r,"Start"),o=>db(this.node,o,"End"))))}unmount(){}}class S5 extends ga{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!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=nl(Jo(this.node.current,"focus",()=>this.onFocus()),Jo(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function hb(t,e,a){const{props:r}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&r.whileTap&&t.animationState.setActive("whileTap",a==="Start");const o="onTap"+(a==="End"?"":a),u=r[o];u&&Ze.postRender(()=>u(e,rl(e)))}class _5 extends ga{mount(){const{current:e}=this.node;e&&(this.unmount=iO(e,(a,r)=>(hb(this.node,r,"Start"),(o,{success:u})=>hb(this.node,o,u?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const vm=new WeakMap,jf=new WeakMap,j5=t=>{const e=vm.get(t.target);e&&e(t)},T5=t=>{t.forEach(j5)};function E5({root:t,...e}){const a=t||document;jf.has(a)||jf.set(a,{});const r=jf.get(a),o=JSON.stringify(e);return r[o]||(r[o]=new IntersectionObserver(T5,{root:t,...e})),r[o]}function N5(t,e,a){const r=E5(e);return vm.set(t,a),r.observe(t),()=>{vm.delete(t),r.unobserve(t)}}const A5={some:0,all:1};class C5 extends ga{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:a,margin:r,amount:o="some",once:u}=e,d={root:a?a.current:void 0,rootMargin:r,threshold:typeof o=="number"?o:A5[o]},f=p=>{const{isIntersecting:g}=p;if(this.isInView===g||(this.isInView=g,u&&!g&&this.hasEnteredView))return;g&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",g);const{onViewportEnter:y,onViewportLeave:v}=this.node.getProps(),b=g?y:v;b&&b(p)};return N5(this.node.current,d,f)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:a}=this.node;["amount","margin","root"].some(k5(e,a))&&this.startObserver()}unmount(){}}function k5({viewport:t={}},{viewport:e={}}={}){return a=>t[a]!==e[a]}const R5={inView:{Feature:C5},tap:{Feature:_5},focus:{Feature:S5},hover:{Feature:w5}},O5={layout:{ProjectionNode:H1,MeasureLayout:aS}},D5={...s5,...R5,...b5,...O5},vs=Z4(D5,Q4),ii="2.11.2",M5="20260130000001";function z5(t,e){const a=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<Math.max(a.length,r.length);o++){const u=a[o]||0,d=r[o]||0;if(u>d)return 1;if(u<d)return-1}return 0}async function U5(t){try{const{data:e,error:a}=await t.rpc("get_latest_migration_timestamp");return a?a.code==="42883"?(console.info("[Migration Check] RPC function missing - assuming fresh DB."),{version:null,latestMigrationTimestamp:"0"}):(console.warn("Could not get latest migration timestamp:",a.message),{version:null,latestMigrationTimestamp:null}):{version:ii,latestMigrationTimestamp:e||null}}catch(e){return console.error("Error checking database migration info:",e),{version:null,latestMigrationTimestamp:null}}}async function fp(t){const e=ii,a=M5,r=await U5(t);if(console.log("[Migration Check]",{appVersion:e,appMigrationTimestamp:a,dbVersion:r.version,dbMigrationTimestamp:r.latestMigrationTimestamp}),r.latestMigrationTimestamp&&r.latestMigrationTimestamp.trim()!==""){const o=a,u=r.latestMigrationTimestamp;return o>u?{needsMigration:!0,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:u,message:`New migrations available. Database is at ${u}, app has ${o}.`}:o<u?(console.warn("[Migration Check] DB is ahead of app - possible downgrade"),{needsMigration:!1,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:u,message:`Database (${u}) is ahead of app (${o}).`}):(console.log("[Migration Check] Timestamps match - database is up-to-date"),{needsMigration:!1,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:u,message:"Database schema is up-to-date."})}if(r.version){console.log("[Migration Check] Legacy DB detected (no timestamp). Falling back to SemVer.");const o=z5(e,r.version);return o>0?{needsMigration:!0,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:null,message:`Database schema (v${r.version}) is outdated. Migration to v${e} required.`}:o===0?(console.warn("[Migration Check] Legacy DB with matching version - forcing migration to add timestamp tracking"),{needsMigration:!0,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:null,message:`Database lacks timestamp tracking. Please run migration to upgrade to modern schema (v${e}).`}):{needsMigration:!1,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:null,message:`Database version (v${r.version}) is ahead of app (v${e}).`}}return console.log("[Migration Check] No DB info found - assuming migration needed"),{needsMigration:!0,appVersion:e,dbVersion:null,latestMigrationTimestamp:null,message:`Database schema unknown. Migration required to v${e}.`}}const rS="email_automator_migration_reminder_dismissed_at";function L5(t=24){try{const e=localStorage.getItem(rS);if(!e)return!1;const a=new Date(e).getTime();return(Date.now()-a)/(1e3*60*60)<t}catch(e){return console.error("Error checking migration reminder:",e),!1}}function P5(){try{localStorage.setItem(rS,new Date().toISOString())}catch(t){console.error("Error dismissing migration reminder:",t)}}const xm={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 V5(t,e){switch(e.type){case"SET_STEP":return{...t,step:e.payload,error:null};case"SET_ACCESS_TOKEN":return{...t,managed:{...t.managed,accessToken:e.payload}};case"SET_ORGANIZATIONS":return{...t,managed:{...t.managed,organizations:e.payload,selectedOrg:e.payload.length>0?e.payload[0].id:""}};case"SET_SELECTED_ORG":return{...t,managed:{...t.managed,selectedOrg:e.payload}};case"SET_PROJECT_NAME":return{...t,managed:{...t.managed,projectName:e.payload}};case"SET_REGION":return{...t,managed:{...t.managed,region:e.payload}};case"SET_FETCHING_ORGS":return{...t,managed:{...t.managed,isFetchingOrgs:e.payload}};case"SET_MANUAL_URL":return{...t,manual:{...t.manual,url:e.payload}};case"SET_MANUAL_ANON_KEY":return{...t,manual:{...t.manual,anonKey:e.payload}};case"SET_PROJECT_ID":return{...t,projectId:e.payload};case"ADD_LOG":return{...t,logs:[...t.logs,{...e.payload,timestamp:Date.now()}].slice(-500)};case"CLEAR_LOGS":return{...t,logs:[]};case"SET_ERROR":return{...t,error:e.payload};case"SET_MIGRATING":return{...t,isMigrating:e.payload};case"SET_MIGRATION_STATUS":return{...t,migrationStatus:e.payload};case"RESET_MANAGED_FLOW":return{...t,managed:{...xm.managed},error:null};case"RESET_MANUAL_FLOW":return{...t,manual:{...xm.manual},error:null};default:return t}}function Tf(t){const e=t.trim();return e?e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}.supabase.co`:""}function iS(t){const e=t.trim();return e?e.startsWith("sbp_")?e.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 fb(t){const e=t.trim();if(!e)return null;if(!e.includes(".")&&!e.includes("/"))return e;try{return new URL(e.startsWith("http")?e:`https://${e}`).hostname.split(".")[0]||null}catch{return null}}class B5{buffer="";processChunk(e){const a=[];this.buffer+=e;const r=this.buffer.split(`
|
|
59
|
+
`),()=>{V.contains(k)&&V.removeChild(k)}},[e]),c.jsx(j4,{isPresent:e,childRef:d,sizeRef:f,children:w.cloneElement(t,{ref:y})})}const E4=({children:t,initial:e,isPresent:a,onExitComplete:r,custom:o,presenceAffectsLayout:u,mode:d,anchorX:f,anchorY:p,root:g})=>{const y=Um(N4),v=w.useId();let b=!0,S=w.useMemo(()=>(b=!1,{id:v,initial:e,isPresent:a,custom:o,onExitComplete:T=>{y.set(T,!0);for(const j of y.values())if(!j)return;r&&r()},register:T=>(y.set(T,!1),()=>y.delete(T))}),[a,y,r]);return u&&b&&(S={...S}),w.useMemo(()=>{y.forEach((T,j)=>y.set(j,!1))},[a]),w.useEffect(()=>{!a&&!y.size&&r&&r()},[a]),d==="popLayout"&&(t=c.jsx(T4,{isPresent:a,anchorX:f,anchorY:p,root:g,children:t})),c.jsx(ju.Provider,{value:S,children:t})};function N4(){return new Map}function G1(t=!0){const e=w.useContext(ju);if(e===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:o}=e,u=w.useId();w.useEffect(()=>{if(t)return o(u)},[t]);const d=w.useCallback(()=>t&&r&&r(u),[u,r,t]);return!a&&r?[!1,d]:[!0]}const Lc=t=>t.key||"";function Qx(t){const e=[];return w.Children.forEach(t,a=>{w.isValidElement(a)&&e.push(a)}),e}const K1=({children:t,custom:e,initial:a=!0,onExitComplete:r,presenceAffectsLayout:o=!0,mode:u="sync",propagate:d=!1,anchorX:f="left",anchorY:p="top",root:g})=>{const[y,v]=G1(d),b=w.useMemo(()=>Qx(t),[t]),S=d&&!y?[]:b.map(Lc),T=w.useRef(!0),j=w.useRef(b),E=Um(()=>new Map),C=w.useRef(new Set),[M,k]=w.useState(b),[V,q]=w.useState(b);_w(()=>{T.current=!1,j.current=b;for(let B=0;B<V.length;B++){const W=Lc(V[B]);S.includes(W)?(E.delete(W),C.current.delete(W)):E.get(W)!==!0&&E.set(W,!1)}},[V,S.length,S.join("-")]);const G=[];if(b!==M){let B=[...b];for(let W=0;W<V.length;W++){const me=V[W],ue=Lc(me);S.includes(ue)||(B.splice(W,0,me),G.push(me))}return u==="wait"&&G.length&&(B=G),q(Qx(B)),k(b),null}const{forceRender:$}=w.useContext(zm);return c.jsx(c.Fragment,{children:V.map(B=>{const W=Lc(B),me=d&&!y?!1:b===V||S.includes(W),ue=()=>{if(C.current.has(W))return;if(C.current.add(W),E.has(W))E.set(W,!0);else return;let pe=!0;E.forEach(ze=>{ze||(pe=!1)}),pe&&($?.(),q(j.current),d&&v?.(),r&&r())};return c.jsx(E4,{isPresent:me,initial:!T.current||a?void 0:!1,custom:e,presenceAffectsLayout:o,mode:u,root:g,onExitComplete:me?void 0:ue,anchorX:f,anchorY:p,children:B},W)})})},F1=w.createContext({strict:!1}),eb={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 tb=!1;function A4(){if(tb)return;const t={};for(const e in eb)t[e]={isEnabled:a=>eb[e].some(r=>!!a[r])};w1(t),tb=!0}function Y1(){return A4(),mO()}function C4(t){const e=Y1();for(const a in t)e[a]={...e[a],...t[a]};w1(e)}const k4=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 yu(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||k4.has(t)}let X1=t=>!yu(t);function R4(t){typeof t=="function"&&(X1=e=>e.startsWith("on")?!yu(e):t(e))}try{R4(require("@emotion/is-prop-valid").default)}catch{}function O4(t,e,a){const r={};for(const o in t)o==="values"&&typeof t.values=="object"||(X1(o)||a===!0&&yu(o)||!e&&!yu(o)||t.draggable&&o.startsWith("onDrag"))&&(r[o]=t[o]);return r}const Nu=w.createContext({});function D4(t,e){if(Eu(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Xo(a)?a:void 0,animate:Xo(r)?r:void 0}}return t.inherit!==!1?e:{}}function M4(t){const{initial:e,animate:a}=D4(t,w.useContext(Nu));return w.useMemo(()=>({initial:e,animate:a}),[nb(e),nb(a)])}function nb(t){return Array.isArray(t)?t.join(" "):t}const dp=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function J1(t,e,a){for(const r in e)!Bt(e[r])&&!A1(r,a)&&(t[r]=e[r])}function z4({transformTemplate:t},e){return w.useMemo(()=>{const a=dp();return lp(a,e,t),Object.assign({},a.vars,a.style)},[e])}function U4(t,e){const a=t.style||{},r={};return J1(r,a,t),Object.assign(r,z4(t,e)),r}function L4(t,e){const a={},r=U4(t,e);return t.drag&&t.dragListener!==!1&&(a.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(a.tabIndex=0),a.style=r,a}const W1=()=>({...dp(),attrs:{}});function P4(t,e,a,r){const o=w.useMemo(()=>{const u=W1();return C1(u,e,R1(r),t.transformTemplate,t.style),{...u.attrs,style:{...u.style}}},[e]);if(t.style){const u={};J1(u,t.style,t),o.style={...u,...o.style}}return o}const V4=["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 hp(t){return typeof t!="string"||t.includes("-")?!1:!!(V4.indexOf(t)>-1||/[A-Z]/u.test(t))}function B4(t,e,a,{latestValues:r},o,u=!1,d){const p=(d??hp(t)?P4:L4)(e,r,o,t),g=O4(e,typeof t=="string",u),y=t!==w.Fragment?{...g,...p,ref:a}:{},{children:v}=e,b=w.useMemo(()=>Bt(v)?v.get():v,[v]);return w.createElement(t,{...y,children:b})}function I4({scrapeMotionValuesFromProps:t,createRenderState:e},a,r,o){return{latestValues:$4(a,r,o,t),renderState:e()}}function $4(t,e,a,r){const o={},u=r(t,{});for(const b in u)o[b]=Yc(u[b]);let{initial:d,animate:f}=t;const p=Eu(t),g=b1(t);e&&g&&!p&&t.inherit!==!1&&(d===void 0&&(d=e.initial),f===void 0&&(f=e.animate));let y=a?a.initial===!1:!1;y=y||d===!1;const v=y?f:d;if(v&&typeof v!="boolean"&&!Tu(v)){const b=Array.isArray(v)?v:[v];for(let S=0;S<b.length;S++){const T=tp(t,b[S]);if(T){const{transitionEnd:j,transition:E,...C}=T;for(const M in C){let k=C[M];if(Array.isArray(k)){const V=y?k.length-1:0;k=k[V]}k!==null&&(o[M]=k)}for(const M in j)o[M]=j[M]}}}return o}const Z1=t=>(e,a)=>{const r=w.useContext(Nu),o=w.useContext(ju),u=()=>I4(t,e,r,o);return a?u():Um(u)},q4=Z1({scrapeMotionValuesFromProps:cp,createRenderState:dp}),H4=Z1({scrapeMotionValuesFromProps:O1,createRenderState:W1}),G4=Symbol.for("motionComponentSymbol");function K4(t,e,a){const r=w.useRef(a);w.useInsertionEffect(()=>{r.current=a});const o=w.useRef(null);return w.useCallback(u=>{u&&t.onMount?.(u),e&&(u?e.mount(u):e.unmount());const d=r.current;if(typeof d=="function")if(u){const f=d(u);typeof f=="function"&&(o.current=f)}else o.current?(o.current(),o.current=null):d(u);else d&&(d.current=u)},[e])}const Q1=w.createContext({});function ko(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function F4(t,e,a,r,o,u){const{visualElement:d}=w.useContext(Nu),f=w.useContext(F1),p=w.useContext(ju),g=w.useContext(up).reducedMotion,y=w.useRef(null),v=w.useRef(!1);r=r||f.renderer,!y.current&&r&&(y.current=r(t,{visualState:e,parent:d,props:a,presenceContext:p,blockInitialAnimation:p?p.initial===!1:!1,reducedMotionConfig:g,isSVG:u}),v.current&&y.current&&(y.current.manuallyAnimateOnMount=!0));const b=y.current,S=w.useContext(Q1);b&&!b.projection&&o&&(b.type==="html"||b.type==="svg")&&Y4(y.current,a,o,S);const T=w.useRef(!1);w.useInsertionEffect(()=>{b&&T.current&&b.update(a,p)});const j=a[i1],E=w.useRef(!!j&&!window.MotionHandoffIsComplete?.(j)&&window.MotionHasOptimisedAnimation?.(j));return _w(()=>{v.current=!0,b&&(T.current=!0,window.MotionIsMounted=!0,b.updateFeatures(),b.scheduleRenderMicrotask(),E.current&&b.animationState&&b.animationState.animateChanges())}),w.useEffect(()=>{b&&(!E.current&&b.animationState&&b.animationState.animateChanges(),E.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(j)}),E.current=!1),b.enteringChildren=void 0)}),b}function Y4(t,e,a,r){const{layoutId:o,layout:u,drag:d,dragConstraints:f,layoutScroll:p,layoutRoot:g,layoutCrossfade:y}=e;t.projection=new a(t.latestValues,e["data-framer-portal-id"]?void 0:eS(t.parent)),t.projection.setOptions({layoutId:o,layout:u,alwaysMeasureLayout:!!d||f&&ko(f),visualElement:t,animationType:typeof u=="string"?u:"both",initialPromotionConfig:r,crossfade:y,layoutScroll:p,layoutRoot:g})}function eS(t){if(t)return t.options.allowProjection!==!1?t.projection:eS(t.parent)}function bf(t,{forwardMotionProps:e=!1,type:a}={},r,o){r&&C4(r);const u=a?a==="svg":hp(t),d=u?H4:q4;function f(g,y){let v;const b={...w.useContext(up),...g,layoutId:X4(g)},{isStatic:S}=b,T=M4(g),j=d(g,S);if(!S&&Sw){J4();const E=W4(b);v=E.MeasureLayout,T.visualElement=F4(t,j,b,o,E.ProjectionNode,u)}return c.jsxs(Nu.Provider,{value:T,children:[v&&T.visualElement?c.jsx(v,{visualElement:T.visualElement,...b}):null,B4(t,g,K4(j,T.visualElement,y),j,S,e,u)]})}f.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const p=w.forwardRef(f);return p[G4]=t,p}function X4({layoutId:t}){const e=w.useContext(zm).id;return e&&t!==void 0?e+"-"+t:t}function J4(t,e){w.useContext(F1).strict}function W4(t){const e=Y1(),{drag:a,layout:r}=e;if(!a&&!r)return{};const o={...a,...r};return{MeasureLayout:a?.isEnabled(t)||r?.isEnabled(t)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function Z4(t,e){if(typeof Proxy>"u")return bf;const a=new Map,r=(u,d)=>bf(u,d,t,e),o=(u,d)=>r(u,d);return new Proxy(o,{get:(u,d)=>d==="create"?r:(a.has(d)||a.set(d,bf(d,void 0,t,e)),a.get(d))})}const Q4=(t,e)=>e.isSVG??hp(t)?new RO(e):new TO(e,{allowProjection:t!==w.Fragment});class e5 extends ga{constructor(e){super(e),e.animationState||(e.animationState=UO(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Tu(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:a}=this.node.prevProps||{};e!==a&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let t5=0;class n5 extends ga{constructor(){super(...arguments),this.id=t5++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:a}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===r)return;const o=this.node.animationState.setActive("exit",!e);a&&!e&&o.then(()=>{a(this.id)})}mount(){const{register:e,onExitComplete:a}=this.node.presenceContext||{};a&&a(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const s5={animation:{Feature:e5},exit:{Feature:n5}};function rl(t){return{point:{x:t.pageX,y:t.pageY}}}const a5=t=>e=>rp(e)&&t(e,rl(e));function Uo(t,e,a,r){return Jo(t,e,a5(a),r)}const tS=({current:t})=>t?t.ownerDocument.defaultView:null,sb=(t,e)=>Math.abs(t-e);function r5(t,e){const a=sb(t.x,e.x),r=sb(t.y,e.y);return Math.sqrt(a**2+r**2)}const ab=new Set(["auto","scroll"]);class nS{constructor(e,a,{transformPagePoint:r,contextWindow:o=window,dragSnapToOrigin:u=!1,distanceThreshold:d=3,element:f}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=Sf(this.lastMoveEventInfo,this.history),T=this.startEvent!==null,j=r5(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!T&&!j)return;const{point:E}=S,{timestamp:C}=Dt;this.history.push({...E,timestamp:C});const{onStart:M,onMove:k}=this.handlers;T||(M&&M(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),k&&k(this.lastMoveEvent,S)},this.handlePointerMove=(S,T)=>{this.lastMoveEvent=S,this.lastMoveEventInfo=wf(T,this.transformPagePoint),Ze.update(this.updatePoint,!0)},this.handlePointerUp=(S,T)=>{this.end();const{onEnd:j,onSessionEnd:E,resumeAnimation:C}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&C&&C(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const M=Sf(S.type==="pointercancel"?this.lastMoveEventInfo:wf(T,this.transformPagePoint),this.history);this.startEvent&&j&&j(S,M),E&&E(S,M)},!rp(e))return;this.dragSnapToOrigin=u,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=d,this.contextWindow=o||window;const p=rl(e),g=wf(p,this.transformPagePoint),{point:y}=g,{timestamp:v}=Dt;this.history=[{...y,timestamp:v}];const{onSessionStart:b}=a;b&&b(e,Sf(g,this.history)),this.removeListeners=nl(Uo(this.contextWindow,"pointermove",this.handlePointerMove),Uo(this.contextWindow,"pointerup",this.handlePointerUp),Uo(this.contextWindow,"pointercancel",this.handlePointerUp)),f&&this.startScrollTracking(f)}startScrollTracking(e){let a=e.parentElement;for(;a;){const r=getComputedStyle(a);(ab.has(r.overflowX)||ab.has(r.overflowY))&&this.scrollPositions.set(a,{x:a.scrollLeft,y:a.scrollTop}),a=a.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(e){const a=this.scrollPositions.get(e);if(!a)return;const r=e===window,o=r?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},u={x:o.x-a.x,y:o.y-a.y};u.x===0&&u.y===0||(r?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=u.x,this.lastMoveEventInfo.point.y+=u.y):this.history.length>0&&(this.history[0].x-=u.x,this.history[0].y-=u.y),this.scrollPositions.set(e,o),Ze.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),ma(this.updatePoint)}}function wf(t,e){return e?{point:e(t.point)}:t}function rb(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Sf({point:t},e){return{point:t,delta:rb(t,sS(e)),offset:rb(t,i5(e)),velocity:o5(e,.1)}}function i5(t){return t[0]}function sS(t){return t[t.length-1]}function o5(t,e){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const o=sS(t);for(;a>=0&&(r=t[a],!(o.timestamp-r.timestamp>Ss(e)));)a--;if(!r)return{x:0,y:0};const u=jn(o.timestamp-r.timestamp);if(u===0)return{x:0,y:0};const d={x:(o.x-r.x)/u,y:(o.y-r.y)/u};return d.x===1/0&&(d.x=0),d.y===1/0&&(d.y=0),d}function l5(t,{min:e,max:a},r){return e!==void 0&&t<e?t=r?nt(e,t,r.min):Math.max(t,e):a!==void 0&&t>a&&(t=r?nt(a,t,r.max):Math.min(t,a)),t}function ib(t,e,a){return{min:e!==void 0?t.min+e:void 0,max:a!==void 0?t.max+a-(t.max-t.min):void 0}}function c5(t,{top:e,left:a,bottom:r,right:o}){return{x:ib(t.x,a,o),y:ib(t.y,e,r)}}function ob(t,e){let a=e.min-t.min,r=e.max-t.max;return e.max-e.min<t.max-t.min&&([a,r]=[r,a]),{min:a,max:r}}function u5(t,e){return{x:ob(t.x,e.x),y:ob(t.y,e.y)}}function d5(t,e){let a=.5;const r=qt(t),o=qt(e);return o>r?a=Ko(e.min,e.max-r,t.min):r>o&&(a=Ko(t.min,t.max-o,e.min)),Fn(0,1,a)}function h5(t,e){const a={};return e.min!==void 0&&(a.min=e.min-t.min),e.max!==void 0&&(a.max=e.max-t.min),a}const ym=.35;function f5(t=ym){return t===!1?t=0:t===!0&&(t=ym),{x:lb(t,"left","right"),y:lb(t,"top","bottom")}}function lb(t,e,a){return{min:cb(t,e),max:cb(t,a)}}function cb(t,e){return typeof t=="number"?t:t[e]||0}const m5=new WeakMap;class p5{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=bt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const u=v=>{a?(this.stopAnimation(),this.snapToCursor(rl(v).point)):this.pauseAnimation()},d=(v,b)=>{this.stopAnimation();const{drag:S,dragPropagation:T,onDragStart:j}=this.getProps();if(S&&!T&&(this.openDragLock&&this.openDragLock(),this.openDragLock=nO(S),!this.openDragLock))return;this.latestPointerEvent=v,this.latestPanInfo=b,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),_n(C=>{let M=this.getAxisMotionValue(C).get()||0;if(Kn.test(M)){const{projection:k}=this.visualElement;if(k&&k.layout){const V=k.layout.layoutBox[C];V&&(M=qt(V)*(parseFloat(M)/100))}}this.originPoint[C]=M}),j&&Ze.postRender(()=>j(v,b)),cm(this.visualElement,"transform");const{animationState:E}=this.visualElement;E&&E.setActive("whileDrag",!0)},f=(v,b)=>{this.latestPointerEvent=v,this.latestPanInfo=b;const{dragPropagation:S,dragDirectionLock:T,onDirectionLock:j,onDrag:E}=this.getProps();if(!S&&!this.openDragLock)return;const{offset:C}=b;if(T&&this.currentDirection===null){this.currentDirection=g5(C),this.currentDirection!==null&&j&&j(this.currentDirection);return}this.updateAxis("x",b.point,C),this.updateAxis("y",b.point,C),this.visualElement.render(),E&&E(v,b)},p=(v,b)=>{this.latestPointerEvent=v,this.latestPanInfo=b,this.stop(v,b),this.latestPointerEvent=null,this.latestPanInfo=null},g=()=>_n(v=>this.getAnimationState(v)==="paused"&&this.getAxisMotionValue(v).animation?.play()),{dragSnapToOrigin:y}=this.getProps();this.panSession=new nS(e,{onSessionStart:u,onStart:d,onMove:f,onSessionEnd:p,resumeAnimation:g},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:y,distanceThreshold:r,contextWindow:tS(this.visualElement),element:this.visualElement.current})}stop(e,a){const r=e||this.latestPointerEvent,o=a||this.latestPanInfo,u=this.isDragging;if(this.cancel(),!u||!o||!r)return;const{velocity:d}=o;this.startAnimation(d);const{onDragEnd:f}=this.getProps();f&&Ze.postRender(()=>f(r,o))}cancel(){this.isDragging=!1;const{projection:e,animationState:a}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),a&&a.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,a,r){const{drag:o}=this.getProps();if(!r||!Pc(e,o,this.currentDirection))return;const u=this.getAxisMotionValue(e);let d=this.originPoint[e]+r[e];this.constraints&&this.constraints[e]&&(d=l5(d,this.constraints[e],this.elastic[e])),u.set(d)}resolveConstraints(){const{dragConstraints:e,dragElastic:a}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;e&&ko(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&r?this.constraints=c5(r.layoutBox,e):this.constraints=!1,this.elastic=f5(a),o!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&_n(u=>{this.constraints!==!1&&this.getAxisMotionValue(u)&&(this.constraints[u]=h5(r.layoutBox[u],this.constraints[u]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:a}=this.getProps();if(!e||!ko(e))return!1;const r=e.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const u=xO(r,o.root,this.visualElement.getTransformPagePoint());let d=u5(o.layout.layoutBox,u);if(a){const f=a(gO(d));this.hasMutatedConstraints=!!f,f&&(d=_1(f))}return d}startAnimation(e){const{drag:a,dragMomentum:r,dragElastic:o,dragTransition:u,dragSnapToOrigin:d,onDragTransitionEnd:f}=this.getProps(),p=this.constraints||{},g=_n(y=>{if(!Pc(y,a,this.currentDirection))return;let v=p&&p[y]||{};d&&(v={min:0,max:0});const b=o?200:1e6,S=o?40:1e7,T={type:"inertia",velocity:r?e[y]:0,bounceStiffness:b,bounceDamping:S,timeConstant:750,restDelta:1,restSpeed:10,...u,...v};return this.startAxisValueAnimation(y,T)});return Promise.all(g).then(f)}startAxisValueAnimation(e,a){const r=this.getAxisMotionValue(e);return cm(this.visualElement,e),r.start(ep(e,r,0,a,this.visualElement,!1))}stopAnimation(){_n(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){_n(e=>this.getAxisMotionValue(e).animation?.pause())}getAnimationState(e){return this.getAxisMotionValue(e).animation?.state}getAxisMotionValue(e){const a=`_drag${e.toUpperCase()}`,r=this.visualElement.getProps(),o=r[a];return o||this.visualElement.getValue(e,(r.initial?r.initial[e]:void 0)||0)}snapToCursor(e){_n(a=>{const{drag:r}=this.getProps();if(!Pc(a,r,this.currentDirection))return;const{projection:o}=this.visualElement,u=this.getAxisMotionValue(a);if(o&&o.layout){const{min:d,max:f}=o.layout.layoutBox[a],p=u.get()||0;u.set(e[a]-nt(d,f,.5)+p)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!ko(a)||!r||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};_n(d=>{const f=this.getAxisMotionValue(d);if(f&&this.constraints!==!1){const p=f.get();o[d]=d5({min:p,max:p},this.constraints[d])}});const{transformTemplate:u}=this.visualElement.getProps();this.visualElement.current.style.transform=u?u({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),_n(d=>{if(!Pc(d,e,null))return;const f=this.getAxisMotionValue(d),{min:p,max:g}=this.constraints[d];f.set(nt(p,g,o[d]))})}addListeners(){if(!this.visualElement.current)return;m5.set(this.visualElement,this);const e=this.visualElement.current,a=Uo(e,"pointerdown",p=>{const{drag:g,dragListener:y=!0}=this.getProps(),v=p.target,b=v!==e&&y1(v);g&&y&&!b&&this.start(p)}),r=()=>{const{dragConstraints:p}=this.getProps();ko(p)&&p.current&&(this.constraints=this.resolveRefConstraints())},{projection:o}=this.visualElement,u=o.addEventListener("measure",r);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),Ze.read(r);const d=Jo(window,"resize",()=>this.scalePositionWithinConstraints()),f=o.addEventListener("didUpdate",(({delta:p,hasLayoutChanged:g})=>{this.isDragging&&g&&(_n(y=>{const v=this.getAxisMotionValue(y);v&&(this.originPoint[y]+=p[y].translate,v.set(v.get()+p[y].translate))}),this.visualElement.render())}));return()=>{d(),a(),u(),f&&f()}}getProps(){const e=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:o=!1,dragConstraints:u=!1,dragElastic:d=ym,dragMomentum:f=!0}=e;return{...e,drag:a,dragDirectionLock:r,dragPropagation:o,dragConstraints:u,dragElastic:d,dragMomentum:f}}}function Pc(t,e,a){return(e===!0||e===t)&&(a===null||a===t)}function g5(t,e=10){let a=null;return Math.abs(t.y)>e?a="y":Math.abs(t.x)>e&&(a="x"),a}class y5 extends ga{constructor(e){super(e),this.removeGroupControls=Tn,this.removeListeners=Tn,this.controls=new p5(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Tn}update(){const{dragControls:e}=this.node.getProps(),{dragControls:a}=this.node.prevProps||{};e!==a&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const ub=t=>(e,a)=>{t&&Ze.postRender(()=>t(e,a))};class v5 extends ga{constructor(){super(...arguments),this.removePointerDownListener=Tn}onPointerDown(e){this.session=new nS(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:tS(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:a,onPan:r,onPanEnd:o}=this.node.getProps();return{onSessionStart:ub(e),onStart:ub(a),onMove:r,onEnd:(u,d)=>{delete this.session,o&&Ze.postRender(()=>o(u,d))}}}mount(){this.removePointerDownListener=Uo(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let _f=!1;class x5 extends w.Component{componentDidMount(){const{visualElement:e,layoutGroup:a,switchLayoutGroup:r,layoutId:o}=this.props,{projection:u}=e;u&&(a.group&&a.group.add(u),r&&r.register&&o&&r.register(u),_f&&u.root.didUpdate(),u.addEventListener("animationComplete",()=>{this.safeToRemove()}),u.setOptions({...u.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Xc.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:a,visualElement:r,drag:o,isPresent:u}=this.props,{projection:d}=r;return d&&(d.isPresent=u,e.layoutDependency!==a&&d.setOptions({...d.options,layoutDependency:a}),_f=!0,o||e.layoutDependency!==a||a===void 0||e.isPresent!==u?d.willUpdate():this.safeToRemove(),e.isPresent!==u&&(u?d.promote():d.relegate()||Ze.postRender(()=>{const f=d.getStack();(!f||!f.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),ap.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:o}=e;_f=!0,o&&(o.scheduleCheckAfterUnmount(),a&&a.group&&a.group.remove(o),r&&r.deregister&&r.deregister(o))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function aS(t){const[e,a]=G1(),r=w.useContext(zm);return c.jsx(x5,{...t,layoutGroup:r,switchLayoutGroup:w.useContext(Q1),isPresent:e,safeToRemove:a})}const b5={pan:{Feature:v5},drag:{Feature:y5,ProjectionNode:H1,MeasureLayout:aS}};function db(t,e,a){const{props:r}=t;t.animationState&&r.whileHover&&t.animationState.setActive("whileHover",a==="Start");const o="onHover"+a,u=r[o];u&&Ze.postRender(()=>u(e,rl(e)))}class w5 extends ga{mount(){const{current:e}=this.node;e&&(this.unmount=sO(e,(a,r)=>(db(this.node,r,"Start"),o=>db(this.node,o,"End"))))}unmount(){}}class S5 extends ga{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!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=nl(Jo(this.node.current,"focus",()=>this.onFocus()),Jo(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function hb(t,e,a){const{props:r}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&r.whileTap&&t.animationState.setActive("whileTap",a==="Start");const o="onTap"+(a==="End"?"":a),u=r[o];u&&Ze.postRender(()=>u(e,rl(e)))}class _5 extends ga{mount(){const{current:e}=this.node;e&&(this.unmount=iO(e,(a,r)=>(hb(this.node,r,"Start"),(o,{success:u})=>hb(this.node,o,u?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const vm=new WeakMap,jf=new WeakMap,j5=t=>{const e=vm.get(t.target);e&&e(t)},T5=t=>{t.forEach(j5)};function E5({root:t,...e}){const a=t||document;jf.has(a)||jf.set(a,{});const r=jf.get(a),o=JSON.stringify(e);return r[o]||(r[o]=new IntersectionObserver(T5,{root:t,...e})),r[o]}function N5(t,e,a){const r=E5(e);return vm.set(t,a),r.observe(t),()=>{vm.delete(t),r.unobserve(t)}}const A5={some:0,all:1};class C5 extends ga{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:a,margin:r,amount:o="some",once:u}=e,d={root:a?a.current:void 0,rootMargin:r,threshold:typeof o=="number"?o:A5[o]},f=p=>{const{isIntersecting:g}=p;if(this.isInView===g||(this.isInView=g,u&&!g&&this.hasEnteredView))return;g&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",g);const{onViewportEnter:y,onViewportLeave:v}=this.node.getProps(),b=g?y:v;b&&b(p)};return N5(this.node.current,d,f)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:a}=this.node;["amount","margin","root"].some(k5(e,a))&&this.startObserver()}unmount(){}}function k5({viewport:t={}},{viewport:e={}}={}){return a=>t[a]!==e[a]}const R5={inView:{Feature:C5},tap:{Feature:_5},focus:{Feature:S5},hover:{Feature:w5}},O5={layout:{ProjectionNode:H1,MeasureLayout:aS}},D5={...s5,...R5,...b5,...O5},vs=Z4(D5,Q4),ii="2.11.3",M5="20260130000001";function z5(t,e){const a=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<Math.max(a.length,r.length);o++){const u=a[o]||0,d=r[o]||0;if(u>d)return 1;if(u<d)return-1}return 0}async function U5(t){try{const{data:e,error:a}=await t.rpc("get_latest_migration_timestamp");return a?a.code==="42883"?(console.info("[Migration Check] RPC function missing - assuming fresh DB."),{version:null,latestMigrationTimestamp:"0"}):(console.warn("Could not get latest migration timestamp:",a.message),{version:null,latestMigrationTimestamp:null}):{version:ii,latestMigrationTimestamp:e||null}}catch(e){return console.error("Error checking database migration info:",e),{version:null,latestMigrationTimestamp:null}}}async function fp(t){const e=ii,a=M5,r=await U5(t);if(console.log("[Migration Check]",{appVersion:e,appMigrationTimestamp:a,dbVersion:r.version,dbMigrationTimestamp:r.latestMigrationTimestamp}),r.latestMigrationTimestamp&&r.latestMigrationTimestamp.trim()!==""){const o=a,u=r.latestMigrationTimestamp;return o>u?{needsMigration:!0,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:u,message:`New migrations available. Database is at ${u}, app has ${o}.`}:o<u?(console.warn("[Migration Check] DB is ahead of app - possible downgrade"),{needsMigration:!1,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:u,message:`Database (${u}) is ahead of app (${o}).`}):(console.log("[Migration Check] Timestamps match - database is up-to-date"),{needsMigration:!1,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:u,message:"Database schema is up-to-date."})}if(r.version){console.log("[Migration Check] Legacy DB detected (no timestamp). Falling back to SemVer.");const o=z5(e,r.version);return o>0?{needsMigration:!0,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:null,message:`Database schema (v${r.version}) is outdated. Migration to v${e} required.`}:o===0?(console.warn("[Migration Check] Legacy DB with matching version - forcing migration to add timestamp tracking"),{needsMigration:!0,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:null,message:`Database lacks timestamp tracking. Please run migration to upgrade to modern schema (v${e}).`}):{needsMigration:!1,appVersion:e,dbVersion:r.version,latestMigrationTimestamp:null,message:`Database version (v${r.version}) is ahead of app (v${e}).`}}return console.log("[Migration Check] No DB info found - assuming migration needed"),{needsMigration:!0,appVersion:e,dbVersion:null,latestMigrationTimestamp:null,message:`Database schema unknown. Migration required to v${e}.`}}const rS="email_automator_migration_reminder_dismissed_at";function L5(t=24){try{const e=localStorage.getItem(rS);if(!e)return!1;const a=new Date(e).getTime();return(Date.now()-a)/(1e3*60*60)<t}catch(e){return console.error("Error checking migration reminder:",e),!1}}function P5(){try{localStorage.setItem(rS,new Date().toISOString())}catch(t){console.error("Error dismissing migration reminder:",t)}}const xm={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 V5(t,e){switch(e.type){case"SET_STEP":return{...t,step:e.payload,error:null};case"SET_ACCESS_TOKEN":return{...t,managed:{...t.managed,accessToken:e.payload}};case"SET_ORGANIZATIONS":return{...t,managed:{...t.managed,organizations:e.payload,selectedOrg:e.payload.length>0?e.payload[0].id:""}};case"SET_SELECTED_ORG":return{...t,managed:{...t.managed,selectedOrg:e.payload}};case"SET_PROJECT_NAME":return{...t,managed:{...t.managed,projectName:e.payload}};case"SET_REGION":return{...t,managed:{...t.managed,region:e.payload}};case"SET_FETCHING_ORGS":return{...t,managed:{...t.managed,isFetchingOrgs:e.payload}};case"SET_MANUAL_URL":return{...t,manual:{...t.manual,url:e.payload}};case"SET_MANUAL_ANON_KEY":return{...t,manual:{...t.manual,anonKey:e.payload}};case"SET_PROJECT_ID":return{...t,projectId:e.payload};case"ADD_LOG":return{...t,logs:[...t.logs,{...e.payload,timestamp:Date.now()}].slice(-500)};case"CLEAR_LOGS":return{...t,logs:[]};case"SET_ERROR":return{...t,error:e.payload};case"SET_MIGRATING":return{...t,isMigrating:e.payload};case"SET_MIGRATION_STATUS":return{...t,migrationStatus:e.payload};case"RESET_MANAGED_FLOW":return{...t,managed:{...xm.managed},error:null};case"RESET_MANUAL_FLOW":return{...t,manual:{...xm.manual},error:null};default:return t}}function Tf(t){const e=t.trim();return e?e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}.supabase.co`:""}function iS(t){const e=t.trim();return e?e.startsWith("sbp_")?e.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 fb(t){const e=t.trim();if(!e)return null;if(!e.includes(".")&&!e.includes("/"))return e;try{return new URL(e.startsWith("http")?e:`https://${e}`).hostname.split(".")[0]||null}catch{return null}}class B5{buffer="";processChunk(e){const a=[];this.buffer+=e;const r=this.buffer.split(`
|
|
60
60
|
`);this.buffer=r.pop()||"";for(const o of r)if(o.startsWith("data: "))try{const u=o.slice(6),d=JSON.parse(u);a.push(d)}catch(u){console.warn("[SSEParser] Failed to parse event:",o,u)}return a}flush(){if(!this.buffer.trim())return[];const e=[];if(this.buffer.startsWith("data: "))try{const a=this.buffer.slice(6),r=JSON.parse(a);e.push(r)}catch(a){console.warn("[SSEParser] Failed to parse final buffer:",this.buffer,a)}return this.buffer="",e}reset(){this.buffer=""}}async function oS(t,e,a={}){const{timeout:r=3e5,onError:o}=a;if(!t.body)throw new Error("Response body is empty");const u=t.body.getReader(),d=new TextDecoder,f=new B5,p=setTimeout(()=>{u.cancel("Timeout")},r);try{for(;;){const{value:g,done:y}=await u.read();if(y){f.flush().forEach(e);break}const v=d.decode(g,{stream:!0});f.processChunk(v).forEach(e)}}catch(g){const y=g instanceof Error?g:new Error(String(g));if(o)o(y);else throw y}finally{clearTimeout(p),f.reset()}}class da extends Error{constructor(e,a,r){super(e),this.code=a,this.status=r,this.name="SetupApiError"}}async function I5(t){const e=await fetch("/api/setup/organizations",{headers:{Authorization:`Bearer ${t}`}}),a=await e.json();if(!e.ok)throw new da(a.error||"Failed to fetch organizations","FETCH_ORGS_FAILED",e.status);return a}async function $5(t,e){const a=await fetch("/api/setup/auto-provision",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({orgId:t.orgId,projectName:t.projectName,region:t.region})});if(!a.ok){const r=await a.json().catch(()=>({}));throw new da(r.error||"Failed to provision project","PROVISION_FAILED",a.status)}await oS(a,e,{timeout:3e5,onError:r=>{throw new da(`Provisioning stream error: ${r.message}`,"STREAM_ERROR")}})}async function q5(t,e){const a=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:t.projectRef,dbPassword:t.dbPassword,accessToken:t.accessToken})});if(!a.ok){const r=await a.json().catch(()=>({}));throw new da(r.error||"Failed to start migration","MIGRATION_FAILED",a.status)}await oS(a,e,{timeout:6e5,onError:r=>{throw new da(`Migration stream error: ${r.message}`,"STREAM_ERROR")}})}function H5({onNext:t}){return c.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-8",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsxs("h2",{className:"text-4xl font-black italic tracking-tighter uppercase leading-none",children:["Initialize ",c.jsx("span",{className:"text-primary italic",children:"Automator"})]}),c.jsx("p",{className:"text-sm text-muted-foreground font-medium max-w-sm",children:"Your specialized environment for high-frequency inbox intelligence is ready for assembly."})]}),c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.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:[c.jsx(Am,{className:"w-5 h-5 text-primary","aria-hidden":"true"}),c.jsx("p",{className:"text-[10px] font-bold uppercase tracking-widest",children:"Encrypted"}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Self-hosted data security."})]}),c.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:[c.jsx(Vo,{className:"w-5 h-5 text-primary","aria-hidden":"true"}),c.jsx("p",{className:"text-[10px] font-bold uppercase tracking-widest",children:"Turbo"}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sub-second AI reasoning."})]})]}),c.jsxs(Q,{onClick:t,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:["Get Started",c.jsx(Tm,{className:"w-5 h-5 ml-4 rotate-180 group-hover:translate-x-1 transition-transform","aria-hidden":"true"})]})]})}function G5({onManaged:t,onManual:e,onBack:a}){return c.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Connection Mode"}),c.jsx("p",{className:"text-xs text-muted-foreground font-bold tracking-widest uppercase",children:"Select deployment vector"})]}),c.jsxs("div",{className:"grid gap-4",children:[c.jsxs("button",{onClick:t,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:[c.jsxs("div",{className:"flex items-center gap-4",children:[c.jsx("div",{className:"p-3 bg-primary rounded-xl shadow-lg ring-4 ring-primary/10",children:c.jsx(TE,{className:"w-6 h-6 text-primary-foreground","aria-hidden":"true"})}),c.jsxs("div",{children:[c.jsx("p",{className:"font-black uppercase italic text-sm tracking-tight",children:"Quick Ignition"}),c.jsx("p",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-widest",children:"Auto-Provision via Token"})]})]}),c.jsx(Zc,{className:"w-5 h-5 text-primary opacity-50 group-hover:opacity-100 transition-all group-hover:translate-x-1"})]}),c.jsxs("button",{onClick:e,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:[c.jsxs("div",{className:"flex items-center gap-4",children:[c.jsx("div",{className:"p-3 bg-muted rounded-xl",children:c.jsx(xu,{className:"w-6 h-6 text-muted-foreground","aria-hidden":"true"})}),c.jsxs("div",{children:[c.jsx("p",{className:"font-black uppercase italic text-sm tracking-tight text-foreground/80",children:"Manual Sync"}),c.jsx("p",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-widest",children:"Existing Credentials"})]})]}),c.jsx(Zc,{className:"w-5 h-5 text-muted-foreground opacity-50 group-hover:opacity-100 transition-all group-hover:translate-x-1"})]})]}),c.jsxs("button",{onClick:a,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:[c.jsx(Tm,{size:12,"aria-hidden":"true"})," Abort Access"]})]})}const Ae=w.forwardRef(({className:t,type:e,...a},r)=>c.jsx("input",{type:e,className:Te("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",t),ref:r,...a}));Ae.displayName="Input";var lS=Ab();const K5=Sm(lS);var F5=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Y5=F5.reduce((t,e)=>{const a=Ub(`Primitive.${e}`),r=w.forwardRef((o,u)=>{const{asChild:d,...f}=o,p=d?a:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c.jsx(p,{...f,ref:u})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{}),X5="Label",cS=w.forwardRef((t,e)=>c.jsx(Y5.label,{...t,ref:e,onMouseDown:a=>{a.target.closest("button, input, select, textarea")||(t.onMouseDown?.(a),!a.defaultPrevented&&a.detail>1&&a.preventDefault())}}));cS.displayName=X5;var J5=cS;function Ht({className:t,...e}){return c.jsx(J5,{"data-slot":"label",className:Te("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",t),...e})}const W5=Vb("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 Wo({className:t,variant:e,...a}){return c.jsx("div",{"data-slot":"alert",role:"alert",className:Te(W5({variant:e}),t),...a})}function Zo({className:t,...e}){return c.jsx("div",{"data-slot":"alert-description",className:Te("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...e})}function Z5({accessToken:t,error:e,isFetching:a,onTokenChange:r,onFetchOrgs:o,onBack:u}){const f=iS(t).valid;return c.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Forge Token"}),c.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Supabase API coordinates"})]}),e&&c.jsxs(Wo,{variant:"destructive",className:"rounded-xl bg-destructive/5 text-destructive border-destructive/20 text-[11px] font-bold",children:[c.jsx(js,{className:"h-4 w-4"}),c.jsx(Zo,{children:e})]}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"access-token",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Personal Access Token"}),c.jsxs("div",{className:"relative",children:[c.jsx(Nm,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:14,"aria-hidden":"true"}),c.jsx(Ae,{id:"access-token",type:"password",placeholder:"sbp_xxxxxxxxxxxxxxxx",value:t,onChange:p=>r(p.target.value),className:"pl-10 h-12 bg-muted/20 border-border/50 rounded-xl","aria-describedby":"token-help","aria-invalid":e?"true":"false"})]}),c.jsxs("p",{id:"token-help",className:"text-[9px] text-muted-foreground/60 px-1 italic",children:["Generate at"," ",c.jsx("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"supabase.com/dashboard/tokens"})]})]}),c.jsxs("div",{className:"flex gap-3 pt-4",children:[c.jsx(Q,{variant:"outline",onClick:u,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",disabled:a,children:"Back"}),c.jsx(Q,{onClick:o,disabled:!f||a,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest group shadow-lg hover:shadow-primary/20",children:a?c.jsx(Pt,{className:"w-4 h-4 animate-spin"}):c.jsxs(c.Fragment,{children:["Scan Organizations"," ",c.jsx(Zc,{size:14,className:"ml-2 group-hover:translate-x-1 transition-transform"})]})})]})]})]})}function Q5({organizations:t,selectedOrg:e,projectName:a,region:r,onOrgSelect:o,onProjectNameChange:u,onRegionChange:d,onProvision:f,onBack:p}){return c.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Project Config"}),c.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Engine parameters"})]}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(Ht,{htmlFor:"project-name",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Project Name"}),c.jsx(Ae,{id:"project-name",value:a,onChange:g=>u(g.target.value),className:"bg-muted/20 border-border/50 rounded-xl text-[11px]"})]}),c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(Ht,{htmlFor:"region",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Hosting Sector"}),c.jsxs("select",{id:"region",value:r,onChange:g=>d(g.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:[c.jsx("option",{value:"us-east-1",children:"US East (N. Virginia)"}),c.jsx("option",{value:"us-west-1",children:"US West (N. California)"}),c.jsx("option",{value:"eu-central-1",children:"Europe (Frankfurt)"}),c.jsx("option",{value:"ap-southeast-1",children:"Asia Pacific (Singapore)"})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Vessel (Organization)"}),c.jsx("div",{className:"max-h-[160px] overflow-y-auto space-y-2 pr-1 custom-scrollbar",role:"radiogroup","aria-label":"Select organization",children:t.map(g=>c.jsxs("button",{onClick:()=>o(g.id),role:"radio","aria-checked":e===g.id,className:Te("w-full flex items-center justify-between p-3 rounded-xl border text-[11px] font-bold transition-all",e===g.id?"border-primary bg-primary/5 ring-1 ring-primary":"hover:bg-muted/30 border-border/50"),children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(tE,{className:Te("w-3.5 h-3.5",e===g.id?"text-primary":"text-muted-foreground/50"),"aria-hidden":"true"}),c.jsx("span",{children:g.name})]}),e===g.id&&c.jsx("div",{className:"w-2 h-2 rounded-full bg-primary animate-pulse","aria-hidden":"true"})]},g.id))})]}),c.jsxs("div",{className:"flex gap-3 pt-2",children:[c.jsx(Q,{variant:"outline",onClick:p,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Back"}),c.jsx(Q,{onClick:f,disabled:!e,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest shadow-md",children:"Initialize System"})]})]})]})}function uS({logs:t,className:e}){const a=w.useRef(null);return w.useEffect(()=>{a.current?.scrollIntoView({behavior:"smooth"})},[t]),c.jsxs("div",{className:Te("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",e),role:"log","aria-live":"polite","aria-label":"Setup progress logs",children:[c.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:[c.jsx(su,{size:10,"aria-hidden":"true"}),c.jsx("span",{children:"Live Feed"})]}),t.length===0?c.jsx("div",{className:"text-slate-600 italic animate-pulse",role:"status",children:"Awaiting kernel signals..."}):c.jsxs(c.Fragment,{children:[t.map((r,o)=>c.jsxs("div",{className:Te("mb-1 break-all transition-all duration-300",r.type==="error"&&"text-red-400 font-bold",r.type==="success"&&"text-green-400 font-bold",r.type==="info"&&"text-blue-300",r.type==="stdout"&&"text-slate-400",r.type==="stderr"&&"text-yellow-400"),children:[c.jsxs("span",{className:"text-slate-600 mr-2 tabular-nums",children:["[",new Date(r.timestamp).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}),"]"]}),r.message]},`${r.timestamp}-${o}`)),c.jsx("div",{ref:a})]})]})}function eD({logs:t,error:e,onRetry:a}){return c.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(Pt,{className:"w-5 h-5 animate-spin text-primary","aria-hidden":"true"}),c.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Provisioning"})]}),c.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Assembling infrastructure..."})]}),c.jsx(uS,{logs:t}),e&&c.jsx(Q,{variant:"destructive",onClick:a,className:"w-full h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Re-Initialize Engine"})]})}function tD({url:t,anonKey:e,error:a,onUrlChange:r,onAnonKeyChange:o,onSave:u,onBack:d}){const f=t.trim().length>0&&e.trim().length>0;return c.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Manual Sync"}),c.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Inject existing coordinates"})]}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(Ht,{htmlFor:"platform-url",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Platform URL"}),c.jsx(Ae,{id:"platform-url",placeholder:"https://xyz.supabase.co",value:t,onChange:p=>r(p.target.value),className:"bg-muted/20 border-border/50 rounded-xl h-12","aria-describedby":"url-help","aria-invalid":a?"true":"false"}),c.jsx("p",{id:"url-help",className:"text-[9px] text-muted-foreground/60 px-1 italic",children:"Enter full URL or just the project ID"})]}),c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(Ht,{htmlFor:"anon-key",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Anon Matrix Key"}),c.jsx(Ae,{id:"anon-key",type:"password",placeholder:"eyJ...",value:e,onChange:p=>o(p.target.value),className:"bg-muted/20 border-border/50 rounded-xl h-12","aria-describedby":"key-help","aria-invalid":a?"true":"false"}),c.jsx("p",{id:"key-help",className:"text-[9px] text-muted-foreground/60 px-1 italic",children:"Found in your Supabase project settings"})]})]}),a&&c.jsxs(vs.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:[c.jsx(js,{size:14,"aria-hidden":"true"}),c.jsx("span",{children:a})]}),c.jsxs("div",{className:"grid grid-cols-2 gap-3 pt-4",children:[c.jsx(Q,{variant:"outline",onClick:d,className:"h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Back"}),c.jsx(Q,{onClick:u,disabled:!f,className:"h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest bg-primary shadow-lg hover:shadow-primary/20",children:"Engage"})]})]})}function nD({logs:t,error:e,isMigrating:a,migrationStatus:r,accessToken:o,onTokenChange:u,onRunMigration:d,onBypass:f}){const p=!o,g=r?.dbVersion!==null&&!r?.isUnknown,y=r?.dbVersion===null||r?.isUnknown;return c.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[a?c.jsx(Pt,{className:"w-5 h-5 animate-spin text-primary","aria-hidden":"true"}):c.jsx(ST,{className:"w-5 h-5 text-primary","aria-hidden":"true"}),c.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Installation"})]}),c.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Applying schema DNA..."})]}),c.jsx(uS,{logs:t}),!a&&c.jsxs(vs.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:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed font-medium",children:y?"Empty project detected. Initialization is mandatory to install core AI systems.":`Version mismatch detected (v${r?.dbVersion||"?.?"} → v${r?.appVersion||ii}). Normalization is recommended.`}),p&&c.jsxs("div",{className:"space-y-2 pt-2 border-t border-primary/10",children:[c.jsx(Ht,{htmlFor:"migration-token",className:"text-[10px] font-bold uppercase tracking-widest text-primary/60",children:"Management Token Required"}),c.jsxs("div",{className:"relative",children:[c.jsx(Nm,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-primary/30",size:12,"aria-hidden":"true"}),c.jsx(Ae,{id:"migration-token",type:"password",placeholder:"sbp_xxxxxxxxxxxxxxxx",value:o,onChange:v=>u(v.target.value),className:"pl-9 h-10 bg-background/50 border-primary/20 rounded-xl text-[11px]","aria-describedby":"migration-token-help"})]}),c.jsxs("p",{id:"migration-token-help",className:"text-[9px] text-muted-foreground/60 italic px-1",children:["Used once to run ",c.jsx("code",{className:"text-primary/70",children:"migrate.sh"})," on your backend."]})]})]}),c.jsxs("div",{className:"flex gap-3",children:[g&&c.jsx(Q,{variant:"ghost",onClick:f,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)"}),c.jsx(Q,{onClick:d,disabled:p,className:"flex-1 h-11 bg-primary text-[10px] font-bold uppercase tracking-widest shadow-lg hover:shadow-primary/30",children:y?"Install Systems":"Normalize System"})]})]}),e&&c.jsxs("div",{className:"space-y-3",children:[c.jsxs(Wo,{variant:"destructive",className:"rounded-xl border-destructive/20 bg-destructive/5 text-destructive font-bold text-[11px]",children:[c.jsx(js,{className:"h-4 w-4"}),c.jsx(Zo,{children:e})]}),c.jsx(Q,{variant:"outline",onClick:d,className:"w-full h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Retry Installation"})]})]})}function Vc({step:t,currentStep:e,label:a}){const r=Array.isArray(t)?t.includes(e):e===t;return c.jsx("div",{className:Te("px-3 py-1.5 rounded-full text-[9px] font-black uppercase tracking-[0.2em] transition-all duration-500",r?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground opacity-40"),role:"status","aria-current":r,children:a})}function mp({className:t}){return c.jsxs("svg",{width:"512",height:"512",viewBox:"0 0 512 512",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:Te("w-9 h-9",t),children:[c.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"}),c.jsx("path",{d:"M64 160 L240 290 C250 295 262 295 272 290 L448 160",stroke:"currentColor",strokeWidth:"28",strokeLinecap:"round",strokeLinejoin:"round"}),c.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 dS({onComplete:t,open:e=!0,canClose:a=!1}){const[r,o]=w.useReducer(V5,xm),u=w.useRef(""),d=w.useRef("");w.useEffect(()=>()=>{u.current="",d.current=""},[]);const f=w.useCallback((S,T)=>{o({type:"ADD_LOG",payload:{type:S,message:T}})},[]),p=w.useCallback(async()=>{o({type:"SET_ERROR",payload:null}),o({type:"SET_FETCHING_ORGS",payload:!0});const S=r.managed.accessToken.trim(),T=iS(S);if(!T.valid){o({type:"SET_ERROR",payload:T.message||"Invalid token"}),o({type:"SET_FETCHING_ORGS",payload:!1});return}try{u.current=S;const j=await I5(S);o({type:"SET_ORGANIZATIONS",payload:j}),o({type:"SET_STEP",payload:"managed-org"})}catch(j){const E=j instanceof da?j:new Error(String(j));o({type:"SET_ERROR",payload:E.message})}finally{o({type:"SET_FETCHING_ORGS",payload:!1})}},[r.managed.accessToken]),g=w.useCallback(async()=>{o({type:"SET_ERROR",payload:null}),o({type:"SET_STEP",payload:"provisioning"}),o({type:"CLEAR_LOGS"}),f("info","Connecting to Supabase provisioning engine...");const S=u.current||r.managed.accessToken.trim();let T=null;try{if(await $5({accessToken:S,orgId:r.managed.selectedOrg,projectName:r.managed.projectName,region:r.managed.region},j=>{switch(j.type){case"info":f("info",j.data);break;case"project_id":o({type:"SET_PROJECT_ID",payload:j.data});break;case"success":T=j.data,f("success","✨ Project ready! Initializing database..."),lf({url:Tf(T.url),anonKey:T.anonKey.trim()}),d.current=T.dbPass,o({type:"SET_MIGRATION_STATUS",payload:{needsMigration:!0,dbVersion:null,appVersion:ii,isUnknown:!0}});break;case"error":o({type:"SET_ERROR",payload:j.data}),f("error",j.data);break}}),T){const j=T;await y(j.projectId,S,j.url,j.anonKey)}}catch(j){const E=j instanceof da?j:new Error(String(j));o({type:"SET_ERROR",payload:E.message}),f("error",`Provisioning failed: ${E.message}`)}},[r.managed.selectedOrg,r.managed.projectName,r.managed.region,r.managed.accessToken,f]),y=w.useCallback(async(S,T,j,E)=>{const C=S||r.projectId||fb(r.manual.url),M=T||u.current||r.managed.accessToken.trim(),k=j||r.manual.url,V=E||r.manual.anonKey;if(!C||!M){o({type:"SET_ERROR",payload:"Project ID and Access Token are required for migration."});return}o({type:"SET_STEP",payload:"migration"}),o({type:"SET_ERROR",payload:null}),o({type:"SET_MIGRATING",payload:!0}),o({type:"CLEAR_LOGS"}),f("info","📦 Preparing database schema initialization...");try{let q=!1;if(await q5({projectRef:C,dbPassword:d.current,accessToken:M},G=>{switch(G.type){case"stdout":f("stdout",G.data);break;case"stderr":f("stderr",`⚠️ ${G.data}`);break;case"info":f("info",G.data);break;case"error":f("error",G.data);break;case"done":G.data==="success"?(q=!0,f("success","✅ Database setup complete!"),k&&V&&lf({url:Tf(k),anonKey:V.trim()}),u.current="",d.current="",setTimeout(()=>{t(),window.location.reload()},2e3)):o({type:"SET_ERROR",payload:"Migration failed. Check terminal logs for details."});break}}),!q)throw new Error("Migration did not complete successfully")}catch(q){const G=q instanceof da?q:new Error(String(q));o({type:"SET_ERROR",payload:G.message}),f("error",`Migration failed: ${G.message}`)}finally{o({type:"SET_MIGRATING",payload:!1})}},[r.projectId,r.manual.url,r.manual.anonKey,r.managed.accessToken,f,t]),v=w.useCallback(async()=>{o({type:"SET_ERROR",payload:null}),o({type:"SET_STEP",payload:"validating"});const S=Tf(r.manual.url),T=r.manual.anonKey.trim(),j=await DC(S,T);if(j.valid){o({type:"SET_MANUAL_URL",payload:S});const E=fb(S);E&&o({type:"SET_PROJECT_ID",payload:E}),lf({url:S,anonKey:T});try{const C=Ff(S,T),M=await fp(C);o({type:"SET_MIGRATION_STATUS",payload:M}),M.needsMigration?o({type:"SET_STEP",payload:"migration"}):(f("success","✨ Database is already up-to-date! Redirecting..."),setTimeout(()=>{t(),window.location.reload()},2e3))}catch(C){console.warn("[SetupWizard] Migration check failed:",C),o({type:"SET_MIGRATION_STATUS",payload:{needsMigration:!0,dbVersion:null,appVersion:ii,isUnknown:!0}}),o({type:"SET_STEP",payload:"migration"})}}else o({type:"SET_ERROR",payload:j.error||"Connection failed"}),o({type:"SET_STEP",payload:"credentials"})},[r.manual.url,r.manual.anonKey,f,t]);if(!e)return null;const b={initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20}};return c.jsx("div",{className:"fixed inset-0 z-50 bg-background flex flex-col items-center justify-center p-0 md:p-8",children:c.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:[c.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:[c.jsxs("div",{className:"space-y-8 relative z-10",children:[c.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[c.jsx("div",{className:"p-2 bg-primary rounded-lg flex-shrink-0",children:c.jsx(mp,{className:"w-5 h-5 text-primary-foreground"})}),c.jsx("span",{className:"font-black italic tracking-tighter uppercase text-xs truncate",children:"Automator Forge"})]}),c.jsxs("div",{className:"space-y-6",children:[c.jsx("p",{className:"text-[9px] font-black uppercase tracking-[0.4em] text-muted-foreground/30 ml-1",children:"Assembly Phase"}),c.jsxs("div",{className:"space-y-4 px-1",children:[c.jsx(Vc,{step:"welcome",currentStep:r.step,label:"Initiation"}),c.jsx(Vc,{step:["type","managed-token","credentials"],currentStep:r.step,label:"Coordinates"}),c.jsx(Vc,{step:["managed-org","provisioning","validating"],currentStep:r.step,label:"Foundation"}),c.jsx(Vc,{step:"migration",currentStep:r.step,label:"Sync"})]})]})]}),c.jsx("div",{className:"relative z-10 space-y-4",children:c.jsxs("p",{className:"text-[9px] font-bold text-muted-foreground/30 uppercase tracking-[0.4em] px-2 text-center",children:["v",ii," // Stable Build"]})})]}),c.jsxs("div",{className:"flex-1 p-8 md:p-12 flex flex-col relative",children:[a&&c.jsx("button",{onClick:t,className:"absolute top-6 right-6 p-2 rounded-full hover:bg-secondary transition-colors z-[60]","aria-label":"Close setup wizard",children:c.jsx(yi,{className:"w-5 h-5 text-muted-foreground opacity-40 hover:opacity-100 transition-opacity"})}),c.jsx(K1,{mode:"wait",children:c.jsxs(vs.div,{initial:"initial",animate:"animate",exit:"exit",variants:b,transition:{type:"spring",damping:25,stiffness:200},className:"flex-1 flex flex-col",children:[r.step==="welcome"&&c.jsx(H5,{onNext:()=>o({type:"SET_STEP",payload:"type"})}),r.step==="type"&&c.jsx(G5,{onManaged:()=>{o({type:"RESET_MANUAL_FLOW"}),o({type:"SET_STEP",payload:"managed-token"})},onManual:()=>{o({type:"RESET_MANAGED_FLOW"}),o({type:"SET_STEP",payload:"credentials"})},onBack:()=>o({type:"SET_STEP",payload:"welcome"})}),r.step==="managed-token"&&c.jsx(Z5,{accessToken:r.managed.accessToken,error:r.error,isFetching:r.managed.isFetchingOrgs,onTokenChange:S=>o({type:"SET_ACCESS_TOKEN",payload:S}),onFetchOrgs:p,onBack:()=>o({type:"SET_STEP",payload:"type"})}),r.step==="managed-org"&&c.jsx(Q5,{organizations:r.managed.organizations,selectedOrg:r.managed.selectedOrg,projectName:r.managed.projectName,region:r.managed.region,onOrgSelect:S=>o({type:"SET_SELECTED_ORG",payload:S}),onProjectNameChange:S=>o({type:"SET_PROJECT_NAME",payload:S}),onRegionChange:S=>o({type:"SET_REGION",payload:S}),onProvision:g,onBack:()=>o({type:"SET_STEP",payload:"managed-token"})}),r.step==="provisioning"&&c.jsx(eD,{logs:r.logs,error:r.error,onRetry:()=>o({type:"SET_STEP",payload:"managed-token"})}),r.step==="credentials"&&c.jsx(tD,{url:r.manual.url,anonKey:r.manual.anonKey,error:r.error,onUrlChange:S=>o({type:"SET_MANUAL_URL",payload:S}),onAnonKeyChange:S=>o({type:"SET_MANUAL_ANON_KEY",payload:S}),onSave:v,onBack:()=>o({type:"SET_STEP",payload:"type"})}),r.step==="migration"&&c.jsx(nD,{logs:r.logs,error:r.error,isMigrating:r.isMigrating,migrationStatus:r.migrationStatus,accessToken:r.managed.accessToken,onTokenChange:S=>o({type:"SET_ACCESS_TOKEN",payload:S}),onRunMigration:()=>y(),onBypass:()=>{t(),window.location.reload()}})]},r.step)})]})]})})}function ha(t,e,{checkForDefaultPrevented:a=!0}={}){return function(o){if(t?.(o),a===!1||!o.defaultPrevented)return e?.(o)}}function sD(t,e){const a=w.createContext(e),r=u=>{const{children:d,...f}=u,p=w.useMemo(()=>f,Object.values(f));return c.jsx(a.Provider,{value:p,children:d})};r.displayName=t+"Provider";function o(u){const d=w.useContext(a);if(d)return d;if(e!==void 0)return e;throw new Error(`\`${u}\` must be used within \`${t}\``)}return[r,o]}function aD(t,e=[]){let a=[];function r(u,d){const f=w.createContext(d),p=a.length;a=[...a,d];const g=v=>{const{scope:b,children:S,...T}=v,j=b?.[t]?.[p]||f,E=w.useMemo(()=>T,Object.values(T));return c.jsx(j.Provider,{value:E,children:S})};g.displayName=u+"Provider";function y(v,b){const S=b?.[t]?.[p]||f,T=w.useContext(S);if(T)return T;if(d!==void 0)return d;throw new Error(`\`${v}\` must be used within \`${u}\``)}return[g,y]}const o=()=>{const u=a.map(d=>w.createContext(d));return function(f){const p=f?.[t]||u;return w.useMemo(()=>({[`__scope${t}`]:{...f,[t]:p}}),[f,p])}};return o.scopeName=t,[r,rD(o,...e)]}function rD(...t){const e=t[0];if(t.length===1)return e;const a=()=>{const r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(u){const d=r.reduce((f,{useScope:p,scopeName:g})=>{const v=p(u)[`__scope${g}`];return{...f,...v}},{});return w.useMemo(()=>({[`__scope${e.scopeName}`]:d}),[d])}};return a.scopeName=e.scopeName,a}var Qo=globalThis?.document?w.useLayoutEffect:()=>{},iD=jm[" useId ".trim().toString()]||(()=>{}),oD=0;function Ef(t){const[e,a]=w.useState(iD());return Qo(()=>{a(r=>r??String(oD++))},[t]),t||(e?`radix-${e}`:"")}var lD=jm[" useInsertionEffect ".trim().toString()]||Qo;function cD({prop:t,defaultProp:e,onChange:a=()=>{},caller:r}){const[o,u,d]=uD({defaultProp:e,onChange:a}),f=t!==void 0,p=f?t:o;{const y=w.useRef(t!==void 0);w.useEffect(()=>{const v=y.current;v!==f&&console.warn(`${r} is changing from ${v?"controlled":"uncontrolled"} to ${f?"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.`),y.current=f},[f,r])}const g=w.useCallback(y=>{if(f){const v=dD(y)?y(t):y;v!==t&&d.current?.(v)}else u(y)},[f,t,u,d]);return[p,g]}function uD({defaultProp:t,onChange:e}){const[a,r]=w.useState(t),o=w.useRef(a),u=w.useRef(e);return lD(()=>{u.current=e},[e]),w.useEffect(()=>{o.current!==a&&(u.current?.(a),o.current=a)},[a,o]),[a,r,u]}function dD(t){return typeof t=="function"}function hD(t){const e=fD(t),a=w.forwardRef((r,o)=>{const{children:u,...d}=r,f=w.Children.toArray(u),p=f.find(pD);if(p){const g=p.props.children,y=f.map(v=>v===p?w.Children.count(g)>1?w.Children.only(null):w.isValidElement(g)?g.props.children:null:v);return c.jsx(e,{...d,ref:o,children:w.isValidElement(g)?w.cloneElement(g,void 0,y):null})}return c.jsx(e,{...d,ref:o,children:u})});return a.displayName=`${t}.Slot`,a}function fD(t){const e=w.forwardRef((a,r)=>{const{children:o,...u}=a;if(w.isValidElement(o)){const d=yD(o),f=gD(u,o.props);return o.type!==w.Fragment&&(f.ref=r?bu(r,d):d),w.cloneElement(o,f)}return w.Children.count(o)>1?w.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var mD=Symbol("radix.slottable");function pD(t){return w.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===mD}function gD(t,e){const a={...e};for(const r in e){const o=t[r],u=e[r];/^on[A-Z]/.test(r)?o&&u?a[r]=(...f)=>{const p=u(...f);return o(...f),p}:o&&(a[r]=o):r==="style"?a[r]={...o,...u}:r==="className"&&(a[r]=[o,u].filter(Boolean).join(" "))}return{...t,...a}}function yD(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,a=e&&"isReactWarning"in e&&e.isReactWarning;return a?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,a=e&&"isReactWarning"in e&&e.isReactWarning,a?t.props.ref:t.props.ref||t.ref)}var vD=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Es=vD.reduce((t,e)=>{const a=hD(`Primitive.${e}`),r=w.forwardRef((o,u)=>{const{asChild:d,...f}=o,p=d?a:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c.jsx(p,{...f,ref:u})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function xD(t,e){t&&lS.flushSync(()=>t.dispatchEvent(e))}function el(t){const e=w.useRef(t);return w.useEffect(()=>{e.current=t}),w.useMemo(()=>(...a)=>e.current?.(...a),[])}function bD(t,e=globalThis?.document){const a=el(t);w.useEffect(()=>{const r=o=>{o.key==="Escape"&&a(o)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[a,e])}var wD="DismissableLayer",bm="dismissableLayer.update",SD="dismissableLayer.pointerDownOutside",_D="dismissableLayer.focusOutside",mb,hS=w.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),fS=w.forwardRef((t,e)=>{const{disableOutsidePointerEvents:a=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:u,onInteractOutside:d,onDismiss:f,...p}=t,g=w.useContext(hS),[y,v]=w.useState(null),b=y?.ownerDocument??globalThis?.document,[,S]=w.useState({}),T=Za(e,$=>v($)),j=Array.from(g.layers),[E]=[...g.layersWithOutsidePointerEventsDisabled].slice(-1),C=j.indexOf(E),M=y?j.indexOf(y):-1,k=g.layersWithOutsidePointerEventsDisabled.size>0,V=M>=C,q=ED($=>{const B=$.target,W=[...g.branches].some(me=>me.contains(B));!V||W||(o?.($),d?.($),$.defaultPrevented||f?.())},b),G=ND($=>{const B=$.target;[...g.branches].some(me=>me.contains(B))||(u?.($),d?.($),$.defaultPrevented||f?.())},b);return bD($=>{M===g.layers.size-1&&(r?.($),!$.defaultPrevented&&f&&($.preventDefault(),f()))},b),w.useEffect(()=>{if(y)return a&&(g.layersWithOutsidePointerEventsDisabled.size===0&&(mb=b.body.style.pointerEvents,b.body.style.pointerEvents="none"),g.layersWithOutsidePointerEventsDisabled.add(y)),g.layers.add(y),pb(),()=>{a&&g.layersWithOutsidePointerEventsDisabled.size===1&&(b.body.style.pointerEvents=mb)}},[y,b,a,g]),w.useEffect(()=>()=>{y&&(g.layers.delete(y),g.layersWithOutsidePointerEventsDisabled.delete(y),pb())},[y,g]),w.useEffect(()=>{const $=()=>S({});return document.addEventListener(bm,$),()=>document.removeEventListener(bm,$)},[]),c.jsx(Es.div,{...p,ref:T,style:{pointerEvents:k?V?"auto":"none":void 0,...t.style},onFocusCapture:ha(t.onFocusCapture,G.onFocusCapture),onBlurCapture:ha(t.onBlurCapture,G.onBlurCapture),onPointerDownCapture:ha(t.onPointerDownCapture,q.onPointerDownCapture)})});fS.displayName=wD;var jD="DismissableLayerBranch",TD=w.forwardRef((t,e)=>{const a=w.useContext(hS),r=w.useRef(null),o=Za(e,r);return w.useEffect(()=>{const u=r.current;if(u)return a.branches.add(u),()=>{a.branches.delete(u)}},[a.branches]),c.jsx(Es.div,{...t,ref:o})});TD.displayName=jD;function ED(t,e=globalThis?.document){const a=el(t),r=w.useRef(!1),o=w.useRef(()=>{});return w.useEffect(()=>{const u=f=>{if(f.target&&!r.current){let p=function(){mS(SD,a,g,{discrete:!0})};const g={originalEvent:f};f.pointerType==="touch"?(e.removeEventListener("click",o.current),o.current=p,e.addEventListener("click",o.current,{once:!0})):p()}else e.removeEventListener("click",o.current);r.current=!1},d=window.setTimeout(()=>{e.addEventListener("pointerdown",u)},0);return()=>{window.clearTimeout(d),e.removeEventListener("pointerdown",u),e.removeEventListener("click",o.current)}},[e,a]),{onPointerDownCapture:()=>r.current=!0}}function ND(t,e=globalThis?.document){const a=el(t),r=w.useRef(!1);return w.useEffect(()=>{const o=u=>{u.target&&!r.current&&mS(_D,a,{originalEvent:u},{discrete:!1})};return e.addEventListener("focusin",o),()=>e.removeEventListener("focusin",o)},[e,a]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function pb(){const t=new CustomEvent(bm);document.dispatchEvent(t)}function mS(t,e,a,{discrete:r}){const o=a.originalEvent.target,u=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:a});e&&o.addEventListener(t,e,{once:!0}),r?xD(o,u):o.dispatchEvent(u)}var Nf="focusScope.autoFocusOnMount",Af="focusScope.autoFocusOnUnmount",gb={bubbles:!1,cancelable:!0},AD="FocusScope",pS=w.forwardRef((t,e)=>{const{loop:a=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:u,...d}=t,[f,p]=w.useState(null),g=el(o),y=el(u),v=w.useRef(null),b=Za(e,j=>p(j)),S=w.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;w.useEffect(()=>{if(r){let j=function(k){if(S.paused||!f)return;const V=k.target;f.contains(V)?v.current=V:ra(v.current,{select:!0})},E=function(k){if(S.paused||!f)return;const V=k.relatedTarget;V!==null&&(f.contains(V)||ra(v.current,{select:!0}))},C=function(k){if(document.activeElement===document.body)for(const q of k)q.removedNodes.length>0&&ra(f)};document.addEventListener("focusin",j),document.addEventListener("focusout",E);const M=new MutationObserver(C);return f&&M.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",j),document.removeEventListener("focusout",E),M.disconnect()}}},[r,f,S.paused]),w.useEffect(()=>{if(f){vb.add(S);const j=document.activeElement;if(!f.contains(j)){const C=new CustomEvent(Nf,gb);f.addEventListener(Nf,g),f.dispatchEvent(C),C.defaultPrevented||(CD(MD(gS(f)),{select:!0}),document.activeElement===j&&ra(f))}return()=>{f.removeEventListener(Nf,g),setTimeout(()=>{const C=new CustomEvent(Af,gb);f.addEventListener(Af,y),f.dispatchEvent(C),C.defaultPrevented||ra(j??document.body,{select:!0}),f.removeEventListener(Af,y),vb.remove(S)},0)}}},[f,g,y,S]);const T=w.useCallback(j=>{if(!a&&!r||S.paused)return;const E=j.key==="Tab"&&!j.altKey&&!j.ctrlKey&&!j.metaKey,C=document.activeElement;if(E&&C){const M=j.currentTarget,[k,V]=kD(M);k&&V?!j.shiftKey&&C===V?(j.preventDefault(),a&&ra(k,{select:!0})):j.shiftKey&&C===k&&(j.preventDefault(),a&&ra(V,{select:!0})):C===M&&j.preventDefault()}},[a,r,S.paused]);return c.jsx(Es.div,{tabIndex:-1,...d,ref:b,onKeyDown:T})});pS.displayName=AD;function CD(t,{select:e=!1}={}){const a=document.activeElement;for(const r of t)if(ra(r,{select:e}),document.activeElement!==a)return}function kD(t){const e=gS(t),a=yb(e,t),r=yb(e.reverse(),t);return[a,r]}function gS(t){const e=[],a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;a.nextNode();)e.push(a.currentNode);return e}function yb(t,e){for(const a of t)if(!RD(a,{upTo:e}))return a}function RD(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function OD(t){return t instanceof HTMLInputElement&&"select"in t}function ra(t,{select:e=!1}={}){if(t&&t.focus){const a=document.activeElement;t.focus({preventScroll:!0}),t!==a&&OD(t)&&e&&t.select()}}var vb=DD();function DD(){let t=[];return{add(e){const a=t[0];e!==a&&a?.pause(),t=xb(t,e),t.unshift(e)},remove(e){t=xb(t,e),t[0]?.resume()}}}function xb(t,e){const a=[...t],r=a.indexOf(e);return r!==-1&&a.splice(r,1),a}function MD(t){return t.filter(e=>e.tagName!=="A")}var zD="Portal",yS=w.forwardRef((t,e)=>{const{container:a,...r}=t,[o,u]=w.useState(!1);Qo(()=>u(!0),[]);const d=a||o&&globalThis?.document?.body;return d?K5.createPortal(c.jsx(Es.div,{...r,ref:e}),d):null});yS.displayName=zD;function UD(t,e){return w.useReducer((a,r)=>e[a][r]??a,t)}var Au=t=>{const{present:e,children:a}=t,r=LD(e),o=typeof a=="function"?a({present:r.isPresent}):w.Children.only(a),u=Za(r.ref,PD(o));return typeof a=="function"||r.isPresent?w.cloneElement(o,{ref:u}):null};Au.displayName="Presence";function LD(t){const[e,a]=w.useState(),r=w.useRef(null),o=w.useRef(t),u=w.useRef("none"),d=t?"mounted":"unmounted",[f,p]=UD(d,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return w.useEffect(()=>{const g=Bc(r.current);u.current=f==="mounted"?g:"none"},[f]),Qo(()=>{const g=r.current,y=o.current;if(y!==t){const b=u.current,S=Bc(g);t?p("MOUNT"):S==="none"||g?.display==="none"?p("UNMOUNT"):p(y&&b!==S?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,p]),Qo(()=>{if(e){let g;const y=e.ownerDocument.defaultView??window,v=S=>{const j=Bc(r.current).includes(CSS.escape(S.animationName));if(S.target===e&&j&&(p("ANIMATION_END"),!o.current)){const E=e.style.animationFillMode;e.style.animationFillMode="forwards",g=y.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=E)})}},b=S=>{S.target===e&&(u.current=Bc(r.current))};return e.addEventListener("animationstart",b),e.addEventListener("animationcancel",v),e.addEventListener("animationend",v),()=>{y.clearTimeout(g),e.removeEventListener("animationstart",b),e.removeEventListener("animationcancel",v),e.removeEventListener("animationend",v)}}else p("ANIMATION_END")},[e,p]),{isPresent:["mounted","unmountSuspended"].includes(f),ref:w.useCallback(g=>{r.current=g?getComputedStyle(g):null,a(g)},[])}}function Bc(t){return t?.animationName||"none"}function PD(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,a=e&&"isReactWarning"in e&&e.isReactWarning;return a?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,a=e&&"isReactWarning"in e&&e.isReactWarning,a?t.props.ref:t.props.ref||t.ref)}var Cf=0;function VD(){w.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??bb()),document.body.insertAdjacentElement("beforeend",t[1]??bb()),Cf++,()=>{Cf===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Cf--}},[])}function bb(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Jc="right-scroll-bar-position",Wc="width-before-scroll-bar",BD="with-scroll-bars-hidden",ID="--removed-body-scroll-bar-size";function kf(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function $D(t,e){var a=w.useState(function(){return{value:t,callback:e,facade:{get current(){return a.value},set current(r){var o=a.value;o!==r&&(a.value=r,a.callback(r,o))}}}})[0];return a.callback=e,a.facade}var qD=typeof window<"u"?w.useLayoutEffect:w.useEffect,wb=new WeakMap;function HD(t,e){var a=$D(null,function(r){return t.forEach(function(o){return kf(o,r)})});return qD(function(){var r=wb.get(a);if(r){var o=new Set(r),u=new Set(t),d=a.current;o.forEach(function(f){u.has(f)||kf(f,null)}),u.forEach(function(f){o.has(f)||kf(f,d)})}wb.set(a,t)},[t]),a}function GD(t){return t}function KD(t,e){e===void 0&&(e=GD);var a=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return a.length?a[a.length-1]:t},useMedium:function(u){var d=e(u,r);return a.push(d),function(){a=a.filter(function(f){return f!==d})}},assignSyncMedium:function(u){for(r=!0;a.length;){var d=a;a=[],d.forEach(u)}a={push:function(f){return u(f)},filter:function(){return a}}},assignMedium:function(u){r=!0;var d=[];if(a.length){var f=a;a=[],f.forEach(u),d=a}var p=function(){var y=d;d=[],y.forEach(u)},g=function(){return Promise.resolve().then(p)};g(),a={push:function(y){d.push(y),g()},filter:function(y){return d=d.filter(y),a}}}};return o}function FD(t){t===void 0&&(t={});var e=KD(null);return e.options=Hn({async:!0,ssr:!1},t),e}var vS=function(t){var e=t.sideCar,a=bi(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return w.createElement(r,Hn({},a))};vS.isSideCarExport=!0;function YD(t,e){return t.useMedium(e),vS}var xS=FD(),Rf=function(){},Cu=w.forwardRef(function(t,e){var a=w.useRef(null),r=w.useState({onScrollCapture:Rf,onWheelCapture:Rf,onTouchMoveCapture:Rf}),o=r[0],u=r[1],d=t.forwardProps,f=t.children,p=t.className,g=t.removeScrollBar,y=t.enabled,v=t.shards,b=t.sideCar,S=t.noRelative,T=t.noIsolation,j=t.inert,E=t.allowPinchZoom,C=t.as,M=C===void 0?"div":C,k=t.gapMode,V=bi(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),q=b,G=HD([a,e]),$=Hn(Hn({},V),o);return w.createElement(w.Fragment,null,y&&w.createElement(q,{sideCar:xS,removeScrollBar:g,shards:v,noRelative:S,noIsolation:T,inert:j,setCallbacks:u,allowPinchZoom:!!E,lockRef:a,gapMode:k}),d?w.cloneElement(w.Children.only(f),Hn(Hn({},$),{ref:G})):w.createElement(M,Hn({},$,{className:p,ref:G}),f))});Cu.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Cu.classNames={fullWidth:Wc,zeroRight:Jc};var XD=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function JD(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=XD();return e&&t.setAttribute("nonce",e),t}function WD(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function ZD(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var QD=function(){var t=0,e=null;return{add:function(a){t==0&&(e=JD())&&(WD(e,a),ZD(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},eM=function(){var t=QD();return function(e,a){w.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&a])}},bS=function(){var t=eM(),e=function(a){var r=a.styles,o=a.dynamic;return t(r,o),null};return e},tM={left:0,top:0,right:0,gap:0},Of=function(t){return parseInt(t||"",10)||0},nM=function(t){var e=window.getComputedStyle(document.body),a=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],o=e[t==="padding"?"paddingRight":"marginRight"];return[Of(a),Of(r),Of(o)]},sM=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return tM;var e=nM(t),a=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-a+e[2]-e[0])}},aM=bS(),oi="data-scroll-locked",rM=function(t,e,a,r){var o=t.left,u=t.top,d=t.right,f=t.gap;return a===void 0&&(a="margin"),`
|
|
61
61
|
.`.concat(BD,` {
|
|
62
62
|
overflow: hidden `).concat(r,`;
|
|
@@ -101,5 +101,5 @@ ${C}`}class mt extends Error{constructor({message:e,code:a,cause:r,name:o}){var
|
|
|
101
101
|
|
|
102
102
|
If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
103
103
|
|
|
104
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return w.useEffect(()=>{t&&(document.getElementById(t)||console.error(a))},[a,t]),null},VM="DialogDescriptionWarning",BM=({contentRef:t,descriptionId:e})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${BS(VM).contentName}}.`;return w.useEffect(()=>{const o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},IM=NS,$M=kS,qM=RS,HM=OS,GM=MS,KM=US,FM=PS;function li({...t}){return c.jsx(IM,{"data-slot":"dialog",...t})}function YM({...t}){return c.jsx($M,{"data-slot":"dialog-portal",...t})}function XM({className:t,...e}){return c.jsx(qM,{"data-slot":"dialog-overlay",className:Te("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function ci({className:t,children:e,...a}){return c.jsxs(YM,{"data-slot":"dialog-portal",children:[c.jsx(XM,{}),c.jsxs(HM,{"data-slot":"dialog-content",className:Te("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...a,children:[e,c.jsxs(FM,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[c.jsx(yi,{}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function ui({className:t,...e}){return c.jsx("div",{"data-slot":"dialog-header",className:Te("flex flex-col gap-2 text-center sm:text-left",t),...e})}function Zr({className:t,...e}){return c.jsx("div",{"data-slot":"dialog-footer",className:Te("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...e})}function di({className:t,...e}){return c.jsx(GM,{"data-slot":"dialog-title",className:Te("text-lg leading-none font-semibold",t),...e})}function hi({className:t,...e}){return c.jsx(KM,{"data-slot":"dialog-description",className:Te("text-muted-foreground text-sm",t),...e})}function JM({email:t,isOpen:e,onOpenChange:a,onRetry:r}){const[o,u]=w.useState([]),[d,f]=w.useState(!1);w.useEffect(()=>{e&&t&&p()},[e,t]);const p=async()=>{if(t){f(!0);try{const y=await Ue.getEmailEvents(t.id);y.data&&u(y.data.events)}catch(y){console.error("Failed to fetch trace:",y)}finally{f(!1)}}},g=y=>{switch(y){case"analysis":return c.jsx(Lo,{className:"w-4 h-4 text-purple-500"});case"action":return c.jsx(Vo,{className:"w-4 h-4 text-emerald-500"});case"error":return c.jsx(js,{className:"w-4 h-4 text-red-500"});default:return c.jsx(mi,{className:"w-4 h-4 text-blue-500"})}};return c.jsx(li,{open:e,onOpenChange:a,children:c.jsxs(ci,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[c.jsxs(ui,{className:"p-6 border-b flex flex-row items-center justify-between",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(xu,{className:"w-5 h-5 text-primary"}),c.jsx(di,{children:"AI Processing Trace"})]}),c.jsx(hi,{children:"Step-by-step log of how the AI analyzed and acted on this email."})]}),t?.processing_status==="failed"&&r&&c.jsxs(Q,{size:"sm",variant:"outline",onClick:()=>{r(t),a(!1)},className:"gap-2 text-destructive border-destructive/20 hover:bg-destructive/10",children:[c.jsx(fa,{className:"w-3.5 h-3.5"}),"Retry Job"]})]}),c.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:d?c.jsx("div",{className:"py-20 flex justify-center",children:c.jsx(ft,{})}):o.length===0?c.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:"No granular trace events found for this email."}):o.map((y,v)=>c.jsxs("div",{className:"relative pl-8",children:[v!==o.length-1&&c.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),c.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:g(y.event_type)}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-foreground/70",children:y.agent_state}),c.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(fi,{className:"w-3 h-3"}),new Date(y.created_at).toLocaleTimeString()]})]}),c.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[y.event_type==="info"&&c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-foreground/90",children:y.details?.message}),y.details?.system_prompt&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[c.jsx(la,{className:"w-3 h-3"})," System Prompt"]}),c.jsx("pre",{className:"text-[10px] bg-secondary/50 p-2 rounded border overflow-x-auto whitespace-pre-wrap max-h-60 overflow-y-auto font-mono",children:y.details.system_prompt})]}),y.details?.content_preview&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[c.jsx(la,{className:"w-3 h-3"})," Email Content (sent to LLM)"]}),c.jsx("pre",{className:"text-[10px] bg-blue-500/5 p-2 rounded border border-blue-500/10 overflow-x-auto whitespace-pre-wrap max-h-40 overflow-y-auto font-mono",children:y.details.content_preview})]})]}),y.event_type==="analysis"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs("div",{className:"text-[10px] bg-secondary px-2 py-1 rounded",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Category:"}),c.jsx("span",{className:"font-bold uppercase",children:y.details?.category||"Analyzing..."})]}),c.jsxs("div",{className:"text-[10px] bg-secondary px-2 py-1 rounded",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Sentiment:"}),c.jsx("span",{className:"font-bold uppercase",children:y.details?.sentiment||"Analyzing..."})]})]}),y.details?.system_prompt&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[c.jsx(la,{className:"w-3 h-3"})," System Prompt"]}),c.jsx("pre",{className:"text-[10px] bg-secondary/50 p-2 rounded border overflow-x-auto whitespace-pre-wrap max-h-40 overflow-y-auto font-mono",children:y.details?.system_prompt})]}),y.details?._raw_response&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[c.jsx(la,{className:"w-3 h-3"})," Raw LLM Response"]}),c.jsx("pre",{className:"text-[10px] bg-emerald-500/5 p-2 rounded border border-emerald-500/10 overflow-x-auto font-mono",children:JSON.stringify(JSON.parse(y.details._raw_response),null,2)})]}),y.details?.usage&&c.jsxs("div",{className:"flex gap-4 pt-2 border-t border-border/50",children:[c.jsxs("div",{className:"text-[10px]",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Prompt:"}),c.jsx("span",{className:"font-mono font-bold",children:y.details.usage.prompt_tokens})]}),c.jsxs("div",{className:"text-[10px]",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Completion:"}),c.jsx("span",{className:"font-mono font-bold",children:y.details.usage.completion_tokens})]}),c.jsxs("div",{className:"text-[10px]",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Total:"}),c.jsx("span",{className:"font-mono font-bold text-primary",children:y.details.usage.total_tokens})]})]})]}),y.event_type==="action"&&c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:["Executed: ",y.details?.action]}),c.jsxs("p",{className:"text-xs text-muted-foreground italic",children:['"',y.details?.reason,'"']})]}),c.jsx(Em,{className:"w-5 h-5 text-emerald-500"})]}),y.event_type==="error"&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:typeof y.details?.error=="object"?y.details.error.message||JSON.stringify(y.details.error):y.details?.error}),y.details?.raw_response&&c.jsx("pre",{className:"text-[10px] bg-red-500/5 p-2 rounded border border-red-500/10 overflow-x-auto whitespace-pre-wrap font-mono",children:typeof y.details.raw_response=="object"?JSON.stringify(y.details.raw_response,null,2):y.details.raw_response})]})]})]})]},y.id))})]})})}const WM={spam:"bg-destructive/10 text-destructive",newsletter:"bg-blue-500/10 text-blue-600 dark:text-blue-400",support:"bg-orange-500/10 text-orange-600 dark:text-orange-400",client:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",internal:"bg-purple-500/10 text-purple-600 dark:text-purple-400",personal:"bg-pink-500/10 text-pink-600 dark:text-pink-400",other:"bg-gray-500/10 text-gray-600 dark:text-gray-400"};function ZM(){const{state:t,actions:e,dispatch:a}=Si(),{openTerminal:r}=ww(),[o,u]=w.useState(!0),[d,f]=w.useState(!1),[p,g]=w.useState(""),[y,v]=w.useState(null),[b,S]=w.useState(null),[T,j]=w.useState({}),[E,C]=w.useState(null),[M,k]=w.useState(!1),[V,q]=w.useState(null);w.useEffect(()=>{t.isAuthenticated?(G(),e.fetchStats()):u(!1)},[y,t.isAuthenticated]);const G=async(A=0)=>{u(!0),await e.fetchEmails({category:y||void 0,search:p||void 0,offset:A,sortBy:t.sortBy,sortOrder:t.sortOrder}),u(!1)},$=A=>{e.fetchEmails({category:y||void 0,search:p||void 0,offset:0,sortBy:A,sortOrder:t.sortOrder})},B=()=>{e.fetchEmails({category:y||void 0,search:p||void 0,offset:0,sortBy:t.sortBy,sortOrder:t.sortOrder==="asc"?"desc":"asc"})},W=async()=>{if(t.accounts.length===0){oe.warning("Please connect an email account first");return}Gn.playStart(),r(),f(!0);const A=await e.triggerSync();f(!1),A?(Gn.playSuccess(),oe.success("Sync completed! Check your emails.")):oe.error("Sync failed. Check account status for details.")},me=async(A,H)=>{if(H==="delete"&&E!==A.id){C(A.id);return}C(null),j(xe=>({...xe,[A.id]:H}));const F=await e.executeAction(A.id,H);j(xe=>{const be={...xe};return delete be[A.id],be}),F&&(oe.success(`Email ${H==="delete"?"deleted":H==="archive"?"archived":"updated"}`),H==="delete"&&G(t.emailsOffset))},ue=()=>{C(null)},pe=A=>{A.preventDefault(),G()},ze=A=>{const H=A==="next"?t.emailsOffset+20:Math.max(0,t.emailsOffset-20);G(H)},Fe=A=>{q(A),k(!0)},Re=async A=>{await e.retryProcessing(A.id)&&oe.success("Retrying email processing...")};return c.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 animate-in fade-in duration-500",children:[c.jsxs("section",{className:"lg:col-span-2 space-y-4",children:[c.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-4",children:[c.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[c.jsx(tu,{className:"w-5 h-5 text-primary"}),"Recent Analysis"]}),c.jsxs("div",{className:"flex gap-2 w-full sm:w-auto",children:[c.jsxs(Q,{onClick:W,size:"sm",variant:"default",className:"h-9 shadow-md px-4",disabled:d,children:[c.jsx(fa,{className:Te("w-3.5 h-3.5 mr-2",d&&"animate-spin")}),d?"Syncing...":"Sync Now"]}),c.jsxs("span",{className:"h-9 text-xs font-medium text-muted-foreground bg-secondary px-3 py-1 rounded-md border border-border flex items-center",children:[t.emailsTotal," emails"]})]})]}),d&&c.jsxs("div",{className:"bg-primary/5 border border-primary/20 p-4 rounded-lg flex items-center justify-between animate-in fade-in slide-in-from-top-2",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"bg-primary/10 p-2 rounded-full",children:c.jsx(Pt,{className:"w-5 h-5 text-primary animate-spin"})}),c.jsxs("div",{children:[c.jsx("h4",{className:"font-semibold text-sm",children:"Sync in progress..."}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Fetching and analyzing emails. New emails will appear below automatically."})]})]}),c.jsxs(Q,{variant:"outline",size:"sm",onClick:r,className:"h-8 text-xs",children:[c.jsx(xu,{className:"w-3.5 h-3.5 mr-2"}),"View Logs"]})]}),c.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-center",children:[c.jsxs("form",{onSubmit:pe,className:"flex-1 flex gap-2 w-full",children:[c.jsxs("div",{className:"relative flex-1",children:[c.jsx(kE,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),c.jsx(Ae,{placeholder:"Search emails...",value:p,onChange:A=>g(A.target.value),className:"pl-9 h-9"})]}),c.jsx(Q,{type:"submit",size:"sm",className:"h-9 px-4",children:"Search"})]}),c.jsxs("div",{className:"flex items-center gap-1 bg-secondary/30 p-1 rounded-md border border-border/50 h-9",children:[c.jsxs("select",{className:"bg-transparent text-xs font-medium border-none focus:ring-0 cursor-pointer pl-2 pr-8 h-full",value:t.sortBy,onChange:A=>$(A.target.value),children:[c.jsx("option",{value:"date",children:"Received Time"}),c.jsx("option",{value:"created_at",children:"Processed Time"})]}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 text-primary",onClick:B,title:t.sortOrder==="asc"?"Sorting: Oldest First":"Sorting: Newest First",children:t.sortOrder==="asc"?c.jsx(bT,{className:"w-3.5 h-3.5"}):c.jsx(yT,{className:"w-3.5 h-3.5"})})]})]}),c.jsxs("div",{className:"flex gap-1 flex-wrap",children:[c.jsx(Q,{size:"sm",variant:t.activeCategory===null?"secondary":"ghost",onClick:()=>v(null),children:"All"}),["spam","client","newsletter","support"].map(A=>c.jsx(Q,{size:"sm",variant:t.activeCategory===A?"secondary":"ghost",onClick:()=>v(A),className:"capitalize",children:A},A))]}),o?c.jsx(ZC,{}):t.emails.length===0?c.jsxs(Vt,{className:"p-20 text-center shadow-sm",children:[c.jsx("div",{className:"w-16 h-16 bg-primary/10 text-primary rounded-full flex items-center justify-center mx-auto mb-6",children:c.jsx(tu,{className:"w-8 h-8"})}),c.jsx("h3",{className:"text-lg font-medium",children:"No emails found"}),c.jsx("p",{className:"text-muted-foreground mt-2 mb-6",children:t.accounts.length===0?"Connect your email account to get started.":"Try syncing or adjusting your filters."}),t.accounts.length>0&&c.jsxs(Q,{onClick:()=>{r(),W()},disabled:d,children:[c.jsx(fa,{className:Te("w-4 h-4 mr-2",d&&"animate-spin")}),"Sync Now"]})]}):c.jsxs(c.Fragment,{children:[t.emails.map(A=>c.jsx(t3,{email:A,onAction:me,onRetry:Re,onViewTrace:Fe,onSelect:()=>S(A),isSelected:b?.id===A.id,loadingAction:T[A.id],isDeletePending:E===A.id,onCancelDelete:ue},A.id)),c.jsx(JM,{isOpen:M,onOpenChange:k,email:V,onRetry:Re}),t.emailsTotal>20&&c.jsxs("div",{className:"flex items-center justify-between pt-4",children:[c.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>ze("prev"),disabled:t.emailsOffset===0,children:[c.jsx(DT,{className:"w-4 h-4 mr-1"}),"Previous"]}),c.jsxs("span",{className:"text-sm text-muted-foreground",children:[t.emailsOffset+1," - ",Math.min(t.emailsOffset+20,t.emailsTotal)," of ",t.emailsTotal]}),c.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>ze("next"),disabled:t.emailsOffset+20>=t.emailsTotal,children:["Next",c.jsx(Zc,{className:"w-4 h-4 ml-1"})]})]})]})]}),c.jsxs("aside",{className:"space-y-6",children:[b&&c.jsxs(Vt,{className:"p-6 border-primary/20 bg-primary/5 animate-in slide-in-from-right-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-4",children:[c.jsx("h3",{className:"font-semibold",children:"Email Details"}),c.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>S(null),children:c.jsx(yi,{className:"w-4 h-4"})})]}),c.jsxs("div",{className:"space-y-3 text-sm",children:[c.jsxs("div",{children:[c.jsx("span",{className:"text-muted-foreground",children:"From:"}),c.jsx("p",{className:"font-medium truncate",children:b.sender})]}),c.jsxs("div",{children:[c.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),c.jsx("p",{className:"font-medium",children:b.subject})]}),b.ai_analysis&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{children:[c.jsx("span",{className:"text-muted-foreground",children:"Summary:"}),c.jsx("p",{className:"text-xs mt-1",children:b.ai_analysis.summary})]}),b.ai_analysis.key_points&&c.jsxs("div",{children:[c.jsx("span",{className:"text-muted-foreground",children:"Key Points:"}),c.jsx("ul",{className:"text-xs mt-1 list-disc list-inside",children:b.ai_analysis.key_points.map((A,H)=>c.jsx("li",{children:A},H))})]}),b.ai_analysis.draft_response&&c.jsxs("div",{className:"mt-4 p-3 bg-emerald-500/5 border border-emerald-500/20 rounded-lg",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2 text-emerald-600 dark:text-emerald-400",children:[c.jsx(OE,{className:"w-3.5 h-3.5"}),c.jsx("span",{className:"text-xs font-bold uppercase",children:"AI Draft Reply"})]}),c.jsx("p",{className:"text-xs leading-relaxed whitespace-pre-wrap italic text-foreground/80",children:b.ai_analysis.draft_response}),c.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:["* This draft is already saved in your ",b.email_accounts?.provider==="gmail"?"Gmail":"Outlook"," Drafts folder."]})]})]})]})]}),c.jsx(QM,{accounts:t.accounts,onUpdate:e.updateAccount,onSync:e.triggerSync,settings:t.settings,onUpdateSettings:e.updateSettings,openTerminal:r}),c.jsxs(Vt,{className:"p-6",children:[c.jsxs("h3",{className:"font-semibold mb-4 flex items-center gap-2",children:[c.jsx(Ob,{className:"w-4 h-4 text-primary"}),"Sync History"]}),c.jsx("div",{className:"space-y-4",children:!t.stats?.recentSyncs||t.stats.recentSyncs.length===0?c.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No sync history available."}):t.stats.recentSyncs.slice(0,5).map(A=>c.jsxs("div",{className:"flex justify-between items-start text-sm border-b last:border-0 pb-3 last:pb-0",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:Te("w-1.5 h-1.5 rounded-full",A.status==="success"?"bg-emerald-500":A.status==="running"?"bg-blue-500 animate-pulse":"bg-red-500")}),c.jsxs("p",{className:"font-medium text-xs",children:[new Date(A.started_at).toLocaleDateString()," ",new Date(A.started_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]}),c.jsxs("p",{className:"text-[10px] text-muted-foreground pl-3.5",children:["Processed: ",c.jsx("span",{className:"font-medium text-foreground",children:A.emails_processed})," • Actioned: ",c.jsx("span",{className:"font-medium text-foreground",children:A.emails_deleted+A.emails_drafted})]}),A.error_message&&c.jsx("p",{className:"text-[10px] text-destructive pl-3.5 line-clamp-1",title:A.error_message,children:A.error_message})]}),c.jsx("div",{className:"text-[10px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded",children:A.status==="running"?"Running":A.completed_at?`${Math.round((new Date(A.completed_at).getTime()-new Date(A.started_at).getTime())/1e3)}s`:"..."})]},A.id))})]}),c.jsxs(Vt,{className:"p-6",children:[c.jsx("h3",{className:"font-semibold mb-4",children:"Quick Stats"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Processed"}),c.jsx("span",{className:"font-medium",children:t.emailsTotal})]}),c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx("span",{className:"text-sm text-muted-foreground",children:"Connected Accounts"}),c.jsx("span",{className:"font-medium",children:t.accounts.length})]}),c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Rules"}),c.jsx("span",{className:"font-medium",children:t.rules.filter(A=>A.is_enabled).length})]})]})]})]})]})}function QM({accounts:t,onUpdate:e,onSync:a,settings:r,onUpdateSettings:o,openTerminal:u}){return t.length===0?null:c.jsxs(Vt,{className:"p-6",children:[c.jsxs("h3",{className:"font-semibold mb-4 flex items-center gap-2",children:[c.jsx(zE,{className:"w-4 h-4 text-primary"}),"Sync Scope"]}),c.jsx("div",{className:"space-y-6",children:t.map(d=>c.jsx(e3,{account:d,onUpdate:e,onSync:a,openTerminal:u},d.id))})]})}function e3({account:t,onUpdate:e,onSync:a,openTerminal:r}){const[o,u]=w.useState(!1),[d,f]=w.useState(""),[p,g]=w.useState(""),y=T=>{if(!T)return"";const j=typeof T=="string"&&/^\d+$/.test(T)?parseInt(T):T,E=new Date(j);if(isNaN(E.getTime()))return"";const C=M=>M<10?"0"+M:M;return E.getFullYear()+"-"+C(E.getMonth()+1)+"-"+C(E.getDate())+"T"+C(E.getHours())+":"+C(E.getMinutes())};w.useEffect(()=>{const T=t.sync_start_date||t.last_sync_checkpoint||t.last_sync_at;f(y(T)),g((t.sync_max_emails_per_run||50).toString())},[t.id,t.sync_start_date,t.last_sync_checkpoint,t.last_sync_at,t.sync_max_emails_per_run]);const v=async T=>{u(!0),await e(t.id,T),u(!1)},b=()=>{const T=t.sync_start_date?new Date(t.sync_start_date).toISOString():"",j=d?new Date(d).toISOString():"";j!==T&&v({sync_start_date:j||null})},S=()=>{const T=parseInt(p,10)||50;T!==t.sync_max_emails_per_run&&v({sync_max_emails_per_run:T})};return c.jsxs("div",{className:"space-y-3 pb-4 border-b last:border-0 last:pb-0",children:[c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx("span",{className:"text-xs font-medium truncate max-w-[150px]",title:t.email_address,children:t.email_address}),c.jsxs("div",{className:"flex items-center gap-1",children:[t.last_sync_status==="syncing"?c.jsx(Pt,{className:"w-3 h-3 text-primary animate-spin"}):t.last_sync_status==="success"?c.jsx(Em,{className:"w-3 h-3 text-emerald-500"}):t.last_sync_status==="error"?c.jsx("span",{title:t.last_sync_error||"Error",children:c.jsx(js,{className:"w-3 h-3 text-destructive"})}):null,c.jsx(Q,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{r(),a(t.id)},disabled:t.last_sync_status==="syncing",children:c.jsx(fa,{className:Te("w-3 h-3",t.last_sync_status==="syncing"&&"animate-spin")})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground hover:text-orange-500",title:"Reset Checkpoint (Force Full Re-sync from Start Date)",onClick:()=>e(t.id,{last_sync_checkpoint:null}),disabled:t.last_sync_status==="syncing",children:c.jsx(Ob,{className:"w-3 h-3"})})]})]}),c.jsxs("div",{className:"grid grid-cols-[1.5fr_1fr] gap-2",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("label",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(TT,{className:"w-2.5 h-2.5"})," Sync From"]}),c.jsx(Ae,{type:"datetime-local",className:"h-7 text-[10px] px-2 py-0 w-full",value:d,onChange:T=>f(T.target.value),onBlur:b,disabled:o||t.last_sync_status==="syncing"})]}),c.jsxs("div",{className:"space-y-1",children:[c.jsxs("label",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(sE,{className:"w-2.5 h-2.5"})," Max Emails"]}),c.jsx(Ae,{type:"number",className:"h-7 text-[10px] px-2 py-0",value:p,onChange:T=>g(T.target.value),onBlur:S,disabled:o||t.last_sync_status==="syncing"})]})]}),t.last_sync_at&&c.jsxs("p",{className:"text-[9px] text-muted-foreground",children:["Last sync: ",new Date(t.last_sync_at).toLocaleString()]}),t.last_sync_error&&c.jsxs("p",{className:"text-[9px] text-destructive italic line-clamp-1",title:t.last_sync_error,children:["Error: ",t.last_sync_error]})]})}function t3({email:t,onAction:e,onRetry:a,onViewTrace:r,onSelect:o,isSelected:u,loadingAction:d,isDeletePending:f,onCancelDelete:p}){if(!t)return null;const g=WM[t.category||"other"],y=!!d,v=()=>{if(!t.email_accounts)return"#";const{provider:b,email_address:S}=t.email_accounts;return b==="gmail"?`https://mail.google.com/mail/u/${S}/#all/${t.external_id}`:`https://outlook.office.com/mail/deeplink/read/${encodeURIComponent(t.external_id)}`};return c.jsx(Vt,{className:Te("hover:shadow-md transition-shadow group cursor-pointer",u&&"ring-2 ring-primary"),onClick:o,children:c.jsxs("div",{className:"p-5",children:[c.jsxs("div",{className:"flex justify-between items-start mb-3 gap-4",children:[c.jsxs("div",{className:"flex gap-3 flex-1 min-w-0",children:[c.jsx("div",{className:Te("w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center font-bold text-white text-xs",t.category==="spam"?"bg-destructive":"bg-primary"),children:t.sender?.[0]?.toUpperCase()||"?"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("h3",{className:"font-semibold text-sm line-clamp-1 group-hover:text-primary transition-colors",children:t.subject||"No Subject"}),c.jsx("p",{className:"text-xs text-muted-foreground truncate",title:t.sender||"",children:t.sender})]})]}),c.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[c.jsx("span",{className:Te("px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",g),children:t.category||"unknown"}),c.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.processing_status==="pending"&&c.jsxs("span",{className:"text-[9px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(fi,{className:"w-2.5 h-2.5"})," Queued"]}),t.processing_status==="processing"&&c.jsxs("span",{className:"text-[9px] text-blue-600 dark:text-blue-400 bg-blue-500/10 border border-blue-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(Pt,{className:"w-2.5 h-2.5 animate-spin"})," Analyzing"]}),t.processing_status==="completed"&&c.jsxs("span",{className:"text-[9px] text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(Lo,{className:"w-2.5 h-2.5"})," Analyzed"]}),t.processing_status==="failed"&&c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsxs("span",{className:"text-[9px] text-red-600 dark:text-red-400 bg-red-500/10 border border-red-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",title:t.processing_error||"Unknown error",children:[c.jsx(js,{className:"w-2.5 h-2.5"})," Failed"]}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-5 w-5 text-red-600 hover:bg-red-500/10",onClick:b=>{b.stopPropagation(),a(t)},title:"Retry Processing",children:c.jsx(fa,{className:"w-2.5 h-2.5"})})]}),!t.processing_status&&!t.ai_analysis&&c.jsxs("span",{className:"text-[9px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(Pt,{className:"w-2.5 h-2.5 animate-spin"})," Pending"]}),!t.processing_status&&t.ai_analysis&&c.jsxs("span",{className:"text-[9px] text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(Lo,{className:"w-2.5 h-2.5"})," Analyzed"]})]}),c.jsxs("div",{className:"flex items-center justify-end gap-2 text-[10px] text-muted-foreground/80 leading-tight",children:[c.jsxs("span",{title:t.date?new Date(t.date).toLocaleString():"",className:"whitespace-nowrap",children:[c.jsx("span",{className:"opacity-70 text-[9px]",children:"REC:"})," ",t.date?new Date(t.date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"-"]}),c.jsx("span",{className:"opacity-30",children:"•"}),c.jsxs("span",{title:new Date(t.created_at).toLocaleString(),className:"whitespace-nowrap",children:[c.jsx("span",{className:"opacity-70 text-[9px]",children:"PROC:"})," ",new Date(t.created_at).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})]})]})]})]}),c.jsx("p",{className:"text-muted-foreground text-sm mb-4 line-clamp-2 leading-relaxed",children:t.body_snippet}),c.jsxs("div",{className:"bg-secondary/30 p-3 rounded-lg border border-border/50 flex justify-between items-center",children:[c.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[c.jsx(Mf,{className:"w-3.5 h-3.5 text-emerald-500"}),"Suggested:",t.suggested_actions&&t.suggested_actions.length>0?c.jsx("div",{className:"flex gap-1 flex-wrap",children:t.suggested_actions.map(b=>c.jsx("span",{className:"text-foreground border border-border/50 px-1.5 py-0.5 rounded capitalize bg-background/50",children:b},b))}):c.jsx("span",{className:"text-foreground",children:t.suggested_action||"none"}),t.actions_taken&&t.actions_taken.length>0?c.jsxs("span",{className:"text-muted-foreground ml-2 truncate max-w-[100px]",title:t.actions_taken.join(", "),children:["(Done: ",t.actions_taken.join(", "),")"]}):t.action_taken?c.jsxs("span",{className:"text-muted-foreground ml-2",children:["(Done: ",t.action_taken,")"]}):null]}),c.jsx("div",{className:"flex gap-1 items-center",onClick:b=>b.stopPropagation(),children:f?c.jsxs("div",{className:"flex items-center gap-1 animate-in fade-in duration-200",children:[c.jsx("span",{className:"text-xs text-destructive mr-1",children:"Delete?"}),c.jsx(Q,{variant:"destructive",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>e(t,"delete"),disabled:y,children:d==="delete"?c.jsx(Pt,{className:"w-3 h-3 animate-spin"}):"Yes"}),c.jsx(Q,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:p,disabled:y,children:"No"})]}):c.jsxs(c.Fragment,{children:[c.jsx("a",{href:v(),target:"_blank",rel:"noreferrer",className:"inline-flex items-center justify-center h-7 w-7 rounded-md text-muted-foreground hover:text-primary hover:bg-secondary/50 transition-colors",title:`Open in ${t.email_accounts?.provider==="gmail"?"Gmail":"Outlook"}`,children:c.jsx(eu,{className:"w-3.5 h-3.5"})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-primary",onClick:()=>r(t),title:"View AI Trace (Prompt/Response)",children:c.jsx(Rb,{className:"w-3.5 h-3.5"})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-destructive",onClick:()=>e(t,"delete"),disabled:y,title:"Delete",children:d==="delete"?c.jsx(Pt,{className:"w-3.5 h-3.5 animate-spin"}):c.jsx(au,{className:"w-3.5 h-3.5"})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-blue-500",onClick:()=>e(t,"archive"),disabled:y,title:"Archive",children:d==="archive"?c.jsx(Pt,{className:"w-3.5 h-3.5 animate-spin"}):c.jsx(pT,{className:"w-3.5 h-3.5"})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-primary",onClick:()=>e(t,"flag"),disabled:y,title:"Flag",children:d==="flag"?c.jsx(Pt,{className:"w-3.5 h-3.5 animate-spin"}):c.jsx(QT,{className:"w-3.5 h-3.5"})})]})})]})]})})}const No="realtimexai";function n3(){const{state:t,actions:e}=Si(),[a,r]=w.useState(!1),[o,u]=w.useState(!1),[d,f]=w.useState(null),[p,g]=w.useState(!1),[y,v]=w.useState(!1),[b,S]=w.useState({}),[T,j]=w.useState(!1),[E,C]=w.useState("credentials"),[M,k]=w.useState(""),[V,q]=w.useState(""),[G,$]=w.useState(""),[B,W]=w.useState(""),[me,ue]=w.useState(!1),[pe,ze]=w.useState(!1),[Fe,Re]=w.useState(!1),[A,H]=w.useState("credentials"),[F,xe]=w.useState(""),[be,R]=w.useState(""),[X,Z]=w.useState(!1),[te,fe]=w.useState(!1),[we,he]=w.useState(""),[Ye,Be]=w.useState("category"),[Mt,wt]=w.useState("newsletter"),[Tt,Ns]=w.useState(["archive"]),[En,As]=w.useState(""),[Qa,er]=w.useState(""),[Ei,Cs]=w.useState(""),[tr,ks]=w.useState(""),[il,ya]=w.useState([]),[St,ol]=w.useState(!1),[Ni,Ai]=w.useState(!1),[un,Ru]=w.useState([]),[va,ll]=w.useState(!1),[cl,Yn]=w.useState(null);w.useEffect(()=>{(async()=>{ll(!0),Yn(null);try{const ee=await Ue.getChatProviders();ee.data?.success?Ru(ee.data.providers||[]):Yn(ee.data?.message||"Failed to load providers")}catch(ee){console.error("Failed to fetch providers:",ee),Yn("Failed to load providers. Using defaults.")}finally{ll(!1)}})()},[]);const Kt=un.find(D=>D.provider===(b.llm_provider||No))?.models||[],zt=w.useMemo(()=>!b.llm_model||Kt.some(ee=>ee.id===b.llm_model)?Kt:[{id:b.llm_model,name:`${b.llm_model} (saved)`},...Kt],[Kt,b.llm_model]),Ou=w.useMemo(()=>!b.llm_provider||b.llm_provider===No||un.some(ee=>ee.provider===b.llm_provider)?un:[{provider:b.llm_provider,name:`${b.llm_provider} (saved)`,models:[]},...un],[un,b.llm_provider]),Du=D=>{const ee=un.find(Ne=>Ne.provider===D);S(Ne=>({...Ne,llm_provider:D,llm_model:ee?.models?.[0]?.id||""}))},Mu=async()=>{v(!0);try{const D=await Ue.testLlm({llm_provider:b.llm_provider||void 0,llm_model:b.llm_model||void 0});D.data?.success?oe.success(D.data.message):oe.error(D.data?.message||"Connection failed")}catch(D){oe.error(D.response?.data?.message||"Connection failed")}finally{v(!1)}},[Xn,Jn]=w.useState(null),[dn,hn]=w.useState(null);w.useEffect(()=>{e.fetchAccounts(),e.fetchRules(),e.fetchSettings()},[]),w.useEffect(()=>{t.settings&&S(t.settings)},[t.settings]);const nr=async()=>{const D=t.rules.find(ee=>ee.name==="Auto-Trash Spam");if(!D){oe.error("System rule not found. Please sync your database.");return}Jn("auto_trash_spam"),await e.toggleRule(D.id),Jn(null)},xa=async()=>{const D=t.rules.find(ee=>ee.name==="Smart Drafts");if(!D){oe.error("System rule not found. Please sync your database.");return}Jn("smart_drafts"),await e.toggleRule(D.id),Jn(null)},Ci=D=>{hn(D),he(D.name);const ee=D.condition,Et=Object.keys(ee).filter(Os=>Os!=="older_than_days")[0]||"category";Be(Et),wt(ee[Et]||""),As(ee.older_than_days?.toString()||"");const Wn=D.actions&&D.actions.length>0?D.actions:D.action?[D.action]:["archive"];Ns(Wn),er(D.instructions||""),Cs(D.description||""),ks(D.intent||""),ya(D.attachments||[]),fe(!0)},ul=w.useRef(null),ki=()=>{C("credentials"),k(""),q(""),$(""),W(""),j(!0)},ba=D=>{k(D);try{const ee=JSON.parse(D),Ne=ee.installed||ee.web||ee;Ne.client_id&&q(Ne.client_id),Ne.client_secret&&$(Ne.client_secret),ee.installed?oe.success("Detected Desktop app credentials"):ee.web&&oe.info("Detected Web app - make sure redirect URI is configured in Google Cloud Console")}catch{}},zu=async()=>{if(!V||!G){oe.error("Please provide both Client ID and Client Secret");return}ue(!0);try{if(await e.updateSettings({...b,google_client_id:V,google_client_secret:G})){S(Ne=>({...Ne,google_client_id:V,google_client_secret:G}));const ee=await Ue.getGmailAuthUrl();if(ee.data?.url)window.open(ee.data.url,"_blank"),C("code"),oe.success("Please authorize in the opened tab, then paste the code here");else{const Ne=typeof ee.error=="string"?ee.error:ee.error?.message;oe.error(Ne||"Failed to get OAuth URL")}}else oe.error("Failed to save credentials")}catch{oe.error("Failed to save credentials")}finally{ue(!1)}},dl=async()=>{if(!B.trim()){oe.error("Please paste the authorization code");return}ze(!0);try{const D=await Ue.connectGmail(B.trim());if(D.data?.success)oe.success("Gmail account connected successfully!"),j(!1),e.fetchAccounts();else{const ee=typeof D.error=="string"?D.error:D.error?.message;oe.error(ee||"Failed to connect Gmail")}}catch{oe.error("Failed to connect Gmail")}finally{ze(!1)}},hl=()=>{H("credentials"),xe(""),R(""),Re(!0)},fl=async()=>{if(!F){oe.error("Please provide the Client ID");return}Z(!0);try{if(await e.updateSettings({...b,microsoft_client_id:F,microsoft_tenant_id:be||"common"})){S(Ne=>({...Ne,microsoft_client_id:F,microsoft_tenant_id:be||"common"}));const ee=await Ue.startMicrosoftDeviceFlow();if(ee.data)f(ee.data),H("device-code"),Ri(ee.data.deviceCode,ee.data.interval);else{const Ne=typeof ee.error=="string"?ee.error:ee.error?.message;oe.error(Ne||"Failed to start device flow")}}else oe.error("Failed to save credentials")}catch{oe.error("Failed to save credentials")}finally{Z(!1)}},Ri=async(D,ee)=>{const Ne=setInterval(async()=>{try{const Et=await Ue.pollMicrosoftDeviceCode(D);Et.data?.status==="completed"?(clearInterval(Ne),f(null),u(!1),Re(!1),oe.success("Outlook account connected"),e.fetchAccounts()):Et.error&&typeof Et.error=="object"&&Et.error.code}catch{}},ee*1e3);setTimeout(()=>{clearInterval(Ne),o&&(f(null),u(!1),Re(!1),oe.error("Connection timed out. Please try again."))},900*1e3)},Oi=async()=>{if(!we){oe.error("Please name your rule");return}if(Tt.length===0){oe.error("Please select at least one action");return}Ai(!0);try{const D={[Ye]:Mt};En&&(D.older_than_days=parseInt(En,10));const ee=Tt.includes("draft"),Ne={name:we,description:Ei||void 0,intent:tr||void 0,condition:D,actions:Tt,instructions:ee?Qa:void 0,attachments:ee?il:[],is_enabled:!0};let Et=!1;dn?Et=await e.updateRule(dn.id,Ne):Et=await e.createRule(Ne),Et?(oe.success(dn?"Rule updated":"Rule created"),fe(!1),hn(null),he(""),Ns(["archive"]),As(""),er(""),Cs(""),ks(""),ya([]),e.fetchRules()):oe.error(`Failed to ${dn?"update":"create"} rule`)}catch{oe.error("An error occurred while saving the rule")}finally{Ai(!1)}},ml=async D=>{if(!confirm("Are you sure you want to disconnect this account?"))return;await e.disconnectAccount(D)&&oe.success("Account disconnected")},Di=async()=>{g(!0);const D=await e.updateSettings(b);g(!1),D&&oe.success("Settings saved")},Pn=async D=>{await e.toggleRule(D)},gt=async D=>{const ee=D.target.files;if(!ee||ee.length===0)return;ol(!0);const Ne=ee[0],Et=Ne.name.split(".").pop(),Wn=`${Math.random().toString(36).substring(2)}.${Et}`,Os=`${t.user.id}/${Wn}`;try{const{error:Nn}=await et.storage.from("rule-attachments").upload(Os,Ne);if(Nn)throw Nn;const Ds={name:Ne.name,path:Os,type:Ne.type,size:Ne.size};ya(wa=>[...wa,Ds]),oe.success("File uploaded")}catch(Nn){console.error("Upload error:",Nn),oe.error("Failed to upload file")}finally{ol(!1),D.target.value=""}},Ut=D=>{ya(ee=>ee.filter(Ne=>Ne.path!==D))},Rs=D=>D==="gmail"?c.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center text-red-600 dark:text-red-400 font-bold",children:"G"}):c.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold",children:"O"});return c.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[c.jsx(li,{open:T,onOpenChange:j,children:c.jsxs(ci,{className:"sm:max-w-lg",children:[c.jsxs(ui,{children:[c.jsxs(di,{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center text-red-600 dark:text-red-400 font-bold text-sm",children:"G"}),"Connect Gmail Account"]}),c.jsx(hi,{children:E==="credentials"?"Enter your Google OAuth credentials to connect your Gmail account.":"Paste the authorization code from Google to complete the connection."})]}),E==="credentials"?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(HE,{className:"w-4 h-4"}),"Paste credentials.json"]}),c.jsx("textarea",{className:"w-full h-24 p-3 text-xs font-mono border rounded-lg bg-secondary/30 resize-none focus:outline-none focus:ring-2 focus:ring-primary",placeholder:'{"installed":{"client_id":"...","client_secret":"..."}}',value:M,onChange:D=>ba(D.target.value)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Download from Google Cloud Console → APIs & Services → Credentials"})]}),c.jsxs("div",{className:"relative",children:[c.jsx("div",{className:"absolute inset-0 flex items-center",children:c.jsx("span",{className:"w-full border-t"})}),c.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:c.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or enter manually"})})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),c.jsx(Ae,{placeholder:"xxx.apps.googleusercontent.com",value:V,onChange:D=>q(D.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client Secret"}),c.jsx(Ae,{type:"password",placeholder:"GOCSPX-...",value:G,onChange:D=>$(D.target.value)})]})]})]}),c.jsxs(Zr,{children:[c.jsx(Q,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),c.jsxs(Q,{onClick:zu,disabled:me||!V||!G,children:[me?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Save & Connect"]})]})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsx("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:c.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:["1. A new tab opened with Google Sign-In",c.jsx("br",{}),"2. Sign in and authorize the app",c.jsx("br",{}),"3. Copy the authorization code shown",c.jsx("br",{}),"4. Paste it below"]})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Authorization Code"}),c.jsx(Ae,{placeholder:"4/0AQlEd8x...",value:B,onChange:D=>W(D.target.value),className:"font-mono"})]})]}),c.jsxs(Zr,{children:[c.jsx(Q,{variant:"outline",onClick:()=>C("credentials"),children:"Back"}),c.jsxs(Q,{onClick:dl,disabled:pe||!B.trim(),children:[pe?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Connect"]})]})]})]})}),c.jsx(li,{open:Fe,onOpenChange:Re,children:c.jsxs(ci,{className:"sm:max-w-lg",children:[c.jsxs(ui,{children:[c.jsxs(di,{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold text-sm",children:"O"}),"Connect Outlook Account"]}),c.jsx(hi,{children:A==="credentials"?"Enter your Microsoft Azure App credentials to connect your Outlook account.":"Follow the instructions to authorize the application."})]}),A==="credentials"?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsx("div",{className:"p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg",children:c.jsx("p",{className:"text-sm text-yellow-800 dark:text-yellow-200",children:"Note: You need an Azure App Registration for this to work."})}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client ID (Application ID)"}),c.jsx(Ae,{placeholder:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",value:F,onChange:D=>xe(D.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Tenant ID (Optional)"}),c.jsx(Ae,{placeholder:"common",value:be,onChange:D=>R(D.target.value)}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:'Default is "common". Use your specific Tenant ID for organization accounts.'})]})]})]}),c.jsxs(Zr,{children:[c.jsx(Q,{variant:"outline",onClick:()=>Re(!1),children:"Cancel"}),c.jsxs(Q,{onClick:fl,disabled:X||!F,children:[X?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Save & Connect"]})]})]}):c.jsxs(c.Fragment,{children:[d&&c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:[c.jsx("h4",{className:"font-medium text-blue-900 dark:text-blue-100 mb-2",children:"Action Required"}),c.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200 mb-4",children:d.message}),c.jsxs("div",{className:"flex flex-col gap-3",children:[c.jsx("div",{className:"flex items-center gap-2 bg-white dark:bg-black/20 p-2 rounded border border-blue-200 dark:border-blue-800",children:c.jsx("code",{className:"text-lg font-mono font-bold flex-1 text-center select-all",children:d.userCode})}),c.jsxs(Q,{variant:"default",className:"w-full bg-blue-600 hover:bg-blue-700",onClick:()=>window.open(d.verificationUri,"_blank"),children:["Open Microsoft Login",c.jsx(eu,{className:"w-4 h-4 ml-2"})]})]})]}),c.jsx("div",{className:"flex justify-center",children:c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(ft,{size:"sm"}),"Waiting for authorization..."]})})]}),c.jsx(Zr,{children:c.jsx(Q,{variant:"outline",onClick:()=>Re(!1),children:"Cancel"})})]})]})}),c.jsx(li,{open:te,onOpenChange:D=>{fe(D),D||hn(null)},children:c.jsxs(ci,{className:"sm:max-w-xl max-h-[90vh] flex flex-col p-0",children:[c.jsxs(ui,{className:"p-6 border-b",children:[c.jsx(di,{children:dn?"Edit Auto-Pilot Rule":"Create Auto-Pilot Rule"}),c.jsx(hi,{children:"Define a condition based on AI analysis to trigger an action."})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Rule Name"}),c.jsx(Ae,{placeholder:"e.g. Archive Newsletters",value:we,onChange:D=>he(D.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Description"}),c.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[60px] text-sm",placeholder:"e.g. Handle all marketing newsletters and promotional content from subscription services",value:Ei,onChange:D=>Cs(D.target.value)}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Describe what this rule is for. The AI uses this to semantically match emails."})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Intent"}),c.jsx(Ae,{placeholder:"e.g. Politely decline all sales pitches",value:tr,onChange:D=>ks(D.target.value)}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"The goal of this rule. Used to generate appropriate draft replies."})]}),c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"If Condition Field"}),c.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ye,onChange:D=>{Be(D.target.value),D.target.value==="category"?wt("newsletter"):D.target.value==="sentiment"?wt("Positive"):D.target.value==="priority"?wt("High"):wt("")},children:[c.jsxs("optgroup",{label:"AI Analysis",children:[c.jsx("option",{value:"category",children:"Category"}),c.jsx("option",{value:"sentiment",children:"Sentiment"}),c.jsx("option",{value:"priority",children:"Priority"})]}),c.jsxs("optgroup",{label:"Metadata",children:[c.jsx("option",{value:"sender_email",children:"Specific Email (Exact)"}),c.jsx("option",{value:"sender_domain",children:"Email Domain (@...)"}),c.jsx("option",{value:"sender_contains",children:"Sender contains..."}),c.jsx("option",{value:"subject_contains",children:"Subject contains..."}),c.jsx("option",{value:"body_contains",children:"Body contains..."})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Equals Value"}),Ye==="category"?c.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Mt,onChange:D=>wt(D.target.value),children:[c.jsx("option",{value:"newsletter",children:"Newsletter"}),c.jsx("option",{value:"spam",children:"Spam"}),c.jsx("option",{value:"promotional",children:"Promotional"}),c.jsx("option",{value:"transactional",children:"Transactional"}),c.jsx("option",{value:"social",children:"Social"}),c.jsx("option",{value:"support",children:"Support"}),c.jsx("option",{value:"client",children:"Client"}),c.jsx("option",{value:"internal",children:"Internal"}),c.jsx("option",{value:"personal",children:"Personal"}),c.jsx("option",{value:"other",children:"Other"})]}):Ye==="sentiment"?c.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Mt,onChange:D=>wt(D.target.value),children:[c.jsx("option",{value:"Positive",children:"Positive"}),c.jsx("option",{value:"Neutral",children:"Neutral"}),c.jsx("option",{value:"Negative",children:"Negative"})]}):Ye==="priority"?c.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Mt,onChange:D=>wt(D.target.value),children:[c.jsx("option",{value:"High",children:"High"}),c.jsx("option",{value:"Medium",children:"Medium"}),c.jsx("option",{value:"Low",children:"Low"})]}):c.jsx(Ae,{placeholder:Ye==="sender_domain"?"rta.vn":Ye==="sender_email"?"john@example.com":"Keywords...",value:Mt,onChange:D=>wt(D.target.value)})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(fi,{className:"w-4 h-4"}),"Only if email is older than... (Optional)"]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Ae,{type:"number",min:"0",placeholder:"0",className:"w-24",value:En,onChange:D=>As(D.target.value)}),c.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Leave empty or 0 to apply rule immediately upon receipt."})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Then Perform Action(s)"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select one or more actions to execute when the rule matches"}),c.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"archive",label:"Archive Email"},{value:"delete",label:"Delete Email"},{value:"draft",label:"Draft Reply"},{value:"read",label:"Mark as Read"},{value:"star",label:"Star / Flag"}].map(D=>c.jsxs("label",{className:`flex items-center gap-2 p-2 border rounded-md cursor-pointer transition-colors ${Tt.includes(D.value)?"bg-primary/10 border-primary":"bg-background hover:bg-secondary/50"}`,children:[c.jsx("input",{type:"checkbox",checked:Tt.includes(D.value),onChange:ee=>{ee.target.checked?Ns([...Tt,D.value]):Ns(Tt.filter(Ne=>Ne!==D.value))},className:"rounded border-gray-300"}),c.jsx("span",{className:"text-sm",children:D.label})]},D.value))})]}),Tt.includes("draft")&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[c.jsx("label",{className:"text-sm font-medium",children:"Draft Instructions (Context)"}),c.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[80px] text-sm",placeholder:"e.g. Tell them I'm busy until Friday, but interested in the proposal.",value:Qa,onChange:D=>er(D.target.value)}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Specific context for the AI ghostwriter."})]}),c.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(x0,{className:"w-4 h-4"}),"Attachments (Optional)"]}),c.jsxs("div",{className:"flex flex-col gap-2",children:[il.map(D=>c.jsxs("div",{className:"flex items-center justify-between p-2 bg-secondary/50 rounded border text-xs",children:[c.jsx("span",{className:"truncate max-w-[200px]",children:D.name}),c.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive",onClick:()=>Ut(D.path),children:c.jsx(yi,{className:"w-3 h-3"})})]},D.path)),c.jsxs("div",{className:"relative",children:[c.jsx("input",{type:"file",className:"absolute inset-0 opacity-0 cursor-pointer",onChange:gt,disabled:St}),c.jsxs(Q,{variant:"outline",size:"sm",className:"w-full border-dashed",disabled:St,children:[St?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(jo,{className:"w-3 h-3 mr-2"}),St?"Uploading...":"Add Attachment"]})]})]}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Files will be attached to every draft generated by this rule."})]})]})]}),c.jsxs(Zr,{className:"p-6 border-t bg-secondary/5",children:[c.jsx(Q,{variant:"outline",onClick:()=>fe(!1),children:"Cancel"}),c.jsxs(Q,{onClick:Oi,disabled:Ni,children:[Ni?c.jsx(ft,{size:"sm",className:"mr-2"}):dn?c.jsx(Pr,{className:"w-4 h-4 mr-2"}):c.jsx(jo,{className:"w-4 h-4 mr-2"}),dn?"Save Changes":"Create Rule"]})]})]})}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(Po,{className:"w-5 h-5 text-primary"}),"Connected Accounts"]}),c.jsx(ca,{children:"Manage your email providers"})]}),c.jsxs(ws,{className:"space-y-4",children:[t.accounts.length===0?c.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No accounts connected yet"}):t.accounts.map(D=>c.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg bg-card",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[Rs(D.provider),c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium capitalize",children:D.provider}),c.jsx("p",{className:"text-xs text-muted-foreground",children:D.email_address})]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[D.is_active?c.jsx("span",{className:"text-xs text-emerald-600 bg-emerald-500/10 px-2 py-1 rounded-full",children:"Active"}):c.jsx("span",{className:"text-xs text-yellow-600 bg-yellow-500/10 px-2 py-1 rounded-full",children:"Inactive"}),c.jsx(Q,{variant:"outline",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>ml(D.id),children:c.jsx(au,{className:"w-4 h-4"})})]})]},D.id)),c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsxs(Q,{className:"w-full border-dashed",variant:"outline",onClick:ki,disabled:a||o,children:[a?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(jo,{className:"w-4 h-4 mr-2"}),"Connect Gmail Account"]}),c.jsxs(Q,{className:"w-full border-dashed",variant:"outline",onClick:hl,disabled:a||o,children:[o&&!d?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(jo,{className:"w-4 h-4 mr-2"}),"Connect Outlook Account"]})]}),d&&c.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg animate-in slide-in-from-top-2",children:[c.jsx("h4",{className:"font-medium text-blue-900 dark:text-blue-100 mb-2",children:"Microsoft Sign-In Required"}),c.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200 mb-4",children:d.message}),c.jsxs("div",{className:"flex flex-col gap-3",children:[c.jsx("div",{className:"flex items-center gap-2 bg-white dark:bg-black/20 p-2 rounded border border-blue-200 dark:border-blue-800",children:c.jsx("code",{className:"text-lg font-mono font-bold flex-1 text-center select-all",children:d.userCode})}),c.jsxs(Q,{variant:"default",className:"w-full bg-blue-600 hover:bg-blue-700",onClick:()=>window.open(d.verificationUri,"_blank"),children:["Open Microsoft Login",c.jsx(eu,{className:"w-4 h-4 ml-2"})]}),c.jsx("p",{className:"text-xs text-center text-muted-foreground mt-2",children:"Waiting for you to sign in..."})]})]})]})]}),c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(Mf,{className:"w-5 h-5 text-emerald-500"}),"Auto-Pilot Rules"]}),c.jsx(ca,{children:"Configure AI automation behavior"})]}),c.jsxs(ws,{className:"space-y-4",children:[c.jsxs("div",{className:"flex justify-between items-center py-3 border-b border-border",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium text-sm",children:"Auto-Trash Spam"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically delete emails categorized as spam"})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{const D=t.rules.find(ee=>ee.name==="Auto-Trash Spam");D&&Ci(D)},title:"Edit Logic",children:c.jsx(Xh,{className:"w-4 h-4 text-muted-foreground"})}),c.jsxs(Q,{variant:t.rules.find(D=>D.name==="Auto-Trash Spam")?.is_enabled?"default":"outline",size:"sm",onClick:nr,disabled:Xn==="auto_trash_spam",children:[Xn==="auto_trash_spam"?c.jsx(ft,{size:"sm",className:"mr-1"}):c.jsx(Nc,{className:"w-4 h-4 mr-1"}),t.rules.find(D=>D.name==="Auto-Trash Spam")?.is_enabled?"On":"Off"]})]})]}),c.jsxs("div",{className:"flex justify-between items-center py-3 border-b border-border",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium text-sm",children:"Smart Drafts"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Generate draft replies for important emails"})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{const D=t.rules.find(ee=>ee.name==="Smart Drafts");D&&Ci(D)},title:"Edit Logic",children:c.jsx(Xh,{className:"w-4 h-4 text-muted-foreground"})}),c.jsxs(Q,{variant:t.rules.find(D=>D.name==="Smart Drafts")?.is_enabled?"default":"outline",size:"sm",onClick:xa,disabled:Xn==="smart_drafts",children:[Xn==="smart_drafts"?c.jsx(ft,{size:"sm",className:"mr-1"}):c.jsx(Nc,{className:"w-4 h-4 mr-1"}),t.rules.find(D=>D.name==="Smart Drafts")?.is_enabled?"On":"Off"]})]})]}),c.jsxs("div",{className:"pt-2",children:[c.jsxs("div",{className:"flex items-center justify-between mb-2",children:[c.jsx("h4",{className:"text-sm font-medium",children:"Custom Rules"}),c.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>{hn(null),he(""),Cs(""),ks(""),Ns(["archive"]),As(""),er(""),ya([]),fe(!0)},children:[c.jsx(jo,{className:"w-4 h-4 mr-1"})," Add Rule"]})]}),t.rules.length===0&&c.jsx("p",{className:"text-xs text-muted-foreground text-center py-2 border border-dashed rounded-lg",children:"No custom rules yet"}),t.rules.length>0&&t.rules.filter(D=>D.name!=="Auto-Trash Spam"&&D.name!=="Smart Drafts").map(D=>{const ee=D.actions&&D.actions.length>0?D.actions:D.action?[D.action]:[];return c.jsxs("div",{className:"p-3 bg-secondary/30 rounded-lg mb-2",children:[c.jsxs("div",{className:"flex justify-between items-center mb-1",children:[c.jsxs("div",{children:[c.jsx("span",{className:"text-sm font-medium",children:D.name}),c.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["→ ",ee.join(" + ")]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>Ci(D),title:"Edit Rule",children:c.jsx(Xh,{className:"w-3.5 h-3.5 text-muted-foreground"})}),c.jsxs(Q,{variant:D.is_enabled?"default":"outline",size:"sm",onClick:()=>Pn(D.id),className:"h-7 px-2",children:[c.jsx(Nc,{className:"w-3.5 h-3.5 mr-1"}),D.is_enabled?"On":"Off"]}),c.jsx(Q,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>e.deleteRule(D.id),children:c.jsx(au,{className:"w-3 h-3"})})]})]}),D.instructions&&c.jsxs("p",{className:"text-[10px] text-muted-foreground italic border-t border-border/50 pt-1 mt-1 truncate",children:['"',D.instructions,'"']}),D.attachments&&D.attachments.length>0&&c.jsx("div",{className:"flex gap-1 mt-1",children:D.attachments.map(Ne=>c.jsxs("div",{className:"flex items-center gap-1 text-[9px] bg-blue-500/10 text-blue-400 px-1.5 py-0.5 rounded border border-blue-500/20",children:[c.jsx(x0,{className:"w-2.5 h-2.5"}),Ne.name]},Ne.path))})]},D.id)})]})]})]})]}),c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(fa,{className:"w-5 h-5 text-indigo-500"}),"Model Configuration"]}),c.jsx(ca,{children:"Configure Local LLM or API settings"})]}),c.jsxs(ws,{className:"space-y-4",children:[c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"LLM Provider"}),va?c.jsxs("div",{className:"h-10 border rounded-md flex items-center px-3 bg-muted/20",children:[c.jsx(ft,{size:"sm",className:"mr-2"}),c.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Discovering..."})]}):c.jsxs(c.Fragment,{children:[c.jsxs("select",{className:"w-full h-10 px-3 border rounded-md bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary",value:b.llm_provider||No,onChange:D=>Du(D.target.value),disabled:va,children:[c.jsx("option",{value:No,children:"RealTimeX AI (Default)"}),Ou.filter(D=>D.provider!==No).map(D=>c.jsx("option",{value:D.provider,children:D.name||D.provider},D.provider))]}),cl&&c.jsxs("div",{className:"text-[10px] text-amber-500 mt-1 px-1 bg-amber-50/50 rounded",children:["⚠️ ",cl]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Model Name"}),zt.length>0||va?c.jsxs("select",{className:"w-full h-10 px-3 border rounded-md bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary",value:b.llm_model||"",onChange:D=>S(ee=>({...ee,llm_model:D.target.value})),disabled:va,children:[!b.llm_model&&c.jsx("option",{value:"",children:"Select a model..."}),zt.map(D=>c.jsx("option",{value:D.id,children:D.name||D.id},D.id))]}):c.jsx(Ae,{placeholder:"e.g. gpt-4o-mini",value:b.llm_model||"",onChange:D=>S(ee=>({...ee,llm_model:D.target.value}))})]})]}),c.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(Po,{className:"w-4 h-4"}),"Local Storage Path (.eml)"]}),c.jsx(Ae,{placeholder:"e.g. ./data/emails or ~/.email-automator/emails",value:b.storage_path||"",onChange:D=>S(ee=>({...ee,storage_path:D.target.value}))}),c.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"Directory where raw emails (.eml) are saved. Default: ./data/emails (falls back to ~/.email-automator/emails if restricted)."})]}),c.jsxs("div",{className:"flex justify-between items-center py-3 border-t border-border/50",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium text-sm",children:"Intelligent Rename"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Use slugified-hyphenated filenames (e.g. 20240119-1430-subject-id.eml)"})]}),c.jsxs(Q,{variant:b.intelligent_rename?"default":"outline",size:"sm",onClick:()=>S(D=>({...D,intelligent_rename:!D.intelligent_rename})),children:[c.jsx(Nc,{className:"w-4 h-4 mr-1"}),b.intelligent_rename?"On":"Off"]})]}),c.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(fi,{className:"w-4 h-4"}),"Background Sync Interval (minutes)"]}),c.jsx(Ae,{type:"number",min:1,max:1440,value:b.sync_interval_minutes||5,onChange:D=>S(ee=>({...ee,sync_interval_minutes:parseInt(D.target.value,10)||5}))}),c.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"How often the system checks for new emails in the background."})]}),c.jsxs("div",{className:"flex justify-end mt-4 gap-2",children:[c.jsxs(Q,{variant:"outline",onClick:Mu,disabled:y,children:[y?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(fa,{className:"w-4 h-4 mr-2"}),"Check Connection"]}),c.jsxs(Q,{onClick:Di,disabled:p,children:[p?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Save Configuration"]})]})]})]}),c.jsx("div",{ref:ul,children:c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(Mf,{className:"w-5 h-5 text-orange-500"}),"Provider Credentials (Advanced)"]}),c.jsx(ca,{children:"Bring Your Own Keys (BYOK). Configure your own OAuth credentials here. Leave empty to use system defaults."})]}),c.jsxs(ws,{className:"space-y-6",children:[c.jsxs("div",{className:"space-y-4 border-b pb-4",children:[c.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[c.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"})," Google / Gmail"]}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),c.jsx(Ae,{type:"password",placeholder:"...apps.googleusercontent.com",value:b.google_client_id||"",onChange:D=>S(ee=>({...ee,google_client_id:D.target.value}))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client Secret"}),c.jsx(Ae,{type:"password",placeholder:"GOCSPX-...",value:b.google_client_secret||"",onChange:D=>S(ee=>({...ee,google_client_secret:D.target.value}))})]})]})]}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[c.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-500"})," Microsoft / Outlook"]}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),c.jsx(Ae,{type:"password",value:b.microsoft_client_id||"",onChange:D=>S(ee=>({...ee,microsoft_client_id:D.target.value}))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client Secret (Optional)"}),c.jsx(Ae,{type:"password",value:b.microsoft_client_secret||"",onChange:D=>S(ee=>({...ee,microsoft_client_secret:D.target.value}))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Tenant ID"}),c.jsx(Ae,{placeholder:"common",value:b.microsoft_tenant_id||"",onChange:D=>S(ee=>({...ee,microsoft_tenant_id:D.target.value}))})]})]})]}),c.jsx("div",{className:"flex justify-end mt-4",children:c.jsxs(Q,{onClick:Di,disabled:p,variant:"secondary",children:[p?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Save Credentials"]})})]})]})})]})}const s3="modulepreload",a3=function(t){return"/"+t},Eb={},r3=function(e,a,r){let o=Promise.resolve();if(a&&a.length>0){let g=function(y){return Promise.all(y.map(v=>Promise.resolve(v).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};var d=g;document.getElementsByTagName("link");const f=document.querySelector("meta[property=csp-nonce]"),p=f?.nonce||f?.getAttribute("nonce");o=g(a.map(y=>{if(y=a3(y),y in Eb)return;Eb[y]=!0;const v=y.endsWith(".css"),b=v?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${y}"]${b}`))return;const S=document.createElement("link");if(S.rel=v?"stylesheet":s3,v||(S.as="script"),S.crossOrigin="",S.href=y,p&&S.setAttribute("nonce",p),document.head.appendChild(S),v)return new Promise((T,j)=>{S.addEventListener("load",T),S.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${y}`)))})}))}function u(f){const p=new Event("vite:preloadError",{cancelable:!0});if(p.payload=f,window.dispatchEvent(p),!p.defaultPrevented)throw f}return o.then(f=>{for(const p of f||[])p.status==="rejected"&&u(p.reason);return e().catch(u)})};function i3(){const[t,e]=w.useState("profile"),{state:a,actions:r}=Si();w.useEffect(()=>{r.fetchProfile()},[]);const o=[{id:"profile",label:"Profile",icon:Db},{id:"security",label:"Security",icon:Am},{id:"database",label:"Supabase",icon:Po}];return c.jsxs("div",{className:"max-w-4xl mx-auto space-y-6 animate-in fade-in duration-500",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Account Settings"}),c.jsx("p",{className:"text-muted-foreground",children:"Manage your profile, security, and connection preferences."})]}),c.jsxs("div",{className:"flex flex-col md:flex-row gap-8",children:[c.jsxs("aside",{className:"w-full md:w-64 flex flex-col justify-between",children:[c.jsx("nav",{className:"space-y-1",children:o.map(u=>{const d=u.icon,f=t===u.id;return c.jsxs("button",{onClick:()=>e(u.id),className:`w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${f?"bg-primary text-primary-foreground":"hover:bg-secondary text-muted-foreground"}`,children:[c.jsx(d,{className:"w-4 h-4"}),u.label]},u.id)})}),c.jsxs("div",{className:"mt-auto space-y-1",children:[c.jsxs("button",{onClick:async()=>{await et.auth.signOut(),oe.success("Logged out successfully"),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:[c.jsx(fE,{className:"w-4 h-4"}),"Sign Out"]}),c.jsxs("div",{className:"px-4 py-4 border-t border-border/40 text-center md:text-left",children:[c.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/50 uppercase tracking-widest mb-1",children:"Version"}),c.jsxs("p",{className:"text-xs font-mono text-muted-foreground/70",children:["v","2.11.2"]})]})]})]}),c.jsxs("div",{className:"flex-1 space-y-6",children:[t==="profile"&&c.jsx(o3,{}),t==="security"&&c.jsx(l3,{}),t==="database"&&c.jsx(c3,{})]})]})]})}function o3(){const{state:t,actions:e}=Si(),[a,r]=w.useState(""),[o,u]=w.useState(""),[d,f]=w.useState(!1),[p,g]=w.useState(!1),[y,v]=w.useState(Gn.isEnabled());w.useEffect(()=>{t.profile&&(r(t.profile.first_name||""),u(t.profile.last_name||""))},[t.profile]);const b=()=>{const j=!y;Gn.setEnabled(j),v(j),j?(Gn.playSuccess(),oe.success("Sound effects enabled")):oe.info("Sound effects disabled")},S=async()=>{f(!0);const j=await e.updateProfile({first_name:a,last_name:o});f(!1),j&&oe.success("Profile updated")},T=async j=>{const E=j.target.files?.[0];if(!(!E||!t.user)){g(!0);try{const C=E.name.split(".").pop(),M=`${t.user.id}/avatar.${C}`,{data:k,error:V}=await et.storage.from("avatars").upload(M,E,{upsert:!0});if(V)throw V;const{data:{publicUrl:q}}=et.storage.from("avatars").getPublicUrl(M);await e.updateProfile({avatar_url:q}),oe.success("Avatar updated")}catch(C){console.error("Avatar upload error:",C),oe.error("Failed to upload avatar")}finally{g(!1)}}};return c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsx(bs,{children:"Profile Information"}),c.jsx(ca,{children:"Update your personal details and avatar."})]}),c.jsxs(ws,{className:"space-y-6",children:[c.jsxs("div",{className:"flex flex-col items-center sm:flex-row sm:items-start gap-6",children:[c.jsxs("div",{className:"relative group",children:[c.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?c.jsx("img",{src:t.profile.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):c.jsx(Db,{className:"w-12 h-12 text-muted-foreground"})}),c.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:[c.jsx(NT,{className:"w-6 h-6 text-white"}),c.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:T,disabled:p})]}),p&&c.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 rounded-full",children:c.jsx(ft,{size:"sm"})})]}),c.jsxs("div",{className:"flex-1 space-y-4 w-full",children:[c.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"first-name",children:"First Name"}),c.jsx(Ae,{id:"first-name",value:a,onChange:j=>r(j.target.value),placeholder:"John"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"last-name",children:"Last Name"}),c.jsx(Ae,{id:"last-name",value:o,onChange:j=>u(j.target.value),placeholder:"Doe"})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"email",children:"Email Address"}),c.jsx(Ae,{id:"email",value:t.profile?.email||"",disabled:!0,className:"bg-secondary/50"}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Email cannot be changed directly."})]})]})]}),c.jsxs("div",{className:"pt-6 border-t flex items-center justify-between",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("label",{className:"text-sm font-medium",children:"Sound & Haptics"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Audio feedback when processing emails and completing tasks."})]}),c.jsxs(Q,{variant:y?"default":"outline",size:"sm",onClick:b,className:"gap-2",children:[y?c.jsx(XE,{className:"w-4 h-4"}):c.jsx(WE,{className:"w-4 h-4"}),y?"Enabled":"Disabled"]})]}),c.jsx("div",{className:"flex justify-end pt-4 border-t",children:c.jsxs(Q,{onClick:S,disabled:d,children:[d?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(AE,{className:"w-4 h-4 mr-2"}),"Save Changes"]})})]})]})}function l3(){const[t,e]=w.useState(""),[a,r]=w.useState(""),[o,u]=w.useState(!1),d=async()=>{if(!t){oe.error("Please enter a new password");return}if(t!==a){oe.error("Passwords do not match");return}if(t.length<6){oe.error("Password must be at least 6 characters");return}u(!0);try{const{api:f}=await r3(async()=>{const{api:g}=await Promise.resolve().then(()=>LC);return{api:g}},void 0),p=await f.changePassword(t);p.success?(oe.success("Password changed successfully"),e(""),r("")):oe.error(p.error?.message||"Failed to change password")}catch{oe.error("An error occurred")}finally{u(!1)}};return c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsx(bs,{children:"Security"}),c.jsx(ca,{children:"Manage your password and account security."})]}),c.jsxs(ws,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"new-password",children:"New Password"}),c.jsx(Ae,{id:"new-password",type:"password",value:t,onChange:f=>e(f.target.value),placeholder:"••••••••"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"confirm-password",children:"Confirm New Password"}),c.jsx(Ae,{id:"confirm-password",type:"password",value:a,onChange:f=>r(f.target.value),placeholder:"••••••••"})]}),c.jsx("div",{className:"flex justify-end pt-4 border-t",children:c.jsxs(Q,{onClick:d,disabled:o,children:[o?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Nm,{className:"w-4 h-4 mr-2"}),"Update Password"]})})]})]})}function c3(){const[t,e]=w.useState(!1),[a,r]=w.useState(null),o=wi(),u=MC();w.useEffect(()=>{o&&fp(et).then(r)},[]);const d=()=>{confirm("Are you sure you want to disconnect from this Supabase project? This will log you out and clear local configuration.")&&(OC(),window.location.reload())};return c.jsxs(c.Fragment,{children:[c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(Po,{className:"w-5 h-5 text-primary"}),"Supabase Connection"]}),c.jsx(ca,{children:"Manage your database configuration (BYOK - Bring Your Own Keys)."})]}),c.jsx(ws,{className:"space-y-6",children:o?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-xl bg-emerald-500/5 border-emerald-500/20",children:[c.jsx(Qc,{className:"w-6 h-6 text-emerald-500 mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("p",{className:"font-semibold text-emerald-700 dark:text-emerald-400",children:"Connected"}),a?.latestMigrationTimestamp&&c.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 ",a.latestMigrationTimestamp]})]}),c.jsx("p",{className:"text-sm font-mono break-all opacity-80",children:o.url})]})]}),u==="env"&&c.jsxs(Wo,{className:"bg-amber-500/5 border-amber-500/20",children:[c.jsx(nu,{className:"h-4 w-4 text-amber-500"}),c.jsx(Zo,{className:"text-amber-700 dark:text-amber-400 text-xs",children:"Configuration is loaded from environment variables. Use the UI to override them."})]}),c.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[c.jsxs(Q,{variant:"outline",onClick:()=>e(!0),className:"w-full",children:[c.jsx(nu,{className:"w-4 h-4 mr-2"}),"Change Connection"]}),u==="ui"&&c.jsxs(Q,{variant:"outline",onClick:d,className:"w-full text-destructive hover:bg-destructive/10",children:[c.jsx(au,{className:"w-4 h-4 mr-2"}),"Clear Config"]})]}),c.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[c.jsx(Ht,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Anon Public Key"}),c.jsxs("div",{className:"p-2 bg-secondary/50 rounded-lg font-mono text-xs break-all",children:[o.anonKey.substring(0,20),"...",o.anonKey.substring(o.anonKey.length-10)]})]})]}):c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center space-y-4",children:[c.jsx(qT,{className:"w-12 h-12 text-destructive opacity-20"}),c.jsxs("div",{children:[c.jsx("p",{className:"font-medium",children:"No Connection Detected"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure a Supabase project to get started."})]}),c.jsxs(Q,{onClick:()=>e(!0),children:[c.jsx(Po,{className:"w-4 h-4 mr-2"}),"Setup Supabase"]})]})})]}),c.jsx(dS,{open:t,onComplete:()=>e(!1),canClose:!0})]})}function u3({length:t=6,value:e,onChange:a,onComplete:r,disabled:o=!1,error:u=!1}){const d=w.useRef([]),[f,p]=w.useState(null),g=(b,S)=>{const T=S.replace(/[^0-9]/g,"");if(T.length===0){const C=e.split("");C[b]=" ",e.split("");let M=e.split("");b<M.length&&M.splice(b,1);const k=M.join("");a(k),b>0&&d.current[b-1]?.focus();return}e.split("");const j=[...e];j[b]=T[0],a(j.join("")),b<t-1&&d.current[b+1]?.focus();const E=j.join("");E.length===t&&r&&r(E)},y=(b,S)=>{S.key==="Backspace"&&!e[b]&&b>0||S.key==="ArrowLeft"&&b>0?d.current[b-1]?.focus():S.key==="ArrowRight"&&b<t-1&&d.current[b+1]?.focus()},v=b=>{b.preventDefault();const T=b.clipboardData.getData("text/plain").replace(/[^0-9]/g,"").slice(0,t);a(T);const j=Math.min(T.length,t-1);d.current[j]?.focus(),T.length===t&&r&&r(T)};return c.jsx("div",{className:"flex gap-2 justify-center",children:Array.from({length:t}).map((b,S)=>c.jsx(Ae,{ref:T=>{d.current[S]=T},type:"text",inputMode:"numeric",maxLength:1,value:e[S]||"",onChange:T=>g(S,T.target.value),onKeyDown:T=>y(S,T),onPaste:v,onFocus:()=>p(S),onBlur:()=>p(null),disabled:o,className:Te("w-10 h-10 sm:w-12 sm:h-12 text-center text-lg font-semibold px-0",u&&"border-destructive focus-visible:ring-destructive",f===S&&"ring-2 ring-ring"),"aria-label":`Digit ${S+1}`},S))})}function d3({onSuccess:t,onConfigure:e,isInitialized:a}){const[r,o]=w.useState(""),[u,d]=w.useState(""),[f,p]=w.useState(""),[g,y]=w.useState(""),[v,b]=w.useState(!1),[S,T]=w.useState(a===void 0),[j,E]=w.useState(a??!1),[C,M]=w.useState(""),[k,V]=w.useState(!1),[q,G]=w.useState("password"),[$,B]=w.useState("email"),[W,me]=w.useState(""),[ue,pe]=w.useState(!1);w.useEffect(()=>{a===void 0?ze():pe(!a)},[a]);const ze=async()=>{try{const{data:A,error:H}=await et.from("init_state").select("is_initialized");if(H){if(H.code==="42P01"){console.info("[Login] init_state relation missing - fresh database detected."),E(!1),pe(!0);return}console.warn("[Login] Init check error:",H),E(!1),pe(!0),M(H.message);return}const F=A&&A.length>0&&A[0].is_initialized>0;E(F),pe(!F)}catch(A){console.warn("[Login] Init check exception:",A),E(!1),pe(!0),M(A.message||"Connection failed")}finally{T(!1)}},Fe=async A=>{A.preventDefault(),b(!0),M("");try{if(j){if(q==="password"){const{error:H}=await et.auth.signInWithPassword({email:r,password:u});if(H)throw H;oe.success("Logged in successfully"),t?.()}else if($==="email"){const{error:H}=await et.auth.signInWithOtp({email:r,options:{shouldCreateUser:!1}});if(H)throw H;B("verify"),oe.success("Validation code sent to your email")}}else{const{data:H,error:F}=await et.functions.invoke("setup",{body:{email:r,password:u,first_name:f,last_name:g}});if(F||!H){if(F?.message?.includes("First user already exists")){oe.info("System already initialized. Please log in."),E(!0);return}throw new Error(F?.message||"Failed to create admin account")}oe.success("Admin account created! Signing you in...");const{error:xe}=await et.auth.signInWithPassword({email:r,password:u});if(xe)throw xe;E(!0),t?.()}}catch(H){M(H?.message||"Authentication failed"),console.error("[Login] Error:",H)}finally{b(!1)}},Re=async()=>{b(!0),M("");try{const{data:A,error:H}=await et.auth.verifyOtp({email:r,token:W,type:"magiclink"});if(H)throw H;if(!A.session)throw new Error("Failed to create session");oe.success("Logged in successfully"),t?.()}catch(A){M(A?.message||"Invalid code")}finally{b(!1)}};return S?c.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:c.jsxs("div",{className:"flex flex-col items-center gap-4",children:[c.jsx(Pt,{className:"w-10 h-10 animate-spin text-primary"}),c.jsx("p",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground",children:"Initializing Engine..."})]})}):c.jsxs("div",{className:"min-h-screen bg-background flex items-center justify-center p-8 relative overflow-hidden",children:[c.jsxs("div",{className:"absolute top-6 right-6 flex items-center gap-4 z-50",children:[e&&c.jsxs(Q,{variant:"ghost",size:"sm",onClick:e,className:"text-xs font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all",children:[c.jsx(nu,{className:"w-3.5 h-3.5 mr-2"}),"Configure"]}),c.jsx(Zb,{})]}),c.jsxs(vs.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full max-w-md relative z-10",children:[c.jsxs("div",{className:"glass p-10 space-y-8 relative overflow-hidden",children:[c.jsxs("div",{className:"text-center space-y-3",children:[c.jsx("div",{className:"mx-auto w-16 h-16 bg-primary rounded-2xl flex items-center justify-center mb-6",children:c.jsx(mp,{className:"w-10 h-10 text-primary-foreground"})}),c.jsx("h2",{className:"text-3xl font-black italic tracking-tighter uppercase text-foreground",children:ue?"Initialize Automator":"Secure Login"}),c.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-[0.2em] uppercase",children:ue?"Create your primary administrator account":q==="otp"?"Magic link authentication":"Personal Access Key Required"})]}),c.jsxs("form",{onSubmit:Fe,className:"space-y-4",children:[c.jsxs(K1,{mode:"wait",children:[ue&&c.jsxs(vs.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"First Name"}),c.jsx(Ae,{value:f,onChange:A=>p(A.target.value),required:ue,placeholder:"John",className:"bg-background"})]}),c.jsxs("div",{className:"space-y-1",children:[c.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Last Name"}),c.jsx(Ae,{value:g,onChange:A=>y(A.target.value),required:ue,placeholder:"Doe",className:"bg-background"})]})]},"signup-fields"),q==="password"||$==="email"?c.jsxs(vs.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[c.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Email Coordinates"}),c.jsxs("div",{className:"relative",children:[c.jsx(tu,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),c.jsx(Ae,{type:"email",placeholder:"admin@automator.ai",value:r,onChange:A=>o(A.target.value),required:!0,className:"pl-10 bg-background",autoComplete:"email",disabled:$==="verify"})]})]},"email-field"):null,q==="password"&&c.jsxs(vs.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[c.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Access Password"}),c.jsxs("div",{className:"relative",children:[c.jsx(v0,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),c.jsx(Ae,{type:k?"text":"password",placeholder:"••••••••",value:u,onChange:A=>d(A.target.value),required:!0,minLength:6,className:"pl-10 pr-10 bg-background",autoComplete:ue?"new-password":"current-password"}),c.jsx("button",{type:"button",onClick:()=>V(!k),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground/30 hover:text-primary transition-colors",children:k?c.jsx(JT,{size:16}):c.jsx(Rb,{size:16})})]})]},"password-field"),q==="otp"&&$==="verify"&&c.jsxs(vs.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"space-y-6 py-4",children:[c.jsx("div",{className:"flex justify-center",children:c.jsx(u3,{value:W,onChange:me,length:6,onComplete:()=>{}})}),c.jsx(Q,{type:"button",variant:"link",className:"w-full text-[10px] font-bold uppercase tracking-widest text-primary/60",onClick:()=>B("email"),children:"Change Coordinates"}),c.jsxs(Q,{type:"button",onClick:Re,disabled:v||W.length!==6,className:"w-full h-12 shadow-md",children:[v?c.jsx(Pt,{className:"w-5 h-5 animate-spin mr-2"}):c.jsx(Am,{size:18,className:"mr-2"}),"Verify Access"]})]},"otp-field")]}),C&&c.jsxs(vs.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:[c.jsx(js,{size:14,className:"mt-0.5 shrink-0"}),c.jsx("p",{children:C})]}),q!=="otp"||$==="email"?c.jsx(Q,{type:"submit",disabled:v||!r||q==="password"&&!u,className:"w-full h-12 shadow-md mt-4",children:v?c.jsx(Pt,{className:"w-5 h-5 animate-spin"}):c.jsxs(c.Fragment,{children:[ue?c.jsx(KE,{className:"w-5 h-5 mr-2"}):q==="otp"?c.jsx(tu,{className:"w-5 h-5 mr-2"}):c.jsx(dE,{className:"w-5 h-5 mr-2"}),ue?"Initialize Master":q==="otp"?"Send Magic Link":"Open Dashboard"]})}):null]}),c.jsxs("div",{className:"space-y-4 pt-4 border-t border-border/10",children:[!ue&&c.jsx("div",{className:"flex flex-col gap-2",children:q==="password"?c.jsxs("button",{type:"button",onClick:()=>{G("otp"),B("email"),M("")},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:[c.jsx(v0,{size:14})," Magic Link Login"]}):c.jsxs("button",{type:"button",onClick:()=>{G("password"),M("")},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:[c.jsx(Tm,{size:14})," Password Access"]})}),c.jsxs("p",{className:"text-center text-[10px] text-muted-foreground font-bold uppercase tracking-wider",children:[ue?"Already have an account?":"Need a new account?"," "," ",c.jsx("button",{onClick:()=>{pe(!ue),G("password"),M("")},className:"text-primary hover:underline ml-1",children:ue?"Login Instead":"Create Account"})]})]})]}),c.jsx("div",{className:"mt-8 text-center",children:c.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/30 uppercase tracking-[0.4em]",children:"Powered by RealTimeX Intelligence"})})]})]})}function h3({status:t,onDismiss:e,onLearnMore:a}){const[r,o]=w.useState(!0);if(!r)return null;const u=()=>{P5(),o(!1),e?.()},d=()=>{a?a():(navigator.clipboard.writeText("npx email-automator migrate"),oe.success("Command copied to clipboard"))};return c.jsx("div",{className:"fixed right-4 top-16 z-50 max-w-sm animate-in slide-in-from-top-5",children:c.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:c.jsxs("div",{className:"flex items-start gap-3",children:[c.jsx(pi,{className:"h-5 w-5 flex-shrink-0 text-yellow-600 dark:text-yellow-500 mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-2",children:[c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("p",{className:"text-sm font-medium text-yellow-900 dark:text-yellow-100",children:"Database Update Required"}),c.jsxs(Q,{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:u,children:[c.jsx(yi,{className:"h-3 w-3"}),c.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),c.jsxs("p",{className:"text-xs text-yellow-800 dark:text-yellow-200",children:["Your app version (",t.appVersion,") requires a database schema update."]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Q,{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:d,children:"Update Now"}),c.jsx(Q,{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:u,children:"Remind Later"})]})]})]})})})}function f3({open:t,onOpenChange:e,status:a}){const r=wi(),[o,u]=w.useState(!1),[d,f]=w.useState([]),[p,g]=w.useState(""),y=w.useRef(null),v=w.useMemo(()=>{const S=r?.url;if(!S)return"";try{return new URL(S).hostname.split(".")[0]||""}catch{return""}},[r?.url]);w.useEffect(()=>{y.current&&y.current.scrollIntoView({behavior:"smooth"})},[d]);const b=async()=>{if(!v){oe.error("Missing Project ID");return}if(!p){oe.error("Provide a Supabase Personal Access Token.");return}u(!0),f(["Initializing migration..."]);try{const S=async C=>{const M=new TextDecoder;let k="",V=null;const q=G=>{const $=G.trim();if(!(!$||!$.startsWith("data: ")))try{const B=$.substring(6),W=JSON.parse(B);W.type==="done"?(W.data==="success"||W.data==="failed")&&(V=W.data==="success"?"success":"failure"):W.data&&f(me=>[...me,W.data])}catch(B){console.error("Failed to parse SSE line:",$,B)}};for(;;){const{done:G,value:$}=await C.read();if(G)break;k+=M.decode($,{stream:!0});const B=k.split(`
|
|
105
|
-
`);k=B.pop()||"",B.forEach(q)}return k+=M.decode(),k&&q(k),V};f(C=>[...C,"","📦 Database Migration & Edge Functions Deployment"]);const T=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:v,accessToken:p})});if(!T.ok)throw new Error(`Migration failed: ${T.status} ${T.statusText}`);const j=T.body?.getReader();if(!j)throw new Error("No migration response stream received.");if(await S(j)!=="success")throw new Error("Migration did not complete successfully");f(C=>[...C,"","═".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(S){console.error(S),f(T=>[...T,"",`❌ Error: ${S instanceof Error?S.message:String(S)}`]),oe.error("Setup failed. Check logs for details.")}finally{u(!1)}};return c.jsx(li,{open:t,onOpenChange:S=>!o&&e(S),children:c.jsxs(ci,{className:"max-h-[90vh] sm:max-w-5xl overflow-y-auto",children:[c.jsxs(ui,{children:[c.jsxs(di,{className:"flex items-center gap-2 text-xl",children:[c.jsx(pi,{className:"h-6 w-6 text-red-700 dark:text-red-600"}),"Database Setup Required"]}),c.jsxs(hi,{children:["Your application version (",a.appVersion,") requires database migration and Edge Functions deployment to function correctly."]})]}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs(Wo,{children:[c.jsx(mi,{className:"h-4 w-4"}),c.jsxs(Zo,{children:[c.jsx("strong",{children:"Why is this needed?"}),c.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[c.jsxs("li",{children:["Updates your database schema to match version ",a.appVersion]}),c.jsx("li",{children:"Deploys Edge Functions (API endpoints) to your Supabase project"}),c.jsx("li",{children:"Enables new features and performance improvements"}),c.jsx("li",{children:"Your existing data will be preserved (safe migration)"})]})]})]}),c.jsxs("div",{className:"space-y-4 py-2",children:[c.jsxs("div",{className:"rounded-lg border bg-card text-card-foreground shadow-sm p-6",children:[c.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Automated Setup"}),c.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."}),c.jsxs("div",{className:"grid gap-4",children:[c.jsxs("div",{className:"grid gap-2",children:[c.jsx(Ht,{htmlFor:"project-id",children:"Supabase Project ID"}),c.jsx(Ae,{id:"project-id",value:v,disabled:!0,readOnly:!0,className:"bg-muted"})]}),c.jsxs("div",{className:"grid gap-2",children:[c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx(Ht,{htmlFor:"access-token",children:"Access Token"}),c.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 ",c.jsx(eu,{className:"h-3 w-3"})]})]}),c.jsx(Ae,{id:"access-token",type:"password",placeholder:"sbp_...",value:p,onChange:S=>g(S.target.value),disabled:o}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"This token is used only for this migration and is not stored."})]}),c.jsx(Q,{onClick:b,disabled:o||!p,className:"w-full",children:o?c.jsxs(c.Fragment,{children:[c.jsx(Pt,{className:"mr-2 h-4 w-4 animate-spin"}),"Running Setup..."]}):c.jsxs(c.Fragment,{children:[c.jsx(su,{className:"mr-2 h-4 w-4"}),"Start Setup"]})})]})]}),c.jsxs("div",{className:"rounded-lg border bg-black text-white font-mono text-xs p-4 h-64 overflow-y-auto",children:[d.length===0?c.jsx("div",{className:"text-gray-500 italic",children:"Waiting to start..."}):d.map((S,T)=>c.jsx("div",{className:"mb-1 whitespace-pre-wrap",children:S},T)),c.jsx("div",{ref:y})]})]}),c.jsxs(Wo,{className:"border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/20",children:[c.jsx(pi,{className:"h-4 w-4 text-red-700 dark:text-red-600"}),c.jsxs(Zo,{children:[c.jsx("strong",{children:"Troubleshooting"}),c.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[c.jsxs("li",{children:["Ensure your Access Token has ",c.jsx("code",{children:"read"})," and ",c.jsx("code",{children:"write"})," permissions."]}),c.jsx("li",{children:"Verify that your Supabase Project ID is correct and active."})]})]})]})]}),c.jsx(Zr,{children:c.jsx(Q,{type:"button",variant:"outline",onClick:()=>e(!1),disabled:o,children:"Close"})})]})})}function m3(){const[t,e]=w.useState([]),{isExpanded:a,setIsExpanded:r}=ww(),[o,u]=w.useState({});w.useEffect(()=>{d();const y=et.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},v=>{const b=v.new;b.event_type==="error"&&u(S=>({...S,[b.id]:!0})),e(S=>{const T=[b,...S];return b.details?.is_completion&&a&&setTimeout(()=>{r(!1)},3e3),T.length>100?T.slice(0,100):T})}).subscribe();return()=>{et.removeChannel(y)}},[a,r]);const d=async()=>{const{data:y}=await et.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(50);y&&e(y)},f=y=>{u(v=>({...v,[y]:!v[y]}))},p=y=>{if(y.details?.is_completion)return c.jsx(Qc,{className:"w-3 h-3 text-emerald-500"});switch(y.event_type){case"analysis":return c.jsx(Lo,{className:"w-3 h-3 text-purple-500"});case"action":return c.jsx(Vo,{className:"w-3 h-3 text-emerald-500"});case"error":return c.jsx(pi,{className:"w-3 h-3 text-red-500"});default:return c.jsx(mi,{className:"w-3 h-3 text-blue-500"})}},g=y=>new Date(y).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});return a?c.jsxs(Vt,{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:[c.jsxs(xs,{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:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(su,{className:"w-4 h-4 text-primary"}),c.jsx(bs,{className:"text-sm font-mono font-bold",children:"Agent Terminal"}),c.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-green-600 dark:text-green-400 bg-green-500/10 px-2 py-0.5 rounded-full border border-green-500/20 font-bold",children:[c.jsx(fT,{className:"w-3 h-3"}),"LIVE"]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 text-[10px] font-mono hover:bg-secondary",onClick:()=>e([]),children:"Clear"}),c.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-secondary",onClick:()=>r(!1),children:c.jsx(gE,{className:"w-4 h-4"})})]})]}),c.jsxs(ws,{className:"flex-1 overflow-y-auto p-4 font-mono text-xs space-y-6 custom-scrollbar",children:[t.length===0&&c.jsx("div",{className:"text-center text-muted-foreground py-20 italic",children:"Waiting for agent activity..."}),t.map((y,v)=>c.jsxs("div",{className:"relative pl-8 animate-in fade-in slide-in-from-top-2 duration-300",children:[v!==t.length-1&&c.jsx("div",{className:"absolute left-[13px] top-7 bottom-[-24px] w-[1px] bg-border"}),c.jsx("div",{className:Te("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",y.event_type==="error"&&"border-red-500/50 bg-red-500/5",y.event_type==="analysis"&&"border-purple-500/50 bg-purple-500/5",y.event_type==="action"&&"border-emerald-500/50 bg-emerald-500/5",y.details?.is_completion&&"border-emerald-500/50 bg-emerald-500/5"),children:p(y)}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsxs("div",{className:"flex items-center justify-between group",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:Te("font-bold uppercase tracking-tight text-[10px]",y.event_type==="info"&&"text-muted-foreground",y.event_type==="analysis"&&"text-purple-600 dark:text-purple-400",y.event_type==="action"&&"text-emerald-600 dark:text-emerald-400",y.event_type==="error"&&"text-red-600 dark:text-red-400"),children:y.agent_state}),c.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:g(y.created_at)})]}),(y.details?.system_prompt||y.details?._raw_response||y.details?.raw_response)&&c.jsxs(Q,{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:()=>f(y.id),children:[o[y.id]?c.jsx(UT,{className:"w-3 h-3 mr-1"}):c.jsx(RT,{className:"w-3 h-3 mr-1"}),"Details"]})]}),y.event_type==="analysis"&&y.details?c.jsxs("div",{className:"bg-purple-500/5 border border-purple-500/10 rounded-lg p-3 space-y-2",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx("span",{className:Te("px-1.5 py-0.5 rounded text-[9px] font-bold border",y.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:y.details.is_useless?"USELESS":"RELEVANT"}),c.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:y.details.category})]}),c.jsxs("p",{className:"text-foreground/90 italic leading-relaxed",children:['"',y.details.summary,'"']}),y.details.suggested_actions&&y.details.suggested_actions.length>0&&c.jsx("div",{className:"pt-1 flex items-center gap-2 flex-wrap",children:y.details.suggested_actions.map(b=>c.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:[c.jsx(Vo,{className:"w-2.5 h-2.5"}),b]},b))}),y.details.usage&&c.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:c.jsxs("span",{children:["Tokens: ",y.details.usage.prompt_tokens," (in) + ",y.details.usage.completion_tokens," (out) = ",c.jsx("span",{className:"text-purple-500 font-bold",children:y.details.usage.total_tokens})]})})]}):y.event_type==="action"&&y.details?c.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/10 rounded-lg p-3",children:[c.jsx("p",{className:"text-emerald-600 dark:text-emerald-400 font-bold mb-1 uppercase text-[9px] tracking-widest",children:"Execution Complete"}),c.jsxs("p",{className:"text-foreground font-medium",children:[y.details.action==="delete"&&"Moved to Trash",y.details.action==="archive"&&"Archived Email",y.details.action==="draft"&&"Drafted Reply",y.details.action==="read"&&"Marked as Read",y.details.action==="star"&&"Starred Email",!["delete","archive","draft","read","star"].includes(y.details.action)&&y.details.action]}),y.details.reason&&c.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 flex items-center gap-1",children:[c.jsx(mi,{className:"w-3 h-3"}),y.details.reason]})]}):y.event_type==="error"&&y.details?c.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 y.details.error=="object"?y.details.error.message||JSON.stringify(y.details.error):y.details.error}):y.details?.is_completion?c.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-lg p-3 space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 dark:text-emerald-400 font-bold uppercase text-[9px] tracking-[0.2em]",children:[c.jsx(Qc,{className:"w-3.5 h-3.5"}),"Batch Sync Finished"]}),c.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-1",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Processed"}),c.jsx("p",{className:"text-sm font-bold",children:y.details.total_processed||0})]}),c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Actions"}),c.jsx("p",{className:"text-sm font-bold text-emerald-500",children:(y.details.deleted||0)+(y.details.drafted||0)})]})]}),y.details.errors>0&&c.jsxs("p",{className:"text-[10px] text-red-500 font-bold pt-1 border-t border-emerald-500/10",children:["⚠️ ",y.details.errors," items failed to process."]})]}):c.jsx("p",{className:"text-muted-foreground leading-relaxed",children:y.details?.message||JSON.stringify(y.details)}),o[y.id]&&c.jsxs("div",{className:"mt-2 space-y-3 animate-in fade-in zoom-in-95 duration-200",children:[y.details?.system_prompt&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[c.jsx(la,{className:"w-3 h-3"})," System Prompt"]}),c.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:c.jsx("pre",{className:"whitespace-pre-wrap break-words text-[10px] leading-normal text-muted-foreground select-all",children:y.details.system_prompt})})]}),y.details?.content_preview&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[c.jsx(la,{className:"w-3 h-3"})," Input Content (Cleaned)"]}),c.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border",children:c.jsx("p",{className:"whitespace-pre-wrap break-words text-[10px] text-muted-foreground",children:y.details.content_preview})})]}),y.details?._raw_response&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[c.jsx(la,{className:"w-3 h-3"})," Raw LLM JSON Output"]}),c.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:c.jsx("pre",{className:"text-[10px] text-muted-foreground select-all",children:JSON.stringify(JSON.parse(y.details._raw_response),null,2)})})]}),y.details?.raw_response&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[c.jsx(la,{className:"w-3 h-3"})," Raw Response (from Error)"]}),c.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:c.jsx("pre",{className:"text-[10px] text-muted-foreground select-all whitespace-pre-wrap",children:typeof y.details.raw_response=="object"?JSON.stringify(y.details.raw_response,null,2):y.details.raw_response})})]})]})]})]},y.id))]})]}):c.jsx("div",{className:"fixed bottom-4 right-4 z-50",children:c.jsxs(Q,{onClick:()=>r(!0),className:"shadow-lg bg-primary text-primary-foreground hover:opacity-90 border border-border",children:[c.jsx(su,{className:"w-4 h-4 mr-2"}),"Live Activity",t.length>0&&c.jsxs("span",{className:"ml-2 flex h-2 w-2 relative",children:[c.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),c.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-green-500"})]})]})})}function p3(){const{state:t,isSubscribed:e,actions:a}=Si(),[r,o]=w.useState(null),[u,d]=w.useState(!0),[f,p]=w.useState(!1),[g,y]=w.useState(!0),[v,b]=w.useState("dashboard"),[S,T]=w.useState(!1),[j,E]=w.useState(null),[C,M]=w.useState(!1),[k,V]=w.useState(!1),[q,G]=w.useState(!1);if(w.useEffect(()=>{const me=new URLSearchParams(window.location.search).get("code");me&&!S&&(async()=>{T(!0);try{const pe=await Ue.connectGmail(me);if(pe.data?.success)oe.success("Gmail connected successfully!"),window.opener?setTimeout(()=>window.close(),1500):(window.history.replaceState({},"",window.location.pathname),a.fetchAccounts());else{const ze=typeof pe.error=="string"?pe.error:pe.error?.message;oe.error(ze||"Failed to connect Gmail")}}catch{oe.error("Connection failed")}finally{T(!1)}})()},[]),S)return c.jsx(uu,{text:"Connecting account..."});w.useEffect(()=>{(async()=>{if(!wi()){p(!0),d(!1);return}try{const{data:ze,error:Fe}=await et.from("init_state").select("is_initialized").single();Fe?(console.warn("[App] Init check error (might be fresh DB):",Fe),Fe.code==="42P01"&&y(!1)):y(ze.is_initialized>0);const{data:{session:Re}}=await et.auth.getSession();if(o(Re?.user??null),Re?.user){const A=await fp(et);E(A.needsMigration?A:null),A.needsMigration&&!L5()&&M(!0)}}catch(ze){console.error("[App] Status check failed:",ze),ze instanceof Error&&ze.message.includes("Invalid API key")&&p(!0)}finally{d(!1)}})();const{data:{subscription:me}}=et.auth.onAuthStateChange((pe,ze)=>{o(ze?.user??null),ze||(E(null),M(!1))}),ue=()=>{if(Gn.isEnabled()){const pe=new(window.AudioContext||window.webkitAudioContext);pe.state==="suspended"&&pe.resume()}window.removeEventListener("click",ue),window.removeEventListener("keydown",ue)};return window.addEventListener("click",ue),window.addEventListener("keydown",ue),()=>{me.unsubscribe(),window.removeEventListener("click",ue),window.removeEventListener("keydown",ue)}},[]),w.useEffect(()=>{r&&(a.fetchAccounts(),a.fetchRules(),a.fetchSettings(),a.fetchProfile())},[r]),w.useEffect(()=>{const W=async()=>{try{await Ue.healthCheck()}catch{console.warn("[App] Keep-alive ping failed")}};W();const me=setInterval(W,3e4);return()=>clearInterval(me)},[]);const $=()=>{V(!0),M(!1)},B={migrationStatus:j,showMigrationBanner:C,showMigrationModal:k,openMigrationModal:$,suppressMigrationBanner:q,setSuppressMigrationBanner:G};return u?c.jsx(uu,{text:"Loading your workspace..."}):f?c.jsx(dS,{onComplete:()=>p(!1)}):r?c.jsx(YC,{value:B,children:c.jsxs("div",{className:"min-h-screen bg-background font-sans text-foreground transition-colors duration-300",children:[c.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:c.jsxs("div",{className:"max-w-7xl mx-auto flex h-16 items-center justify-between px-4 sm:px-8",children:[c.jsxs("div",{className:"flex items-center gap-4",children:[c.jsxs("button",{onClick:()=>b("dashboard"),className:"text-xl font-bold flex items-center gap-2 hover:opacity-80 transition-opacity",children:[c.jsx(mp,{className:"w-8 h-8"}),c.jsx("span",{className:"hidden sm:inline",children:"Email Automator"}),c.jsx("span",{className:"sm:hidden",children:"Email AI"})]}),c.jsxs("div",{className:Te("flex items-center gap-1.5 px-2 h-6 rounded-full text-[10px] font-bold border transition-colors",e?"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:[c.jsxs("div",{className:"relative flex items-center justify-center",children:[e&&c.jsx("span",{className:"absolute inline-flex h-3 w-3 rounded-full bg-emerald-500/40 animate-ping"}),c.jsx("div",{className:Te("relative w-2 h-2 rounded-full",e?"bg-emerald-500":"bg-yellow-500")})]}),c.jsx("span",{className:"hidden xs:inline leading-none",children:e?"LIVE":"OFFLINE"})]})]}),c.jsxs("div",{className:"flex gap-4 items-center",children:[c.jsxs("nav",{className:"flex items-center gap-1 bg-secondary/50 p-1 rounded-lg",children:[c.jsxs(Q,{variant:v==="dashboard"?"secondary":"ghost",size:"sm",onClick:()=>b("dashboard"),className:"gap-2",children:[c.jsx(lE,{className:"w-4 h-4"}),c.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),c.jsxs(Q,{variant:v==="analytics"?"secondary":"ghost",size:"sm",onClick:()=>b("analytics"),className:"gap-2",children:[c.jsx(kb,{className:"w-4 h-4"}),c.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),c.jsxs(Q,{variant:v==="config"?"secondary":"ghost",size:"sm",onClick:()=>b("config"),className:"gap-2",children:[c.jsx(nu,{className:"w-4 h-4"}),c.jsx("span",{className:"hidden sm:inline",children:"Configuration"})]})]}),c.jsx("div",{className:"h-6 w-px bg-border/50 mx-2 hidden sm:block"}),c.jsx(Zb,{}),c.jsx(Q,{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:"Account Settings",children:t.profile?.avatar_url?c.jsx("img",{src:t.profile.avatar_url,alt:"Profile",className:"w-full h-full object-cover"}):c.jsx(IT,{className:"w-5 h-5"})})]})]})}),c.jsxs("main",{className:"max-w-7xl mx-auto p-4 sm:p-8 mt-4 mb-12",children:[v==="dashboard"&&c.jsx(ZM,{}),v==="config"&&c.jsx(n3,{}),v==="analytics"&&c.jsx(y3,{}),v==="account"&&c.jsx(i3,{})]}),c.jsx("footer",{className:"max-w-7xl mx-auto px-4 sm:px-8 pb-8 text-center sm:text-left",children:c.jsxs("p",{className:"text-[10px] font-medium text-muted-foreground/40 uppercase tracking-[0.2em]",children:["Email Automator ",c.jsx("span",{className:"mx-1",children:"•"})," v","2.11.2"]})}),t.error&&c.jsx("div",{className:"fixed bottom-20 left-4 right-4 sm:left-auto sm:right-4 sm:max-w-sm z-50",children:c.jsx("div",{className:"bg-destructive/10 border border-destructive/20 text-destructive p-4 rounded-lg",children:c.jsx("p",{className:"text-sm",children:t.error})})}),j&&C&&!q&&c.jsx(h3,{status:j,onDismiss:()=>M(!1),onLearnMore:$}),j&&c.jsx(f3,{open:k,onOpenChange:V,status:j}),c.jsx(m3,{})]})}):c.jsx(d3,{onSuccess:()=>a.fetchProfile(),onConfigure:()=>p(!0),isInitialized:g})}function g3({runId:t,accountEmail:e,isOpen:a,onOpenChange:r}){const[o,u]=w.useState([]),[d,f]=w.useState(!1);w.useEffect(()=>{a&&t&&p()},[a,t]);const p=async()=>{if(t){f(!0);try{const y=await Ue.getRunEvents(t);y.data&&u(y.data.events)}catch(y){console.error("Failed to fetch run trace:",y)}finally{f(!1)}}},g=y=>{switch(y){case"analysis":return c.jsx(Lo,{className:"w-4 h-4 text-purple-500"});case"action":return c.jsx(Vo,{className:"w-4 h-4 text-emerald-500"});case"error":return c.jsx(js,{className:"w-4 h-4 text-red-500"});default:return c.jsx(mi,{className:"w-4 h-4 text-blue-500"})}};return c.jsx(li,{open:a,onOpenChange:r,children:c.jsxs(ci,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[c.jsxs(ui,{className:"p-6 border-b",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(xu,{className:"w-5 h-5 text-primary"}),c.jsx(di,{children:"Sync Run Trace"})]}),c.jsx(hi,{children:e?`Full log for account: ${e}`:"Historical log for this synchronization run."})]}),c.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:d?c.jsx("div",{className:"py-20 flex justify-center",children:c.jsx(uu,{text:"Loading trace..."})}):o.length===0?c.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:"No granular trace events found for this run."}):o.map((y,v)=>c.jsxs("div",{className:"relative pl-8",children:[v!==o.length-1&&c.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),c.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:g(y.event_type)}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-foreground/70",children:y.agent_state}),y.emails?.subject&&c.jsxs("span",{className:"text-[10px] text-primary font-medium truncate max-w-[300px]",children:["Re: ",y.emails.subject]})]}),c.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(fi,{className:"w-3 h-3"}),new Date(y.created_at).toLocaleTimeString()]})]}),c.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[y.event_type==="info"&&c.jsx("p",{className:"text-sm text-foreground/90",children:y.details?.message}),y.event_type==="analysis"&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("p",{className:"text-xs text-foreground italic leading-relaxed",children:['"',y.details?.summary,'"']}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("span",{className:"text-[9px] bg-secondary px-1.5 py-0.5 rounded font-bold uppercase",children:y.details?.category}),y.details?.suggested_actions?.map(b=>c.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))]}),y.details?.usage&&c.jsxs("div",{className:"flex gap-3 pt-1.5 mt-1 border-t border-border/50 text-[9px] text-muted-foreground",children:[c.jsxs("span",{children:["In: ",c.jsx("b",{children:y.details.usage.prompt_tokens})]}),c.jsxs("span",{children:["Out: ",c.jsx("b",{children:y.details.usage.completion_tokens})]}),c.jsxs("span",{children:["Total: ",c.jsx("span",{className:"text-primary font-bold",children:y.details.usage.total_tokens})]})]})]}),y.event_type==="action"&&c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:["Executed: ",y.details?.action]}),c.jsx(Em,{className:"w-4 h-4 text-emerald-500"})]}),y.event_type==="error"&&c.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:y.details?.error})]})]})]},y.id))})]})})}function y3(){const{state:t,actions:e}=Si(),[a,r]=w.useState(null),[o,u]=w.useState(void 0),[d,f]=w.useState(!1);if(w.useEffect(()=>{e.fetchStats()},[]),!t.stats)return c.jsx(uu,{text:"Loading analytics..."});const p=(y,v)=>{r(y),u(v),f(!0)},{stats:g}=t;return c.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[c.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[c.jsx(kb,{className:"w-6 h-6 text-primary"}),"Analytics Dashboard"]}),c.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[c.jsx(Gc,{title:"Total Emails",value:g.totalEmails,color:"primary"}),c.jsx(Gc,{title:"Spam Caught",value:g.categoryCounts.spam||0,color:"destructive"}),c.jsx(Gc,{title:"Actions Taken",value:Object.values(g.actionCounts).reduce((y,v)=>y+v,0)-(g.actionCounts.none||0),color:"emerald"}),c.jsx(Gc,{title:"Accounts",value:g.accountCount,color:"blue"})]}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[c.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[c.jsx("h3",{className:"font-semibold mb-4",children:"Email Categories"}),c.jsx("div",{className:"space-y-3",children:Object.entries(g.categoryCounts).map(([y,v])=>c.jsx("div",{className:"flex items-center gap-3",children:c.jsxs("div",{className:"flex-1",children:[c.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[c.jsx("span",{className:"capitalize",children:y}),c.jsx("span",{className:"text-muted-foreground",children:v})]}),c.jsx("div",{className:"h-2 bg-secondary rounded-full overflow-hidden",children:c.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${v/g.totalEmails*100}%`}})})]})},y))})]}),c.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[c.jsx("h3",{className:"font-semibold mb-4",children:"Actions Taken"}),c.jsx("div",{className:"space-y-3",children:Object.entries(g.actionCounts).map(([y,v])=>c.jsxs("div",{className:"flex items-center justify-between py-2 border-b last:border-0",children:[c.jsx("span",{className:"capitalize",children:y}),c.jsx("span",{className:"font-medium",children:v})]},y))})]})]}),c.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[c.jsx("h3",{className:"font-semibold mb-4",children:"Recent Sync Activity"}),g.recentSyncs.length===0?c.jsx("p",{className:"text-muted-foreground text-sm",children:"No sync activity yet"}):c.jsx("div",{className:"space-y-3",children:g.recentSyncs.map(y=>{const v=y.completed_at?Math.round((new Date(y.completed_at).getTime()-new Date(y.started_at).getTime())/1e3):null;return c.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:()=>p(y.id,y.email_accounts?.email_address),children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:Te("w-2.5 h-2.5 rounded-full",y.status==="success"?"bg-emerald-500":y.status==="failed"?"bg-destructive":"bg-yellow-500 shadow-[0_0_8px_rgba(234,179,8,0.5)] animate-pulse")}),c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-sm font-medium group-hover:text-primary transition-colors",children:y.email_accounts?.email_address||"System Sync"}),c.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(fi,{className:"w-3 h-3"}),new Date(y.started_at).toLocaleString(),v!==null&&c.jsxs("span",{className:"ml-2 px-1.5 py-0.5 bg-secondary rounded-full",children:[v,"s"]})]})]})]}),c.jsx("div",{className:"flex items-center gap-4 text-xs",children:c.jsxs("div",{className:"flex flex-col items-end",children:[c.jsxs("span",{className:"font-bold text-primary",children:[y.emails_processed," emails"]}),c.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[y.emails_deleted," deleted, ",y.emails_drafted," drafted"]})]})})]},y.id)})})]}),c.jsx(g3,{runId:a,accountEmail:o,isOpen:d,onOpenChange:f})]})}function Gc({title:t,value:e,color:a}){const r={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 c.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[c.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:t}),c.jsx("p",{className:`text-3xl font-bold ${r[a]||""}`,children:e})]})}function v3(){return c.jsx(tN,{defaultTheme:"system",storageKey:"email-automator-theme",children:c.jsx(WC,{children:c.jsx(XC,{children:c.jsxs(KC,{children:[c.jsx(p3,{}),c.jsx(HC,{})]})})})})}iT.createRoot(document.getElementById("root")).render(c.jsx(Nb.StrictMode,{children:c.jsx(v3,{})}));
|
|
104
|
+
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return w.useEffect(()=>{t&&(document.getElementById(t)||console.error(a))},[a,t]),null},VM="DialogDescriptionWarning",BM=({contentRef:t,descriptionId:e})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${BS(VM).contentName}}.`;return w.useEffect(()=>{const o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},IM=NS,$M=kS,qM=RS,HM=OS,GM=MS,KM=US,FM=PS;function li({...t}){return c.jsx(IM,{"data-slot":"dialog",...t})}function YM({...t}){return c.jsx($M,{"data-slot":"dialog-portal",...t})}function XM({className:t,...e}){return c.jsx(qM,{"data-slot":"dialog-overlay",className:Te("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function ci({className:t,children:e,...a}){return c.jsxs(YM,{"data-slot":"dialog-portal",children:[c.jsx(XM,{}),c.jsxs(HM,{"data-slot":"dialog-content",className:Te("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...a,children:[e,c.jsxs(FM,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[c.jsx(yi,{}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function ui({className:t,...e}){return c.jsx("div",{"data-slot":"dialog-header",className:Te("flex flex-col gap-2 text-center sm:text-left",t),...e})}function Zr({className:t,...e}){return c.jsx("div",{"data-slot":"dialog-footer",className:Te("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...e})}function di({className:t,...e}){return c.jsx(GM,{"data-slot":"dialog-title",className:Te("text-lg leading-none font-semibold",t),...e})}function hi({className:t,...e}){return c.jsx(KM,{"data-slot":"dialog-description",className:Te("text-muted-foreground text-sm",t),...e})}function JM({email:t,isOpen:e,onOpenChange:a,onRetry:r}){const[o,u]=w.useState([]),[d,f]=w.useState(!1);w.useEffect(()=>{e&&t&&p()},[e,t]);const p=async()=>{if(t){f(!0);try{const y=await Ue.getEmailEvents(t.id);y.data&&u(y.data.events)}catch(y){console.error("Failed to fetch trace:",y)}finally{f(!1)}}},g=y=>{switch(y){case"analysis":return c.jsx(Lo,{className:"w-4 h-4 text-purple-500"});case"action":return c.jsx(Vo,{className:"w-4 h-4 text-emerald-500"});case"error":return c.jsx(js,{className:"w-4 h-4 text-red-500"});default:return c.jsx(mi,{className:"w-4 h-4 text-blue-500"})}};return c.jsx(li,{open:e,onOpenChange:a,children:c.jsxs(ci,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[c.jsxs(ui,{className:"p-6 border-b flex flex-row items-center justify-between",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(xu,{className:"w-5 h-5 text-primary"}),c.jsx(di,{children:"AI Processing Trace"})]}),c.jsx(hi,{children:"Step-by-step log of how the AI analyzed and acted on this email."})]}),t?.processing_status==="failed"&&r&&c.jsxs(Q,{size:"sm",variant:"outline",onClick:()=>{r(t),a(!1)},className:"gap-2 text-destructive border-destructive/20 hover:bg-destructive/10",children:[c.jsx(fa,{className:"w-3.5 h-3.5"}),"Retry Job"]})]}),c.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:d?c.jsx("div",{className:"py-20 flex justify-center",children:c.jsx(ft,{})}):o.length===0?c.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:"No granular trace events found for this email."}):o.map((y,v)=>c.jsxs("div",{className:"relative pl-8",children:[v!==o.length-1&&c.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),c.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:g(y.event_type)}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-foreground/70",children:y.agent_state}),c.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(fi,{className:"w-3 h-3"}),new Date(y.created_at).toLocaleTimeString()]})]}),c.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[y.event_type==="info"&&c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-foreground/90",children:y.details?.message}),y.details?.system_prompt&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[c.jsx(la,{className:"w-3 h-3"})," System Prompt"]}),c.jsx("pre",{className:"text-[10px] bg-secondary/50 p-2 rounded border overflow-x-auto whitespace-pre-wrap max-h-60 overflow-y-auto font-mono",children:y.details.system_prompt})]}),y.details?.content_preview&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[c.jsx(la,{className:"w-3 h-3"})," Email Content (sent to LLM)"]}),c.jsx("pre",{className:"text-[10px] bg-blue-500/5 p-2 rounded border border-blue-500/10 overflow-x-auto whitespace-pre-wrap max-h-40 overflow-y-auto font-mono",children:y.details.content_preview})]})]}),y.event_type==="analysis"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs("div",{className:"text-[10px] bg-secondary px-2 py-1 rounded",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Category:"}),c.jsx("span",{className:"font-bold uppercase",children:y.details?.category||"Analyzing..."})]}),c.jsxs("div",{className:"text-[10px] bg-secondary px-2 py-1 rounded",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Sentiment:"}),c.jsx("span",{className:"font-bold uppercase",children:y.details?.sentiment||"Analyzing..."})]})]}),y.details?.system_prompt&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[c.jsx(la,{className:"w-3 h-3"})," System Prompt"]}),c.jsx("pre",{className:"text-[10px] bg-secondary/50 p-2 rounded border overflow-x-auto whitespace-pre-wrap max-h-40 overflow-y-auto font-mono",children:y.details?.system_prompt})]}),y.details?._raw_response&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-[9px] font-bold text-muted-foreground uppercase flex items-center gap-1",children:[c.jsx(la,{className:"w-3 h-3"})," Raw LLM Response"]}),c.jsx("pre",{className:"text-[10px] bg-emerald-500/5 p-2 rounded border border-emerald-500/10 overflow-x-auto font-mono",children:JSON.stringify(JSON.parse(y.details._raw_response),null,2)})]}),y.details?.usage&&c.jsxs("div",{className:"flex gap-4 pt-2 border-t border-border/50",children:[c.jsxs("div",{className:"text-[10px]",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Prompt:"}),c.jsx("span",{className:"font-mono font-bold",children:y.details.usage.prompt_tokens})]}),c.jsxs("div",{className:"text-[10px]",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Completion:"}),c.jsx("span",{className:"font-mono font-bold",children:y.details.usage.completion_tokens})]}),c.jsxs("div",{className:"text-[10px]",children:[c.jsx("span",{className:"text-muted-foreground mr-1",children:"Total:"}),c.jsx("span",{className:"font-mono font-bold text-primary",children:y.details.usage.total_tokens})]})]})]}),y.event_type==="action"&&c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:["Executed: ",y.details?.action]}),c.jsxs("p",{className:"text-xs text-muted-foreground italic",children:['"',y.details?.reason,'"']})]}),c.jsx(Em,{className:"w-5 h-5 text-emerald-500"})]}),y.event_type==="error"&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:typeof y.details?.error=="object"?y.details.error.message||JSON.stringify(y.details.error):y.details?.error}),y.details?.raw_response&&c.jsx("pre",{className:"text-[10px] bg-red-500/5 p-2 rounded border border-red-500/10 overflow-x-auto whitespace-pre-wrap font-mono",children:typeof y.details.raw_response=="object"?JSON.stringify(y.details.raw_response,null,2):y.details.raw_response})]})]})]})]},y.id))})]})})}const WM={spam:"bg-destructive/10 text-destructive",newsletter:"bg-blue-500/10 text-blue-600 dark:text-blue-400",support:"bg-orange-500/10 text-orange-600 dark:text-orange-400",client:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",internal:"bg-purple-500/10 text-purple-600 dark:text-purple-400",personal:"bg-pink-500/10 text-pink-600 dark:text-pink-400",other:"bg-gray-500/10 text-gray-600 dark:text-gray-400"};function ZM(){const{state:t,actions:e,dispatch:a}=Si(),{openTerminal:r}=ww(),[o,u]=w.useState(!0),[d,f]=w.useState(!1),[p,g]=w.useState(""),[y,v]=w.useState(null),[b,S]=w.useState(null),[T,j]=w.useState({}),[E,C]=w.useState(null),[M,k]=w.useState(!1),[V,q]=w.useState(null);w.useEffect(()=>{t.isAuthenticated?(G(),e.fetchStats()):u(!1)},[y,t.isAuthenticated]);const G=async(A=0)=>{u(!0),await e.fetchEmails({category:y||void 0,search:p||void 0,offset:A,sortBy:t.sortBy,sortOrder:t.sortOrder}),u(!1)},$=A=>{e.fetchEmails({category:y||void 0,search:p||void 0,offset:0,sortBy:A,sortOrder:t.sortOrder})},B=()=>{e.fetchEmails({category:y||void 0,search:p||void 0,offset:0,sortBy:t.sortBy,sortOrder:t.sortOrder==="asc"?"desc":"asc"})},W=async()=>{if(t.accounts.length===0){oe.warning("Please connect an email account first");return}Gn.playStart(),r(),f(!0);const A=await e.triggerSync();f(!1),A?(Gn.playSuccess(),oe.success("Sync completed! Check your emails.")):oe.error("Sync failed. Check account status for details.")},me=async(A,H)=>{if(H==="delete"&&E!==A.id){C(A.id);return}C(null),j(xe=>({...xe,[A.id]:H}));const F=await e.executeAction(A.id,H);j(xe=>{const be={...xe};return delete be[A.id],be}),F&&(oe.success(`Email ${H==="delete"?"deleted":H==="archive"?"archived":"updated"}`),H==="delete"&&G(t.emailsOffset))},ue=()=>{C(null)},pe=A=>{A.preventDefault(),G()},ze=A=>{const H=A==="next"?t.emailsOffset+20:Math.max(0,t.emailsOffset-20);G(H)},Fe=A=>{q(A),k(!0)},Re=async A=>{await e.retryProcessing(A.id)&&oe.success("Retrying email processing...")};return c.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 animate-in fade-in duration-500",children:[c.jsxs("section",{className:"lg:col-span-2 space-y-4",children:[c.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-4",children:[c.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[c.jsx(tu,{className:"w-5 h-5 text-primary"}),"Recent Analysis"]}),c.jsxs("div",{className:"flex gap-2 w-full sm:w-auto",children:[c.jsxs(Q,{onClick:W,size:"sm",variant:"default",className:"h-9 shadow-md px-4",disabled:d,children:[c.jsx(fa,{className:Te("w-3.5 h-3.5 mr-2",d&&"animate-spin")}),d?"Syncing...":"Sync Now"]}),c.jsxs("span",{className:"h-9 text-xs font-medium text-muted-foreground bg-secondary px-3 py-1 rounded-md border border-border flex items-center",children:[t.emailsTotal," emails"]})]})]}),d&&c.jsxs("div",{className:"bg-primary/5 border border-primary/20 p-4 rounded-lg flex items-center justify-between animate-in fade-in slide-in-from-top-2",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"bg-primary/10 p-2 rounded-full",children:c.jsx(Pt,{className:"w-5 h-5 text-primary animate-spin"})}),c.jsxs("div",{children:[c.jsx("h4",{className:"font-semibold text-sm",children:"Sync in progress..."}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Fetching and analyzing emails. New emails will appear below automatically."})]})]}),c.jsxs(Q,{variant:"outline",size:"sm",onClick:r,className:"h-8 text-xs",children:[c.jsx(xu,{className:"w-3.5 h-3.5 mr-2"}),"View Logs"]})]}),c.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-center",children:[c.jsxs("form",{onSubmit:pe,className:"flex-1 flex gap-2 w-full",children:[c.jsxs("div",{className:"relative flex-1",children:[c.jsx(kE,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),c.jsx(Ae,{placeholder:"Search emails...",value:p,onChange:A=>g(A.target.value),className:"pl-9 h-9"})]}),c.jsx(Q,{type:"submit",size:"sm",className:"h-9 px-4",children:"Search"})]}),c.jsxs("div",{className:"flex items-center gap-1 bg-secondary/30 p-1 rounded-md border border-border/50 h-9",children:[c.jsxs("select",{className:"bg-transparent text-xs font-medium border-none focus:ring-0 cursor-pointer pl-2 pr-8 h-full",value:t.sortBy,onChange:A=>$(A.target.value),children:[c.jsx("option",{value:"date",children:"Received Time"}),c.jsx("option",{value:"created_at",children:"Processed Time"})]}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 text-primary",onClick:B,title:t.sortOrder==="asc"?"Sorting: Oldest First":"Sorting: Newest First",children:t.sortOrder==="asc"?c.jsx(bT,{className:"w-3.5 h-3.5"}):c.jsx(yT,{className:"w-3.5 h-3.5"})})]})]}),c.jsxs("div",{className:"flex gap-1 flex-wrap",children:[c.jsx(Q,{size:"sm",variant:t.activeCategory===null?"secondary":"ghost",onClick:()=>v(null),children:"All"}),["spam","client","newsletter","support"].map(A=>c.jsx(Q,{size:"sm",variant:t.activeCategory===A?"secondary":"ghost",onClick:()=>v(A),className:"capitalize",children:A},A))]}),o?c.jsx(ZC,{}):t.emails.length===0?c.jsxs(Vt,{className:"p-20 text-center shadow-sm",children:[c.jsx("div",{className:"w-16 h-16 bg-primary/10 text-primary rounded-full flex items-center justify-center mx-auto mb-6",children:c.jsx(tu,{className:"w-8 h-8"})}),c.jsx("h3",{className:"text-lg font-medium",children:"No emails found"}),c.jsx("p",{className:"text-muted-foreground mt-2 mb-6",children:t.accounts.length===0?"Connect your email account to get started.":"Try syncing or adjusting your filters."}),t.accounts.length>0&&c.jsxs(Q,{onClick:()=>{r(),W()},disabled:d,children:[c.jsx(fa,{className:Te("w-4 h-4 mr-2",d&&"animate-spin")}),"Sync Now"]})]}):c.jsxs(c.Fragment,{children:[t.emails.map(A=>c.jsx(t3,{email:A,onAction:me,onRetry:Re,onViewTrace:Fe,onSelect:()=>S(A),isSelected:b?.id===A.id,loadingAction:T[A.id],isDeletePending:E===A.id,onCancelDelete:ue},A.id)),c.jsx(JM,{isOpen:M,onOpenChange:k,email:V,onRetry:Re}),t.emailsTotal>20&&c.jsxs("div",{className:"flex items-center justify-between pt-4",children:[c.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>ze("prev"),disabled:t.emailsOffset===0,children:[c.jsx(DT,{className:"w-4 h-4 mr-1"}),"Previous"]}),c.jsxs("span",{className:"text-sm text-muted-foreground",children:[t.emailsOffset+1," - ",Math.min(t.emailsOffset+20,t.emailsTotal)," of ",t.emailsTotal]}),c.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>ze("next"),disabled:t.emailsOffset+20>=t.emailsTotal,children:["Next",c.jsx(Zc,{className:"w-4 h-4 ml-1"})]})]})]})]}),c.jsxs("aside",{className:"space-y-6",children:[b&&c.jsxs(Vt,{className:"p-6 border-primary/20 bg-primary/5 animate-in slide-in-from-right-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-4",children:[c.jsx("h3",{className:"font-semibold",children:"Email Details"}),c.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>S(null),children:c.jsx(yi,{className:"w-4 h-4"})})]}),c.jsxs("div",{className:"space-y-3 text-sm",children:[c.jsxs("div",{children:[c.jsx("span",{className:"text-muted-foreground",children:"From:"}),c.jsx("p",{className:"font-medium truncate",children:b.sender})]}),c.jsxs("div",{children:[c.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),c.jsx("p",{className:"font-medium",children:b.subject})]}),b.ai_analysis&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{children:[c.jsx("span",{className:"text-muted-foreground",children:"Summary:"}),c.jsx("p",{className:"text-xs mt-1",children:b.ai_analysis.summary})]}),b.ai_analysis.key_points&&c.jsxs("div",{children:[c.jsx("span",{className:"text-muted-foreground",children:"Key Points:"}),c.jsx("ul",{className:"text-xs mt-1 list-disc list-inside",children:b.ai_analysis.key_points.map((A,H)=>c.jsx("li",{children:A},H))})]}),b.ai_analysis.draft_response&&c.jsxs("div",{className:"mt-4 p-3 bg-emerald-500/5 border border-emerald-500/20 rounded-lg",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2 text-emerald-600 dark:text-emerald-400",children:[c.jsx(OE,{className:"w-3.5 h-3.5"}),c.jsx("span",{className:"text-xs font-bold uppercase",children:"AI Draft Reply"})]}),c.jsx("p",{className:"text-xs leading-relaxed whitespace-pre-wrap italic text-foreground/80",children:b.ai_analysis.draft_response}),c.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:["* This draft is already saved in your ",b.email_accounts?.provider==="gmail"?"Gmail":"Outlook"," Drafts folder."]})]})]})]})]}),c.jsx(QM,{accounts:t.accounts,onUpdate:e.updateAccount,onSync:e.triggerSync,settings:t.settings,onUpdateSettings:e.updateSettings,openTerminal:r}),c.jsxs(Vt,{className:"p-6",children:[c.jsxs("h3",{className:"font-semibold mb-4 flex items-center gap-2",children:[c.jsx(Ob,{className:"w-4 h-4 text-primary"}),"Sync History"]}),c.jsx("div",{className:"space-y-4",children:!t.stats?.recentSyncs||t.stats.recentSyncs.length===0?c.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No sync history available."}):t.stats.recentSyncs.slice(0,5).map(A=>c.jsxs("div",{className:"flex justify-between items-start text-sm border-b last:border-0 pb-3 last:pb-0",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:Te("w-1.5 h-1.5 rounded-full",A.status==="success"?"bg-emerald-500":A.status==="running"?"bg-blue-500 animate-pulse":"bg-red-500")}),c.jsxs("p",{className:"font-medium text-xs",children:[new Date(A.started_at).toLocaleDateString()," ",new Date(A.started_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]}),c.jsxs("p",{className:"text-[10px] text-muted-foreground pl-3.5",children:["Processed: ",c.jsx("span",{className:"font-medium text-foreground",children:A.emails_processed})," • Actioned: ",c.jsx("span",{className:"font-medium text-foreground",children:A.emails_deleted+A.emails_drafted})]}),A.error_message&&c.jsx("p",{className:"text-[10px] text-destructive pl-3.5 line-clamp-1",title:A.error_message,children:A.error_message})]}),c.jsx("div",{className:"text-[10px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded",children:A.status==="running"?"Running":A.completed_at?`${Math.round((new Date(A.completed_at).getTime()-new Date(A.started_at).getTime())/1e3)}s`:"..."})]},A.id))})]}),c.jsxs(Vt,{className:"p-6",children:[c.jsx("h3",{className:"font-semibold mb-4",children:"Quick Stats"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Processed"}),c.jsx("span",{className:"font-medium",children:t.emailsTotal})]}),c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx("span",{className:"text-sm text-muted-foreground",children:"Connected Accounts"}),c.jsx("span",{className:"font-medium",children:t.accounts.length})]}),c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Rules"}),c.jsx("span",{className:"font-medium",children:t.rules.filter(A=>A.is_enabled).length})]})]})]})]})]})}function QM({accounts:t,onUpdate:e,onSync:a,settings:r,onUpdateSettings:o,openTerminal:u}){return t.length===0?null:c.jsxs(Vt,{className:"p-6",children:[c.jsxs("h3",{className:"font-semibold mb-4 flex items-center gap-2",children:[c.jsx(zE,{className:"w-4 h-4 text-primary"}),"Sync Scope"]}),c.jsx("div",{className:"space-y-6",children:t.map(d=>c.jsx(e3,{account:d,onUpdate:e,onSync:a,openTerminal:u},d.id))})]})}function e3({account:t,onUpdate:e,onSync:a,openTerminal:r}){const[o,u]=w.useState(!1),[d,f]=w.useState(""),[p,g]=w.useState(""),y=T=>{if(!T)return"";const j=typeof T=="string"&&/^\d+$/.test(T)?parseInt(T):T,E=new Date(j);if(isNaN(E.getTime()))return"";const C=M=>M<10?"0"+M:M;return E.getFullYear()+"-"+C(E.getMonth()+1)+"-"+C(E.getDate())+"T"+C(E.getHours())+":"+C(E.getMinutes())};w.useEffect(()=>{const T=t.sync_start_date||t.last_sync_checkpoint||t.last_sync_at;f(y(T)),g((t.sync_max_emails_per_run||50).toString())},[t.id,t.sync_start_date,t.last_sync_checkpoint,t.last_sync_at,t.sync_max_emails_per_run]);const v=async T=>{u(!0),await e(t.id,T),u(!1)},b=()=>{const T=t.sync_start_date?new Date(t.sync_start_date).toISOString():"",j=d?new Date(d).toISOString():"";j!==T&&v({sync_start_date:j||null})},S=()=>{const T=parseInt(p,10)||50;T!==t.sync_max_emails_per_run&&v({sync_max_emails_per_run:T})};return c.jsxs("div",{className:"space-y-3 pb-4 border-b last:border-0 last:pb-0",children:[c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx("span",{className:"text-xs font-medium truncate max-w-[150px]",title:t.email_address,children:t.email_address}),c.jsxs("div",{className:"flex items-center gap-1",children:[t.last_sync_status==="syncing"?c.jsx(Pt,{className:"w-3 h-3 text-primary animate-spin"}):t.last_sync_status==="success"?c.jsx(Em,{className:"w-3 h-3 text-emerald-500"}):t.last_sync_status==="error"?c.jsx("span",{title:t.last_sync_error||"Error",children:c.jsx(js,{className:"w-3 h-3 text-destructive"})}):null,c.jsx(Q,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{r(),a(t.id)},disabled:t.last_sync_status==="syncing",children:c.jsx(fa,{className:Te("w-3 h-3",t.last_sync_status==="syncing"&&"animate-spin")})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground hover:text-orange-500",title:"Reset Checkpoint (Force Full Re-sync from Start Date)",onClick:()=>e(t.id,{last_sync_checkpoint:null}),disabled:t.last_sync_status==="syncing",children:c.jsx(Ob,{className:"w-3 h-3"})})]})]}),c.jsxs("div",{className:"grid grid-cols-[1.5fr_1fr] gap-2",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("label",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(TT,{className:"w-2.5 h-2.5"})," Sync From"]}),c.jsx(Ae,{type:"datetime-local",className:"h-7 text-[10px] px-2 py-0 w-full",value:d,onChange:T=>f(T.target.value),onBlur:b,disabled:o||t.last_sync_status==="syncing"})]}),c.jsxs("div",{className:"space-y-1",children:[c.jsxs("label",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(sE,{className:"w-2.5 h-2.5"})," Max Emails"]}),c.jsx(Ae,{type:"number",className:"h-7 text-[10px] px-2 py-0",value:p,onChange:T=>g(T.target.value),onBlur:S,disabled:o||t.last_sync_status==="syncing"})]})]}),t.last_sync_at&&c.jsxs("p",{className:"text-[9px] text-muted-foreground",children:["Last sync: ",new Date(t.last_sync_at).toLocaleString()]}),t.last_sync_error&&c.jsxs("p",{className:"text-[9px] text-destructive italic line-clamp-1",title:t.last_sync_error,children:["Error: ",t.last_sync_error]})]})}function t3({email:t,onAction:e,onRetry:a,onViewTrace:r,onSelect:o,isSelected:u,loadingAction:d,isDeletePending:f,onCancelDelete:p}){if(!t)return null;const g=WM[t.category||"other"],y=!!d,v=()=>{if(!t.email_accounts)return"#";const{provider:b,email_address:S}=t.email_accounts;return b==="gmail"?`https://mail.google.com/mail/u/${S}/#all/${t.external_id}`:`https://outlook.office.com/mail/deeplink/read/${encodeURIComponent(t.external_id)}`};return c.jsx(Vt,{className:Te("hover:shadow-md transition-shadow group cursor-pointer",u&&"ring-2 ring-primary"),onClick:o,children:c.jsxs("div",{className:"p-5",children:[c.jsxs("div",{className:"flex justify-between items-start mb-3 gap-4",children:[c.jsxs("div",{className:"flex gap-3 flex-1 min-w-0",children:[c.jsx("div",{className:Te("w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center font-bold text-white text-xs",t.category==="spam"?"bg-destructive":"bg-primary"),children:t.sender?.[0]?.toUpperCase()||"?"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("h3",{className:"font-semibold text-sm line-clamp-1 group-hover:text-primary transition-colors",children:t.subject||"No Subject"}),c.jsx("p",{className:"text-xs text-muted-foreground truncate",title:t.sender||"",children:t.sender})]})]}),c.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[c.jsx("span",{className:Te("px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",g),children:t.category||"unknown"}),c.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.processing_status==="pending"&&c.jsxs("span",{className:"text-[9px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(fi,{className:"w-2.5 h-2.5"})," Queued"]}),t.processing_status==="processing"&&c.jsxs("span",{className:"text-[9px] text-blue-600 dark:text-blue-400 bg-blue-500/10 border border-blue-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(Pt,{className:"w-2.5 h-2.5 animate-spin"})," Analyzing"]}),t.processing_status==="completed"&&c.jsxs("span",{className:"text-[9px] text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(Lo,{className:"w-2.5 h-2.5"})," Analyzed"]}),t.processing_status==="failed"&&c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsxs("span",{className:"text-[9px] text-red-600 dark:text-red-400 bg-red-500/10 border border-red-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",title:t.processing_error||"Unknown error",children:[c.jsx(js,{className:"w-2.5 h-2.5"})," Failed"]}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-5 w-5 text-red-600 hover:bg-red-500/10",onClick:b=>{b.stopPropagation(),a(t)},title:"Retry Processing",children:c.jsx(fa,{className:"w-2.5 h-2.5"})})]}),!t.processing_status&&!t.ai_analysis&&c.jsxs("span",{className:"text-[9px] text-muted-foreground bg-secondary px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(Pt,{className:"w-2.5 h-2.5 animate-spin"})," Pending"]}),!t.processing_status&&t.ai_analysis&&c.jsxs("span",{className:"text-[9px] text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.5 rounded flex items-center gap-1",children:[c.jsx(Lo,{className:"w-2.5 h-2.5"})," Analyzed"]})]}),c.jsxs("div",{className:"flex items-center justify-end gap-2 text-[10px] text-muted-foreground/80 leading-tight",children:[c.jsxs("span",{title:t.date?new Date(t.date).toLocaleString():"",className:"whitespace-nowrap",children:[c.jsx("span",{className:"opacity-70 text-[9px]",children:"REC:"})," ",t.date?new Date(t.date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"-"]}),c.jsx("span",{className:"opacity-30",children:"•"}),c.jsxs("span",{title:new Date(t.created_at).toLocaleString(),className:"whitespace-nowrap",children:[c.jsx("span",{className:"opacity-70 text-[9px]",children:"PROC:"})," ",new Date(t.created_at).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})]})]})]})]}),c.jsx("p",{className:"text-muted-foreground text-sm mb-4 line-clamp-2 leading-relaxed",children:t.body_snippet}),c.jsxs("div",{className:"bg-secondary/30 p-3 rounded-lg border border-border/50 flex justify-between items-center",children:[c.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[c.jsx(Mf,{className:"w-3.5 h-3.5 text-emerald-500"}),"Suggested:",t.suggested_actions&&t.suggested_actions.length>0?c.jsx("div",{className:"flex gap-1 flex-wrap",children:t.suggested_actions.map(b=>c.jsx("span",{className:"text-foreground border border-border/50 px-1.5 py-0.5 rounded capitalize bg-background/50",children:b},b))}):c.jsx("span",{className:"text-foreground",children:t.suggested_action||"none"}),t.actions_taken&&t.actions_taken.length>0?c.jsxs("span",{className:"text-muted-foreground ml-2 truncate max-w-[100px]",title:t.actions_taken.join(", "),children:["(Done: ",t.actions_taken.join(", "),")"]}):t.action_taken?c.jsxs("span",{className:"text-muted-foreground ml-2",children:["(Done: ",t.action_taken,")"]}):null]}),c.jsx("div",{className:"flex gap-1 items-center",onClick:b=>b.stopPropagation(),children:f?c.jsxs("div",{className:"flex items-center gap-1 animate-in fade-in duration-200",children:[c.jsx("span",{className:"text-xs text-destructive mr-1",children:"Delete?"}),c.jsx(Q,{variant:"destructive",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>e(t,"delete"),disabled:y,children:d==="delete"?c.jsx(Pt,{className:"w-3 h-3 animate-spin"}):"Yes"}),c.jsx(Q,{variant:"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:p,disabled:y,children:"No"})]}):c.jsxs(c.Fragment,{children:[c.jsx("a",{href:v(),target:"_blank",rel:"noreferrer",className:"inline-flex items-center justify-center h-7 w-7 rounded-md text-muted-foreground hover:text-primary hover:bg-secondary/50 transition-colors",title:`Open in ${t.email_accounts?.provider==="gmail"?"Gmail":"Outlook"}`,children:c.jsx(eu,{className:"w-3.5 h-3.5"})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-primary",onClick:()=>r(t),title:"View AI Trace (Prompt/Response)",children:c.jsx(Rb,{className:"w-3.5 h-3.5"})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-destructive",onClick:()=>e(t,"delete"),disabled:y,title:"Delete",children:d==="delete"?c.jsx(Pt,{className:"w-3.5 h-3.5 animate-spin"}):c.jsx(au,{className:"w-3.5 h-3.5"})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-blue-500",onClick:()=>e(t,"archive"),disabled:y,title:"Archive",children:d==="archive"?c.jsx(Pt,{className:"w-3.5 h-3.5 animate-spin"}):c.jsx(pT,{className:"w-3.5 h-3.5"})}),c.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 hover:text-primary",onClick:()=>e(t,"flag"),disabled:y,title:"Flag",children:d==="flag"?c.jsx(Pt,{className:"w-3.5 h-3.5 animate-spin"}):c.jsx(QT,{className:"w-3.5 h-3.5"})})]})})]})]})})}const No="realtimexai";function n3(){const{state:t,actions:e}=Si(),[a,r]=w.useState(!1),[o,u]=w.useState(!1),[d,f]=w.useState(null),[p,g]=w.useState(!1),[y,v]=w.useState(!1),[b,S]=w.useState({}),[T,j]=w.useState(!1),[E,C]=w.useState("credentials"),[M,k]=w.useState(""),[V,q]=w.useState(""),[G,$]=w.useState(""),[B,W]=w.useState(""),[me,ue]=w.useState(!1),[pe,ze]=w.useState(!1),[Fe,Re]=w.useState(!1),[A,H]=w.useState("credentials"),[F,xe]=w.useState(""),[be,R]=w.useState(""),[X,Z]=w.useState(!1),[te,fe]=w.useState(!1),[we,he]=w.useState(""),[Ye,Be]=w.useState("category"),[Mt,wt]=w.useState("newsletter"),[Tt,Ns]=w.useState(["archive"]),[En,As]=w.useState(""),[Qa,er]=w.useState(""),[Ei,Cs]=w.useState(""),[tr,ks]=w.useState(""),[il,ya]=w.useState([]),[St,ol]=w.useState(!1),[Ni,Ai]=w.useState(!1),[un,Ru]=w.useState([]),[va,ll]=w.useState(!1),[cl,Yn]=w.useState(null);w.useEffect(()=>{(async()=>{ll(!0),Yn(null);try{const ee=await Ue.getChatProviders();ee.data?.success?Ru(ee.data.providers||[]):Yn(ee.data?.message||"Failed to load providers")}catch(ee){console.error("Failed to fetch providers:",ee),Yn("Failed to load providers. Using defaults.")}finally{ll(!1)}})()},[]);const Kt=un.find(D=>D.provider===(b.llm_provider||No))?.models||[],zt=w.useMemo(()=>!b.llm_model||Kt.some(ee=>ee.id===b.llm_model)?Kt:[{id:b.llm_model,name:`${b.llm_model} (saved)`},...Kt],[Kt,b.llm_model]),Ou=w.useMemo(()=>!b.llm_provider||b.llm_provider===No||un.some(ee=>ee.provider===b.llm_provider)?un:[{provider:b.llm_provider,name:`${b.llm_provider} (saved)`,models:[]},...un],[un,b.llm_provider]),Du=D=>{const ee=un.find(Ne=>Ne.provider===D);S(Ne=>({...Ne,llm_provider:D,llm_model:ee?.models?.[0]?.id||""}))},Mu=async()=>{v(!0);try{const D=await Ue.testLlm({llm_provider:b.llm_provider||void 0,llm_model:b.llm_model||void 0});D.data?.success?oe.success(D.data.message):oe.error(D.data?.message||"Connection failed")}catch(D){oe.error(D.response?.data?.message||"Connection failed")}finally{v(!1)}},[Xn,Jn]=w.useState(null),[dn,hn]=w.useState(null);w.useEffect(()=>{e.fetchAccounts(),e.fetchRules(),e.fetchSettings()},[]),w.useEffect(()=>{t.settings&&S(t.settings)},[t.settings]);const nr=async()=>{const D=t.rules.find(ee=>ee.name==="Auto-Trash Spam");if(!D){oe.error("System rule not found. Please sync your database.");return}Jn("auto_trash_spam"),await e.toggleRule(D.id),Jn(null)},xa=async()=>{const D=t.rules.find(ee=>ee.name==="Smart Drafts");if(!D){oe.error("System rule not found. Please sync your database.");return}Jn("smart_drafts"),await e.toggleRule(D.id),Jn(null)},Ci=D=>{hn(D),he(D.name);const ee=D.condition,Et=Object.keys(ee).filter(Os=>Os!=="older_than_days")[0]||"category";Be(Et),wt(ee[Et]||""),As(ee.older_than_days?.toString()||"");const Wn=D.actions&&D.actions.length>0?D.actions:D.action?[D.action]:["archive"];Ns(Wn),er(D.instructions||""),Cs(D.description||""),ks(D.intent||""),ya(D.attachments||[]),fe(!0)},ul=w.useRef(null),ki=()=>{C("credentials"),k(""),q(""),$(""),W(""),j(!0)},ba=D=>{k(D);try{const ee=JSON.parse(D),Ne=ee.installed||ee.web||ee;Ne.client_id&&q(Ne.client_id),Ne.client_secret&&$(Ne.client_secret),ee.installed?oe.success("Detected Desktop app credentials"):ee.web&&oe.info("Detected Web app - make sure redirect URI is configured in Google Cloud Console")}catch{}},zu=async()=>{if(!V||!G){oe.error("Please provide both Client ID and Client Secret");return}ue(!0);try{if(await e.updateSettings({...b,google_client_id:V,google_client_secret:G})){S(Ne=>({...Ne,google_client_id:V,google_client_secret:G}));const ee=await Ue.getGmailAuthUrl();if(ee.data?.url)window.open(ee.data.url,"_blank"),C("code"),oe.success("Please authorize in the opened tab, then paste the code here");else{const Ne=typeof ee.error=="string"?ee.error:ee.error?.message;oe.error(Ne||"Failed to get OAuth URL")}}else oe.error("Failed to save credentials")}catch{oe.error("Failed to save credentials")}finally{ue(!1)}},dl=async()=>{if(!B.trim()){oe.error("Please paste the authorization code");return}ze(!0);try{const D=await Ue.connectGmail(B.trim());if(D.data?.success)oe.success("Gmail account connected successfully!"),j(!1),e.fetchAccounts();else{const ee=typeof D.error=="string"?D.error:D.error?.message;oe.error(ee||"Failed to connect Gmail")}}catch{oe.error("Failed to connect Gmail")}finally{ze(!1)}},hl=()=>{H("credentials"),xe(""),R(""),Re(!0)},fl=async()=>{if(!F){oe.error("Please provide the Client ID");return}Z(!0);try{if(await e.updateSettings({...b,microsoft_client_id:F,microsoft_tenant_id:be||"common"})){S(Ne=>({...Ne,microsoft_client_id:F,microsoft_tenant_id:be||"common"}));const ee=await Ue.startMicrosoftDeviceFlow();if(ee.data)f(ee.data),H("device-code"),Ri(ee.data.deviceCode,ee.data.interval);else{const Ne=typeof ee.error=="string"?ee.error:ee.error?.message;oe.error(Ne||"Failed to start device flow")}}else oe.error("Failed to save credentials")}catch{oe.error("Failed to save credentials")}finally{Z(!1)}},Ri=async(D,ee)=>{const Ne=setInterval(async()=>{try{const Et=await Ue.pollMicrosoftDeviceCode(D);Et.data?.status==="completed"?(clearInterval(Ne),f(null),u(!1),Re(!1),oe.success("Outlook account connected"),e.fetchAccounts()):Et.error&&typeof Et.error=="object"&&Et.error.code}catch{}},ee*1e3);setTimeout(()=>{clearInterval(Ne),o&&(f(null),u(!1),Re(!1),oe.error("Connection timed out. Please try again."))},900*1e3)},Oi=async()=>{if(!we){oe.error("Please name your rule");return}if(Tt.length===0){oe.error("Please select at least one action");return}Ai(!0);try{const D={[Ye]:Mt};En&&(D.older_than_days=parseInt(En,10));const ee=Tt.includes("draft"),Ne={name:we,description:Ei||void 0,intent:tr||void 0,condition:D,actions:Tt,instructions:ee?Qa:void 0,attachments:ee?il:[],is_enabled:!0};let Et=!1;dn?Et=await e.updateRule(dn.id,Ne):Et=await e.createRule(Ne),Et?(oe.success(dn?"Rule updated":"Rule created"),fe(!1),hn(null),he(""),Ns(["archive"]),As(""),er(""),Cs(""),ks(""),ya([]),e.fetchRules()):oe.error(`Failed to ${dn?"update":"create"} rule`)}catch{oe.error("An error occurred while saving the rule")}finally{Ai(!1)}},ml=async D=>{if(!confirm("Are you sure you want to disconnect this account?"))return;await e.disconnectAccount(D)&&oe.success("Account disconnected")},Di=async()=>{g(!0);const D=await e.updateSettings(b);g(!1),D&&oe.success("Settings saved")},Pn=async D=>{await e.toggleRule(D)},gt=async D=>{const ee=D.target.files;if(!ee||ee.length===0)return;ol(!0);const Ne=ee[0],Et=Ne.name.split(".").pop(),Wn=`${Math.random().toString(36).substring(2)}.${Et}`,Os=`${t.user.id}/${Wn}`;try{const{error:Nn}=await et.storage.from("rule-attachments").upload(Os,Ne);if(Nn)throw Nn;const Ds={name:Ne.name,path:Os,type:Ne.type,size:Ne.size};ya(wa=>[...wa,Ds]),oe.success("File uploaded")}catch(Nn){console.error("Upload error:",Nn),oe.error("Failed to upload file")}finally{ol(!1),D.target.value=""}},Ut=D=>{ya(ee=>ee.filter(Ne=>Ne.path!==D))},Rs=D=>D==="gmail"?c.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center text-red-600 dark:text-red-400 font-bold",children:"G"}):c.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold",children:"O"});return c.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[c.jsx(li,{open:T,onOpenChange:j,children:c.jsxs(ci,{className:"sm:max-w-lg",children:[c.jsxs(ui,{children:[c.jsxs(di,{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center text-red-600 dark:text-red-400 font-bold text-sm",children:"G"}),"Connect Gmail Account"]}),c.jsx(hi,{children:E==="credentials"?"Enter your Google OAuth credentials to connect your Gmail account.":"Paste the authorization code from Google to complete the connection."})]}),E==="credentials"?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(HE,{className:"w-4 h-4"}),"Paste credentials.json"]}),c.jsx("textarea",{className:"w-full h-24 p-3 text-xs font-mono border rounded-lg bg-secondary/30 resize-none focus:outline-none focus:ring-2 focus:ring-primary",placeholder:'{"installed":{"client_id":"...","client_secret":"..."}}',value:M,onChange:D=>ba(D.target.value)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Download from Google Cloud Console → APIs & Services → Credentials"})]}),c.jsxs("div",{className:"relative",children:[c.jsx("div",{className:"absolute inset-0 flex items-center",children:c.jsx("span",{className:"w-full border-t"})}),c.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:c.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or enter manually"})})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),c.jsx(Ae,{placeholder:"xxx.apps.googleusercontent.com",value:V,onChange:D=>q(D.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client Secret"}),c.jsx(Ae,{type:"password",placeholder:"GOCSPX-...",value:G,onChange:D=>$(D.target.value)})]})]})]}),c.jsxs(Zr,{children:[c.jsx(Q,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),c.jsxs(Q,{onClick:zu,disabled:me||!V||!G,children:[me?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Save & Connect"]})]})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsx("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:c.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:["1. A new tab opened with Google Sign-In",c.jsx("br",{}),"2. Sign in and authorize the app",c.jsx("br",{}),"3. Copy the authorization code shown",c.jsx("br",{}),"4. Paste it below"]})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Authorization Code"}),c.jsx(Ae,{placeholder:"4/0AQlEd8x...",value:B,onChange:D=>W(D.target.value),className:"font-mono"})]})]}),c.jsxs(Zr,{children:[c.jsx(Q,{variant:"outline",onClick:()=>C("credentials"),children:"Back"}),c.jsxs(Q,{onClick:dl,disabled:pe||!B.trim(),children:[pe?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Connect"]})]})]})]})}),c.jsx(li,{open:Fe,onOpenChange:Re,children:c.jsxs(ci,{className:"sm:max-w-lg",children:[c.jsxs(ui,{children:[c.jsxs(di,{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold text-sm",children:"O"}),"Connect Outlook Account"]}),c.jsx(hi,{children:A==="credentials"?"Enter your Microsoft Azure App credentials to connect your Outlook account.":"Follow the instructions to authorize the application."})]}),A==="credentials"?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsx("div",{className:"p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg",children:c.jsx("p",{className:"text-sm text-yellow-800 dark:text-yellow-200",children:"Note: You need an Azure App Registration for this to work."})}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client ID (Application ID)"}),c.jsx(Ae,{placeholder:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",value:F,onChange:D=>xe(D.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Tenant ID (Optional)"}),c.jsx(Ae,{placeholder:"common",value:be,onChange:D=>R(D.target.value)}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:'Default is "common". Use your specific Tenant ID for organization accounts.'})]})]})]}),c.jsxs(Zr,{children:[c.jsx(Q,{variant:"outline",onClick:()=>Re(!1),children:"Cancel"}),c.jsxs(Q,{onClick:fl,disabled:X||!F,children:[X?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Save & Connect"]})]})]}):c.jsxs(c.Fragment,{children:[d&&c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:[c.jsx("h4",{className:"font-medium text-blue-900 dark:text-blue-100 mb-2",children:"Action Required"}),c.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200 mb-4",children:d.message}),c.jsxs("div",{className:"flex flex-col gap-3",children:[c.jsx("div",{className:"flex items-center gap-2 bg-white dark:bg-black/20 p-2 rounded border border-blue-200 dark:border-blue-800",children:c.jsx("code",{className:"text-lg font-mono font-bold flex-1 text-center select-all",children:d.userCode})}),c.jsxs(Q,{variant:"default",className:"w-full bg-blue-600 hover:bg-blue-700",onClick:()=>window.open(d.verificationUri,"_blank"),children:["Open Microsoft Login",c.jsx(eu,{className:"w-4 h-4 ml-2"})]})]})]}),c.jsx("div",{className:"flex justify-center",children:c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(ft,{size:"sm"}),"Waiting for authorization..."]})})]}),c.jsx(Zr,{children:c.jsx(Q,{variant:"outline",onClick:()=>Re(!1),children:"Cancel"})})]})]})}),c.jsx(li,{open:te,onOpenChange:D=>{fe(D),D||hn(null)},children:c.jsxs(ci,{className:"sm:max-w-xl max-h-[90vh] flex flex-col p-0",children:[c.jsxs(ui,{className:"p-6 border-b",children:[c.jsx(di,{children:dn?"Edit Auto-Pilot Rule":"Create Auto-Pilot Rule"}),c.jsx(hi,{children:"Define a condition based on AI analysis to trigger an action."})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Rule Name"}),c.jsx(Ae,{placeholder:"e.g. Archive Newsletters",value:we,onChange:D=>he(D.target.value)})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Description"}),c.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[60px] text-sm",placeholder:"e.g. Handle all marketing newsletters and promotional content from subscription services",value:Ei,onChange:D=>Cs(D.target.value)}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Describe what this rule is for. The AI uses this to semantically match emails."})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Intent"}),c.jsx(Ae,{placeholder:"e.g. Politely decline all sales pitches",value:tr,onChange:D=>ks(D.target.value)}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"The goal of this rule. Used to generate appropriate draft replies."})]}),c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"If Condition Field"}),c.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Ye,onChange:D=>{Be(D.target.value),D.target.value==="category"?wt("newsletter"):D.target.value==="sentiment"?wt("Positive"):D.target.value==="priority"?wt("High"):wt("")},children:[c.jsxs("optgroup",{label:"AI Analysis",children:[c.jsx("option",{value:"category",children:"Category"}),c.jsx("option",{value:"sentiment",children:"Sentiment"}),c.jsx("option",{value:"priority",children:"Priority"})]}),c.jsxs("optgroup",{label:"Metadata",children:[c.jsx("option",{value:"sender_email",children:"Specific Email (Exact)"}),c.jsx("option",{value:"sender_domain",children:"Email Domain (@...)"}),c.jsx("option",{value:"sender_contains",children:"Sender contains..."}),c.jsx("option",{value:"subject_contains",children:"Subject contains..."}),c.jsx("option",{value:"body_contains",children:"Body contains..."})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Equals Value"}),Ye==="category"?c.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Mt,onChange:D=>wt(D.target.value),children:[c.jsx("option",{value:"newsletter",children:"Newsletter"}),c.jsx("option",{value:"spam",children:"Spam"}),c.jsx("option",{value:"promotional",children:"Promotional"}),c.jsx("option",{value:"transactional",children:"Transactional"}),c.jsx("option",{value:"social",children:"Social"}),c.jsx("option",{value:"support",children:"Support"}),c.jsx("option",{value:"client",children:"Client"}),c.jsx("option",{value:"internal",children:"Internal"}),c.jsx("option",{value:"personal",children:"Personal"}),c.jsx("option",{value:"other",children:"Other"})]}):Ye==="sentiment"?c.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Mt,onChange:D=>wt(D.target.value),children:[c.jsx("option",{value:"Positive",children:"Positive"}),c.jsx("option",{value:"Neutral",children:"Neutral"}),c.jsx("option",{value:"Negative",children:"Negative"})]}):Ye==="priority"?c.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:Mt,onChange:D=>wt(D.target.value),children:[c.jsx("option",{value:"High",children:"High"}),c.jsx("option",{value:"Medium",children:"Medium"}),c.jsx("option",{value:"Low",children:"Low"})]}):c.jsx(Ae,{placeholder:Ye==="sender_domain"?"rta.vn":Ye==="sender_email"?"john@example.com":"Keywords...",value:Mt,onChange:D=>wt(D.target.value)})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(fi,{className:"w-4 h-4"}),"Only if email is older than... (Optional)"]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Ae,{type:"number",min:"0",placeholder:"0",className:"w-24",value:En,onChange:D=>As(D.target.value)}),c.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Leave empty or 0 to apply rule immediately upon receipt."})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Then Perform Action(s)"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select one or more actions to execute when the rule matches"}),c.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"archive",label:"Archive Email"},{value:"delete",label:"Delete Email"},{value:"draft",label:"Draft Reply"},{value:"read",label:"Mark as Read"},{value:"star",label:"Star / Flag"}].map(D=>c.jsxs("label",{className:`flex items-center gap-2 p-2 border rounded-md cursor-pointer transition-colors ${Tt.includes(D.value)?"bg-primary/10 border-primary":"bg-background hover:bg-secondary/50"}`,children:[c.jsx("input",{type:"checkbox",checked:Tt.includes(D.value),onChange:ee=>{ee.target.checked?Ns([...Tt,D.value]):Ns(Tt.filter(Ne=>Ne!==D.value))},className:"rounded border-gray-300"}),c.jsx("span",{className:"text-sm",children:D.label})]},D.value))})]}),Tt.includes("draft")&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[c.jsx("label",{className:"text-sm font-medium",children:"Draft Instructions (Context)"}),c.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[80px] text-sm",placeholder:"e.g. Tell them I'm busy until Friday, but interested in the proposal.",value:Qa,onChange:D=>er(D.target.value)}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Specific context for the AI ghostwriter."})]}),c.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(x0,{className:"w-4 h-4"}),"Attachments (Optional)"]}),c.jsxs("div",{className:"flex flex-col gap-2",children:[il.map(D=>c.jsxs("div",{className:"flex items-center justify-between p-2 bg-secondary/50 rounded border text-xs",children:[c.jsx("span",{className:"truncate max-w-[200px]",children:D.name}),c.jsx(Q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive",onClick:()=>Ut(D.path),children:c.jsx(yi,{className:"w-3 h-3"})})]},D.path)),c.jsxs("div",{className:"relative",children:[c.jsx("input",{type:"file",className:"absolute inset-0 opacity-0 cursor-pointer",onChange:gt,disabled:St}),c.jsxs(Q,{variant:"outline",size:"sm",className:"w-full border-dashed",disabled:St,children:[St?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(jo,{className:"w-3 h-3 mr-2"}),St?"Uploading...":"Add Attachment"]})]})]}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Files will be attached to every draft generated by this rule."})]})]})]}),c.jsxs(Zr,{className:"p-6 border-t bg-secondary/5",children:[c.jsx(Q,{variant:"outline",onClick:()=>fe(!1),children:"Cancel"}),c.jsxs(Q,{onClick:Oi,disabled:Ni,children:[Ni?c.jsx(ft,{size:"sm",className:"mr-2"}):dn?c.jsx(Pr,{className:"w-4 h-4 mr-2"}):c.jsx(jo,{className:"w-4 h-4 mr-2"}),dn?"Save Changes":"Create Rule"]})]})]})}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(Po,{className:"w-5 h-5 text-primary"}),"Connected Accounts"]}),c.jsx(ca,{children:"Manage your email providers"})]}),c.jsxs(ws,{className:"space-y-4",children:[t.accounts.length===0?c.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No accounts connected yet"}):t.accounts.map(D=>c.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg bg-card",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[Rs(D.provider),c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium capitalize",children:D.provider}),c.jsx("p",{className:"text-xs text-muted-foreground",children:D.email_address})]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[D.is_active?c.jsx("span",{className:"text-xs text-emerald-600 bg-emerald-500/10 px-2 py-1 rounded-full",children:"Active"}):c.jsx("span",{className:"text-xs text-yellow-600 bg-yellow-500/10 px-2 py-1 rounded-full",children:"Inactive"}),c.jsx(Q,{variant:"outline",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>ml(D.id),children:c.jsx(au,{className:"w-4 h-4"})})]})]},D.id)),c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsxs(Q,{className:"w-full border-dashed",variant:"outline",onClick:ki,disabled:a||o,children:[a?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(jo,{className:"w-4 h-4 mr-2"}),"Connect Gmail Account"]}),c.jsxs(Q,{className:"w-full border-dashed",variant:"outline",onClick:hl,disabled:a||o,children:[o&&!d?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(jo,{className:"w-4 h-4 mr-2"}),"Connect Outlook Account"]})]}),d&&c.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg animate-in slide-in-from-top-2",children:[c.jsx("h4",{className:"font-medium text-blue-900 dark:text-blue-100 mb-2",children:"Microsoft Sign-In Required"}),c.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200 mb-4",children:d.message}),c.jsxs("div",{className:"flex flex-col gap-3",children:[c.jsx("div",{className:"flex items-center gap-2 bg-white dark:bg-black/20 p-2 rounded border border-blue-200 dark:border-blue-800",children:c.jsx("code",{className:"text-lg font-mono font-bold flex-1 text-center select-all",children:d.userCode})}),c.jsxs(Q,{variant:"default",className:"w-full bg-blue-600 hover:bg-blue-700",onClick:()=>window.open(d.verificationUri,"_blank"),children:["Open Microsoft Login",c.jsx(eu,{className:"w-4 h-4 ml-2"})]}),c.jsx("p",{className:"text-xs text-center text-muted-foreground mt-2",children:"Waiting for you to sign in..."})]})]})]})]}),c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(Mf,{className:"w-5 h-5 text-emerald-500"}),"Auto-Pilot Rules"]}),c.jsx(ca,{children:"Configure AI automation behavior"})]}),c.jsxs(ws,{className:"space-y-4",children:[c.jsxs("div",{className:"flex justify-between items-center py-3 border-b border-border",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium text-sm",children:"Auto-Trash Spam"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically delete emails categorized as spam"})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{const D=t.rules.find(ee=>ee.name==="Auto-Trash Spam");D&&Ci(D)},title:"Edit Logic",children:c.jsx(Xh,{className:"w-4 h-4 text-muted-foreground"})}),c.jsxs(Q,{variant:t.rules.find(D=>D.name==="Auto-Trash Spam")?.is_enabled?"default":"outline",size:"sm",onClick:nr,disabled:Xn==="auto_trash_spam",children:[Xn==="auto_trash_spam"?c.jsx(ft,{size:"sm",className:"mr-1"}):c.jsx(Nc,{className:"w-4 h-4 mr-1"}),t.rules.find(D=>D.name==="Auto-Trash Spam")?.is_enabled?"On":"Off"]})]})]}),c.jsxs("div",{className:"flex justify-between items-center py-3 border-b border-border",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium text-sm",children:"Smart Drafts"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Generate draft replies for important emails"})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{const D=t.rules.find(ee=>ee.name==="Smart Drafts");D&&Ci(D)},title:"Edit Logic",children:c.jsx(Xh,{className:"w-4 h-4 text-muted-foreground"})}),c.jsxs(Q,{variant:t.rules.find(D=>D.name==="Smart Drafts")?.is_enabled?"default":"outline",size:"sm",onClick:xa,disabled:Xn==="smart_drafts",children:[Xn==="smart_drafts"?c.jsx(ft,{size:"sm",className:"mr-1"}):c.jsx(Nc,{className:"w-4 h-4 mr-1"}),t.rules.find(D=>D.name==="Smart Drafts")?.is_enabled?"On":"Off"]})]})]}),c.jsxs("div",{className:"pt-2",children:[c.jsxs("div",{className:"flex items-center justify-between mb-2",children:[c.jsx("h4",{className:"text-sm font-medium",children:"Custom Rules"}),c.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>{hn(null),he(""),Cs(""),ks(""),Ns(["archive"]),As(""),er(""),ya([]),fe(!0)},children:[c.jsx(jo,{className:"w-4 h-4 mr-1"})," Add Rule"]})]}),t.rules.length===0&&c.jsx("p",{className:"text-xs text-muted-foreground text-center py-2 border border-dashed rounded-lg",children:"No custom rules yet"}),t.rules.length>0&&t.rules.filter(D=>D.name!=="Auto-Trash Spam"&&D.name!=="Smart Drafts").map(D=>{const ee=D.actions&&D.actions.length>0?D.actions:D.action?[D.action]:[];return c.jsxs("div",{className:"p-3 bg-secondary/30 rounded-lg mb-2",children:[c.jsxs("div",{className:"flex justify-between items-center mb-1",children:[c.jsxs("div",{children:[c.jsx("span",{className:"text-sm font-medium",children:D.name}),c.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["→ ",ee.join(" + ")]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>Ci(D),title:"Edit Rule",children:c.jsx(Xh,{className:"w-3.5 h-3.5 text-muted-foreground"})}),c.jsxs(Q,{variant:D.is_enabled?"default":"outline",size:"sm",onClick:()=>Pn(D.id),className:"h-7 px-2",children:[c.jsx(Nc,{className:"w-3.5 h-3.5 mr-1"}),D.is_enabled?"On":"Off"]}),c.jsx(Q,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>e.deleteRule(D.id),children:c.jsx(au,{className:"w-3 h-3"})})]})]}),D.instructions&&c.jsxs("p",{className:"text-[10px] text-muted-foreground italic border-t border-border/50 pt-1 mt-1 truncate",children:['"',D.instructions,'"']}),D.attachments&&D.attachments.length>0&&c.jsx("div",{className:"flex gap-1 mt-1",children:D.attachments.map(Ne=>c.jsxs("div",{className:"flex items-center gap-1 text-[9px] bg-blue-500/10 text-blue-400 px-1.5 py-0.5 rounded border border-blue-500/20",children:[c.jsx(x0,{className:"w-2.5 h-2.5"}),Ne.name]},Ne.path))})]},D.id)})]})]})]})]}),c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(fa,{className:"w-5 h-5 text-indigo-500"}),"Model Configuration"]}),c.jsx(ca,{children:"Configure Local LLM or API settings"})]}),c.jsxs(ws,{className:"space-y-4",children:[c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"LLM Provider"}),va?c.jsxs("div",{className:"h-10 border rounded-md flex items-center px-3 bg-muted/20",children:[c.jsx(ft,{size:"sm",className:"mr-2"}),c.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Discovering..."})]}):c.jsxs(c.Fragment,{children:[c.jsxs("select",{className:"w-full h-10 px-3 border rounded-md bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary",value:b.llm_provider||No,onChange:D=>Du(D.target.value),disabled:va,children:[c.jsx("option",{value:No,children:"RealTimeX AI (Default)"}),Ou.filter(D=>D.provider!==No).map(D=>c.jsx("option",{value:D.provider,children:D.name||D.provider},D.provider))]}),cl&&c.jsxs("div",{className:"text-[10px] text-amber-500 mt-1 px-1 bg-amber-50/50 rounded",children:["⚠️ ",cl]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Model Name"}),zt.length>0||va?c.jsxs("select",{className:"w-full h-10 px-3 border rounded-md bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary",value:b.llm_model||"",onChange:D=>S(ee=>({...ee,llm_model:D.target.value})),disabled:va,children:[!b.llm_model&&c.jsx("option",{value:"",children:"Select a model..."}),zt.map(D=>c.jsx("option",{value:D.id,children:D.name||D.id},D.id))]}):c.jsx(Ae,{placeholder:"e.g. gpt-4o-mini",value:b.llm_model||"",onChange:D=>S(ee=>({...ee,llm_model:D.target.value}))})]})]}),c.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(Po,{className:"w-4 h-4"}),"Local Storage Path (.eml)"]}),c.jsx(Ae,{placeholder:"e.g. ./data/emails or ~/.email-automator/emails",value:b.storage_path||"",onChange:D=>S(ee=>({...ee,storage_path:D.target.value}))}),c.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"Directory where raw emails (.eml) are saved. Default: ./data/emails (falls back to ~/.email-automator/emails if restricted)."})]}),c.jsxs("div",{className:"flex justify-between items-center py-3 border-t border-border/50",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium text-sm",children:"Intelligent Rename"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Use slugified-hyphenated filenames (e.g. 20240119-1430-subject-id.eml)"})]}),c.jsxs(Q,{variant:b.intelligent_rename?"default":"outline",size:"sm",onClick:()=>S(D=>({...D,intelligent_rename:!D.intelligent_rename})),children:[c.jsx(Nc,{className:"w-4 h-4 mr-1"}),b.intelligent_rename?"On":"Off"]})]}),c.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[c.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[c.jsx(fi,{className:"w-4 h-4"}),"Background Sync Interval (minutes)"]}),c.jsx(Ae,{type:"number",min:1,max:1440,value:b.sync_interval_minutes||5,onChange:D=>S(ee=>({...ee,sync_interval_minutes:parseInt(D.target.value,10)||5}))}),c.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"How often the system checks for new emails in the background."})]}),c.jsxs("div",{className:"flex justify-end mt-4 gap-2",children:[c.jsxs(Q,{variant:"outline",onClick:Mu,disabled:y,children:[y?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(fa,{className:"w-4 h-4 mr-2"}),"Check Connection"]}),c.jsxs(Q,{onClick:Di,disabled:p,children:[p?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Save Configuration"]})]})]})]}),c.jsx("div",{ref:ul,children:c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(Mf,{className:"w-5 h-5 text-orange-500"}),"Provider Credentials (Advanced)"]}),c.jsx(ca,{children:"Bring Your Own Keys (BYOK). Configure your own OAuth credentials here. Leave empty to use system defaults."})]}),c.jsxs(ws,{className:"space-y-6",children:[c.jsxs("div",{className:"space-y-4 border-b pb-4",children:[c.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[c.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"})," Google / Gmail"]}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),c.jsx(Ae,{type:"password",placeholder:"...apps.googleusercontent.com",value:b.google_client_id||"",onChange:D=>S(ee=>({...ee,google_client_id:D.target.value}))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client Secret"}),c.jsx(Ae,{type:"password",placeholder:"GOCSPX-...",value:b.google_client_secret||"",onChange:D=>S(ee=>({...ee,google_client_secret:D.target.value}))})]})]})]}),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[c.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-500"})," Microsoft / Outlook"]}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client ID"}),c.jsx(Ae,{type:"password",value:b.microsoft_client_id||"",onChange:D=>S(ee=>({...ee,microsoft_client_id:D.target.value}))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Client Secret (Optional)"}),c.jsx(Ae,{type:"password",value:b.microsoft_client_secret||"",onChange:D=>S(ee=>({...ee,microsoft_client_secret:D.target.value}))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("label",{className:"text-sm font-medium",children:"Tenant ID"}),c.jsx(Ae,{placeholder:"common",value:b.microsoft_tenant_id||"",onChange:D=>S(ee=>({...ee,microsoft_tenant_id:D.target.value}))})]})]})]}),c.jsx("div",{className:"flex justify-end mt-4",children:c.jsxs(Q,{onClick:Di,disabled:p,variant:"secondary",children:[p?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Pr,{className:"w-4 h-4 mr-2"}),"Save Credentials"]})})]})]})})]})}const s3="modulepreload",a3=function(t){return"/"+t},Eb={},r3=function(e,a,r){let o=Promise.resolve();if(a&&a.length>0){let g=function(y){return Promise.all(y.map(v=>Promise.resolve(v).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};var d=g;document.getElementsByTagName("link");const f=document.querySelector("meta[property=csp-nonce]"),p=f?.nonce||f?.getAttribute("nonce");o=g(a.map(y=>{if(y=a3(y),y in Eb)return;Eb[y]=!0;const v=y.endsWith(".css"),b=v?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${y}"]${b}`))return;const S=document.createElement("link");if(S.rel=v?"stylesheet":s3,v||(S.as="script"),S.crossOrigin="",S.href=y,p&&S.setAttribute("nonce",p),document.head.appendChild(S),v)return new Promise((T,j)=>{S.addEventListener("load",T),S.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${y}`)))})}))}function u(f){const p=new Event("vite:preloadError",{cancelable:!0});if(p.payload=f,window.dispatchEvent(p),!p.defaultPrevented)throw f}return o.then(f=>{for(const p of f||[])p.status==="rejected"&&u(p.reason);return e().catch(u)})};function i3(){const[t,e]=w.useState("profile"),{state:a,actions:r}=Si();w.useEffect(()=>{r.fetchProfile()},[]);const o=[{id:"profile",label:"Profile",icon:Db},{id:"security",label:"Security",icon:Am},{id:"database",label:"Supabase",icon:Po}];return c.jsxs("div",{className:"max-w-4xl mx-auto space-y-6 animate-in fade-in duration-500",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Account Settings"}),c.jsx("p",{className:"text-muted-foreground",children:"Manage your profile, security, and connection preferences."})]}),c.jsxs("div",{className:"flex flex-col md:flex-row gap-8",children:[c.jsxs("aside",{className:"w-full md:w-64 flex flex-col justify-between",children:[c.jsx("nav",{className:"space-y-1",children:o.map(u=>{const d=u.icon,f=t===u.id;return c.jsxs("button",{onClick:()=>e(u.id),className:`w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${f?"bg-primary text-primary-foreground":"hover:bg-secondary text-muted-foreground"}`,children:[c.jsx(d,{className:"w-4 h-4"}),u.label]},u.id)})}),c.jsxs("div",{className:"mt-auto space-y-1",children:[c.jsxs("button",{onClick:async()=>{await et.auth.signOut(),oe.success("Logged out successfully"),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:[c.jsx(fE,{className:"w-4 h-4"}),"Sign Out"]}),c.jsxs("div",{className:"px-4 py-4 border-t border-border/40 text-center md:text-left",children:[c.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/50 uppercase tracking-widest mb-1",children:"Version"}),c.jsxs("p",{className:"text-xs font-mono text-muted-foreground/70",children:["v","2.11.3"]})]})]})]}),c.jsxs("div",{className:"flex-1 space-y-6",children:[t==="profile"&&c.jsx(o3,{}),t==="security"&&c.jsx(l3,{}),t==="database"&&c.jsx(c3,{})]})]})]})}function o3(){const{state:t,actions:e}=Si(),[a,r]=w.useState(""),[o,u]=w.useState(""),[d,f]=w.useState(!1),[p,g]=w.useState(!1),[y,v]=w.useState(Gn.isEnabled());w.useEffect(()=>{t.profile&&(r(t.profile.first_name||""),u(t.profile.last_name||""))},[t.profile]);const b=()=>{const j=!y;Gn.setEnabled(j),v(j),j?(Gn.playSuccess(),oe.success("Sound effects enabled")):oe.info("Sound effects disabled")},S=async()=>{f(!0);const j=await e.updateProfile({first_name:a,last_name:o});f(!1),j&&oe.success("Profile updated")},T=async j=>{const E=j.target.files?.[0];if(!(!E||!t.user)){g(!0);try{const C=E.name.split(".").pop(),M=`${t.user.id}/avatar.${C}`,{data:k,error:V}=await et.storage.from("avatars").upload(M,E,{upsert:!0});if(V)throw V;const{data:{publicUrl:q}}=et.storage.from("avatars").getPublicUrl(M);await e.updateProfile({avatar_url:q}),oe.success("Avatar updated")}catch(C){console.error("Avatar upload error:",C),oe.error("Failed to upload avatar")}finally{g(!1)}}};return c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsx(bs,{children:"Profile Information"}),c.jsx(ca,{children:"Update your personal details and avatar."})]}),c.jsxs(ws,{className:"space-y-6",children:[c.jsxs("div",{className:"flex flex-col items-center sm:flex-row sm:items-start gap-6",children:[c.jsxs("div",{className:"relative group",children:[c.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?c.jsx("img",{src:t.profile.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):c.jsx(Db,{className:"w-12 h-12 text-muted-foreground"})}),c.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:[c.jsx(NT,{className:"w-6 h-6 text-white"}),c.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:T,disabled:p})]}),p&&c.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 rounded-full",children:c.jsx(ft,{size:"sm"})})]}),c.jsxs("div",{className:"flex-1 space-y-4 w-full",children:[c.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"first-name",children:"First Name"}),c.jsx(Ae,{id:"first-name",value:a,onChange:j=>r(j.target.value),placeholder:"John"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"last-name",children:"Last Name"}),c.jsx(Ae,{id:"last-name",value:o,onChange:j=>u(j.target.value),placeholder:"Doe"})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"email",children:"Email Address"}),c.jsx(Ae,{id:"email",value:t.profile?.email||"",disabled:!0,className:"bg-secondary/50"}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Email cannot be changed directly."})]})]})]}),c.jsxs("div",{className:"pt-6 border-t flex items-center justify-between",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("label",{className:"text-sm font-medium",children:"Sound & Haptics"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Audio feedback when processing emails and completing tasks."})]}),c.jsxs(Q,{variant:y?"default":"outline",size:"sm",onClick:b,className:"gap-2",children:[y?c.jsx(XE,{className:"w-4 h-4"}):c.jsx(WE,{className:"w-4 h-4"}),y?"Enabled":"Disabled"]})]}),c.jsx("div",{className:"flex justify-end pt-4 border-t",children:c.jsxs(Q,{onClick:S,disabled:d,children:[d?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(AE,{className:"w-4 h-4 mr-2"}),"Save Changes"]})})]})]})}function l3(){const[t,e]=w.useState(""),[a,r]=w.useState(""),[o,u]=w.useState(!1),d=async()=>{if(!t){oe.error("Please enter a new password");return}if(t!==a){oe.error("Passwords do not match");return}if(t.length<6){oe.error("Password must be at least 6 characters");return}u(!0);try{const{api:f}=await r3(async()=>{const{api:g}=await Promise.resolve().then(()=>LC);return{api:g}},void 0),p=await f.changePassword(t);p.success?(oe.success("Password changed successfully"),e(""),r("")):oe.error(p.error?.message||"Failed to change password")}catch{oe.error("An error occurred")}finally{u(!1)}};return c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsx(bs,{children:"Security"}),c.jsx(ca,{children:"Manage your password and account security."})]}),c.jsxs(ws,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"new-password",children:"New Password"}),c.jsx(Ae,{id:"new-password",type:"password",value:t,onChange:f=>e(f.target.value),placeholder:"••••••••"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Ht,{htmlFor:"confirm-password",children:"Confirm New Password"}),c.jsx(Ae,{id:"confirm-password",type:"password",value:a,onChange:f=>r(f.target.value),placeholder:"••••••••"})]}),c.jsx("div",{className:"flex justify-end pt-4 border-t",children:c.jsxs(Q,{onClick:d,disabled:o,children:[o?c.jsx(ft,{size:"sm",className:"mr-2"}):c.jsx(Nm,{className:"w-4 h-4 mr-2"}),"Update Password"]})})]})]})}function c3(){const[t,e]=w.useState(!1),[a,r]=w.useState(null),o=wi(),u=MC();w.useEffect(()=>{o&&fp(et).then(r)},[]);const d=()=>{confirm("Are you sure you want to disconnect from this Supabase project? This will log you out and clear local configuration.")&&(OC(),window.location.reload())};return c.jsxs(c.Fragment,{children:[c.jsxs(Vt,{children:[c.jsxs(xs,{children:[c.jsxs(bs,{className:"flex items-center gap-2",children:[c.jsx(Po,{className:"w-5 h-5 text-primary"}),"Supabase Connection"]}),c.jsx(ca,{children:"Manage your database configuration (BYOK - Bring Your Own Keys)."})]}),c.jsx(ws,{className:"space-y-6",children:o?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-xl bg-emerald-500/5 border-emerald-500/20",children:[c.jsx(Qc,{className:"w-6 h-6 text-emerald-500 mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-1",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("p",{className:"font-semibold text-emerald-700 dark:text-emerald-400",children:"Connected"}),a?.latestMigrationTimestamp&&c.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 ",a.latestMigrationTimestamp]})]}),c.jsx("p",{className:"text-sm font-mono break-all opacity-80",children:o.url})]})]}),u==="env"&&c.jsxs(Wo,{className:"bg-amber-500/5 border-amber-500/20",children:[c.jsx(nu,{className:"h-4 w-4 text-amber-500"}),c.jsx(Zo,{className:"text-amber-700 dark:text-amber-400 text-xs",children:"Configuration is loaded from environment variables. Use the UI to override them."})]}),c.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[c.jsxs(Q,{variant:"outline",onClick:()=>e(!0),className:"w-full",children:[c.jsx(nu,{className:"w-4 h-4 mr-2"}),"Change Connection"]}),u==="ui"&&c.jsxs(Q,{variant:"outline",onClick:d,className:"w-full text-destructive hover:bg-destructive/10",children:[c.jsx(au,{className:"w-4 h-4 mr-2"}),"Clear Config"]})]}),c.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[c.jsx(Ht,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Anon Public Key"}),c.jsxs("div",{className:"p-2 bg-secondary/50 rounded-lg font-mono text-xs break-all",children:[o.anonKey.substring(0,20),"...",o.anonKey.substring(o.anonKey.length-10)]})]})]}):c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center space-y-4",children:[c.jsx(qT,{className:"w-12 h-12 text-destructive opacity-20"}),c.jsxs("div",{children:[c.jsx("p",{className:"font-medium",children:"No Connection Detected"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure a Supabase project to get started."})]}),c.jsxs(Q,{onClick:()=>e(!0),children:[c.jsx(Po,{className:"w-4 h-4 mr-2"}),"Setup Supabase"]})]})})]}),c.jsx(dS,{open:t,onComplete:()=>e(!1),canClose:!0})]})}function u3({length:t=6,value:e,onChange:a,onComplete:r,disabled:o=!1,error:u=!1}){const d=w.useRef([]),[f,p]=w.useState(null),g=(b,S)=>{const T=S.replace(/[^0-9]/g,"");if(T.length===0){const C=e.split("");C[b]=" ",e.split("");let M=e.split("");b<M.length&&M.splice(b,1);const k=M.join("");a(k),b>0&&d.current[b-1]?.focus();return}e.split("");const j=[...e];j[b]=T[0],a(j.join("")),b<t-1&&d.current[b+1]?.focus();const E=j.join("");E.length===t&&r&&r(E)},y=(b,S)=>{S.key==="Backspace"&&!e[b]&&b>0||S.key==="ArrowLeft"&&b>0?d.current[b-1]?.focus():S.key==="ArrowRight"&&b<t-1&&d.current[b+1]?.focus()},v=b=>{b.preventDefault();const T=b.clipboardData.getData("text/plain").replace(/[^0-9]/g,"").slice(0,t);a(T);const j=Math.min(T.length,t-1);d.current[j]?.focus(),T.length===t&&r&&r(T)};return c.jsx("div",{className:"flex gap-2 justify-center",children:Array.from({length:t}).map((b,S)=>c.jsx(Ae,{ref:T=>{d.current[S]=T},type:"text",inputMode:"numeric",maxLength:1,value:e[S]||"",onChange:T=>g(S,T.target.value),onKeyDown:T=>y(S,T),onPaste:v,onFocus:()=>p(S),onBlur:()=>p(null),disabled:o,className:Te("w-10 h-10 sm:w-12 sm:h-12 text-center text-lg font-semibold px-0",u&&"border-destructive focus-visible:ring-destructive",f===S&&"ring-2 ring-ring"),"aria-label":`Digit ${S+1}`},S))})}function d3({onSuccess:t,onConfigure:e,isInitialized:a}){const[r,o]=w.useState(""),[u,d]=w.useState(""),[f,p]=w.useState(""),[g,y]=w.useState(""),[v,b]=w.useState(!1),[S,T]=w.useState(a===void 0),[j,E]=w.useState(a??!1),[C,M]=w.useState(""),[k,V]=w.useState(!1),[q,G]=w.useState("password"),[$,B]=w.useState("email"),[W,me]=w.useState(""),[ue,pe]=w.useState(!1);w.useEffect(()=>{a===void 0?ze():pe(!a)},[a]);const ze=async()=>{try{const{data:A,error:H}=await et.from("init_state").select("is_initialized");if(H){if(H.code==="42P01"){console.info("[Login] init_state relation missing - fresh database detected."),E(!1),pe(!0);return}console.warn("[Login] Init check error:",H),E(!1),pe(!0),M(H.message);return}const F=A&&A.length>0&&A[0].is_initialized>0;E(F),pe(!F)}catch(A){console.warn("[Login] Init check exception:",A),E(!1),pe(!0),M(A.message||"Connection failed")}finally{T(!1)}},Fe=async A=>{A.preventDefault(),b(!0),M("");try{if(j){if(q==="password"){const{error:H}=await et.auth.signInWithPassword({email:r,password:u});if(H)throw H;oe.success("Logged in successfully"),t?.()}else if($==="email"){const{error:H}=await et.auth.signInWithOtp({email:r,options:{shouldCreateUser:!1}});if(H)throw H;B("verify"),oe.success("Validation code sent to your email")}}else{const{data:H,error:F}=await et.functions.invoke("setup",{body:{email:r,password:u,first_name:f,last_name:g}});if(F||!H){if(F?.message?.includes("First user already exists")){oe.info("System already initialized. Please log in."),E(!0);return}throw new Error(F?.message||"Failed to create admin account")}oe.success("Admin account created! Signing you in...");const{error:xe}=await et.auth.signInWithPassword({email:r,password:u});if(xe)throw xe;E(!0),t?.()}}catch(H){M(H?.message||"Authentication failed"),console.error("[Login] Error:",H)}finally{b(!1)}},Re=async()=>{b(!0),M("");try{const{data:A,error:H}=await et.auth.verifyOtp({email:r,token:W,type:"magiclink"});if(H)throw H;if(!A.session)throw new Error("Failed to create session");oe.success("Logged in successfully"),t?.()}catch(A){M(A?.message||"Invalid code")}finally{b(!1)}};return S?c.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:c.jsxs("div",{className:"flex flex-col items-center gap-4",children:[c.jsx(Pt,{className:"w-10 h-10 animate-spin text-primary"}),c.jsx("p",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground",children:"Initializing Engine..."})]})}):c.jsxs("div",{className:"min-h-screen bg-background flex items-center justify-center p-8 relative overflow-hidden",children:[c.jsxs("div",{className:"absolute top-6 right-6 flex items-center gap-4 z-50",children:[e&&c.jsxs(Q,{variant:"ghost",size:"sm",onClick:e,className:"text-xs font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all",children:[c.jsx(nu,{className:"w-3.5 h-3.5 mr-2"}),"Configure"]}),c.jsx(Zb,{})]}),c.jsxs(vs.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full max-w-md relative z-10",children:[c.jsxs("div",{className:"glass p-10 space-y-8 relative overflow-hidden",children:[c.jsxs("div",{className:"text-center space-y-3",children:[c.jsx("div",{className:"mx-auto w-16 h-16 bg-primary rounded-2xl flex items-center justify-center mb-6",children:c.jsx(mp,{className:"w-10 h-10 text-primary-foreground"})}),c.jsx("h2",{className:"text-3xl font-black italic tracking-tighter uppercase text-foreground",children:ue?"Initialize Automator":"Secure Login"}),c.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-[0.2em] uppercase",children:ue?"Create your primary administrator account":q==="otp"?"Magic link authentication":"Personal Access Key Required"})]}),c.jsxs("form",{onSubmit:Fe,className:"space-y-4",children:[c.jsxs(K1,{mode:"wait",children:[ue&&c.jsxs(vs.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"First Name"}),c.jsx(Ae,{value:f,onChange:A=>p(A.target.value),required:ue,placeholder:"John",className:"bg-background"})]}),c.jsxs("div",{className:"space-y-1",children:[c.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Last Name"}),c.jsx(Ae,{value:g,onChange:A=>y(A.target.value),required:ue,placeholder:"Doe",className:"bg-background"})]})]},"signup-fields"),q==="password"||$==="email"?c.jsxs(vs.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[c.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Email Coordinates"}),c.jsxs("div",{className:"relative",children:[c.jsx(tu,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),c.jsx(Ae,{type:"email",placeholder:"admin@automator.ai",value:r,onChange:A=>o(A.target.value),required:!0,className:"pl-10 bg-background",autoComplete:"email",disabled:$==="verify"})]})]},"email-field"):null,q==="password"&&c.jsxs(vs.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[c.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Access Password"}),c.jsxs("div",{className:"relative",children:[c.jsx(v0,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),c.jsx(Ae,{type:k?"text":"password",placeholder:"••••••••",value:u,onChange:A=>d(A.target.value),required:!0,minLength:6,className:"pl-10 pr-10 bg-background",autoComplete:ue?"new-password":"current-password"}),c.jsx("button",{type:"button",onClick:()=>V(!k),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground/30 hover:text-primary transition-colors",children:k?c.jsx(JT,{size:16}):c.jsx(Rb,{size:16})})]})]},"password-field"),q==="otp"&&$==="verify"&&c.jsxs(vs.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"space-y-6 py-4",children:[c.jsx("div",{className:"flex justify-center",children:c.jsx(u3,{value:W,onChange:me,length:6,onComplete:()=>{}})}),c.jsx(Q,{type:"button",variant:"link",className:"w-full text-[10px] font-bold uppercase tracking-widest text-primary/60",onClick:()=>B("email"),children:"Change Coordinates"}),c.jsxs(Q,{type:"button",onClick:Re,disabled:v||W.length!==6,className:"w-full h-12 shadow-md",children:[v?c.jsx(Pt,{className:"w-5 h-5 animate-spin mr-2"}):c.jsx(Am,{size:18,className:"mr-2"}),"Verify Access"]})]},"otp-field")]}),C&&c.jsxs(vs.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:[c.jsx(js,{size:14,className:"mt-0.5 shrink-0"}),c.jsx("p",{children:C})]}),q!=="otp"||$==="email"?c.jsx(Q,{type:"submit",disabled:v||!r||q==="password"&&!u,className:"w-full h-12 shadow-md mt-4",children:v?c.jsx(Pt,{className:"w-5 h-5 animate-spin"}):c.jsxs(c.Fragment,{children:[ue?c.jsx(KE,{className:"w-5 h-5 mr-2"}):q==="otp"?c.jsx(tu,{className:"w-5 h-5 mr-2"}):c.jsx(dE,{className:"w-5 h-5 mr-2"}),ue?"Initialize Master":q==="otp"?"Send Magic Link":"Open Dashboard"]})}):null]}),c.jsxs("div",{className:"space-y-4 pt-4 border-t border-border/10",children:[!ue&&c.jsx("div",{className:"flex flex-col gap-2",children:q==="password"?c.jsxs("button",{type:"button",onClick:()=>{G("otp"),B("email"),M("")},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:[c.jsx(v0,{size:14})," Magic Link Login"]}):c.jsxs("button",{type:"button",onClick:()=>{G("password"),M("")},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:[c.jsx(Tm,{size:14})," Password Access"]})}),c.jsxs("p",{className:"text-center text-[10px] text-muted-foreground font-bold uppercase tracking-wider",children:[ue?"Already have an account?":"Need a new account?"," "," ",c.jsx("button",{onClick:()=>{pe(!ue),G("password"),M("")},className:"text-primary hover:underline ml-1",children:ue?"Login Instead":"Create Account"})]})]})]}),c.jsx("div",{className:"mt-8 text-center",children:c.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/30 uppercase tracking-[0.4em]",children:"Powered by RealTimeX Intelligence"})})]})]})}function h3({status:t,onDismiss:e,onLearnMore:a}){const[r,o]=w.useState(!0);if(!r)return null;const u=()=>{P5(),o(!1),e?.()},d=()=>{a?a():(navigator.clipboard.writeText("npx email-automator migrate"),oe.success("Command copied to clipboard"))};return c.jsx("div",{className:"fixed right-4 top-16 z-50 max-w-sm animate-in slide-in-from-top-5",children:c.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:c.jsxs("div",{className:"flex items-start gap-3",children:[c.jsx(pi,{className:"h-5 w-5 flex-shrink-0 text-yellow-600 dark:text-yellow-500 mt-0.5"}),c.jsxs("div",{className:"flex-1 space-y-2",children:[c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("p",{className:"text-sm font-medium text-yellow-900 dark:text-yellow-100",children:"Database Update Required"}),c.jsxs(Q,{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:u,children:[c.jsx(yi,{className:"h-3 w-3"}),c.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),c.jsxs("p",{className:"text-xs text-yellow-800 dark:text-yellow-200",children:["Your app version (",t.appVersion,") requires a database schema update."]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Q,{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:d,children:"Update Now"}),c.jsx(Q,{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:u,children:"Remind Later"})]})]})]})})})}function f3({open:t,onOpenChange:e,status:a}){const r=wi(),[o,u]=w.useState(!1),[d,f]=w.useState([]),[p,g]=w.useState(""),y=w.useRef(null),v=w.useMemo(()=>{const S=r?.url;if(!S)return"";try{return new URL(S).hostname.split(".")[0]||""}catch{return""}},[r?.url]);w.useEffect(()=>{y.current&&y.current.scrollIntoView({behavior:"smooth"})},[d]);const b=async()=>{if(!v){oe.error("Missing Project ID");return}if(!p){oe.error("Provide a Supabase Personal Access Token.");return}u(!0),f(["Initializing migration..."]);try{const S=async C=>{const M=new TextDecoder;let k="",V=null;const q=G=>{const $=G.trim();if(!(!$||!$.startsWith("data: ")))try{const B=$.substring(6),W=JSON.parse(B);W.type==="done"?(W.data==="success"||W.data==="failed")&&(V=W.data==="success"?"success":"failure"):W.data&&f(me=>[...me,W.data])}catch(B){console.error("Failed to parse SSE line:",$,B)}};for(;;){const{done:G,value:$}=await C.read();if(G)break;k+=M.decode($,{stream:!0});const B=k.split(`
|
|
105
|
+
`);k=B.pop()||"",B.forEach(q)}return k+=M.decode(),k&&q(k),V};f(C=>[...C,"","📦 Database Migration & Edge Functions Deployment"]);const T=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:v,accessToken:p})});if(!T.ok)throw new Error(`Migration failed: ${T.status} ${T.statusText}`);const j=T.body?.getReader();if(!j)throw new Error("No migration response stream received.");if(await S(j)!=="success")throw new Error("Migration did not complete successfully");f(C=>[...C,"","═".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(S){console.error(S),f(T=>[...T,"",`❌ Error: ${S instanceof Error?S.message:String(S)}`]),oe.error("Setup failed. Check logs for details.")}finally{u(!1)}};return c.jsx(li,{open:t,onOpenChange:S=>!o&&e(S),children:c.jsxs(ci,{className:"max-h-[90vh] sm:max-w-5xl overflow-y-auto",children:[c.jsxs(ui,{children:[c.jsxs(di,{className:"flex items-center gap-2 text-xl",children:[c.jsx(pi,{className:"h-6 w-6 text-red-700 dark:text-red-600"}),"Database Setup Required"]}),c.jsxs(hi,{children:["Your application version (",a.appVersion,") requires database migration and Edge Functions deployment to function correctly."]})]}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs(Wo,{children:[c.jsx(mi,{className:"h-4 w-4"}),c.jsxs(Zo,{children:[c.jsx("strong",{children:"Why is this needed?"}),c.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[c.jsxs("li",{children:["Updates your database schema to match version ",a.appVersion]}),c.jsx("li",{children:"Deploys Edge Functions (API endpoints) to your Supabase project"}),c.jsx("li",{children:"Enables new features and performance improvements"}),c.jsx("li",{children:"Your existing data will be preserved (safe migration)"})]})]})]}),c.jsxs("div",{className:"space-y-4 py-2",children:[c.jsxs("div",{className:"rounded-lg border bg-card text-card-foreground shadow-sm p-6",children:[c.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Automated Setup"}),c.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."}),c.jsxs("div",{className:"grid gap-4",children:[c.jsxs("div",{className:"grid gap-2",children:[c.jsx(Ht,{htmlFor:"project-id",children:"Supabase Project ID"}),c.jsx(Ae,{id:"project-id",value:v,disabled:!0,readOnly:!0,className:"bg-muted"})]}),c.jsxs("div",{className:"grid gap-2",children:[c.jsxs("div",{className:"flex justify-between items-center",children:[c.jsx(Ht,{htmlFor:"access-token",children:"Access Token"}),c.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 ",c.jsx(eu,{className:"h-3 w-3"})]})]}),c.jsx(Ae,{id:"access-token",type:"password",placeholder:"sbp_...",value:p,onChange:S=>g(S.target.value),disabled:o}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"This token is used only for this migration and is not stored."})]}),c.jsx(Q,{onClick:b,disabled:o||!p,className:"w-full",children:o?c.jsxs(c.Fragment,{children:[c.jsx(Pt,{className:"mr-2 h-4 w-4 animate-spin"}),"Running Setup..."]}):c.jsxs(c.Fragment,{children:[c.jsx(su,{className:"mr-2 h-4 w-4"}),"Start Setup"]})})]})]}),c.jsxs("div",{className:"rounded-lg border bg-black text-white font-mono text-xs p-4 h-64 overflow-y-auto",children:[d.length===0?c.jsx("div",{className:"text-gray-500 italic",children:"Waiting to start..."}):d.map((S,T)=>c.jsx("div",{className:"mb-1 whitespace-pre-wrap",children:S},T)),c.jsx("div",{ref:y})]})]}),c.jsxs(Wo,{className:"border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/20",children:[c.jsx(pi,{className:"h-4 w-4 text-red-700 dark:text-red-600"}),c.jsxs(Zo,{children:[c.jsx("strong",{children:"Troubleshooting"}),c.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[c.jsxs("li",{children:["Ensure your Access Token has ",c.jsx("code",{children:"read"})," and ",c.jsx("code",{children:"write"})," permissions."]}),c.jsx("li",{children:"Verify that your Supabase Project ID is correct and active."})]})]})]})]}),c.jsx(Zr,{children:c.jsx(Q,{type:"button",variant:"outline",onClick:()=>e(!1),disabled:o,children:"Close"})})]})})}function m3(){const[t,e]=w.useState([]),{isExpanded:a,setIsExpanded:r}=ww(),[o,u]=w.useState({});w.useEffect(()=>{d();const y=et.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},v=>{const b=v.new;b.event_type==="error"&&u(S=>({...S,[b.id]:!0})),e(S=>{const T=[b,...S];return b.details?.is_completion&&a&&setTimeout(()=>{r(!1)},3e3),T.length>100?T.slice(0,100):T})}).subscribe();return()=>{et.removeChannel(y)}},[a,r]);const d=async()=>{const{data:y}=await et.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(50);y&&e(y)},f=y=>{u(v=>({...v,[y]:!v[y]}))},p=y=>{if(y.details?.is_completion)return c.jsx(Qc,{className:"w-3 h-3 text-emerald-500"});switch(y.event_type){case"analysis":return c.jsx(Lo,{className:"w-3 h-3 text-purple-500"});case"action":return c.jsx(Vo,{className:"w-3 h-3 text-emerald-500"});case"error":return c.jsx(pi,{className:"w-3 h-3 text-red-500"});default:return c.jsx(mi,{className:"w-3 h-3 text-blue-500"})}},g=y=>new Date(y).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});return a?c.jsxs(Vt,{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:[c.jsxs(xs,{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:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(su,{className:"w-4 h-4 text-primary"}),c.jsx(bs,{className:"text-sm font-mono font-bold",children:"Agent Terminal"}),c.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-green-600 dark:text-green-400 bg-green-500/10 px-2 py-0.5 rounded-full border border-green-500/20 font-bold",children:[c.jsx(fT,{className:"w-3 h-3"}),"LIVE"]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 text-[10px] font-mono hover:bg-secondary",onClick:()=>e([]),children:"Clear"}),c.jsx(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-secondary",onClick:()=>r(!1),children:c.jsx(gE,{className:"w-4 h-4"})})]})]}),c.jsxs(ws,{className:"flex-1 overflow-y-auto p-4 font-mono text-xs space-y-6 custom-scrollbar",children:[t.length===0&&c.jsx("div",{className:"text-center text-muted-foreground py-20 italic",children:"Waiting for agent activity..."}),t.map((y,v)=>c.jsxs("div",{className:"relative pl-8 animate-in fade-in slide-in-from-top-2 duration-300",children:[v!==t.length-1&&c.jsx("div",{className:"absolute left-[13px] top-7 bottom-[-24px] w-[1px] bg-border"}),c.jsx("div",{className:Te("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",y.event_type==="error"&&"border-red-500/50 bg-red-500/5",y.event_type==="analysis"&&"border-purple-500/50 bg-purple-500/5",y.event_type==="action"&&"border-emerald-500/50 bg-emerald-500/5",y.details?.is_completion&&"border-emerald-500/50 bg-emerald-500/5"),children:p(y)}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsxs("div",{className:"flex items-center justify-between group",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:Te("font-bold uppercase tracking-tight text-[10px]",y.event_type==="info"&&"text-muted-foreground",y.event_type==="analysis"&&"text-purple-600 dark:text-purple-400",y.event_type==="action"&&"text-emerald-600 dark:text-emerald-400",y.event_type==="error"&&"text-red-600 dark:text-red-400"),children:y.agent_state}),c.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:g(y.created_at)})]}),(y.details?.system_prompt||y.details?._raw_response||y.details?.raw_response)&&c.jsxs(Q,{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:()=>f(y.id),children:[o[y.id]?c.jsx(UT,{className:"w-3 h-3 mr-1"}):c.jsx(RT,{className:"w-3 h-3 mr-1"}),"Details"]})]}),y.event_type==="analysis"&&y.details?c.jsxs("div",{className:"bg-purple-500/5 border border-purple-500/10 rounded-lg p-3 space-y-2",children:[c.jsxs("div",{className:"flex gap-2",children:[c.jsx("span",{className:Te("px-1.5 py-0.5 rounded text-[9px] font-bold border",y.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:y.details.is_useless?"USELESS":"RELEVANT"}),c.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:y.details.category})]}),c.jsxs("p",{className:"text-foreground/90 italic leading-relaxed",children:['"',y.details.summary,'"']}),y.details.suggested_actions&&y.details.suggested_actions.length>0&&c.jsx("div",{className:"pt-1 flex items-center gap-2 flex-wrap",children:y.details.suggested_actions.map(b=>c.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:[c.jsx(Vo,{className:"w-2.5 h-2.5"}),b]},b))}),y.details.usage&&c.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:c.jsxs("span",{children:["Tokens: ",y.details.usage.prompt_tokens," (in) + ",y.details.usage.completion_tokens," (out) = ",c.jsx("span",{className:"text-purple-500 font-bold",children:y.details.usage.total_tokens})]})})]}):y.event_type==="action"&&y.details?c.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/10 rounded-lg p-3",children:[c.jsx("p",{className:"text-emerald-600 dark:text-emerald-400 font-bold mb-1 uppercase text-[9px] tracking-widest",children:"Execution Complete"}),c.jsxs("p",{className:"text-foreground font-medium",children:[y.details.action==="delete"&&"Moved to Trash",y.details.action==="archive"&&"Archived Email",y.details.action==="draft"&&"Drafted Reply",y.details.action==="read"&&"Marked as Read",y.details.action==="star"&&"Starred Email",!["delete","archive","draft","read","star"].includes(y.details.action)&&y.details.action]}),y.details.reason&&c.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 flex items-center gap-1",children:[c.jsx(mi,{className:"w-3 h-3"}),y.details.reason]})]}):y.event_type==="error"&&y.details?c.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 y.details.error=="object"?y.details.error.message||JSON.stringify(y.details.error):y.details.error}):y.details?.is_completion?c.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-lg p-3 space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 dark:text-emerald-400 font-bold uppercase text-[9px] tracking-[0.2em]",children:[c.jsx(Qc,{className:"w-3.5 h-3.5"}),"Batch Sync Finished"]}),c.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-1",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Processed"}),c.jsx("p",{className:"text-sm font-bold",children:y.details.total_processed||0})]}),c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Actions"}),c.jsx("p",{className:"text-sm font-bold text-emerald-500",children:(y.details.deleted||0)+(y.details.drafted||0)})]})]}),y.details.errors>0&&c.jsxs("p",{className:"text-[10px] text-red-500 font-bold pt-1 border-t border-emerald-500/10",children:["⚠️ ",y.details.errors," items failed to process."]})]}):c.jsx("p",{className:"text-muted-foreground leading-relaxed",children:y.details?.message||JSON.stringify(y.details)}),o[y.id]&&c.jsxs("div",{className:"mt-2 space-y-3 animate-in fade-in zoom-in-95 duration-200",children:[y.details?.system_prompt&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[c.jsx(la,{className:"w-3 h-3"})," System Prompt"]}),c.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:c.jsx("pre",{className:"whitespace-pre-wrap break-words text-[10px] leading-normal text-muted-foreground select-all",children:y.details.system_prompt})})]}),y.details?.content_preview&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[c.jsx(la,{className:"w-3 h-3"})," Input Content (Cleaned)"]}),c.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border",children:c.jsx("p",{className:"whitespace-pre-wrap break-words text-[10px] text-muted-foreground",children:y.details.content_preview})})]}),y.details?._raw_response&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[c.jsx(la,{className:"w-3 h-3"})," Raw LLM JSON Output"]}),c.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:c.jsx("pre",{className:"text-[10px] text-muted-foreground select-all",children:JSON.stringify(JSON.parse(y.details._raw_response),null,2)})})]}),y.details?.raw_response&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[c.jsx(la,{className:"w-3 h-3"})," Raw Response (from Error)"]}),c.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:c.jsx("pre",{className:"text-[10px] text-muted-foreground select-all whitespace-pre-wrap",children:typeof y.details.raw_response=="object"?JSON.stringify(y.details.raw_response,null,2):y.details.raw_response})})]})]})]})]},y.id))]})]}):c.jsx("div",{className:"fixed bottom-4 right-4 z-50",children:c.jsxs(Q,{onClick:()=>r(!0),className:"shadow-lg bg-primary text-primary-foreground hover:opacity-90 border border-border",children:[c.jsx(su,{className:"w-4 h-4 mr-2"}),"Live Activity",t.length>0&&c.jsxs("span",{className:"ml-2 flex h-2 w-2 relative",children:[c.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"}),c.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-green-500"})]})]})})}function p3(){const{state:t,isSubscribed:e,actions:a}=Si(),[r,o]=w.useState(null),[u,d]=w.useState(!0),[f,p]=w.useState(!1),[g,y]=w.useState(!0),[v,b]=w.useState("dashboard"),[S,T]=w.useState(!1),[j,E]=w.useState(null),[C,M]=w.useState(!1),[k,V]=w.useState(!1),[q,G]=w.useState(!1);if(w.useEffect(()=>{const me=new URLSearchParams(window.location.search).get("code");me&&!S&&(async()=>{T(!0);try{const pe=await Ue.connectGmail(me);if(pe.data?.success)oe.success("Gmail connected successfully!"),window.opener?setTimeout(()=>window.close(),1500):(window.history.replaceState({},"",window.location.pathname),a.fetchAccounts());else{const ze=typeof pe.error=="string"?pe.error:pe.error?.message;oe.error(ze||"Failed to connect Gmail")}}catch{oe.error("Connection failed")}finally{T(!1)}})()},[]),S)return c.jsx(uu,{text:"Connecting account..."});w.useEffect(()=>{(async()=>{if(!wi()){p(!0),d(!1);return}try{const{data:ze,error:Fe}=await et.from("init_state").select("is_initialized").single();Fe?(console.warn("[App] Init check error (might be fresh DB):",Fe),Fe.code==="42P01"&&y(!1)):y(ze.is_initialized>0);const{data:{session:Re}}=await et.auth.getSession();if(o(Re?.user??null),Re?.user){const A=await fp(et);E(A.needsMigration?A:null),A.needsMigration&&!L5()&&M(!0)}}catch(ze){console.error("[App] Status check failed:",ze),ze instanceof Error&&ze.message.includes("Invalid API key")&&p(!0)}finally{d(!1)}})();const{data:{subscription:me}}=et.auth.onAuthStateChange((pe,ze)=>{o(ze?.user??null),ze||(E(null),M(!1))}),ue=()=>{if(Gn.isEnabled()){const pe=new(window.AudioContext||window.webkitAudioContext);pe.state==="suspended"&&pe.resume()}window.removeEventListener("click",ue),window.removeEventListener("keydown",ue)};return window.addEventListener("click",ue),window.addEventListener("keydown",ue),()=>{me.unsubscribe(),window.removeEventListener("click",ue),window.removeEventListener("keydown",ue)}},[]),w.useEffect(()=>{r&&(a.fetchAccounts(),a.fetchRules(),a.fetchSettings(),a.fetchProfile())},[r]),w.useEffect(()=>{const W=async()=>{try{await Ue.healthCheck()}catch{console.warn("[App] Keep-alive ping failed")}};W();const me=setInterval(W,3e4);return()=>clearInterval(me)},[]);const $=()=>{V(!0),M(!1)},B={migrationStatus:j,showMigrationBanner:C,showMigrationModal:k,openMigrationModal:$,suppressMigrationBanner:q,setSuppressMigrationBanner:G};return u?c.jsx(uu,{text:"Loading your workspace..."}):f?c.jsx(dS,{onComplete:()=>p(!1)}):r?c.jsx(YC,{value:B,children:c.jsxs("div",{className:"min-h-screen bg-background font-sans text-foreground transition-colors duration-300",children:[c.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:c.jsxs("div",{className:"max-w-7xl mx-auto flex h-16 items-center justify-between px-4 sm:px-8",children:[c.jsxs("div",{className:"flex items-center gap-4",children:[c.jsxs("button",{onClick:()=>b("dashboard"),className:"text-xl font-bold flex items-center gap-2 hover:opacity-80 transition-opacity",children:[c.jsx(mp,{className:"w-8 h-8"}),c.jsx("span",{className:"hidden sm:inline",children:"Email Automator"}),c.jsx("span",{className:"sm:hidden",children:"Email AI"})]}),c.jsxs("div",{className:Te("flex items-center gap-1.5 px-2 h-6 rounded-full text-[10px] font-bold border transition-colors",e?"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:[c.jsxs("div",{className:"relative flex items-center justify-center",children:[e&&c.jsx("span",{className:"absolute inline-flex h-3 w-3 rounded-full bg-emerald-500/40 animate-ping"}),c.jsx("div",{className:Te("relative w-2 h-2 rounded-full",e?"bg-emerald-500":"bg-yellow-500")})]}),c.jsx("span",{className:"hidden xs:inline leading-none",children:e?"LIVE":"OFFLINE"})]})]}),c.jsxs("div",{className:"flex gap-4 items-center",children:[c.jsxs("nav",{className:"flex items-center gap-1 bg-secondary/50 p-1 rounded-lg",children:[c.jsxs(Q,{variant:v==="dashboard"?"secondary":"ghost",size:"sm",onClick:()=>b("dashboard"),className:"gap-2",children:[c.jsx(lE,{className:"w-4 h-4"}),c.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),c.jsxs(Q,{variant:v==="analytics"?"secondary":"ghost",size:"sm",onClick:()=>b("analytics"),className:"gap-2",children:[c.jsx(kb,{className:"w-4 h-4"}),c.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),c.jsxs(Q,{variant:v==="config"?"secondary":"ghost",size:"sm",onClick:()=>b("config"),className:"gap-2",children:[c.jsx(nu,{className:"w-4 h-4"}),c.jsx("span",{className:"hidden sm:inline",children:"Configuration"})]})]}),c.jsx("div",{className:"h-6 w-px bg-border/50 mx-2 hidden sm:block"}),c.jsx(Zb,{}),c.jsx(Q,{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:"Account Settings",children:t.profile?.avatar_url?c.jsx("img",{src:t.profile.avatar_url,alt:"Profile",className:"w-full h-full object-cover"}):c.jsx(IT,{className:"w-5 h-5"})})]})]})}),c.jsxs("main",{className:"max-w-7xl mx-auto p-4 sm:p-8 mt-4 mb-12",children:[v==="dashboard"&&c.jsx(ZM,{}),v==="config"&&c.jsx(n3,{}),v==="analytics"&&c.jsx(y3,{}),v==="account"&&c.jsx(i3,{})]}),c.jsx("footer",{className:"max-w-7xl mx-auto px-4 sm:px-8 pb-8 text-center sm:text-left",children:c.jsxs("p",{className:"text-[10px] font-medium text-muted-foreground/40 uppercase tracking-[0.2em]",children:["Email Automator ",c.jsx("span",{className:"mx-1",children:"•"})," v","2.11.3"]})}),t.error&&c.jsx("div",{className:"fixed bottom-20 left-4 right-4 sm:left-auto sm:right-4 sm:max-w-sm z-50",children:c.jsx("div",{className:"bg-destructive/10 border border-destructive/20 text-destructive p-4 rounded-lg",children:c.jsx("p",{className:"text-sm",children:t.error})})}),j&&C&&!q&&c.jsx(h3,{status:j,onDismiss:()=>M(!1),onLearnMore:$}),j&&c.jsx(f3,{open:k,onOpenChange:V,status:j}),c.jsx(m3,{})]})}):c.jsx(d3,{onSuccess:()=>a.fetchProfile(),onConfigure:()=>p(!0),isInitialized:g})}function g3({runId:t,accountEmail:e,isOpen:a,onOpenChange:r}){const[o,u]=w.useState([]),[d,f]=w.useState(!1);w.useEffect(()=>{a&&t&&p()},[a,t]);const p=async()=>{if(t){f(!0);try{const y=await Ue.getRunEvents(t);y.data&&u(y.data.events)}catch(y){console.error("Failed to fetch run trace:",y)}finally{f(!1)}}},g=y=>{switch(y){case"analysis":return c.jsx(Lo,{className:"w-4 h-4 text-purple-500"});case"action":return c.jsx(Vo,{className:"w-4 h-4 text-emerald-500"});case"error":return c.jsx(js,{className:"w-4 h-4 text-red-500"});default:return c.jsx(mi,{className:"w-4 h-4 text-blue-500"})}};return c.jsx(li,{open:a,onOpenChange:r,children:c.jsxs(ci,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[c.jsxs(ui,{className:"p-6 border-b",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(xu,{className:"w-5 h-5 text-primary"}),c.jsx(di,{children:"Sync Run Trace"})]}),c.jsx(hi,{children:e?`Full log for account: ${e}`:"Historical log for this synchronization run."})]}),c.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:d?c.jsx("div",{className:"py-20 flex justify-center",children:c.jsx(uu,{text:"Loading trace..."})}):o.length===0?c.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:"No granular trace events found for this run."}):o.map((y,v)=>c.jsxs("div",{className:"relative pl-8",children:[v!==o.length-1&&c.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),c.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:g(y.event_type)}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-foreground/70",children:y.agent_state}),y.emails?.subject&&c.jsxs("span",{className:"text-[10px] text-primary font-medium truncate max-w-[300px]",children:["Re: ",y.emails.subject]})]}),c.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(fi,{className:"w-3 h-3"}),new Date(y.created_at).toLocaleTimeString()]})]}),c.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[y.event_type==="info"&&c.jsx("p",{className:"text-sm text-foreground/90",children:y.details?.message}),y.event_type==="analysis"&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("p",{className:"text-xs text-foreground italic leading-relaxed",children:['"',y.details?.summary,'"']}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("span",{className:"text-[9px] bg-secondary px-1.5 py-0.5 rounded font-bold uppercase",children:y.details?.category}),y.details?.suggested_actions?.map(b=>c.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))]}),y.details?.usage&&c.jsxs("div",{className:"flex gap-3 pt-1.5 mt-1 border-t border-border/50 text-[9px] text-muted-foreground",children:[c.jsxs("span",{children:["In: ",c.jsx("b",{children:y.details.usage.prompt_tokens})]}),c.jsxs("span",{children:["Out: ",c.jsx("b",{children:y.details.usage.completion_tokens})]}),c.jsxs("span",{children:["Total: ",c.jsx("span",{className:"text-primary font-bold",children:y.details.usage.total_tokens})]})]})]}),y.event_type==="action"&&c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:["Executed: ",y.details?.action]}),c.jsx(Em,{className:"w-4 h-4 text-emerald-500"})]}),y.event_type==="error"&&c.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:y.details?.error})]})]})]},y.id))})]})})}function y3(){const{state:t,actions:e}=Si(),[a,r]=w.useState(null),[o,u]=w.useState(void 0),[d,f]=w.useState(!1);if(w.useEffect(()=>{e.fetchStats()},[]),!t.stats)return c.jsx(uu,{text:"Loading analytics..."});const p=(y,v)=>{r(y),u(v),f(!0)},{stats:g}=t;return c.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[c.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[c.jsx(kb,{className:"w-6 h-6 text-primary"}),"Analytics Dashboard"]}),c.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[c.jsx(Gc,{title:"Total Emails",value:g.totalEmails,color:"primary"}),c.jsx(Gc,{title:"Spam Caught",value:g.categoryCounts.spam||0,color:"destructive"}),c.jsx(Gc,{title:"Actions Taken",value:Object.values(g.actionCounts).reduce((y,v)=>y+v,0)-(g.actionCounts.none||0),color:"emerald"}),c.jsx(Gc,{title:"Accounts",value:g.accountCount,color:"blue"})]}),c.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[c.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[c.jsx("h3",{className:"font-semibold mb-4",children:"Email Categories"}),c.jsx("div",{className:"space-y-3",children:Object.entries(g.categoryCounts).map(([y,v])=>c.jsx("div",{className:"flex items-center gap-3",children:c.jsxs("div",{className:"flex-1",children:[c.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[c.jsx("span",{className:"capitalize",children:y}),c.jsx("span",{className:"text-muted-foreground",children:v})]}),c.jsx("div",{className:"h-2 bg-secondary rounded-full overflow-hidden",children:c.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${v/g.totalEmails*100}%`}})})]})},y))})]}),c.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[c.jsx("h3",{className:"font-semibold mb-4",children:"Actions Taken"}),c.jsx("div",{className:"space-y-3",children:Object.entries(g.actionCounts).map(([y,v])=>c.jsxs("div",{className:"flex items-center justify-between py-2 border-b last:border-0",children:[c.jsx("span",{className:"capitalize",children:y}),c.jsx("span",{className:"font-medium",children:v})]},y))})]})]}),c.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[c.jsx("h3",{className:"font-semibold mb-4",children:"Recent Sync Activity"}),g.recentSyncs.length===0?c.jsx("p",{className:"text-muted-foreground text-sm",children:"No sync activity yet"}):c.jsx("div",{className:"space-y-3",children:g.recentSyncs.map(y=>{const v=y.completed_at?Math.round((new Date(y.completed_at).getTime()-new Date(y.started_at).getTime())/1e3):null;return c.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:()=>p(y.id,y.email_accounts?.email_address),children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:Te("w-2.5 h-2.5 rounded-full",y.status==="success"?"bg-emerald-500":y.status==="failed"?"bg-destructive":"bg-yellow-500 shadow-[0_0_8px_rgba(234,179,8,0.5)] animate-pulse")}),c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-sm font-medium group-hover:text-primary transition-colors",children:y.email_accounts?.email_address||"System Sync"}),c.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[c.jsx(fi,{className:"w-3 h-3"}),new Date(y.started_at).toLocaleString(),v!==null&&c.jsxs("span",{className:"ml-2 px-1.5 py-0.5 bg-secondary rounded-full",children:[v,"s"]})]})]})]}),c.jsx("div",{className:"flex items-center gap-4 text-xs",children:c.jsxs("div",{className:"flex flex-col items-end",children:[c.jsxs("span",{className:"font-bold text-primary",children:[y.emails_processed," emails"]}),c.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[y.emails_deleted," deleted, ",y.emails_drafted," drafted"]})]})})]},y.id)})})]}),c.jsx(g3,{runId:a,accountEmail:o,isOpen:d,onOpenChange:f})]})}function Gc({title:t,value:e,color:a}){const r={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 c.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[c.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:t}),c.jsx("p",{className:`text-3xl font-bold ${r[a]||""}`,children:e})]})}function v3(){return c.jsx(tN,{defaultTheme:"system",storageKey:"email-automator-theme",children:c.jsx(WC,{children:c.jsx(XC,{children:c.jsxs(KC,{children:[c.jsx(p3,{}),c.jsx(HC,{})]})})})})}iT.createRoot(document.getElementById("root")).render(c.jsx(Nb.StrictMode,{children:c.jsx(v3,{})}));
|