1import{aj as pi,am as xi,aT as $s,aU as gi,aw as un,n as $e,r as f,ao as bi,ax as yi,aV as h,aW as k,aX as pe,aY as B,aZ as P,a_ as O,a$ as ye,b0 as ze,b1 as cs,b2 as be,b3 as ht,b4 as gt,b5 as Qt,b6 as hn,b7 as ji,b8 as vi,b9 as wi,ba as Ni,bb as Ds,bc as mt,bd as Si,be as Ci,bf as ki,bg as ns,bh as ds,bi as Ti,bj as mn,bk as Ai,bl as fn,bm as zi,bn as bt,bo as Ut,bp as $i,bq as Di,br as Mi,J as U,K as W,bs as Qe,bt as Te,bu as _i,bv as Wt,bw as pn,bx as Ms,j as e,P as $,L as Ae,by as Ht}from"./main-B_Cvglal.js";import{u as de}from"./useQuery-I1jPbJgX.js";import{C as ee,a as ge,c as oe,d as ue,b as ce,e as us}from"./card-Dzs8kq2p.js";import{S as ie,a as ae,b as re,c as le,d as V}from"./select-BxkOIe63.js";import{b as fe,a as je,f as Fi,c as Be}from"./format-DVetQkco.js";import{e as xn,B as Y,f as _s,h as gn,p as Li,i as Pi,j as Ri,g as Ei}from"./badge-BvH43h95.js";import{B as T}from"./button-CfX9IiId.js";import{D as Ve,a as Je,b as Ke,c as Ye,d as Ge,e as Xe}from"./dialog-CMaLGqc_.js";import{I}from"./input-BTB84jqK.js";import{L as D}from"./label-DwJirtHu.js";import{p as qi,i as Oi,a as Bi,b as bn,P as Ii,c as Qi,d as Ui,e as Wi,r as Hi,f as Vi,g as Ji,h as Ki,N as Yi,j as Gi,k as At,l as dt,A as Xi}from"./iso-week-D4IMo93T.js";import{C as Fs}from"./checkbox-BcFAQ6hH.js";import{n as Zi,an as zt,b as yt,c as jt,d as vt,ap as Vt,e as wt,aq as Ls,ar as Ps,as as ea,at as ta,r as sa,au as na,av as ia,aw as aa,o as yn,x as is,ax as Oe,am as ra,ae as hs,af as ms,ag as xe,ah as Fe,S as la,ak as oa,p as ca}from"./tabs-Cr2NXDjd.js";import{a as fs,b as Le,c as K,d as ps,e as Q,T as jn}from"./table-Do2N_yis.js";import{T as te}from"./textarea-DqNHm87Z.js";import{c as Rs}from"./utils-4perknFd.js";import{c as Ue}from"./createLucideIcon-H4D3MNyv.js";import{a as Lt}from"./chevron-down-BmS6K-Ro.js";import{L as da}from"./loader-circle-B85RUEYh.js";import{X as ua}from"./x-CH_nOgn-.js";import{m as ha,l as ma,a as fa,d as pa}from"./broadcasts-C3cYaAwc.js";import{u as vn}from"./useInfiniteQuery-tVSyXMAD.js";import{u as xa,e as ga,S as ba,a as ya,b as ja,c as va,d as wa}from"./sheet-nN1oD64I.js";import{l as Na}from"./step-overrides-B44ShrZ9.js";import"./index-C_1LsUi4.js";import"./index-DJg7RvSn.js";import"./index-PDXJ-zF7.js";var Sa=class extends pi{#t;#n=void 0;#e;#s;constructor(s,t){super(),this.#t=s,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(s){const t=this.options;this.options=this.#t.defaultMutationOptions(s),xi(this.options,t)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#e,observer:this}),t?.mutationKey&&this.options.mutationKey&&$s(t.mutationKey)!==$s(this.options.mutationKey)?this.reset():this.#e?.state.status==="pending"&&this.#e.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#e?.removeObserver(this)}onMutationUpdate(s){this.#i(),this.#a(s)}getCurrentResult(){return this.#n}reset(){this.#e?.removeObserver(this),this.#e=void 0,this.#i(),this.#a()}mutate(s,t){return this.#s=t,this.#e?.removeObserver(this),this.#e=this.#t.getMutationCache().build(this.#t,this.options),this.#e.addObserver(this),this.#e.execute(s)}#i(){const s=this.#e?.state??gi();this.#n={...s,isPending:s.status==="pending",isSuccess:s.status==="success",isError:s.status==="error",isIdle:s.status==="idle",mutate:this.mutate,reset:this.reset}}#a(s){un.batch(()=>{if(this.#s&&this.hasListeners()){const t=this.#n.variables,n=this.#n.context,a={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(s?.type==="success"){try{this.#s.onSuccess?.(s.data,t,n,a)}catch(i){Promise.reject(i)}try{this.#s.onSettled?.(s.data,null,t,n,a)}catch(i){Promise.reject(i)}}else if(s?.type==="error"){try{this.#s.onError?.(s.error,t,n,a)}catch(i){Promise.reject(i)}try{this.#s.onSettled?.(void 0,s.error,t,n,a)}catch(i){Promise.reject(i)}}}this.listeners.forEach(t=>{t(this.#n)})})}};function Es(s,t){const n=$e(),[a]=f.useState(()=>new Sa(n,s));f.useEffect(()=>{a.setOptions(s)},[a,s]);const i=f.useSyncExternalStore(f.useCallback(l=>a.subscribe(un.batchCalls(l)),[a]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),r=f.useCallback((l,c)=>{a.mutate(l,c).catch(bi)},[a]);if(i.error&&yi(a.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:r,mutateAsync:i.mutate}}class $t{constructor(t){this.table=t}static[P]="ColumnAliasProxyHandler";get(t,n){return n==="table"?this.table:t[n]}}class xs{constructor(t,n){this.alias=t,this.replaceOriginalName=n}static[P]="TableAliasProxyHandler";get(t,n){if(n===O.Symbol.IsAlias)return!0;
1if(n===O.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===O.Symbol.OriginalName)return this.alias;if(n===ye)return{...t[ye],name:this.alias,isAlias:!0};if(n===O.Symbol.Columns){const i=t[O.Symbol.Columns];if(!i)return i;const r={};return Object.keys(i).map(l=>{r[l]=new Proxy(i[l],new $t(new Proxy(t,this)))}),r}const a=t[n];return k(a,pe)?new Proxy(a,new $t(new Proxy(t,this))):a}}function Jt(s,t){return new Proxy(s,new xs(t,!1))}function ke(s,t){return new Proxy(s,new $t(new Proxy(s.table,new xs(t,!1))))}function wn(s,t){return new B.Aliased(Dt(s.sql,t),s.fieldAlias)}function Dt(s,t){return h.join(s.queryChunks.map(n=>k(n,pe)?ke(n,t):k(n,B)?Dt(n,t):k(n,B.Aliased)?wn(n,t):n))}class gs extends Error{static[P]="DrizzleError";constructor({message:t,cause:n}){super(t),this.name="DrizzleError",this.cause=n}}class _e extends Error{constructor(t,n,a){super(`Failed query: ${t} 2params: ${n}`),this.query=t,this.params=n,this.cause=a,Error.captureStackTrace(this,_e),a&&(this.cause=a)}}class Ca extends gs{static[P]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class ka{static[P]="ConsoleLogWriter";write(t){console.log(t)}}class Ta{static[P]="DefaultLogger";writer;constructor(t){this.writer=t?.writer??new ka}logQuery(t,n){const a=n.map(r=>{try{return JSON.stringify(r)}catch{return String(r)}}),i=a.length?` -- params: [${a.join(", ")}]`:"";this.writer.write(`Query: ${t}${i}`)}}class Aa{static[P]="NoopLogger";logQuery(){}}class We{static[P]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(t){return this.then(void 0,t)}finally(t){return this.then(n=>(t?.(),n),n=>{throw t?.(),n})}then(t,n){return this.execute().then(t,n)}}function za(){return globalThis.__leapspaceWorkerEnv??null}class se{static[P]="SelectionProxyHandler";config;constructor(t){this.config={...t}}get(t,n){if(n==="_")return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(n===ye)return{...t[ye],selectedFields:new Proxy(t[ye].selectedFields,this)};if(typeof n=="symbol")return t[n];const i=(k(t,ze)?t._.selectedFields:k(t,cs)?t[ye].selectedFields:t)[n];if(k(i,B.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;const r=i.clone();return r.isSelectionField=!0,r}if(k(i,B)){if(this.config.sqlBehavior==="sql")return i;throw new Error(`You tried to reference "${n}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return k(i,pe)?this.config.alias?new Proxy(i,new $t(new Proxy(i.table,new xs(this.config.alias,this.config.replaceOriginalName??!1)))):i:typeof i!="object"||i===null?i:new Proxy(i,new se(this.config))}}function Ie(s){return k(s,be)?[`${s[O.Symbol.BaseName]}`]:k(s,ze)?s._.usedTables??[]:k(s,B)?s.usedTables??[]:[]}class qs extends We{constructor(t,n,a,i){super(),this.table=t,this.session=n,this.dialect=a,this.config={table:t,withList:i}}static[P]="SQLiteDelete";config;where(t){return this.config.where=t,this}orderBy(...t){if(typeof t[0]=="function"){const n=t[0](new Proxy(this.config.table[O.Symbol.Columns],new se({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),a=Array.isArray(n)?n:[n];this.config.orderBy=a}else{const n=t;this.config.orderBy=n}return this}limit(t){return this.config.limit=t,this}returning(t=this.table[be.Symbol.Columns]){return this.config.returning=ht(t),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:t,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(t=!0){return this.session[t?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:Ie(this.config.table)})}prepare(){return this._prepare(!1)}run=t=>this._prepare().run(t);all=t=>this._prepare().all(t);get=t=>this._prepare().get(t);values=t=>this._prepare().values(t);async execute(t){return this._prepare().execute(t)}$dynamic(){return this}}function $a(s){return(s.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(n=>n.toLowerCase()).join("_")}function Da(s){return(s.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((n,a,i)=>{const r=i===0?a.toLowerCase():`${a[0].toUpperCase()}${a.slice(1)}`;return n+r},"")}function Ma(s){return s}class _a{static[P]="CasingCache";cache={};cachedTables={};convert;constructor(t){this.convert=t==="snake_case"?$a:t==="camelCase"?Da:Ma}getColumnCasing(t){if(!t.keyAsName)return t.name;const n=t.table[O.Symbol.Schema]??"public",a=t.table[O.Symbol.OriginalName],i=`${n}.${a}.${t.name}`;return this.cache[i]||this.cacheTable(t.table),this.cache[i]}cacheTable(t){const n=t[O.Symbol.Schema]??"public",a=t[O.Symbol.OriginalName],i=`${n}.${a}`;if(!this.cachedTables[i]){for(const r of Object.values(t[O.Symbol.Columns])){const l=`${i}.${r.name}`;this.cache[l]=this.convert(r.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class bs extends cs{static[P]="SQLiteViewBase"}class Mt{static[P]="SQLiteDialect";casing;constructor(t){this.casing=new _a(t?.casing)}escapeName(t){return`"${t.replace(/"/g,'""')}"`}escapeParam(t){return"?"}escapeString(t){return`'${t.replace(/'/g,"''")}'`}buildWithCTE(t){if(!t?.length)return;const n=[h`with `];for(const[a,i]of t.entries())n.push(h`${h.identifier(i._.alias)} as (${i._.sql})`),a<t.length-1&&n.push(h`, `);return n.push(h` `),h.join(n)}buildDeleteQuery({table:t,where:n,returning:a,withList:i,limit:r,orderBy:l}){const c=this.buildWithCTE(i),d=a?h` returning ${this.buildSelection(a,{isSingleTable:!0})}`:void 0,u=n?h` where ${n}`:void 0,x=this.buildOrderBy(l),m=this.buildLimit(r);return h`${c}delete from ${t}${u}${d}${x}${m}`}buildUpdateSet(t,n){const a=t[O.Symbol.Columns],i=Object.keys(a).filter(l=>n[l]!==void 0||a[l]?.onUpdateFn!==void 0),r=i.length;return h.join(i.flatMap((l,c)=>{const d=a[l],u=d.onUpdateFn?.(),x=n[l]??(k(u,B)?u:h.param(u,d)),m=h`${h.identifier(this.casing.getColumnCasing(d))} = ${x}`;
2return c<r-1?[m,h.raw(", ")]:[m]}))}buildUpdateQuery({table:t,set:n,where:a,returning:i,withList:r,joins:l,from:c,limit:d,orderBy:u}){const x=this.buildWithCTE(r),m=this.buildUpdateSet(t,n),S=c&&h.join([h.raw(" from "),this.buildFromTable(c)]),A=this.buildJoins(l),M=i?h` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,b=a?h` where ${a}`:void 0,g=this.buildOrderBy(u),C=this.buildLimit(d);return h`${x}update ${t} set ${m}${S}${A}${b}${M}${g}${C}`}buildSelection(t,{isSingleTable:n=!1}={}){const a=t.length,i=t.flatMap(({field:r},l)=>{const c=[];if(k(r,B.Aliased)&&r.isSelectionField)c.push(h.identifier(r.fieldAlias));else if(k(r,B.Aliased)||k(r,B)){const d=k(r,B.Aliased)?r.sql:r;n?c.push(new B(d.queryChunks.map(u=>k(u,pe)?h.identifier(this.casing.getColumnCasing(u)):u))):c.push(d),k(r,B.Aliased)&&c.push(h` as ${h.identifier(r.fieldAlias)}`)}else if(k(r,pe)){const d=r.table[O.Symbol.Name];r.columnType==="SQLiteNumericBigInt"?n?c.push(h`cast(${h.identifier(this.casing.getColumnCasing(r))} as text)`):c.push(h`cast(${h.identifier(d)}.${h.identifier(this.casing.getColumnCasing(r))} as text)`):n?c.push(h.identifier(this.casing.getColumnCasing(r))):c.push(h`${h.identifier(d)}.${h.identifier(this.casing.getColumnCasing(r))}`)}else if(k(r,ze)){const d=Object.entries(r._.selectedFields);if(d.length===1){const u=d[0][1],x=k(u,B)?u.decoder:k(u,pe)?{mapFromDriverValue:m=>u.mapFromDriverValue(m)}:u.sql.decoder;x&&(r._.sql.decoder=x)}c.push(r)}return l<a-1&&c.push(h`, `),c});return h.join(i)}buildJoins(t){if(!t||t.length===0)return;const n=[];if(t)for(const[a,i]of t.entries()){a===0&&n.push(h` `);const r=i.table,l=i.on?h` on ${i.on}`:void 0;if(k(r,be)){const c=r[be.Symbol.Name],d=r[be.Symbol.Schema],u=r[be.Symbol.OriginalName],x=c===u?void 0:i.alias;n.push(h`${h.raw(i.joinType)} join ${d?h`${h.identifier(d)}.`:void 0}${h.identifier(u)}${x&&h` ${h.identifier(x)}`}${l}`)}else n.push(h`${h.raw(i.joinType)} join ${r}${l}`);a<t.length-1&&n.push(h` `)}return h.join(n)}buildLimit(t){return typeof t=="object"||typeof t=="number"&&t>=0?h` limit ${t}`:void 0}buildOrderBy(t){const n=[];if(t)for(const[a,i]of t.entries())n.push(i),a<t.length-1&&n.push(h`, `);return n.length>0?h` order by ${h.join(n)}`:void 0}buildFromTable(t){return k(t,O)&&t[O.Symbol.IsAlias]?h`${h`${h.identifier(t[O.Symbol.Schema]??"")}.`.if(t[O.Symbol.Schema])}${h.identifier(t[O.Symbol.OriginalName])} ${h.identifier(t[O.Symbol.Name])}`:t}buildSelectQuery({withList:t,fields:n,fieldsFlat:a,where:i,having:r,table:l,joins:c,orderBy:d,groupBy:u,limit:x,offset:m,distinct:S,setOperators:A}){const M=a??ht(n);for(const H of M)if(k(H.field,pe)&>(H.field.table)!==(k(l,ze)?l._.alias:k(l,bs)?l[ye].name:k(l,B)?void 0:gt(l))&&!(G=>c?.some(({alias:Z})=>Z===(G[O.Symbol.IsAlias]?gt(G):G[O.Symbol.BaseName])))(H.field.table)){const G=gt(H.field.table);throw new Error(`Your "${H.path.join("->")}" field references a column "${G}"."${H.field.name}", but the table "${G}" is not part of the query! Did you forget to join it?`)}const b=!c||c.length===0,g=this.buildWithCTE(t),C=S?h` distinct`:void 0,F=this.buildSelection(M,{isSingleTable:b}),_=this.buildFromTable(l),v=this.buildJoins(c),w=i?h` where ${i}`:void 0,L=r?h` having ${r}`:void 0,p=[];if(u)for(const[H,G]of u.entries())p.push(G),H<u.length-1&&p.push(h`, `);const j=p.length>0?h` group by ${h.join(p)}`:void 0,y=this.buildOrderBy(d),R=this.buildLimit(x),J=m?h` offset ${m}`:void 0,E=h`${g}select${C} ${F} from ${_}${v}${w}${j}${L}${y}${R}${J}`;return A.length>0?this.buildSetOperations(E,A):E}buildSetOperations(t,n){const[a,...i]=n;if(!a)throw new Error("Cannot pass undefined values to any set operator");return i.length===0?this.buildSetOperationQuery({leftSelect:t,setOperator:a}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:t,setOperator:a}),i)}buildSetOperationQuery({leftSelect:t,setOperator:{type:n,isAll:a,rightSelect:i,limit:r,orderBy:l,offset:c}}){const d=h`${t.getSQL()} `,u=h`${i.getSQL()}`;let x;if(l&&l.length>0){const M=[];for(const b of l)if(k(b,Qt))M.push(h.identifier(b.name));else if(k(b,B)){for(let g=0;g<b.queryChunks.length;g++){const C=b.queryChunks[g];k(C,Qt)&&(b.queryChunks[g]=h.identifier(this.casing.getColumnCasing(C)))}M.push(h`${b}`)}else M.push(h`${b}`);x=h` order by ${h.join(M,h`, `)}`}const m=typeof r=="object"||typeof r=="number"&&r>=0?h` limit ${r}`:void 0,S=h.raw(`${n} ${a?"all ":""}`),A=c?h` offset ${c}`:void 0;return h`${d}${S}${u}${x}${m}${A}`}buildInsertQuery({table:t,values:n,onConflict:a,returning:i,withList:r,select:l}){const c=[],d=t[O.Symbol.Columns],u=Object.entries(d).filter(([b,g])=>!g.shouldDisableInsert()),x=u.map(([,b])=>h.identifier(this.casing.getColumnCasing(b)));if(l){const b=n;k(b,B)?c.push(b):c.push(b.getSQL())}else{const b=n;c.push(h.raw("values "));for(const[g,C]of b.entries()){const F=[];for(const[_,v]of u){const w=C[_];if(w===void 0||k(w,hn)&&w.value===void 0){let L;if(v.default!==null&&v.default!==void 0)L=k(v.default,B)?v.default:h.param(v.default,v);else if(v.defaultFn!==void 0){const p=v.defaultFn();L=k(p,B)?p:h.param(p,v)}else if(!v.default&&v.onUpdateFn!==void 0){const p=v.onUpdateFn();L=k(p,B)?p:h.param(p,v)}else L=h`null`;F.push(L)}else F.push(w)}
2c.push(F),g<b.length-1&&c.push(h`, `)}}const m=this.buildWithCTE(r),S=h.join(c),A=i?h` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,M=a?.length?h.join(a):void 0;return h`${m}insert into ${t} ${x} ${S}${M}${A}`}sqlToQuery(t,n){return t.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:n})}buildRelationalQuery({fullSchema:t,schema:n,tableNamesMap:a,table:i,tableConfig:r,queryConfig:l,tableAlias:c,nestedQueryRelation:d,joinOn:u}){let x=[],m,S,A=[],M;const b=[];if(l===!0)x=Object.entries(r.columns).map(([F,_])=>({dbKey:_.name,tsKey:F,field:ke(_,c),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const C=Object.fromEntries(Object.entries(r.columns).map(([p,j])=>[p,ke(j,c)]));if(l.where){const p=typeof l.where=="function"?l.where(C,ji()):l.where;M=p&&Dt(p,c)}const F=[];let _=[];if(l.columns){let p=!1;for(const[j,y]of Object.entries(l.columns))y!==void 0&&j in r.columns&&(!p&&y===!0&&(p=!0),_.push(j));_.length>0&&(_=p?_.filter(j=>l.columns?.[j]===!0):Object.keys(r.columns).filter(j=>!_.includes(j)))}else _=Object.keys(r.columns);for(const p of _){const j=r.columns[p];F.push({tsKey:p,value:j})}let v=[];l.with&&(v=Object.entries(l.with).filter(p=>!!p[1]).map(([p,j])=>
2({tsKey:p,queryConfig:j,relation:r.relations[p]})));let w;if(l.extras){w=typeof l.extras=="function"?l.extras(C,{sql:h}):l.extras;for(const[p,j]of Object.entries(w))F.push({tsKey:p,value:wn(j,c)})}for(const{tsKey:p,value:j}of F)x.push({dbKey:k(j,B.Aliased)?j.fieldAlias:r.columns[p].name,tsKey:p,field:k(j,pe)?ke(j,c):j,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof l.orderBy=="function"?l.orderBy(C,vi()):l.orderBy??[];Array.isArray(L)||(L=[L]),A=L.map(p=>k(p,pe)?ke(p,c):Dt(p,c)),m=l.limit,S=l.offset;for(const{tsKey:p,queryConfig:j,relation:y}of v){const R=wi(n,a,y),J=Ni(y.referencedTable),E=a[J],H=`${c}_${p}`,G=Ds(...R.fields.map((he,De)=>mt(ke(R.references[De],H),ke(he,c)))),Z=this.buildRelationalQuery({fullSchema:t,schema:n,tableNamesMap:a,table:t[E],tableConfig:n[E],queryConfig:k(y,Si)?j===!0?{limit:1}:{...j,limit:1}:j,tableAlias:H,joinOn:G,nestedQueryRelation:y}),ve=h`(${Z.sql})`.as(p);x.push({dbKey:p,tsKey:p,field:ve,relationTableTsKey:E,isJson:!0,selection:Z.selection})}}if(x.length===0)throw new gs({message:`No fields selected for table "${r.tsName}" ("${c}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let g;if(M=Ds(u,M),d){let C=h`json_array(${h.join(x.map(({field:v})=>k(v,Qt)?h.identifier(this.casing.getColumnCasing(v)):k(v,B.Aliased)?v.sql:v),h`, `)})`;k(d,Ci)&&(C=h`coalesce(json_group_array(${C}), json_array())`);const F=[{dbKey:"data",tsKey:"data",field:C.as("data"),isJson:!0,relationTableTsKey:r.tsName,selection:x}];
2m!==void 0||S!==void 0||A.length>0?(g=this.buildSelectQuery({table:Jt(i,c),fields:{},fieldsFlat:[{path:[],field:h.raw("*")}],where:M,limit:m,offset:S,orderBy:A,setOperators:[]}),M=void 0,m=void 0,S=void 0,A=void 0):g=Jt(i,c),g=this.buildSelectQuery({table:k(g,be)?g:new ze(g,{},c),fields:{},fieldsFlat:F.map(({field:v})=>({path:[],field:k(v,pe)?ke(v,c):v})),joins:b,where:M,limit:m,offset:S,orderBy:A,setOperators:[]})}else g=this.buildSelectQuery({table:Jt(i,c),fields:{},fieldsFlat:x.map(({field:C})=>({path:[],field:k(C,pe)?ke(C,c):C})),joins:b,where:M,limit:m,offset:S,orderBy:A,setOperators:[]});return{tableTsKey:r.tsName,sql:g,selection:x}}}class Fa extends Mt{static[P]="SQLiteSyncDialect";migrate(t,n,a){const i=a===void 0||typeof a=="string"?"__drizzle_migrations":a.migrationsTable??"__drizzle_migrations",r=h` 3 CREATE TABLE IF NOT EXISTS ${h.identifier(i)} ( 4 id SERIAL PRIMARY KEY, 5 hash text NOT NULL, 6 created_at numeric 7 ) 8 `;n.run(r);const c=n.values(h`SELECT id, hash, created_at FROM ${h.identifier(i)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;n.run(h`BEGIN`);try{for(const d of t)if(!c||Number(c[2])<d.folderMillis){for(const u of d.sql)n.run(h.raw(u));n.run(h`INSERT INTO ${h.identifier(i)} ("hash", "created_at") VALUES(${d.hash}, ${d.folderMillis})`)}n.run(h`COMMIT`)}catch(d){throw n.run(h`ROLLBACK`),d}}}class La extends Mt{static[P]="SQLiteAsyncDialect";async migrate(t,n,a){const i=a===void 0||typeof a=="string"?"__drizzle_migrations":a.migrationsTable??"__drizzle_migrations",r=h` 9 CREATE TABLE IF NOT EXISTS ${h.identifier(i)} ( 10 id SERIAL PRIMARY KEY, 11 hash text NOT NULL, 12 created_at numeric 13 ) 14 `;await n.run(r);const c=(await n.values(h`SELECT id, hash, created_at FROM ${h.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await n.transaction(async d=>{for(const u of t)if(!c||Number(c[2])<u.folderMillis){for(const x of u.sql)await d.run(h.raw(x));await d.run(h`INSERT INTO ${h.identifier(i)} ("hash", "created_at") VALUES(${u.hash}, ${u.folderMillis})`)}})}}class Pa{static[P]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Pe{static[P]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(t){this.fields=t.fields,this.session=t.session,this.dialect=t.dialect,this.withList=t.withList,this.distinct=t.distinct}from(t){const n=!!this.fields;let a;return this.fields?a=this.fields:k(t,ze)?a=Object.fromEntries(Object.keys(t._.selectedFields).map(i=>[i,t[i]])):k(t,bs)?a=t[ye].selectedFields:k(t,B)?a={}:a=ki(t),new Nn({table:t,fields:a,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class Ra extends Pa{static[P]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:t,fields:n,isPartialSelect:a,session:i,dialect:r,withList:l,distinct:c}){super(),this.config={withList:l,table:t,fields:{...n},distinct:c,setOperators:[]},this.isPartialSelect=a,this.session=i,this.dialect=r,this._={selectedFields:n,config:this.config},this.tableName=ns(t),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(const d of Ie(t))this.usedTables.add(d)}getUsedTables(){return[...this.usedTables]}createJoin(t){return(n,a)=>{const i=this.tableName,r=ns(n);for(const l of Ie(n))this.usedTables.add(l);if(typeof r=="string"&&this.config.joins?.some(l=>l.alias===r))throw new Error(`Alias "${r}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i=="string"&&(this.config.fields={[i]:this.config.fields}),typeof r=="string"&&!k(n,B))){const l=k(n,ze)?n._.selectedFields:k(n,cs)?n[ye].selectedFields:n[O.Symbol.Columns];this.config.fields[r]=l}if(typeof a=="function"&&(a=a(new Proxy(this.config.fields,new se({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:a,table:n,joinType:t,alias:r}),typeof r=="string")switch(t){case"left":{this.joinsNotNullableMap[r]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[r]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[r]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[r]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(t,n){return a=>{const i=typeof a=="function"?a(Ea()):a;if(!ds(this.getSelectedFields(),i.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:t,isAll:n,rightSelect:i}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(t){return this.config.setOperators.push(...t),this}where(t){return typeof t=="function"&&(t=t(new Proxy(this.config.fields,new se({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=t,this}having(t){return typeof t=="function"&&(t=t(new Proxy(this.config.fields,new se({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=t,this}groupBy(...t){if(typeof t[0]=="function"){const n=t[0](new Proxy(this.config.fields,new se({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(n)?n:[n]}else this.config.groupBy=t;return this}orderBy(...t){if(typeof t[0]=="function"){const n=t[0](new Proxy(this.config.fields,new se({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),a=Array.isArray(n)?n:[n];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=a:this.config.orderBy=a}else{const n=t;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}return this}limit(t){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=t:this.config.limit=t,this}offset(t){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=t:this.config.offset=t,this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:t,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(t){const n=[];if(n.push(...Ie(this.config.table)),this.config.joins)for(const a of this.config.joins)n.push(...Ie(a.table));return new Proxy(new ze(this.getSQL(),this.config.fields,t,!1,[...new Set(n)]),new se({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new se({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class Nn extends Ra{static[P]="SQLiteSelect";_prepare(t=!0){if(!this.session)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");const n=ht(this.config.fields),a=this.session[t?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),n,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return a.joinsNotNullableMap=this.joinsNotNullableMap,a}$withCache(t){return this.cacheConfig=t===void 0?{config:{},enable:!0,autoInvalidate:!0}:t===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...t},this}prepare(){return this._prepare(!1)}run=t=>this._prepare().run(t);all=t=>this._prepare().all(t);get=t=>this._prepare().get(t);values=t=>this._prepare().values(t);async execute(){return this.all()}}Ti(Nn,[We]);function Pt(s,t){return(n,a,...i)=>
14{const r=[a,...i].map(l=>({type:s,isAll:t,rightSelect:l}));for(const l of r)if(!ds(n.getSelectedFields(),l.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return n.addSetOperators(r)}}const Ea=()=>({union:qa,unionAll:Oa,intersect:Ba,except:Ia}),qa=Pt("union",!1),Oa=Pt("union",!0),Ba=Pt("intersect",!1),Ia=Pt("except",!1);class Sn{static[P]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(t){this.dialect=k(t,Mt)?t:void 0,this.dialectConfig=k(t,Mt)?void 0:t}$with=(t,n)=>{const a=this;return{as:r=>(typeof r=="function"&&(r=r(a)),new Proxy(new mn(r.getSQL(),n??("getSelectedFields"in r?r.getSelectedFields()??{}:{}),t,!0),new se({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...t){const n=this;function a(r){return new Pe({fields:r??void 0,session:void 0,dialect:n.getDialect(),withList:t})}function i(r){return new Pe({fields:r??void 0,session:void 0,dialect:n.getDialect(),withList:t,distinct:!0})}return{select:a,selectDistinct:i}}select(t){return new Pe({fields:t??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(t){return new Pe({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||(this.dialect=new Fa(this.dialectConfig)),this.dialect}}class Os{constructor(t,n,a,i){this.table=t,this.session=n,this.dialect=a,this.withList=i}static[P]="SQLiteInsertBuilder";values(t){if(t=Array.isArray(t)?t:[t],t.length===0)throw new Error("values() must be called with at least one value");const n=t.map(a=>{const i={},r=this.table[O.Symbol.Columns];for(const l of Object.keys(a)){const c=a[l];i[l]=k(c,B)?c:new hn(c,r[l])}return i});return new Bs(this.table,n,this.session,this.dialect,this.withList)}select(t){const n=typeof t=="function"?t(new Sn):t;if(!k(n,B)&&!ds(this.table[Ai],n._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new Bs(this.table,n,this.session,this.dialect,this.withList,!0)}}class Bs extends We{constructor(t,n,a,i,r,l){super(),this.session=a,this.dialect=i,this.config={table:t,values:n,withList:r,select:l}}static[P]="SQLiteInsert";config;returning(t=this.config.table[be.Symbol.Columns]){return this.config.returning=ht(t),this}onConflictDoNothing(t={}){if(this.config.onConflict||(this.config.onConflict=[]),t.target===void 0)this.config.onConflict.push(h` on conflict do nothing`);else{const n=Array.isArray(t.target)?h`${t.target}`:h`${[t.target]}`,a=t.where?h` where ${t.where}`:h``;this.config.onConflict.push(h` on conflict ${n} do nothing${a}`)}return this}onConflictDoUpdate(t){if(t.where&&(t.targetWhere||t.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');this.config.onConflict||(this.config.onConflict=[]);const n=t.where?h` where ${t.where}`:void 0,a=t.targetWhere?h` where ${t.targetWhere}`:void 0,i=t.setWhere?h` where ${t.setWhere}`:void 0,r=Array.isArray(t.target)?h`${t.target}`:h`${[t.target]}`,l=this.dialect.buildUpdateSet(this.config.table,fn(this.config.table,t.set));return this.config.onConflict.push(h` on conflict ${r}${a} do update set ${l}${n}${i}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:t,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(t=!0){return this.session[t?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Ie(this.config.table)})}prepare(){return this._prepare(!1)}run=t=>this._prepare().run(t);all=t=>this._prepare().all(t);get=t=>this._prepare().get(t);values=t=>this._prepare().values(t);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class Is{constructor(t,n,a,i){this.table=t,this.session=n,this.dialect=a,this.withList=i}static[P]="SQLiteUpdateBuilder";set(t){return new Qa(this.table,fn(this.table,t),this.session,this.dialect,this.withList)}}class Qa extends We{constructor(t,n,a,i,r){super(),this.session=a,this.dialect=i,this.config={set:n,table:t,withList:r,joins:[]}}static[P]="SQLiteUpdate";config;from(t){return this.config.from=t,this}createJoin(t){return(n,a)=>{const i=ns(n);if(typeof i=="string"&&this.config.joins.some(r=>r.alias===i))throw new Error(`Alias "${i}" is already used in this query`);
14if(typeof a=="function"){const r=this.config.from?k(n,be)?n[O.Symbol.Columns]:k(n,ze)?n._.selectedFields:k(n,bs)?n[ye].selectedFields:void 0:void 0;a=a(new Proxy(this.config.table[O.Symbol.Columns],new se({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),r&&new Proxy(r,new se({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:a,table:n,joinType:t,alias:i}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(t){return this.config.where=t,this}orderBy(...t){if(typeof t[0]=="function"){const n=t[0](new Proxy(this.config.table[O.Symbol.Columns],new se({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),a=Array.isArray(n)?n:[n];this.config.orderBy=a}else{const n=t;this.config.orderBy=n}return this}limit(t){return this.config.limit=t,this}returning(t=this.config.table[be.Symbol.Columns]){return this.config.returning=ht(t),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:t,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(t=!0){return this.session[t?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Ie(this.config.table)})}prepare(){return this._prepare(!1)}run=t=>this._prepare().run(t);all=t=>this._prepare().all(t);get=t=>this._prepare().get(t);values=t=>this._prepare().values(t);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class _t extends B{constructor(t){super(_t.buildEmbeddedCount(t.source,t.filters).queryChunks),this.params=t,this.session=t.session,this.sql=_t.buildCount(t.source,t.filters)}sql;static[P]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(t,n){return h`(select count(*) from ${t}${h.raw(" where ").if(n)}${n})`}static buildCount(t,n){return h`select count(*) from ${t}${h.raw(" where ").if(n)}${n}`}then(t,n){return Promise.resolve(this.session.count(this.sql)).then(t,n)}catch(t){return this.then(void 0,t)}finally(t){return this.then(n=>(t?.(),n),n=>{throw t?.(),n})}}class Ua{constructor(t,n,a,i,r,l,c,d){this.mode=t,this.fullSchema=n,this.schema=a,this.tableNamesMap=i,this.table=r,this.tableConfig=l,this.dialect=c,this.session=d}static[P]="SQLiteAsyncRelationalQueryBuilder";findMany(t){return this.mode==="sync"?new Qs(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t||{},"many"):new as(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t||{},"many")}findFirst(t){return this.mode==="sync"?new Qs(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t?{...t,limit:1}:{limit:1},"first"):new as(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t?{...t,limit:1}:{limit:1},"first")}}class as extends We{constructor(t,n,a,i,r,l,c,d,u){super(),this.fullSchema=t,this.schema=n,this.tableNamesMap=a,this.table=i,this.tableConfig=r,this.dialect=l,this.session=c,this.config=d,this.mode=u}static[P]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(t=!1){const{query:n,builtQuery:a}=this._toSQL();return this.session[t?"prepareOneTimeQuery":"prepareQuery"](a,void 0,this.mode==="first"?"get":"all",!0,(i,r)=>{const l=i.map(c=>zi(this.schema,this.tableConfig,c,n.selection,r));return this.mode==="first"?l[0]:l})}prepare(){return this._prepare(!1)}_toSQL(){const t=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),n=this.dialect.sqlToQuery(t.sql);return{query:t,builtQuery:n}}toSQL(){return this._toSQL().builtQuery}executeRaw(){return this.mode==="first"?this._prepare(!1).get():this._prepare(!1).all()}async execute(){return this.executeRaw()}}class Qs extends as{static[P]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}class Nt extends We{constructor(t,n,a,i,r){super(),this.execute=t,this.get
14SQL=n,this.dialect=i,this.mapBatchResult=r,this.config={action:a}}static[P]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(t,n){return n?this.mapBatchResult(t):t}_prepare(){return this}isResponseInArrayMode(){return!1}}class Cn{constructor(t,n,a,i){this.resultKind=t,this.dialect=n,this.session=a,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};const r=this.query;if(this._.schema)for(const[l,c]of Object.entries(this._.schema))r[l]=new Ua(t,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[l],c,n,a);this.$cache={invalidate:async l=>{}}}static[P]="BaseSQLiteDatabase";query;$with=(t,n)=>{const a=this;return{as:r=>(typeof r=="function"&&(r=r(new Sn(a.dialect))),new Proxy(new mn(r.getSQL(),n??("getSelectedFields"in r?r.getSelectedFields()??{}:{}),t,!0),new se({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(t,n){return new _t({source:t,filters:n,session:this.session})}with(...t){const n=this;function a(d){return new Pe({fields:d??void 0,session:n.session,dialect:n.dialect,withList:t})}function i(d){return new Pe({fields:d??void 0,session:n.session,dialect:n.dialect,withList:t,distinct:!0})}function r(d){return new Is(d,n.session,n.dialect,t)}function l(d){return new Os(d,n.session,n.dialect,t)}function c(d){return new qs(d,n.session,n.dialect,t)}return{select:a,selectDistinct:i,update:r,insert:l,delete:c}}select(t){return new Pe({fields:t??void 0,session:this.session,dialect:this.dialect})}selectDistinct(t){return new Pe({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(t){return new Is(t,this.session,this.dialect)}$cache;insert(t){return new Os(t,this.session,this.dialect)}delete(t){return new qs(t,this.session,this.dialect)}run(t){const n=typeof t=="string"?h.raw(t):t.getSQL();return this.resultKind==="async"?new Nt(async()=>this.session.run(n),()=>n,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session)):this.session.run(n)}all(t){const n=typeof t=="string"?h.raw(t):t.getSQL();return this.resultKind==="async"?new Nt(async()=>this.session.all(n),()=>n,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session)):this.session.all(n)}get(t){const n=typeof t=="string"?h.raw(t):t.getSQL();return this.resultKind==="async"?new Nt(async()=>this.session.get(n),()=>n,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session)):this.session.get(n)}values(t){const n=typeof t=="string"?h.raw(t):t.getSQL();return this.resultKind==="async"?new Nt(async()=>this.session.values(n),()=>n,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session)):this.session.values(n)}transaction(t,n){return this.session.transaction(t,n)}}class Wa{static[P]="Cache"}class kn extends Wa{strategy(){return"all"}static[P]="NoopCache";async get(t){}async put(t,n,a,i){}async onMutate(t){}}async function Us(s,t){const n=`${s}-${JSON.stringify(t)}`,i=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",i);return[...new Uint8Array(r)].map(d=>d.toString(16).padStart(2,"0")).join("")}class Ha extends We{constructor(t){super(),this.resultCb=t}static[P]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}}class Va{constructor(t,n,a,i,r,l){this.mode=t,this.executeMethod=n,this.query=a,this.cache=i,this.queryMetadata=r,this.cacheConfig=l,i&&i.strategy()==="all"&&l===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}static[P]="PreparedQuery";joinsNotNullableMap;async queryWithCache(t,n,a){if(this.cache===void 0||k(this.cache,kn)||this.queryMetadata===void 0)try{return await a()}catch(i){throw new _e(t,n,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await a()}catch(i){throw new _e(t,n,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{const[i]=await Promise.all([a(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new _e(t,n,i)}if(!this.cacheConfig)try{return await a()}catch(i){throw new _e(t,n,i)}if(this.queryMetadata.type==="select"){const i=await this.cache.get(this.cacheConfig.tag??await Us(t,n),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let r;try{r=await a()}catch(l){throw new _e(t,n,l)}return await this.cache.put(this.cacheConfig.tag??await Us(t,n),r,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),r}return i}try{return await a()}catch(i){throw new _e(t,n,i)}}getQuery(){return this.query}mapRunResult(t,n){return t}mapAllResult(t,n){throw new Error("Not implemented")}mapGetResult(t,n){throw new Error("Not implemented")}execute(t){return this.mode==="async"?this[this.executeMethod](t):new Ha(()=>this[this.executeMethod](t))}mapResult(t,n){switch(this.executeMethod){case"run":return this.mapRunResult(t,n);case"all":return this.mapAllResult(t,n);case"get":return this.mapGetResult(t,n)}}}class Ja{constructor(t){this.dialect=t}static[P]="SQLiteSession";prepareOneTimeQuery(t,n,a,i,r,l,c){return this.prepareQuery(t,n,a,i,r,l,c)}run(t){const n=this.dialect.sqlToQuery(t);try{return this.prepareOneTimeQuery(n,void 0,"run",!1).run()}catch(a){throw new gs({cause:a,message:`Failed to run the query '${n.sql}'`})}}extractRawRunValueFromBatchResult(t){return t}all(t){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(t),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(t){throw new Error("Not implemented")}get(t){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(t),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(t){throw new Error("Not implemented")}values(t){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(t),void 0,"run",!1).values()}async count(t){return(await this.values(t))[0][0]}extractRawValuesValueFromBatchResult(t){throw new Error("Not implemented")}}class Ka extends Cn{constructor(t,n,a,i,r=0){super(t,n,a,i),this.schema=i,this.nestedIndex=r}static[P]="SQLiteTransaction";rollback(){throw new Ca}}class Ya extends Ja{constructor(t,n,a,i={}){super(n),this.client=t,this.schema=a,this.options=i,this.logger=i.logger??new Aa,this.cache=i.cache??new kn}static[P]="SQLiteD1Session";logger;cache;prepareQuery(t,n,a,i,r,l,c){const d=this.client.prepare(t.sql);return new Ga(d,t,this.logger,this.cache,l,c,n,a,i,r)}async batch(t){const n=[],a=[];for(const r of t){const l=r._prepare(),c=l.getQuery();if(n.push(l),c.params.length>0)a.push(l.stmt.bind(...c.params));else{const d=l.getQuery();a.push(this.client.prepare(d.sql).bind(...d.params))}}return(await this.client.batch(a)).map((r,l)=>n[l].mapResult(r,!0))}extractRawAllValueFromBatchResult(t){return t.results}extractRawGetValueFromBatchResult(t){return t.results[0]}extractRawValuesValueFromBatchResult(t){return rs(t.results)}async transaction(t,n){const a=new ys("async",this.dialect,this,this.schema);await this.run(h.raw(`begin${n?.behavior?" "+n.behavior:""}`));try{const i=await t(a);return await this.run(h`commit`),i}catch(i){throw await this.run(h`rollback`),i}}}
14class ys extends Ka{static[P]="D1Transaction";async transaction(t){const n=`sp${this.nestedIndex}`,a=new ys("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(h.raw(`savepoint ${n}`));try{const i=await t(a);return await this.session.run(h.raw(`release savepoint ${n}`)),i}catch(i){throw await this.session.run(h.raw(`rollback to savepoint ${n}`)),i}}}function rs(s){const t=[];for(const n of s){const a=Object.keys(n).map(i=>n[i]);t.push(a)}return t}class Ga extends Va{constructor(t,n,a,i,r,l,c,d,u,x){super("async",d,n,i,r,l),this.logger=a,this._isResponseInArrayMode=u,this.customResultMapper=x,this.fields=c,this.stmt=t}static[P]="D1PreparedQuery";customResultMapper;fields;stmt;async run(t){const n=bt(this.query.params,t??{});return this.logger.logQuery(this.query.sql,n),await this.queryWithCache(this.query.sql,n,async()=>this.stmt.bind(...n).run())}async all(t){const{fields:n,query:a,logger:i,stmt:r,customResultMapper:l}=this;if(!n&&!l){const d=bt(a.params,t??{});return i.logQuery(a.sql,d),await this.queryWithCache(a.sql,d,async()=>r.bind(...d).all().then(({results:u})=>this.mapAllResult(u)))}const c=await this.values(t);return this.mapAllResult(c)}mapAllResult(t,n){return n&&(t=rs(t.results)),!this.fields&&!this.customResultMapper?t:this.customResultMapper?this.customResultMapper(t):t.map(a=>Ut(this.fields,a,this.joinsNotNullableMap))}async get(t){const{fields:n,joinsNotNullableMap:a,query:i,logger:r,stmt:l,customResultMapper:c}=this;if(!n&&!c){const u=bt(i.params,t??{});return r.logQuery(i.sql,u),await this.queryWithCache(i.sql,u,async()=>l.bind(...u).all().then(({results:x})=>x[0]))}const d=await this.values(t);if(d[0])return c?c(d):Ut(n,d[0],a)}mapGetResult(t,n){return n&&(t=rs(t.results)[0]),!this.fields&&!this.customResultMapper?t:this.customResultMapper?this.customResultMapper([t]):Ut(this.fields,t,this.joinsNotNullableMap)}async values(t){const n=bt(this.query.params,t??{});return this.logger.logQuery(this.query.sql,n),await this.queryWithCache(this.query.sql,n,async()=>this.stmt.bind(...n).raw())}isResponseInArrayMode(){return this._isResponseInArrayMode}}class Xa extends Cn{static[P]="D1Database";async batch(t){return this.session.batch(t)}}function Za(s,t={}){const n=new La({casing:t.casing});let a;t.logger===!0?a=new Ta:t.logger!==!1&&(a=t.logger);let i;if(t.schema){const c=$i(t.schema,Di);i={fullSchema:t.schema,schema:c.tables,tableNamesMap:c.tableNamesMap}}const r=new Ya(s,n,i,{logger:a,cache:t.cache}),l=new Xa("async",n,r,i);return l.$client=s,l.$cache=t.cache,l.$cache&&(l.$cache.invalidate=t.cache?.onMutate),l}function er(s){return Za(s,{schema:Mi})}function ut(){const s=za();if(!s?.DB)throw new Error("D1 binding `DB` not present on env");return er(s.DB)}const tr=U({method:"POST"}).handler(W("5ceddf5ed4d2043404c598fbcfbee5a59a9a643d22e31ee48eed4003ecad10c6"));function Ft(s){const t=s?.trim();if(!t)return;if(t.includes("{{"))return t;const n=t.split("@").at(0),a=t.includes("@")?n:t;if(!a)return;const i=a.replace(/[._-]+/g," ").trim();if(i)return i.split(/\s+/).map(sr).join(" ")}function sr(s){if(s!==s.toLowerCase())return s;const t=s.at(0);return t?`${t.toUpperCase()}${s.slice(1)}`:s}const ot=s=>({ms:s*864e5});const Ws=120*6e4;function Hs(s){return typeof s=="object"&&s!==null}function Kt(){return Qe.WORKFLOW_BASE_URL??pn()}async function Yt(){const t=await ut().select({shellJson:Wt.shellJson}).from(Wt).where(mt(Wt.workflowKey,"newsletter")).limit(1).then(n=>n.at(0));return zt(t?.shellJson)??void 0}const nr={kind:"broadcast",key:"newsletter",displayName:"Newsletter",description:"Recurring weekly broadcast with product updates. Audience: waitlist members on weekly or milestones cadence, joined at least 2h before send.",audienceDescription:'waitlistMembers.notificationFrequency in ("weekly", "milestones") AND joinedAt ⤠scheduledAt - 2h AND not in workflowSuppressions',schedule:"0 14 * * THU",defaultFromAddress:"[email protected]",defaultReplyTo:"[email protected]",minMembershipAgeMs:Ws,audience:async({scheduledAt:s})=>{const t=ut(),n=s-Ws;
14return(await t.select({id:Te.id,emailNormalized:Te.emailNormalized,notificationFrequency:Te.notificationFrequency}).from(Te).where(_i(Te.joinedAt,new Date(n)))).filter(i=>i.emailNormalized!=null).filter(i=>i.notificationFrequency==="weekly"||i.notificationFrequency==="milestones").map(i=>i.id)},loadRecipientContext:async s=>{const n=await ut().select().from(Te).where(mt(Te.id,s)).limit(1).then(i=>i.at(0)),a=await Yt();return{name:Ft(n?.fullName??n?.emailNormalized??void 0),language:n?.language??void 0,referralCode:n?.referralCode,baseUrl:Kt(),postalAddress:a?.postalAddress??Qe.COMPANY_POSTAL_ADDRESS,shell:a}},loadExternalRecipientContext:async()=>{const s=await Yt();return{baseUrl:Kt(),postalAddress:s?.postalAddress??Qe.COMPANY_POSTAL_ADDRESS,shell:s}},isPayloadComplete:s=>{const t=qi(s);if(t!==null||Hs(s)&&s.layout==="tsx")return Oi(t);const n=Bi(s);if(n)return bn(n);if(!Hs(s))return!1;const{subject:a,bodyHtml:i,bodyJson:r}=s;return typeof a!="string"||a.trim().length===0?!1:typeof r=="string"&&r.trim().length>0?Zi(r):typeof i=="string"&&i.trim().length>=50},createPreviewCtx:async(s,t,n)=>{const a=n?.shellOverride??await Yt(),i=Kt();return{name:Ft(s)??"there",language:t,referralCode:"PREVIEW",baseUrl:i,postalAddress:a?.postalAddress??Qe.COMPANY_POSTAL_ADDRESS,shell:a,unsubscribeUrl:`${i}/api/wf/unsubscribe?preview=1`}}},Vs=nr,ir=/\b\d{5,6}(?:-\d{4})?\b/;function ar(s){if(s==="knowledge_creator")return"knowledge_creator";if(s==="startup_community")return"startup_community";if(s==="after_school")return"after_school"}function rr(){return Qe.WORKFLOW_BASE_URL??pn()}function lr(){const s=Qe.COMPANY_POSTAL_ADDRESS?.trim();return s&&s.length>0?s:void 0}function or(s){return s?.match(ir)?.[0]}function ls(s){const t=lr(),n=rr();return{...s,baseUrl:n,fullAddress:t,postalAddress:t,pincode:or(t),unsubscribeUrl:`${n}/api/wf/unsubscribe?preview=1`}}async function Js(s){const n=await ut().select().from(Te).where(mt(Te.id,s)).limit(1).then(a=>a.at(0));return n?ls({name:Ft(n.fullName??void 0),icpSegment:ar(n.icpSegment),language:n.language??void 0,referralCode:n.referralCode}):null}const cr={kind:"sequence",key:"nurture",displayName:"Nurture",description:"Six-email welcome and education sequence for new waitlist members.",audienceDescription:'Every new waitlist signup with notificationFrequency != "off". Excludes globally-suppressed emails.',trigger:{type:"auto_on_signup"},defaultFromAddress:"[email protected]",defaultReplyTo:"[email protected]",loadContext:async s=>{const n=await ut().select().from(Ms).where(mt(Ms.id,s)).limit(1).then(i=>i.at(0));if(!n)throw new Error("Enrollment not found");const a=await Js(n.memberId);if(!a)throw new Error("Member not found for enrollment");return a},loadContextForOneOff:async s=>{const t=await Js(s);if(!t)throw new Error("Member not found");return t},createPreviewCtx:(s,t)=>ls({name:Ft(s)??"admin",icpSegment:void 0,language:t,referralCode:"PREVIEW"}),createTokenCtx:()=>ls({name:"{{name}}",icpSegment:void 0,language:"en",referralCode:"{{referralCode}}"}),steps:[{kind:"send_email",key:"ls01_welcome",description:"Welcome to Orian. Single template; greets by name when known, segments opener by ICP, conditionally shows profile-completion CTA when icpSegment is missing."},{kind:"wait",key:"w_after_ls01_welcome",description:"3 days",delay:ot(3)},{kind:"send_email",key:"ls02_problem",description:"Validates the community-ops pain (repeat onboarding, midnight DMs, buried posts). No CTA â empathy build."},{kind:"wait",key:"w_after_ls02_problem",description:"5 days",delay:ot(5)},{kind:"send_email",key:"ls03_solution",description:"Introduces the Orian approach: three pillars (member memory, AI as the engine, surface-not-feed). Sets product POV; no CTA."},{kind:"wait",key:"w_after_ls03_solution",description:"7 days",delay:ot(7)},{kind:"send_email",key:"ls04_proof",description:"Honest social proof: three patterns from listening to operators on the waitlist. Bridges to LS-05 referral."},{kind:"wait",key:"w_after_ls04_proof",description:"7 days",delay:ot(7)},{kind:"send_email",key:"ls05_referral",description:'Referral nudge. Callback to LS-04 patterns, share-with-three ask, member referral link, "moves you up the queue" mechanic.'},{kind:"wait",key:"w_after_ls05_referral",description:"14 days",delay:ot(14)},{kind:"send_email",key:"ls06_close",description:"Graduation email: thanks, recap, and three things going forward. Closes the orientation."}],exitConditions:[{reason:"member_status_activated",when:s=>Promise.resolve(s.referralCode.length===0)}]},Ks=cr,dr={[Ks.key]:Ks,[Vs.key]:Vs};function ur(){return Qe.ALLOWED_FROM_DOMAINS.split(",").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0)}function hr(s){const t=s.lastIndexOf("@");if(t<0)return!1;const n=s.slice(t+1).toLowerCase();return ur().includes(n)}function mr(){const s=new Set;for(const t of Object.values(dr)){if(s.has(t.key))throw new Error(`Duplicate workflow key: ${t.key}`);if(s.add(t.key),!hr(t.defaultFromAddress))throw new Error(`Workflow ${t.key} defaultFromAddress not in ALLOWED_FROM_DOMAINS: ${t.defaultFromAddress}`);if(t.kind==="sequence"){const n=new Set,a=new Set;for(const i of t.steps){if(i.kind==="send_email"){if(n.has(i.key))throw new Error(`Workflow ${t.key} has duplicate step key: ${i.key}`);n.add(i.key);continue}if(i.kind==="wait"){if(a.has(i.key))throw new Error(`Workflow ${t.key} has duplicate wait key: ${i.key}`);a.add(i.key)}}}}}mr();U({method:"GET"}).handler(W("ec74f51c0ef3946366b4fb4f3583703651efa14aec35faffe5918d5047124dec"));U({method:"GET"}).handler(W("905bbe11920f405a0e15c106ac5425573526af994d164aff22af646de903e37f"));const fr=U({method:"POST"}).handler(W("2193ba0f73464f8ca0604a77ab095f07beeea268ad1f8a9b4eaccacf113984c0")),pr=U({method:"GET"}).handler(W("d184f0da546e0ef4d21936f8bd5891877bec75ff78ca451d2ecd11e13cfeeb56")),Ys=U({method:"POST"}).handler(W("8f9decd5921e490e191f0246cc7cc6c68eadb017ef433ece04edbb7ba4244767"));U({method:"POST"}).handler(W("f930c32243a5603ff1abdd9a8d9a6f9974b4422203b1ad4b20a40b98ef48ccd0"));const xr=U({method:"POST"}).handler(W("9ed5bc5331e1fdcfdba23dd73f019e563a2ce759cb5f22024132fc5dc8453bce")),gr=U({method:"POST"}).handler(W("a61b4387dd357489bb59e80177a377f9de70ddc307499f02cb9bd2ce87d8b4ac")),br=U({method:"POST"}).handler(W("e8cfddd5dfb8ecb2ebe0072f876e2e1e323b730bb9b97e3842623ad930dccbad")),yr=U({method:"POST"}).handler(W("a0b0ce12f2173f1a75c17f2dc79dcde37c13f4ccf48b424fcd8b1bfaf9950a0e")),jr=U({method:"POST"}).handler(W("831a7cfc4356ae6eebb1d0b00c58018709d032c640f727bdbb800e1c934a72b3")),vr=U({method:"POST"}).handler(W("d247f430eb5c859449022f4c7cb8b1ecf1c9efb71ee7a735679528ec029f19eb")),wr=U({method:"POST"}).handler(W("c50adef9e7f1125749d7b0519799d78a6a9994b5a91e27a69d2c15874c651606")),Nr=U({method:"POST"}).handler(W("38275712ffc101e95de523fba4268787382f1fbccedd341aa856b29482a7be97")),Sr=U({method:"POST"}).handler(W("09077d9722273d1b6f646a1e37a4d47c76cb29d35cdb133837a81751ba29f8c4"));U({method:"POST"}).handler(W("c1073ef6609b66be78b0fdf29e5521f2d41e83486b07f163a034238c3f048fec"));const Tn=U({method:"GET"}).handler(W("852ecada32e8ffd079244df49136a78bd9742049ded605f8e57c10607aa7875c")),Cr=U({method:"POST"}).handler(W("e03d00b51490a8f3ee52cf73e1274ad05730f02dd8fbfae2277106ff00d52e61")),kr=U({method:"GET"}).handler(W("66f99f980716ab157e21ee76aaa121bfa5fe85006d020b5fae5bac815d0d3cd9")),Tr=U({method:"POST"}).handler(W("509f453d4e256676f4a4607efa3ce1783197eddf08c429158d3022e9d6780eda"));U({method:"GET"}).handler(W("293e090d5677f7cdf8b6e4ff9b44dc9e4a41ed59b3647518c8c0401e12da368a"));const Ar=U({method:"POST"}).handler(W("6633a89a2eea1295e4858d3fc1ab5900d5781e68b75a7e2f6a9b81553aaae7f3")),zr=U({method:"POST"}).handler(W("6082f1f59781624a1ffe1a487e2e90a958c4ac23b9406eacffa4dda819f6e0d7"));const $r=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],Dr=Ue("calendar",$r);const Mr=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],_r=Ue("chevron-right",Mr);const Fr=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Lr=Ue("clock",Fr);const Pr=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],Rr=Ue("funnel",Pr);const Er=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}
14]],qr=Ue("radio",Er);const Or=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Br=Ue("search",Or);const Ir=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],Qr=Ue("users",Ir);function Ur({onWindowChange:s,window:t,workflowKey:n}){const{data:a,error:i,isLoading:r}=de({queryKey:["admin","workflowAnalytics",n,t],queryFn:()=>xn({data:{workflowKey:n,window:t}})});return e.jsxs(ee,{children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(oe,{children:"Analytics"}),e.jsx(ue,{children:"How emails are performing in this window."})]}),e.jsxs(ie,{onValueChange:l=>s(l),value:t,children:[e.jsx(ae,{className:"w-[160px]",children:e.jsx(re,{})}),e.jsxs(le,{children:[e.jsx(V,{value:"7d",children:"Last 7 days"}),e.jsx(V,{value:"30d",children:"Last 30 days"}),e.jsx(V,{value:"90d",children:"Last 90 days"})]})]})]})}),e.jsx(ce,{className:"space-y-6",children:r?e.jsx(Wr,{}):i?e.jsx("p",{className:"text-sm text-rose-600",children:i.message}):a?e.jsx(Hr,{data:a}):null})]})}function Wr(){return e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-5",children:Array.from({length:5}).map((s,t)=>e.jsx("div",{className:"h-20 animate-pulse rounded-lg bg-zinc-100"},t))}),e.jsx("div",{className:"h-20 animate-pulse rounded-md bg-zinc-100"})]})}function Hr({data:s}){const t=s.kpis,n=[{label:"Sent",value:t.sent.toLocaleString()},{label:"Delivered",sub:t.sent>0?fe(t.deliveredRate):void 0,value:t.delivered.toLocaleString()},{label:"Opened",sub:fe(t.openRate),value:t.opened.toLocaleString()},{label:"Clicked",sub:fe(t.clickRate),value:t.clicked.toLocaleString()},{label:"Bounced",sub:t.sent>0?fe(t.bouncedRate):void 0,tone:t.bouncedRate>.02?"danger":"default",value:t.bounced.toLocaleString()},{label:"Spam reports",sub:t.sent>0?fe(t.spamReportRate):void 0,tone:t.spamReportRate>.001?"danger":"default",value:t.spamReport.toLocaleString()},{label:"Unsubscribed",value:t.unsubscribed.toLocaleString()}],a=Math.max(1,...s.byDay.map(i=>i.sent));return e.jsxs("div",{className:"space-y-6",children:[e.jsx("dl",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-7",children:n.map(i=>e.jsxs("div",{className:"rounded-lg bg-white p-3 ring-1 ring-black/5",children:[e.jsx("dt",{className:"truncate text-xs text-zinc-500",children:i.label}),e.jsx("dd",{className:`mt-1 text-2xl font-semibold tabular-nums ${i.tone==="danger"?"text-rose-700":i.tone==="warn"?"text-amber-700":"text-zinc-900"}`,children:i.value}),i.sub?e.jsx("p",{className:"text-xs text-zinc-500 tabular-nums",children:i.sub}):null]},i.label))}),e.jsxs("section",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium text-zinc-700",children:"Send volume"}),s.byDay.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No sends in this window."}):e.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(20px,1fr))] gap-1",children:s.byDay.map(i=>e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("div",{className:"w-full rounded-sm bg-zinc-700",style:{height:`${Math.max(2,i.sent/a*60)}px`},title:`${i.day} · ${i.sent} sent`}),e.jsx("span",{className:"text-[10px] text-zinc-500 tabular-nums",children:i.day.slice(5)})]},i.day))})]}),s.byStep&&s.byStep.length>0?e.jsxs("section",{children:[e.jsx("h4",{className:"mb-3 text-sm font-medium text-zinc-700",children:"Per-step engagement"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-black/10 text-left text-zinc-500",children:[e.jsx("th",{className:"py-2 pr-4 font-normal whitespace-nowrap",children:"Step"}),e.jsx("th",{className:"py-2 pr-4 font-normal whitespace-nowrap",children:"Sent"}),e.jsx("th",{className:"py-2 pr-4 font-normal whitespace-nowrap",children:"Delivered"}),e.jsx("th",{className:"py-2 pr-4 font-normal whitespace-nowrap",children:"Opened"}),e.jsx("th",{className:"py-2 pr-4 font-normal whitespace-nowrap",children:"Clicked"}),e.jsx("th",{className:"py-2 pr-4 font-normal whitespace-nowrap",children:"Bounced"}),e.jsx("th",{className:"py-2 pr-4 font-normal whitespace-nowrap",children:"Dropped"}),e.jsx("th",{className:"py-2 pr-4 font-normal whitespace-nowrap",children:"Spam"})]})}),e.jsx("tbody",{className:"divide-y divide-black/5",children:s.byStep.map(i=>{const r=i.sent>
140?i.delivered/i.sent:0,l=i.sent>0?i.opened/i.sent:0,c=i.sent>0?i.clicked/i.sent:0,d=i.sent>0?i.bounced/i.sent:0;return e.jsxs("tr",{className:"text-zinc-700",children:[e.jsx("td",{className:"py-2 pr-4 font-mono text-[0.8125rem]",children:i.stepKey}),e.jsx("td",{className:"py-2 pr-4 tabular-nums",children:i.sent}),e.jsxs("td",{className:"py-2 pr-4 tabular-nums",children:[e.jsx("span",{children:i.delivered}),e.jsx("span",{className:"ml-1 text-xs text-zinc-500",children:i.sent>0?fe(r):""})]}),e.jsxs("td",{className:"py-2 pr-4 tabular-nums",children:[e.jsx("span",{children:i.opened}),e.jsx("span",{className:"ml-1 text-xs text-zinc-500",children:i.sent>0?fe(l):""})]}),e.jsxs("td",{className:"py-2 pr-4 tabular-nums",children:[e.jsx("span",{children:i.clicked}),e.jsx("span",{className:"ml-1 text-xs text-zinc-500",children:i.sent>0?fe(c):""})]}),e.jsxs("td",{className:`py-2 pr-4 tabular-nums ${d>.02?"text-rose-700":""}`,children:[e.jsx("span",{children:i.bounced}),e.jsx("span",{className:"ml-1 text-xs text-zinc-500",children:i.sent>0?fe(d):""})]}),e.jsx("td",{className:`py-2 pr-4 tabular-nums ${i.dropped>0?"text-amber-700":""}`,children:i.dropped}),e.jsx("td",{className:`py-2 pr-4 tabular-nums ${i.spamReport>0?"text-rose-700":""}`,children:i.spamReport})]},i.stepKey)})})]})})]}):null]})}const Gs=1e4,Vr=6,St={direction:"asc",key:"email"},An="orian.admin.memberPicker.savedFilterViews",zn={createdAt:"Created",domain:"Domain",email:"Email",fullName:"Name",hubspotSyncedAt:"HubSpot",icpSegment:"ICP",notificationFrequency:"Cadence",status:"Status",suppression:"Suppression"},Xs=["fullName","domain","status","notificationFrequency","icpSegment","createdAt","hubspotSyncedAt","suppression"],Jr=[{key:"fullName",label:"Name"},{key:"domain",label:"Domain"},{key:"status",label:"Status"},{key:"notificationFrequency",label:"Cadence"},{key:"icpSegment",label:"ICP"},{key:"createdAt",label:"Created"},{key:"hubspotSyncedAt",label:"HubSpot"},{key:"suppression",label:"Suppression"}],$n=[{label:"All statuses",value:"all"},{label:"Joined",value:"joined"},{label:"Verified",value:"verified"},{label:"Profile completed",value:"profile_completed"},{label:"Invited",value:"invited"},{label:"Activated",value:"activated"}],Dn=[{label:"All frequencies",value:"all"},{label:"Instant",value:"instant"},{label:"Weekly",value:"weekly"},{label:"Milestones",value:"milestones"},{label:"Off",value:"off"}],Mn=[{label:"All ICPs",value:"all"},{label:"Not set",value:"unset"},{label:"Knowledge creator",value:"knowledge_creator"},{label:"Startup community",value:"startup_community"},{label:"After-school",value:"after_school"}],_n=[{label:"All HubSpot states",value:"all"},{label:"Synced",value:"synced"},{label:"Unsynced",value:"unsynced"}],Fn=[{label:"All sources",value:"all"},{label:"Waitlist",value:"member"},{label:"First Orbit",value:"first_orbit"},{label:"Audience contacts",value:"audience_contact"}];function Ln(s){return $n.some(t=>t.value===s)}function Pn(s){return Dn.some(t=>t.value===s)}function Rn(s){return Mn.some(t=>t.value===s)}function En(s){return _n.some(t=>t.value===s)}function qn(s){return Fn.some(t=>t.value===s)}function On(s){return s==="include"||s==="exclude"}function Kr(s){return Object.prototype.hasOwnProperty.call(zn,s)}function Yr(s){return s==="asc"||s==="desc"}function os(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function Gr(s){return Array.isArray(s)&&s.every(t=>typeof t=="string")}function Xr(s){if(!os(s))return null;const t=s.createdAfter,n=s.createdBefore,a=s.domainMode,i=s.frequencyFilter,r=s.hubspotFilter,l=s.icpFilter,c=s.quickFilter,d=s.selectedDomains,u=s.sourceFilter,x=s.sort,m=s.statusFilter;if(typeof t!="string"||typeof n!="string"||typeof a!="string"||!On(a)||typeof i!="string"||!Pn(i)||typeof r!="string"||!En(r)||typeof l!="string"||!Rn(l)||typeof c!="string"||!Gr(d)||u!==void 0&&(typeof u!="string"||!qn(u))||!os(x)||typeof m!="string"||!Ln(m))return null;const S=x.key,A=x.direction;return typeof S!="string"||!Kr(S)||typeof A!="string"||!Yr(A)?null:{createdAfter:t,createdBefore:n,domainMode:a,frequencyFilter:i,hubspotFilter:r,icpFilter:l,quickFilter:c,selectedDomains:d,sort:{direction:A,key:S},sourceFilter:u??"all",statusFilter:m}}function Zr(s){if(!os(s))return null;const t=Xr(s.filters);return!t||typeof s.id!="string"||typeof s.name!="string"?null:{filters:t,id:s.id,name:s.name}}function el(s){if(!s)return[];try{const t=JSON.parse(s);if(!Array.isArray(t))return[];const n=[];for(const a of t){const i=Zr(a);i&&n.push(i)}return n.slice(0,20)}catch{return[]}}function tl(){if(typeof window>"u")return[];try{return el(window.localStorage.getItem(An))}catch{return[]}}function sl(s){if(!(typeof window>"u"))try{window.localStorage.setItem(An,JSON.stringify(s))}catch{return}}function nl(s,t){if(s.length!==t.length)return!1;const n=[...s].sort(),a=[...t].sort();return n.every((i,r)=>i===a[r])}function Zs(s,t){return s.createdAfter===t.createdAfter&&s.createdBefore===t.createdBefore&&s.domainMode===t.domainMode&&s.frequencyFilter===t.frequencyFilter&&s.hubspotFilter===t.hubspotFilter&&s.icpFilter===t.icpFilter&&s.quickFilter===t.quickFilter&&s.sort.direction===t.sort.direction&&s.sort.key===t.sort.key&&s.sourceFilter===t.sourceFilter&&s.statusFilter===t.statusFilter&&nl(s.selectedDomains,t.selectedDomains)}function Gt(s){return{_id:s._id,email:s.email,fullName:s.fullName,recipientType:s.recipientType}}function ct(s){const t=new Set,n=[];for(const a of s){const i=a.email.toLowerCase();t.has(i)||(t.add(i),n.push(a))}return n}function il(s){return s?new Date(s).toISOString().slice(0,10):"â"}function Tt(s){return s?s.replaceAll("_"," "):"â"}function Bn(s){return s.suppression?`${s.suppression.workflowKey??"Global"}: ${Tt(s.suppression.reason)}`:"Sendable"}function en(s,t){if(!s)return null;const n=t?"T23:59:59.999":"T00:00:00.000",a=Date.parse(`${s}${n}`);return Number.isFinite(a)?a:null}function al(s,t){return t.length===0?!0:[s.email,s.fullName??"",s.domain,s.status,s.notificationFrequency,s.sources.join(" ").replaceAll("_"," "),s.icpSegment??"",s.hubspotSyncedAt?"synced":"unsynced",s.suppression?"suppressed":"sendable",s.suppression?.reason??"",s.suppression?.workflowKey??""].some(a=>a.toLowerCase().includes(t))}function tn(s,t){if(t==="suppression")return Bn(s).toLowerCase();const n=s[t];return typeof n=="number"?n:typeof n=="string"?n.toLowerCase():""}function rl(s,t,n){const a=tn(s,n.key),i=tn(t,n.key),r=n.direction==="asc"?1:-1;return typeof a=="number"&&typeof i=="number"?(a-i)*r:String(a).localeCompare(String(i))*r}function ll(s,t){return s.key!==t?"":s.direction==="asc"?"asc":"desc"}function In({allowAudienceContacts:s=!1,onConfirm:t,onOpenChange:n,open:a,selected:i,workflowKey:r}){const[l,c]=f.useState(""),[d,u]=f.useState(""),[x,m]=f.useState(!1),[S,A]=f.useState(!1),M=f.useDeferredValue(l),[b,g]=f.useState(i),[C,F]=f.useState("all"),[_,v]=f.useState("all"),[w,L]=f.useState("all"),[p,j]=f.useState("include"),[y,R]=f.useState([]),[J,E]=f.useState(""),[H,G]=f.useState(""),[Z,ve]=f.useState(""),[he,De]=f.useState("all"),[me,Ze]=f.useState("all"),[we,et]=f.useState(St),[tt,ft]=f.useState(""),[ne,z]=f.useState([]),[Ne,Wn]=f.useState(!1),[Re,st]=f.useState(null),[pt,Hn]=f.useState(Xs),Rt=f.useRef(null),Et=f.useRef(null);f.useEffect(()=>{a&&g(ct(i))},[a,i]),f.useEffect(()=>
14{a&&(z(tl()),Wn(!0))},[a]),f.useEffect(()=>{Ne&&sl(ne)},[ne,Ne]),f.useEffect(()=>{Re&&(ne.some(o=>o.id===Re)||st(null))},[Re,ne]);const nt=de({queryKey:["admin","membersForPickerTable",r,s,"recipient-sources-v2"],queryFn:()=>r?_s({data:{includeAudienceContacts:s,includeFirstOrbitApplications:s,limit:Gs,workflowKey:r}}):_s({data:{includeAudienceContacts:s,includeFirstOrbitApplications:s,limit:Gs}}),enabled:a,refetchOnMount:"always"}),it=f.useMemo(()=>(nt.data?.page??[]).map(o=>({_id:o._id,createdAt:o.createdAt,domain:o.domain,email:o.email,fullName:o.fullName,hubspotSyncedAt:o.hubspotSyncedAt,icpSegment:o.icpSegment,joinedAt:o.joinedAt,notificationFrequency:o.notificationFrequency,recipientType:o.recipientType,sources:o.sources,status:o.status,suppression:o.suppression})).sort((o,N)=>o.email.localeCompare(N.email)),[nt.data]),qt=f.useMemo(()=>{const o=new Map;for(const N of it)o.set(N.domain,(o.get(N.domain)??0)+1);return Array.from(o.entries()).map(([N,q])=>({count:q,domain:N})).sort((N,q)=>q.count!==N.count?q.count-N.count:N.domain.localeCompare(q.domain))},[it]),at=f.useMemo(()=>new Set(y),[y]),vs=f.useMemo(()=>{const o=J.trim().toLowerCase();return o.length===0?qt.slice(0,50):qt.filter(N=>N.domain.includes(o)).slice(0,50)},[J,qt]),Ot=f.useMemo(()=>en(H,!1),[H]),Bt=f.useMemo(()=>en(Z,!0),[Z]),ws=M.trim().toLowerCase(),Se=f.useMemo(()=>it.filter(o=>!(!al(o,ws)||me!=="all"&&!o.sources.includes(me)||C!=="all"&&o.status!==C||_!=="all"&&o.notificationFrequency!==_||w==="unset"&&o.icpSegment||w!=="all"&&w!=="unset"&&o.icpSegment!==w||at.size>0&&p==="include"&&!at.has(o.domain)||at.size>0&&p==="exclude"&&at.has(o.domain)||Ot&&o.createdAt<Ot||Bt&&o.createdAt>Bt||he==="synced"&&!o.hubspotSyncedAt||he==="unsynced"&&o.hubspotSyncedAt)),[Ot,Bt,p,_,he,w,ws,it,at,me,C]),rt=f.useMemo(()=>[...Se].sort((o,N)=>rl(o,N,we)),[Se,we]),lt=f.useMemo(()=>({createdAfter:H,createdBefore:Z,domainMode:p,frequencyFilter:_,hubspotFilter:he,icpFilter:w,quickFilter:l,selectedDomains:[...y],sort:we,sourceFilter:me,statusFilter:C}),[H,Z,p,_,he,w,l,y,we,me,C]),Vn=f.useMemo(()=>ne.find(o=>Zs(o.filters,lt))??null,[lt,ne]),Ee=f.useMemo(()=>Re?ne.find(o=>o.id===Re)??null:null,[Re,ne])??Vn,Ns=Ee?!Zs(Ee.filters,lt):!1,Jn=f.useMemo(()=>new Set(pt),[pt]),Ss=f.useMemo(()=>new Set(b.map(o=>o._id)),[b]),Cs=Se.filter(o=>Ss.has(o._id)).length,It=Se.length>0&&Cs===Se.length,Kn=Cs>0&&!It;function Yn(o){g(N=>N.some(q=>q._id===o._id)?N.filter(q=>q._id!==o._id):ct([...N,Gt(o)]))}function Gn(){g(o=>{if(It){const N=new Set(Se.map(q=>q._id));return o.filter(q=>!N.has(q._id))}return ct([...o,...Se.map(Gt)])})}function Xn(o){R(N=>N.includes(o)?N.filter(q=>q!==o):[...N,o])}function Zn(o){Hn(N=>{if(N.includes(o)){const q=N.filter(qe=>qe!==o);return q.length>0?q:N}return Xs.filter(q=>q===o||N.includes(q))})}function ei(){c(""),F("all"),v("all"),L("all"),j("include"),R([]),E(""),G(""),ve(""),De("all"),Ze("all"),et(St),st(null)}function ti(){return{...lt,selectedDomains:[...lt.selectedDomains]}}function si(o){c(o.quickFilter),F(o.statusFilter),v(o.frequencyFilter),L(o.icpFilter),j(o.domainMode),R([...o.selectedDomains]),G(o.createdAfter),ve(o.createdBefore),De(o.hubspotFilter),Ze(o.sourceFilter),et(o.sort)}function ni(o){st(o.id),si(o.filters)}function ks(){const o=tt.trim();if(o.length===0)return;const N={filters:ti(),id:window.crypto.randomUUID(),name:o};z(q=>[N,...q.filter(qe=>qe.name.toLowerCase()!==o.toLowerCase())].slice(0,20)),st(N.id),ft("")}function ii(o){z(N=>N.filter(q=>q.id!==o)),Re===o&&st(null)}function ai(){g([])}async function ri(){const o=d.split(/[\s,;]+/).map(N=>N.trim()).filter(N=>N.length>0);if(o.length!==0){m(!0);try{const N=await tr({data:{emails:o}}),q=N.recipients.filter(xt=>xt.recipientType==="member"||xt.status==="active");g(xt=>ct([...xt,...q])),u(""),A(!1),await nt.refetch();const qe=N.recipients.length-q.length;$.success(`Selected ${q.length} recipient${q.length===1?"":"s"}${N.createdCount>0?`; saved ${N.createdCount} new contact${N.createdCount===1?"":"s"}`:""}.`),qe>0&&$.warning(`${qe} inactive contact${qe===1?" was":"s were"} not selected.`)}catch(N){$.error(N instanceof Error?N.message:String(N))}finally{m(!1)}}}function li(){g(ct(rt.map(Gt)))}function oi(o){et(N=>N.key!==o?{direction:"asc",key:o}:{direction:N.direction==="asc"?"desc":"asc",key:o})}function Ce(o){return e.jsxs("button",{className:`inline-flex items-center gap-1 font-medium text-zinc-500 15 hover:text-zinc-900`,onClick:()=>oi(o),type:"button",children:[e.jsx("span",{children:zn[o]}),e.jsx("span",{className:`w-8 text-left text-[10px] font-semibold text-zinc-400 16 uppercase`,children:ll(we,o)})]})}function ci(){const o=Rt.current,N=Et.current;!o||!N||N.scrollLeft!==o.scrollLeft&&(N.scrollLeft=o.scrollLeft)}function di(){const o=Rt.current,N=Et.current;!o||!N||o.scrollLeft!==N.scrollLeft&&(o.scrollLeft=N.scrollLeft)}function X(o){return Jn.has(o)}const ui=we.key===St.key&&we.direction===St.direction,hi=l.trim().length>0||C!=="all"||_!=="all"||w!=="all"||y.length>0||H.length>0||Z.length>0||he!=="all"||me!=="all"||!ui,mi=nt.isLoading||nt.isFetching,fi=y.length===0?"All domains":y.length===1?y[0]:`${y.length} domains`,Ts=2+pt.length,As=b.slice(0,Vr),zs=b.length-As.length;return e.jsx(Ve,{onOpenChange:n,open:a,children:e.jsxs(Je,{className:`flex h-[calc(100dvh-1rem)] min-h-0 w-[calc(100vw-1rem)] 17 max-w-none grid-rows-none flex-col overflow-hidden p-0 sm:h-[90dvh] 18 sm:w-[90vw]`,children:[e.jsx("div",{className:"shrink-0 border-b border-zinc-200 px-4 pt-4 pb-3 sm:px-5",children:e.jsxs(Ke,{children:[e.jsx(Ye,{children:s?"Select recipients":"Select members"}
18),e.jsx(Ge,{children:s?"Select members or save email-only audience contacts.":"Filter the member database, save filter views, and select members."})]})}),e.jsxs("div",{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-x-hidden 19 overflow-y-auto px-4 pt-4 pb-4 [scrollbar-gutter:stable] sm:px-5`,children:[e.jsxs("div",{className:"grid gap-2 lg:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsxs("div",{className:"relative min-w-0",children:[e.jsx(Br,{className:`pointer-events-none absolute top-1/2 left-3 size-4 20 -translate-y-1/2 text-zinc-400`}),e.jsx(I,{"aria-label":"Quick filter members",autoFocus:!0,className:"h-9 py-1.5 pr-4 pl-9 text-base/5 sm:text-sm/5",name:"member-quick-filter",onChange:o=>c(o.target.value),placeholder:"Quick filter by email, name, domain, statusâ¦",type:"search",value:l})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 lg:justify-end",children:[s?e.jsxs(Ii,{onOpenChange:A,open:S,children:[e.jsx(Qi,{asChild:!0,children:e.jsxs(T,{size:"sm",variant:"outline",children:[e.jsx(Ui,{className:"size-4"}),"Add email recipients"]})}),e.jsx(Wi,{align:"end",className:"w-[min(28rem,calc(100vw-2rem))] p-0",sideOffset:8,children:e.jsxs("form",{className:"grid gap-3 p-4",onSubmit:o=>{o.preventDefault(),ri()},children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(D,{className:"text-sm font-medium text-zinc-900",htmlFor:"audience-contact-email",children:"Add recipients by email"}),e.jsx("p",{className:"mt-1 text-xs text-pretty text-zinc-500",children:"New addresses are saved to your audience for future sends."})]}),e.jsx(Y,{className:"shrink-0",variant:"secondary",children:"Saved"})]}),e.jsx(te,{autoComplete:"off",className:`min-h-28 resize-y border-zinc-200 bg-white 21 text-base shadow-none sm:text-sm`,disabled:x,id:"audience-contact-email",name:"audience-contact-email",onChange:o=>u(o.target.value),placeholder:"[email protected], [email protected]",value:d}),e.jsxs("div",{className:`flex flex-col gap-2 sm:flex-row 22 sm:items-center sm:justify-between`,children:[e.jsx("p",{className:"text-xs text-zinc-500",children:"Comma, semicolon, space, or new line · 500 maximum"}),e.jsx(T,{className:"w-full sm:w-auto",disabled:x||d.trim().length===0,size:"sm",type:"submit",children:x?"Savingâ¦":"Save and select"})]})]})})]}):null,e.jsxs(yt,{children:[e.jsx(jt,{asChild:!0,children:e.jsx(T,{className:Rs("max-w-64 min-w-32",Ee&&`border-violet-200 bg-violet-50 text-violet-700 23 hover:bg-violet-50`),size:"sm",variant:"outline",children:e.jsx("span",{className:"truncate",children:Ee?`Saved: ${Ee.name}${Ns?" + changes":""}`:`Saved filters${ne.length>0?` ${ne.length}`:""}`})})}),e.jsxs(vt,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)]",children:[e.jsx(Vt,{children:"Apply saved filter"}),ne.length>0?e.jsx("div",{className:`max-h-56 overflow-auto 24 [scrollbar-gutter:stable]`,children:ne.map(o=>e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(wt,{className:Rs("min-w-0 flex-1",Ee?.id===o.id&&"bg-violet-50 text-violet-900"),onClick:()=>ni(o),children:e.jsxs("span",{className:"truncate",children:[o.name,Ee?.id===o.id?Ns?" (base)":" (active)":""]})}),e.jsx("button",{"aria-label":`Delete ${o.name}`,className:`shrink-0 rounded px-2 py-1 text-sm 25 text-zinc-500 hover:bg-zinc-100 26 hover:text-zinc-900`,onClick:N=>{N.preventDefault(),N.stopPropagation(),ii(o.id)},type:"button",children:"Delete"})]},o.id))}):e.jsx("p",{className:"px-2 py-2 text-sm text-zinc-500",children:"No saved filters yet."})]})]}),e.jsxs(yt,{children:[e.jsx(jt,{asChild:!0,children:e.jsxs(T,{className:"min-w-24",size:"sm",variant:"outline",children:["Columns ",pt.length]})}),e.jsxs(vt,{align:"end",className:"w-48",children:[e.jsx(Vt,{children:"Visible columns"}),e.jsx(Ls,{}),Jr.map(o=>e.jsx(Ps,{checked:X(o.key),onCheckedChange:()=>Zn(o.key),onSelect:N=>N.preventDefault(),children:o.label},o.key))]})]})]})]}),e.jsxs("div",{className:`grid gap-2 rounded-lg border border-zinc-200 27 bg-zinc-50/60 p-1.5 sm:grid-cols-[minmax(0,1fr)_auto]`,children:[e.jsx(I,{"aria-label":"Saved filter name",className:"h-9 py-1.5 text-base/5 sm:text-sm/5",name:"saved-filter-name",onChange:o=>ft(o.target.value),onKeyDown:o=>{o.key==="Enter"&&ks()},placeholder:"Save current filters asâ¦",type:"text",value:tt}),e.jsx(T,{className:"h-9",disabled:tt.trim().length===0,onClick:ks,size:"sm",variant:"outline",children:"Save filter"})]}),e.jsxs("div",{className:"grid gap-2 md:grid-cols-2 xl:grid-cols-5",children:[e.jsxs(ie,{onValueChange:o=>{qn(o)&&Ze(o)},value:me,children:[e.jsx(ae,{"aria-label":"Filter by source",className:"h-8",children:e.jsx(re,{})}),e.jsx(le,{children:Fn.map(o=>e.jsx(V,{value:o.value,children:o.label},o.value))})]}),e.jsxs(ie,{onValueChange:o=>{Ln(o)&&F(o)},value:C,children:[e.jsx(ae,{"aria-label":"Filter by member status",className:"h-8",children:e.jsx(re,{})}),e.jsx(le,{children:$n.map(o=>e.jsx(V,{value:o.value,children:o.label},o.value))})]}),e.jsxs(ie,{onValueChange:o=>{Pn(o)&&v(o)},value:_,children:[e.jsx(ae,{"aria-label":"Filter by notification frequency",className:"h-8",children:e.jsx(re,{})}),e.jsx(le,{children:Dn.map(o=>e.jsx(V,{value:o.value,children:o.label},o.value))})]}),e.jsxs(ie,{onValueChange:o=>{Rn(o)&&L(o)},value:w,children:[e.jsx(ae,{"aria-label":"Filter by ICP segment",className:"h-8",children:e.jsx(re,{})}),e.jsx(le,{children:Mn.map(o=>e.jsx(V,{value:o.value,children:o.label},o.value))})]}),e.jsxs(ie,{onValueChange:o=>{En(o)&&De(o)},value:he,children:[e.jsx(ae,{"aria-label":"Filter by HubSpot sync status",className:"h-8",children:e.jsx(re,{})}),e.jsx(le,{children:_n.map(o=>e.jsx(V,{value:o.value,children:o.label},o.value))})]})]}),e.jsxs("div",{className:"grid gap-3 xl:grid-cols-[minmax(0,1fr)_28rem]",children:[e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"grid min-w-0 gap-1.5",children:[e.jsx(D,{htmlFor:"member-created-after",children:"Created after"}),e.jsx(I,{className:"h-9 py-1.5 text-base/5 sm:text-sm/5",id:"member-created-after",min:"2020-01-01",name:"member-created-after",onChange:o=>G(o.target.value),type:"date",value:H})]}),e.jsxs("div",{className:"grid min-w-0 gap-1.5",children:[e.jsx(D,{htmlFor:"member-created-before",children:"Created before"}),e.jsx(I,{className:"h-9 py-1.5 text-base/5 sm:text-sm/5",id:"member-created-before",min:"2020-01-01",name:"member-created-before",onCh
27ange:o=>ve(o.target.value),type:"date",value:Z})]})]}),e.jsxs("div",{className:"grid min-w-0 gap-1.5",children:[e.jsx(D,{children:"Domains"}),e.jsxs("div",{className:"grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_8rem]",children:[e.jsxs(yt,{children:[e.jsx(jt,{asChild:!0,children:e.jsxs(T,{className:"h-9 w-full justify-between bg-white",variant:"outline",children:[e.jsx("span",{className:"min-w-0 truncate text-left",children:fi}),e.jsx(Lt,{className:"size-4 shrink-0 text-zinc-500"})]})}),e.jsxs(vt,{align:"start",className:"w-72",children:[e.jsx(Vt,{children:"Filter domains"}),e.jsx("div",{className:"px-2 pb-2",children:e.jsx(I,{"aria-label":"Search domains",className:"h-8 text-base/5 sm:text-sm/5",name:"member-domain-search",onChange:o=>E(o.target.value),placeholder:"Search domainsâ¦",type:"search",value:J})}),e.jsx(Ls,{}),e.jsx("div",{className:`max-h-56 overflow-auto 28 [scrollbar-gutter:stable]`,children:vs.length>0?vs.map(o=>e.jsxs(Ps,{checked:y.includes(o.domain),onCheckedChange:()=>Xn(o.domain),onSelect:N=>N.preventDefault(),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate",children:o.domain}),e.jsx("span",{className:`shrink-0 text-xs text-zinc-400 29 tabular-nums`,children:o.count})]},o.domain)):e.jsx("p",{className:"px-2 py-1.5 text-sm text-zinc-500",children:"No domains found."})})]})]}),e.jsxs(ie,{onValueChange:o=>{On(o)&&j(o)},value:p,children:[e.jsx(ae,{"aria-label":"Choose domain filter mode",className:"h-9 w-full",children:e.jsx(re,{})}),e.jsxs(le,{children:[e.jsx(V,{value:"include",children:"Include"}),e.jsx(V,{value:"exclude",children:"Exclude"})]})]})]})]})]}),e.jsxs("div",{className:"flex min-h-[16rem] flex-1 flex-col",children:[e.jsx("div",{className:`min-h-0 flex-1 overflow-x-auto overflow-y-auto 30 rounded-t-lg border border-b-0 border-zinc-200 bg-white 31 [scrollbar-gutter:stable]`,onScroll:ci,ref:Rt,children:e.jsxs("table",{className:"w-[2100px] table-fixed caption-bottom text-sm",children:[e.jsx(fs,{children:e.jsxs(Le,{children:[e.jsx(K,{className:"sticky left-0 z-30 h-8 w-10 bg-white px-2",children:e.jsx(Fs,{"aria-label":"Select filtered members",checked:It?!0:Kn?"indeterminate":!1,disabled:Se.length===0,onCheckedChange:Gn})}),e.jsx(K,{className:`sticky left-10 z-30 h-8 w-[360px] bg-white 32 px-2`,children:Ce("email")}),X("fullName")?e.jsx(K,{className:"h-8 w-[220px] px-2",children:Ce("fullName")}):null,X("domain")?e.jsx(K,{className:"h-8 w-[200px] px-2",children:Ce("domain")}):null,X("status")?e.jsx(K,{className:"h-8 w-[150px] px-2",children:Ce("status")}):null,X("notificationFrequency")?e.jsx(K,{className:"h-8 w-[170px] px-2",children:Ce("notificationFrequency")}):null,X("icpSegment")?e.jsx(K,{className:"h-8 w-[190px] px-2",children:Ce("icpSegment")}):null,X("createdAt")?e.jsx(K,{className:"h-8 w-[150px] px-2",children:Ce("createdAt")}):null,X("hubspotSyncedAt")?e.jsx(K,{className:"h-8 w-[150px] px-2",children:Ce("hubspotSyncedAt")}):null,X("suppression")?e.jsx(K,{className:"h-8 w-[200px] px-2",children:Ce("suppression")}):null]})}),e.jsx(ps,{children:mi?e.jsx(Le,{children:e.jsx(Q,{className:"py-10 text-center",colSpan:Ts,children:e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm 33 text-zinc-500`,children:[e.jsx(da,{className:"size-4 animate-spin"}),"Loading membersâ¦"]})})}):rt.length===0?e.jsx(Le,{children:e.jsx(Q,{className:"py-10 text-center",colSpan:Ts,children:e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm 34 text-zinc-500`,children:[e.jsx(Qr,{className:"size-4"}),"No matching members."]})})}):rt.map(o=>{const N=Ss.has(o._id);return e.jsxs(Le,{className:"h-8","data-state":N?"selected":void 0,children:[e.jsx(Q,{className:"sticky left-0 z-20 bg-white px-2 py-1",children:e.jsx(Fs,{"aria-label":`Select ${o.email}`,checked:N,onCheckedChange:()=>Yn(o)})}),e.jsx(Q,{className:`sticky left-10 z-20 truncate bg-white 35 px-2 py-1 font-medium whitespace-nowrap`,title:o.email,children:e.jsxs("span",{className:`inline-flex max-w-full items-center 36 gap-2`,children:[e.jsx("span",{className:"truncate",children:o.email}),o.sources.includes("first_orbit")?e.jsx(Y,{variant:"default",children:"First Orbit"}
36):null,o.sources.includes("audience_contact")?e.jsx(Y,{variant:"secondary",children:"Contact"}):null]})}),X("fullName")?e.jsx(Q,{className:"truncate px-2 py-1 whitespace-nowrap",title:o.fullName??void 0,children:o.fullName??"â"}):null,X("domain")?e.jsx(Q,{className:"truncate px-2 py-1 whitespace-nowrap",title:o.domain,children:o.domain}):null,X("status")?e.jsx(Q,{className:"px-2 py-1 whitespace-nowrap",children:Tt(o.status)}):null,X("notificationFrequency")?e.jsx(Q,{className:"px-2 py-1 whitespace-nowrap",children:Tt(o.notificationFrequency)}):null,X("icpSegment")?e.jsx(Q,{className:"truncate px-2 py-1 whitespace-nowrap",title:o.icpSegment??void 0,children:Tt(o.icpSegment)}):null,X("createdAt")?e.jsx(Q,{className:"px-2 py-1 whitespace-nowrap",children:il(o.createdAt)}):null,X("hubspotSyncedAt")?e.jsx(Q,{className:"px-2 py-1 whitespace-nowrap",children:e.jsx(Y,{variant:o.hubspotSyncedAt?"success":"warning",children:o.hubspotSyncedAt?"Synced":"Unsynced"})}):null,X("suppression")?e.jsx(Q,{className:"px-2 py-1 whitespace-nowrap",children:o.suppression?e.jsx(Y,{title:Bn(o),variant:"warning",children:"Suppressed"}):e.jsx(Y,{variant:"success",children:"Sendable"})}):null]},o._id)})})]})}),e.jsx("div",{"aria-label":"Horizontal member table scroll",className:`h-4 overflow-x-scroll overflow-y-hidden rounded-b-lg 37 border border-zinc-200 bg-zinc-50`,onScroll:di,ref:Et,children:e.jsx("div",{className:"h-px w-[2100px]"})})]})]}),e.jsx("div",{className:"shrink-0 border-t border-zinc-200 px-4 pt-3 pb-4 sm:px-5",children:e.jsxs("div",{className:`grid min-w-0 gap-3 lg:grid-cols-[minmax(0,1fr)_auto] 38 lg:items-end`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:`mb-2 flex flex-wrap items-center gap-2 text-sm 39 text-zinc-600`,children:[e.jsxs("span",{children:["Showing"," ",e.jsx("span",{className:"text-zinc-900 tabular-nums",children:Se.length})," ","of"," ",e.jsx("span",{className:"text-zinc-900 tabular-nums",children:it.length})," ","loaded members"]}),e.jsx("span",{className:"text-zinc-300","aria-hidden":"true",children:"/"}),e.jsxs("span",{children:["Selected"," ",e.jsx("span",{className:"text-zinc-900 tabular-nums",children:b.length})]})]}),b.length>0?e.jsxs("ul",{className:`flex min-w-0 flex-nowrap items-center gap-1.5 40 overflow-hidden pr-1`,role:"list",children:[As.map(o=>e.jsx("li",{className:"min-w-0",children:e.jsxs(Y,{className:"max-w-[12rem] min-w-0 pr-1 sm:max-w-[16rem]",variant:"secondary",children:[e.jsx("span",{className:"min-w-0 truncate",title:o.email,children:o.email}),e.jsx("button",{"aria-label":`Remove ${o.email}`,className:`grid size-4 shrink-0 place-items-center 41 rounded-full text-zinc-500 hover:bg-zinc-200 42 hover:text-zinc-900`,onClick:()=>{g(N=>N.filter(q=>q._id!==o._id))},type:"button",children:e.jsx(ua,{className:"size-3"})})]})},o._id)),zs>0?e.jsx("li",{className:"shrink-0",children:e.jsxs(Y,{variant:"secondary",children:["+",zs," more"]})}):null]}):e.jsx("p",{className:"text-sm text-zinc-500",children:"Select members from the table."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 lg:justify-end",children:[e.jsxs(yt,{children:[e.jsx(jt,{asChild:!0,children:e.jsx(T,{size:"sm",variant:"outline",children:"Selection"})}),e.jsxs(vt,{align:"end",className:"w-64",children:[e.jsxs(wt,{disabled:rt.length===0,onClick:li,children:["Select all ",rt.length," matches"]}),e.jsx(wt,{disabled:b.length===0,onClick:ai,children:"Clear selected members"}),e.jsx(wt,{disabled:!hi,onClick:ei,children:"Reset filters and sort"})]})]}),e.jsxs(Xe,{className:"shrink-0 flex-row items-center",children:[e.jsx(T,{onClick:()=>n(!1),variant:"outline",children:"Cancel"}),e.jsxs(T,{disabled:b.length===0,onClick:()=>{t(b),n(!1)},children:["Add ",b.length>0?b.length:""]})]})]})]})})]})})}function ol(s){if(Hi(s)==="changelog"){const n=Vi(s);return bn(n)?n:null}const t=Ji(s);return Ki(t)?t:null}function cl(s){const t=s instanceof Date?s.getTime():typeof s=="number"?s:typeof s=="string"?Date.parse(s):Number.NaN;return Number.isFinite(t)?je(t):"unknown date"}function dl(s){return`${s.issueNumber===null?"Draft issue":`Issue #${s.issueNumber}`}: ${s.payload.subject}`}function ul({paused:s=!1,workflowKey:t}){const n=f.useId(),[a,i]=f.useState(""),[r,l]=f.useState("desktop"),[c,d]=f.useState(null),[u,x]=f.useState(""),[m,S]=f.useState([]),[A,M]=f.useState(!1),[b,g]=f.useState(!1),[C,F]=f.useState(!1),[_,v]=f.useState(!1),[w,L]=f.useState(!1),[p,j]=f.useState(""),{data:y,isLoading:R}=de({queryFn:()=>gn({data:{limit:25,status:"draft",workflowKey:t}}),queryKey:["admin","broadcastDrafts",t]}),J=f.useMemo(()=>(y?.page??[]).flatMap(z=>{const Ne=ol(z.templatePayload);
42return Ne===null?[]:[{createdAt:z.createdAt,id:z.id,issueNumber:z.issueNumber??null,payload:Ne,templatePayload:z.templatePayload}]}),[y]),E=J.find(z=>z.id===a)??J.at(0),H=E?.id,G=c!==null&&H!==void 0&&c.broadcastId===H,Z=H!==void 0&&p===H,ve=m.filter(z=>z.recipientType==="member").length,he=m.filter(z=>z.recipientType==="first_orbit").length,De=m.length-ve-he,me=C||_||w,Ze=E!==void 0&&G,we=E!==void 0&&Z&&!s,et=async()=>{if(!E){$.error("Compose and save a draft issue first.");return}F(!0);try{const z=await ea({data:{locale:"en",payload:E.templatePayload,workflowKey:t}});d({broadcastId:E.id,html:z.html,preheader:z.preheader,subject:z.subject})}catch(z){$.error(z instanceof Error?z.message:String(z))}finally{F(!1)}},tt=async()=>{if(!E){$.error("Compose and save a draft issue first.");return}const z=u.trim();if(z.length===0){$.error("Enter a test inbox.");return}v(!0);try{await ta({data:{email:z,locale:"en",payload:E.templatePayload,workflowKey:t}}),j(E.id),$.success(`Sent safe test to ${z}.`),x("")}catch(Ne){$.error(Ne instanceof Error?Ne.message:String(Ne))}finally{v(!1)}},ft=()=>{if(!E){$.error("Compose and save a draft issue first.");return}if(s){$.error("Resume the workflow before real sends.");return}if(m.length===0){$.error("Pick at least one recipient.");return}if(!Z){$.error("Send a safe test for this draft before real sends.");return}g(!0)},ne=async()=>{if(E&&m.length!==0){L(!0);try{await ha({data:{audienceContactIds:m.filter(z=>z.recipientType==="audience_contact").map(z=>z._id),firstOrbitApplicationIds:m.filter(z=>z.recipientType==="first_orbit").map(z=>z._id),memberIds:m.filter(z=>z.recipientType==="member").map(z=>z._id),templatePayload:E.templatePayload,workflowKey:t}}),$.success(`Started real send to ${m.length} recipient(s).`),g(!1),S([])}catch(z){$.error(z instanceof Error?z.message:String(z))}finally{L(!1)}}};return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(oe,{children:"Send safely"}),e.jsx(ue,{children:"Send uses saved Compose drafts only. Preview the rendered email, send a safe test, then confirm any real recipient send."})]}),e.jsxs(ce,{children:[e.jsxs("div",{className:"flex flex-col gap-6",children:[s?e.jsxs("div",{className:"rounded-lg bg-amber-50 p-4 ring-1 ring-amber-200/70",role:"status",children:[e.jsx("p",{className:"font-medium text-amber-950",children:"Workflow paused."}),e.jsx("p",{className:"text-base text-pretty text-amber-900 sm:text-sm",children:"Safe tests still work, but real recipient sends are locked until the workflow is resumed."})]}):null,e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[3fr_2fr]",children:[e.jsxs("section",{className:"flex min-w-0 flex-col gap-4","aria-labelledby":`${n}-draft-source`,children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h2",{id:`${n}-draft-source`,className:"text-sm font-medium text-zinc-900",children:"Compose draft source"}),e.jsx("p",{className:`max-w-[72ch] text-base text-pretty text-zinc-600 43 sm:text-sm`,children:"Compose is the source of truth. This tab does not edit email content, so tests and real sends use the exact same saved draft."})]}),R?e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"h-10 animate-pulse rounded-md bg-zinc-100"}),e.jsx("div",{className:"h-32 animate-pulse rounded-lg bg-zinc-100"})]}):J.length===0?e.jsxs("div",{className:`flex flex-col gap-3 rounded-lg bg-zinc-50 p-4 44 ring-1 ring-black/5`,children:[e.jsx("p",{className:"font-medium text-zinc-900",children:"No complete draft issues."}),e.jsx("p",{className:"text-base text-pretty text-zinc-600 sm:text-sm",children:"Create a Compose draft with a subject, preheader, and body before testing or sending."}),e.jsx(Ae,{className:`inline-flex h-9 items-center justify-center 45 rounded-md bg-zinc-900 px-3 text-sm font-medium 46 tracking-[-0.01em] text-white hover:bg-zinc-800 47 focus-visible:outline-2 focus-visible:outline-offset-2 48 focus-visible:outline-violet-500`,params:{key:t},to:"/admin/workflows/$key/issues/new",children:"Compose issue"})]}):e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(D,{htmlFor:`${n}-draft`,children:"Draft issue"}),e.jsx("select",{className:`rounded-md bg-white px-3 py-2 text-base 49 text-zinc-900 ring-1 ring-black/10 outline-none 50 focus:ring-2 focus:ring-violet-500 sm:text-sm`,id:`${n}-draft`,name:"broadcastDraft",onChange:z=>i(z.target.value),value:E?.id??"",children:J.map(z=>e.jsx("option",{value:z.id,children:dl(z)},z.id))})]}),E?e.jsxs("div",{className:`grid gap-3 rounded-lg bg-zinc-50 p-4 ring-1 51 ring-black/5 sm:grid-cols-2`,children:[e.jsxs("div",{className:"min-w-0 sm:col-span-2",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-900",children:E.payload.subject}),e.jsx("p",{className:`text-base text-pretty text-zinc-600 52 sm:text-sm`,children:E.payload.preheader})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-zinc-500",children:"Draft"}),e.jsx("p",{className:"text-base text-zinc-900 sm:text-sm",children:E.issueNumber===null?"Not numbered yet":`#${E.issueNumber}`})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-zinc-500",children:"Created"}),e.jsx("p",{className:"text-base text-zinc-900 sm:text-sm",children:cl(E.createdAt)})]})]}):null]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h2",{className:"text-sm font-medium text-zinc-900",children:"Rendered preview"}),e.jsx("p",{className:"text-base text-pretty text-zinc-600 sm:text-sm",children:"Preview the final React Email output before any inbox send."})]}),e.jsxs("div",{className:`flex items-center gap-1 rounded-md bg-zinc-100 53 p-0.5`,children:[e.jsx("button",{className:`rounded px-2 py-1 text-sm font-medium ${r==="desktop"?`bg-white text-zinc-900 shadow-sm ring-1 54 ring-black/5`:"text-zinc-600 hover:text-zinc-900"}`,onClick:()=>
54l("desktop"),type:"button",children:"Desktop"}),e.jsx("button",{className:`rounded px-2 py-1 text-sm font-medium ${r==="mobile"?`bg-white text-zinc-900 shadow-sm ring-1 55 ring-black/5`:"text-zinc-600 hover:text-zinc-900"}`,onClick:()=>l("mobile"),type:"button",children:"Mobile"})]})]}),e.jsx(T,{disabled:me||E===void 0,onClick:et,variant:"outline",children:C?"Rendering previewâ¦":"Preview final email"}),G?e.jsx("div",{className:"rounded-lg bg-zinc-100 p-3 ring-1 ring-black/5",children:e.jsx("div",{className:`overflow-hidden rounded-md bg-white ring-1 56 ring-black/10 ${r==="mobile"?"mx-auto w-full max-w-[390px]":"w-full"}`,children:e.jsx("iframe",{className:"h-[32rem] w-full bg-white",sandbox:"",srcDoc:c.html,title:`${r} email preview`})})}):e.jsx("div",{className:"rounded-lg bg-zinc-50 p-4 ring-1 ring-black/5",children:e.jsx("p",{className:"text-base text-pretty text-zinc-600 sm:text-sm",children:"Select a draft and render the desktop or mobile preview."})})]})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-4",children:[e.jsx("section",{className:`rounded-lg bg-emerald-50 p-4 ring-1 57 ring-emerald-200/70`,"aria-labelledby":`${n}-safe-test`,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h2",{id:`${n}-safe-test`,className:"text-sm font-medium text-emerald-950",children:"Safe test inbox"}),e.jsx("p",{className:`text-base text-pretty text-emerald-900 58 sm:text-sm`,children:"Sends one transactional email with a [TEST] subject prefix. This does not create recipients or analytics."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(D,{htmlFor:`${n}-test-email`,children:"Test inbox"}),e.jsx(I,{className:"min-w-0 bg-white max-sm:text-base",id:`${n}-test-email`,name:"testEmail",placeholder:"[email protected]",type:"email",value:u,onChange:z=>x(z.target.value)}),e.jsx(T,{disabled:me||!Ze,onClick:tt,variant:"outline",children:_?"Sending testâ¦":"Send safe test"})]}),G?null:e.jsx("p",{className:`text-base text-pretty text-emerald-900 59 sm:text-sm`,children:"Render the preview for this draft before sending a test inbox email."}),Z?e.jsx(Y,{className:"w-fit",variant:"success",children:"Current draft tested"}):null]})}),e.jsx("section",{className:"rounded-lg bg-rose-50 p-4 ring-1 ring-rose-200/70","aria-labelledby":`${n}-member-send`,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h2",{id:`${n}-member-send`,className:"text-sm font-medium text-rose-950",children:"Real recipient send"}),e.jsx("p",{className:"text-base text-pretty text-rose-900 sm:text-sm",children:"Not a test. Sends the selected Compose draft to members and saved audience contacts after suppression checks and final confirmation. No [TEST] or [PREVIEW] subject prefix is added."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(T,{disabled:me||s||E===void 0,onClick:()=>M(!0),variant:"outline",children:m.length===0?"Pick recipients":`${m.length} selected`}),m.slice(0,4).map(z=>e.jsx(Y,{className:"max-w-full",variant:"secondary",children:e.jsx("span",{className:"truncate",children:z.email})},z._id)),m.length>4?e.jsxs(Y,{variant:"secondary",children:["+",m.length-4," more"]}):null]}),Z?null:e.jsx("p",{className:"text-base text-pretty text-rose-800 sm:text-sm",children:"Send a safe test for this draft to unlock real sends."}),e.jsx(T,{className:"border-rose-300 text-rose-950 hover:bg-rose-100",disabled:me||m.length===0||!we,onClick:ft,variant:"outline",children:w?"Starting real sendâ¦":"Review real send"})]})}),e.jsxs("div",{className:"rounded-lg bg-zinc-50 p-4 ring-1 ring-black/5",children:[e.jsx("h2",{className:"text-sm font-medium text-zinc-900",children:"After sending"}),e.jsx("p",{className:"text-base text-pretty text-zinc-600 sm:text-sm",children:"The copied issue appears on Overview. Delivery status, failures, opens, and clicks appear in Analytics and the issue recipient table."})]})]})]})]}),e.jsx(Ve,{onOpenChange:g,open:b,children:e.jsxs(Je,{className:"max-w-[min(calc(100vw-2rem),460px)]",children:[e.jsxs(Ke,{children:[e.jsx(Ye,{children:"Send real emails?"}),e.jsx(Ge,{className:"text-pretty",children:"This will start a real marketing send to the selected recipients. This is not a safe test."})]}),e.jsxs("div",{className:`flex flex-col gap-3 rounded-lg bg-rose-50 p-3 ring-1 60 ring-rose-200/70`,children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-rose-950",children:"Real subject"}),e.jsx("p",{className:"text-base text-pretty text-rose-900 sm:text-sm",children:E?.payload.subject??"Selected draft"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-rose-950",children:"Recipients"}),e.jsxs("p",{className:"text-base text-rose-900 tabular-nums sm:text-sm",children:[ve," member",ve===1?"":"s"," · ",he," First Orbit"," · ",De," audience contact",De===1?"":"s"]})]})]}),e.jsxs(Xe,{children:[e.jsx(T,{disabled:w,onClick:()=>g(!1),variant:"outline",children:"Cancel"}),e.jsx(T,{className:`bg-rose-600 text-white hover:bg-rose-700 61 focus-visible:ring-rose-500`,disabled:w,onClick:ne,children:w?"Sendingâ¦":"Send real emails"})]})]})}),e.jsx(In,{allowAudienceContacts:!0,open:A,selected:m,onConfirm:S,onOpenChange:M,workflowKey:t})]})]})}function sn(s){return typeof s=="object"&&s!==null}
61async function Xt(s,t,n,a){if(typeof s!="string"||s.trim().length===0)return null;const i=sa(s);return i?na(i.doc,{fontKey:ia(n,i.fontKey),shell:t},a):null}async function hl(s,t,n){let a;try{a=JSON.parse(s)}catch{return null}if(!sn(a))return null;const i=a;let r=!1;const l=await Xt(i.bodyJson,t,i.fontKey,n);l!==null&&(i.bodyHtml=l,r=!0);const c=await Xt(i.introJson,t,i.fontKey,n);return c!==null&&(i.introHtml=c,r=!0),Array.isArray(i.sections)&&(i.sections=await Promise.all(i.sections.map(async d=>{if(!sn(d))return d;const u=await Xt(d.bodyJson,t,i.fontKey,n);return u===null?d:(r=!0,{...d,bodyHtml:u})}))),r?JSON.stringify(i):null}async function ml(s){const{broadcasts:t}=await ma({data:{workflowKey:s.workflowKey}});let n=0,a=0;for(const i of t)try{const r=await hl(i.templatePayload,s.shell,s.extensions);if(r===null)continue;await fa({data:{broadcastId:i.id,templatePayload:r}}),n+=1}catch{a+=1}return{failed:a,updated:n}}const Qn=330;function nn(s){let n=s.hour*60+s.minute-Qn,a=0;return n<0?(n+=1440,a=-1):n>=1440&&(n-=1440,a=1),{dow:(s.dow+a+7)%7,hour:Math.floor(n/60),minute:n%60}}function js(s){let n=s.hour*60+s.minute+Qn,a=0;return n>=1440&&(n-=1440,a=1),{dow:(s.dow+a+7)%7,hour:Math.floor(n/60),minute:n%60}}const fl={off:"Real emails go out on real delays. Required for auto-enroll. Use this once you have fully tested the workflow.",accelerated:"Real emails go out, but every wait collapses to a few minutes so you can walk through the whole sequence quickly. Auto-enroll is blocked.",dry_run:"Nothing is sent. Each step logs to events so you can verify rendering, branching, and ordering without spamming inboxes. Auto-enroll is blocked."},pl=64;function Ct(s){const t=zt(s.shellJson);return{testMode:s.testMode,fromAddress:s.fromAddress??"",fromName:s.fromName??"",replyTo:s.replyTo??"",autoDraftEnabled:s.autoDraftEnabled??!1,autoDraftDow:s.autoDraftDow??null,autoDraftHourUtc:s.autoDraftHourUtc??null,autoDraftMinuteUtc:s.autoDraftMinuteUtc??null,autoDraftAiFill:s.autoDraftAiFill??!1,shellLogoUrl:t?.logoUrl??"",shellFooterNote:t?.footerNote??"",shellAddressLabel:t?.addressLabel??"",shellPostalAddress:t?.postalAddress??"",shellPrivacyUrl:t?.privacyUrl??"",shellTermsUrl:t?.termsUrl??"",shellCopyrightText:t?.copyrightText??"",shellFontKey:t?.fontKey??"",shellHeaderStyle:t?.headerStyle??"",shellHeaderColor:t?.headerColor??"",shellAccentColor:t?.accentColor??"",shellLinkColor:t?.linkColor??"",shellPageBgColor:t?.pageBgColor??"",shellCardBgColor:t?.cardBgColor??"",shellBorderColor:t?.borderColor??"",shellSectionIconSize:t?.sectionIconSize!=null?String(t.sectionIconSize):"",shellSectionDividers:t?.sectionDividers??yn.sectionDividers,shellHeadingColor:t?.headingColor??"",shellHeadingSize:t?.headingSize!=null?String(t.headingSize):"",shellHeadingWeight:t?.headingWeight??""}}function Zt(s,t){return s.testMode===t.testMode&&s.fromAddress.trim()===t.fromAddress.trim()&&s.fromName.trim()===t.fromName.trim()&&s.replyTo.trim()===t.replyTo.trim()&&s.autoDraftEnabled===t.autoDraftEnabled&&s.autoDraftDow===t.autoDraftDow&&s.autoDraftHourUtc===t.autoDraftHourUtc&&s.autoDraftMinuteUtc===t.autoDraftMinuteUtc&&s.autoDraftAiFill===t.autoDraftAiFill&&s.shellLogoUrl.trim()===t.shellLogoUrl.trim()&&s.shellFooterNote.trim()===t.shellFooterNote.trim()&&s.shellAddressLabel.trim()===t.shellAddressLabel.trim()&&s.shellPostalAddress.trim()===t.shellPostalAddress.trim()&&s.shellPrivacyUrl.trim()===t.shellPrivacyUrl.trim()&&s.shellTermsUrl.trim()===t.shellTermsUrl.trim()&&s.shellCopyrightText.trim()===t.shellCopyrightText.trim()&&s.shellFontKey===t.shellFontKey&&s.shellHeaderStyle===t.shellHeaderStyle&&s.shellHeaderColor.trim()===t.shellHeaderColor.trim()&&s.shellAccentColor.trim()===t.shellAccentColor.trim()&&s.shellLinkColor.trim()===t.shellLinkColor.trim()&&s.shellPageBgColor.trim()===t.shellPageBgColor.trim()&&s.shellCardBgColor.trim()===t.shellCardBgColor.trim()&&s.shellBorderColor.trim()===t.shellBorderColor.trim()&&s.shellSectionIconSize.trim()===t.shellSectionIconSize.trim()&&s.shellSectionDividers===t.shellSectionDividers&&s.shellHeadingColor.trim()===t.shellHeadingColor.trim()&&s.shellHeadingSize.trim()===t.shellHeadingSize.trim()&&s.shellHeadingWeight===t.shellHeadingWeight}function es(s,t){const n=[],a=(i,r)=>{const l=r.trim();l.length>0&&n.push([i,l])};return a("logoUrl",s.shellLogoUrl),a("footerNote",s.shellFooterNote),a("addressLabel",s.shellAddressLabel),a("postalAddress",s.shellPostalAddress),a("privacyUrl",s.shellPrivacyUrl),a("termsUrl",s.shellTermsUrl),a("copyrightText",s.shellCopyrightText),t==="newsletter"&&(a("fontKey",s.shellFontKey),a("headerStyle",s.shellHeaderStyle),a("headerColor",s.shellHeaderColor),a("accentColor",s.shellAccentColor),a("linkColor",s.shellLinkColor),a("pageBgColor",s.shellPageBgColor),a("cardBgColor",s.shellCardBgColor),a("borderColor",s.shellBorderColor),a("sectionIconSize",s.shellSectionIconSize),n.push(["sectionDividers",s.shellSectionDividers?"true":"false"]),a("headingColor",s.shellHeadingColor),a("headingSize",s.shellHeadingSize),a("headingWeight",s.shellHeadingWeight)),n.length>0?Object.fromEntries(n):void 0}const Un=[{dow:1,label:"Monday"},{dow:2,label:"Tuesday"},{dow:3,label:"Wednesday"},{dow:4,label:"Thursday"},{dow:5,label:"Friday"},{dow:6,label:"Saturday"},{dow:0,label:"Sunday"}],xl=Array.from({length:48},(s,t)=>{const n=Math.floor(t/2),a=t%2===0?0:30;return{hour:n,label:`${String(n).padStart(2,"0")}
61:${String(a).padStart(2,"0")}`,minute:a}});function gl(s){return s.autoDraftDow!==null&&s.autoDraftHourUtc!==null&&s.autoDraftMinuteUtc!==null}function bl(s){if(!gl(s))return null;const t=js({dow:s.autoDraftDow??0,hour:s.autoDraftHourUtc??0,minute:s.autoDraftMinuteUtc??0}),n=Un.find(i=>i.dow===t.dow)?.label??"",a=`${String(t.hour).padStart(2,"0")}:${String(t.minute).padStart(2,"0")}`;return`Every ${n} at ${a} IST`}function yl({config:s,workflowKey:t}){const n=$e(),a=aa(),{data:i}=de({queryKey:["admin","configDraft",t],queryFn:()=>pr({data:{workflowKey:t}})}),r=Ct(s),l=i?Ct({testMode:i.testMode,fromAddress:i.fromAddress??void 0,fromName:i.fromName??void 0,replyTo:i.replyTo??void 0,autoDraftEnabled:i.autoDraftEnabled,autoDraftDow:i.autoDraftDow??void 0,autoDraftHourUtc:i.autoDraftHourUtc??void 0,autoDraftMinuteUtc:i.autoDraftMinuteUtc??void 0,autoDraftAiFill:i.autoDraftAiFill,shellJson:i.shellJson}):null,c=l??r,[d,u]=f.useState(c),[x,m]=f.useState(!1),S=i?.id,A=i?.updatedAt?new Date(i.updatedAt).getTime():null;f.useEffect(()=>{u(Ct(i?{testMode:i.testMode,fromAddress:i.fromAddress??void 0,fromName:i.fromName??void 0,replyTo:i.replyTo??void 0,autoDraftEnabled:i.autoDraftEnabled,autoDraftDow:i.autoDraftDow??void 0,autoDraftHourUtc:i.autoDraftHourUtc??void 0,autoDraftMinuteUtc:i.autoDraftMinuteUtc??void 0,autoDraftAiFill:i.autoDraftAiFill,shellJson:i.shellJson}:s))},[S,A,s,i]);const M=()=>n.invalidateQueries({queryKey:["admin","configDraft",t]}),b=l?Zt(d,l):!1,g=Zt(d,r),C=l?Zt(l,r):!0,F=async()=>{m(!0);try{await Ys({data:{workflowKey:t,testMode:d.testMode,fromAddress:d.fromAddress.trim()===""?void 0:d.fromAddress.trim(),fromName:d.fromName.trim()===""?void 0:d.fromName.trim(),replyTo:d.replyTo.trim()===""?void 0:d.replyTo.trim(),autoDraftEnabled:d.autoDraftEnabled,autoDraftDow:d.autoDraftDow,autoDraftHourUtc:d.autoDraftHourUtc,autoDraftMinuteUtc:d.autoDraftMinuteUtc,autoDraftAiFill:d.autoDraftAiFill,shell:es(d,t)}}),M(),$.success("Draft saved.")}catch(j){$.error(j instanceof Error?j.message:String(j))}finally{m(!1)}},_=async()=>{m(!0);try{b||await Ys({data:{workflowKey:t,testMode:d.testMode,fromAddress:d.fromAddress.trim()===""?void 0:d.fromAddress.trim(),fromName:d.fromName.trim()===""?void 0:d.fromName.trim(),replyTo:d.replyTo.trim()===""?void 0:d.replyTo.trim(),autoDraftEnabled:d.autoDraftEnabled,autoDraftDow:d.autoDraftDow,autoDraftHourUtc:d.autoDraftHourUtc,autoDraftMinuteUtc:d.autoDraftMinuteUtc,autoDraftAiFill:d.autoDraftAiFill,shell:es(d,t)}}),await xr({data:{workflowKey:t}}),M(),n.invalidateQueries({queryKey:["admin","workflowDetail",t]});const j=zt(JSON.stringify(es(d,t)??{})),y=JSON.stringify(j)!==JSON.stringify(zt(s.shellJson??null));if(t==="newsletter"&&y){const R=await ml({extensions:a,shell:j,workflowKey:t});R.failed>0?$.warning(`Published. ${R.failed} pending issue(s) could not pick up the new design â open and re-save them.`):R.updated>0?$.success(`Published â ${R.updated} pending issue(s) updated with the new design.`):$.success("Published.")}else $.success("Published.")}catch(j){$.error(j instanceof Error?j.message:String(j))}finally{m(!1)}},v=async()=>{m(!0);try{await gr({data:{workflowKey:t}}),M(),$.success("Reverted to published.")}catch(j){$.error(j instanceof Error?j.message:String(j))}finally{m(!1)}},w=l!==null&&!C,p=!g||w?w&&b?`Draft saved ${je(A??null)}. Click Publish to make it live.`:"Unsaved changes. Save as draft to keep them, or Publish to apply.":null;return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(oe,{children:"Settings"}),e.jsx(ue,{children:"Test mode and the From / Reply to addresses for this workflow. Changes don't go live until you click Publish."})]}),e.jsxs(ce,{className:"space-y-4",children:[p?e.jsx("div",{className:`rounded-md bg-amber-50 px-3 py-2 text-sm text-amber-800 62 ring-1 ring-amber-200`,children:p}):null,e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"Test mode"}),e.jsxs(ie,{onValueChange:j=>u(y=>({...y,testMode:j})),value:d.testMode,children:[e.jsx(ae,{children:e.jsx(re,{})}),e.jsxs(le,{children:[e.jsx(V,{value:"off",children:"Off â send for real"}),e.jsx(V,{value:"accelerated",children:"Accelerated â short delays"}),e.jsx(V,{value:"dry_run",children:"Dry run â log only, no email"})]})]}),e.jsx("p",{className:"text-sm text-pretty text-zinc-600",children:fl[d.testMode]})]}),e.jsx(Nl,{form:d,onChange:j=>u(y=>({...y,...j}))}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"From name"}),e.jsx(I,{maxLength:pl,onChange:j=>u(y=>({...y,fromName:j.target.value})),placeholder:"Bikash from Orian",value:d.fromName}),e.jsx("p",{className:"text-xs text-zinc-500",children:"Display name shown to recipients before the address. Leave blank to send as just the From address."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"From address"}),e.jsx(I,{onChange:j=>u(y=>({...y,fromAddress:j.target.value})),placeholder:"[email protected]",value:d.fromAddress})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(D,{children:"Reply to"}),e.jsx(I,{onChange:j=>u(y=>({...y,replyTo:j.target.value})),placeholder:"[email protected]",value:d.replyTo})]})]}),t==="newsletter"?e.jsx(jl,{form:d,onChange:j=>u(y=>({...y,...j}))}):null]}),e.jsxs(us,{className:"flex flex-wrap items-center justify-end gap-2",children:[w?e.jsx(T,{disabled:x,onClick:v,type:"button",variant:"outline",children:"Revert to published"}):null,e.jsx(T,{disabled:x||b&&w,onClick:F,type:"button",variant:"outline",children:"Save draft"}),e.jsx(T,{disabled:x||g&&!w,onClick:_,type:"button",children:"Publish"})]})]})}const He=yn;function jl({form:s,onChange:t}){return e.jsxs("div",{className:"space-y-3 rounded-lg bg-zinc-50 p-4 ring-1 ring-black/5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(D,{className:"text-sm font-medium text-zinc-900",children:"Email shell"}),e.jsx("p",{className:"text-sm text-pretty text-zinc-600",children:"Logo, footer note, mailing address, legal links, and copyright wrapped around every issue. Leave a field blank to use the default shown as placeholder. Unsubscribe handling stays automatic."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"shell-logo-url",children:"Logo URL"}),e.jsx(I,{id:"shell-logo-url",maxLength:Oe.url,onChange:n=>
62t({shellLogoUrl:n.target.value}),placeholder:He.logoUrl,value:s.shellLogoUrl})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"shell-footer-note",children:"Footer note"}),e.jsx(te,{id:"shell-footer-note",maxLength:Oe.footerNote,onChange:n=>t({shellFooterNote:n.target.value}),placeholder:He.footerNote,rows:2,value:s.shellFooterNote}),e.jsx("p",{className:"text-xs text-zinc-500",children:"Why the recipient is getting this email. Plain text only."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"shell-address-label",children:"Mailing address label"}),e.jsx(I,{id:"shell-address-label",maxLength:Oe.label,onChange:n=>t({shellAddressLabel:n.target.value}),placeholder:He.addressLabel,value:s.shellAddressLabel})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"shell-postal-address",children:"Mailing address"}),e.jsx(I,{id:"shell-postal-address",maxLength:Oe.label,onChange:n=>t({shellPostalAddress:n.target.value}),placeholder:"5000 Gulf Fwy, Houston, TX 77204, USA",value:s.shellPostalAddress}),e.jsx("p",{className:"text-xs text-zinc-500",children:"When set, this wins over the COMPANY_POSTAL_ADDRESS environment value."})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"shell-privacy-url",children:"Privacy policy URL"}),e.jsx(I,{id:"shell-privacy-url",maxLength:Oe.url,onChange:n=>t({shellPrivacyUrl:n.target.value}),placeholder:He.privacyUrl,value:s.shellPrivacyUrl})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"shell-terms-url",children:"Terms URL"}),e.jsx(I,{id:"shell-terms-url",maxLength:Oe.url,onChange:n=>t({shellTermsUrl:n.target.value}),placeholder:He.termsUrl,value:s.shellTermsUrl})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"shell-copyright",children:"Copyright line"}),e.jsx(I,{id:"shell-copyright",maxLength:Oe.label,onChange:n=>t({shellCopyrightText:n.target.value}),placeholder:He.copyrightText,value:s.shellCopyrightText})]}),e.jsxs("div",{className:"space-y-3 border-t border-black/5 pt-3",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-900",children:"Design"}),e.jsx(Yi,{onChange:n=>t(wl(n)),values:vl(s)})]})]})}function vl(s){return{accentColor:s.shellAccentColor,borderColor:s.shellBorderColor,cardBgColor:s.shellCardBgColor,fontKey:s.shellFontKey,headerColor:s.shellHeaderColor,headerStyle:s.shellHeaderStyle,headingColor:s.shellHeadingColor,headingSize:s.shellHeadingSize,headingWeight:s.shellHeadingWeight,linkColor:s.shellLinkColor,pageBgColor:s.shellPageBgColor,sectionDividers:s.shellSectionDividers,sectionIconSize:s.shellSectionIconSize}}function wl(s){const t={};return s.fontKey!==void 0&&(t.shellFontKey=s.fontKey),s.headerStyle!==void 0&&(t.shellHeaderStyle=s.headerStyle),s.headerColor!==void 0&&(t.shellHeaderColor=s.headerColor),s.accentColor!==void 0&&(t.shellAccentColor=s.accentColor),s.linkColor!==void 0&&(t.shellLinkColor=s.linkColor),s.pageBgColor!==void 0&&(t.shellPageBgColor=s.pageBgColor),s.cardBgColor!==void 0&&(t.shellCardBgColor=s.cardBgColor),s.borderColor!==void 0&&(t.shellBorderColor=s.borderColor),s.sectionIconSize!==void 0&&(t.shellSectionIconSize=s.sectionIconSize),s.sectionDividers!==void 0&&(t.shellSectionDividers=s.sectionDividers),s.headingColor!==void 0&&(t.shellHeadingColor=s.headingColor),s.headingSize!==void 0&&(t.shellHeadingSize=s.headingSize),s.headingWeight!==void 0&&(t.shellHeadingWeight=s.headingWeight),t}function Nl({form:s,onChange:t}){const n=s.autoDraftEnabled,a=s.autoDraftDow!==null&&s.autoDraftHourUtc!==null&&s.autoDraftMinuteUtc!==null?js({dow:s.autoDraftDow,hour:s.autoDraftHourUtc,minute:s.autoDraftMinuteUtc}):null,i=c=>{const d=Number(c),u=a?.hour??9,x=a?.minute??30,m=nn({dow:d,hour:u,minute:x});t({autoDraftDow:m.dow,autoDraftHourUtc:m.hour,autoDraftMinuteUtc:m.minute})},r=c=>{const[d,u]=c.split(":"),x=Number(d),m=Number(u),S=a?.dow??4,A=nn({dow:S,hour:x,minute:m});t({autoDraftDow:A.dow,autoDraftHourUtc:A.hour,autoDraftMinuteUtc:A.minute})},l=bl(s);return e.jsxs("div",{className:"space-y-3 rounded-lg bg-zinc-50 p-4 ring-1 ring-black/5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(D,{className:"text-sm font-medium text-zinc-900",children:"Auto-draft cadence"}),e.jsx("p",{className:"text-sm text-pretty text-zinc-600",children:"Create a draft issue automatically each week. Off by default. The draft is empty â you still compose and publish manually."})]}),e.jsx(is,{"aria-label":"Toggle auto-draft",checked:n,onCheckedChange:c=>t({autoDraftEnabled:c})})]}),n?e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-zinc-600",htmlFor:"cadence-day",children:"Day"}),e.jsxs(ie,{onValueChange:i,value:a!==null?String(a.dow):void 0,children:[e.jsx(ae,{id:"cadence-day",children:e.jsx(re,{placeholder:"Pick a day"})}),e.jsx(le,{children:Un.map(c=>e.jsx(V,{value:String(c.dow),children:c.label},c.dow))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-zinc-600",htmlFor:"cadence-time",children:"Time (IST)"}),e.jsxs(ie,{onValueChange:r,value:a!==null?`${String(a.hour).padStart(2,"0")}
62:${String(a.minute).padStart(2,"0")}`:void 0,children:[e.jsx(ae,{id:"cadence-time",children:e.jsx(re,{placeholder:"Pick a time"})}),e.jsx(le,{className:"max-h-72",children:xl.map(c=>e.jsx(V,{value:c.label,children:c.label},c.label))})]})]})]}):null,n&&l!==null?e.jsx("p",{className:"text-xs text-zinc-600 tabular-nums",children:l}):null,n&&l===null?e.jsx("p",{className:"text-xs text-amber-700",children:"Pick a day and time to enable auto-draft."}):null,e.jsxs("div",{className:`flex items-start justify-between gap-3 border-t 63 border-black/5 pt-3`,children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(D,{className:"text-sm font-medium text-zinc-900",children:"AI auto-fill"}),e.jsx("p",{className:"text-sm text-pretty text-zinc-600",children:"Generate subject and body using the workflow's prompts and signal brief when the draft fires. Always lands as a draft â you still review and send manually."})]}),e.jsx(is,{"aria-label":"Toggle AI auto-fill",checked:s.autoDraftAiFill,onCheckedChange:c=>t({autoDraftAiFill:c})})]})]})}const an={canceled:"secondary",draft:"secondary","draft-sendnow":"warning",failed:"danger",scheduled:"default",sending:"warning",sent:"success"},rn={canceled:"Canceled",draft:"Draft","draft-sendnow":"Sending shortly",failed:"Failed",scheduled:"Scheduled",sending:"Sending",sent:"Sent"};function Sl(s){return s in rn?rn[s]:s}function Cl(s){return s in an?an[s]:"secondary"}function kl(s){return s==="draft"||s==="scheduled"||s==="draft-sendnow"||s==="canceled"}function Tl({score:s}){const t=s>=75?"bg-emerald-50 text-emerald-700 ring-emerald-200/60":s>=50?"bg-amber-50 text-amber-700 ring-amber-200/60":"bg-rose-50 text-rose-700 ring-rose-200/60";return e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full px-2 py-0.5 64 text-xs font-medium tabular-nums ring-1 ${t}`,title:`AI confidence score ${s}/100`,children:["score ",s]})}function Al({workflowKey:s}
64){const t=$e(),[n,a]=f.useState(null),i=async m=>{if(window.confirm("Delete this issue permanently? This cannot be undone.")){a(m);try{await pa({data:{broadcastId:m}}),$.success("Issue deleted."),await t.invalidateQueries({queryKey:["admin","broadcasts",s]})}catch(S){$.error(S instanceof Error?S.message:String(S))}finally{a(null)}}},{data:r,fetchNextPage:l,hasNextPage:c,isFetching:d,isLoading:u}=vn({queryKey:["admin","broadcasts",s],initialPageParam:null,queryFn:({pageParam:m})=>gn({data:{workflowKey:s,limit:25,cursor:m??void 0}}),getNextPageParam:m=>m.isDone?void 0:m.continueCursor}),x=f.useMemo(()=>(r?.pages??[]).flatMap(m=>m.page),[r]);return e.jsxs(ee,{children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(oe,{children:"Newsletter issues"}),e.jsx(ue,{children:"Past and upcoming broadcasts for this workflow."})]}),e.jsx(Ae,{className:`inline-flex h-9 items-center justify-center rounded-md 65 bg-zinc-900 px-3 text-sm font-medium tracking-[-0.01em] text-white 66 transition-colors hover:bg-zinc-800`,params:{key:s},to:"/admin/workflows/$key/issues/new",children:"Compose issue"})]})}),e.jsxs(ce,{children:[u&&x.length===0?e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx("div",{className:"h-9 animate-pulse rounded bg-zinc-100"}),e.jsx("div",{className:"h-9 animate-pulse rounded bg-zinc-100"}),e.jsx("div",{className:"h-9 animate-pulse rounded bg-zinc-100"})]}):x.length===0?e.jsxs("div",{className:"py-10 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-900",children:"No issues yet"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-500",children:"Compose your first newsletter to get started."}),e.jsx(Ae,{className:`mt-4 inline-flex h-9 items-center justify-center 67 rounded-md bg-zinc-900 px-3 text-sm font-medium 68 tracking-[-0.01em] text-white transition-colors 69 hover:bg-zinc-800`,params:{key:s},to:"/admin/workflows/$key/issues/new",children:"Compose issue"})]}):e.jsxs(jn,{children:[e.jsx(fs,{children:e.jsxs(Le,{children:[e.jsx(K,{children:"Issue"}),e.jsx(K,{children:"Status"}),e.jsx(K,{children:"Scheduled"}),e.jsx(K,{className:"hidden md:table-cell",children:"Audience"}),e.jsx(K,{})]})}),e.jsx(ps,{children:x.map(m=>e.jsxs(Le,{children:[e.jsx(Q,{className:"max-w-[38ch] text-sm",children:e.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[e.jsx("div",{className:"truncate font-medium text-zinc-900",children:Gi(m.templatePayload)}),e.jsx("div",{className:"text-zinc-500 tabular-nums",children:m.issueNumber==null?"Draft not numbered":`Issue #${m.issueNumber}`})]})}),e.jsx(Q,{children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(Y,{variant:Cl(m.status),children:Sl(m.status)}),typeof m.aiConfidence=="number"?e.jsx(Tl,{score:m.aiConfidence}):null,m.triggeredBy==="manual"?e.jsx("span",{className:"text-xs text-zinc-500",children:"Selected send"}):null,m.aiSource?e.jsx("span",{className:"text-xs text-zinc-500",title:`AI source: ${m.aiSource}`,children:m.aiSource==="auto"?"AI":m.aiSource==="manual_regen"?"AI · regen":m.aiSource==="auto_low_score"||m.aiSource==="manual_regen_low_score"?"AI · low score":m.aiSource==="auto_failed"?"AI · failed":"AI"}):null]})}),e.jsx(Q,{className:"text-sm text-zinc-600",children:je(m.scheduledAt?.getTime()??null)}),e.jsx(Q,{className:`hidden text-sm text-zinc-600 tabular-nums 70 md:table-cell`,children:m.audienceCount.toLocaleString()}),e.jsx(Q,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[m.status==="draft"?e.jsx(Ae,{params:{key:s},search:{edit:m.id},to:"/admin/workflows/$key/issues/new",children:e.jsx(T,{size:"sm",variant:"outline",children:"Edit"})}):null,e.jsx(Ae,{params:{issueId:m.id,key:s},to:"/admin/workflows/$key/issues/$issueId",children:e.jsx(T,{size:"sm",variant:"outline",children:"Open"})}),kl(m.status)?e.jsx(T,{"aria-label":"Delete issue",className:`px-2 text-rose-600 hover:bg-rose-50 71 hover:text-rose-700`,disabled:n===m.id,onClick:()=>i(m.id),size:"sm",variant:"outline",children:e.jsx(ra,{className:"size-3.5"})}):null]})})]},m.id))})]}),c?e.jsx("div",{className:"mt-4 flex justify-center",children:e.jsx(T,{disabled:d,onClick:()=>l(),variant:"outline",children:"Load more"})}):null]})]})}function zl({enabled:s,workflowKey:t}){const[n,a]=f.useState(!1),[i,r]=f.useState(null),[l,c]=f.useState(!1),d=$e(),{data:u}=de({queryKey:["admin","previewLiveSync",t],queryFn:()=>Li({data:{workflowKey:t}}),enabled:n}),x=S=>{r(S),a(!0)},m=async()=>
71{if(i!==null){c(!0);try{await fr({data:{workflowKey:t,autoTriggerEnabled:i}}),d.invalidateQueries({queryKey:["admin","workflowDetail",t]}),$.success(i?"Auto-enroll on. New signups will be enrolled automatically.":"Auto-enroll off. Anyone already in the workflow keeps moving through it."),a(!1),r(null)}catch(S){$.error(S instanceof Error?S.message:String(S))}finally{c(!1)}}};return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(oe,{children:"Auto-enroll"}),e.jsx(ue,{children:"When on, new members who match this workflow's audience are enrolled automatically. When off, you can still trigger sends manually."})]}),e.jsxs(ce,{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-zinc-700",children:["Auto-enroll is"," ",e.jsx("span",{className:"font-medium",children:s?"on":"off"}),"."]}),e.jsx(is,{checked:s,onCheckedChange:x})]}),e.jsx(Ve,{onOpenChange:a,open:n,children:e.jsxs(Je,{children:[e.jsxs(Ke,{children:[e.jsx(Ye,{children:i?"Turn auto-enroll on?":"Turn auto-enroll off?"}),e.jsx(Ge,{children:i?u?.message??"Loadingâ¦":"New signups will stop enrolling automatically. Members already in the workflow keep moving through it."})]}),i&&u&&u.kind==="broadcast"&&u.nextRunAt?e.jsxs("p",{className:"text-sm text-zinc-600",children:["Next scheduled send: ",Fi(u.nextRunAt)]}):null,e.jsxs(Xe,{children:[e.jsx(T,{onClick:()=>a(!1),variant:"outline",children:"Cancel"}),e.jsx(T,{disabled:l,onClick:m,children:i?"Turn on":"Turn off"})]})]})})]})}const Me="__first__",$l=[{value:"unset",label:"Not set"},{value:"knowledge_creator",label:"Knowledge creator"},{value:"startup_community",label:"Startup community"},{value:"after_school",label:"After-school"}];function Dl(s){const{count:t,mode:n,steps:a,stepKey:i}=s,r=t===1?"member":"members";if(n==="full")return i===Me?`Starts the full sequence at the first step for ${t} ${r}. Suppressed emails are skipped.`:`Starts the sequence at "${a.find(d=>d.key===i)?.key??i}" for ${t} ${r}. Suppressed emails are skipped.`;const l=a.find(c=>c.key===i);return l?`Sends "${l.key}" once to ${t} ${r}. Suppressed emails are skipped. Does not enroll them in the sequence.`:`Sends a single step to ${t} ${r} once. Pick a step above.`}const Ml=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function _l(s){const[t,n]=f.useState("members"),[a,i]=f.useState(!1),[r,l]=f.useState([]),[c,d]=f.useState(Me),[u,x]=f.useState("full"),[m,S]=f.useState(!1),[A,M]=f.useState(""),[b,g]=f.useState(""),[C,F]=f.useState("unset"),[_,v]=f.useState(8640),[w,L]=f.useState(Me),p=async()=>{if(r.length===0){$.error("Pick at least one member.");return}if(u==="one_off"&&c===Me){$.error("Pick a step to send.");return}const y=r.map(R=>R._id);S(!0);try{u==="one_off"?(await Sr({data:{workflowKey:s.workflowKey,memberIds:y,stepKey:c}}),$.success(`Queued one-off send for ${y.length} member(s).`)):(await wr({data:{workflowKey:s.workflowKey,memberIds:y,startAtStepKey:c===Me?void 0:c}}),$.success(`Started sequence for ${y.length} member(s).`)),l([])}catch(R){$.error(R instanceof Error?R.message:String(R))}finally{S(!1)}},j=async()=>{const y=A.trim();if(!Ml.test(y)){$.error("Enter a valid email.");return}S(!0);try{await Nr({data:{workflowKey:s.workflowKey,email:y,name:b.trim()||void 0,icpSegment:C==="unset"?void 0:C,timeScale:_,startAtStepKey:w===Me?void 0:w}});const R=_===8640?"compressed (1 day â 10 seconds)":"real-time";$.success(`Test enrolled â cadence ${R}. Auto-purges in 7d.`),M(""),g("")}catch(R){$.error(R instanceof Error?R.message:String(R))}finally{S(!1)}};return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(oe,{children:"Send manually"}),e.jsx(ue,{children:"Send to existing members or run a synthetic test enrollment for any email. Suppressed emails are always skipped."})]}),e.jsx(ce,{children:e.jsxs(hs,{onValueChange:y=>n(y),value:t,children:[e.jsxs(ms,{className:"mb-4",children:[e.jsx(xe,{value:"members",children:"Existing members"}),e.jsx(xe,{value:"test",children:"Test email"})]}),e.jsxs(Fe,{className:"space-y-4",value:"members",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"Members"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(T,{onClick:()=>i(!0),variant:"outline",children:r.length===0?"Pick membersâ¦":`${r.length} selected`}),r.slice(0,4).map(y=>e.jsx(Y,{variant:"secondary",children:y.email},y._id)),r.length>4?e.jsxs(Y,{variant:"secondary",children:["+",r.length-4," more"]}):null]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"What to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{onClick:()=>x("full"),size:"sm",variant:u==="full"?"default":"outline",children:"Whole sequence"}),e.jsx(T,{onClick:()=>x("one_off"),size:"sm",variant:u==="one_off"?"default":"outline",children:"One step only"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:u==="one_off"?"Step to send":"Start at step"}),e.jsxs(ie,{onValueChange:d,value:c,children:[e.jsx(ae,{children:e.jsx(re,{})}),e.jsxs(le,{children:[u==="full"?e.jsx(V,{value:Me,children:"First step (default)"}):null,s.steps.map(y=>e.jsxs(V,{value:y.key,children:[y.key,y.isPlaceholder?" (stub)":""]},y.key))]})]})]})]}),r.length>0?e.jsx("div",{className:`rounded-lg bg-zinc-50 p-3 text-sm text-pretty 72 text-zinc-700`,children:Dl({count:r.length,mode:u,steps:s.steps,stepKey:c})}):null,e.jsx("div",{className:"flex justify-end",children:e.jsx(T,{disabled:r.length===0||m,onClick:p,children:"Send now"})})]}),e.jsxs(Fe,{className:"space-y-4",value:"test",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"test-email",children:"Email"}),e.jsx(I,{id:"test-email",onChange:y=>M(y.target.value),placeholder:"[email protected]",type:"email",value:A})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"test-name",children:"Name (optional)"}),e.jsx(I,{id:"test-name",onChange:y=>g(y.target.value),placeholder:"Alex",value:b})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"ICP segment"}),e.jsxs(ie,{onValueChange:F,value:C,children:[e.jsx(ae,{children:e.jsx(re,{})}),e.jsx(le,{children:$l.map(y=>e.jsx(V,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"Start at step"}),e.jsxs(ie,{onValueChange:L,value:w,children:[e.jsx(ae,{children:e.jsx(re,{})}),e.jsxs(le,{children:[e.jsx(V,{value:Me,children:"First step (default)"}),s.steps.map(y=>e.jsxs(V,{value:y.key,children:[y.key,y.isPlaceholder?" (stub)":""]},y.key))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"Time scale"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{onClick:()=>v(1),size:"sm",variant:_===1?"default":"outline",children:"Real-time (1Ã)"}),e.jsx(T,{onClick:()=>v(8640),size:"sm",variant:_===8640?"default":"outline",children:"Days â 10s"})]}),e.jsx("p",{className:"text-sm text-zinc-500",children:_===8640?"1 day of delay collapses to ~10 seconds (min 10s floor). Synthetic member auto-purges in 7 days.":"Real cadence â multi-day delays still apply. Synthetic member auto-purges in 7 days."})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(T,{disabled:A.trim().length===0||m,onClick:j,children:"Start test"})})]})]})}),e.jsx(In,{onConfirm:l,onOpenChange:i,open:a,selected:r,workflowKey:s.workflowKey})]})}const Fl={aiMinConfidence:50,antiPatternsRaw:"",ctaKeywordsRaw:`join 73sign up 74reply 75click 76try 77start`,promptTemplate:"",subjectPrinciples:"",voiceCard:"",wordCountMax:700,wordCountMin:500};function ln(s){return s.split(` 78`).map(t=>t.trim()).filter(t=>t.length>0)}function on(s){return s.join(` 79`)}function Ll(s,t){return s.voiceCard===t.voiceCard&&s.promptTemplate===t.promptTemplate&&s.antiPatternsRaw===t.antiPatternsRaw&&s.ctaKeywordsRaw===t.ctaKeywordsRaw&&s.subjectPrinciples===t.subjectPrinciples&&s.wordCountMin===t.wordCountMin&&s.wordCountMax===t.wordCountMax&&s.aiMinConfidence===t.aiMinConfidence}function Pl({workflowKey:s}
79){const t=$e(),{data:n,isLoading:a}=de({queryFn:()=>ga({data:{workflowKey:s}}),queryKey:["admin","prompts",s]}),i=n?{aiMinConfidence:n.aiMinConfidence,antiPatternsRaw:on(n.antiPatterns),ctaKeywordsRaw:on(n.ctaKeywords),promptTemplate:n.promptTemplate,subjectPrinciples:n.subjectPrinciples,voiceCard:n.voiceCard,wordCountMax:n.wordCountMax,wordCountMin:n.wordCountMin}:Fl,[r,l]=f.useState(!1),[c,d]=f.useState(i),[u,x]=f.useState(!1),m=f.useRef(i);f.useEffect(()=>{m.current=i,d(i)},[n?.updatedAt]);const S=!Ll(c,m.current),A=async()=>{x(!0);try{await xa({data:{aiMinConfidence:c.aiMinConfidence,antiPatterns:ln(c.antiPatternsRaw),ctaKeywords:ln(c.ctaKeywordsRaw),promptTemplate:c.promptTemplate,subjectPrinciples:c.subjectPrinciples,voiceCard:c.voiceCard,wordCountMax:c.wordCountMax,wordCountMin:c.wordCountMin,workflowKey:s}}),t.invalidateQueries({queryKey:["admin","prompts",s]}),$.success("Prompts saved.")}catch(b){$.error(b instanceof Error?b.message:String(b))}finally{x(!1)}},M=()=>{d(m.current)};return e.jsxs(ee,{children:[e.jsxs("button",{"aria-controls":`prompts-body-${s}`,"aria-expanded":r,className:`flex w-full items-start justify-between gap-3 rounded-t-xl 80 p-6 text-left transition-colors hover:bg-zinc-50 81 focus-visible:bg-zinc-50 focus-visible:outline-none`,onClick:()=>l(b=>!b),type:"button",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{"aria-hidden":!0,className:`mt-0.5 inline-flex size-7 shrink-0 items-center 82 justify-center rounded-md ring-1 ${n&&n.voiceCard.trim().length>0?"bg-emerald-50 text-emerald-700 ring-emerald-200/60":"bg-violet-50 text-violet-600 ring-violet-200/60"}`,children:e.jsx(la,{className:"size-4"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{children:"AI prompts"}),e.jsx(ue,{children:"Voice card, prompt template, and constraints used by AI compose. Per-workflow."}),n?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-zinc-700 tabular-nums",children:[n.voiceCard.length," char voice ·"," ",n.antiPatterns.length," anti-patterns ·"," ",n.wordCountMin,"â",n.wordCountMax," words"]}),e.jsxs("p",{className:"text-xs text-zinc-500 tabular-nums",children:["Last updated ",je(n.updatedAt)," by"," ",n.updatedBy??"unknown"]})]}):e.jsx("p",{className:"text-xs text-zinc-500",children:"No custom prompts saved yet â falls back to house defaults."})]})]}),e.jsx(Lt,{"aria-hidden":!0,className:`size-4 shrink-0 text-zinc-500 transition-transform ${r?"rotate-180":""}`})]}),r?e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:"space-y-5 border-t border-black/5 pt-5",id:`prompts-body-${s}`,children:[a?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loadingâ¦"}):null,e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`voice-card-${s}`,children:"Voice card"}),e.jsx(te,{"aria-describedby":`voice-card-help-${s}`,className:"min-h-32 font-mono text-xs leading-5",id:`voice-card-${s}`,name:"voiceCard",onChange:b=>d(g=>({...g,voiceCard:b.target.value})),placeholder:"Identity, sentence patterns, vocabulary, tone markers, example passages.",value:c.voiceCard}),e.jsx("p",{className:"text-xs text-zinc-500",id:`voice-card-help-${s}`,children:"Prepended to the AI system prompt. Treat this as the writer's style guide."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`prompt-template-${s}`,children:"Prompt template"}),e.jsx(te,{className:"min-h-32 font-mono text-xs leading-5",id:`prompt-template-${s}`,name:"promptTemplate",onChange:b=>d(g=>({...g,promptTemplate:b.target.value})),placeholder:"Section structure, CTA placement, tone calibration. Free text.",value:c.promptTemplate})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`subject-principles-${s}`,children:"Subject line principles"}),e.jsx(te,{className:"min-h-24 font-mono text-xs leading-5",id:`subject-principles-${s}`,name:"subjectPrinciples",onChange:b=>d(g=>({...g,subjectPrinciples:b.target.value})),placeholder:"Length, tone, examples for subject suggestions.",value:c.subjectPrinciples})]}),e.jsxs("div",{className:"grid gap-5 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`anti-patterns-${s}`,children:"Anti-patterns"}),e.jsx(te,{className:"min-h-32 font-mono text-xs leading-5",id:`anti-patterns-${s}`,name:"antiPatterns",onChange:b=>d(g=>({...g,antiPatternsRaw:b.target.value})),placeholder:`one phrase per line 83revolutionize 84unlock 85supercharge`,value:c.antiPatternsRaw}),e.jsx("p",{className:"text-xs text-zinc-500",children:"One phrase per line. Confidence check flags drafts containing these."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`cta-keywords-${s}`,children:"CTA keywords"}),e.jsx(te,{className:"min-h-32 font-mono text-xs leading-5",id:`cta-keywords-${s}`,name:"ctaKeywords",onChange:b=>d(g=>({...g,ctaKeywordsRaw:b.target.value})),placeholder:`one keyword per line 86join 87reply 88click`,value:c.ctaKeywordsRaw}),e.jsx("p",{className:"text-xs text-zinc-500",children:"Confidence check looks for at least one of these in the final section."})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{htmlFor:`wc-min-${s}`,children:"Word count min"}),e.jsx(I,{id:`wc-min-${s}`,inputMode:"numeric",max:5e3,min:50,name:"wordCountMin",onChange:b=>d(g=>({...g,wordCountMin:Number(b.target.value)||0})),type:"number",value:c.wordCountMin})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{htmlFor:`wc-max-${s}`,children:"Word count max"}),e.jsx(I,{id:`wc-max-${s}`,inputMode:"numeric",max:5e3,min:50,name:"wordCountMax",onChange:b=>d(g=>({...g,wordCountMax:Number(b.target.value)||0})),type:"number",value:c.wordCountMax})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{htmlFor:`min-conf-${s}`,children:"Minimum confidence to keep AI fill"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(I,{className:"max-w-24",id:`min-conf-${s}`,inputMode:"numeric",max:100,min:0,name:"aiMinConfidence",onChange:b=>d(g=>({...g,aiMinConfidence:Math.max(0,Math.min(100,Number(b.target.value)||0))}
88)),type:"number",value:c.aiMinConfidence}),e.jsx("p",{className:"text-xs text-zinc-500",children:"0â100. Drafts scoring below this are saved empty so you start from a blank page rather than weak copy."})]})]})]}),e.jsxs(us,{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx(T,{disabled:u||!S,onClick:M,type:"button",variant:"ghost",children:"Reset"}),e.jsx(T,{disabled:u||!S,onClick:A,type:"button",children:"Save prompts"})]})]}):null]})}const Rl={aiNews:"",angle:"",marketSignals:"",memberWins:"",mustAvoid:"",mustInclude:"",observations:"",sourceLinksRaw:"",targetSubject:"",theme:""};function El(s){return s.split(` 89`).map(t=>t.trim()).filter(t=>t.length>0)}function ql(s){return s.join(` 90`)}function Ol(s,t){return s.observations===t.observations&&s.marketSignals===t.marketSignals&&s.aiNews===t.aiNews&&s.memberWins===t.memberWins&&s.theme===t.theme&&s.angle===t.angle&&s.mustInclude===t.mustInclude&&s.mustAvoid===t.mustAvoid&&s.targetSubject===t.targetSubject&&s.sourceLinksRaw===t.sourceLinksRaw}function Bl({workflowKey:s}
90){const t=$e(),[n,a]=f.useState(!1),[i,r]=f.useState(()=>At(new Date)),{data:l,isLoading:c}=de({queryFn:()=>Tn({data:{isoWeek:i,workflowKey:s}}),queryKey:["admin","signalBrief",s,i]}),d=l?{aiNews:l.aiNews,angle:l.angle,marketSignals:l.marketSignals,memberWins:l.memberWins,mustAvoid:l.mustAvoid,mustInclude:l.mustInclude,observations:l.observations,sourceLinksRaw:ql(l.sourceLinks),targetSubject:l.targetSubject,theme:l.theme}:Rl,[u,x]=f.useState(d),[m,S]=f.useState(!1),A=f.useRef(d);f.useEffect(()=>{A.current=d,x(d)},[l?.updatedAt,i,l?.id]);const M=!Ol(u,A.current),b=async()=>{S(!0);try{await Cr({data:{aiNews:u.aiNews,angle:u.angle,isoWeek:i,marketSignals:u.marketSignals,memberWins:u.memberWins,mustAvoid:u.mustAvoid,mustInclude:u.mustInclude,observations:u.observations,sourceLinks:El(u.sourceLinksRaw),targetSubject:u.targetSubject,theme:u.theme,workflowKey:s}}),t.invalidateQueries({queryKey:["admin","signalBrief",s,i]}),$.success("Brief saved.")}catch(v){$.error(v instanceof Error?v.message:String(v))}finally{S(!1)}},g=()=>x(A.current),C=v=>{r(w=>dt(w,v))},F=At(new Date),_=(()=>{if(i===F)return"this week";let v=F;for(let w=1;w<=12;w++)if(v=dt(F,w),v===i)return`+${w} week${w===1?"":"s"}`;v=F;for(let w=1;w<=12;w++)if(v=dt(F,-w),v===i)return`-${w} week${w===1?"":"s"}`;return null})();return e.jsxs(ee,{children:[e.jsxs("button",{"aria-controls":`signal-body-${s}`,"aria-expanded":n,className:`flex w-full items-start justify-between gap-3 rounded-t-xl 91 p-6 text-left transition-colors hover:bg-zinc-50 92 focus-visible:bg-zinc-50 focus-visible:outline-none`,onClick:()=>a(v=>!v),type:"button",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{"aria-hidden":!0,className:`mt-0.5 inline-flex size-7 shrink-0 items-center 93 justify-center rounded-md ring-1 ${l?"bg-emerald-50 text-emerald-700 ring-emerald-200/60":"bg-amber-50 text-amber-700 ring-amber-200/60"}`,children:e.jsx(qr,{className:"size-4"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{children:"Signal brief"}),e.jsx(ue,{children:"Weekly observations, market signals, and constraints AI compose uses when drafting."}),l?e.jsxs(e.Fragment,{children:[l.theme.trim().length>0?e.jsxs("p",{className:"line-clamp-1 max-w-prose text-sm text-zinc-700",children:["Theme: ",l.theme]}):null,e.jsxs("p",{className:"text-xs text-zinc-500 tabular-nums",children:[i," · last edited ",je(l.updatedAt)," by"," ",l.updatedBy??"unknown"]})]}):e.jsxs("p",{className:"text-xs text-zinc-500 tabular-nums",children:[i," · no brief saved yet"]})]})]}),e.jsx(Lt,{"aria-hidden":!0,className:`size-4 shrink-0 text-zinc-500 transition-transform ${n?"rotate-180":""}`})]}),n?e.jsxs(e.Fragment,{children:[e.jsxs(ce,{className:"space-y-5 border-t border-black/5 pt-5",id:`signal-body-${s}`,children:[e.jsxs("div",{className:`flex flex-wrap items-center justify-between gap-2 94 rounded-md bg-zinc-50 px-3 py-2`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{"aria-label":"Previous week",onClick:()=>C(-1),size:"icon",type:"button",variant:"ghost",children:e.jsx(oa,{className:"size-4"})}),e.jsx("span",{className:"text-sm font-medium tabular-nums",children:i}),e.jsx(T,{"aria-label":"Next week",onClick:()=>C(1),size:"icon",type:"button",variant:"ghost",children:e.jsx(_r,{className:"size-4"})}),_?e.jsxs("span",{className:"text-xs text-zinc-500",children:["(",_,")"]}):null]}),i!==F?e.jsx(T,{onClick:()=>r(F),size:"sm",type:"button",variant:"ghost",children:"Jump to this week"}):null]}),c?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loadingâ¦"}):null,e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`theme-${s}`,children:"Theme"}),e.jsx(I,{id:`theme-${s}`,name:"theme",onChange:v=>x(w=>({...w,theme:v.target.value})),placeholder:"One-line theme for this issue",value:u.theme})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`angle-${s}`,children:"Angle"}),e.jsx(I,{id:`angle-${s}`,name:"angle",onChange:v=>x(w=>({...w,angle:v.target.value})),placeholder:"The framing or POV",value:u.angle})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`observations-${s}`,children:"Observations"}),e.jsx(te,{className:"min-h-24",id:`observations-${s}`,name:"observations",onChange:v=>x(w=>
94({...w,observations:v.target.value})),placeholder:"What happened this week (community, product, conversations)",value:u.observations})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`market-signals-${s}`,children:"Market signals"}),e.jsx(te,{className:"min-h-24",id:`market-signals-${s}`,name:"marketSignals",onChange:v=>x(w=>({...w,marketSignals:v.target.value})),placeholder:"Trends, competitor moves, investor signals",value:u.marketSignals})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`ai-news-${s}`,children:"AI news"}),e.jsx(te,{className:"min-h-24",id:`ai-news-${s}`,name:"aiNews",onChange:v=>x(w=>({...w,aiNews:v.target.value})),placeholder:"Releases, papers, tools worth flagging",value:u.aiNews})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`member-wins-${s}`,children:"Member wins"}),e.jsx(te,{className:"min-h-20",id:`member-wins-${s}`,name:"memberWins",onChange:v=>x(w=>({...w,memberWins:v.target.value})),placeholder:"Wins, milestones, or stories from members",value:u.memberWins})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`must-include-${s}`,children:"Must include"}),e.jsx(te,{className:"min-h-20",id:`must-include-${s}`,name:"mustInclude",onChange:v=>x(w=>({...w,mustInclude:v.target.value})),placeholder:"Names, links, callouts that are non-negotiable",value:u.mustInclude})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`must-avoid-${s}`,children:"Must avoid"}),e.jsx(te,{className:"min-h-20",id:`must-avoid-${s}`,name:"mustAvoid",onChange:v=>x(w=>({...w,mustAvoid:v.target.value})),placeholder:"Topics, phrasings, sensitive items to skip",value:u.mustAvoid})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`target-subject-${s}`,children:"Target subject"}),e.jsx(I,{id:`target-subject-${s}`,name:"targetSubject",onChange:v=>x(w=>({...w,targetSubject:v.target.value})),placeholder:"Optional working subject line for this issue",value:u.targetSubject})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:`source-links-${s}`,children:"Source links"}),e.jsx(te,{className:"min-h-20 font-mono text-xs leading-5",id:`source-links-${s}`,name:"sourceLinks",onChange:v=>x(w=>({...w,sourceLinksRaw:v.target.value})),placeholder:`one URL per line 95https://example.com/post`,value:u.sourceLinksRaw}),e.jsx("p",{className:"text-xs text-zinc-500",children:"One URL per line. Available to AI compose as references."})]})]}),e.jsxs(us,{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsx(T,{disabled:m||!M,onClick:g,type:"button",variant:"ghost",children:"Reset"}),e.jsx(T,{disabled:m||!M,onClick:b,type:"button",children:"Save brief"})]})]}):null]})}const Il={enrolled:{label:"Enrolled",tone:"neutral"},email_sent:{label:"Sent",tone:"neutral"},email_processed:{label:"Processed",tone:"neutral"},email_delivered:{label:"Delivered",tone:"good"},email_deferred:{label:"Deferred",tone:"warn"},email_opened:{label:"Opened",tone:"good"},email_clicked:{label:"Clicked",tone:"good"},email_bounced:{label:"Bounced",tone:"danger"},email_dropped:{label:"Dropped",tone:"danger"},email_spam_report:{label:"Spam report",tone:"danger"},email_group_unsubscribe:{label:"Group unsubscribe",tone:"warn"},unsubscribed:{label:"Unsubscribed",tone:"warn"},exited:{label:"Exited",tone:"neutral"},completed:{label:"Completed",tone:"good"},canceled:{label:"Canceled",tone:"neutral"},errored:{label:"Errored",tone:"danger"},test_sent:{label:"Test sent",tone:"neutral"},email_dry_run:{label:"Dry run",tone:"neutral"},reconciled:{label:"Reconciled",tone:"neutral"},missing_i18n_key:{label:"Missing i18n",tone:"warn"},manual_oneoff_sent:{label:"Manual send",tone:"neutral"}},Ql={danger:"bg-rose-50 text-rose-700 ring-rose-200",good:"bg-emerald-50 text-emerald-700 ring-emerald-200",neutral:"bg-zinc-50 text-zinc-700 ring-zinc-200",warn:"bg-amber-50 text-amber-800 ring-amber-200"},Ul={danger:"bg-rose-500",good:"bg-emerald-500",neutral:"bg-zinc-400",warn:"bg-amber-500"};
95function Wl(s){return new Date(s).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}function Hl({enrollmentId:s,onOpenChange:t}){const n=s!==null,a=$e(),{data:i,error:r,isLoading:l}=de({queryKey:["admin","enrollmentTimeline",s],queryFn:()=>s?Pi({data:{enrollmentId:s}}):Promise.resolve(null),enabled:n}),[c,d]=f.useState(null),[u,x]=f.useState(!1),m=async()=>{if(!(!s||!c)){x(!0);try{c==="cancel"?(await br({data:{enrollmentId:s,reason:"manual_cancel"}}),$.success("Enrollment canceled.")):(await yr({data:{enrollmentId:s}}),$.success("Enrollment retried.")),a.invalidateQueries({queryKey:["admin","enrollmentTimeline",s]}),d(null),t(!1)}catch(g){$.error(g instanceof Error?g.message:String(g))}finally{x(!1)}}},S=i?.enrollment.status,A=i?.enrollment.errorClass,M=S==="active"||S==="errored",b=S==="errored"&&A==="transient";return e.jsxs(ba,{onOpenChange:t,open:n,children:[e.jsxs(ya,{className:"flex flex-col gap-0 sm:max-w-2xl",children:[e.jsxs(ja,{className:"gap-2",children:[e.jsx(va,{className:"text-base",children:"Member timeline"}),e.jsx(wa,{className:"text-pretty",children:"Per-message events for this enrollment. Open / click come from tracking pixel + redirect; delivered / bounced / spam come from the SendGrid Event Webhook."})]}),l?e.jsxs("div",{className:"mt-6 space-y-2",children:[e.jsx("div",{className:"h-10 animate-pulse rounded bg-zinc-100"}),e.jsx("div",{className:"h-10 animate-pulse rounded bg-zinc-100"}),e.jsx("div",{className:"h-10 animate-pulse rounded bg-zinc-100"})]}):r?e.jsx("p",{className:"mt-6 text-sm text-rose-600",children:r.message}):i?e.jsxs("div",{className:"mt-6 flex flex-col gap-6",children:[e.jsxs("header",{className:"flex flex-col gap-3 rounded-lg bg-zinc-50 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-zinc-900",children:i.member?.email??"â anonymized member â"}),i.member?.fullName?e.jsx("p",{className:"truncate text-xs text-zinc-500",children:i.member.fullName}):null]}),e.jsx(Y,{variant:"outline",children:i.enrollment.status})]}),e.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-1 text-xs",children:[e.jsx("dt",{className:"text-zinc-500",children:"Workflow"}),e.jsx("dd",{className:"font-mono text-[0.8125rem] text-zinc-700",children:i.enrollment.workflowKey}),e.jsx("dt",{className:"text-zinc-500",children:"Step"}),e.jsx("dd",{className:"text-zinc-700 tabular-nums",children:i.enrollment.currentStepIndex+1}),e.jsx("dt",{className:"text-zinc-500",children:"Enrolled"}),e.jsx("dd",{className:"text-zinc-700",children:je(i.enrollment.enrolledAt)}),e.jsx("dt",{className:"text-zinc-500",children:"Next run"}),e.jsx("dd",{className:"text-zinc-700",children:je(i.enrollment.nextRunAt??null)}),e.jsx("dt",{className:"text-zinc-500",children:"Trigger"}),e.jsx("dd",{className:"text-zinc-700",children:i.enrollment.triggeredBy}),e.jsx("dt",{className:"text-zinc-500",children:"Attempts"}),e.jsx("dd",{className:"text-zinc-700 tabular-nums",children:i.enrollment.stepAttempts})]}),i.enrollment.errorMessage?e.jsx("p",{className:`rounded bg-rose-50 p-2 text-xs text-rose-700 ring-1 96 ring-rose-200`,children:i.enrollment.errorMessage}):null,M||b?e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[b?e.jsx(T,{disabled:u,onClick:()=>d("retry"),size:"sm",variant:"outline",children:"Retry now"}):null,M?e.jsx(T,{disabled:u,onClick:()=>d("cancel"),size:"sm",variant:"outline",children:"Cancel enrollment"}):null]}):null]}),i.events.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No events yet."}):e.jsxs("ol",{className:"relative flex flex-col gap-3 pl-5",role:"list",children:[e.jsx("span",{"aria-hidden":"true",className:`absolute top-2 bottom-2 left-[5px] w-px 97 bg-black/10`}),i.events.map(g=>{const C=Il[g.eventType]??{label:g.eventType,tone:"neutral"};return e.jsxs("li",{className:"relative flex items-start gap-3 text-sm",children:[e.jsx("span",{"aria-hidden":"true",className:`absolute top-1.5 -left-5 size-2.5 98 rounded-full ring-2 ring-white 99 ${Ul[C.tone]}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:`flex flex-wrap items-baseline gap-x-2 100 gap-y-0.5`,children:[e.jsx("span",{className:`rounded px-1.5 py-0.5 text-xs 101 font-medium ring-1 ring-inset 102 ${Ql[C.tone]}`,children:C.label}),g.stepKey?e.jsx("code",{className:"font-mono text-xs text-zinc-500",children:g.stepKey}):null]}),e.jsx("p",{className:"mt-0.5 text-xs text-zinc-500 tabular-nums",children:Wl(g.createdAt)})]})]},g._id)})]})]}):null]}),e.jsx(Ve,{onOpenChange:g=>{g||d(null)},open:c!==null,children:e.jsxs(Je,{children:[e.jsxs(Ke,{children:[e.jsx(Ye,{children:c==="cancel"?"Cancel this enrollment?":"Retry this enrollment?"}),e.jsx(Ge,{className:"text-pretty",children:c==="cancel"?"The member stops receiving any further steps in this workflow. Already-sent emails are unaffected. This is reversible only by re-enrolling the member.":"The current step runs again from attempt 0. Retries only w
102ork on transient failures and only when the workflow is not paused."})]}),e.jsxs(Xe,{children:[e.jsx(T,{disabled:u,onClick:()=>d(null),variant:"outline",children:"Back"}),e.jsx(T,{disabled:u,onClick:m,children:c==="cancel"?"Cancel enrollment":"Retry now"})]})]})})]})}const Vl={active:"active",all:void 0,completed:"completed",errored:"errored"},Jl={active:"default",canceled:"secondary",completed:"success",errored:"danger",exited:"secondary",unsubscribed:"secondary"},Kl={active:"Active",canceled:"Canceled",completed:"Completed",errored:"Failed",exited:"Exited",unsubscribed:"Unsubscribed"};function Yl({workflowKey:s}){const[t,n]=f.useState("active"),[a,i]=f.useState(""),[r,l]=f.useState(null),d={status:Vl[t],workflowKey:s},{data:u,fetchNextPage:x,hasNextPage:m,isFetching:S,isLoading:A}=vn({queryKey:["admin","enrollments",d],initialPageParam:null,queryFn:({pageParam:g})=>Ri({data:{...d,limit:50,cursor:g??void 0}}),getNextPageParam:g=>g.isDone?void 0:g.continueCursor}),M=f.useMemo(()=>(u?.pages??[]).flatMap(g=>g.page),[u]),b=a.trim()?M.filter(g=>g.email?.toLowerCase().includes(a.trim().toLowerCase())):M;return e.jsxs(ee,{children:[e.jsx(ge,{children:e.jsx(oe,{children:"Members in this workflow"})}),e.jsx(ce,{children:e.jsxs(hs,{onValueChange:g=>n(g),value:t,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs(ms,{children:[e.jsx(xe,{value:"active",children:"Active"}),e.jsx(xe,{value:"completed",children:"Completed"}),e.jsx(xe,{value:"errored",children:"Failed"}),e.jsx(xe,{value:"all",children:"All"})]}),e.jsx(I,{className:"max-w-xs",onChange:g=>i(g.target.value),placeholder:"Filter by emailâ¦",value:a})]}),e.jsxs(Fe,{value:t,children:[A&&M.length===0?e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx("div",{className:"h-9 animate-pulse rounded bg-zinc-100"}),e.jsx("div",{className:"h-9 animate-pulse rounded bg-zinc-100"}),e.jsx("div",{className:"h-9 animate-pulse rounded bg-zinc-100"})]}):b.length===0?e.jsx("p",{className:"py-10 text-center text-sm text-zinc-500",children:a.trim()?"No members match this filter.":t==="active"?"No active members in this workflow.":t==="completed"?"No one has finished this workflow yet.":t==="errored"?"No failures.":"No members in this workflow yet."}):e.jsxs(jn,{children:[e.jsx(fs,{children:e.jsxs(Le,{children:[e.jsx(K,{children:"Member"}),e.jsx(K,{children:"Status"}),e.jsx(K,{children:"Step"}),e.jsx(K,{className:"hidden md:table-cell",children:"Next run"}),e.jsx(K,{className:"hidden md:table-cell",children:"Last update"}),e.jsx(K,{className:"hidden md:table-cell",children:"Attempts"}),t==="errored"?e.jsx(K,{children:"Reason"}):null]})}),e.jsx(ps,{children:b.map(g=>e.jsxs(Le,{className:"cursor-pointer hover:bg-zinc-50",onClick:()=>l(g._id),children:[e.jsx(Q,{children:e.jsx("span",{className:"block max-w-[28ch] truncate text-sm",title:g.email??"",children:g.email??"â"})}),e.jsx(Q,{children:e.jsx(Y,{variant:Jl[g.status],children:Kl[g.status]})}),e.jsxs(Q,{className:"text-sm text-zinc-600 tabular-nums",children:["Step ",g.currentStepIndex+1]}),e.jsx(Q,{className:"hidden text-sm text-zinc-600 md:table-cell",children:je(g.nextRunAt??null)}),e.jsx(Q,{className:"hidden text-sm text-zinc-600 md:table-cell",children:je(g.lastEventAt)}),e.jsx(Q,{className:`hidden text-sm text-zinc-600 tabular-nums 103 md:table-cell`,children:g.stepAttempts}),t==="errored"?e.jsx(Q,{className:`max-w-[28ch] truncate text-sm 104 text-rose-600`,title:g.errorMessage??"",children:g.errorMessage??"â"}):null]},g._id))})]}),m?e.jsx("div",{className:"mt-4 flex justify-center",children:e.jsx(T,{disabled:S,onClick:()=>x(),variant:"outline",children:"Load more"})}):null]})]})}),e.jsx(Hl,{enrollmentId:r,onOpenChange:g=>{g||l(null)}})]})}function Gl({steps:s,workflowKey:t}){const{data:n}=de({queryKey:["admin","overrides",t],queryFn:()=>Na({data:{workflowKey:t}})}),{data:a}=de({queryKey:["admin","workflowAnalytics",t,"30d"],queryFn:()=>xn({data:{workflowKey:t,window:"30d"}})}),i=f.useMemo(()=>new Map((n??[]).map(u=>[u.stepKey,{updatedAt:typeof u.updatedAt=="number"?u.updatedAt:new Date(u.updatedAt).getTime(),updatedBy:u.updatedBy}])),[n]),r=f.useMemo(()=>{const u=new Map;for(const x of a?.byStep??[])u.set(x.stepKey,{sent:x.sent,delivered:x.delivered,opened:x.opened,clicked:x.clicked,bounced:x.bounced});return u},[a]),[l,c]=f.useState(null),d=s.filter(u=>u.kind==="send_email").length;return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(oe,{children:"Steps"}),e.jsxs(ue,{children:[d," email",d===1?"":"s",", walked through in order. Click Edit copy on a send step to override the default."]})]}),e.jsx(ce,{className:"px-0",children:e.jsx("ol",{className:"divide-y divide-black/5 border-t border-black/5",role:"list",children:s.map(u=>{if(u.kind==="wait")return e.jsx(eo,{onEdit:()=>c(u),step:u},u.index);if(u.kind==="exit_if")return e.jsx(so,{step:u},u.index);const x=u.key?i.get(u.key):void 0,m=u.key?r.get(u.key):void 0;return e.jsx(Xl,{override:x,stats:m,step:u,workflowKey:t},u.index)})})}),l?e.jsx(to,{onOpenChange:u=>{u||c(null)},step:l,workflowKey:t}):null]})}function Xl({override:s,stats:t,step:n,workflowKey:a}){return e.jsxs("li",{className:"flex items-start gap-3 px-6 py-4",children:[e.jsx("span",{className:`mt-0.5 size-7 shrink-0 rounded-full bg-zinc-900 text-center 105 text-xs leading-7 font-medium text-white tabular-nums`,children:n.index}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-zinc-900",children:"Send email"}),n.key?e.jsx("code",{className:`rounded bg-zinc-100 px-1.5 py-0.5 font-mono 106 text-[0.8125rem] text-zinc-700`,children:n.key}):null,n.isPlaceholder?e.jsx(Y,{variant:"secondary",children:"Stub"}):null,s?e.jsx(Y,{variant:"outline",children:"Custom copy"}):null]}),e.jsx("p",{className:"mt-1 text-sm text-pretty text-zinc-600",children:n.description}),t&&t.sent>0?e.jsx(Zl,{stats:t}):null,s?e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:["Edited ",je(s.updatedAt)," by ",s.updatedBy]}):null,n.key?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(no,{stepKey:n.key,workflowKey:a}),e.jsx(Ae,{className:`inline-flex h-9 items-center justify-center rounded-md 107 bg-zinc-900 px-3 text-sm font-medium tracking-[-0.01em] 108 text-white transition-colors hover:bg-zinc-800`,params:{key:a,stepKey:n.key},to:"/admin/workflows/$key/steps/$stepKey/edit",children:"Edit copy"})]}):null]})]})}function Zl({stats:s}){const t=s.sent>0?s.opened/s.sent:0,n=s.sent>0?s.clicked/s.sent:0,a=s.sent>0?s.bounced/s.sent:0;return e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs",children:[e.jsxs("span",{className:"text-zinc-700 tabular-nums",children:[s.sent.toLocaleStr
108ing()," sent"]}),e.jsx("span",{className:"text-zinc-500",children:"·"}),e.jsxs("span",{className:"text-zinc-700 tabular-nums",children:[s.opened.toLocaleString()," opened",e.jsx("span",{className:"ml-1 text-zinc-500",children:fe(t)})]}),e.jsx("span",{className:"text-zinc-500",children:"·"}),e.jsxs("span",{className:"text-zinc-700 tabular-nums",children:[s.clicked.toLocaleString()," clicked",e.jsx("span",{className:"ml-1 text-zinc-500",children:fe(n)})]}),s.bounced>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-zinc-500",children:"·"}),e.jsxs("span",{className:`tabular-nums ${a>.02?"text-rose-700":"text-zinc-700"}`,children:[s.bounced.toLocaleString()," bounced"]})]}):null]})}function eo({onEdit:s,step:t}){const n=!!t.key,a=t.delayMs??0,i=t.defaultDelayMs??a;return e.jsxs("li",{className:"flex items-center gap-3 px-6 py-2.5 text-zinc-500",children:[e.jsx("span",{"aria-hidden":"true",className:`flex size-7 shrink-0 items-center justify-center 109 text-zinc-400`,children:e.jsx(Xi,{className:"size-4"})}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2 text-sm",children:[e.jsx(Lr,{"aria-hidden":"true",className:"size-4 h-lh shrink-0 text-zinc-400"}),e.jsxs("span",{children:["Wait ",Be(a)]}),t.overridden?e.jsxs(Y,{variant:"outline",children:["Custom · default ",Be(i)]}):null]}),n?e.jsx(T,{onClick:s,size:"sm",variant:"outline",children:"Edit delay"}):null]})}const ts=3600*1e3,cn=2160*60*60*1e3;function dn(s){return s%864e5===0?"days":s%36e5===0?"hours":"minutes"}function kt(s){return s==="days"?864e5:s==="hours"?36e5:6e4}function to({onOpenChange:s,step:t,workflowKey:n}){const a=$e(),i=t.key??"",r=t.delayMs??t.defaultDelayMs??ts,[l,c]=f.useState(dn(r)),[d,u]=f.useState(String(r/kt(dn(r)))),x=Number(d),m=Number.isFinite(x)&&x>0,S=m?Math.round(x*kt(l)):0,A=m&&S<ts,M=m&&S>cn,b=()=>a.invalidateQueries({queryKey:["admin","workflowDetail"]}),g=Es({mutationFn:()=>Ar({data:{workflowKey:n,waitKey:i,delayMs:S}}),onSuccess:()=>{$.success(`Delay set to ${Be(S)}.`),b(),s(!1)},onError:L=>$.error(L instanceof Error?L.message:String(L))}),C=Es({mutationFn:()=>zr({data:{workflowKey:n,waitKey:i}}),onSuccess:()=>{$.success("Reset to default."),b(),s(!1)},onError:L=>$.error(L instanceof Error?L.message:String(L))}),F=L=>{if(L==="minutes"||L==="hours"||L==="days"){const p=Number.isFinite(x)&&x>0?Math.round(x*kt(l)):0;if(c(L),p>0){const j=p/kt(L);u(String(Number.isInteger(j)?j:j.toFixed(2)))}}},_=g.isPending||C.isPending,v=m&&!A&&!M&&!_,w=m?A?`Minimum is ${Be(ts)}.`:M?`Maximum is ${Be(cn)}.`:null:"Enter a positive number.";return e.jsx(Ve,{onOpenChange:s,open:!0,children:e.jsxs(Je,{children:[e.jsxs(Ke,{children:[e.jsx(Ye,{children:"Edit wait delay"}),e.jsx(Ge,{children:"Applies to enrollments not yet entered into this wait. Already scheduled sleeps are not retroactively shortened."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md bg-zinc-50 p-3 text-sm text-zinc-700",children:[e.jsx("span",{className:"font-medium",children:i}),e.jsxs("span",{className:"ml-2 text-zinc-500",children:["· default ",Be(t.defaultDelayMs??0)]})]}),e.jsxs("div",{className:"grid grid-cols-[1fr_8rem] gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{htmlFor:"wait-amount",children:"Delay"}),e.jsx(I,{id:"wait-amount",inputMode:"numeric",onChange:L=>u(L.target.value),value:d})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{children:"Unit"}),e.jsxs(ie,{onValueChange:F,value:l,children:[e.jsx(ae,{children:e.jsx(re,{})}),e.jsxs(le,{children:[e.jsx(V,{value:"minutes",children:"minutes"}),e.jsx(V,{value:"hours",children:"hours"}),e.jsx(V,{value:"days",children:"days"})]})]})]})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:w??`Effective delay: ${Be(S)}.`})]}),e.jsxs(Xe,{className:"justify-between sm:justify-between",children:[e.jsx(T,{disabled:_||!t.overridden,onClick:()=>C.mutate(),variant:"outline",children:"Reset to default"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{disabled:_,onClick:()=>s(!1),variant:"outline",children:"Cancel"}),e.jsx(T,{disabled:!v,onClick:()=>g.mutate(),children:"Save"})]})]})]})})}function so({step:s}){return e.jsxs("li",{className:"flex items-start gap-3 px-6 py-3",children:[e.jsx("span",{"aria-hidden":"true",className:`mt-0.5 flex size-7 shrink-0 items-center justify-center 110 text-amber-600`,children:e.jsx(Rr,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-zinc-900",children:"Exit condition"})}),e.jsx("p",{className:"mt-0.5 text-sm text-pretty text-zinc-600",children:s.description})]})]})}function no({stepKey:s,workflowKey:t}){const[n,a]=f.useState(!1);return e.jsx(T,{disabled:n,onClick:async()=>{a(!0);try{await ca({data:{workflowKey:t,stepKey:s,locale:"en"}}),$.success(`Preview "${s}" sent.`)}catch(i){$.error(i instanceof Error?i.message:String(i))}finally{a(!1)}},size:"sm",variant:"outline",children:"Send preview to me"})}const io=8;function ao(s,t){const n=[];n.push(dt(s,-1)),n.push(s);for(let a=1;a<=t;a++)n.push(dt(s,a));return n}
110function ro({workflowKey:s}){const t=$e(),[n,a]=f.useState(!1),[i,r]=f.useState(io),[l,c]=f.useState(null),{data:d,isLoading:u}=de({queryFn:()=>kr({data:{weeksAhead:i+2,workflowKey:s}}),queryKey:["admin","themeCalendar",s,i]}),x=f.useMemo(()=>At(new Date),[]),m=f.useMemo(()=>ao(x,i),[x,i]),S=f.useMemo(()=>{const p=new Map;for(const j of d?.entries??[])p.set(j.isoWeek,{angle:j.angle,notes:j.notes,theme:j.theme});return m.map(j=>{const y=p.get(j)??{angle:"",notes:"",theme:""};return{angle:y.angle,baselineAngle:y.angle,baselineNotes:y.notes,baselineTheme:y.theme,isoWeek:j,notes:y.notes,theme:y.theme}})},[d,m]),[A,M]=f.useState(S),b=f.useRef(S.map(p=>p.isoWeek).join(","));f.useEffect(()=>{M(S),b.current=S.map(p=>p.isoWeek).join(",")},[S]);const g=p=>p.theme!==p.baselineTheme||p.angle!==p.baselineAngle||p.notes!==p.baselineNotes,C=async p=>{const j=A.find(y=>y.isoWeek===p);if(j){c(p);try{await Tr({data:{angle:j.angle,isoWeek:p,notes:j.notes,theme:j.theme,workflowKey:s}}),t.invalidateQueries({queryKey:["admin","themeCalendar",s]}),$.success(`${p} saved.`)}catch(y){$.error(y instanceof Error?y.message:String(y))}finally{c(null)}}},F=(p,j,y)=>{M(R=>R.map(J=>J.isoWeek===p?{...J,[j]:y}:J))},_=d?.entries.length??0,v=(d?.entries??[]).filter(p=>p.isoWeek>=x&&p.theme.trim().length>0).sort((p,j)=>p.isoWeek.localeCompare(j.isoWeek)),w=v.at(0),L=v.length>0;return e.jsxs(ee,{children:[e.jsxs("button",{"aria-controls":`theme-cal-body-${s}`,"aria-expanded":n,className:`flex w-full items-start justify-between gap-3 rounded-t-xl 111 p-6 text-left transition-colors hover:bg-zinc-50 112 focus-visible:bg-zinc-50 focus-visible:outline-none`,onClick:()=>a(p=>!p),type:"button",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{"aria-hidden":!0,className:`mt-0.5 inline-flex size-7 shrink-0 items-center 113 justify-center rounded-md ring-1 ${L?"bg-emerald-50 text-emerald-700 ring-emerald-200/60":"bg-amber-50 text-amber-700 ring-amber-200/60"}`,children:e.jsx(Dr,{className:"size-4"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{children:"Theme calendar"}),e.jsx(ue,{children:"Plan upcoming issues. Themes feed AI compose as fallback when the full brief is missing."}),w?e.jsxs("p",{className:"line-clamp-1 max-w-prose text-sm text-zinc-700",children:["Next: ",w.isoWeek," â ",w.theme]}):null,e.jsxs("p",{className:"text-xs text-zinc-500 tabular-nums",children:[_," planned · current week ",x]})]})]}),e.jsx(Lt,{"aria-hidden":!0,className:`size-4 shrink-0 text-zinc-500 transition-transform ${n?"rotate-180":""}`})]}),n?e.jsxs(ce,{className:"space-y-3 border-t border-black/5 pt-5",id:`theme-cal-body-${s}`,children:[u?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loadingâ¦"}):null,e.jsx("ul",{className:"divide-y divide-black/5",role:"list",children:A.map(p=>{const j=g(p),y=p.isoWeek===x,R=p.isoWeek<x;return e.jsxs("li",{className:"space-y-3 py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:`text-sm font-medium tabular-nums ${y?"text-emerald-700":R?"text-zinc-400":"text-zinc-900"}`,children:p.isoWeek}),y?e.jsx("span",{className:`rounded-full bg-emerald-50 px-2 py-0.5 114 text-xs font-medium text-emerald-700 ring-1 115 ring-emerald-200/60`,children:"this week"}):null,R?e.jsx("span",{className:"text-xs text-zinc-400",children:"past"}):null]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs text-zinc-500",htmlFor:`tc-theme-${s}-${p.isoWeek}`,children:"Theme"}),e.jsx(I,{id:`tc-theme-${s}-${p.isoWeek}`,name:"theme",onChange:J=>F(p.isoWeek,"theme",J.target.value),placeholder:"Theme",value:p.theme})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs text-zinc-500",htmlFor:`tc-angle-${s}-${p.isoWeek}`,children:"Angle"}),e.jsx(I,{id:`tc-angle-${s}-${p.isoWeek}`,name:"angle",onChange:J=>F(p.isoWeek,"angle",J.target.value),placeholder:"Angle",value:p.angle})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs text-zinc-500",htmlFor:`tc-notes-${s}-${p.isoWeek}`,children:"Notes"}),e.jsx(te,{className:"min-h-16",id:`tc-notes-${s}-${p.isoWeek}`,name:"notes",onChange:J=>F(p.isoWeek,"notes",J.target.value),placeholder:"Optional planning notes",value:p.notes})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(T,{disabled:!j||l===p.isoWeek,onClick:()=>C(p.isoWeek),size:"sm",type:"button",variant:j?"default":"outline",children:l===p.isoWeek?"Savingâ¦":"Save"})})]},p.isoWeek)})}),e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(T,{onClick:()=>r(p=>p+4),size:"sm",type:"button",variant:"ghost",children:"Show 4 more weeks"})})]}):null]})}const lo=["overview","brief","send","analytics","settings"];function oo(s){return typeof s=="string"&&lo.some(t=>t===s)}function Ko(){const{key:s}=Ht.useParams(),t=Ht.useSearch(),n=Ht.useNavigate(),a=t.window??"30d",i=t.tab??"overview",r=f.useMemo(()=>At(new Date),[]),{data:l,isLoading:c}=de({queryKey:["admin","workflowDetail",s],queryFn:()=>Ei({data:{workflowKey:s}})}),d=l?.kind==="broadcast",{data:u}=de({enabled:d,queryFn:()=>Tn({data:{isoWeek:r,workflowKey:s}}),queryKey:["admin","signalBrief",s,r]}),[x,m]=f.useState(!1),[S,A]=f.useState(!1);if(c)return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"h-3 w-24 animate-pulse rounded bg-zinc-100"}),e.jsx("div",{className:"h-7 w-64 animate-pulse rounded bg-zinc-100"}),e.jsx("div",{className:"h-4 w-96 max-w-full animate-pulse rounded bg-zinc-100"})]}),e.jsx("div",{className:"h-9 w-72 animate-pulse rounded-md bg-zinc-100"}),e.jsx("div",{className:"h-32 animate-pulse rounded-xl bg-zinc-100"})]});if(!l)return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ae,{className:`inline-flex items-center gap-1 text-sm text-zinc-500 116 hover:text-zinc-900`,to:"/admin/workflows",children:"â Workflows"}),e.jsxs(ee,{className:"p-10 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-900",children:"Workflow not found"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-500",children:"This workflow doesn't exist or has been removed."})]})]});const M=async()=>
116{if(l.config){A(!0);try{l.config.paused?(await vr({data:{workflowKey:s}}),$.success("Resumed.")):(await jr({data:{workflowKey:s,reason:"manual_pause"}}),$.success("Paused.")),m(!1)}catch(C){$.error(C instanceof Error?C.message:String(C))}finally{A(!1)}}},b=C=>n({search:F=>({...F,tab:C==="overview"?void 0:C}),replace:!0}),g=l.kind==="sequence"?l.steps.flatMap(C=>C.kind==="send_email"&&C.key?[{key:C.key,description:C.description,isPlaceholder:C.isPlaceholder}]:[]):[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("header",{className:"space-y-2",children:[e.jsx(Ae,{className:`inline-flex items-center gap-1 text-sm text-zinc-500 117 hover:text-zinc-900`,to:"/admin/workflows",children:"â Workflows"}),e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-semibold tracking-tight",children:l.displayName}),l.config?.paused?e.jsx(Y,{variant:"warning",children:"Paused"}):null]}),e.jsx("p",{className:"mt-1 max-w-prose text-sm text-pretty text-zinc-600",children:l.description})]}),e.jsx(T,{onClick:()=>m(!0),variant:"outline",children:l.config?.paused?"Resume":"Pause"})]}),d&&l.config?e.jsx(go,{aiFill:l.config.autoDraftAiFill,autoDraftEnabled:l.config.autoDraftEnabled,briefFilled:u!=null,cadenceText:xo(l.config),currentWeek:r,onJumpToBrief:()=>b("brief"),onJumpToSettings:()=>b("settings")}):null,l.config?.paused?e.jsx(po,{}):null]}),e.jsx(Ve,{onOpenChange:m,open:x,children:e.jsxs(Je,{children:[e.jsxs(Ke,{children:[e.jsx(Ye,{children:l.config?.paused?"Resume this workflow?":"Pause this workflow?"}),e.jsx(Ge,{className:"text-pretty",children:l.config?.paused?"Scheduled steps will resume from where they left off. Members already in the workflow keep moving through it.":"No new steps will fire while paused. Active enrollments stay where they are; you can resume any time."})]}),e.jsxs(Xe,{children:[e.jsx(T,{disabled:S,onClick:()=>m(!1),variant:"outline",children:"Cancel"}),e.jsx(T,{disabled:S,onClick:M,children:l.config?.paused?"Resume":"Pause"})]})]})}),e.jsxs(hs,{onValueChange:C=>{oo(C)&&b(C)},value:i,children:[e.jsxs(ms,{children:[e.jsx(xe,{value:"overview",children:"Overview"}),d?e.jsx(xe,{value:"brief",children:"Plan"}):null,e.jsx(xe,{value:"send",children:"Send"}),e.jsx(xe,{value:"analytics",children:"Analytics"}),e.jsx(xe,{value:"settings",children:"Settings"})]}),e.jsxs(Fe,{className:"space-y-6",value:"overview",children:[l.kind==="broadcast"?e.jsx(bo,{briefFilled:u!=null,workflowKey:s,onJumpToAnalytics:()=>b("analytics"),onJumpToPlan:()=>b("brief"),onJumpToSend:()=>b("send")}):null,e.jsx(jo,{audience:l.audienceDescription,from:l.config?.fromAddress??l.defaultFromAddress,replyTo:l.config?.replyTo??l.defaultReplyTo,schedule:l.schedule,trigger:l.trigger}),l.kind==="sequence"?e.jsx(Gl,{steps:l.steps,workflowKey:s}):null,l.kind==="broadcast"?e.jsx(Al,{workflowKey:s}):null]}),e.jsxs(Fe,{className:"space-y-6",value:"send",children:[l.kind==="sequence"?e.jsx(_l,{kind:"sequence",steps:g,workflowKey:s}):e.jsx(ul,{paused:l.config?.paused??!1,workflowKey:s}),e.jsx(zl,{enabled:l.config?.autoTriggerEnabled??!1,workflowKey:s})]}),e.jsxs(Fe,{className:"space-y-6",value:"analytics",children:[e.jsx(Ur,{onWindowChange:C=>n({search:F=>({...F,window:C}),replace:!0}),window:a,workflowKey:s}),l.kind==="sequence"?e.jsx(Yl,{workflowKey:s}):null]}),d?e.jsxs(Fe,{className:"space-y-6",value:"brief",children:[e.jsx(yo,{onJumpToSend:()=>b("send")}),e.jsx(Bl,{workflowKey:s}),e.jsx(ro,{workflowKey:s})]}):null,e.jsx(Fe,{className:"space-y-6",value:"settings",children:l.config?e.jsxs(e.Fragment,{children:[e.jsx(yl,{config:l.config,workflowKey:s}),e.jsx(Pl,{workflowKey:s})]}):e.jsxs(ee,{className:"p-10 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-900",children:"Settings unavailable"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-500",children:"Config row hasn't been bootstrapped yet. Try again in a minute."})]})})]})]})}const co=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],uo={FRI:"Friday",MON:"Monday",SAT:"Saturday",SUN:"Sunday",THU:"Thursday",TUE:"Tuesday",WED:"Wednesday"};function ho(s,t){const n=s>=12?"PM":"AM",a=s%12===0?12:s%12;return t===0?`${a} ${n}`:`${a}
117:${String(t).padStart(2,"0")} ${n}`}function mo(s){if(!s)return null;const t=s.trim().split(/\s+/);if(t.length!==5)return null;const[n,a,i,r,l]=t;if(i!=="*"||r!=="*")return null;const c=Number(n),d=Number(a);if(!Number.isInteger(c)||c<0||c>59||!Number.isInteger(d)||d<0||d>23)return null;const u=uo[l.toUpperCase()];return u?`Every ${u} at ${ho(d,c)} UTC`:null}function fo(s,t){const n=mo(t);return n||(t?`${s} (${t})`:s)}function po(){return e.jsxs("div",{className:"rounded-lg bg-amber-50 p-4 ring-1 ring-amber-200/70",role:"status",children:[e.jsx("p",{className:"font-medium text-amber-950",children:"Workflow paused."}),e.jsx("p",{className:"text-base text-pretty text-amber-900 sm:text-sm",children:"Scheduled automation and real selected-member sends are locked until the workflow is resumed. Safe test emails still work."})]})}function xo(s){if(!s.autoDraftEnabled||s.autoDraftDow==null||s.autoDraftHourUtc==null||s.autoDraftMinuteUtc==null)return null;const t=js({dow:s.autoDraftDow,hour:s.autoDraftHourUtc,minute:s.autoDraftMinuteUtc}),n=co[t.dow],a=`${String(t.hour).padStart(2,"0")}:${String(t.minute).padStart(2,"0")}`;return`${n} ${a} IST`}function go({aiFill:s,autoDraftEnabled:t,briefFilled:n,cadenceText:a,currentWeek:i,onJumpToBrief:r,onJumpToSettings:l}){return e.jsxs("div",{className:`flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg 118 bg-zinc-50 px-3 py-2 text-sm text-zinc-700 ring-1 ring-black/5`,children:[e.jsxs("button",{className:`inline-flex items-center gap-1.5 rounded text-left 119 transition-colors hover:text-zinc-900 focus-visible:text-zinc-900 120 focus-visible:outline-2 focus-visible:outline-offset-2 121 focus-visible:outline-violet-500`,onClick:l,type:"button",children:[e.jsx("span",{"aria-hidden":!0,className:`inline-block size-1.5 shrink-0 rounded-full ${t&&a?"bg-emerald-500":"bg-zinc-300"}`}),e.jsx("span",{className:"tabular-nums",children:t&&a?`Auto-draft ${a}`:"Auto-draft off"})]}),t?e.jsxs("span",{className:"text-zinc-500",children:["· AI fill ",s?"on":"off"]}):null,e.jsx("span",{"aria-hidden":!0,className:"text-zinc-300",children:"·"}),e.jsxs("button",{className:`inline-flex items-center gap-1.5 rounded text-left 122 transition-colors hover:text-zinc-900 focus-visible:text-zinc-900 123 focus-visible:outline-2 focus-visible:outline-offset-2 124 focus-visible:outline-violet-500`,onClick:r,type:"button",children:[e.jsx("span",{"aria-hidden":!0,className:`inline-block size-1.5 shrink-0 rounded-full ${n?"bg-emerald-500":"bg-amber-500"}`}),e.jsxs("span",{className:"tabular-nums",children:["Plan ",i,": ",n?"brief filled":"brief empty"]})]})]})}function bo({briefFilled:s,onJumpToAnalytics:t,onJumpToPlan:n,onJumpToSend:a,workflowKey:i}){return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(oe,{children:"Newsletter flow"}),e.jsx(ue,{children:"Follow this path when preparing an issue. Planning shapes drafts, sending happens only from Compose or Send."})]}),e.jsx(ce,{children:e.jsxs("ol",{className:"grid gap-3 md:grid-cols-5",role:"list","aria-label":"Newsletter workflow steps",children:[e.jsxs("li",{className:`grid min-w-0 grid-rows-[auto_1fr_auto] gap-3 rounded-lg 125 bg-zinc-50 p-3 ring-1 ring-black/5`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`flex size-6 shrink-0 items-center justify-center 126 rounded-full bg-zinc-900 text-[0.8125rem] font-medium 127 text-white tabular-nums`,children:"1"}),e.jsx("h2",{className:"min-w-0 truncate text-sm font-medium text-zinc-900",children:"Plan"})]}),e.jsx("p",{className:"text-base text-pretty text-zinc-600 sm:text-sm",children:"Fill the signal brief or theme calendar for this week."}),e.jsxs("div",{className:"flex flex-col items-start gap-3",children:[e.jsx(Y,{variant:s?"success":"warning",children:s?"Brief ready":"Brief empty"}),e.jsx(T,{onClick:n,size:"sm",variant:"outline",children:"Open Plan"})]})]}),e.jsxs("li",{className:`grid min-w-0 grid-rows-[auto_1fr_auto] gap-3 rounded-lg 128 bg-zinc-50 p-3 ring-1 ring-black/5`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`flex size-6 shrink-0 items-center justify-center 129 rounded-full bg-zinc-900 text-[0.8125rem] font-medium 130 text-white tabular-nums`,children:"2"}),e.jsx("h2",{className:"min-w-0 truncate text-sm font-medium text-zinc-900",children:"Compose"})]}),e.jsx("p",{className:"text-base text-pretty text-zinc-600 sm:text-sm",children:"Create the polished issue, preview it, and save a draft."}),e.jsx("div",{className:"flex items-start",children:e.jsx(Ae,{className:`inline-flex h-9 items-center justify-center 131 rounded-md px-3 text-sm font-medium text-zinc-700 ring-1 132 ring-black/10 hover:bg-white focus-visible:outline-2 133 focus-visible:outline-offset-2 134 focus-visible:outline-violet-500`,params:{key:i},to:"/admin/workflows/$key/issues/new",children:"Compose issue"})})]}),e.jsxs("li",{className:`grid min-w-0 grid-rows-[auto_1fr_auto] gap-3 rounded-lg 135 bg-zinc-50 p-3 ring-1 ring-black/5`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`flex size-6 shrink-0 items-center justify-center 136 rounded-full bg-zinc-900 text-[0.8125rem] font-medium 137 text-white tabular-nums`,children:"3"}),e.jsx("h2",{className:"min-w-0 truncate text-sm font-medium text-zinc-900",children:"Test"})]}),e.jsx("p",{className:"text-base text-pretty text-zinc-600 sm:text-sm",children:"Send one safe [TEST] email to an inbox before recipients see it."}),e.jsx("div",{className:"flex items-start",children:e.jsx(T,{onClick:a,size:"sm",variant:"outline",children:"Open Send"})})]}),e.jsxs("li",{className:`grid min-w-0 grid-rows-[auto_1fr_auto] gap-3 rounded-lg 138 bg-zinc-50 p-3 ring-1 ring-black/5`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`flex size-6 shrink-0 items-center justify-center 139 rounded-full bg-zinc-900 text-[0.8125rem] font-medium 140 text-white tabular-nums`,children:"4"}),e.jsx("h2",{className:"min-w-0 truncate text-sm font-medium text-zinc-900",children:"Send"})]}),e.jsx("p",{className:"text-base text-pretty text-zinc-600 sm:text-sm",children:"Send to
140selected members, with suppression and recipient tracking."}),e.jsx("div",{className:"flex items-start",children:e.jsx(T,{onClick:a,size:"sm",variant:"outline",children:"Select members"})})]}),e.jsxs("li",{className:`grid min-w-0 grid-rows-[auto_1fr_auto] gap-3 rounded-lg 141 bg-zinc-50 p-3 ring-1 ring-black/5`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`flex size-6 shrink-0 items-center justify-center 142 rounded-full bg-zinc-900 text-[0.8125rem] font-medium 143 text-white tabular-nums`,children:"5"}),e.jsx("h2",{className:"min-w-0 truncate text-sm font-medium text-zinc-900",children:"Analyze"})]}),e.jsx("p",{className:"text-base text-pretty text-zinc-600 sm:text-sm",children:"Check sent, failed, opens, clicks, and recipient status rows."}),e.jsx("div",{className:"flex items-start",children:e.jsx(T,{onClick:t,size:"sm",variant:"outline",children:"View analytics"})})]})]})})]})}function yo({onJumpToSend:s}){return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(oe,{children:"Planning inputs"}),e.jsx(ue,{children:"These guide newsletter drafts. They do not send emails."})]}),e.jsx(ce,{children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"min-w-0 rounded-lg bg-zinc-50 p-3 ring-1 ring-black/5",children:[e.jsx("h2",{className:"text-sm font-medium text-zinc-900",children:"Signal brief"}),e.jsx("p",{className:"mt-1 text-sm text-pretty text-zinc-600",children:"The strongest input for this week: observations, market signals, AI news, member wins, sources, and must-include constraints."})]}),e.jsxs("div",{className:"min-w-0 rounded-lg bg-zinc-50 p-3 ring-1 ring-black/5",children:[e.jsx("h2",{className:"text-sm font-medium text-zinc-900",children:"Theme calendar"}),e.jsx("p",{className:"mt-1 text-sm text-pretty text-zinc-600",children:"A lightweight forward plan. AI compose uses its theme and angle when the weekly signal brief is missing or thin."})]}),e.jsxs("div",{className:"min-w-0 rounded-lg bg-zinc-50 p-3 ring-1 ring-black/5",children:[e.jsx("h2",{className:"text-sm font-medium text-zinc-900",children:"Send tab"}),e.jsx("p",{className:"mt-1 text-sm text-pretty text-zinc-600",children:"Where testing and real sends happen. Use Plan to shape the draft, then Send to validate and deliver."}),e.jsx(T,{className:"mt-3",onClick:s,size:"sm",variant:"outline",children:"Go to Send"})]})]})})]})}function jo(s){return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsx(oe,{children:"About"}),e.jsx(ue,{children:s.audience})]}),e.jsx(ce,{children:e.jsxs("dl",{className:"grid grid-cols-1 gap-4 text-sm sm:grid-cols-2",children:[e.jsx(ss,{label:"Trigger",value:fo(s.trigger,s.schedule)}),e.jsx(ss,{label:"From",value:s.from}),e.jsx(ss,{label:"Reply to",value:s.replyTo??"â"})]})})]})}function ss({label:s,value:t}){return e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-zinc-500",children:s}),e.jsx("dd",{className:"mt-0.5 break-words text-zinc-900",children:t})]})}export{Ko as component};
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.