1import{r as p,j as e,u as X,b as ye,d as oe}from"./query-vendor-CqOtiPNe.js";import{ba as ts,C as as,bb as rs,au as is,ac as ns,D as ls,bc as os}from"./DashboardLayout-bhpyg6kK.js";import{P as cs}from"./PageHeader-CZkE0AwI.js";import{B as v,b as ds,s as A,a as P,o as ge,x as Ne,D as W,p as $,q as ee,r as se,t as de,L as b,v as Pe,h as f,i as S,k as _,m as y,l as O,S as Me,u as ne,j as fe,T as ms,C as pe,X as us,d as ze,y as xs}from"./index-CgiuONvO.js";import{T as me,a as ue,b as F,c as L}from"./tabs-DhAXdYsK.js";import{B as I}from"./badge-CSzvBtO5.js";import{D as Oe,a as qe,b as Ue,c as G,e as hs,d as ps}from"./dropdown-menu-D-1fS2hr.js";import{u as Be,a as js}from"./useAutomationTemplates-CiIK4D7N.js";import{P as we}from"./play-jGttOVZX.js";import{T as gs,a as fs,b as vs,c as ys}from"./tooltip-DukMi9Yb.js";import{A as ve}from"./activity-DmUxG0fV.js";import{C as ae}from"./circle-check-big-B-nqExcc.js";import{S as Y,a as J,b as Z,c as Q,d as w}from"./select-DLa9MRfA.js";import{I as E}from"./input-oPoHA7Fw.js";import{C as q}from"./clock-DZbyb8Zh.js";import{C as re}from"./circle-x-BuyswQ-Z.js";import{R as Se,L as Ns,C as ke,X as _e,Y as Te,T as Ee,b as Ae,d as je,B as ws,g as De}from"./chart-vendor-De-uRwFm.js";import{D as Re}from"./dollar-sign-BoJmMuTa.js";import{T as be}from"./trending-up-BVHf_RoK.js";import{T as V}from"./textarea-CxLaKExY.js";import{D as bs}from"./download-CVkjVrJo.js";import{S as Cs}from"./share-2-CZ8fruyy.js";import{C as Ke}from"./check-EsNBkSFR.js";import{C as We}from"./copy-B3hQhSgM.js";import{U as Ss}from"./upload-B2TjyuSq.js";import{C as ks}from"./chart-no-axes-column-increasing-DINm0A4J.js";import{E as _s}from"./use-mobile-Bs-uMLmp.js";import{S as Ts}from"./square-pen-Cd8FE6iD.js";import{C as Es}from"./landmark-DVOwzqRj.js";import{T as $e}from"./trash-2-XdlKjO4t.js";import{f as xe}from"./formatDistanceToNow-DExfhm_y.js";import{S as Ie}from"./search-CT8fLn3_.js";import{Z as ie}from"./zap-CZwSyBya.js";import{T as He,a as Ge,b as ce,c as M,d as Ve,e as z}from"./table-CUs_AvL6.js";import{S as Ye}from"./scroll-area-Cf6pvS46.js";import{S as te}from"./separator-BBHmpRWz.js";import{C as Je}from"./circle-check-DJQ0aRpE.js";import{C as As}from"./chevron-right-Cl4Mx2Wq.js";import{M as Ds}from"./message-square-BqIfb2eA.js";import{M as Rs}from"./mail-dnbKMUvE.js";import{C as Is}from"./calendar-njTWr43i.js";import{P as K}from"./plus-DhJDBkeB.js";import{L as Fs}from"./lightbulb-IBP3Qpkq.js";import{M as Ls}from"./minus-BWhsihkF.js";import{T as Ps}from"./trending-down-BOTbmgUi.js";import{D as Ms}from"./cjs-Bkg5ehav.js";import{L as Fe}from"./list-ordered-CD-hc5AR.js";import{u as zs}from"./useOrganization-BfvJJCCq.js";import{B as Os}from"./bell-CJIBHycy.js";import{F as qs}from"./FeatureGate-CPI3lzyi.js";import{H as Us}from"./wifi-off--tLv87Xm.js";import"./ui-vendor-C92kXd7i.js";import"./react-vendor-Oyj1q24G.js";import"./sheet-Dt5T48FQ.js";import"./skeleton-B97PTBMn.js";import"./Logo-BMQirxBI.js";import"./house-C9sHcoTX.js";import"./calendar-days-BvC5INej.js";import"./building-2-Dhg-JMoH.js";import"./users-BKG6ZMTq.js";import"./map-pin-C3B4zHzE.js";import"./wrench-BveqLzJ6.js";import"./file-text-BqBFGr3S.js";import"./credit-card-B4XMcBmh.js";import"./panel-top-C_rCNK16.js";import"./log-out-BzS-CLno.js";import"./check-check-XSobeTl0.js";import"./en-US-5rFTtd83.js";import"./LanguageSwitcher-k7A6VFzv.js";import"./languages-1QBd6nWm.js";import"./message-circle-C3Kdh8KU.js";import"./arrow-down-C4HxAdL9.js";import"./arrow-left-Cg5pwYzI.js";import"./arrow-right-left-tf9Dbt9n.js";import"./arrow-right-CcjvJnjH.js";import"./banknote-wg82AAG7.js";import"./bed--FRu_ZOR.js";import"./book-open-check-DeGSCDpn.js";import"./book-open-CkJItcBu.js";import"./brain-QP504LxU.js";import"./building-B1y8ifkf.js";import"./calculator-BuA7e-mZ.js";import"./car-BBeSSily.js";import"./chart-pie-BH1JXQN4.js";import"./chevron-down-C04YKbFY.js";import"./chevron-left-ChhJq7GD.js";import"./chevron-up-YEko4sQ9.js";import"./message-square-text-CGi8Ghec.js";import"./circle-help-C7Zpw0pA.js";import"./circle-QNrbGPhh.js";import"./clipboard-check-BqHgjlQp.js";import"./clipboard-list-Csw_7fPS.js";import"./clipboard-BrLc9XKt.js";import"./database-BFqeg3FR.js";import"./zoom-out-CZzr-t9-.js";import"./external-link-DLbL3mEn.js";import"./twitter-DZP3beY2.js";import"./file-chart-column-increasing-B5g6evDe.js";import"./file-check-2P_f7S4-.js";import"./file-spreadsheet-BbKDqPhp.js";import"./filter-DOTkE5Cb.js";import"./folder-open-CQAcdSBr.js";import"./tree-pine-BPQJJftn.js";import"./globe-CnUNDEKq.js";import"./video-CEw6mOAP.js";import"./hammer-wk7AQWqX.js";import"./heart-BnQgcucT.js";import"./hotel-GOTEiWOT.js";
1import"./image-plus-DfX-_AyQ.js";import"./image-DrO_YHf9.js";import"./infinity-BeOXN0LM.js";import"./key-round-Cl3pyXjD.js";import"./pen-tool-ErvG_pvg.js";import"./keyboard-CzV9enBr.js";import"./layers-BFQ0OLI3.js";import"./list-checks-CsRR_GQp.js";import"./list-Cj3mFARp.js";import"./lock-rMWs3zu_.js";import"./map-pinned-DBhEITMu.js";import"./map-Dml-fuwB.js";import"./maximize-2-BAo6X0VP.js";import"./maximize-DllRQL4I.js";import"./menu-B6QavzjZ.js";import"./mouse-pointer-click-BX0OFv2U.js";import"./mouse-z7gxK0yj.js";import"./navigation-CE5W2bfp.js";import"./pause-DMf9J0er.js";import"./pencil-s0UamddO.js";import"./ruler-PMZpHEX4.js";import"./phone-CCpZm87m.js";import"./printer-DPItEGKX.js";import"./refresh-ccw-D8-NZbc0.js";import"./rocket-o5dk1x7z.js";import"./rotate-ccw-D5LvpNON.js";import"./rotate-cw-qBQXdDzU.js";import"./route-BHkgA-GC.js";import"./save-CD5NOpBU.js";import"./scale-ChbaOrX5.js";import"./send-Dev9pED3.js";import"./square-plus-BYoTN96c.js";import"./skip-forward-B2g28Adz.js";import"./smartphone-BVaS8Ogf.js";import"./square-check-big-S7f3xHqK.js";import"./square-DpPlSXOl.js";import"./star-DgTF5ai2.js";import"./user-check-DLa2T6BS.js";import"./user-C4n8hF8r.js";import"./volume-2-CyzFl9Wm.js";import"./volume-x-DwUdAb_B.js";import"./wallet-DFZjOwp1.js";import"./workflow-eRF_Iozj.js";import"./useIsRTL-CvXztNyx.js";import"./index-BdQq_4o_.js";import"./UpgradePrompt-BCxglecJ.js";import"./usePaddle-Br6zzzHi.js";import"./paddleJs-DXC336ur.js";const Bs=({automationId:t})=>{const[i,n]=p.useState(!1),a=async()=>{n(!0);try{const{data:s,error:r}=await A.functions.invoke("automation-executor",{body:{automationId:t,triggerType:"manual",triggerData:{source:"manual_test",timestamp:new Date().toISOString()}}});if(r)throw r;P.success("Test run passed",{description:"The trigger, conditions, and actions are valid. No messages were sent and no records were changed."})}catch(s){console.error("Test execution error:",s),P.error("Failed to execute automation",{description:s instanceof Error?s.message:"Unknown error"})}finally{n(!1)}};return e.jsxs(v,{variant:"outline",size:"sm",onClick:a,disabled:i,title:"Validate this automation without performing its actions",children:[i?e.jsx(ds,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(we,{className:"h-4 w-4 mr-2"}),i?"Testing...":"Test run"]})},Ks=t=>X({queryKey:["automation-health",t],queryFn:async()=>{if(!t)return null;const{data:i,error:n}=await A.functions.invoke("check-automation-health",{body:{automationId:t}});if(n)throw n;return i.health},enabled:!!t,refetchInterval:3e4});function Ws({automationId:t}){const{data:i,isLoading:n}=Ks(t);if(n||!i)return e.jsxs(I,{variant:"outline",className:"gap-1",children:[e.jsx(ve,{className:"h-3 w-3"}),"Checking..."]});const a=()=>{switch(i.status){case"healthy":return"bg-green-500/10 text-green-600 border-green-500/20";case"warning":return"bg-yellow-500/10 text-yellow-600 border-yellow-500/20";case"critical":return"bg-red-500/10 text-red-600 border-red-500/20";default:return"bg-muted"}},s=()=>{switch(i.status){case"healthy":return e.jsx(ae,{className:"h-3 w-3"});case"warning":return e.jsx(ge,{className:"h-3 w-3"});case"critical":return e.jsx(ge,{className:"h-3 w-3"});default:return e.jsx(ve,{className:"h-3 w-3"})}};return e.jsx(gs,{children:e.jsxs(fs,{children:[e.jsx(vs,{children:e.jsxs(I,{variant:"outline",className:`gap-1 ${a()}`,children:[s(),i.successRate,"% Success"]})}),e.jsx(ys,{children:e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("p",{className:"font-semibold",children:["Health Status: ",i.status]}),e.jsxs("p",{children:["Total Executions: ",i.totalExecutions]}),e.jsxs("p",{children:["Success: ",i.successCount," | Failed: ",i.failureCount]}),i.hasRecentFailures&&e.jsx("p",{className:"text-destructive",children:"â ï¸ Recent failures detected"})]})})]})})}const $s=()=>{const{toast:t}=Ne(),i=ye(),n=oe({mutationFn:async({automationId:a,schedule:s})=>{const{data:r,error:d}=await A.functions.invoke("schedule-automation",{body:{automationId:a,schedule:s}});if(d)throw d;return r},onSuccess:()=>{i.invalidateQueries({queryKey:["automations"]}),t({title:"Success",description:"Automation scheduled successfully"})},onError:a=>{t({title:"Error",description:a.message,variant:"destructive"})}});return{scheduleAutomation:(a,s)=>n.mutate({automationId:a,schedule:s}),isScheduling:n.isPending}};function Hs({open:t,onOpenChange:i,automationId:n,automationName:a}){const[s,r]=p.useState("once"),[d,m]=p.useState(""),[l,c]=p.useState(""),{scheduleAutomation:u,isScheduling:o}=$s(),j=()=>{const g={type:s,cronExpression:s==="custom"?d:void 0,nextRun:l||new Date().toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone};u(n,g),i(!1)};return e.jsx(W,{open:t,onOpenChange:i,children:e.jsxs($,{className:"sm:max-w-[500px]",children:[e.jsxs(ee,{children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(q,{className:"h-5 w-5"}),"Schedule Automation"]}),e.jsxs(de,{children:['Configure when "',a,'" should run']})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"schedule-type",children:"Schedule Type"}),e.jsxs(Y,{value:s,onValueChange:r,children:[e.jsx(J,{id:"schedule-type",children:e.jsx(Z,{})}),e.jsxs(Q,{children:[e.jsx(w,{value:"once",children:"Run Once"}),e.jsx(w,{value:"daily",children:"Daily"}),e.jsx(w,{value:"weekly",children:"Weekly"}),e.jsx(w,{value:"monthly",children:"Monthly"}),e.jsx(w,{value:"custom",children:"Custom (Cron)"})]})]})]}),s==="custom"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"cron",children:"Cron Expression"}),e.jsx(E,{id:"cron",value:d,onChange:g=>m(g.target.value),placeholder:"0 0 * * *"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Example: "0 0 * * *" runs daily at midnight'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"next-run",children:"Next Run Time"}
1),e.jsx(E,{id:"next-run",type:"datetime-local",value:l,onChange:g=>c(g.target.value)})]}),e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm",children:[e.jsx("p",{className:"font-medium mb-1",children:"Quick Reference:"}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsx("li",{children:"⢠Daily: Runs every day at specified time"}),e.jsx("li",{children:"⢠Weekly: Runs once per week"}),e.jsx("li",{children:"⢠Monthly: Runs once per month"}),e.jsx("li",{children:"⢠Custom: Use cron syntax for precise control"})]})]})]}),e.jsxs(Pe,{children:[e.jsx(v,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(v,{onClick:j,disabled:o,children:o?"Scheduling...":"Schedule"})]})]})})}const Gs=(t,i,n)=>X({queryKey:["automation-report",t,i,n],queryFn:async()=>{if(!t||!i||!n)return null;const{data:a,error:s}=await A.functions.invoke("generate-automation-report",{body:{automationId:t,startDate:i,endDate:n}});if(s)throw s;return a.report},enabled:!!t&&!!i&&!!n});function Vs({open:t,onOpenChange:i,automationId:n,automationName:a}){const[s,r]=p.useState(new Date(Date.now()-2592e6).toISOString().split("T")[0]),[d,m]=p.useState(new Date().toISOString().split("T")[0]),{data:l,isLoading:c}=Gs(n,s,d);return e.jsx(W,{open:t,onOpenChange:i,children:e.jsxs($,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ee,{children:[e.jsxs(se,{children:["Automation Report: ",a]}),e.jsx(de,{children:"Detailed analytics and performance metrics"})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(b,{htmlFor:"start-date",children:"Start Date"}),e.jsx(E,{id:"start-date",type:"date",value:s,onChange:u=>r(u.target.value)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(b,{htmlFor:"end-date",children:"End Date"}),e.jsx(E,{id:"end-date",type:"date",value:d,onChange:u=>m(u.target.value)})]})]}),c?e.jsx("div",{className:"text-center py-8",children:"Loading report..."}):l?e.jsxs(me,{defaultValue:"overview",className:"w-full",children:[e.jsxs(ue,{className:"flex w-full md:grid md:grid-cols-3",children:[e.jsx(F,{value:"overview",children:"Overview"}),e.jsx(F,{value:"performance",children:"Performance"}),e.jsx(F,{value:"impact",children:"Impact"})]}),e.jsxs(L,{value:"overview",className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(f,{children:[e.jsxs(S,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(_,{className:"text-sm font-medium",children:"Total Runs"}),e.jsx(ve,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(y,{children:e.jsx("div",{className:"text-2xl font-bold",children:l.metrics.totalExecutions})})]}),e.jsxs(f,{children:[e.jsxs(S,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(_,{className:"text-sm font-medium",children:"Success Rate"}),e.jsx(ae,{className:"h-4 w-4 text-green-600"})]}),e.jsx(y,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[l.metrics.successRate,"%"]})})]}),e.jsxs(f,{children:[e.jsxs(S,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(_,{className:"text-sm font-medium",children:"Avg Duration"}),e.jsx(q,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(y,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[l.metrics.avgExecutionTimeSeconds,"s"]})})]}),e.jsxs(f,{children:[e.jsxs(S,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(_,{className:"text-sm font-medium",children:"Failed Runs"}),e.jsx(re,{className:"h-4 w-4 text-red-600"})]}),e.jsx(y,{children:e.jsx("div",{className:"text-2xl font-bold",children:l.metrics.failedExecutions})})]})]}),e.jsxs(f,{children:[e.jsxs(S,{children:[e.jsx(_,{children:"Execution Timeline"}),e.jsx(O,{children:"Daily execution statistics"})]}),e.jsx(y,{children:e.jsx(Se,{width:"100%",height:300,children:e.jsxs(Ns,{data:l.timeline,children:[e.jsx(ke,{strokeDasharray:"3 3"}),e.jsx(_e,{dataKey:"date"}),e.jsx(Te,{}),e.jsx(Ee,{}),e.jsx(Ae,{}),e.jsx(je,{type:"monotone",dataKey:"total",stroke:"#8884d8",name:"Total"}),e.jsx(je,{type:"monotone",dataKey:"success",stroke:"#82ca9d",name:"Success"}),e.jsx(je,{type:"monotone",dataKey:"failed",stroke:"#ff6b6b",name:"Failed"})]})})})]})]}),e.jsxs(L,{value:"performance",className:"space-y-4",children:[e.jsxs(f,{children:[e.jsxs(S,{children:[e.jsx(_,{children:"Action Performance"}),e.jsx(O,{children:"Success rate by action type"})]}),e.jsx(y,{children:e.jsx(Se,{width:"100%",height:300,children:e.jsxs(ws,{data:Object.entries(l.actionBreakdown).map(([u,o])=>({name:u,success:o.success,failed:o.failed})),children:[e.jsx(ke,{strokeDasharray:"3 3"}),e.jsx(_e,{dataKey:"name"}),e.jsx(Te,{}),e.jsx(Ee,{}),e.jsx(Ae,{}),e.jsx(De,{dataKey:"success",fill:"#82ca9d",name:"Success"}),e.jsx(De,{dataKey:"failed",fill:"#ff6b6b",name:"Failed"})]})})})]}),e.jsxs(f,{children:[e.jsxs(S,{children:[e.jsx(_,{children:"Recent Executions"}),e.jsx(O,{children:"Last 10 automation runs"})]}),e.jsx(y,{children:e.jsx("div",{className:"space-y-2",children:l.recentExecutions.map(u=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[u.status==="completed"?e.jsx(ae,{className:"h-4 w-4 text-green-600"}):e.jsx(re,{className:"h-4 w-4 text-red-600"}),e.jsx("span",{className:"text-sm",children:new Date(u.createdAt).toLocaleStr
1ing()})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.status})]},u.id))})})]})]}),e.jsxs(L,{value:"impact",className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(f,{children:[e.jsxs(S,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(_,{className:"text-sm font-medium",children:"Time Saved"}),e.jsx(q,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(y,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[l.impact.timeSavedHours,"h"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.impact.timeSavedMinutes," minutes total"]})]})]}),e.jsxs(f,{children:[e.jsxs(S,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(_,{className:"text-sm font-medium",children:"Cost Savings"}),e.jsx(Re,{className:"h-4 w-4 text-green-600"})]}),e.jsxs(y,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:["$",l.impact.costSavings]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Based on $30/hour labor cost"})]})]}),e.jsxs(f,{children:[e.jsxs(S,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(_,{className:"text-sm font-medium",children:"ROI"}),e.jsx(be,{className:"h-4 w-4 text-green-600"})]}),e.jsxs(y,{children:[e.jsx("div",{className:"text-2xl font-bold",children:"High"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Positive impact on productivity"})]})]})]}),e.jsxs(f,{children:[e.jsxs(S,{children:[e.jsx(_,{children:"Value Proposition"}),e.jsx(O,{children:"How this automation helps your business"})]}),e.jsxs(y,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(q,{className:"h-5 w-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Time Efficiency"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Saved ",l.impact.timeSavedHours," hours by automating ",l.metrics.successfulExecutions," tasks"]})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Re,{className:"h-5 w-5 text-green-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Cost Reduction"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Estimated savings of $",l.impact.costSavings," in labor costs"]})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ae,{className:"h-5 w-5 text-purple-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Consistency"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[l.metrics.successRate,"% success rate ensures reliable execution"]})]})]})]})]})]})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No data available for the selected period"})]})]})})}function Ze({open:t,onOpenChange:i,automationId:n,automationName:a,onImportSuccess:s}){const{toast:r}=Ne(),[d,m]=p.useState(""),[l,c]=p.useState(!1),[u,o]=p.useState(!1),[j,g]=p.useState(!1),[x,U]=p.useState(""),[k,D]=p.useState(!1),[R,C]=p.useState(!1),[N,h]=p.useState(7),B=async()=>{if(n){c(!0);try{const{data:T,error:H}=await A.functions.invoke("export-automation",{body:{automationId:n}});if(H)throw H;const le=new Blob([JSON.stringify(T,null,2)],{type:"application/json"}),Ce=URL.createObjectURL(le),he=document.createElement("a");he.href=Ce,he.download=`${a==null?void 0:a.replace(/[^a-z0-9]/gi,"_")}.json`,he.click(),URL.revokeObjectURL(Ce),r({title:"Success",description:"Automation exported successfully"})}catch(T){console.error("Export error:",T),r({title:"Error",description:T instanceof Error?T.message:"Failed to export automation",variant:"destructive"})}finally{c(!1)}}},Xe=async()=>{if(d.trim()){o(!0);try{const T=JSON.parse(d),{data:H,error:le}=await A.functions.invoke("import-automation",{body:{automationData:T}});if(le)throw le;r({title:"Success",description:"Automation imported successfully"}),m(""),s==null||s(),i(!1)}catch(T){console.error("Import error:",T),r({title:"Error",description:T instanceof Error?T.message:"Failed to import automation",variant:"destructive"})}finally{o(!1)}}},es=async()=>
1{if(n){g(!0);try{const{data:T,error:H}=await A.functions.invoke("share-automation",{body:{automationId:n,isPublic:R,expiresInDays:N||null}});if(H)throw H;U(T.shareUrl),r({title:"Success",description:"Share link created successfully"})}catch(T){console.error("Share error:",T),r({title:"Error",description:T instanceof Error?T.message:"Failed to create share link",variant:"destructive"})}finally{g(!1)}}},ss=async()=>{await navigator.clipboard.writeText(x),D(!0),setTimeout(()=>D(!1),2e3),r({title:"Copied",description:"Share link copied to clipboard"})};return e.jsx(W,{open:t,onOpenChange:i,children:e.jsxs($,{className:"sm:max-w-[600px]",children:[e.jsxs(ee,{children:[e.jsx(se,{children:"Import & Export Automations"}),e.jsx(de,{children:"Share, export, or import automation workflows"})]}),e.jsxs(me,{defaultValue:n?"export":"import",className:"w-full",children:[e.jsxs(ue,{className:"flex w-full md:grid md:grid-cols-3",children:[e.jsx(F,{value:"export",disabled:!n,children:"Export"}),e.jsx(F,{value:"share",disabled:!n,children:"Share"}),e.jsx(F,{value:"import",children:"Import"})]}),e.jsx(L,{value:"export",className:"space-y-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:['Export "',a,'" as a JSON file that can be imported later or shared with others.']}),e.jsxs(v,{onClick:B,disabled:l,className:"w-full",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),l?"Exporting...":"Export Automation"]})]})}),e.jsx(L,{value:"share",className:"space-y-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(b,{htmlFor:"public",children:"Public Share"}),e.jsx(Me,{id:"public",checked:R,onCheckedChange:C})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Public shares can be accessed by anyone with the link"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"expires",children:"Expires In (Days)"}),e.jsx(E,{id:"expires",type:"number",value:N,onChange:T=>h(parseInt(T.target.value)||void 0),placeholder:"Leave empty for no expiration"})]}),e.jsxs(v,{onClick:es,disabled:j,className:"w-full",children:[e.jsx(Cs,{className:"mr-2 h-4 w-4"}),j?"Creating Link...":"Create Share Link"]}),x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{value:x,readOnly:!0,className:"flex-1"}),e.jsx(v,{variant:"outline",size:"icon",onClick:ss,children:k?e.jsx(Ke,{className:"h-4 w-4"}):e.jsx(We,{className:"h-4 w-4"})})]})]})]})}),e.jsx(L,{value:"import",className:"space-y-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"import-data",children:"Automation JSON"}),e.jsx(V,{id:"import-data",placeholder:"Paste exported automation JSON here...",value:d,onChange:T=>m(T.target.value),rows:10})]}),e.jsxs(v,{onClick:Xe,disabled:u||!d.trim(),className:"w-full",children:[e.jsx(Ss,{className:"mr-2 h-4 w-4"}),u?"Importing...":"Import Automation"]})]})})]})]})})}function Ys({onEdit:t,onCreate:i}){const{t:n}=ne(),{automations:a,isLoading:s,toggleAutomation:r,deleteAutomation:d}=Be(),[m,l]=p.useState(null),[c,u]=p.useState(null),[o,j]=p.useState(null),g=x=>({rent_collection:"bg-green-500/10 text-green-700",maintenance:"bg-blue-500/10 text-blue-700",lease_management:"bg-purple-500/10 text-purple-700",tenant_communication:"bg-yellow-500/10 text-yellow-700",marketing:"bg-pink-500/10 text-pink-700",financial_reporting:"bg-indigo-500/10 text-indigo-700",compliance:"bg-red-500/10 text-red-700",crm:"bg-teal-500/10 text-teal-700"})[x]||"bg-gray-500/10 text-gray-700";return s?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(x=>e.jsx(f,{className:"animate-pulse",children:e.jsxs(S,{className:"space-y-2",children:[e.jsx("div",{className:"h-4 bg-muted rounded w-3/4"}),e.jsx("div",{className:"h-3 bg-muted rounded w-full"})]})},x))}):!a||a.length===0?e.jsx(f,{children:e.jsxs(y,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(ks,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:n("automations.empty.title","No Automations Yet")}),e.jsx("p",{className:"text-muted-foreground text-center mb-6 max-w-md",children:n("automations.empty.description","Get started by creating your first automation workflow or use one of our pre-built templates.")}),e.jsx(v,{onClick:i,children:n("automations.empty.create","Create Your First Automation")})]})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[a.map(x=>e.jsxs(f,{className:"hover:shadow-md transition-shadow",children:[e.jsx(S,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(_,{className:"text-lg",children:x.name}),e.jsx(O,{className:"mt-1 line-clamp-2",children:x.description})]}),e.jsxs(Oe,{children:[e.jsx(qe,{asChild:!0,children:e.jsx(v,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(_s,{className:"h-4 w-4"})})}),e.jsxs(Ue,{align:"end",children:[e.jsxs(G,{onClick:()=>t(x.id),children:[e.jsx(Ts,{className:"mr-2 h-4 w-4"}),n("common.edit","Edit")]}),e.jsxs(G,{onClick:()=>u({open:!0,automationId:x.id,name:x.name}),children:[e.jsx(Es,{className:"mr-2 h-4 w-4"}),n("automations.viewReport","View Report")]}),e.jsxs(G,{onClick:()=>j({open:!0,automationId:x.id,name:x.name}),children:[e.jsx(ts,{className:"mr-2 h-4 w-4"}),n("automations.exportShare","Export & Share")]}),e.jsxs(G,{children:[e.jsx(We,{className:"mr-2 h-4 w-4"}),n("common.duplicate","Duplicate")]}),e.jsxs(G,{onClick:()=>d(x.id),className:"text-destructive",children:[e.jsx($e,{className:"mr-2 h-4 w-4"}),n("common.delete","Delete")]})]})]})]})}),e.jsxs(y,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(I,{className:g(x.category),children:x.category.replace("_"," ")}),e.jsx(I,{variant:x.status==="active"?"default":"secondary",children:x.status})]}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:n("automations.stats.executions","Executions")}),e.jsx("span",{className:"font-medium",children:x.run_count||0})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:n("automations.stats.successRate","Success Rate")}),e.jsxs("span",{className:"font-medium",children:[x.run_count?Math.round((x.success_count||0)/x.run_count*100):0,"%"]})]}),x.last_run_at&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:n("automations.lastRun","Last run")}),e.jsx("span",{className:"font-medium",children:xe(new Date(x.last_run_at),{addSuffix:!0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{automationId:x.id}),e.jsx(Bs,{automationId:x.id}),e.jsx(v,{variant:"ghost",size:"sm",onClick:()=>l({open:!0,automationId:x.id,name:x.name}),children:e.jsx(q,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:x.status==="active"?n("automations.active","Active"):n("automations.paused","Paused")}),e.jsx(Me,{checked:x.status==="active",onCheckedChange:()=>r(x.id,x.status!=="active")})]})]})]})]},x.id)),m&&e.jsx(Hs,{open:m.open,onOpenChange:x=>!x&&l(null),automationId:m.automationId,automationName:m.name}),c&&e.jsx(Vs,{open:c.open,onOpenChange:x=>!x&&u(null),automationId:c.automationId,automationName:c.name}),o&&e.jsx(Ze,{open:o.open,onOpenChange:x=>!x&&j(null),automationId:o.automationId,automationName:o.name,onImportSuccess:()=>{window.location.reload()}})]})}function Js({onUseTemplate:t}){const{t:i}=ne(),{templates:n,isLoading:a}=js(),[s,r]=p.useState(""),[d,m]=p.useState("all"),l=n==null?void 0:n.filter(u=>{var g;const o=u.name.toLowerCase().includes(s.toLowerCase())||((g=u.description)==null?void 0:g.toLowerCase().includes(s.toLowerCase())),j=d==="all"||u.category===d;return o&&j}),c=u=>u?rs[u]||ie:ie;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ie,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(E,{placeholder:i("automations.templates.search","Search templates..."),value:s,onChange:u=>r(u.target.value),className:"pl-10"})]}),e.jsxs(Y,{value:d,onValueChange:m,children:[e.jsx(J,{className:"w-full sm:w-[200px]",children:e.jsx(Z,{placeholder:i("automations.templates.category","Category")})}),e.jsxs(Q,{children:[e.jsx(w,{value:"all",children:i("common.all","All Categories")}),e.jsx(w,{value:"rent_collection",children:i("automations.category.rentCollection","Rent Collection")}),e.jsx(w,{value:"maintenance",children:i("automations.category.maintenance","Maintenance")}),e.jsx(w,{value:"lease_management",children:i("automations.category.leaseManagement","Lease Management")}),e.jsx(w,{value:"tenant_communication",children:i("automations.category.tenantCommunication","Tenant Communication")}),e.jsx(w,{value:"marketing",children:i("automations.category.marketing","Marketing")}),e.jsx(w,{value:"financial_reporting",children:i("automations.category.financialReporting","Financial Reporting")}),e.jsx(w,{value:"compliance",children:i("automations.category.compliance","Compliance")}),e.jsx(w,{value:"crm",children:i("automations.category.crm","CRM")})]})]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:a?[1,2,3].map(u=>e.jsx(f,{className:"animate-pulse",children:e.jsxs(S,{className:"space-y-2",children:[e.jsx("div",{className:"h-4 bg-muted rounded w-3/4"}),e.jsx("div",{className:"h-3 bg-muted rounded w-full"})]})},u)):l==null?void 0:l.map(u=>{var j;const o=c(u.icon);return e.jsxs(f,{className:"hover:shadow-md transition-shadow",children:[e.jsx(S,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(o,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_,{className:"text-base",children:u.name}),u.is_premium&&e.jsx(as,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx(O,{className:"mt-1",children:u.description})]})]})}),e.jsxs(y,{className:"space-y-4",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:(j=u.tags)==null?void 0:j.map(g=>e.jsx(I,{variant:"outline",className:"text-xs",children:g},g))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[u.use_count||0," ",i("automations.templates.uses","uses")]}),e.jsxs(v,{onClick:()=>t(u.id),size:"sm",children:[e.jsx(fe,{className:"mr-2 h-3 w-3"}),i("automations.templates.use","Use Template")]})]})]})]},u.id)})}),(l==null?void 0:l.length)===0&&!a&&e.jsx(f,{children:e.jsxs(y,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Ie,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:i("automations.templates.noResults","N
1o templates found matching your search")})]})})]})}const Qe=t=>{const{data:i,isLoading:n}=X({queryKey:["automation-executions",t],queryFn:async()=>{let a=A.from("automation_executions").select(` 2 *, 3 automation:automations(name) 4 `).order("created_at",{ascending:!1}).limit(50);t&&(a=a.eq("automation_id",t));const{data:s,error:r}=await a;if(r)throw r;return s},enabled:!0});return{executions:i,isLoading:n}},Zs=t=>{const{data:i,isLoading:n}=X({queryKey:["automation-actions",t],queryFn:async()=>{const{data:a,error:s}=await A.from("automation_actions").select("*").eq("execution_id",t).order("created_at",{ascending:!0});if(s)throw s;return a},enabled:!!t});return{actions:i,isLoading:n}};function Qs(){const{t}=ne(),{executions:i,isLoading:n}=Qe(),a=r=>{switch(r){case"success":return e.jsx(ae,{className:"h-4 w-4 text-green-600"});case"failure":return e.jsx(re,{className:"h-4 w-4 text-red-600"});case"partial":return e.jsx(ms,{className:"h-4 w-4 text-yellow-600"});default:return e.jsx(q,{className:"h-4 w-4 text-blue-600"})}},s=r=>{const d={success:"default",failure:"destructive",partial:"outline"};return e.jsx(I,{variant:d[r]||"secondary",children:r})};return n?e.jsx(f,{children:e.jsx(y,{className:"py-8",children:e.jsx("div",{className:"space-y-2",children:[1,2,3].map(r=>e.jsx("div",{className:"h-12 bg-muted rounded animate-pulse"},r))})})}):!i||i.length===0?e.jsx(f,{children:e.jsxs(y,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(q,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:t("automations.logs.empty.title","No Execution History")}),e.jsx("p",{className:"text-muted-foreground text-center max-w-md",children:t("automations.logs.empty.description","Automation execution logs will appear here once your workflows start running.")})]})}):e.jsx(f,{children:e.jsx(y,{className:"p-0",children:e.jsxs(He,{children:[e.jsx(Ge,{children:e.jsxs(ce,{children:[e.jsx(M,{children:t("automations.logs.status","Status")}),e.jsx(M,{children:t("automations.logs.automation","Automation")}),e.jsx(M,{children:t("automations.logs.trigger","Trigger")}),e.jsx(M,{children:t("automations.logs.duration","Duration")}),e.jsx(M,{children:t("automations.logs.time","Time")})]})}),e.jsx(Ve,{children:i.map(r=>e.jsxs(ce,{children:[e.jsx(z,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[a(r.status),s(r.status)]})}),e.jsx(z,{className:"font-medium",children:r.automation_id}),e.jsx(z,{className:"text-muted-foreground",children:r.trigger_data?JSON.stringify(r.trigger_data).substring(0,50)+"...":"N/A"}),e.jsx(z,{children:r.duration_ms?`${r.duration_ms}ms`:"N/A"}),e.jsx(z,{className:"text-muted-foreground",children:xe(new Date(r.started_at),{addSuffix:!0})})]},r.id))})]})})})}const Xs=({executionId:t,open:i,onOpenChange:n})=>{var l;const{data:a,isLoading:s}=X({queryKey:["automation-execution",t],queryFn:async()=>{const{data:c,error:u}=await A.from("automation_executions").select("*, automation:automations(name)").eq("id",t).single();if(u)throw u;return c},enabled:i&&!!t}),{actions:r,isLoading:d}=Zs(i?t:void 0),m=c=>{switch(c){case"completed":return e.jsx(Je,{className:"h-5 w-5 text-green-500"});case"failed":return e.jsx(re,{className:"h-5 w-5 text-destructive"});case"running":return e.jsx(q,{className:"h-5 w-5 text-blue-500"});default:return e.jsx(ge,{className:"h-5 w-5 text-muted-foreground"})}};return s?e.jsx(W,{open:i,onOpenChange:n,children:e.jsx($,{children:e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})})}):a?e.jsx(W,{open:i,onOpenChange:n,children:e.jsxs($,{className:"max-w-3xl max-h-[80vh]",children:[e.jsx(ee,{children:e.jsxs(se,{className:"flex items-center gap-3",children:[m(a.status),e.jsx("span",{children:"Execution Details"}),e.jsx(I,{variant:"outline",className:"capitalize ml-auto",children:a.status})]})}),e.jsx(Ye,{className:"h-[60vh]",children:e.jsxs("div",{className:"space-y-6 pr-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"font-semibold",children:"Automation"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((l=a.automation)==null?void 0:l.name)||"Unknown"})]}),e.jsx(te,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"font-semibold",children:"Trigger"}),a.trigger_data&&typeof a.trigger_data=="object"&&e.jsx("pre",{className:"text-xs bg-muted p-3 rounded-lg overflow-auto",children:JSON.stringify(a.trigger_data,null,2)})]}),e.jsx(te,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Started"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:new Date(a.started_at).toLocaleStr
4ing()})]}),a.completed_at&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Completed"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:new Date(a.completed_at).toLocaleString()})]})]}),e.jsx(te,{}),!d&&r&&r.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold",children:["Actions (",r.length,")"]}),r.map(c=>e.jsxs("div",{className:"p-3 border border-border rounded-lg space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[m(c.status),e.jsx("span",{className:"font-medium capitalize",children:c.action_type.replace("_"," ")})]}),e.jsx(I,{variant:"outline",className:"capitalize",children:c.status})]}),c.error_message&&e.jsx("p",{className:"text-sm text-destructive",children:c.error_message})]},c.id))]}),e.jsx(te,{})]}),a.execution_result&&typeof a.execution_result=="object"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"font-semibold",children:"Execution Result"}),e.jsx("pre",{className:"text-xs bg-muted p-4 rounded-lg overflow-auto font-mono",children:JSON.stringify(a.execution_result,null,2)})]}),a.error_message&&e.jsxs(e.Fragment,{children:[e.jsx(te,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"font-semibold text-destructive",children:"Error"}),e.jsx("p",{className:"text-sm text-destructive",children:a.error_message})]})]})]})})]})}):null},et=({automationId:t})=>{const{executions:i,isLoading:n}=Qe(t),[a,s]=p.useState(null),r=m=>{switch(m){case"completed":return e.jsx(Je,{className:"h-4 w-4 text-green-500"});case"failed":return e.jsx(re,{className:"h-4 w-4 text-destructive"});case"running":return e.jsx(we,{className:"h-4 w-4 text-blue-500 animate-pulse"});default:return e.jsx(q,{className:"h-4 w-4 text-muted-foreground"})}},d=m=>{const l={completed:"default",failed:"destructive",running:"secondary",pending:"outline"};return e.jsx(I,{variant:l[m]||"outline",className:"capitalize",children:m})};return n?e.jsx(f,{children:e.jsx(y,{className:"py-8",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})})}):!i||i.length===0?e.jsx(f,{children:e.jsx(y,{className:"py-8",children:e.jsx("div",{className:"text-center text-muted-foreground",children:"No execution history yet"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(f,{children:[e.jsx(S,{children:e.jsx(_,{children:"Execution History"})}),e.jsx(y,{children:e.jsxs(He,{children:[e.jsx(Ge,{children:e.jsxs(ce,{children:[e.jsx(M,{children:"Status"}),!t&&e.jsx(M,{children:"Automation"}),e.jsx(M,{children:"Trigger"}),e.jsx(M,{children:"Started"}),e.jsx(M,{children:"Duration"}),e.jsx(M,{})]})}),e.jsx(Ve,{children:i.map(m=>{var c;const l=m.completed_at?Math.round((new Date(m.completed_at).getTime()-new Date(m.started_at).getTime())/1e3):null;return e.jsxs(ce,{children:[e.jsx(z,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[r(m.status),d(m.status)]})}),!t&&e.jsx(z,{className:"font-medium",children:((c=m.automation)==null?void 0:c.name)||"Unknown"}),e.jsx(z,{className:"capitalize",children:"Manual"}),e.jsx(z,{children:xe(new Date(m.started_at),{addSuffix:!0})}),e.jsx(z,{children:l!==null?`${l}s`:"-"}),e.jsx(z,{children:e.jsxs(v,{variant:"ghost",size:"sm",onClick:()=>s(m.id),children:["Details",e.jsx(As,{className:"h-4 w-4 ml-1"})]})})]},m.id)})})]})})]}),a&&e.jsx(Xs,{executionId:a,open:!!a,onOpenChange:m=>!m&&s(null)})]})},Le=[{id:"twilio",name:"Twilio SMS",description:"Send SMS messages via Twilio",icon:Ds,secretKeys:[{key:"TWILIO_ACCOUNT_SID",label:"Account SID",placeholder:"ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"},{key:"TWILIO_AUTH_TOKEN",label:"Auth Token",placeholder:"your_auth_token"},{key:"TWILIO_PHONE_NUMBER",label:"Phone Number",placeholder:"+1234567890"}],docs:"https://www.twilio.com/docs/sms"},{id:"sendgrid",name:"SendGrid Email",description:"Send emails via SendGrid",icon:Rs,secretKeys:[{key:"SENDGRID_API_KEY",label:"API Key",placeholder:"SG.xxxxxxxxxxxxxxxxxxxxxxxx"}],docs:"https://docs.sendgrid.com/"},{id:"google_calendar",name:"Google Calendar",description:"Create calendar events",icon:Is,secretKeys:[{key:"GOOGLE_CALENDAR_API_KEY",label:"API Key",placeholder:"your_api_key"},{key:"GOOGLE_CALENDAR_ID",label:"Calendar ID",placeholder:"primary"}],docs:"https://developers.google.com/calendar"},{id:"zapier",name:"Zapier Webhooks",description:"No setup required - just use webhook URLs in automations",icon:is,secretKeys:[],docs:"https://zapier.com/apps/webhook/integrations"}],st=()=>{const[t,i]=p.useState(null),[n,a]=p.useState({}),s=()=>{P.success("Integration setup saved!",{description:"Your secrets have been securely stored and are ready to use in automations."}),i(null),a({})},r=Le.find(d=>d.id===t);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Integration Setup"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Configure external services to unlock powerful automation capabilities"})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:Le.map(d=>{const m=d.icon;return e.jsxs(f,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(S,{children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(m,{className:"h-5 w-5 text-primary"})}),d.secretKeys.length===0&&e.jsxs(I,{variant:"outline",className:"text-green-600",children:[e.jsx(Ke,{className:"h-3 w-3 mr-1"}),"Ready"]})]}),e.jsx(_,{className:"text-lg mt-4",children:d.name}),e.jsx(O,{className:"text-sm",children:d.description})]}),e.jsx(y,{children:d.secretKeys.length>0?e.jsx(v,{variant:"outline",className:"w-full",onClick:()=>i(d.id),children:"Configure"}):e.jsx(v,{variant:"ghost",className:"w-full",asChild:!0,children:e.jsx("a",{href:d.docs,target:"_blank",rel:"noopener noreferrer",children:"View Docs"})})})]},d.id)})}),r&&e.jsxs(f,{children:[e.jsxs(S,{children:[e.jsxs(_,{children:["Configure ",r.name]}),e.jsxs(O,{children:["Enter your API credentials below. These will be securely stored as secrets.",r.docs&&e.jsxs(e.Fragment,{children:[" ",e.jsx("a",{href:r.docs,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"View documentation"})]})]})]}),e.jsxs(y,{className:"space-y-4",children:[r.secretKeys.map(d=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:d.
4key,children:d.label}),e.jsx(E,{id:d.key,type:"password",placeholder:d.placeholder,value:n[d.key]||"",onChange:m=>a({...n,[d.key]:m.target.value})})]},d.key)),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(v,{onClick:s,children:"Save Configuration"}),e.jsx(v,{variant:"outline",onClick:()=>{i(null),a({})},children:"Cancel"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connection secrets are stored in protected server configuration and are never shipped to the browser."})]})]})]})},tt=()=>{const[t,i]=p.useState([]),[n,a]=p.useState(!1),[s,r]=p.useState(null),d=async(c,u)=>{r(u);try{const{error:o}=await A.functions.invoke("import-automation",{body:{automationData:{name:c.name,description:c.description,category:c.category,trigger_type:c.triggerType,actions:c.actions,conditions:[],priority:c.priority}}});if(o)throw o;P.success("Workflow created as a paused draft",{description:"Review its trigger and actions before enabling it."})}catch(o){P.error("Could not create workflow",{description:o instanceof Error?o.message:"Unknown error"})}finally{r(null)}},m=async()=>{var c,u;a(!0);try{const{data:o,error:j}=await A.functions.invoke("suggest-automations");if(j){if((c=j.message)!=null&&c.includes("Rate limit"))P.error("Rate limit exceeded",{description:"Please try again in a few minutes."});else if((u=j.message)!=null&&u.includes("credits"))P.error("AI credits exhausted",{description:"Please add credits to continue using AI features."});else throw j;return}i(o.suggestions||[]),P.success("AI suggestions loaded!",{description:`Found ${o.suggestions.length} automation opportunities`})}catch(o){console.error("Suggestion error:",o),P.error("Failed to load suggestions",{description:o instanceof Error?o.message:"Unknown error"})}finally{a(!1)}},l=c=>{switch(c){case"high":return"destructive";case"medium":return"default";default:return"secondary"}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(fe,{className:"h-5 w-5 text-primary"}),"Smart Suggestions"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Practical recommendations based on your portfolio data"})]}),e.jsx(v,{onClick:m,disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-primary mr-2"}),"Analyzing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"h-4 w-4 mr-2"}),"Get Suggestions"]})})]}),t.length>0&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:t.map((c,u)=>e.jsxs(f,{className:"hover:shadow-md transition-shadow",children:[e.jsx(S,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(_,{className:"text-base",children:c.name}),e.jsx(O,{className:"mt-1",children:c.description})]}),e.jsx(I,{variant:l(c.priority),className:"capitalize",children:c.priority})]})}),e.jsxs(y,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(q,{className:"h-4 w-4"}),e.jsxs("span",{children:["Saves ~",c.estimatedTimeSaved]})]}),e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Why:"})," ",c.reason]}),e.jsx(I,{variant:"outline",className:"capitalize",children:c.category.replace("_"," ")}),e.jsxs(v,{variant:"outline",size:"sm",className:"w-full mt-2",disabled:s===u,onClick:()=>d(c,u),children:[e.jsx(K,{className:"h-4 w-4 mr-2"}),s===u?"Creating...":"Create Draft Workflow"]})]})]},u))}),t.length===0&&!n&&e.jsx(f,{children:e.jsxs(y,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(be,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Suggestions Yet"}),e.jsx("p",{className:"text-muted-foreground text-center mb-6 max-w-md",children:'Click "Get Suggestions" to analyze your data and receive personalized automation recommendations.'})]})})]})},at=()=>{const[t,i]=p.useState(null),[n,a]=p.useState([]),[s,r]=p.useState([]),[d,m]=p.useState(!1),l=async()=>{var o,j;m(!0);try{const{data:g,error:x}=await A.functions.invoke("predict-automation-performance");if(x){if((o=x.message)!=null&&o.includes("Rate limit"))P.error("Rate limit exceeded",{description:"Please try again in a few minutes."});else if((j=x.message)!=null&&j.includes("credits"))P.error("AI credits exhausted",{description:"Please add credits to continue using AI features."});else throw x;return}i(g.metrics),a(g.predictions||[]),r(g.recommendations||[]),P.success("Performance analysis complete!",{description:`Generated ${g.predictions.length} predictions and ${g.recommendations.length} recommendations`})}catch(g){console.error("Analytics error:",g),P.error("Failed to load anal
4ytics",{description:g instanceof Error?g.message:"Unknown error"})}finally{m(!1)}},c=o=>{switch(o){case"up":return e.jsx(be,{className:"h-4 w-4 text-green-500"});case"down":return e.jsx(Ps,{className:"h-4 w-4 text-red-500"});default:return e.jsx(Ls,{className:"h-4 w-4 text-muted-foreground"})}},u=o=>{switch(o){case"high":return"destructive";case"medium":return"default";default:return"secondary"}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(pe,{className:"h-5 w-5 text-primary"}),"Performance Analytics"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Measured reliability and recommendations from execution history"})]}),e.jsx(v,{onClick:l,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-primary mr-2"}),"Analyzing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 mr-2"}),"Analyze Performance"]})})]}),t&&e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(f,{children:[e.jsx(S,{className:"pb-3",children:e.jsx(_,{className:"text-sm font-medium",children:"Total Executions"})}),e.jsx(y,{children:e.jsx("div",{className:"text-2xl font-bold",children:t.totalExecutions})})]}),e.jsxs(f,{children:[e.jsx(S,{className:"pb-3",children:e.jsx(_,{className:"text-sm font-medium",children:"Success Rate"})}),e.jsx(y,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[t.successRate,"%"]})})]}),e.jsxs(f,{children:[e.jsx(S,{className:"pb-3",children:e.jsx(_,{className:"text-sm font-medium",children:"Avg Duration"})}),e.jsx(y,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[t.avgDuration,"s"]})})]})]}),n.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold mb-3",children:"Predictions"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:n.map((o,j)=>e.jsxs(f,{children:[e.jsx(S,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(_,{className:"text-base",children:o.metric}),e.jsxs("div",{className:"flex items-center gap-2",children:[c(o.trend),e.jsx(I,{variant:"outline",className:"capitalize",children:o.confidence})]})]})}),e.jsxs(y,{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Current:"}),e.jsx("span",{className:"font-medium",children:o.currentValue})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Predicted:"}),e.jsx("span",{className:"font-medium",children:o.predictedValue})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:o.insight})]})]},j))})]}),s.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Fs,{className:"h-5 w-5 text-yellow-500"}),"Recommendations"]}),e.jsx("div",{className:"space-y-3",children:s.map((o,j)=>e.jsxs(f,{children:[e.jsx(S,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(_,{className:"text-base",children:o.title}),e.jsx(O,{className:"mt-1",children:o.description})]}),e.jsx(I,{variant:u(o.priority),className:"capitalize",children:o.priority})]})}),e.jsx(y,{children:e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Impact:"})," ",o.impact]})})]},j))})]}),!t&&!d&&e.jsx(f,{children:e.jsxs(y,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(pe,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Analytics Yet"}),e.jsx("p",{className:"text-muted-foreground text-center mb-6 max-w-md",children:'Click "Analyze Performance" to review measured workflow history and practical recommendations.'})]})})]})},rt=({node:t,isConnecting:i,onMove:n,onClick:a,onDelete:s,onStartConnection:r,onEndConnection:d})=>{const m=p.useRef(null),l=()=>{switch(t.type){case"trigger":return e.jsx(ie,{className:"h-5 w-5"});case"action":return e.jsx(we,{className:"h-5 w-5"});case"condition":return e.jsx(ns,{className:"h-5 w-5"})}},c=()=>{switch(t.type){case"trigger":return"border-blue-500";case"action":return"border-green-500";case"condition":return"border-yellow-500"}},u=()=>{if(t.config.name)return t.config.name;switch(t.type){case"trigger":return"Trigger";case"action":return"Action";case"condition":return"Condition"}};return e.jsx(Ms,{nodeRef:m,position:t.position,onStop:(o,j)=>n(t.id,{x:j.x,y:j.y}),handle:".drag-handle",children:e.jsx("div",{ref:m,className:"absolute cursor-move",style:{width:"280px"},children:e.jsx(f,{className:`p-4 border-2 ${c()} ${i?"ring-2 ring-primary":""} group hover:shadow-lg transition-shadow`,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between drag-handle",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-muted rounded-lg",children:l()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:u()}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:t.type})]})]}),e.jsx(v,{variant:"ghost",size:"icon",className:"h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",onClick:o=>{o.stopPropagation(),s(t.id)},children:e.jsx($e,{className:"h-3 w-3"})})]}),t.config.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.config.description}),e.jsxs("div",{className:"flex justify-between pt-2 border-t border-border",children:[e.jsx(v,{variant:"ghost",size:"sm",onClick:o=>{o.stopPropagation(),a(t.id)},className:"h-7 text-xs",children:"Configure"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(v,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:o=>
4{o.stopPropagation(),r(t.id)},title:"Start Connection",children:e.jsx(Fe,{className:"h-3 w-3"})}),e.jsx(v,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:o=>{o.stopPropagation(),d(t.id)},title:"End Connection Here",children:e.jsx(Fe,{className:"h-3 w-3 rotate-90"})})]})]})]})})})})},it=[{value:"schedule",label:"Schedule (Time-based)"},{value:"webhook",label:"Webhook"},{value:"email_received",label:"Email Received"},{value:"form_submission",label:"Form Submission"},{value:"payment_received",label:"Payment Received"},{value:"lease_expiring",label:"Lease Expiring"},{value:"maintenance_request",label:"Maintenance Request"}],nt=[{value:"send_email",label:"Send Email"},{value:"send_sms",label:"Send SMS"},{value:"create_task",label:"Create Task"},{value:"update_property",label:"Update Property"},{value:"send_invoice",label:"Send Invoice"},{value:"schedule_inspection",label:"Schedule Inspection"},{value:"create_calendar_event",label:"Create Calendar Event"},{value:"webhook",label:"Call Webhook"},{value:"zapier_webhook",label:"Trigger Zapier Zap"}],lt=[{value:"if",label:"If (Simple Condition)"},{value:"if_else",label:"If/Else"},{value:"switch",label:"Switch (Multiple Conditions)"}],ot=({open:t,onOpenChange:i,node:n,onSave:a})=>{var l,c,u,o,j,g,x,U,k,D,R,C,N;const[s,r]=p.useState(n.config);p.useEffect(()=>{r(n.config)},[n]);const d=()=>{a(s)},m=()=>{switch(n.type){case"trigger":return it;case"action":return nt;case"condition":return lt;default:return[]}};return e.jsx(W,{open:t,onOpenChange:i,children:e.jsxs($,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(ee,{children:e.jsxs(se,{className:"capitalize",children:["Configure ",n.type]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"type",children:"Type"}),e.jsxs(Y,{value:s.type||"",onValueChange:h=>r({...s,type:h}),children:[e.jsx(J,{children:e.jsx(Z,{placeholder:`Select ${n.type} type`})}),e.jsx(Q,{children:m().map(h=>e.jsx(w,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"name",children:"Name"}),e.jsx(E,{id:"name",value:s.name||"",onChange:h=>r({...s,name:h.target.value}),placeholder:"Enter a descriptive name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"description",children:"Description"}),e.jsx(V,{id:"description",value:s.description||"",onChange:h=>r({...s,description:h.target.value}),placeholder:"Describe what this node does",rows:3})]}),s.type==="schedule"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"schedule",children:"Schedule (Cron Expression)"}),e.jsx(E,{id:"schedule",value:((l=s.settings)==null?void 0:l.schedule)||"",onChange:h=>r({...s,settings:{...s.settings,schedule:h.target.value}}),placeholder:"0 9 * * * (Daily at 9 AM)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use cron format: minute hour day month weekday"})]}),s.type==="send_email"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"recipient",children:"Recipient Email"}),e.jsx(E,{id:"recipient",value:((c=s.settings)==null?void 0:c.recipient)||"",onChange:h=>r({...s,settings:{...s.settings,recipient:h.target.value}}),placeholder:"[email protected] or {{variable}}"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"subject",children:"Email Subject"}),e.jsx(E,{id:"subject",value:((u=s.settings)==null?void 0:u.subject)||"",onChange:h=>r({...s,settings:{...s.settings,subject:h.target.value}}),placeholder:"Email subject with {{variables}}"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"body",children:"Email Body"}),e.jsx(V,{id:"body",value:((o=s.settings)==null?void 0:o.body)||"",onChange:h=>r({...s,settings:{...s.settings,body:h.target.value}}),placeholder:"Email body with {{variables}}",rows:5})]})]}),(s.type==="webhook"||s.type==="zapier_webhook")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"url",children:s.type==="zapier_webhook"?"Zapier Webhook URL":"Webhook URL"}),e.jsx(E,{id:"url",value:((j=s.settings)==null?void 0:j.url)||"",onChange:h=>r({...s,settings:{...s.settings,url:h.target.value}}),placeholder:s.type==="zapier_webhook"?"https://hooks.zapier.com/hooks/catch/...":"https://example.com/webhook"}),s.type==="zapier_webhook"&&e.jsx("p",{className:"text-xs text-muted-foreground",children:'Create a Zap with a "Catch Hook" trigger and paste the webhook URL here'})]}),s.type==="webhook"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"method",children:"HTTP Method"}),e.jsxs(Y,{value:((g=s.settings)==null?void 0:g.method)||"POST",onValueChange:h=>r({...s,settings:{...s.settings,method:h}}),children:[e.jsx(J,{children:e.jsx(Z,{})}),e.jsxs(Q,{children:[e.jsx(w,{value:"GET",children:"GET"}),e.jsx(w,{value:"POST",children:"POST"}),e.jsx(w,{value:"PUT",children:"PUT"}),e.jsx(w,{value:"DELETE",children:"DELETE"})]})]})]})]}),s.type==="send_sms"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"phoneNumber",children:"Phone Number"}),e.jsx(E,{id:"phoneNumber",value:((x=s.settings)==null?void 0:x.phoneNumber)||"",onChange:h=>r({...s,settings:{...s.settings,phoneNumber:h.target.value}}),placeholder:"+1234567890 or {{tenant_phone}}"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use E.164 format or template variables"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"smsMessage",children:"Message"}),e.jsx(V,{id:"smsMessage",value:((U=s.settings)==null?void 0:U.message)||"",onChange:h=>r({...s,settings:{...s.settings,message:h.target.value}}),placeholder:"SMS message with {{variables}}",rows:3})]})]}),s.type==="create_calendar_event"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"eventSummary",children:"Event Title"}),e.jsx(E,{id:"eventSummary",value:((k=s.settings)==null?void 0:k.summary)||"",onChange:h=>r({...s,settings:{...s.settings,summary:h.target.value}}),placeholder:"Meeting with {{tenant_name}}"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"eventDescription",children:"Description"}),e.jsx(V,{id:"eventDescription",value:((D=s.settings)==null?void 0:D.description)||"",onChange:h=>r({...s,settings:{...s.settings,description:h.target.value}}),placeholder:"Event description with {{variables}}",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"startTime",children:"Start Time"}),e.jsx(E,{id:"startTime",type:"datetime-local",value:((R=s.settings)==null?void 0:R.startTime)||"",onChange:h=>r({...s,settings:{...s.settings,startTime:h.target.value}})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"endTime",children:"End Time"}),e.jsx(E,{id:"endTime",type:"datetime-local",value:((C=s.settings)==null?void 0:C.endTime)||"",onChange:h=>r({...s,settings:{...s.settings,endTime:h.target.value}})})]})]})]}),n.type==="condition"&&e.jsx(e.Fragment,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{htmlFor:"condition",children:"Condition"}),e.jsx(E,{id:"condition",value:((N=s.settings)==null?void 0:N.condition)||"",onChange:h=>r({...s,settings:{...s.settings,condition:h.target.value}}),placeholder:"{{variable}} == 'value'"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use comparison operators: ==, !=, >, <, >=, <="})]})})]}),e.jsxs(Pe,{children:[e.jsx(v,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(v,{onClick:d,children:"Save Configuration"})]})]})})},ct=({nodes:t,connections:i,onConnectionDelete:n})=>{const a=s=>{const r=t.find(d=>d.id===s);return r?{x:r.position.x+140,y:r.position.y+60}:{x:0,y:0}};return e.jsxs("svg",{className:"absolute inset-0 w-full h-full pointer-events-none",style:{zIndex:0},children:[e.jsx("defs",{children:e.jsx("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"10",refX:"9",refY:"3",orient:"auto",children:e.jsx("polygon",{points:"0 0, 10 3, 0 6",fill:"hsl(var(--primary))",opacity:"0.6"})})}),i.map((s,r)=>{const d=a(s.from),m=a(s.to),l=(d.y+m.y)/2,c=`M ${d.x} ${d.y} C ${d.x} ${l}, ${m.x} ${l}, ${m.x} ${m.y}`,u=(d.x+m.x)/2;return e.jsxs("g",{children:[e.jsx("path",{d:c,stroke:"hsl(var(--primary))",strokeWidth:"2",fill:"none",opacity:"0.6",markerEnd:"url(#arrowhead)"}),e.jsx("foreignObject",{x:u-12,y:l-12,width:"24",height:"24",className:"pointer-events-auto",children:e.jsx(v,{variant:"destructive",size:"icon",className:"h-6 w-6 rounded-full opacity-0 hover:opacity-100 transition-opacity",onClick:()=>n(s.from,s.to),children:e.jsx(us,{className:"h-3 w-3"})})})]},`${s.from}-${s.to}-${r}`)})]})},dt=({nodes:t,connections:i,onNodesChange:n,onConnectionsChange:a})=>{const[s,r]=p.useState(null),[d,m]=p.useState(!1),[l,c]=p.useState(null),u=p.useRef(null),o=p.useCallback(N=>{const h={id:`node-${Date.now()}`,type:N,position:{x:100,y:t.length*150+50},config:{}};n([...t,h])},[t,n]),j=p.useCallback((N,h)=>{n(t.map(B=>B.id===N?{...B,position:h}:B))},[t,n]),g=p.useCallback(N=>{r(N),m(!0)},[]),x=p.useCallback(N=>
4{n(t.filter(h=>h.id!==N)),a(i.filter(h=>h.from!==N&&h.to!==N))},[t,i,n,a]),U=p.useCallback(N=>{s&&(n(t.map(h=>h.id===s?{...h,config:N}:h)),m(!1),r(null))},[s,t,n]),k=p.useCallback(N=>{c(N)},[]),D=p.useCallback(N=>{if(l&&l!==N){const h={from:l,to:N};a([...i,h])}c(null)},[l,i,a]),R=p.useCallback((N,h)=>{a(i.filter(B=>!(B.from===N&&B.to===h)))},[i,a]),C=t.find(N=>N.id===s);return e.jsxs("div",{className:"relative w-full h-[600px] border border-border rounded-lg bg-muted/20",children:[e.jsxs("div",{ref:u,className:"relative w-full h-full overflow-auto",children:[e.jsx(ct,{nodes:t,connections:i,onConnectionDelete:R}),t.map(N=>e.jsx(rt,{node:N,isConnecting:l===N.id,onMove:j,onClick:g,onDelete:x,onStartConnection:k,onEndConnection:D},N.id)),t.length===0&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Start building your workflow"}),e.jsx("div",{className:"flex gap-2 justify-center",children:e.jsxs(v,{onClick:()=>o("trigger"),size:"sm",children:[e.jsx(K,{className:"h-4 w-4 mr-2"}),"Add Trigger"]})})]})})]}),e.jsxs("div",{className:"absolute bottom-4 left-4 flex gap-2 bg-card p-2 rounded-lg border border-border shadow-sm",children:[e.jsxs(v,{onClick:()=>o("trigger"),size:"sm",variant:"outline",children:[e.jsx(K,{className:"h-4 w-4 mr-2"}),"Trigger"]}),e.jsxs(v,{onClick:()=>o("action"),size:"sm",variant:"outline",children:[e.jsx(K,{className:"h-4 w-4 mr-2"}),"Action"]}),e.jsxs(v,{onClick:()=>o("condition"),size:"sm",variant:"outline",children:[e.jsx(K,{className:"h-4 w-4 mr-2"}),"Condition"]})]}),C&&e.jsx(ot,{open:d,onOpenChange:m,node:C,onSave:U})]})};function mt({open:t,onOpenChange:i,automationId:n}){const{t:a}=ne(),{toast:s}=Ne(),{user:r}=ze(),{organization:d}=zs(),m=ye(),[l,c]=p.useState({name:"",description:"",category:"general",trigger_type:"schedule"}),[u,o]=p.useState([]),[j,g]=p.useState([]);p.useEffect(()=>{if(!t)return;if(!n){c({name:"",description:"",category:"general",trigger_type:"schedule"}),o([]),g([]);return}let k=!1;return A.from("automations").select("name, description, category, trigger_type, trigger_config").eq("id",n).single().then(({data:D,error:R})=>{var N;if(k)return;if(R||!D){s({title:a("common.error","Error"),description:(R==null?void 0:R.message)||"Automation not found",variant:"destructive"}),i(!1);return}const C=((N=D.trigger_config)==null?void 0:N.workflow)||{};c({name:D.name,description:D.description||"",category:D.category||"general",trigger_type:D.trigger_type||"manual"}),o(Array.isArray(C.nodes)?C.nodes:[]),g(Array.isArray(C.connections)?C.connections:[])}),()=>{k=!0}},[n,i,t,a,s]);const x=oe({mutationFn:async()=>{if(!r)throw new Error("Sign in before saving an automation");if(!d)throw new Error("Choose a workspace before saving an automation");if(!u.some(C=>C.type==="trigger"))throw new Error("Add at least one trigger to the workflow");if(!u.some(C=>C.type==="action"))throw new Error("Add at least one action to the workflow");const k={name:l.name.trim(),description:l.description.trim()||null,category:l.category,trigger_type:l.trigger_type,trigger_config:{workflow:{nodes:u,connections:j}},conditions:u.filter(C=>C.type==="condition").map(C=>C.config),actions:u.filter(C=>C.type==="action").map(C=>C.config),organization_id:d.id,user_id:r.id,created_by:r.id,status:"draft",updated_at:new Date().toISOString()},D=n?A.from("automations").update(k).eq("id",n):A.from("automations").insert(k),{error:R}=await D;if(R)throw R},onSuccess:()=>{m.invalidateQueries({queryKey:["automations"]}),s({title:a("common.success","Success"),description:a("automations.builder.saved","Automation saved successfully")}),i(!1)},onError:k=>s({title:a("common.error","Error"),description:k.message,variant:"destructive"})}),U=()=>{if(!l.name.trim()){s({title:a("common.error","Error"),description:a("automations.builder.nameRequired","Please enter an automation name"),variant:"destructive"});return}x.mutate()};return e.jsx(W,{open:t,onOpenChange:i,children:e.jsxs($,{className:"max-w-6xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ee,{children:[e.jsx(se,{children:n?a("automations.builder.edit","Edit Automation"):a("automations.builder.create","Create New Automation")}),e.jsx(de,{children:a("automations.builder.description","Configure your automation workflow with triggers and actions")})]}),e.jsxs(me,{defaultValue:"basic",className:"w-full",children:[e.jsxs(ue,{className:"flex w-full md:grid md:grid-cols-2",children:[e.jsx(F,{value:"basic",children:a("automations.builder.basicInfo","Basic Info")}),e.jsx(F,{value:"workflow",children:a("automations.builder.visualWorkflow","Visual Workflow")})]}),e.jsx(L,{value:"basic",className:"space-y-6 py-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(b,{htmlFor:"name",children:a("automations.builder.name","Automation Name")}),e.jsx(E,{id:"name",value:l.name,onChange:k=>c({...l,name:k.target.value}),placeholder:a("automations.builder.namePlaceholder","E.g., Send rent reminders")})]}),e.jsxs("div",{children:[e.jsx(b,{htmlFor:"description",children:a("automations.builder.description","Description")}),e.jsx(V,{id:"description",value:l.description,onChange:k=>c({...l,description:k.target.value}),placeholder:a("automations.builder.descriptionPlaceholder","What does this automation do?"),rows:3})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(b,{htmlFor:"category",children:a("automations.builder.category","Category")}),e.jsxs(Y,{value:l.category,onValueChange:k=>c({...l,category:k}),children:[e.jsx(J,{children:e.jsx(Z,{})}),e.jsxs(Q,{children:[e.jsx(w,{value:"rent_collection",children:a("automations.category.rentCollection","Rent Collection")}),e.jsx(w,{value:"maintenance",children:a("automations.category.maintenance","Maintenance")}),e.jsx(w,{value:"lease_management",children:a("automations.category.leaseManagement","Lease Management")}),e.jsx(w,{value:"tenant_communication",children:a("automations.category.tenantCommunication","Tenant Communication")}),e.jsx(w,{value:"marketing",children:a("automations.category.marketing","Marketing")}),e.jsx(w,{value:"financial_reporting",children:a("automations.category.financialReporting","Financial Reporting")}),e.jsx(w,{value:"compliance",children:a("automations.category.compliance","Compliance")}),e.jsx(w,{value:"crm",children:a("automations.category.crm","CRM")}),e.jsx(w,{value:"general",children:a("automations.category.general","General")})]})]})]}),e.jsxs("div",{children:[e.jsx(b,{htmlFor:"trigger",children:a("automations.builder.trigger","Trigger Type")}),e.jsxs(Y,{value:l.trigger_type,onValueChange:k=>c({...l,trigger_type:k}
4),children:[e.jsx(J,{children:e.jsx(Z,{})}),e.jsxs(Q,{children:[e.jsx(w,{value:"schedule",children:a("automations.trigger.schedule","Schedule (Time-based)")}),e.jsx(w,{value:"event",children:a("automations.trigger.event","Event (Action-based)")}),e.jsx(w,{value:"condition",children:a("automations.trigger.condition","Condition (Rule-based)")}),e.jsx(w,{value:"manual",children:a("automations.trigger.manual","Manual")})]})]})]})]})]})}),e.jsx(L,{value:"workflow",className:"py-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:a("automations.builder.workflowBuilder","Workflow Builder")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a("automations.builder.workflowHint","Drag nodes to position them, click to configure, and connect them to build your workflow")})]}),e.jsx(v,{variant:"outline",size:"sm",onClick:()=>{o([]),g([])},children:a("automations.builder.clearWorkflow","Clear Workflow")})]}),e.jsx(dt,{nodes:u,connections:j,onNodesChange:o,onConnectionsChange:g})]})})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(v,{variant:"outline",onClick:()=>i(!1),children:a("common.cancel","Cancel")}),e.jsx(v,{onClick:U,disabled:x.isPending,children:x.isPending?a("common.saving","Saving..."):a("common.save","Save Automation")})]})]})})}const ut=()=>{const{user:t}=ze(),i=ye(),{data:n,isLoading:a}=X({queryKey:["automation-notifications",t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];const{data:m,error:l}=await A.from("automation_notifications").select(` 5 *, 6 automation:automations(name) 7 `).order("created_at",{ascending:!1}).limit(50);if(l)throw l;return m},enabled:!!t,refetchInterval:3e4}),s=oe({mutationFn:async m=>{const{error:l}=await A.from("automation_notifications").update({is_read:!0}).eq("id",m);if(l)throw l},onSuccess:()=>{i.invalidateQueries({queryKey:["automation-notifications"]})}}),r=oe({mutationFn:async()=>{if(!t)return;const{error:m}=await A.from("automation_notifications").update({is_read:!0}).eq("user_id",t.id).eq("is_read",!1);if(m)throw m},onSuccess:()=>{i.invalidateQueries({queryKey:["automation-notifications"]})}}),d=(n==null?void 0:n.filter(m=>!m.is_read).length)||0;return{notifications:n,isLoading:a,unreadCount:d,markAsRead:m=>s.mutate(m),markAllAsRead:()=>r.mutate()}};function xt(){const{notifications:t,unreadCount:i,markAsRead:n,markAllAsRead:a}=ut(),s=r=>{switch(r){case"failure":return"text-red-600";case"success":return"text-green-600";case"warning":return"text-yellow-600";case"retry":return"text-blue-600";default:return"text-muted-foreground"}};return e.jsxs(Oe,{children:[e.jsx(qe,{asChild:!0,children:e.jsxs(v,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(Os,{className:"h-5 w-5"}),i>0&&e.jsx(I,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs",children:i>9?"9+":i})]})}),e.jsxs(Ue,{align:"end",className:"w-screen max-w-[calc(100vw-32px)] sm:w-[380px]",children:[e.jsxs(hs,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Notifications"}),i>0&&e.jsx(v,{variant:"ghost",size:"sm",onClick:()=>a(),className:"h-auto p-1 text-xs",children:"Mark all read"})]}),e.jsx(ps,{}),e.jsx(Ye,{className:"h-[400px]",children:t&&t.length>0?t.map(r=>e.jsxs(G,{className:`flex flex-col items-start gap-1 p-3 cursor-pointer ${r.is_read?"":"bg-muted/50"}`,onClick:()=>!r.is_read&&n(r.id),children:[e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("div",{className:`h-2 w-2 rounded-full ${s(r.notification_type)}`}),e.jsx("span",{className:"font-medium text-sm flex-1",children:r.title}),e.jsx("span",{className:"text-xs text-muted-foreground",children:xe(new Date(r.created_at),{addSuffix:!0})})]}),e.jsx("p",{className:"text-xs text-muted-foreground pl-4",children:r.message}),r.automation&&e.jsxs("span",{className:"text-xs text-muted-foreground pl-4",children:["Automation: ",r.automation.name]})]},r.id)):e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No notifications"})})]})]})}function oi(){const{t}
7=ne(),[i,n]=p.useState("workflows"),[a,s]=p.useState(!1),[r,d]=p.useState(null),[m,l]=p.useState(!1),{automations:c}=Be(),u=()=>{d(null),s(!0)},o=j=>{d(j),s(!0)};return e.jsx(ls,{children:e.jsx(qs,{feature:"Automations (Beta)",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(cs,{title:t("automations.title","Automations"),subtitle:t("automations.subtitle","Streamline your workflows with intelligent automation"),icon:e.jsx(ie,{className:"h-5 w-5"}),actions:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(xt,{}),e.jsxs(v,{variant:"outline",onClick:()=>l(!0),children:[e.jsx(K,{className:"mr-2 h-4 w-4"}),t("automations.import","Import")]}),e.jsxs(v,{onClick:u,children:[e.jsx(K,{className:"mr-2 h-4 w-4"}),t("automations.createNew","Create Automation")]})]})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsx(f,{children:e.jsxs(y,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:t("automations.stats.active","Active Workflows")})]}),e.jsx("p",{className:"text-2xl font-bold mt-2",children:(c==null?void 0:c.filter(j=>j.status==="active").length)||0})]})}),e.jsx(f,{children:e.jsxs(y,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Us,{className:"h-4 w-4 text-blue-500"}),e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:t("automations.stats.executions","This Month")})]}),e.jsx("p",{className:"text-2xl font-bold mt-2",children:(c==null?void 0:c.reduce((j,g)=>j+(g.run_count||0),0))||0})]})}),e.jsx(f,{children:e.jsxs(y,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(os,{className:"h-4 w-4 text-green-500"}),e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:t("automations.stats.templates","Available Templates")})]}),e.jsx("p",{className:"text-2xl font-bold mt-2",children:"10"})]})}),e.jsx(f,{children:e.jsxs(y,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"h-4 w-4 text-orange-500"}),e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:t("automations.stats.integrations","Integrations")})]}),e.jsx("p",{className:"text-2xl font-bold mt-2",children:"5"})]})})]}),e.jsxs(me,{value:i,onValueChange:n,children:[e.jsxs(ue,{className:"flex w-full md:grid md:grid-cols-6 lg:w-[900px]",children:[e.jsx(F,{value:"workflows",children:t("automations.tabs.workflows","My Workflows")}),e.jsx(F,{value:"ai",children:t("automations.tabs.ai","AI Insights")}),e.jsx(F,{value:"templates",children:t("automations.tabs.templates","Templates")}
7),e.jsx(F,{value:"integrations",children:t("automations.tabs.integrations","Integrations")}),e.jsx(F,{value:"logs",children:t("automations.tabs.logs","Execution Logs")}),e.jsx(F,{value:"history",children:t("automations.tabs.history","Execution History")})]}),e.jsx(L,{value:"workflows",className:"mt-6",children:e.jsx(Ys,{onEdit:o,onCreate:u})}),e.jsxs(L,{value:"ai",className:"mt-6 space-y-6",children:[e.jsx(tt,{}),e.jsx(at,{})]}),e.jsx(L,{value:"templates",className:"mt-6",children:e.jsx(Js,{onUseTemplate:j=>{s(!0)}})}),e.jsx(L,{value:"integrations",className:"mt-6",children:e.jsx(st,{})}),e.jsx(L,{value:"logs",className:"mt-6",children:e.jsx(Qs,{})}),e.jsx(L,{value:"history",className:"mt-6",children:e.jsx(et,{})})]}),e.jsx(mt,{open:a,onOpenChange:s,automationId:r}),e.jsx(Ze,{open:m,onOpenChange:l,onImportSuccess:()=>{l(!1),window.location.reload()}})]})})})}export{oi as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.