1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/web-vT3BfPdX.js","assets/firebaseHelper-CezmP0DK.js","assets/vendor-firebase-Cr-z2ntb.js","assets/vendor-react-DVKDpznt.js","assets/twilio-Bb-eHOxP.js","assets/SiteAuditScreen-a23zHAuX.js","assets/icon-BAV_X4rZ.js","assets/ChatFeed-CaDe2Y4v.js","assets/x-CmSDVY9Y.js","assets/useTotalCredits-CpQo5HeC.js","assets/api-CHYxDEvj.js","assets/ChatProfileGate-f3bLSFx2.js","assets/ChatProfileGate-oPHmW_XL.css","assets/loader-2-DwVb8-Jf.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-framer-motion-DKtqbc2t.js","assets/vendor-radix-BjZvO4YG.js","assets/vendor-recharts-DQaRMGeR.js","assets/useProjectsByShopifyUrl-Crci73Q0.js","assets/TransferCreditsModal-DmM6DBX6.js","assets/clientStrategy-CAmWPSpT.js","assets/QAReviewScreen-CEEQsBPu.js","assets/core.esm-DgAQa9pm.js","assets/uploader-DBSp2hux.js","assets/index-YQlFN7wH.css","assets/CommunicationsHub-NdOYJU9u.js","assets/GameBoard-BeXbe_9-.js","assets/TranscriptTicketScreen-BQFCOah7.js","assets/MarketingResearchScreen-R0npD1Qz.js"])))=>i.map(i=>d[i]); 2var v0=Object.defineProperty;var w0=(t,s,n)=>s in t?v0(t,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[s]=n;var dm=(t,s,n)=>w0(t,typeof s!="symbol"?s+"":s,n);import"./modulepreload-polyfill-B5Qt9EMX.js";import{r as l,c as ee,b as N0,j as e,a as k0,d as il,g as af,R as S0,e as C0}from"./vendor-react-DVKDpznt.js";import{u as of,s as T0,a as El,C as A0,r as E0}from"./ChatProfileGate-f3bLSFx2.js";import{r as I0,_ as Gs,C as Br,f as lf,a as Il,c as re,b as R0,d as ge,e as Lr,u as cf,g as D0,h as M0,i as P0,s as L0,n as z0,j as O0,m as $0,k as um}from"./firebaseHelper-CezmP0DK.js";import{C as Ns,a as Ot,V as tu,e as B0,b as F0,H as Uo,P as Ut,A as dt,S as An,M as mn,c as Rt,u as pt,d as Pt,f as En,g as gs,h as Ra,i as ws,R as yt,j as _0,k as In,l as ms,m as W0,n as U0,o as H0,p as q0,E as So,t as yo,J as df,q as Hr,r as Tn,s as ll,D as Co,v as uf,w as Da,x as hr,y as mm,z as Dt,B as su,F as Ki,G as V0,I as pm,K as Sd,L as nu,N as xm}from"./ChatFeed-CaDe2Y4v.js";import{P as hm,C as Rl,b as as,T as cl,s as qn}from"./api-CHYxDEvj.js";import{w as Ve,o as Nt,l as Tt,s as qr,d as ut,c as ss,e as Y0,f as Re,q as Ge,g as qt,h as ps,i as Ze,j as G0,u as er,k as Ma,m as ru,T as ja,n as K0,r as Dl,p as mf,t as Q0,v as ys}from"./vendor-firebase-Cr-z2ntb.js";import{u as Ml,m as st,a as J0,A as hs}from"./vendor-framer-motion-DKtqbc2t.js";import{c as be,X as mt}from"./x-CmSDVY9Y.js";import{S as pf,R as Z0,a as X0,I as ej,O as au,b as xf,C as hf,c as ff,T as gf,D as bf,P as yf,d as tj,e as sj,V as nj,f as rj,g as aj,h as oj,i as ij,j as lj,k as cj,l as dj,m as uj,A as mj,n as pj,o as xj,p as hj,q as fj,r as gj,s as bj,t as yj,u as jj,v as vj,w as wj,H as Nj,x as kj,y as Sj,z as Cj,B as Tj,E as Aj,F as Ej,G as Ij,J as Rj,K as Dj,L as Mj,M as Pj,N as Lj,Q as zj,U as Oj,W as $j,X as Bj,Y as Fj,Z as _j,_ as Wj,$ as Uj,a0 as Hj,a1 as qj,a2 as Vj,a3 as Yj,a4 as Gj,a5 as Kj}from"./vendor-radix-BjZvO4YG.js";import{c as jf,R as vf,C as Qj,a as wf,X as Nf,Y as kf,b as Jj,d as fm,L as Zj,T as Sf,A as Xj,e as ev,f as tv}from"./vendor-recharts-DQaRMGeR.js";import{L as fe,C as kt}from"./loader-2-DwVb8-Jf.js";import{s as ks,u as Cf,a as sv,N as gm,b as nv}from"./useProjectsByShopifyUrl-Crci73Q0.js";import{u as Tf,a as Pa,b as rv}from"./useTotalCredits-CpQo5HeC.js";import{s as Vr}from"./icon-BAV_X4rZ.js";import{S as Af,B as av,T as ov,A as Ef,C as If}from"./TransferCreditsModal-DmM6DBX6.js";import{u as iv,m as lv,p as bm,o as cv,b as ym,r as jm,c as dv,f as xc,a as vm,d as hc,e as uv,g as mv}from"./clientStrategy-CAmWPSpT.js";import{Q as Pl,c as va,q as bn,o as wm,a as pv,b as xv,C as hv,d as fv,e as gv,f as Nm}from"./QAReviewScreen-CEEQsBPu.js";import{K as xr,u as bv,a as yv,b as Rf,c as Df,g as jv,d as vv,s as wv,e as ou,f as iu,h as Nv,C as lu,i as kv,j as Sv,k as Ho,l as Rn,D as qo,m as cu,n as Vo,P as Yo,o as Mf}from"./core.esm-DgAQa9pm.js";import{u as Cv,c as Tv}from"./uploader-DBSp2hux.js";/* empty css *//** 3 * react-router v7.9.4 4 * 5 * Copyright (c) Remix Software Inc. 6 * 7 * This source code is licensed under the MIT license found in the 8 * LICENSE.md file in the root directory of this source tree. 9 * 10 * @license MIT 11 */var km="popstate";function Av(t={}){function s(r,a){let{pathname:o,search:i,hash:d}=r.location;return Cd("",{pathname:o,search:i,hash:d},a.state&&a.state.usr||null,a.state&&a.state.key||"default")}
11function n(r,a){return typeof a=="string"?a:To(a)}return Iv(s,n,null,t)}function Qt(t,s){if(t===!1||t===null||typeof t>"u")throw new Error(s)}function pn(t,s){if(!t){typeof console<"u"&&console.warn(s);try{throw new Error(s)}catch{}}}function Ev(){return Math.random().toString(36).substring(2,10)}function Sm(t,s){return{usr:t.state,key:t.key,idx:s}}function Cd(t,s,n=null,r){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof s=="string"?La(s):s,state:n,key:s&&s.key||r||Ev()}}function To({pathname:t="/",search:s="",hash:n=""}){return s&&s!=="?"&&(t+=s.charAt(0)==="?"?s:"?"+s),n&&n!=="#"&&(t+=n.charAt(0)==="#"?n:"#"+n),t}function La(t){let s={};if(t){let n=t.indexOf("#");n>=0&&(s.hash=t.substring(n),t=t.substring(0,n));let r=t.indexOf("?");r>=0&&(s.search=t.substring(r),t=t.substring(0,r)),t&&(s.pathname=t)}return s}function Iv(t,s,n,r={}){let{window:a=document.defaultView,v5Compat:o=!1}=r,i=a.history,d="POP",m=null,p=c();p==null&&(p=0,i.replaceState({...i.state,idx:p},""));function c(){return(i.state||{idx:null}).idx}function u(){d="POP";let g=c(),y=g==null?null:g-p;p=g,m&&m({action:d,location:f.location,delta:y})}function x(g,y){d="PUSH";let j=Cd(f.location,g,y);p=c()+1;let v=Sm(j,p),T=f.createHref(j);try{i.pushState(v,"",T)}catch(k){if(k instanceof DOMException&&k.name==="DataCloneError")throw k;a.location.assign(T)}o&&m&&m({action:d,location:f.location,delta:1})}function h(g,y){d="REPLACE";let j=Cd(f.location,g,y);p=c();let v=Sm(j,p),T=f.createHref(j);i.replaceState(v,"",T),o&&m&&m({action:d,location:f.location,delta:0})}function b(g){return Rv(g)}let f={get action(){return d},get location(){return t(a,i)},listen(g){if(m)throw new Error("A history only accepts one active listener");return a.addEventListener(km,u),m=g,()=>{a.removeEventListener(km,u),m=null}},createHref(g){return s(a,g)},createURL:b,encodeLocation(g){let y=b(g);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:x,replace:h,go(g){return i.go(g)}};return f}function Rv(t,s=!1){let n="http://localhost";
11typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),Qt(n,"No window.location.(origin|href) available to create URL");let r=typeof t=="string"?t:To(t);return r=r.replace(/ $/,"%20"),!s&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function Pf(t,s,n="/"){return Dv(t,s,n,!1)}function Dv(t,s,n,r){let a=typeof s=="string"?La(s):s,o=Xn(a.pathname||"/",n);if(o==null)return null;let i=Lf(t);Mv(i);let d=null;for(let m=0;d==null&&m<i.length;++m){let p=Hv(o);d=Wv(i[m],p,r)}return d}function Lf(t,s=[],n=[],r="",a=!1){let o=(i,d,m=a,p)=>{let c={relativePath:p===void 0?i.path||"":p,caseSensitive:i.caseSensitive===!0,childrenIndex:d,route:i};if(c.relativePath.startsWith("/")){if(!c.relativePath.startsWith(r)&&m)return;Qt(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let u=Jn([r,c.relativePath]),x=n.concat(c);i.children&&i.children.length>0&&(Qt(i.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${u}".`),Lf(i.children,s,x,u,m)),!(i.path==null&&!i.index)&&s.push({path:u,score:Fv(u,i.index),routesMeta:x})};return t.forEach((i,d)=>{var m;if(i.path===""||!((m=i.path)!=null&&m.includes("?")))o(i,d);else for(let p of zf(i.path))o(i,d,!0,p)}),s}function zf(t){let s=t.split("/");if(s.length===0)return[];let[n,...r]=s,a=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return a?[o,""]:[o];let i=zf(r.join("/")),d=[];return d.push(...i.map(m=>m===""?o:[o,m].join("/"))),a&&d.push(...i),d.map(m=>t.startsWith("/")&&m===""?"/":m)}function Mv(t){t.sort((s,n)=>s.score!==n.score?n.score-s.score:_v(s.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var Pv=/^:[\w-]+$/,Lv=3,zv=2,Ov=1,$v=10,Bv=-2,Cm=t=>t==="*";function Fv(t,s){let n=t.split("/"),r=n.length;return n.some(Cm)&&(r+=Bv),s&&(r+=zv),n.filter(a=>!Cm(a)).reduce((a,o)=>a+(Pv.test(o)?Lv:o===""?Ov:$v),r)}function _v(t,s){return t.length===s.length&&t.slice(0,-1).every((r,a)=>r===s[a])?t[t.length-1]-s[s.length-1]:0}function Wv(t,s,n=!1){let{routesMeta:r}=t,a={},o="/",i=[];for(let d=0;d<r.length;++d){let m=r[d],p=d===r.length-1,c=o==="/"?s:s.slice(o.length)||"/",u=dl({path:m.relativePath,caseSensitive:m.caseSensitive,end:p},c),x=m.route;if(!u&&p&&n&&!r[r.length-1].route.index&&(u=dl({path:m.relativePath,caseSensitive:m.caseSensitive,end:!1},c)),!u)return null;
11Object.assign(a,u.params),i.push({params:a,pathname:Jn([o,u.pathname]),pathnameBase:Gv(Jn([o,u.pathnameBase])),route:x}),u.pathnameBase!=="/"&&(o=Jn([o,u.pathnameBase]))}return i}function dl(t,s){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[n,r]=Uv(t.path,t.caseSensitive,t.end),a=s.match(n);if(!a)return null;let o=a[0],i=o.replace(/(.)\/+$/,"$1"),d=a.slice(1);return{params:r.reduce((p,{paramName:c,isOptional:u},x)=>{if(c==="*"){let b=d[x]||"";i=o.slice(0,o.length-b.length).replace(/(.)\/+$/,"$1")}const h=d[x];return u&&!h?p[c]=void 0:p[c]=(h||"").replace(/%2F/g,"/"),p},{}),pathname:o,pathnameBase:i,pattern:t}}function Uv(t,s=!1,n=!0){pn(t==="*"||!t.endsWith("*")||t.endsWith("/*"),`Route path "${t}" will be treated as if it were "${t.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${t.replace(/\*$/,"/*")}".`);let r=[],a="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,d,m)=>(r.push({paramName:d,isOptional:m!=null}),m?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return t.endsWith("*")?(r.push({paramName:"*"}),a+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":t!==""&&t!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,s?void 0:"i"),r]}function Hv(t){try{return t.split("/").map(s=>decodeURIComponent(s).replace(/\//g,"%2F")).join("/")}catch(s){return pn(!1,`The URL path "${t}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${s}).`),t}}function Xn(t,s){if(s==="/")return t;if(!t.toLowerCase().startsWith(s.toLowerCase()))return null;let n=s.endsWith("/")?s.length-1:s.length,r=t.charAt(n);return r&&r!=="/"?null:t.slice(n)||"/"}function qv(t,s="/"){let{pathname:n,search:r="",hash:a=""}=typeof t=="string"?La(t):t;return{pathname:n?n.startsWith("/")?n:Vv(n,s):s,search:Kv(r),hash:Qv(a)}}function Vv(t,s){let n=s.replace(/\/+$/,"").split("/");return t.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function fc(t,s,n,r){return`Cannot include a '${t}' character in a manually specified \`to.${s}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function Yv(t){return t.filter((s,n)=>n===0||s.route.path&&s.route.path.length>0)}function Of(t){let s=Yv(t);return s.map((n,r)=>r===s.length-1?n.pathname:n.pathnameBase)}function $f(t,s,n,r=!1){let a;typeof t=="string"?a=La(t):(a={...t},Qt(!a.pathname||!a.pathname.includes("?"),fc("?","pathname","search",a)),Qt(!a.pathname||!a.pathname.includes("#"),fc("#","pathname","hash",a)),Qt(!a.search||!a.search.includes("#"),fc("#","search","hash",a)));let o=t===""||a.pathname==="",i=o?"/":a.pathname,d;if(i==null)d=n;else{let u=s.length-1;if(!r&&i.startsWith("..")){let x=i.split("/");for(;x[0]==="..";)x.shift(),u-=1;a.pathname=x.join("/")}d=u>=0?s[u]:"/"}let m=qv(a,d),p=i&&i!=="/"&&i.endsWith("/"),c=(o||i===".")&&n.endsWith("/");return!m.pathname.endsWith("/")&&(p||c)&&(m.pathname+="/"),m}var Jn=t=>t.join("/").replace(/\/\/+/g,"/"),Gv=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),Kv=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,Qv=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function Jv(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}var Bf=["POST","PUT","PATCH","DELETE"];new Set(Bf);var Zv=["GET",...Bf];new Set(Zv);var za=l.createContext(null);za.displayName="DataRouter";var Ll=l.createContext(null);Ll.displayName="DataRouterState";l.createContext(!1);var Ff=l.createContext({isTransitioning:!1});Ff.displayName="ViewTransition";var Xv=l.createContext(new Map);Xv.displayName="Fetchers";var e1=l.createContext(null);e1.displayName="Await";var zn=l.createContext(null);zn.displayName="Navigation";var Go=l.createContext(null);Go.displayName="Location";var On=l.createContext({outlet:null,matches:[],isDataRoute:!1});On.displayName="Route";var du=l.createContext(null);du.displayName="RouteError";function t1(t,{relative:s}={}){Qt(Ko(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=l.useContext(zn),{hash:a,pathname:o,search:i}=Jo(t,{relative:s}),d=o;return n!=="/"&&(d=o==="/"?n:Jn([n,o])),r.createHref({pathname:d,search:i,hash:a})}function Ko(){return l.useContext(Go)!=null}function tr(){return Qt(Ko(),"useLocation() may be used only in the context of a <Router> component."),l.useContext(Go).location}var _f="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function Wf(t){l.useContext(zn).static||l.useLayoutEffect(t)}function Qo(){let{isDataRoute:t}=l.useContext(On);return t?x1():s1()}function s1(){Qt(Ko(),"useNavigate() may be used only in the context of a <Router> component.");let t=l.useContext(za),{basename:s,navigator:n}=l.useContext(zn),{matches:r}=l.useContext(On),{pathname:a}=tr(),o=JSON.stringify(Of(r)),i=l.useRef(!1);return Wf(()=>{i.current=!0}),l.useCallback((m,p={})=>
11{if(pn(i.current,_f),!i.current)return;if(typeof m=="number"){n.go(m);return}let c=$f(m,JSON.parse(o),a,p.relative==="path");t==null&&s!=="/"&&(c.pathname=c.pathname==="/"?s:Jn([s,c.pathname])),(p.replace?n.replace:n.push)(c,p.state,p)},[s,n,o,a,t])}l.createContext(null);function zl(){let{matches:t}=l.useContext(On),s=t[t.length-1];return s?s.params:{}}function Jo(t,{relative:s}={}){let{matches:n}=l.useContext(On),{pathname:r}=tr(),a=JSON.stringify(Of(n));return l.useMemo(()=>$f(t,JSON.parse(a),r,s==="path"),[t,a,r,s])}function n1(t,s){return Uf(t,s)}function Uf(t,s,n,r,a){var j;Qt(Ko(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:o}=l.useContext(zn),{matches:i}=l.useContext(On),d=i[i.length-1],m=d?d.params:{},p=d?d.pathname:"/",c=d?d.pathnameBase:"/",u=d&&d.route;{let v=u&&u.path||"";Hf(p,!u||v.endsWith("*")||v.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${p}" (under <Route path="${v}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render. 12 13Please change the parent <Route path="${v}"> to <Route path="${v==="/"?"*":`${v}/*`}">.`)}let x=tr(),h;if(s){let v=typeof s=="string"?La(s):s;Qt(c==="/"||((j=v.pathname)==null?void 0:j.startsWith(c)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${v.pathname}" was given in the \`location\` prop.`),h=v}else h=x;let b=h.pathname||"/",f=b;if(c!=="/"){let v=c.replace(/^\//,"").split("/");f="/"+b.replace(/^\//,"").split("/").slice(v.length).join("/")}let g=Pf(t,{pathname:f});pn(u||g!=null,`No routes matched location "${h.pathname}${h.search}${h.hash}" `),pn(g==null||g[g.length-1].route.element!==void 0||g[g.length-1].route.Component!==void 0||g[g.length-1].route.lazy!==void 0,`Matched leaf route at location "${h.pathname}${h.search}${h.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let y=l1(g&&g.map(v=>Object.assign({},v,{params:Object.assign({},m,v.params),pathname:Jn([c,o.encodeLocation?o.encodeLocation(v.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?c:Jn([c,o.encodeLocation?o.encodeLocation(v.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:v.pathnameBase])})),i,n,r,a);return s&&y?l.createElement(Go.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...h},navigationType:"POP"}},y):y}function r1(){let t=p1(),s=Jv(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,r="rgba(200,200,200, 0.5)",a={padding:"0.5rem",backgroundColor:r},o={padding:"2px 4px",backgroundColor:r},i=null;return console.error("Error handled by React Router default ErrorBoundary:",t),i=l.createElement(l.Fragment,null,l.createElement("p",null,"ð¿ Hey developer ð"),l.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",l.createElement("code",{style:o},"ErrorBoundary")," or"," ",l.createElement("code",{style:o},"errorElement")," prop on your route.")),l.createElement(l.Fragment,null,l.createElement("h2",null,"Unexpected Application Error!"),l.createElement("h3",{style:{fontStyle:"italic"}},s),n?l.createElement("pre",{style:a},n):null,i)}var a1=l.createElement(r1,null),o1=class extends l.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,s){return s.location!==t.location||s.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:s.error,location:s.location,revalidation:t.revalidation||s.revalidation}}componentDidCatch(t,s){this.props.unstable_onError?this.props.unstable_onError(t,s):console.error("React Router caught the following error during render",t)}render(){return this.state.error!==void 0?l.createElement(On.Provider,{value:this.props.routeContext},l.createElement(du.Provider,{value:this.state.error,children:this.props.component})):this.props.children}};function i1({routeContext:t,match:s,children:n}){let r=l.useContext(za);return r&&r.static&&r.staticContext&&(s.route.errorElement||s.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=s.route.id),l.createElement(On.Provider,{value:t},n)}
13function l1(t,s=[],n=null,r=null,a=null){if(t==null){if(!n)return null;if(n.errors)t=n.matches;else if(s.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let o=t,i=n==null?void 0:n.errors;if(i!=null){let p=o.findIndex(c=>c.route.id&&(i==null?void 0:i[c.route.id])!==void 0);Qt(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(i).join(",")}`),o=o.slice(0,Math.min(o.length,p+1))}let d=!1,m=-1;if(n)for(let p=0;p<o.length;p++){let c=o[p];if((c.route.HydrateFallback||c.route.hydrateFallbackElement)&&(m=p),c.route.id){let{loaderData:u,errors:x}=n,h=c.route.loader&&!u.hasOwnProperty(c.route.id)&&(!x||x[c.route.id]===void 0);if(c.route.lazy||h){d=!0,m>=0?o=o.slice(0,m+1):o=[o[0]];break}}}return o.reduceRight((p,c,u)=>{let x,h=!1,b=null,f=null;n&&(x=i&&c.route.id?i[c.route.id]:void 0,b=c.route.errorElement||a1,d&&(m<0&&u===0?(Hf("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),h=!0,f=null):m===u&&(h=!0,f=c.route.hydrateFallbackElement||null)));let g=s.concat(o.slice(0,u+1)),y=()=>{let j;return x?j=b:h?j=f:c.route.Component?j=l.createElement(c.route.Component,null):c.route.element?j=c.route.element:j=p,l.createElement(i1,{match:c,routeContext:{outlet:p,matches:g,isDataRoute:n!=null},children:j})};return n&&(c.route.ErrorBoundary||c.route.errorElement||u===0)?l.createElement(o1,{location:n.location,revalidation:n.revalidation,component:b,error:x,children:y(),routeC
13ontext:{outlet:null,matches:g,isDataRoute:!0},unstable_onError:r}):y()},null)}function uu(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function c1(t){let s=l.useContext(za);return Qt(s,uu(t)),s}function d1(t){let s=l.useContext(Ll);return Qt(s,uu(t)),s}function u1(t){let s=l.useContext(On);return Qt(s,uu(t)),s}function mu(t){let s=u1(t),n=s.matches[s.matches.length-1];return Qt(n.route.id,`${t} can only be used on routes that contain a unique "id"`),n.route.id}function m1(){return mu("useRouteId")}function p1(){var r;let t=l.useContext(du),s=d1("useRouteError"),n=mu("useRouteError");return t!==void 0?t:(r=s.errors)==null?void 0:r[n]}function x1(){let{router:t}=c1("useNavigate"),s=mu("useNavigate"),n=l.useRef(!1);return Wf(()=>{n.current=!0}),l.useCallback(async(a,o={})=>{pn(n.current,_f),n.current&&(typeof a=="number"?t.navigate(a):await t.navigate(a,{fromRouteId:s,...o}))},[t,s])}var Tm={};function Hf(t,s,n){!s&&!Tm[t]&&(Tm[t]=!0,pn(!1,n))}l.memo(h1);function h1({routes:t,future:s,state:n,unstable_onError:r}){return Uf(t,void 0,n,r,s)}function Bs(t){Qt(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function f1({basename:t="/",children:s=null,location:n,navigationType:r="POP",navigator:a,static:o=!1}){Qt(!Ko(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let i=t.replace(/^\/*/,"/"),d=l.useMemo(()=>({basename:i,navigator:a,static:o,future:{}}),[i,a,o]);typeof n=="string"&&(n=La(n));let{pathname:m="/",search:p="",hash:c="",state:u=null,key:x="default"}=n,h=l.useMemo(()=>{let b=Xn(m,i);return b==null?null:{location:{pathname:b,search:p,hash:c,state:u,key:x},navigationType:r}},[i,m,p,c,u,x,r]);return pn(h!=null,`<Router basename="${i}"> is not able to match the URL "${m}${p}${c}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:l.createElement(zn.Provider,{value:d},l.createElement(Go.Provider,{children:s,value:h}))}function g1({children:t,location:s}){return n1(Td(t),s)}function Td(t,s=[]){let n=[];return l.Children.forEach(t,(r,a)=>{if(!l.isValidElement(r))return;let o=[...s,a];if(r.type===l.Fragment){n.push.apply(n,Td(r.props.children,o));return}Qt(r.type===Bs,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Qt(!r.props.index||!r.props.children,"An index route cannot have child routes.");let i={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(i.children=Td(r.props.children,o)),n.push(i)}),n}var Qi="get",Ji="application/x-www-form-urlencoded";function Ol(t){return t!=null&&typeof t.tagName=="string"}function b1(t){return Ol(t)&&t.tagName.toLowerCase()==="button"}function y1(t){return Ol(t)&&t.tagName.toLowerCase()==="form"}function j1(t){return Ol(t)&&t.tagName.toLowerCase()==="input"}function v1(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function w1(t,s){return t.button===0&&(!s||s==="_self")&&!v1(t)}function Ad(t=""){return new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((s,n)=>{let r=t[n];return s.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function N1(t,s){let n=Ad(t);return s&&s.forEach((r,a)=>{n.has(a)||s.getAll(a).forEach(o=>{n.append(a,o)})}),n}var mi=null;function k1(){if(mi===null)try{new FormData(document.createElement("form"),0),mi=!1}catch{mi=!0}return mi}var S1=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function gc(t){return t!=null&&!S1.has(t)?(pn(!1,`"${t}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Ji}"`),null):t}function C1(t,s){let n,r,a,o,i;if(y1(t)){let d=t.getAttribute("action");r=d?Xn(d,s):null,n=t.getAttribute("method")||Qi,a=gc(t.getAttribute("enctype"))||Ji,o=new FormData(t)}else if(b1(t)||j1(t)&&(t.type==="submit"||t.type==="image")){let d=t.form;if(d==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let m=t.getAttribute("formaction")||d.getAttribute("action");if(r=m?Xn(m,s):null,n=t.getAttribute("formmethod")||d.getAttribute("method")||Qi,a=gc(t.getAttribute("formenctype"))||gc(d.getAttribute("enctype"))||Ji,o=new FormData(d,t),!k1()){let{name:p,type:c,value:u}=t;if(c==="image"){let x=p?`${p}.`:"";o.append(`${x}x`,"0"),o.append(`${x}y`,"0")}else p&&o.append(p,u)}}else{if(Ol(t))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=Qi,r=null,a=Ji,i=t}return o&&a==="text/plain"&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:o,body:i}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function pu(t,s){if(t===!1||t===null||typeof t>"u")throw new Error(s)}function T1(t,s,n){let r=typeof t=="string"?new URL(t,typeof window>"u"?"server://singlefetch/":window.location.origin):t;return r.pathname==="/"?r.pathname=`_root.${n}`:s&&Xn(r.pathname,s)==="/"?r.pathname=`${s.replace(/\/$/,"")}/_root.${n}`:r.pathname=`${r.pathname.replace(/\/$/,"")}.${n}`,r}async function A1(t,s){if(t.id in s)return s[t.id];try{let n=await import(t.module);return s[t.id]=n,n}catch(n){return console.error(`Error loading route module \`${t.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.
13isSpaMode,window.location.reload(),new Promise(()=>{})}}function E1(t){return t==null?!1:t.href==null?t.rel==="preload"&&typeof t.imageSrcSet=="string"&&typeof t.imageSizes=="string":typeof t.rel=="string"&&typeof t.href=="string"}async function I1(t,s,n){let r=await Promise.all(t.map(async a=>{let o=s.routes[a.route.id];if(o){let i=await A1(o,n);return i.links?i.links():[]}return[]}));return P1(r.flat(1).filter(E1).filter(a=>a.rel==="stylesheet"||a.rel==="preload").map(a=>a.rel==="stylesheet"?{...a,rel:"prefetch",as:"style"}:{...a,rel:"prefetch"}))}function Am(t,s,n,r,a,o){let i=(m,p)=>n[p]?m.route.id!==n[p].route.id:!0,d=(m,p)=>{var c;return n[p].pathname!==m.pathname||((c=n[p].route.path)==null?void 0:c.endsWith("*"))&&n[p].params["*"]!==m.params["*"]};return o==="assets"?s.filter((m,p)=>i(m,p)||d(m,p)):o==="data"?s.filter((m,p)=>{var u;let c=r.routes[m.route.id];if(!c||!c.hasLoader)return!1;if(i(m,p)||d(m,p))return!0;if(m.route.shouldRevalidate){let x=m.route.shouldRevalidate({currentUrl:new URL(a.pathname+a.search+a.hash,window.origin),currentParams:((u=n[0])==null?void 0:u.params)||{},nextUrl:new URL(t,window.origin),nextParams:m.params,defaultShouldRevalidate:!0});if(typeof x=="boolean")return x}return!0}):[]}function R1(t,s,{includeHydrateFallback:n}={}){return D1(t.map(r=>{let a=s.routes[r.route.id];if(!a)return[];let o=[a.module];return a.clientActionModule&&(o=o.concat(a.clientActionModule)),a.clientLoaderModule&&(o=o.concat(a.clientLoaderModule)),n&&a.hydrateFallbackModule&&(o=o.concat(a.hydrateFallbackModule)),a.imports&&(o=o.concat(a.imports)),o}).flat(1))}function D1(t){return[...new Set(t)]}function M1(t){let s={},n=Object.keys(t).sort();for(let r of n)s[r]=t[r];return s}function P1(t,s){let n=new Set;return new Set(s),t.reduce((r,a)=>{let o=JSON.stringify(M1(a));return n.has(o)||(n.add(o),r.push({key:o,link:a})),r},[])}function qf(){let t=l.useContext(za);return pu(t,"You must render this element inside a <DataRouterContext.Provider> element"),t}function L1(){let t=l.useContext(Ll);return pu(t,"You must render this element inside a <DataRouterStateContext.Provider> element"),t}var xu=l.createContext(void 0);xu.displayName="FrameworkContext";function Vf(){let t=l.useContext(xu);return pu(t,"You must render this element inside a <HydratedRouter> element"),t}function z1(t,s){let n=l.useContext(xu),[r,a]=l.useState(!1),[o,i]=l.useState(!1),{onFocus:d,onBlur:m,onMouseEnter:p,onMouseLeave:c,onTouchStart:u}=s,x=l.useRef(null);l.useEffect(()=>{if(t==="render"&&i(!0),t==="viewport"){let f=y=>{y.forEach(j=>{i(j.isIntersecting)})},g=new IntersectionObserver(f,{threshold:.5});return x.current&&g.observe(x.current),()=>{g.disconnect()}}},[t]),l.useEffect(()=>{if(r){let f=setTimeout(()=>{i(!0)},100);return()=>{clearTimeout(f)}}},[r]);let h=()=>{a(!0)},b=()=>{a(!1),i(!1)};return n?t!=="intent"?[o,x,{}]:[o,x,{onFocus:Ha(d,h),onBlur:Ha(m,b),onMouseEnter:Ha(p,h),onMouseLeave:Ha(c,b),onTouchStart:Ha(u,h)}]:[!1,x,{}]}function Ha(t,s){return n=>{t&&t(n),n.defaultPrevented||s(n)}}function O1({page:t,...s}){let{router:n}=qf(),r=l.useMemo(()=>Pf(n.routes,t,n.basename),[n.routes,t,n.basename]);return r?l.createElement(B1,{page:t,matches:r,...s}):null}function $1(t){let{manifest:s,routeModules:n}=Vf(),[r,a]=l.useState([]);return l.useEffect(()=>{let o=!1;return I1(t,s,n).then(i=>{o||a(i)}),()=>{o=!0}},[t,s,n]),r}function B1({page:t,matches:s,...n}){let r=tr(),{manifest:a,routeModules:o}=Vf(),{basename:i}=qf(),{loaderData:d,matches:m}=L1(),p=l.useMemo(()=>Am(t,s,m,a,r,"data"),[t,s,m,a,r]),c=l.useMemo(()=>Am(t,s,m,a,r,"assets"),[t,s,m,a,r]),u=l.useMemo(()=>{if(t===r.pathname+r.search+r.hash)return[];let b=new Set,f=!1;if(s.forEach(y=>{var v;let j=a.routes[y.route.id];!j||!j.hasLoader||(!p.some(T=>T.route.id===y.route.id)&&y.route.id in d&&((v=o[y.route.id])!=null&&v.shouldRevalidate)||j.hasClientLoader?f=!0:b.add(y.route.id))}),b.size===0)return[];let g=T1(t,i,"data");return f&&b.size>0&&g.searchParams.set("_routes",s.filter(y=>b.has(y.route.id)).map(y=>y.route.id).join(",")),[g.pathname+g.search]},[i,d,r,a,p,s,t,o]),x=l.useMemo(()=>R1(c,a),[c,a]),h=$1(c);return l.createElement(l.Fragment,null,u.map(b=>l.createElement("link",{key:b,rel:"prefetch",as:"fetch",href:b,...n})),x.map(b=>l.createElement("link",{key:b,rel:"modulepreload",href:b,...n})),h.map(({key:b,link:f})=>l.createElement("link",{key:b,nonce:n.nonce,...f})))}function F1(...t){return s=>{t.forEach(n=>{typeof n=="function"?n(s):n!=null&&(n.current=s)})}}var Yf=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Yf&&(window.__reactRouterVersion="7.9.4")}catch{}function _1({basename:t,children:s,window:n}){let r=l.useRef();r.current==null&&(r.current=Av({window:n,v5Compat:!0}));let a=r.current,[o,i]=l.useState({action:a.action,location:a.location}),d=l.useCallback(m=>{l.startTransition(()=>i(m))},[i]);return l.useLayoutEffect(()=>a.listen(d),[a,d]),l.createElement(f1,{basename:t,children:s,location:o.location,navigationType:o.action,navigator:a})}var Gf=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Kf=l.forwardRef(function({onClick:s,discover:n="render",prefetch:r="none",relative:a,reloadDocument:o,replace:i,state:d,target:m,to:p,preventScrollReset:c,viewTransition:u,...x},h){let{basename:b}=l.useContext(zn),f=typeof p=="string"&&Gf.test(p),g,y=!1;if(typeof p=="string"&&f&&(g=p,Yf))try{let E=new URL(window.location.href),C=p.startsWith("//")?new URL(E.protocol+p):new URL(p),N=Xn(C.pathname,b);C.origin===E.origin&&N!=null?p=N+C.search+C.hash:y=!0}catch{pn(!1,`<Link to="${p}">
13 contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}let j=t1(p,{relative:a}),[v,T,k]=z1(r,x),w=q1(p,{replace:i,state:d,target:m,preventScrollReset:c,relative:a,viewTransition:u});function I(E){s&&s(E),E.defaultPrevented||w(E)}let A=l.createElement("a",{...x,...k,href:g||j,onClick:y||o?s:I,ref:F1(h,T),target:m,"data-discover":!f&&n==="render"?"true":void 0});return v&&!f?l.createElement(l.Fragment,null,A,l.createElement(O1,{page:j})):A});Kf.displayName="Link";var W1=l.forwardRef(function({"aria-current":s="page",caseSensitive:n=!1,className:r="",end:a=!1,style:o,to:i,viewTransition:d,children:m,...p},c){let u=Jo(i,{relative:p.relative}),x=tr(),h=l.useContext(Ll),{navigator:b,basename:f}=l.useContext(zn),g=h!=null&&Q1(u)&&d===!0,y=b.encodeLocation?b.encodeLocation(u).pathname:u.pathname,j=x.pathname,v=h&&h.navigation&&h.navigation.location?h.navigation.location.pathname:null;n||(j=j.toLowerCase(),v=v?v.toLowerCase():null,y=y.toLowerCase()),v&&f&&(v=Xn(v,f)||v);const T=y!=="/"&&y.endsWith("/")?y.length-1:y.length;let k=j===y||!a&&j.startsWith(y)&&j.charAt(T)==="/",w=v!=null&&(v===y||!a&&v.startsWith(y)&&v.charAt(y.length)==="/"),I={isActive:k,isPending:w,isTransitioning:g},A=k?s:void 0,E;typeof r=="function"?E=r(I):E=[r,k?"active":null,w?"pending":null,g?"transitioning":null].filter(Boolean).join(" ");let C=typeof o=="function"?o(I):o;return l.createElement(Kf,{...p,"aria-current":A,className:E,ref:c,style:C,to:i,viewTransition:d},typeof m=="function"?m(I):m)});W1.displayName="NavLink";var U1=l.forwardRef(({discover:t="render",fetcherKey:s,navigate:n,reloadDocument:r,replace:a,state:o,method:i=Qi,action:d,onSubmit:m,relative:p,preventScrollReset:c,viewTransition:u,...x},h)=>{let b=G1(),f=K1(d,{relative:p}),g=i.toLowerCase()==="get"?"get":"post",y=typeof d=="string"&&Gf.test(d),j=v=>{if(m&&m(v),v.defaultPrevented)return;v.preventDefault();let T=v.nativeEvent.submitter,k=(T==null?void 0:T.getAttribute("formmethod"))||i;b(T||v.currentTarget,{fetcherKey:s,method:k,navigate:n,replace:a,state:o,relative:p,preventScrollReset:c,viewTransition:u})};return l.createElement("form",{ref:h,method:g,action:f,onSubmit:r?m:j,...x,"data-discover":!y&&t==="render"?"true":void 0})});U1.displayName="Form";function H1(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Qf(t){let s=l.useContext(za);return Qt(s,H1(t)),s}function q1(t,{target:s,replace:n,state:r,preventScrollReset:a,relative:o,viewTransition:i}={}){let d=Qo(),m=tr(),p=Jo(t,{relative:o});return l.useCallback(c=>{if(w1(c,s)){c.preventDefault();let u=n!==void 0?n:To(m)===To(p);d(t,{replace:u,state:r,preventScrollReset:a,relative:o,viewTransition:i})}},[m,d,p,n,r,s,t,a,o,i])}function Zo(t){pn(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let s=l.useRef(Ad(t)),n=l.useRef(!1),r=tr(),a=l.useMemo(()=>N1(r.search,n.current?null:s.current),[r.search]),o=Qo(),i=l.useCallback((d,m)=>{const p=Ad(typeof d=="function"?d(new URLSearchParams(a)):d);n.current=!0,o("?"+p,m)},[o,a]);return[a,i]}var V1=0,Y1=()=>`__${String(++V1)}__`;function G1(){let{router:t}=Qf("useSubmit"),{basename:s}=l.useContext(zn),n=m1();return l.useCallback(async(r,a={})=>{let{action:o,method:i,encType:d,formData:m,body:p}=C1(r,s);if(a.navigate===!1){let c=a.fetcherKey||Y1();await t.fetch(c,n,a.action||o,{preventScrollReset:a.preventScrollReset,formData:m,body:p,formMethod:a.method||i,formEncType:a.encType||d,flushSync:a.flushSync})}else await t.navigate(a.action||o,{preventScrollReset:a.preventScrollReset,formData:m,body:p,formMethod:a.method||i,formEncType:a.encType||d,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[t,s,n])}function K1(t,{relative:s}={}){let{basename:n}=l.useContext(zn),r=l.useContext(On);Qt(r,"useFormAction must be used inside a RouteContext");let[a]=r.matches.slice(-1),o={...Jo(t||".",{relative:s})},i=tr();if(t==null){o.search=i.search;let d=new URLSearchParams(o.search),m=d.getAll("index");if(m.some(c=>
13c==="")){d.delete("index"),m.filter(u=>u).forEach(u=>d.append("index",u));let c=d.toString();o.search=c?`?${c}`:""}}return(!t||t===".")&&a.route.index&&(o.search=o.search?o.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(o.pathname=o.pathname==="/"?n:Jn([n,o.pathname])),To(o)}function Q1(t,{relative:s}={}){let n=l.useContext(Ff);Qt(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=Qf("useViewTransitionState"),a=Jo(t,{relative:s});if(!n.isTransitioning)return!1;let o=Xn(n.currentLocation.pathname,r)||n.currentLocation.pathname,i=Xn(n.nextLocation.pathname,r)||n.nextLocation.pathname;return dl(a.pathname,i)!=null||dl(a.pathname,o)!=null}function J1(t){if(typeof document>"u")return;let s=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",s.appendChild(n),n.styleSheet?n.styleSheet.cssText=t:n.appendChild(document.createTextNode(t))}const Z1=t=>{switch(t){case"success":return tw;case"info":return nw;case"warning":return sw;case"error":return rw;default:return null}},X1=Array(12).fill(0),ew=({visible:t,className:s})=>ee.createElement("div",{className:["sonner-loading-wrapper",s].filter(Boolean).join(" "),"data-visible":t},ee.createElement("div",{className:"sonner-spinner"},X1.map((n,r)=>ee.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),tw=ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ee.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),sw=ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ee.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),nw=ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ee.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),rw=ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ee.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),aw=ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ee.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ee.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),ow=()=>{const[t,s]=ee.useState(document.hidden);return ee.useEffect(()=>{const n=()=>{s(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),t};let Ed=1;class iw{constructor(){this.subscribe=s=>(this.subscribers.push(s),()=>{const n=this.subscribers.indexOf(s);this.subscribers.splice(n,1)}),this.publish=s=>{this.subscribers.forEach(n=>n(s))},this.addToast=s=>{this.publish(s),this.toasts=[...this.toasts,s]},this.create=s=>{var n;const{message:r,...a}=s,o=typeof(s==null?void 0:s.id)=="number"||((n=s.id)==null?void 0:n.length)>0?s.id:Ed++,i=this.toasts.find(m=>m.id===o),d=s.dismissible===void 0?!0:s.dismissible;return this.dismissedToasts.has(o)&&this.dismissedToasts.delete(o),i?this.toasts=this.toasts.map(m=>m.id===o?(this.publish({...m,...s,id:o,title:r}
vendor: 3,209 bytes, line 13
13),{...m,...s,id:o,dismissible:d,title:r}):m):this.addToast({title:r,...a,dismissible:d,id:o}),o},this.dismiss=s=>(s?(this.dismissedToasts.add(s),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:s,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),s),this.message=(s,n)=>this.create({...n,message:s}),this.error=(s,n)=>this.create({...n,message:s,type:"error"}),this.success=(s,n)=>this.create({...n,type:"success",message:s}),this.info=(s,n)=>this.create({...n,type:"info",message:s}),this.warning=(s,n)=>this.create({...n,type:"warning",message:s}),this.loading=(s,n)=>this.create({...n,type:"loading",message:s}),this.promise=(s,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:s,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const a=Promise.resolve(s instanceof Function?s():s);let o=r!==void 0,i;const d=a.then(async p=>{if(i=["resolve",p],ee.isValidElement(p))o=!1,this.create({id:r,type:"default",message:p});else if(cw(p)&&!p.ok){o=!1;const u=typeof n.error=="function"?await n.error(`HTTP error! status: ${p.status}`):n.error,x=typeof n.description=="function"?await n.description(`HTTP error! status: ${p.status}`):n.description,b=typeof u=="object"&&!ee.isValidElement(u)?u:{message:u};this.create({id:r,type:"error",description:x,...b})}else if(p instanceof Error){o=!1;const u=typeof n.error=="function"?await n.error(p):n.error,x=typeof n.description=="function"?await n.description(p):n.description,b=typeof u=="object"&&!ee.isValidElement(u)?u:{message:u};this.create({id:r,type:"error",description:x,...b})}else if(n.success!==void 0){o=!1;const u=typeof n.success=="function"?await n.success(p):n.success,x=typeof n.description=="function"?await n.description(p):n.description,b=typeof u=="object"&&!ee.isValidElement(u)?u:{message:u};this.create({id:r,type:"success",description:x,...b})}}).catch(async p=>{if(i=["reject",p],n.error!==void 0){o=!1;const c=typeof n.error=="function"?await n.error(p):n.error,u=typeof n.description=="function"?await n.description(p):n.description,h=typeof c=="object"&&!ee.isValidElement(c)?c:{message:c};this.create({id:r,type:"error",description:u,...h})}}).finally(()=>{o&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),m=()=>new Promise((p,c)=>d.then(()=>i[0]==="reject"?c(i[1]):p(i[1])).catch(c));return typeof r!="string"&&typeof r!="number"?{unwrap:m}:Object.assign(r,{unwrap:m})},this.custom=(s,n)=>{const r=(n==null?void 0:n.id)||Ed++;return this.create({jsx:s(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(s=>!this.dismissedToasts.has(s.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Rs=new iw,lw=(t,s)=>{const n=(s==null?void 0:s.id)||Ed++;return Rs.addToast({title:t,...s,id:n}),n},cw=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",dw=lw,uw=()=>Rs.toasts,mw=()=>Rs.getActiveToasts(),ce=Object.assign(dw,{success:Rs.success,info:Rs.info,warning:Rs.warning,error:Rs.error,custom:Rs.custom,message:Rs.message,promise:Rs.promise,dismiss:Rs.dismiss,loading:Rs.loading},{getHistory:uw,getToasts:mw});J1
vendor: 14,873 bytes, line 13
13("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function
vendor: 1,896 bytes, line 13
13pi(t){return t.label!==void 0}const pw=3,xw="24px",hw="16px",Em=4e3,fw=356,gw=14,bw=45,yw=200;function yn(...t){return t.filter(Boolean).join(" ")}function jw(t){const[s,n]=t.split("-"),r=[];return s&&r.push(s),n&&r.push(n),r}const vw=t=>{var s,n,r,a,o,i,d,m,p;const{invert:c,toast:u,unstyled:x,interacting:h,setHeights:b,visibleToasts:f,heights:g,index:y,toasts:j,expanded:v,removeToast:T,defaultRichColors:k,closeButton:w,style:I,cancelButtonStyle:A,actionButtonStyle:E,className:C="",descriptionClassName:N="",duration:S,position:O,gap:R,expandByDefault:z,classNames:D,icons:L,closeButtonAriaLabel:$="Close toast"}=t,[q,P]=ee.useState(null),[U,V]=ee.useState(null),[M,F]=ee.useState(!1),[W,_]=ee.useState(!1),[G,B]=ee.useState(!1),[Y,J]=ee.useState(!1),[H,Z]=ee.useState(!1),[Q,K]=ee.useState(0),[X,se]=ee.useState(0),pe=ee.useRef(u.duration||S||Em),me=ee.useRef(null),Ne=ee.useRef(null),at=y===0,ae=y+1<=f,xe=u.type,ze=u.dismissible!==!1,Le=u.className||"",ht=u.descriptionClassName||"",ue=ee.useMemo(()=>g.findIndex(he=>he.toastId===u.id)||0,[g,u.id]),we=ee.useMemo(()=>{var he;return(he=u.closeButton)!=null?he:w},[u.closeButton,w]),Be=ee.useMemo(()=>u.duration||S||Em,[u.duration,S]),Ye=ee.useRef(0),rt=ee.useRef(0),te=ee.useRef(0),ve=ee.useRef(null),[Ae,We]=O.split("-"),ie=ee.useMemo(()=>g.reduce((he,lt,tt)=>tt>=ue?he:he+lt.height,0),[g,ue]),Ue=ow(),Te=u.invert||c,He=xe==="loading";rt.current=ee.useMemo(()=>ue*R+ie,[ue,ie]),ee.useEffect(()=>{pe.current=Be},[Be]),ee.useEffect(()=>{F(!0)},[]),ee.useEffect(()=>{const he=Ne.current;if(he){const lt=he.getBoundingClientRect().height;return se(lt),b(tt=>[{toastId:u.id,height:lt,position:u.position},...tt]),()=>b(tt=>tt.filter(Se=>Se.toastId!==u.id))}},[b,u.id]),ee.useLayoutEffect(()=>{if(!M)return;const he=Ne.current,lt=he.style.height;he.style.height="auto";const tt=he.getBoundingClientRect().height;he.style.height=lt,se(tt),b(Se=>
vendor: 11,263 bytes, line 13
13Se.find(_e=>_e.toastId===u.id)?Se.map(_e=>_e.toastId===u.id?{..._e,height:tt}:_e):[{toastId:u.id,height:tt,position:u.position},...Se])},[M,u.title,u.description,b,u.id,u.jsx,u.action,u.cancel]);const Oe=ee.useCallback(()=>{_(!0),K(rt.current),b(he=>he.filter(lt=>lt.toastId!==u.id)),setTimeout(()=>{T(u)},yw)},[u,T,b,rt]);ee.useEffect(()=>{if(u.promise&&xe==="loading"||u.duration===1/0||u.type==="loading")return;let he;return v||h||Ue?(()=>{if(te.current<Ye.current){const Se=new Date().getTime()-Ye.current;pe.current=pe.current-Se}te.current=new Date().getTime()})():(()=>{pe.current!==1/0&&(Ye.current=new Date().getTime(),he=setTimeout(()=>{u.onAutoClose==null||u.onAutoClose.call(u,u),Oe()},pe.current))})(),()=>clearTimeout(he)},[v,h,u,xe,Ue,Oe]),ee.useEffect(()=>{u.delete&&(Oe(),u.onDismiss==null||u.onDismiss.call(u,u))},[Oe,u.delete]);function Je(){var he;if(L!=null&&L.loading){var lt;return ee.createElement("div",{className:yn(D==null?void 0:D.loader,u==null||(lt=u.classNames)==null?void 0:lt.loader,"sonner-loader"),"data-visible":xe==="loading"},L.loading)}return ee.createElement(ew,{className:yn(D==null?void 0:D.loader,u==null||(he=u.classNames)==null?void 0:he.loader),visible:xe==="loading"})}const de=u.icon||(L==null?void 0:L[xe])||Z1(xe);var je,qe;return ee.createElement("li",{tabIndex:0,ref:Ne,className:yn(C,Le,D==null?void 0:D.toast,u==null||(s=u.classNames)==null?void 0:s.toast,D==null?void 0:D.default,D==null?void 0:D[xe],u==null||(n=u.classNames)==null?void 0:n[xe]),"data-sonner-toast":"","data-rich-colors":(je=u.richColors)!=null?je:k,"data-styled":!(u.jsx||u.unstyled||x),"data-mounted":M,"data-promise":!!u.promise,"data-swiped":H,"data-removed":W,"data-visible":ae,"data-y-position":Ae,"data-x-position":We,"data-index":y,"data-front":at,"data-swiping":G,"data-dismissible":ze,"data-type":xe,"data-invert":Te,"data-swipe-out":Y,"data-swipe-direction":U,"data-expanded":!!(v||z&&M),"data-testid":u.testId,style:{"--index":y,"--toasts-before":y,"--z-index":j.length-y,"--offset":`${W?Q:rt.current}px`,"--initial-height":z?"auto":`${X}px`,...I,...u.style},onDragEnd:()=>{B(!1),P(null),ve.current=null},onPointerDown:he=>{he.button!==2&&(He||!ze||(me.current=new Date,K(rt.current),he.target.setPointerCapture(he.pointerId),he.target.tagName!=="BUTTON"&&(B(!0),ve.current={x:he.clientX,y:he.clientY})))},onPointerUp:()=>{var he,lt,tt;if(Y||!ze)return;ve.current=null;const Se=Number(((he=Ne.current)==null?void 0:he.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),es=Number(((lt=Ne.current)==null?void 0:lt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),_e=new Date().getTime()-((tt=me.current)==null?void 0:tt.getTime()),St=q==="x"?Se:es,$t=Math.abs(St)/_e;if(Math.abs(St)>=bw||$t>.11){K(rt.current),u.onDismiss==null||u.onDismiss.call(u,u),V(q==="x"?Se>0?"right":"left":es>0?"down":"up"),Oe(),J(!0);return}else{var Ct,ot;(Ct=Ne.current)==null||Ct.style.setProperty("--swipe-amount-x","0px"),(ot=Ne.current)==null||ot.style.setProperty("--swipe-amount-y","0px")}Z(!1),B(!1),P(null)},onPointerMove:he=>{var lt,tt,Se;if(!ve.current||!ze||((lt=window.getSelection())==null?void 0:lt.toString().length)>0)return;const _e=he.clientY-ve.current.y,St=he.clientX-ve.current.x;var $t;const Ct=($t=t.swipeDirections)!=null?$t:jw(O);!q&&(Math.abs(St)>1||Math.abs(_e)>1)&&P(Math.abs(St)>Math.abs(_e)?"x":"y");let ot={x:0,y:0};const fn=Vt=>1/(1.5+Math.abs(Vt)/20);if(q==="y"){if(Ct.includes("top")||Ct.includes("bottom"))if(Ct.includes("top")&&_e<0||Ct.includes("bottom")&&_e>0)ot.y=_e;else{const Vt=_e*fn(_e);ot.y=Math.abs(Vt)<Math.abs(_e)?Vt:_e}}else if(q==="x"&&(Ct.includes("left")||Ct.includes("right")))if(Ct.includes("left")&&St<0||Ct.includes("right")&&St>0)ot.x=St;else{const Vt=St*fn(St);ot.x=Math.abs(Vt)<Math.abs(St)?Vt:St}(Math.abs(ot.x)>0||Math.abs(ot.y)>0)&&Z(!0),(tt=Ne.current)==null||tt.style.setProperty("--swipe-amount-x",`${ot.x}px`),(Se=Ne.current)==null||Se.style.setProperty("--swipe-amount-y",`${ot.y}px`)}},we&&!u.jsx&&xe!=="loading"?ee.createElement("button",{"aria-label":$,"data-disabled":He,"data-close-button":!0,onClick:He||!ze?()=>{}:()=>{Oe(),u.onDismiss==null||u.onDismiss.call(u,u)},className:yn(D==null?void 0:D.closeButton,u==null||(r=u.classNames)==null?void 0:r.closeButton)},(qe=L==null?void 0:L.close)!=null?qe:aw):null,(xe||u.icon||u.promise)&&u.icon!==null&&((L==null?void 0:L[xe])!==null||u.icon)?ee.createElement("div",{"data-icon":"",className:yn(D==null?void 0:D.icon,u==null||(a=u.classNames)==null?void 0:a.icon)},u.promise||u.type==="loading"&&!u.icon?u.icon||Je():null,u.type!=="loading"?de:null):null,ee.createElement("div",{"data-content":"",className:yn(D==null?void 0:D.content,u==null||(o=u.classNames)==null?void 0:o.content)},ee.createElement("div",{"data-title":"",className:yn(D==null?void 0:D.title,u==null||(i=u.classNames)==null?void 0:i.title)},u.jsx?u.jsx:typeof u.title=="function"?u.title():u.title),u.description?ee.createElement("div",{"data-description":"",className:yn(N,ht,D==null?void 0:D.description,u==null||(d=u.classNames)==null?void 0:d.description)},typeof u.description=="function"?u.description():u.description):null),ee.isValidElement(u.cancel)?u.cancel:u.cancel&&pi(u.cancel)?ee.createElement("button",{"data-button":!0,"data-cancel":!0,style:u.cancelButtonStyle||A,onClick:he=>{pi(u.cancel)&&ze&&(u.cancel.onClick==null||u.cancel.onClick.call(u.cancel,he),Oe())},className:yn(D==null?void 0:D.cancelButton,u==null||(m=u.classNames)==null?void 0:m.cancelButton)},u.cancel.label):null,ee.isValidElement(u.action)?u.action:u.action&&pi(u.action)?ee.createElement("button",{"data-button":!0,"data-action":!0,style:u.actionButtonStyle||E,onClick:he=>{pi(u.action)&&(u.action.onClick==null||u.action.onClick.call(u.action,he),!he.defaultPrevented&&Oe())},className:yn(D==null?void 0:D.actionButton,u==null||(p=u.classNames)==null?void 0:p.actionButton)},u.action.label):null)};function Im(){if(typeof window>"u"||typeof document>"u")return"ltr";const t=document.documentElement.getAttribute("dir");return t==="auto"||!t?window.getComputedStyle(document.documentElement).direction:t}function ww(t,s){const n={};return[t,s].forEach((r,a)=>{const o=a===1,i=o?"--mobile-offset":"--offset",d=o?hw:xw;function m(p){["top","right","bottom","left"].forEach(c=>{n[`${i}-${c}`]=typeof p=="number"?`${p}px`:p})}typeof r=="number"||typeof r=="string"?m(r):typeof r=="object"?["top","right","bottom","left"].forEach(p=>{r[p]===void 0?n[`${i}-${p}`]=d:n[`${i}-${p}`]=typeof r[p]=="number"?`${r[p]}px`:r[p]}):m(d)}),n}const Oa=ee.forwardRef(function(s,n){const{id:r,invert:a,position:o="bottom-right",hotkey:i=["altKey","KeyT"],expand:d,closeButton:m,className:p,offset:c,mobileOffset:u,theme:x="light",richColors:h,duration:b,style:f,visibleToasts:g=pw,toastOptions:y,dir:j=Im(),gap:v=gw,icons:T,containerAriaLabel:k="Notifications"}=s,[w,I]=ee.useState([]),A=ee.useMemo(()=>r?w.filter(M=>M.toasterId===r):w.filter(M=>!M.toasterId),[w,r]),E=ee.useMemo(()=>Array.from(new Set([o].concat(A.filter(M=>M.position).map(M=>M.position)))),[A,o]),[C,N]=ee.useState([]),[S,O]=ee.useState(!1),[R,z]=ee.useState(!1),[D,L]=ee.useState(x!=="system"?x:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),$=ee.useRef(null),q=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),P=ee.useRef(null),U=ee.useRef(!1),V=ee.useCallback(M=>{I(F=>{var W;return(W=F.find(_=>_.id===M.id))!=null&&W.delete||Rs.dismiss(M.id),F.filter(({id:_})=>_!==M.id)})},[]);return ee.useEffect(()=>Rs.subscribe(M=>{if(M.dismiss){requestAnimationFrame(()=>{I(F=>F.map(W=>W.id===M.id?{...W,delete:!0}:W))});return}setTimeout(()=>{N0.flushSync(()=>{I(F=>{const W=F.findIndex(_=>_.id===M.id);return W!==-1?[...F.slice(0,W),{...F[W],...M},...F.slice(W+1)]:[M,...F]})})})}),[w]),ee.useEffect(()=>{if(x!=="system"){L(x);return}if(x==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?L("dark"):L("light")),typeof window>"u")return;const M=window.matchMedia("(prefers-color-scheme: dark)");try{M.addEventListener("change",({matches:F})=>{L(F?"dark":"light")})}catch{M.addListener(({matches:W})=>{try{L(W?"dark":"light")}catch(_){console.error(_)}})}},[x]),ee.useEffect(()=>{w.length<=1&&O(!1)},[w]),ee.useEffect(()=>{const M=F=>{var W;if(i.every(B=>F[B]||F.code===B)){var G;O(!0),(G=$.current)==null||G.focus()}F.code==="Escape"&&(document.activeElement===$.current||(W=$.current)!=null&&W.contains(document.activeElement))&&O(!1)};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[i]),ee.useEffect(()=>{if($.current)return()=>{P.current&&(P.current.focus({preventScroll:!0}),P.current=null,U.current=!1)}},[$.current]),ee.createElement("section",{ref:n,"aria-label":`${k} ${q}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},E.map((M,F)=>{var W;const[_,G]=M.split("-");return A.length?ee.createElement("ol",{key:M,dir:j==="auto"?Im():j,tabIndex:-1,ref:$,className:p,"data-sonner-toaster":!0,"data-sonner-theme":D,"data-y-position":_,"data-x-position":G,style:{"--front-toast-height":`${((W=C[0])==null?void 0:W.height)||0}px`,"--width":`${fw}px`,"--gap":`${v}px`,...f,...ww(c,u)},onBlur:B=>{U.current&&!B.currentTarget.contains(B.relatedTarget)&&(U.current=!1,P.current&&(P.current.focus({preventScroll:!0}),P.current=null))},onFocus:B=>{B.target instanceof HTMLElement&&B.target.dataset.dismissible==="false"||U.current||(U.current=!0,P.current=B.relatedTarget)},onMouseEnter:()=>O(!0),onMouseMove:()=>O(!0),onMouseLeave:()=>{R||O(!1)},onDragEnd:()=>O(!1),onPointerDown:B=>{B.target instanceof HTMLElement&&B.target.dataset.dismissible==="false"||z(!0)},onPointerUp:()=>z(!1)},A.filter(B=>!B.position&&F===0||B.position===M).map((B,Y)=>{var J,H;return ee.createElement(vw,{key:B.id,icons:T,index:Y,toast:B,defaultRichColors:h,duration:(J=y==null?void 0:y.duration)!=null?J:b,className:y==null?void 0:y.className,descriptionClassName:y==null?void 0:y.descriptionClassName,invert:a,visibleToasts:g,closeButton:(H=y==null?void 0:y.closeButton)!=null?H:m,interacting:R,position:M,style:y==null?void 0:y.style,unstyled:y==null?void 0:y.unstyled,classNames:y==null?void 0:y.classNames,cancelButtonStyle:y==null?void 0:y.cancelButtonStyle,actionButtonStyle:y==null?void 0:y.actionButtonStyle,closeButtonAriaLabel:y==null?void 0:y.closeButtonAriaLabel,removeToast:V,toasts:A.filter(Z=>Z.position==B.position),heights:C.filter(Z=>Z.position==B.position),setHeights:N,expandByDefault:d,gap:v,expanded:S,swipeDirections:s.swipeDirections})})):null}))});var Rm;(function(t){t[t.Min=1]="Min",t[t.Low=2]="Low",t[t.Default=3]="Default",t[t.High=4]="High",t[t.Max=5]="Max"})(Rm||(Rm={}));var Dm;(function(t){t[t.Secret=-1]="Secret",t[t.Private=0]="Private",t[t.Public=1]="Public"})(Dm||(Dm={}));const Zr=I0("FirebaseMessaging",{web:()=>Gs(()=>import("./web-vT3BfPdX.js"),__vite__mapDeps([0,1,2,3])).then(t=>new t.FirebaseMessagingWeb)});async function Nw(){const t="bucky_device_id";try{const{value:s}=await hm.get({key:t});if(s)return console.log("[PushNotifications] Using existing device ID:",s),s;const n=`${Br.getPlatform()}-${crypto.randomUUID()}`;return await hm.set({key:t,value:n}
13),console.log("[PushNotifications] Generated new device ID:",n),n}catch(s){return console.error("[PushNotifications] Error getting device ID:",s),`${Br.getPlatform()}-fallback-${Date.now()}`}}function kw({userId:t,userEmail:s,token:n,onNotificationReceived:r,onNotificationTapped:a}){const[o,i]=l.useState(!1),[d,m]=l.useState(null),[p,c]=l.useState(null),u=Br.isNativePlatform(),x=l.useRef(null),h=l.useCallback(async f=>{if(!t||!s||!n){console.log("[PushNotifications] Cannot save token - missing user info");return}if(x.current===f){console.log("[PushNotifications] Token already saved, skipping duplicate save");return}try{const g=await Nw();await lf("pushNotificationTokens",`${t}_${g}`,{fcmToken:f,userId:t,userEmail:s,platform:Br.getPlatform(),deviceId:g,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),active:!0},n),x.current=f,console.log("[PushNotifications] FCM token saved to Firestore with device ID:",g)}catch(g){console.error("[PushNotifications] Failed to save FCM token:",g)}},[t,s,n]),b=l.useCallback(async()=>{if(!u){console.log("[PushNotifications] Not supported on this platform");return}try{let f=await Zr.checkPermissions();if(console.log("[PushNotifications] Current permission status:",f.receive),f.receive==="prompt"&&(f=await Zr.requestPermissions()),f.receive!=="granted"){c("Push notification permission denied"),console.log("[PushNotifications] Permission denied");return}const g=await Zr.getToken();console.log("[PushNotifications] FCM Token received:",g.token),m(g.token),i(!0),g.token&&h(g.token),console.log("[PushNotifications] Registered successfully")}catch(f){console.error("[PushNotifications] Registration failed:",f),c(f.message||"Failed to register for push notifications")}},[u,h]);return l.useEffect(()=>{if(!u)return;const f=Zr.addListener("tokenReceived",j=>{console.log("[PushNotifications] Token refreshed:",j.token),m(j.token),h(j.token)}),g=Zr.addListener("notificationReceived",j=>{console.log("[PushNotifications] Notification received:",j.notification),r==null||r(j.notification)}
13),y=Zr.addListener("notificationActionPerformed",j=>{console.log("[PushNotifications] Notification action performed:",j.notification),a==null||a(j.notification)});return()=>{f.then(j=>j.remove()),g.then(j=>j.remove()),y.then(j=>j.remove())}},[u,h,r,a]),l.useEffect(()=>{u&&t&&!o&&b()},[u,t,o,b]),{isSupported:u,isRegistered:o,fcmToken:d,error:p,registerForPushNotifications:b}}function Sw(t,s){const[n,r]=l.useState([]),a=l.useRef(t);a.current=t;const o=l.useRef(new Set);l.useEffect(()=>{if(!t){r([]);return}const c=Il("notifications",[Ve("recipientId","==",t),Nt("createdAt","desc"),Tt(50)],u=>{r(u.filter(x=>!o.current.has(x.id)))});return()=>c()},[t,s]);const i=n.reduce((c,u)=>u.seen?c:c+1,0),d=l.useCallback(async c=>{r(u=>u.map(x=>x.id===c?{...x,seen:!0,read:!0}:x));try{await re("markNotificationRead",{notificationId:c},s)}catch(u){console.error("[useNotifications] markRead failed:",u)}},[s]),m=l.useCallback(async()=>{r(c=>c.map(u=>({...u,seen:!0,read:!0})));try{await re("markAllNotificationsRead",{},s)}catch(c){console.error("[useNotifications] markAllRead failed:",c)}},[s]),p=l.useCallback(async c=>{o.current.add(c),r(u=>u.filter(x=>x.id!==c));try{await re("dismissNotification",{notificationId:c},s)}catch(u){console.error("[useNotifications] dismiss failed:",u),o.current.delete(c)}},[s]);return{notifications:n,unreadCount:i,markRead:d,markAllRead:m,dismiss:p}}const bc=async()=>{},Cw={enabled:!1,notifications:[],unreadCount:0,messagesUnread:0,markRead:bc,markAllRead:bc,dismiss:bc,isOpen:!1,tab:"notifications",activeThreadId:null,openDrawer:()=>{},closeDrawer:()=>{},setTab:()=>{},setActiveThreadId:()=>{},uid:void 0,token:void 0,isAdmin:!1,deepLink:()=>{}},Jf=l.createContext(Cw);function $n(){return l.useContext(Jf)}function Tw({uid:t,token:s,isAdmin:n,onDeepLink:r,children:a}){const{notifications:o,unreadCount:i,markRead:d,markAllRead:m,dismiss:p}=Sw(t,s),[c,u]=l.useState(!1),[x,h]=l.useState("notifications"),[b,f]=l.useState(null),g=l.useCallback((T,k)=>{T&&h(T),k!==void 0&&f(k),u(!0)},[]),y=l.useCallback(()=>u(!1),[]),j=l.useMemo(()=>o.reduce((T,k)=>k.type==="team_dm"&&!k.seen?T+1:T,0),[o]),v={enabled:!0,notifications:o,unreadCount:i,messagesUnread:j,markRead:d,markAllRead:m,dismiss:p,isOpen:c,tab:x,activeThreadId:b,openDrawer:g,closeDrawer:y,setTab:h,setActiveThreadId:f,uid:t,token:s,isAdmin:n,deepLink:r};return e.jsx(Jf.Provider,{value:v,children:a})}const Zf=be("AlarmClock",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]]),Aw=be("Archive",[["rect",{width:"20",height:"5",x:"2",y:"4",rx:"2",key:"uhwcea"}],["path",{d:"M4 9v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9",key:"shkvi4"}],["path",{d:"M10 13h4",key:"ytezjc"}]]),$l=be("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),Ew=be("ArrowUpCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]]),Bl=be("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),Iw=be("Award",[["circle",{cx:"12",cy:"8",r:"6",key:"1vp47v"}],["path",{d:"M15.477 12.89 17 22l-5-3-5 3 1.523-9.11",key:"em7aur"}]]),hu=be("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]),Fr=be("BarChart3",[["path",{d:"M3 3v18h18",key:"1s2lah"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]),Xf=be("BellRing",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M4 2C2.8 3.7 2 5.7 2 8",key:"tap9e0"}],["path",{d:"M22 8c0-2.3-.8-4.3-2-6",key:"5bb3ad"}]]),Dn=be("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]),Rw=be("BookOpenCheck",[["path",{d:"M8 3H2v15h7c1.7 0 3 1.3 3 3V7c0-2.2-1.8-4-4-4Z",key:"1i8u0n"}],["path",{d:"m16 12 2 2 4-4",key:"mdajum"}],["path",{d:"M22 6V3h-6c-2.2 0-4 1.8-4 4v14c0-1.7 1.3-3 3-3h7v-2.3",key:"jb5l51"}]]),Fl=be("Bot",[["rect",{width:"18",height:"10",x:"3",y:"11",rx:"2",key:"1ofdy3"}],["circle",{cx:"12",cy:"5",r:"2",key:"f1ur92"}],["path",{d:"M12 7v4",key:"xawao1"}],["line",{x1:"8",x2:"8",y1:"16",y2:"16",key:"h6x27f"}],["line",{x1:"16",x2:"16",y1:"16",y2:"16",key:"5lty7f"}]]),Dw=be("Briefcase",[["rect",{width:"20",height:"14",x:"2",y:"7",rx:"2",ry:"2",key:"eto64e"}],["path",{d:"M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"zwj3tp"}]]),eg=be("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}
13],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]),uo=be("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]),Mw=be("CalendarCheck",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2",key:"eu3xkr"}],["line",{x1:"16",x2:"16",y1:"2",y2:"6",key:"m3sa8f"}],["line",{x1:"8",x2:"8",y1:"2",y2:"6",key:"18kwsl"}],["line",{x1:"3",x2:"21",y1:"10",y2:"10",key:"xt86sb"}],["path",{d:"m9 16 2 2 4-4",key:"19s6y9"}]]),Pw=be("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.25V14",key:"re2vv1"}],["path",{d:"M22 16a6 6 0 1 1-12 0 6 6 0 0 1 12 0Z",key:"ame013"}]]),Lw=be("CalendarDays",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2",key:"eu3xkr"}],["line",{x1:"16",x2:"16",y1:"2",y2:"6",key:"m3sa8f"}],["line",{x1:"8",x2:"8",y1:"2",y2:"6",key:"18kwsl"}],["line",{x1:"3",x2:"21",y1:"10",y2:"10",key:"xt86sb"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]),Ss=be("Calendar",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2",key:"eu3xkr"}],["line",{x1:"16",x2:"16",y1:"2",y2:"6",key:"m3sa8f"}],["line",{x1:"8",x2:"8",y1:"2",y2:"6",key:"18kwsl"}],["line",{x1:"3",x2:"21",y1:"10",y2:"10",key:"xt86sb"}]]),fu=be("CheckCircle",[["path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14",key:"g774vq"}],["polyline",{points:"22 4 12 14.01 9 11.01",key:"6xbx8j"}]]),zw=be("CheckSquare",[["polyline",{points:"9 11 12 14 22 4",key:"19ybtz"}],["path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11",key:"1jnkn4"}]]),fr=be("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),Mm=be("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),gu=be("Clapperboard",[["path",{d:"M4 11v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8H4Z",key:"1hxvyx"}],["path",{d:"m4 11-.88-2.87a2 2 0 0 1 1.33-2.5l11.48-3.5a2 2 0 0 1 2.5 1.32l.87 2.87L4 11.01Z",key:"1vz1k2"}],["path",{d:"m6.6 4.99 3.38 4.2",key:"192ida"}],["path",{d:"m11.86 3.38 3.38 4.2",key:"hhucvz"}]]),bu=be("ClipboardCheck",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m9 14 2 2 4-4",key:"df797q"}]]),Ow=be("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]),tg=be("Coins",[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]]),Pm=be("Columns",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["line",{x1:"12",x2:"12",y1:"3",y2:"21",key:"1efggb"}]]),$w=be("Contact",[["path",{d:"M17 18a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2",key:"1mghuy"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["circle",{cx:"12",cy:"10",r:"2",key:"1yojzk"}],["line",{x1:"8",x2:"8",y1:"2",y2:"4",key:"1ff9gb"}],["line",{x1:"16",x2:"16",y1:"2",y2:"4",key:"1ufoma"}]]),Bw=be("Cpu",[["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"9",y:"9",width:"6",height:"6",key:"o3kz5p"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}
13],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]]),Fw=be("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]),yu=be("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]),zr=be("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]),Lm=be("EyeOff",[["path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24",key:"1jxqfv"}],["path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68",key:"9wicm4"}],["path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61",key:"1jreej"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]),_w=be("FileEdit",[["path",{d:"M4 13.5V4a2 2 0 0 1 2-2h8.5L20 7.5V20a2 2 0 0 1-2 2h-5.5",key:"1bg6eb"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["path",{d:"M10.42 12.61a2.1 2.1 0 1 1 2.97 2.97L7.95 21 4 22l.99-3.95 5.43-5.44Z",key:"1rgxu8"}]]),Ww=be("FilePlus",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["line",{x1:"12",x2:"12",y1:"18",y2:"12",key:"1tsf04"}],["line",{x1:"9",x2:"15",y1:"15",y2:"15",key:"110plj"}]]),Id=be("FileSearch",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7.5L14.5 2H6a2 2 0 0 0-2 2v3",key:"am10z3"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["path",{d:"M5 17a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"ychnub"}],["path",{d:"m9 18-1.5-1.5",key:"1j6qii"}]]),Mn=be("FileText",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["line",{x1:"16",x2:"8",y1:"13",y2:"13",key:"14keom"}],["line",{x1:"16",x2:"8",y1:"17",y2:"17",key:"17nazh"}],["line",{x1:"10",x2:"8",y1:"9",y2:"9",key:"1a5vjj"}]]),Uw=be("FileX",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["line",{x1:"9.5",x2:"14.5",y1:"12.5",y2:"17.5",key:"izs6du"}],["line",{x1:"14.5",x2:"9.5",y1:"12.5",y2:"17.5",key:"1lehlj"}]]),Hw=be("File",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}]]),qw=be("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]),sg=be("Flame",[["path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",key:"96xj49"}]]),Vw=be("FolderKanban",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M12 10v2",key:"hh53o1"}],["path",{d:"M16 10v6",key:"1d6xys"}]]),ng=be("FolderPlus",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["line",{x1:"12",x2:"12",y1:"10",y2:"16",key:"3c25pp"}],["line",{x1:"9",x2:"15",y1:"13",y2:"13",key:"10hoct"}]]),Yw=be("Gamepad2",[["line",{x1:"6",x2:"10",y1:"11",y2:"11",key:"1gktln"}],["line",{x1:"8",x2:"8",y1:"9",y2:"13",key:"qnk9ow"}],["line",{x1:"15",x2:"15.01",y1:"12",y2:"12",key:"krot7o"}],["line",{x1:"18",x2:"18.01",y1:"10",y2:"10",key:"1lcuu1"}],["path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z",key:"mfqc10"}]]),rg=be("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]),Gw=be("GitCompare",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]]),Or=be("GitMerge",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]]),Kw=be("GitPullRequest",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]]),ag=be("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"2",x2:"22",y1:"12",y2:"12",key:"1dnqot"}],["path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z",key:"nb9nel"}]]),Yr=be("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]),og=be("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]),Qw=be("Home",[["path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"y5dka4"}],["polyline",{points:"9 22 9 12 15 12 15 22",key:"e2us08"}]]),ig=be("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),ju=be("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]),wa=be("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]),Jw=be("Landmark",[["line",{x1:"3",x2:"21",y1:"22",y2:"22",key:"j8o0r"}],["line",{x1:"6",x2:"6",y1:"18",y2:"11",key:"10tf0k"}],["line",{x1:"10",x2:"10",y1:"18",y2:"11",key:"54lgf6"}],["line",{x1:"14",x2:"14",y1:"18",y2:"11",key:"380y"}],["line",{x1:"18",x2:"18",y1:"18",y2:"11",key:"1kevvc"}],["polygon",{points:"12 2 20 7 4 7",key:"jkujk7"}]]),Zw=be("Layers",[["polygon",{points:"12 2 2 7 12 12 22 7 12 2",key:"1b0ttc"}],["polyline",{points:"2 17 12 22 22 17",key:"imjtdl"}],["polyline",{points:"2 12 12 17 22 12",key:"5dexcv"}
13]]),lg=be("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]),cg=be("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]),Zi=be("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]),zm=be("List",[["line",{x1:"8",x2:"21",y1:"6",y2:"6",key:"7ey8pc"}],["line",{x1:"8",x2:"21",y1:"12",y2:"12",key:"rjfblc"}],["line",{x1:"8",x2:"21",y1:"18",y2:"18",key:"c3b1m8"}],["line",{x1:"3",x2:"3.01",y1:"6",y2:"6",key:"1g7gq3"}],["line",{x1:"3",x2:"3.01",y1:"12",y2:"12",key:"1pjlvk"}],["line",{x1:"3",x2:"3.01",y1:"18",y2:"18",key:"28t2mc"}]]),Xw=be("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]),eN=be("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]),tN=be("Merge",[["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M12 2v10.3a4 4 0 0 1-1.172 2.872L4 22",key:"1hyw0i"}],["path",{d:"m20 22-5-5",key:"1m27yz"}]]),_l=be("MessageCircle",[["path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z",key:"v2veuj"}]]),sN=be("MicOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]),nN=be("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]),Wl=be("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),dg=be("MonitorSmartphone",[["path",{d:"M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8",key:"10dyio"}],["path",{d:"M10 19v-3.96 3.15",key:"1irgej"}],["path",{d:"M7 19h5",key:"qswx4l"}],["rect",{width:"6",height:"10",x:"16",y:"12",rx:"2",key:"1egngj"}]]),ug=be("MoonStar",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}],["path",{d:"M19 3v4",key:"vgv24u"}],["path",{d:"M21 5h-4",key:"1wcg1f"}]]),rN=be("MoreVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]),Om=be("Package",[["path",{d:"M16.5 9.4 7.55 4.24",key:"10qotr"}],["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]),mg=be("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",key:"1xcu5"}],["circle",{cx:"17.5",cy:"10.5",r:".5",key:"736e4u"}],["circle",{cx:"8.5",cy:"7.5",r:".5",key:"clrty"}],["circle",{cx:"6.5",cy:"12.5",r:".5",key:"1s4xz9"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]),pg=be("Palmtree",[["path",{d:"M13 8c0-2.76-2.46-5-5.5-5S2 5.24 2 8h2l1-1 1 1h4",key:"foxbe7"}],["path",{d:"M13 7.14A5.82 5.82 0 0 1 16.5 6c3.04 0 5.5 2.24 5.5 5h-3l-1-1-1 1h-3",key:"18arnh"}],["path",{d:"M5.89 9.71c-2.15 2.15-2.3 5.47-.35 7.43l4.24-4.25.7-.7.71-.71 2.12-2.12c-1.95-1.96-5.27-1.8-7.42.35z",key:"epoumf"}],["path",{d:"M11 15.5c.5 2.5-.17 4.5-1 6.5h4c2-5.5-.5-12-1-14",key:"ft0feo"}]]),aN=be("PauseCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]]),xg=be("Pause",[["rect",{width:"4",height:"16",x:"6",y:"4",key:"iffhe4"}],["rect",{width:"4",height:"16",x:"14",y:"4",key:"sjin7j"}]]),Na=be("Pencil",[["path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z",key:"5qss01"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]),oN=be("PhoneIncoming",[["polyline",{points:"16 2 16 8 22 8",key:"1ygljm"}],["line",{x1:"22",x2:"16",y1:"2",y2:"8",key:"1xzwqn"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]),iN=be("PhoneMissed",[["line",{x1:"22",x2:"16",y1:"2",y2:"8",key:"1xzwqn"}],["line",{x1:"16",x2:"22",y1:"2",y2:"8",key:"13zxdn"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]),lN=be("PhoneOff",[["path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m
13-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91",key:"z86iuo"}],["line",{x1:"22",x2:"2",y1:"2",y2:"22",key:"11kh81"}]]),cN=be("PhoneOutgoing",[["polyline",{points:"22 8 22 2 16 2",key:"1g204g"}],["line",{x1:"16",x2:"22",y1:"8",y2:"2",key:"1ggias"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]),hg=be("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]),fg=be("Printer",[["polyline",{points:"6 9 6 2 18 2 18 9",key:"1306q4"}],["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["rect",{width:"12",height:"8",x:"6",y:"14",key:"5ipwut"}]]),dN=be("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]),ul=be("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]),gg=be("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]),ml=be("Save",[["path",{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z",key:"1owoqh"}],["polyline",{points:"17 21 17 13 7 13 7 21",key:"1md35c"}],["polyline",{points:"7 3 7 8 15 8",key:"8nz8an"}]]),bg=be("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]),vu=be("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),wu=be("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]),yg=be("ShieldAlert",[["path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",key:"3xmgem"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]),Xi=be("ShieldCheck",[["path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",key:"3xmgem"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),uN=be("ShieldOff",[["path",{d:"M19.69 14a6.9 6.9 0 0 0 .31-2V5l-8-3-3.16 1.18",key:"ungvgc"}],["path",{d:"M4.73 4.73 4 5v7c0 6 8 10 8 10a20.29 20.29 0 0 0 5.62-4.38",key:"1qf5yw"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]),$m=be("Shield",[["path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",key:"3xmgem"}]]),mN=be("Star",[["polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2",key:"8f66p6"}]]),pN=be("StickyNote",[["path",{d:"M15.5 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V8.5L15.5 3Z",key:"1wis1t"}],["path",{d:"M15 3v6h6",key:"edgan2"}
13]]),Nu=be("Store",[["path",{d:"m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7",key:"ztvudi"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["path",{d:"M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4",key:"2ebpfo"}],["path",{d:"M2 7h20",key:"1fcdvo"}],["path",{d:"M22 7v3a2 2 0 0 1-2 2v0a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12v0a2 2 0 0 1-2-2V7",key:"jon5kx"}]]),xN=be("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]),hN=be("Tag",[["path",{d:"M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2Z",key:"14b2ls"}],["path",{d:"M7 7h.01",key:"7u93v4"}]]),gr=be("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]),_r=be("Ticket",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M13 5v2",key:"dyzc3o"}],["path",{d:"M13 17v2",key:"1ont0d"}],["path",{d:"M13 11v2",key:"1wjjxi"}]]),zs=be("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]),Xo=be("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]),jg=be("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5v0a5.5 5.5 0 0 1-5.5 5.5H11",key:"llx8ln"}]]),pl=be("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]),fN=be("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]),Ul=be("UserCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]),gN=be("UserMinus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]),vg=be("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]),ei=be("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]),Hl=be("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]),bN=be("Volume2",[["polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5",key:"16drj5"}],["path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07",key:"ltjumu"}],["path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14",key:"1kegas"}]]),yN=be("Wallet",[["path",{d:"M21 12V7H5a2 2 0 0 1 0-4h14v4",key:"195gfw"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h16v-5",key:"195n9w"}],["path",{d:"M18 12a2 2 0 0 0 0 4h4v-4Z",key:"vllfpd"}]]),jN=be("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]),vN=be("XCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]),Ao=be("Zap",[["polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2",key:"45s27k"}]]),wN={type:"spring",stiffness:380,damping:34},NN={type:"spring",stiffness:500,damping:15};function kN(t){return t?{initial:{opacity:0}
13,animate:{opacity:1,transition:{duration:.15}},exit:{opacity:0,transition:{duration:.1}}}:{initial:{scale:0,opacity:0},animate:{scale:1,opacity:1,transition:NN},exit:{scale:0,opacity:0,transition:{duration:.12}}}}const xi=-12;function SN(t){return t?{rotate:0}:{rotate:[0,xi,-xi,xi,-xi,0],transition:{duration:.5}}}function CN(t,s){return t?{initial:{opacity:0},animate:{opacity:1,transition:{duration:.12}},exit:{opacity:0,transition:{duration:.12}}}:{initial:{opacity:0,y:12},animate:{opacity:1,y:0,transition:{...wN,delay:Math.min(s,8)*.04}},exit:{opacity:0,scale:.85,x:24,transition:{duration:.18,ease:"easeIn"}}}}function TN(t){if(!t)return 0;if(typeof t=="number")return t;if(typeof t=="string"){const s=new Date(t);return isNaN(s.getTime())?0:s.getTime()}if(typeof t.toMillis=="function")try{return t.toMillis()}catch(s){return console.error("Error calling toMillis:",s),0}return typeof t.seconds=="number"?t.seconds*1e3:typeof t._seconds=="number"?t._seconds*1e3:0}function xl(t){const s=TN(t);if(!s)return"";const n=Date.now()-s,r=Math.floor(n/1e3);if(r<60)return"now";const a=Math.floor(r/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);if(o<24)return`${o}h`;const i=Math.floor(o/24);return i<7?`${i}d`:new Date(s).toLocaleDateString()}function AN(t){switch(t){case"ticket_assigned_department":case"ticket_assigned_user":return{Icon:Dw,bg:"rgba(236,203,123,0.28)",fg:"#9a7d2e"};case"team_dm":case"customer_message":return{Icon:_l,bg:"rgba(126,204,238,0.15)",fg:"var(--primary)"};case"ticket_status":return{Icon:bu,bg:"rgba(236,203,123,0.28)",fg:"#9a7d2e"};case"ticket_followed":return{Icon:Xf,bg:"rgba(236,203,123,0.28)",fg:"#9a7d2e"};case"ticket_reminder":return{Icon:Zf,bg:"rgba(245,158,11,0.20)",fg:"#b45309"};case"release":return{Icon:ul,bg:"rgba(134,217,168,0.22)",fg:"#2e7d4f"};case"job_report":return{Icon:tu,bg:"rgba(139,92,246,0.18)",fg:"#7c3aed"};case"pr_ready":return{Icon:Kw,bg:"rgba(134,217,168,0.22)",fg:"#2e7d4f"};case"ai_pipeline":return{Icon:Fl,bg:"rgba(239,68,68,0.15)",fg:"#b91c1c"};case"theme_sync":return{Icon:Or,bg:"rgba(239,68,68,0.15)",fg:"#b91c1c"};default:return{Icon:Dn,bg:"var(--muted)",fg:"var(--muted-foreground)"}}}const EN={display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},IN=/(https?:\/\/[^\s]+)/g;function RN(t){return t&&t.split(IN).map((s,n)=>/^https?:\/\//i.test(s)?e.jsx("a",{href:s,onClick:r=>{r.stopPropagation(),r.preventDefault(),window.open(s,"_blank","noopener,noreferrer")},style:{color:"var(--primary)",textDecoration:"underline",wordBreak:"break-all"},children:s},n):e.jsx(ee.Fragment,{children:s},n))}function DN({n:t,index:s,onActivate:n,onDismiss:r}){const a=!!Ml(),{Icon:o,bg:i,fg:d}=AN(t.type),[m,p]=l.useState(!1),[c,u]=l.useState(!1),x=Array.isArray(t.updates)?t.updates:[],h=t.updateCount??x.length,b=h>1&&x.length>1;return e.jsxs(st.div,{variants:CN(a,s),initial:!1,animate:"animate",onClick:()=>n(t),role:"button",tabIndex:0,className:"relative flex text-left border-b border-border hover:bg-muted/50 transition-colors",style:{gap:12,paddingLeft:16,paddingRight:16,paddingTop:14,paddingBottom:14,cursor:"pointer",background:t.seen?void 0:"rgba(126,204,238,0.05)"},children:[!t.seen&&e.jsx("span",{style:{position:"absolute",left:0,top:0,bottom:0,width:3,background:"var(--primary)",borderRadius:"0 2px 2px 0"}}),e.jsx("button",{onClick:f=>{f.stopPropagation(),r(t.id)},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),"aria-label":"Dismiss notification",title:"Dismiss",className:"flex items-center justify-center rounded-full transition-all active:scale-90",style:{width:40,height:40,flexShrink:0,border:"none",cursor:"pointer",background:m?"rgba(235,87,87,0.15)":i,color:d},children:m?e.jsx("span",{style:{fontSize:20,lineHeight:1},children:"ð¥"}):e.jsx(o,{style:{width:18,height:18},strokeWidth:2})}),e.jsxs("div",{style:{minWidth:0,flex:1},children:[e.jsxs("div",{className:"flex items-baseline justify-between",style:{gap:8},children:[e.jsx("span",{className:"truncate text-card-foreground",style:{fontSize:14,fontWeight:t.seen?500:600},children:t.title}),e.jsx("span",{className:"text-muted-foreground",style:{fontSize:11,flexShrink:0,fontVariantNumeric:"tabular-nums"},children:xl(t.createdAt)})]}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:13,lineHeight:1.4,marginTop:3,...EN},children:RN(t.body)}),b&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:f=>{f.stopPropagation(),u(g=>!g)},className:"flex items-center transition-colors",style:{marginTop:8,gap:5,padding:"3px 9px",borderRadius:999,border:"none",background:"rgba(126,204,238,0.15)",color:"var(--primary)",fontSize:11,fontWeight:600,cursor:"pointer"},children:[h," updates",e.jsx(Ot,{style:{width:13,height:13,transform:c?"rotate(180deg)":"none",transition:"transform 0.18s ease"},strokeWidth:2.5})]}),c&&e.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6},children:[...x].reverse().map((f,g)=>e.jsxs("div",{className:"flex items-baseline",style:{gap:8},children:[e.jsx("span",{style:{width:5,height:5,borderRadius:"50%",background:"var(--muted-foreground)",flexShrink:0,marginTop:5}}),e.jsx("span",{className:"text-card-foreground",style:{fontSize:12.5,flex:1,minWidth:0},children:f.summary}),e.jsx("span",{className:"text-muted-foreground",style:{fontSize:10.5,flexShrink:0,fontVariantNumeric:"tabular-nums"},children:xl(f.at)})]},g))})]})]})]})}const MN={paddingTop:80,paddingBottom:80,paddingLeft:24,paddingRight:24},PN={width:56,height:56,marginBottom:16,background:"rgba(126,204,238,0.12)",color:"var(--primary)"},LN={width:28,height:28},zN={paddingLeft:16,paddingRight:16,paddingTop:10,paddingBottom:10},ON={fontSize:14,fontWeight:600},$N={fontSize:12,marginTop:4},BN={fontSize:12,fontWeight:500},FN={fontSize:12,fontWeight:600};function _N(){const{notifications:t,unreadCount:s,markRead:n,markAllRead:r,dismiss:a,deepLink:o,closeDrawer:i,openDrawer:d}=$n(),m=p=>{var c,u;if(p.read||n(p.id),p.type==="team_dm"&&((c=p.entity)!=null&&c.threadId)){d("messages",p.entity.threadId);return}i(),(u=p.target)!=null&&u.screen&&o(p.target)};return t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center text-center",style:MN,children:[e.jsx("span",{className:"flex items-center justify-center rounded-full",style:PN,children:e.jsx(Ns,{style:LN,strokeWidth:1.75})}),e.jsx("p",{className:"text-card-foreground",style:ON,children:"You're all caught up"}),e.jsx("p",{className:"text-muted-foreground",style:$N,children:"New notifications will appear here."})]}):e.jsxs("div",{className:"flex flex-col",children:[s>0&&e.jsxs("div",{className:"flex items-center justify-between border-b border-border bg-muted/30",style:zN,children:[e.jsxs("span",{className:"text-muted-foreground",style:BN,children:[s," unread"]}),e.jsx("button",{onClick:()=>r(),className:"text-primary active:scale-95 transition-transform",style:FN,children:"Mark all read"})]}),t.map((p,c)=>e.jsx(DN,{n:p,index:c,onActivate:m,onDismiss:a}
13,p.id))]})}function Rd({text:t,isOwn:s,sender:n,timestamp:r,status:a="sent"}){const o=b=>{const f=b.indexOf(":");if(f>0&&f<30){const g=b.substring(0,f).trim();if(g&&!g.includes("/")&&!g.includes("."))return{name:g,messageText:b.substring(f+1).trim()}}return{name:null,messageText:b}},{name:i,messageText:d}=s?o(t):{name:null,messageText:t},m=s?i:n,p=s?d:t,c=(b,f,g)=>e.jsx("a",{href:b,target:"_blank",rel:"noopener noreferrer",className:`font-bold hover:underline ${g?"text-primary-foreground":"text-primary"}`,children:"LINK ð"},`link-${f}`),u=b=>{const f=[];let g=0,y=0;const j=/<(https?:\/\/[^|>]+)(?:\|[^>]+)??>|((?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_+.~#?&/=]*))/g;let v;for(;(v=j.exec(b))!==null;){if(v.index>g&&f.push(b.substring(g,v.index)),v[1]){const T=v[1];f.push(c(T,y++,s))}else if(v[2]){let T=v[2];T.match(/^https?:\/\//)||(T="https://"+T),v[2].includes("@")&&!v[2].includes("://")?f.push(v[0]):/\.(com|org|net|edu|gov|io|co|dev|app|ai|tv|me|info|biz)/.test(v[2])?f.push(c(T,y++,s)):f.push(v[0])}g=v.index+v[0].length}return g<b.length&&f.push(b.substring(g)),f.length>0?f:b},x=B0(p),h=F0(p);return e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:`flex ${s?"justify-end":"justify-start"} px-4`,children:e.jsxs("div",{className:`max-w-[75%] ${s?"items-end":"items-start"} flex flex-col`,children:[m&&e.jsx("span",{className:"text-muted-foreground mb-1 px-3",children:m}),e.jsx("div",{className:`rounded-[20px] px-4 py-2.5 ${s?"bg-primary text-primary-foreground rounded-br-md":"bg-muted text-foreground rounded-bl-md"}`,children:e.jsx("p",{className:"leading-relaxed whitespace-pre-wrap",children:u(p)})}),e.jsxs("div",{className:"flex items-center gap-1 mt-1 px-3",children:[e.jsx("span",{className:"text-muted-foreground",children:r}),s&&a==="processing"&&e.jsx("span",{className:"text-primary",children:"⢠Processing"}),s&&a==="sending"&&e.jsx("span",{className:"text-muted-foreground",children:"⢠Sending..."})]})]})}),x&&e.jsx("div",{className:"relative w-full mt-2",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{src:`https://www.loom.com/embed/${x}`,allowFullScreen:!0,className:"absolute top-0 left-0 w-full h-full"})}),h&&e.jsx("div",{className:"relative w-full mt-2",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${h}`,allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"absolute top-0 left-0 w-full h-full"})})]})}function WN(t,s){const[n,r]=l.useState([]);return l.useEffect(()=>{if(!t){r([]);return}const a=Il("dmThreads",[Ve("participants","array-contains",t),Nt("lastMessageAt","desc")],o=>r(o));return()=>a()},[t,s]),n}function UN(t,s){const[n,r]=l.useState([]);return l.useEffect(()=>{if(!t){r([]);return}const a=Il("dmMessages",[Ve("threadId","==",t),Nt("createdAt","asc")],o=>r(o));return()=>a()},[t,s]),n}function HN(t){return l.useCallback(async(s,n)=>re("sendDmMessage",{toUid:s,text:n}),[t])}function qN(t){const s=l.useCallback(async n=>{if(!t){console.error("[useMarkDmRead] Token is undefined");return}try{await re("markDmThreadRead",{threadId:n},t)}catch(r){console.error("[useMarkDmRead] failed:",r)}},[t]);return t?s:()=>{}}function VN(t,s){const[n,r]=l.useState([]);return l.useEffect(()=>{let a=!1;return R0("staffDirectory",[Ve("active","==",!0)]).then(o=>{a||r(o.map(i=>({uid:i.uid||i.id,email:i.email,displayName:i.displayName||i.email,departments:i.departments})))}).catch(o=>console.error("[useStaffDirectory] failed:",o)),()=>{a=!0}},[t,s]),n}const ql="rgba(126,204,238,0.15)";function YN(t,s){return[t,s].sort().join("_")}function ku({name:t,size:s=36}){return e.jsx("span",{className:"flex items-center justify-center rounded-full text-primary",style:{width:s,height:s,flexShrink:0,background:ql,fontWeight:600,fontSize:s*.4},children:t.charAt(0).toUpperCase()})}function GN(){const{setActiveThreadId:t}=$n(),[s,n]=l.useState("team");return e.jsxs("div",{className:"flex flex-col",children:[e.jsx("div",{className:"flex border-b border-border",style:{padding:8,gap:6},children:["team","customers"].map(r=>e.jsx("button",{onClick:()=>{r==="customers"&&t(null),n(r)},className:"flex-1 transition-colors",style:{padding:"6px 10px",borderRadius:8,fontSize:12.5,fontWeight:600,border:"none",cursor:"pointer",background:s===r?"var(--primary)":"transparent",color:s===r?"#fff":"var(--muted-foreground)"},children:r==="team"?"Team":"Customers"},r))}),s==="customers"?e.jsx(nk,{}):e.jsx(KN,{})]})}
13function KN(){const{uid:t,token:s,activeThreadId:n,setActiveThreadId:r}=$n(),a=WN(t,s),[o,i]=l.useState(!1);if(n)return e.jsx(ZN,{threadId:n,onBack:()=>r(null)});if(o)return e.jsx(XN,{onClose:()=>i(!1)});const d={paddingLeft:16,paddingRight:16,paddingTop:10,paddingBottom:10},m={gap:4,fontSize:12,fontWeight:600};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border bg-muted/30",style:d,children:[e.jsxs("span",{className:"text-muted-foreground",style:{fontSize:12,fontWeight:500},children:[a.length," conversation",a.length===1?"":"s"]}),e.jsxs("button",{onClick:()=>i(!0),className:"flex items-center text-primary active:scale-95 transition-transform",style:m,children:[e.jsx(Ut,{style:{width:14,height:14},strokeWidth:2.5})," New"]})]}),a.length===0?e.jsx(QN,{setPicking:i}):a.map(p=>{var h;const c=p.participants.find(b=>b!==t)||"",u=((h=p.participantNames)==null?void 0:h[c])||"Teammate",x=p.lastSenderUid!==t;return e.jsx(JN,{onClick:()=>r(p.threadId),name:u,lastMessageAt:p.lastMessageAt,lastMessage:p.lastMessage,isUnread:x},p.id)})]})}const QN=({setPicking:t})=>e.jsxs("div",{className:"flex flex-col items-center justify-center text-center",style:{paddingTop:72,paddingBottom:72,paddingLeft:24,paddingRight:24},children:[e.jsx("span",{className:"flex items-center justify-center rounded-full",style:{width:56,height:56,marginBottom:16,background:ql,color:"var(--primary)"},children:e.jsx(mn,{style:{width:26,height:26},strokeWidth:1.75})}),e.jsx("p",{className:"text-card-foreground",style:{fontSize:14,fontWeight:600},children:"No messages yet"}),e.jsx("button",{onClick:()=>t(!0),className:"text-primary",style:{fontSize:13,marginTop:6,fontWeight:600},children:"Start a conversation"})]}),JN=({onClick:t,name:s,lastMessageAt:n,lastMessage:r,isUnread:a})=>e.jsxs("button",{onClick:t,className:"flex text-left border-b border-border hover:bg-muted/50 transition-colors",style:{gap:12,width:"100%",paddingLeft:16,paddingRight:16,paddingTop:12,paddingBottom:12},children:[e.jsx(ku,{name:s}),e.jsxs("div",{style:{minWidth:0,flex:1},children:[e.jsxs("div",{className:"flex items-baseline justify-between",style:{gap:8},children:[e.jsx("span",{className:"truncate text-card-foreground",style:{fontSize:14,fontWeight:600},children:s}),e.jsx("span",{className:"text-muted-foreground",style:{fontSize:11,flexShrink:0},children:xl(n)})]}),e.jsx("p",{className:"truncate",style:{fontSize:13,marginTop:2,color:a?"var(--card-foreground)":"var(--muted-foreground)",fontWeight:a?500:400},children:r})]})]});function ZN({threadId:t,onBack:s}){var f;const{uid:n,token:r}=$n(),a=UN(t,r),o=HN(r),i=qN(r),[d,m]=l.useState(""),[p,c]=l.useState(!1),u=l.useRef(null),x=l.useMemo(()=>{var y;const g=(y=a.find(j=>j.fromUid!==n))==null?void 0:y.fromUid;return g||t.split("_").find(j=>j!==n)||""},[a,n,t]),h=((f=a.find(g=>g.fromUid===x))==null?void 0:f.fromName)||"Teammate";l.useEffect(()=>{t&&i(t)},[t,a.length,i]),l.useEffect(()=>{var g;(g=u.current)==null||g.scrollIntoView({behavior:"smooth"})},[a.length]);const b=async()=>{const g=d.trim();if(!(!g||!x||p)){c(!0),m("");try{await o(x,g)}catch(y){console.error("[MessagesTab] send failed:",y),m(g)}finally{c(!1)}}};return e.jsxs("div",{className:"flex flex-col",style:{height:"100%"},children:[e.jsxs("div",{className:"flex items-center border-b border-border",style:{gap:8,paddingLeft:8,paddingRight:12,paddingTop:8,paddingBottom:8},children:[e.jsx("button",{onClick:s,className:"text-foreground hover:bg-muted/50 rounded-full transition-all active:scale-95",style:{padding:6},"aria-label":"Back to conversations",children:e.jsx(dt,{style:{width:20,height:20},strokeWidth:2})}),e.jsx(ku,{name:h,size:28}),e.jsx("span",{className:"text-card-foreground",style:{fontSize:14,fontWeight:600},children:h})]}),e.jsxs("div",{className:"flex-1",style:{overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:8},children:[a.map(g=>e.jsx(Rd,{text:g.text,isOwn:g.fromUid===n,sender:g.fromName,timestamp:xl(g.createdAt)},g.id)),e.jsx("div",{ref:u})]}),e.jsxs("div",{className:"flex border-t border-border",style:{gap:8,padding:8,alignItems:"flex-end"},children:[e.jsx("textarea",{value:d,onChange:g=>m(g.target.value),onKeyDown:g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),b())},rows:1,placeholder:"Messageâ¦",className:"flex-1 rounded-2xl border border-border bg-card text-card-foreground",style:{resize:"none",padding:"8px 12px",fontSize:14,maxHeight:112,outline:"none"}}),e.jsx("button",{onClick:b,disabled:!d.trim()||p,className:"rounded-full bg-primary transition-opacity",style:{padding:9,color:"#fff",opacity:!d.trim()||p?.4:1},"aria-label":"Send",children:e.jsx(An,{style:{width:18,height:18},strokeWidth:2})})]})]})}function XN({onClose:t}
13){const{uid:s,token:n,setActiveThreadId:r}=$n(),a=VN(!0,n),[o,i]=l.useState(""),d=a.filter(m=>m.uid!==s).filter(m=>m.displayName.toLowerCase().includes(o.toLowerCase()));return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center border-b border-border",style:{gap:8,paddingLeft:8,paddingRight:12,paddingTop:8,paddingBottom:8},children:[e.jsx("button",{onClick:t,className:"text-foreground hover:bg-muted/50 rounded-full transition-all active:scale-95",style:{padding:6},"aria-label":"Back",children:e.jsx(dt,{style:{width:20,height:20},strokeWidth:2})}),e.jsx("input",{autoFocus:!0,value:o,onChange:m=>i(m.target.value),placeholder:"Search teammatesâ¦",className:"flex-1 text-card-foreground",style:{background:"transparent",fontSize:14,outline:"none"}})]}),d.map(m=>e.jsxs("button",{onClick:()=>{s&&r(YN(s,m.uid))},className:"flex items-center border-b border-border hover:bg-muted/50 transition-colors",style:{gap:12,width:"100%",textAlign:"left",paddingLeft:16,paddingRight:16,paddingTop:12,paddingBottom:12},children:[e.jsx(ku,{name:m.displayName}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{className:"truncate text-card-foreground",style:{fontSize:14,fontWeight:500},children:m.displayName}),e.jsx("div",{className:"truncate text-muted-foreground",style:{fontSize:12},children:m.email})]})]},m.uid)),d.length===0&&e.jsx("p",{className:"text-muted-foreground text-center",style:{fontSize:13,paddingTop:40,paddingBottom:40},children:"No teammates found."})]})}function ek(t){const[s,n]=l.useState([]),[r,a]=l.useState(!0);return l.useEffect(()=>{let o=!1;return a(!0),re("listAllSlackChannels",{}).then(i=>{if(o)return;const d=(i==null?void 0:i.channels)||[];n(d.filter(m=>(m==null?void 0:m.id)&&(m==null?void 0:m.name)&&!m.is_archived).map(m=>({id:m.id,name:m.name})).sort((m,p)=>m.name.localeCompare(p.name)))}).catch(i=>console.error("[useSlackChannels] failed:",i)).finally(()=>!o&&a(!1)),()=>{o=!0}},[t]),{channels:s,loading:r}}const tk={width:"100%",background:"transparent",fontSize:14,outline:"none"},sk={fontSize:13,paddingTop:40,paddingBottom:40};function Bm(t){return e.jsx("p",{className:"text-muted-foreground text-center",style:sk,children:t})}function nk(){const{token:t}=$n(),{channels:s,loading:n}=ek(t),[r,a]=l.useState(""),[o,i]=l.useState(null);if(o)return e.jsx(rk,{channel:o,onBack:()=>i(null)});const d=s.filter(m=>m.name.toLowerCase().includes(r.toLowerCase())).slice(0,60);return e.jsxs("div",{className:"flex flex-col",children:[e.jsx("div",{className:"border-b border-border",style:{padding:"10px 12px"},children:e.jsx("input",{autoFocus:!0,value:r,onChange:m=>a(m.target.value),placeholder:"Search a client channelâ¦",className:"text-card-foreground",style:tk})}),n&&Bm("Loading channelsâ¦"),!n&&d.map(m=>e.jsxs("button",{onClick:()=>i(m),className:"flex items-center border-b border-border hover:bg-muted/50 transition-colors",style:{gap:10,width:"100%",textAlign:"left",paddingLeft:16,paddingRight:16,paddingTop:11,paddingBottom:11},children:[e.jsx("span",{className:"flex items-center justify-center rounded-full text-primary",style:{width:32,height:32,flexShrink:0,background:ql},children:e.jsx(Uo,{style:{width:16,height:16},strokeWidth:2.25})}),e.jsxs("span",{className:"truncate text-card-foreground",style:{fontSize:14,fontWeight:500},children:["#",m.name]})]},m.id)),!n&&d.length===0&&Bm("No channels match.")]})}function rk({channel:t,onBack:s}){const{token:n}=$n(),[r,a]=l.useState(""),[o,i]=l.useState(!1),[d,m]=l.useState(null),p=async()=>{const c=r.trim();if(!(!c||o)){i(!0),m(null);try{const u=await re("sendCustomerProjectMessage",{channelId:t.id,channelName:t.name,text:c},n);a(""),m({ok:!0,msg:`Sent to #${t.name}${u!=null&&u.notified?` · notified ${u.notified} customer${u.notified===1?"":"s"}`:" · posted (no app customer to notify)"}`})}catch(u){m({ok:!1,msg:u.message||"Failed to send"})}finally{i(!1)}}};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center border-b border-border",style:{gap:8,paddingLeft:8,paddingRight:12,paddingTop:8,paddingBottom:8},children:[e.jsx("button",{onClick:s,className:"text-foreground hover:bg-muted/50 rounded-full transition-all active:scale-95",style:{padding:6},"aria-label":"Back",children:e.jsx(dt,{style:{width:20,height:20},strokeWidth:2})}),e.jsx("span",{className:"flex items-center justify-center rounded-full text-primary",style:{width:28,height:28,background:ql},children:e.jsx(Uo,{style:{width:15,height:15},strokeWidth:2.25})}),e.jsxs("span",{className:"text-card-foreground truncate",style:{fontSize:14,fontWeight:600},children:["#",t.name]})]}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:12,padding:"10px 16px 0"},children:"Posts to the client's chat and notifies their customers."}),d&&e.jsx("p",{style:{fontSize:12.5,padding:"8px 16px 0",color:d.ok?"#16a34a":"var(--destructive)"},children:d.msg}),e.jsxs("div",{className:"flex",style:{gap:8,padding:12,alignItems:"flex-end"},children:[e.jsx("textarea",{value:r,onChange:c=>a(c.target.value),onKeyDown:c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),p())},rows:2,placeholder:`Message #${t.name}â¦`,className:"flex-1 rounded-2xl border border-border bg-card text-card-foreground",style:{resize:"none",padding:"8px 12px",fontSize:14,maxHeight:140,outline:"none"}}),e.jsx("button",{onClick:p,disabled:!r.trim()||o,className:"rounded-full bg-primary transition-opacity",style:{padding:9,color:"#fff",opacity:!r.trim()||o?.4:1},"aria-label":"Send",children:e.jsx(An,{style:{width:18,height:18},strokeWidth:2})})]})]})}const ak=480;function ok(){const{isOpen:t,closeDrawer:s,tab:n,setTab:r,isAdmin:a,unreadCount:o,messagesUnread:i,setActiveThreadI
13d:d}=$n(),m=!!Ml();l.useEffect(()=>{if(!t)return;const h=f=>{f.key==="Escape"&&s()};window.addEventListener("keydown",h);const b=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{window.removeEventListener("keydown",h),document.body.style.overflow=b}},[t,s]);const p=ee.useRef(null),c=h=>{p.current=h.clientX},u=h=>{const b=p.current;b!=null&&h.clientX-b>80&&s(),p.current=null},x=a;return k0.createPortal(e.jsxs("div",{className:"fixed inset-0",style:{zIndex:100,pointerEvents:t?"auto":"none"},children:[e.jsx("div",{onClick:s,className:"absolute inset-0",style:{background:"rgba(0,0,0,0.4)",backdropFilter:"blur(2px)",opacity:t?1:0,transition:m?"opacity 0.12s linear":"opacity 0.25s ease",pointerEvents:t?"auto":"none"}}),e.jsxs("aside",{onPointerDown:c,onPointerUp:u,className:"absolute bg-card flex flex-col",style:{pointerEvents:t?"auto":"none",transform:`translateX(${t?0:ak}px)`,transition:m?"transform 0.12s linear":t?"transform 0.36s cubic-bezier(0.34, 1.4, 0.5, 1)":"transform 0.26s cubic-bezier(0.4, 0, 1, 1)",willChange:"transform",top:0,right:0,height:"100%",width:"min(420px, 92vw)",boxShadow:"-12px 0 40px rgba(0,0,0,0.18)"},role:"dialog","aria-label":"Notifications",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border",style:{paddingTop:"max(env(safe-area-inset-top, 0px), 2.25rem)",paddingLeft:16,paddingRight:12,paddingBottom:12},children:[e.jsx("h2",{className:"text-card-foreground",style:{fontSize:20,fontWeight:"var(--font-weight-semibold)",letterSpacing:"-0.02em"},children:n==="messages"?"Messages":"Notifications"}),e.jsx("button",{onClick:s,className:"text-foreground hover:bg-muted/50 rounded-full transition-all active:scale-95",style:{padding:8,marginRight:-6},"aria-label":"Close",children:e.jsx(mt,{style:{width:20,height:20},strokeWidth:2})})]}),x&&e.jsxs("div",{className:"flex border-b border-border",children:[e.jsx(Fm,{active:n==="notifications",onClick:()=>{d(null),r("notifications")},icon:e.jsx(Dn,{style:{width:16,height:16},strokeWidth:2}),label:"Notifications",badge:o}),e.jsx(Fm,{active:n==="messages",onClick:()=>r("messages"),icon:e.jsx(mn,{style:{width:16,height:16},strokeWidth:2}),label:"Messages",badge:i})]}),e.jsx("div",{className:"flex-1",style:{overflowY:"auto",overscrollBehavior:"contain"},children:n==="messages"&&x?e.jsx(GN,{}):e.jsx(_N,{})})]})]}),document.body)}function Fm({active:t,onClick:s,icon:n,label:r,badge:a}){return e.jsxs("button",{onClick:s,className:`flex-1 flex items-center justify-center transition-colors ${t?"text-primary":"text-muted-foreground hover:text-card-foreground"}`,style:{gap:6,paddingTop:12,paddingBottom:12,fontSize:13,fontWeight:600,borderBottom:t?"2px solid var(--primary)":"2px solid transparent",marginBottom:-1},children:[n,r,a>0&&e.jsx("span",{className:"flex items-center justify-center rounded-full bg-destructive",style:{minWidth:16,height:16,padding:"0 4px",color:"#fff",fontSize:10,fontWeight:700,lineHeight:1},children:a>9?"9+":a})]})}function ik(t,s,n){const r=l.useRef([]),a=l.useRef(!1);l.useEffect(()=>{if(a.current){a.current=!1;return}const d=r.current;d[d.length-1]!==t&&(d.push(t),d.length>50&&d.shift())},[t]);const o=l.useCallback(()=>{const d=r.current;d.pop();const m=d[d.length-1];m?(a.current=!0,s(m)):n()},[s,n]),i=l.useCallback(()=>{r.current=[],n()},[n]);return{goBack:o,goHome:i}}const yc={},_m=yc==null?void 0:yc.VITE_FCM_VAPID_KEY,Wm="bucky_web_device_id";function lk(){return`web_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function ck(){let t=localStorage.getItem(Wm);return t||(t=lk(),localStorage.setItem(Wm,t)),t}function dk({userId:t,userEmail:s,onDeepLink:n}){l.useEffect(()=>{var i;if(Br.isNativePlatform()||!t)return;if(!_m){console.log("[webPush] VITE_FCM_VAPID_KEY not set â web push disabled");return}if(!("serviceWorker"in navigator)||!("Notification"in window))return;let r=!1;(async()=>{try{const{isSupported:d,getMessaging:m,getToken:p}=await Gs(async()=>{const{isSupported:b,getMessaging:f,getToken:g}=await import("./vendor-firebase-Cr-z2ntb.js").then(y=>y.U);return{isSupported:b,getMessaging:f,getToken:g}},[]);if(!await d())return;const c=await navigator.serviceWorker.register("/firebase-messaging-sw.js");if(await Notification.requestPermission()!=="granted"||r)return;const x=m(),h=await p(x,{vapidKey:_m,serviceWorkerRegistration:c});if(!h||r)return;await qr(ut(ge,"pushNotificationTokens",`${t}_${ck()}`),{fcmToken:h,userId:t,userEmail:s||"",platform:"web",active:!0,updatedAt:ss()},{merge:!0}),console.log("[webPush] registered web FCM token")}catch(d){console.error("[webPush] registration failed:",d)}})();const a=d=>{const m={};
13return Object.entries(d).forEach(([p,c])=>{p.startsWith("param_")?m[p.slice(6)]=c:(p==="projectId"||p==="channelId")&&(m[p]=c)}),m},o=d=>{var m;if(((m=d.data)==null?void 0:m.type)==="NOTIFICATION_CLICK"){const p=d.data.data||{},c=p.screen;if(c&&n){const u=a(p);n({screen:c,params:u})}}};return(i=navigator.serviceWorker)==null||i.addEventListener("message",o),()=>{var d;r=!0,(d=navigator.serviceWorker)==null||d.removeEventListener("message",o)}},[t,s,n])}const wg=l.createContext([]),Ng=l.createContext(null);function uk({value:t,rootHome:s,children:n}){return e.jsx(wg.Provider,{value:t,children:e.jsx(Ng.Provider,{value:s??null,children:n})})}function mk(){return l.useContext(wg)}function pk(){return l.useContext(Ng)}function xk(){const t=mk();return!t||t.length===0?null:e.jsx("div",{className:"flex items-center",style:{gap:5,marginTop:8,minHeight:16,overflow:"hidden"},children:t.map((s,n)=>{const r=n===t.length-1;return e.jsxs(ee.Fragment,{children:[n>0&&e.jsx(Rt,{style:{width:13,height:13,color:"var(--muted-foreground)",flexShrink:0},strokeWidth:2}),s.onClick&&!r?e.jsx("button",{onClick:s.onClick,className:"hover:underline truncate",style:{fontSize:12,fontWeight:500,color:"var(--muted-foreground)",flexShrink:0},children:s.label}):e.jsx("span",{className:"truncate",style:{fontSize:12,fontWeight:r?600:500,color:r?"var(--card-foreground)":"var(--muted-foreground)",minWidth:0},children:s.label})]},`${s.label}-${n}`)})})}const hk="dublin";function fk(){const[t,s]=l.useState("idle"),[n,r]=l.useState(null),[a,o]=l.useState(!1),[i,d]=l.useState(0),[m,p]=l.useState(null),[c,u]=l.useState(null),[x,h]=l.useState(null),[b,f]=l.useState(!1),[g,y]=l.useState(null),j=l.useRef(null),v=l.useRef(null),T=l.useRef(null),k=l.useCallback(async()=>{const R=await re("getVoiceToken");if(!(R!=null&&R.token))throw new Error("No voice token returned");return{token:R.token,callerId:R.callerId}},[]),w=l.useCallback(async()=>{if(j.current)return j.current;const{Device:R}=await Gs(async()=>{const{Device:$}=await import("./twilio-Bb-eHOxP.js");return{Device:$}},__vite__mapDeps([4,2,3])),{token:z,callerId:D}=await k(),L=new R(z,{codecPreferences:["opus","pcmu"],edge:hk});return L.on("tokenWillExpire",async()=>{try{const $=await k();L.updateToken($.token)}catch($){console.error("[voice] token refresh failed:",$)}}),L.on("error",$=>{console.error("[voice] device error:",$),h(($==null?void 0:$.message)||"Voice device error")}),j.current=L,y(D??null),f(!0),L},[k]),I=l.useCallback((R,z)=>{v.current=R,T.current=z,R.on("ringing",()=>s("ringing")),R.on("accept",()=>{var $;s("active"),d(0);const L=(($=R.parameters)==null?void 0:$.CallSid)??null;L&&p(L)});const D=()=>{var q;const L=((q=R.parameters)==null?void 0:q.CallSid)??null,$=T.current;L&&$&&$.logCall!==!1&&u({callSid:L,target:$}),v.current=null,T.current=null,s("idle"),r(null),o(!1),d(0),p(null)};R.on("disconnect",D),R.on("cancel",D),R.on("reject",D),R.on("error",L=>{console.error("[voice] call error:",L),h((L==null?void 0:L.message)||"Call failed"),D()})},[]),A=l.useCallback(async R=>{if(v.current||t!=="idle"){h("You are already on a call.");return}h(null),s("connecting"),r(R);try{const D=await(await w()).connect({params:{To:R.to,...R.ticketId?{ticketId:R.ticketId}:{},...R.clientId?{clientId:R.clientId}:{},...R.contactId?{contactId:R.contactId}:{},...R.logCall===!1?{logCall:"false"}:{}}});I(D,R)}catch(z){console.error("[voice] connect failed:",z),h((z==null?void 0:z.message)||"Could not start the call"),s("idle"),r(null)}},[I,w,t]),E=l.useCallback(()=>{const R=v.current;R&&(s("ending"),R.disconnect())},[]),C=l.useCallback(R=>{const z=v.current,D=R.replace(/[^0-9*#w]/g,"");!z||!D||z.sendDigits(D)},[]),N=l.useCallback(()=>{const R=v.current;if(!R)return;const z=!R.isMuted();R.mute(z),o(z)},[]),S=l.useCallback(()=>u(null),[]),O=l.useCallback(()=>h(null),[]);return l.useEffect(()=>{if(t!=="active")return;const R=window.setInterval(()=>{d(z=>z+1)},1e3);return()=>window.clearInterval(R)},[t]),l.useEffect(()=>()=>{var R,z;(R=v.current)==null||R.disconnect(),(z=j.current)==null||z.destroy(),j.current=null},[]),{phase:t,target:n,isMuted:a,durationSeconds:i,callSid:m,lastCall:c,error:x,isReady:b,callerId:g,startCall:A,hangUp:E,toggleMute:N,sendDigits:C,dismissLastCall:S,clearError:O}}function ti(){const{isAdminDomain:t}=pt(),{isImpersonating:s}=of();return!!t&&!s}const kg=l.createContext(null);function gk({children:t}){const s=fk(),n=ti();return e.jsx(kg.Provider,{value:n?s:null,children:t})}function Vl(){return l.useContext(kg)}function Sg({open:t,call:s,onClose:n,onLinked:r}){const[a,o]=l.useState(""),[i,d]=l.useState([]),[m,p]=l.useState(!1),[c,u]=l.useState(!0),[x,h]=l.useState(null);l.useEffect(()=>{t&&(o(""),d([]),u(!!(s!=null&&s.clientId)),h(null))},[t,s==null?void 0:s.callSid]),l.useEffect(()=>{if(!t)return;const g=y=>{y.key==="Escape"&&n()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t,n]);const b=c&&(s!=null&&s.clientId)?s.clientId:null;l.useEffect(()=>{if(!t)return;const g=a.trim();if(g.length<2){d([]);return}let y=!1;const j=setTimeout(async()=>{p(!0);try{const v=await re("chatSearchTickets",{query:g,...b?{clientId:b}:{}});y||d((v==null?void 0:v.tickets)??[])}catch(v){console.error("[voice] ticket search failed:",v),y||d([])}finally{y||p(!1)}},250);return()=>{y=!0,clearTimeout(j)}},[t,a,b]);const f=async g=>{if(!(!s||x)){h(g.id);try{const y=await re("linkCallToTicket",{callSid:s.callSid,ticketId:g.id});ce.success(`Call attached to ${(y==null?void 0:y.ticketDisplayId)||g.displayId}
13`),r==null||r({ticketId:g.id,ticketDisplayId:(y==null?void 0:y.ticketDisplayId)??g.displayId??null,clientId:(y==null?void 0:y.clientId)??g.clientId??null}),n()}catch(y){console.error("[voice] linking call failed:",y),ce.error((y==null?void 0:y.message)||"Could not attach the call")}finally{h(null)}}};return!t||!s?null:e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.75)",padding:16},onClick:n,role:"dialog","aria-label":"Attach call to a ticket",children:e.jsxs("div",{className:"bg-card border border-border shadow-2xl flex flex-col",style:{maxHeight:"85vh",width:"100%",maxWidth:480,borderRadius:12,overflow:"hidden"},onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border",style:{padding:"12px 16px"},children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-foreground text-sm font-medium",children:s.ticketId?"Move this call to another ticket":"Attach this call to a ticket"}),e.jsxs("p",{className:"text-muted-foreground text-sm",children:[s.ticketDisplayId?`Currently on ${s.ticketDisplayId}. `:"","The recording, recap and notes go with it."]})]}),e.jsx("button",{onClick:n,"aria-label":"Close",className:"text-muted-foreground hover:text-foreground rounded-full",style:{padding:4},children:e.jsx(mt,{className:"w-4 h-4"})})]}),e.jsxs("div",{style:{padding:"12px 16px 0"},children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute text-muted-foreground",style:{width:16,height:16,left:12,top:"50%",transform:"translateY(-50%)"}}),e.jsx("input",{type:"text",autoFocus:!0,value:a,onChange:g=>o(g.target.value),placeholder:"Ticket number or name, e.g. 3963","aria-label":"Search tickets",className:"w-full bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:border-primary",style:{padding:"8px 12px 8px 36px"}})]}),s.clientId&&e.jsxs("label",{className:"flex items-center gap-2 text-muted-foreground text-sm mt-2 select-none",children:[e.jsx("input",{type:"checkbox",checked:c,onChange:g=>u(g.target.checked)}),"Only this client's tickets"]})]}),e.jsx("div",{className:"overflow-y-auto",style:{padding:"8px 8px 12px",minHeight:120},children:a.trim().length<2?e.jsx("p",{className:"text-muted-foreground text-sm",style:{padding:"12px 8px"},children:"Type at least two characters to search."}):m&&i.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",style:{padding:"12px 8px"},children:"Searchingâ¦"}):i.length===0?e.jsxs("p",{className:"text-muted-foreground text-sm",style:{padding:"12px 8px"},children:["No tickets match",b?" for this client":"","."]}):i.map(g=>{const y=g.id===s.ticketId;return e.jsxs("button",{onClick:()=>f(g),disabled:!!x||y,className:"w-full text-left rounded-lg hover:bg-muted disabled:opacity-50 transition-colors flex items-start gap-3",style:{padding:"8px 10px"},children:[e.jsx(_r,{className:"w-4 h-4 text-muted-foreground flex-shrink-0",style:{marginTop:2}}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block text-foreground text-sm truncate",children:[e.jsx("span",{className:"font-medium",children:g.displayId})," · ",g.name]}),e.jsxs("span",{className:"block text-muted-foreground text-xs truncate",children:[[g.clientName,g.projectName,g.status].filter(Boolean).join(" ⢠"),y?" ⢠already attached":""]})]}),x===g.id&&e.jsx("span",{className:"text-muted-foreground text-xs",children:"Attachingâ¦"})]},g.id)})})]})})}const Um=/^\+[1-9]\d{7,14}$/;function si(t){if(!t)return null;const s=t.trim();if(Um.test(s))return s;const n=s.replace(/\D/g,"");if(s.startsWith("+")){const r=`+${n}`;return Um.test(r)?r:null}return n.length===10?`+1${n}`:n.length===11&&n.startsWith("1")?`+${n}`:null}function cn(t){if(!t)return"";const s=si(t);if(!s)return t;const n=/^\+1(\d{3})(\d{3})(\d{4})$/.exec(s);return n?`(${n[1]}) ${n[2]}-${n[3]}`:s}function Su(t){const s=Math.max(0,Math.floor(t??0)),n=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60,o=i=>String(i).padStart(2,"0");return n>0?`${n}:${o(r)}:${o(a)}`:`${r}:${o(a)}`}const bk={connecting:"Connectingâ¦",ringing:"Ringingâ¦",active:"On call",ending:"Hanging upâ¦"},yk=[["1",""],["2","ABC"],["3","DEF"],["4","GHI"],["5","JKL"],["6","MNO"],["7","PQRS"],["8","TUV"],["9","WXYZ"],["*",""],["0","+"],["#",""]];function jk(){const t=Vl(),[s,n]=l.useState(""),[r,a]=l.useState(!1),[o,i]=l.useState(!1),[d,m]=l.useState(""),[p,c]=l.useState(!1),[u,x]=l.useState(null);l.useEffect(()=>{t!=null&&t.error&&(ce.error(t.error),t.clearError())},[t==null?void 0:t.error]);const h=!!(t&&t.phase!=="idle");l.useEffect(()=>{h||(i(!1),m(""))},[h]),l.useEffect(()=>{h&&x(null)},[h]);const b=k=>{!t||t.phase!=="active"||(t.sendDigits(k),m(w=>(w+k).slice(-20)))};if(l.useEffect(()=>{if(!o||(t==null?void 0:t.phase)!=="active")return;const k=w=>{if(!/^[0-9*#]$/.test(w.key))return;const I=w.target;I&&(I.tagName==="INPUT"||I.tagName==="TEXTAREA"||I.isContentEditable)||b(w.key)};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[o,t==null?void 0:t.phase]),!t)return null;const{phase:f,target:g,isMuted:y,durationSeconds:j,lastCall:v}=t,T=async()=>
13{if(!v)return;const k=s.trim();if(!k){t.dismissLastCall(),n("");return}a(!0);try{await re("saveCallNote",{callSid:v.callSid,notes:k}),ce.success("Call note saved"),n(""),t.dismissLastCall()}catch(w){console.error("[voice] saving note failed:",w),ce.error((w==null?void 0:w.message)||"Could not save the note")}finally{a(!1)}};if(!h&&v){const k=(u==null?void 0:u.ticketId)??v.target.ticketId??null,w=(u==null?void 0:u.ticketDisplayId)??(v.target.ticketId?"a ticket":null);return e.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-50 bg-card border-t border-border shadow-lg p-4",children:[e.jsx(Sg,{open:p,call:{callSid:v.callSid,clientId:(u==null?void 0:u.clientId)??v.target.clientId??null,ticketId:k,ticketDisplayId:(u==null?void 0:u.ticketDisplayId)??null},onClose:()=>c(!1),onLinked:x}),e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-foreground text-sm",children:["Call ended â ",v.target.displayName||cn(v.target.to)]}),e.jsxs("p",{className:"text-muted-foreground text-sm",children:[w?`Attached to ${w}. `:"Not on a ticket yet. ","Add a note?"]})]}),e.jsx("button",{onClick:()=>{n(""),t.dismissLastCall()},"aria-label":"Dismiss without a note",className:"text-muted-foreground hover:text-foreground rounded-full",style:{padding:4},children:e.jsx(mt,{className:"w-4 h-4"})})]}),e.jsx("textarea",{value:s,onChange:I=>n(I.target.value),rows:2,autoFocus:!0,placeholder:"What came out of the call?",className:"w-full rounded-xl border border-border bg-background p-2 text-sm text-foreground"}),e.jsxs("div",{className:"flex justify-end gap-2 mt-2",children:[e.jsxs("button",{onClick:()=>c(!0),className:"px-3 py-2 rounded-xl text-sm text-muted-foreground hover:bg-muted transition-colors inline-flex items-center gap-1 mr-auto",children:[e.jsx(_r,{className:"w-4 h-4"}),k?"Change ticket":"Attach to ticket"]}),e.jsx("button",{onClick:()=>{n(""),t.dismissLastCall()},className:"px-3 py-2 rounded-xl text-sm text-muted-foreground hover:bg-muted transition-colors",children:"Skip"}),e.jsx("button",{onClick:T,disabled:r,className:"px-3 py-2 rounded-xl text-sm bg-primary text-primary-foreground disabled:opacity-50 transition-colors",children:r?"Savingâ¦":"Save note"})]})]})}return h?e.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-50 bg-card border-t border-border shadow-lg p-3",children:[o&&f==="active"&&e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-muted-foreground text-sm text-center mb-2",style:{fontFamily:"monospace",minHeight:"1.25rem"},"aria-live":"polite",children:d||"Keypad â tones go to the call"}),e.jsx("div",{className:"grid gap-2 mx-auto",style:{gridTemplateColumns:"repeat(3, 1fr)",maxWidth:240},children:yk.map(([k,w])=>e.jsxs("button",{onClick:()=>b(k),"aria-label":`Dial ${k}`,className:"w-12 h-12 mx-auto rounded-full bg-muted text-foreground hover:bg-primary/10 select-none transition-colors",children:[e.jsx("span",{className:"text-lg leading-none",children:k}),e.jsx("span",{className:"text-muted-foreground leading-none",style:{display:"block",fontSize:9,minHeight:9},children:w})]},k))})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(En,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-foreground truncate",children:(g==null?void 0:g.displayName)||cn(g==null?void 0:g.to)}),e.jsx("p",{className:"text-muted-foreground text-sm",children:f==="active"?Su(j):bk[f]??""})]}),e.jsx("button",{onClick:()=>i(k=>!k),disabled:f!=="active","aria-label":o?"Hide keypad":"Show keypad",title:"Keypad",className:`w-10 h-10 rounded-full flex items-center justify-center text-foreground hover:bg-muted disabled:opacity-40 transition-colors ${o?"bg-muted":""}`,children:e.jsx(Uo,{className:"w-5 h-5"})}),e.jsx("button",{onClick:t.toggleMute,disabled:f!=="active","aria-label":y?"Unmute":"Mute",title:y?"Unmute":"Mute",className:"w-10 h-10 rounded-full flex items-center justify-center text-foreground hover:bg-muted disabled:opacity-40 transition-colors",children:y?e.jsx(sN,{className:"w-5 h-5"}):e.jsx(nN,{className:"w-5 h-5"})}),e.jsx("button",{onClick:t.hangUp,"aria-label":"Hang up",title:"Hang up",className:"w-10 h-10 rounded-full flex items-center justify-center bg-destructive text-destructive-foreground hover:bg-destructive/90 transition-colors",children:e.jsx(lN,{className:"w-5 h-5"})})]})]}):null}const Hm=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,qm=jf,Yl=(t,s)=>n=>{var r;if((s==null?void 0:s.variants)==null)return qm(t,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:a,defaultVariants:o}=s,i=Object.keys(a).map(p=>{const c=n==null?void 0:n[p],u=o==null?void 0:o[p];if(c===null)return null;const x=Hm(c)||Hm(u);return a[p][x]}),d=n&&Object.entries(n).reduce((p,c)=>{let[u,x]=c;return x===void 0||(p[u]=x),p},{}),m=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((p,c)=>{let{class:u,className:x,...h}=c;return Object.entries(h).every(b=>{let[f,g]=b;return Array.isArray(g)?g.includes({...o,...d}[f]):{...o,...d}[f]===g})?[...p,u,x]:p},[]);return qm(t,i,m,n==null?void 0:n.class,n==null?void 0:n.className)},Cu="-",vk=t=>{const s=Nk(t),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:i=>{const d=i.split(Cu);return d[0]===""&&d.length!==1&&d.shift(),Cg(d,s)||wk(i)},getConflictingClassGroupIds:(i,d)=>{const m=n[i]||[];return d&&r[i]?[...m,...r[i]]:m}}},Cg=(t,s)=>{var i;if(t.length===0)return s.classGroupId;const n=t[0],r=s.nextPart.get(n),a=r?Cg(t.slice(1),r):void 0;if(a)return a;
vendor: 5,457 bytes, line 13
13if(s.validators.length===0)return;const o=t.join(Cu);return(i=s.validators.find(({validator:d})=>d(o)))==null?void 0:i.classGroupId},Vm=/^\[(.+)\]$/,wk=t=>{if(Vm.test(t)){const s=Vm.exec(t)[1],n=s==null?void 0:s.substring(0,s.indexOf(":"));if(n)return"arbitrary.."+n}},Nk=t=>{const{theme:s,prefix:n}=t,r={nextPart:new Map,validators:[]};return Sk(Object.entries(t.classGroups),n).forEach(([o,i])=>{Dd(i,r,o,s)}),r},Dd=(t,s,n,r)=>{t.forEach(a=>{if(typeof a=="string"){const o=a===""?s:Ym(s,a);o.classGroupId=n;return}if(typeof a=="function"){if(kk(a)){Dd(a(r),s,n,r);return}s.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([o,i])=>{Dd(i,Ym(s,o),n,r)})})},Ym=(t,s)=>{let n=t;return s.split(Cu).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},kk=t=>t.isThemeGetter,Sk=(t,s)=>s?t.map(([n,r])=>{const a=r.map(o=>typeof o=="string"?s+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([i,d])=>[s+i,d])):o);return[n,a]}):t,Ck=t=>{if(t<1)return{get:()=>{},set:()=>{}};let s=0,n=new Map,r=new Map;const a=(o,i)=>{n.set(o,i),s++,s>t&&(s=0,r=n,n=new Map)};return{get(o){let i=n.get(o);if(i!==void 0)return i;if((i=r.get(o))!==void 0)return a(o,i),i},set(o,i){n.has(o)?n.set(o,i):a(o,i)}}},Tg="!",Tk=t=>{const{separator:s,experimentalParseClassName:n}=t,r=s.length===1,a=s[0],o=s.length,i=d=>{const m=[];let p=0,c=0,u;for(let g=0;g<d.length;g++){let y=d[g];if(p===0){if(y===a&&(r||d.slice(g,g+o)===s)){m.push(d.slice(c,g)),c=g+o;continue}if(y==="/"){u=g;continue}}y==="["?p++:y==="]"&&p--}const x=m.length===0?d:d.substring(c),h=x.startsWith(Tg),b=h?x.substring(1):x,f=u&&u>c?u-c:void 0;return{modifiers:m,hasImportantModifier:h,baseClassName:b,maybePostfixModifierPosition:f}};return n?d=>n({className:d,parseClassName:i}):i},Ak=t=>{if(t.length<=1)return t;const s=[];let n=[];return t.forEach(r=>{r[0]==="["?(s.push(...n.sort(),r),n=[]):n.push(r)}),s.push(...n.sort()),s},Ek=t=>({cache:Ck(t.cacheSize),parseClassName:Tk(t),...vk(t)}),Ik=/\s+/,Rk=(t,s)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=s,o=[],i=t.trim().split(Ik);let d="";for(let m=i.length-1;m>=0;m-=1){const p=i[m],{modifiers:c,hasImportantModifier:u,baseClassName:x,maybePostfixModifierPosition:h}=n(p);let b=!!h,f=r(b?x.substring(0,h):x);if(!f){if(!b){d=p+(d.length>0?" "+d:d);continue}if(f=r(x),!f){d=p+(d.length>0?" "+d:d);continue}b=!1}const g=Ak(c).join(":"),y=u?g+Tg:g,j=y+f;if(o.includes(j))continue;o.push(j);const v=a(f,b);for(let T=0;T<v.length;++T){const k=v[T];o.push(y+k)}d=p+(d.length>0?" "+d:d)}return d};function Dk(){let t=0,s,n,r="";for(;t<arguments.length;)(s=arguments[t++])&&(n=Ag(s))&&(r&&(r+=" "),r+=n);return r}const Ag=t=>{if(typeof t=="string")return t;let s,n="";for(let r=0;r<t.length;r++)t[r]&&(s=Ag(t[r]))&&(n&&(n+=" "),n+=s);return n};function Mk(t,...s){let n,r,a,o=i;function i(m){const p=s.reduce((c,u)=>u(c),t());return n=Ek(p),r=n.cache.get,a=n.cache.set,o=d,d(m)}function d(m){const p=r(m);if(p)return p;const c=Rk(m,n);return a(m,c),c}return function(){return o(Dk.apply(null,arguments))}}const _t=t=>{const s=n=>n[t]||[];return s.isThemeGetter=!0,s},Eg=/^\[(?:([a-z-]+):)?(.+)\]$/i,Pk=/^\d+\/\d+$/,Lk=new Set(["px","full","screen"]),zk=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Ok=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,$k=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Bk=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Fk=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,_n=t=>fa(t)||Lk.has(t)||Pk.test(t),ar=t=>$a(t,"length",Gk),fa=t=>!!t&&!Number.isNaN(Number(t)),jc=t=>$a(t,"number",fa),qa=t=>!!t&&Number.isInteger(Number(t)),_k=t=>t.endsWith("%")&&fa(t.slice(0,-1)),ft=t=>Eg.test(t),or=t=>zk.test(t),Wk=new Set(["length","size","percentage"]),Uk=t=>$a(t,Wk,Ig),Hk=t=>$a(t,"position",Ig),qk=new Set(["image","url"]),Vk=t=>$a(t,qk,Qk),Yk=t=>$a(t,"",Kk),Va=()=>!0,$a=(t,s,n)=>{const r=Eg.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):n(r[2]):!1},Gk=t=>Ok.test(t)&&!$k.test(t),Ig=()=>!1,Kk=t=>Bk.test(t),Qk=t=>Fk.test(t),Jk=()=>{const t=_t("colors"),s=_t("spacing"),n=_t("blur"),r=_t("brightness"),a=_t("borderColor"),o=_t("borderRadius"),i=_t("borderSpacing"),d=_t("borderWidth"),m=_t("contrast"),p=_t("grayscale"),c=_t("hueRotate"),u=_t("invert"),x=_t("gap"),h=_t("gradientColorStops"),b=_t("gradientColorStopPositions"),f=_t("inset"),g=_t("margin"),y=_t("opacity"),j=_t("padding"),v=_t("saturate"),T=_t("scale"),k=_t("sepia"),w=_t("skew"),I=_t("space"),A=_t("translate"),E=()=>["auto","contain","none"],C=()=>["auto","hidden","clip","visible","scroll"],N=()=>["auto",ft,s],S=()=>[ft,s],O=()=>["",_n,ar],R=()=>["auto",fa,ft],z=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],D=()=>["solid","dashed","dotted","double","none"],L=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],$=()=>["start","end","center","between","around","evenly","stretch"],q=()=>["","0",ft],P=()=>["auto","avoid","all","avoid-page","page","left","right","column"],U=()=>[fa,ft];return{cacheSize:500,separator:":",theme:{colors:[Va],spacing:[_n,ar],blur:["none","",or,ft],brightness:U(),borderColor:[t],borderRadius:["n
13one","","full",or,ft],borderSpacing:S(),borderWidth:O(),contrast:U(),grayscale:q(),hueRotate:U(),invert:q(),gap:S(),gradientColorStops:[t],gradientColorStopPositions:[_k,ar],inset:N(),margin:N(),opacity:U(),padding:S(),saturate:U(),scale:U(),sepia:q(),skew:U(),space:S(),translate:S()},classGroups:{aspect:[{aspect:["auto","square","video",ft]}],container:["container"],columns:[{columns:[or]}],"break-after":[{"break-after":P()}],"break-before":[{"break-before":P()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...z(),ft]}],overflow:[{overflow:C()}],"overflow-x":[{"overflow-x":C()}],"overflow-y":[{"overflow-y":C()}],overscroll:[{overscroll:E()}],"overscroll-x":[{"overscroll-x":E()}],"overscroll-y":[{"overscroll-y":E()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[f]}],"inset-x":[{"inset-x":[f]}],"inset-y":[{"inset-y":[f]}],start:[{start:[f]}],end:[{end:[f]}],top:[{top:[f]}],right:[{right:[f]}],bottom:[{bottom:[f]}],left:[{left:[f]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",qa,ft]}],basis:[{basis:N()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",ft]}],grow:[{grow:q()}],shrink:[{shrink:q()}],order:[{order:["first","last","none",qa,ft]}],"grid-cols":[{"grid-cols":[Va]}],"col-start-end":[{col:["auto",{span:["full",qa,ft]},ft]}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":[Va]}],"row-start-end":[{row:["auto",{span:[qa,ft]},ft]}],"row-start":[{"row-start":R()}],"row-end":[{"row-end":R()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",ft]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",ft]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...$()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...$(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...$(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[j]}],px:[{px:[j]}],py:[{py:[j]}],ps:[{ps:[j]}],pe:[{pe:[j]}],pt:[{pt:[j]}],pr:[{pr:[j]}],pb:[{pb:[j]}],pl:[{pl:[j]}],m:[{m:[g]}],mx:[{mx:[g]}],my:[{my:[g]}],ms:[{ms:[g]}],me:[{me:[g]}],mt:[{mt:[g]}],mr:[{mr:[g]}],mb:[{mb:[g]}],ml:[{ml:[g]}],"space-x":[{"space-x":[I]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[I]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",ft,s]}],"min-w":[{"min-w":[ft,s,"min","max","fit"]}],"max-w":[{"max-w":[ft,s,"none","full","min","max","fit","prose",{screen:[or]},or]}],h:[{h:[ft,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[ft,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[ft,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[ft,s,"auto","min","max","fit"]}],"font-size":[{text:["base",or,ar]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",jc]}],"font-family":[{font:[Va]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",ft]}],"line-clamp":[{"line-clamp":["none",fa,jc]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",_n,ft]}],"list-image":[{"list-image":["none",ft]}],"list-style-type":[{list:["none","disc","decimal",ft]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...D(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",_n,ar]}],"underline-offset":[{"underline-offset":["auto",_n,ft]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",ft]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",ft]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...z(),Hk]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Uk]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Vk]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[b]}
13],"gradient-via-pos":[{via:[b]}],"gradient-to-pos":[{to:[b]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[d]}],"border-w-x":[{"border-x":[d]}],"border-w-y":[{"border-y":[d]}],"border-w-s":[{"border-s":[d]}],"border-w-e":[{"border-e":[d]}],"border-w-t":[{"border-t":[d]}],"border-w-r":[{"border-r":[d]}],"border-w-b":[{"border-b":[d]}],"border-w-l":[{"border-l":[d]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...D(),"hidden"]}],"divide-x":[{"divide-x":[d]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[d]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}
vendor: 4,467 bytes, line 13
13],"divide-style":[{divide:D()}],"border-color":[{border:[a]}],"border-color-x":[{"border-x":[a]}],"border-color-y":[{"border-y":[a]}],"border-color-s":[{"border-s":[a]}],"border-color-e":[{"border-e":[a]}],"border-color-t":[{"border-t":[a]}],"border-color-r":[{"border-r":[a]}],"border-color-b":[{"border-b":[a]}],"border-color-l":[{"border-l":[a]}],"divide-color":[{divide:[a]}],"outline-style":[{outline:["",...D()]}],"outline-offset":[{"outline-offset":[_n,ft]}],"outline-w":[{outline:[_n,ar]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:O()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[_n,ar]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",or,Yk]}],"shadow-color":[{shadow:[Va]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...L(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":L()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[m]}],"drop-shadow":[{"drop-shadow":["","none",or,ft]}],grayscale:[{grayscale:[p]}],"hue-rotate":[{"hue-rotate":[c]}],invert:[{invert:[u]}],saturate:[{saturate:[v]}],sepia:[{sepia:[k]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[m]}],"backdrop-grayscale":[{"backdrop-grayscale":[p]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[c]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[v]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[i]}],"border-spacing-x":[{"border-spacing-x":[i]}],"border-spacing-y":[{"border-spacing-y":[i]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",ft]}],duration:[{duration:U()}],ease:[{ease:["linear","in","out","in-out",ft]}],delay:[{delay:U()}],animate:[{animate:["none","spin","ping","pulse","bounce",ft]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[T]}],"scale-x":[{"scale-x":[T]}],"scale-y":[{"scale-y":[T]}],rotate:[{rotate:[qa,ft]}],"translate-x":[{"translate-x":[A]}],"translate-y":[{"translate-y":[A]}],"skew-x":[{"skew-x":[w]}],"skew-y":[{"skew-y":[w]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",ft]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",ft]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",ft]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[_n,ar,jc]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","
13none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},Zk=Mk(Jk);function $e(...t){return Zk(jf(t))}const Gl=Yl("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}});function ke({className:t,variant:s,size:n,asChild:r=!1,...a}){const o=r?pf:"button";return e.jsx(o,{"data-slot":"button",className:$e(Gl({variant:s,size:n,className:t})),...a})}function it({className:t,type:s,...n}){return e.jsx("input",{type:s,"data-slot":"input",className:$e("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",t),...n})}function Rg({className:t,orientation:s="horizontal",decorative:n=!0,...r}){return e.jsx(Z0,{"data-slot":"separator-root",decorative:n,orientation:s,className:$e("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}const Xk=Yl("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function Gm({className:t,variant:s,...n}){return e.jsx("div",{"data-slot":"alert",role:"alert",className:$e(Xk({variant:s}),t),...n})}function Km({className:t,...s}){return e.jsx("div",{"data-slot":"alert-description",className:$e("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...s})}const Eo="/assets/6c2f4e8615a47e4f59af49cf163f11d54edbeee2-BmDyUjA5.webp";function e2({onLogin:t}){const[s,n]=l.useState(""),[r,a]=l.useState(""),[o,i]=l.useState(null),[d,m]=l.useState(!1),[p,c]=l.useState("login"),[u,x]=l.useState(""),[h,b]=l.useState(""),[f,g]=l.useState(!1),[y,j]=l.useState(null),{signInWithGoogle:v,signInWithApple:T,signInWithEmail:k,loading:w,error:I}=pt();l.useEffect(()=>{m(Br.isNativePlatform())},[]);const A=async L=>{if(L.preventDefault(),i(null),!s||!r){i("Email and password are required");return}try{await k(s,r),t()}catch($){i($.message||"Failed to sign in")}},E=async()=>{i(null);try{await v(),t()}catch(L){i(L.message||"Failed to sign in with Google")}},C=async()=>{i(null);try{await T(),t()}catch(L){i(L.message||"Failed to sign in with Apple")}},N=o||I,S=async(L,$)=>{const q=await fetch(`https://us-central1-bucky-app-355a3.cloudfunctions.net/${L}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),P=await q.json().catch(()=>({}));if(!q.ok)throw new Error(P.error||"Something went wrong. Please try again.");return P},O=async L=>{if(L.preventDefault(),i(null),j(null),!s){i("Enter your email address");return}g(!0);try{const $=await S("authRegisterRequest",{email:s});j($.message||"Check your email for a one-time code."),c("code")}catch($){i($.message)}finally{g(!1)}},R=async L=>{if(L.preventDefault(),i(null),u.replace(/\D/g,"").length!==6){i("Enter the 6-digit code from your email");return}if(h.length<8){i("Password must be at least 8 characters");return}g(!0);
13try{await S("authRegisterComplete",{email:s,code:u,password:h}),j(null),await k(s,h),t()}catch($){i($.message||"Could not finish registration")}finally{g(!1)}},z=async()=>{if(i(null),j(null),!s){i("Enter your email address above, then tap Forgot Password");return}g(!0);try{await Y0(Lr,s.trim()),j("If an account exists for that email, a password reset link is on its way.")}catch(L){(L==null?void 0:L.code)==="auth/user-not-found"||(L==null?void 0:L.code)==="auth/invalid-email"?j("If an account exists for that email, a password reset link is on its way."):i(L.message||"Could not send the reset email")}finally{g(!1)}},D=L=>{i(null),j(null),c(L)};return e.jsx("div",{className:"min-h-screen bg-login-background flex flex-col items-center justify-center p-6",children:e.jsxs("div",{className:"w-full max-w-sm",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsx("div",{className:"w-32 h-32 mx-auto mb-4",children:e.jsx("img",{src:Eo,alt:"Bucky Logo",className:"w-full h-full object-contain"})}),e.jsx("h1",{className:"text-foreground mb-1",children:"Bucky"}),e.jsx("p",{className:"text-muted-foreground",children:"by Sunbowl"})]}),N&&e.jsxs(Gm,{variant:"destructive",className:"mb-6",children:[e.jsx(gs,{className:"h-4 w-4"}),e.jsx(Km,{children:N})]}),y&&e.jsx(Gm,{className:"mb-6",children:e.jsx(Km,{children:y})}),p==="register"&&e.jsxs("form",{onSubmit:O,className:"space-y-4",children:[e.jsxs("div",{className:"text-center mb-2",children:[e.jsx("h2",{className:"text-foreground",style:{fontSize:"18px",fontWeight:600},children:"Create your account"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"14px"},children:"Enter the email address we have on file for you. We'll send a one-time code."})]}),e.jsx(it,{type:"email",placeholder:"Email",value:s,onChange:L=>n(L.target.value),className:"h-12 rounded-xl",required:!0,autoFocus:!0,disabled:f}),e.jsx(ke,{type:"submit",className:"w-full h-12 rounded-xl",disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending code..."]}):"Send me a code"}),e.jsx("div",{className:"text-center",children:e.jsx("button",{type:"button",className:"text-primary hover:text-primary/80",onClick:()=>D("login"),disabled:f,children:"Back to sign in"})})]}),p==="code"&&e.jsxs("form",{onSubmit:R,className:"space-y-4",children:[e.jsxs("div",{className:"text-center mb-2",children:[e.jsx("h2",{className:"text-foreground",style:{fontSize:"18px",fontWeight:600},children:"Enter your code"}),e.jsxs("p",{className:"text-muted-foreground",style:{fontSize:"14px"},children:["Sent to ",e.jsx("strong",{children:s}),". Then choose a password."]})]}),e.jsx(it,{type:"text",inputMode:"numeric",autoComplete:"one-time-code",placeholder:"6-digit code",value:u,onChange:L=>x(L.target.value.replace(/\D/g,"").slice(0,6)),className:"h-12 rounded-xl text-center tracking-[0.4em]",required:!0,autoFocus:!0,disabled:f}),e.jsx(it,{type:"password",autoComplete:"new-password",placeholder:"Choose a password (8+ characters)",value:h,onChange:L=>b(L.target.value),className:"h-12 rounded-xl",required:!0,disabled:f}),e.jsx(ke,{type:"submit",className:"w-full h-12 rounded-xl",disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-4 h-4 mr-2 animate-spin"}),"Creating account..."]}):"Create account & sign in"}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("button",{type:"button",className:"text-primary hover:text-primary/80",onClick:()=>D("register"),disabled:f,children:"Resend code"}),e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>D("login"),disabled:f,children:"Back to sign in"})]})]}),p==="login"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs(ke,{type:"button",onClick:E,variant:"outline",className:"w-full h-12 rounded-xl border-border hover:bg-muted",disabled:w,children:[w?e.jsx(fe,{className:"w-5 h-5 mr-3 animate-spin"}):e.jsxs("svg",{className:"w-5 h-5 mr-3",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z",fill:"#4285F4"}),e.jsx("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"#34A853"}),e.jsx("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"#EA4335"})]}
13),w?"Signing in...":"Continue with Google Workspace"]}),d&&e.jsxs(ke,{type:"button",onClick:C,variant:"outline",className:"w-full h-12 rounded-xl border-border hover:bg-muted",disabled:w,children:[w?e.jsx(fe,{className:"w-5 h-5 mr-3 animate-spin"}):e.jsx("svg",{className:"w-5 h-5 mr-3",viewBox:"0 0 24 24",fill:"black",children:e.jsx("path",{d:"M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09l.01-.01zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"})}),w?"Signing in...":"Continue with Apple"]})]}),e.jsxs("div",{className:"relative mb-6",children:[e.jsx(Rg,{className:"bg-border"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"bg-background px-4 text-muted-foreground",style:{fontSize:"14px"},children:"or sign in with email"})})]}),e.jsxs("form",{onSubmit:A,className:"space-y-4",children:[e.jsx("div",{children:e.jsx(it,{type:"email",placeholder:"Email",value:s,onChange:L=>n(L.target.value),className:"h-12 rounded-xl",required:!0,disabled:w})}),e.jsx("div",{children:e.jsx(it,{type:"password",placeholder:"Password",value:r,onChange:L=>a(L.target.value),className:"h-12 rounded-xl",required:!0,disabled:w})}),e.jsx(ke,{type:"submit",className:"w-full h-12 rounded-xl",disabled:w,children:w?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-4 h-4 mr-2 animate-spin"}),"Signing In..."]}):"Sign In"})]}),e.jsxs("div",{className:"text-center mt-6 space-y-2",children:[e.jsx("div",{children:e.jsx("button",{type:"button",className:"text-primary hover:text-primary/80",onClick:z,disabled:w||f,children:"Forgot Password?"})}),e.jsxs("div",{className:"text-muted-foreground",style:{fontSize:"14px"},children:["New to Bucky?"," ",e.jsx("button",{type:"button",className:"text-primary hover:text-primary/80",onClick:()=>D("register"),disabled:w,children:"Create your account"})]})]})]}),e.jsx("p",{className:"text-center text-muted-foreground mt-12",children:"Your direct line to eCommerce expertise"})]})})}function t2({className:t,value:s,...n}){return e.jsx(X0,{"data-slot":"progress",className:$e("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...n,children:e.jsx(ej,{"data-slot":"progress-indicator",className:"bg-primary h-full w-full flex-1 transition-all",style:{transform:`translateX(-${100-(s||0)}%)`}})})}function s2({onComplete:t}){cf();const{token:s}=pt(),{prefetch:n}=Tf(),[r,a]=l.useState(0),[o,i]=l.useState("Initializing..."),[d,m]=l.useState([{id:"companies",label:"Loading companies",completed:!1},{id:"setup",label:"Setting up workspace",completed:!1}]);return l.useEffect(()=>{(async()=>{try{i("Loading your companies..."),a(10),s&&await n(Rl.HUBSPOT_COMPANIES,async()=>{const c=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getProjects",{method:"POST",headers:as(s)});if(!c.ok)throw new Error("Failed to fetch companies");const u=await c.json(),{projects:x}=u||{};if(!x||x.length===0)return[];const h=new Map;return x.forEach(b=>{const f=b.companyName;h.has(f)||h.set(f,{id:f.replace("#","").toLowerCase().replace(/\s+/g,"-"),name:f,slackChannels:[],projectCount:0});const g=h.get(f);b.name&&!g.slackChannels.includes(b.name)&&g.slackChannels.push(b.name),g.projectCount++}),Array.from(h.values())},cl.ONE_DAY),m(c=>c.map(u=>u.id==="companies"?{...u,completed:!0}:u)),a(50),i("Preparing your workspace..."),await new Promise(c=>setTimeout(c,500)),m(c=>c.map(u=>u.id==="setup"?{...u,completed:!0}:u)),a(80),i("Almost ready..."),await new Promise(c=>setTimeout(c,300)),a(100),await new Promise(c=>setTimeout(c,200)),t&&t()}catch(c){console.error("Prefetch error:",c),setTimeout(()=>{a(100),t&&t()},1e3)}})()},[s,n,t]),e.jsxs("div",{className:"min-h-screen bg-background flex flex-col items-center justify-center max-w-md mx-auto px-4",children:[e.jsx("div",{className:"mb-8 animate-spin",children:e.jsx("img",{src:ks,alt:"Sunbowl",className:"w-24 h-24",style:{animationDuration:"2s"}})}),e.jsxs("div",{className:"text-center space-y-3 mb-8",children:[e.jsx("h2",{style:{color:"var(--foreground)"},children:"Loading Your Workspace"}),e.jsx("p",{className:"text-muted-foreground",children:o})]}),e.jsx("div",{className:"w-full max-w-xs mb-4",children:e.jsx(t2,{value:r,className:"h-2"})}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:[r,"%"]}),e.jsx("div",{className:"w-full max-w-xs space-y-2",children:d.map(p=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",style:{color:p.completed?"var(--primary)":"var(--muted-foreground)",opacity:p.completed?1:.6},children:[e.jsx("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center ${p.completed?"border-primary bg-primary":"border-muted-foreground"}`,children:p.completed&&e.jsx("svg",{className:"w-3 h-3 text-white",f
13ill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),e.jsx("span",{children:p.label})]},p.id))})]})}function n2(){const{enabled:t,unreadCount:s,openDrawer:n}=$n(),r=J0(),a=!!Ml(),o=l.useRef(s);l.useEffect(()=>{s>o.current&&r.start(SN(a)),o.current=s},[s,r,a]);const i=s>99?"99+":String(s);return t?e.jsxs("button",{onClick:()=>n("notifications"),className:"relative text-foreground hover:bg-muted/50 rounded-full transition-all active:scale-95",style:{padding:8,marginRight:-6,display:"flex",alignItems:"center",justifyContent:"center",lineHeight:0},"aria-label":`Notifications${s?`, ${s} unread`:""}`,children:[e.jsx(st.span,{animate:r,style:{display:"flex",transformOrigin:"50% 18%"},children:e.jsx(Dn,{style:{width:24,height:24},strokeWidth:1.85})}),e.jsx(hs,{children:s>0&&e.jsx(st.span,{variants:kN(a),initial:"initial",animate:"animate",exit:"exit",className:"absolute flex items-center justify-center rounded-full bg-destructive",style:{top:3,right:3,minWidth:17,height:17,padding:"0 4px",color:"#fff",fontSize:10,fontWeight:700,lineHeight:1,boxShadow:"0 0 0 2px var(--card)"},children:i},s)})]}):null}const r2={team_dm:"var(--primary)",customer_message:"var(--primary)",ticket_assigned_department:"#d6a73a",ticket_assigned_user:"#d6a73a",ticket_status:"#d6a73a"};function a2({fallback:t}){var g;const{notifications:s,openDrawer:n,markRead:r,deepLink:a}=$n(),o=!!Ml(),i=s.filter(y=>!y.seen),d=(g=i[0])==null?void 0:g.id,m=y=>{var j,v;if(y.read||r(y.id),y.type==="team_dm"&&((j=y.entity)!=null&&j.threadId)){n("messages",y.entity.threadId);return}(v=y.target)!=null&&v.screen&&a(y.target)},p=l.useRef(d),[c,u]=l.useState(!1);if(l.useEffect(()=>{if(d&&p.current&&d!==p.current){u(!0);const y=setTimeout(()=>u(!1),900);return p.current=d,()=>clearTimeout(y)}p.current=d},[d]),i.length===0)return e.jsx(e.Fragment,{children:t??null});const x=i.slice(0,8),h=x.reduce((y,j)=>y+j.title.length+3,0),b=Math.max(8,h*.22),f=y=>e.jsx("span",{style:{display:"inline-flex",alignItems:"center",flexShrink:0},children:x.map(j=>e.jsxs("button",{onClick:()=>m(j),title:j.body,className:"bucky-ticker-item",style:{display:"inline-flex",alignItems:"center",paddingRight:28,background:"transparent",border:"none",cursor:"pointer",whiteSpace:"nowrap"},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:r2[j.type]||"var(--muted-foreground)",marginRight:8,flexShrink:0}}),e.jsx("span",{style:{fontSize:13,fontWeight:600,color:"var(--card-foreground)",whiteSpace:"nowrap"},children:j.title})]},`${y}-${j.id}`))});return e.jsxs("div",{style:{display:"flex",alignItems:"center",width:"100%",minWidth:0,gap:8},children:[e.jsxs("button",{onClick:()=>n("notifications"),"aria-label":`${i.length} unread notifications â open`,style:{position:"relative",width:8,height:8,flexShrink:0,background:"transparent",border:"none",padding:0,cursor:"pointer"},children:[!o&&e.jsx(st.span,{style:{position:"absolute",inset:0,borderRadius:"50%",background:"var(--destructive)"},animate:{scale:[1,2.2],opacity:[.5,0]},transition:{duration:1.4,repeat:1/0,ease:"easeOut"}}),e.jsx("span",{style:{position:"absolute",inset:0,borderRadius:"50%",background:"var(--destructive)"}})]}),e.jsx(st.div,{animate:c?{backgroundColor:["rgba(126,204,238,0)","rgba(126,204,238,0.18)","rgba(126,204,238,0)"]}:{},transition:{duration:.9},style:{position:"relative",flex:1,minWidth:0,overflow:"hidden",height:22,borderRadius:6},children:o?e.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:f("r")}):e.jsxs("div",{className:"bucky-ticker-track",style:{position:"absolute",top:0,bottom:0,display:"flex",alignItems:"center",willChange:"transform","--ticker-duration":`${b}s`},children:[f("a"),f("b")]})})]})}function o2(){const[t,s]=l.useState("idle");return l.useEffect(()=>{var o,i;const n=(o=window.electron)==null?void 0:o.meeting;if(!n)return;const r=d=>{d!=null&&d.status&&s(d.status)};return(i=n.getStatus)==null||i.call(n).then(r).catch(()=>{}),n.onStatusChanged(r)},[]),{status:t,isActive:t==="active"}}
13const i2=5*6e4,l2=6e4,c2=15;function d2(){const{user:t}=pt(),s=l.useRef(!1);l.useEffect(()=>{var d,m;const n=(d=window.electron)==null?void 0:d.meeting;if(!(n!=null&&n.openWindow)||!t||window.location.search.includes("screen=hub"))return;let r=!1;const a=async()=>{var p;if(!s.current){s.current=!0;try{const c=await re("upcomingStaffMeetings",{lookaheadMinutes:c2},void 0,{timeoutMs:2e4});if(r)return;const u=Array.isArray(c==null?void 0:c.meetings)?c.meetings:[],x=Date.now();for(const h of u){if(h.startsAt-x>i2||h.endsAt&&h.endsAt<x)continue;const b={eventId:h.eventId,title:h.title,startsAt:h.startsAt,meetLink:h.meetLink,clientId:h.clientId,clientName:h.clientName,attendees:h.attendees,candidates:h.candidates};await((p=n.autoLaunch)==null?void 0:p.call(n,b))}}catch(c){console.warn("[autoLaunch] poll failed:",c instanceof Error?c.message:c)}finally{s.current=!1}}};a();const o=window.setInterval(a,l2),i=(m=n.onPowerResumed)==null?void 0:m.call(n,()=>{a()});return()=>{r=!0,window.clearInterval(o),i==null||i()}},[t])}const u2="#22c55e";function m2(){var n;const{status:t}=o2();if(d2(),!((n=window.electron)!=null&&n.meeting))return null;const s=t==="active"||t==="loading"||t==="ending";return e.jsx("button",{onClick:()=>{var r,a,o;return(o=(a=(r=window.electron)==null?void 0:r.meeting)==null?void 0:a.openWindow)==null?void 0:o.call(a)},"aria-label":s?"Bucky Live is active":"Open Bucky Live",title:s?"Bucky Live â active":"Bucky Live",className:"text-foreground hover:bg-muted/50 rounded-full transition-all active:scale-95",style:{padding:8,display:"flex",alignItems:"center",justifyContent:"center",lineHeight:0},children:e.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.9,strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"9",y:"2",width:"6",height:"11",rx:"3",fill:s?u2:"none",style:{transition:"fill 0.2s ease"}}),e.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),e.jsx("line",{x1:"12",x2:"12",y1:"19",y2:"22"}),e.jsx("line",{x1:"8",x2:"16",y1:"22",y2:"22"})]})})}function Xe({title:t,showTitle:s=!1,onBack:n,onLogoClick:r,rightAction:a,contextualTitle:o,onHome:i,showHome:d=!0,showBell:m=!0}){const p=pk(),c=i??p??r;return e.jsxs("div",{className:"bg-card border-b border-border",style:{paddingTop:"max(env(safe-area-inset-top, 0px), 0.75rem)",paddingLeft:12,paddingRight:12,paddingBottom:10},children:[e.jsxs("div",{className:"relative flex items-center justify-between",style:{minHeight:40},children:[e.jsx("div",{className:"flex items-center",children:n?e.jsx("button",{onClick:n,className:"text-foreground hover:bg-muted/50 rounded-full transition-all active:scale-95",style:{padding:8,marginLeft:-8},"aria-label":"Go back",children:e.jsx(dt,{style:{width:22,height:22},strokeWidth:2})}):d&&c?e.jsx("button",{onClick:c,className:"rounded-full hover:bg-muted/50 transition-all active:scale-95",style:{padding:6,marginLeft:-2},"aria-label":"Go home",children:e.jsx("img",{src:Vr,alt:"Home",style:{width:24,height:24,display:"block"}})}):e.jsx("span",{style:{width:36},"aria-hidden":!0})}),e.jsx("div",{style:{flex:1,minWidth:0,marginLeft:10,marginRight:10,display:"flex",justifyContent:"center"},children:e.jsx(a2,{fallback:o?e.jsx("span",{className:"truncate text-card-foreground",style:{fontSize:17,fontWeight:"var(--font-weight-semibold)",letterSpacing:"-0.01em",textAlign:"center"},children:o}):null})}),e.jsxs("div",{className:"flex items-center",style:{gap:2},children:[a,e.jsx(m2,{}),m&&e.jsx(n2,{})]})]}),e.jsx(xk,{}),s&&t&&e.jsx("h1",{className:"text-card-foreground text-center",style:{fontSize:26,fontWeight:"var(--font-weight-semibold)",letterSpacing:"-0.02em",marginTop:8},children:t})]})}function p2({userEmail:t,onSelectClient:s,onSelectAdmin:n}){return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto",children:[e.jsx(Xe,{}),e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center px-6 pb-24",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"How would you like to continue?"})]}),e.jsxs("div",{className:"w-full space-y-4",children:[e.jsx(st.button,{onClick:s,className:"w-full bg-card border border-border rounded-2xl p-6 text-left transition-all hover:border-primary hover:shadow-md",whileTap:{scale:.98},children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 w-12 h-12 bg-primary/10 rounded-xl flex items-center justify-center",children:e.jsx(Ul,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-1",children:"Client View"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"View projects, tickets, and support resources"})]})]})}),e.jsx(st.button,{onClick:n,className:"w-full bg-card border border-border rounded-2xl p-6 text-left transition-all hover:border-primary hover:shadow-md",whileTap:{scale:.98},children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 w-12 h-12 bg-purple-500/10 rounded-xl flex items-center justify-center",children:e.jsx(vu,{className:"w-6 h-6 text-purple-500"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-1",children:"Admin View"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage companies, logos, and settings"})]})]})})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center mt-8",children:"You can switch between views at any time from Settings"})]})]})}const ka="/assets/f4cb921574454edde2e324f28af4b7526126aefa-C9_jWWJj.png",Sa="/assets/dbc32aa49
136f21ffa8508a4f6432d1e6c6f76e3b1-BXWDXNsx.png",ni="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAllBMVEUIETWYAC7jGDcAETWVAC7AEDPmGDe2Fjd6BzAAEDWbAC7qGDeeAC7sGDcEETXfGDcwDjSCBS8eDzQ4EjUZETVeEzbYGDeHBC8qEjUOEDVjEzY7DjMkDzTOFzdWCzLDEDObFTaKFTZQDDJBDTNuCDF+FDZNEjWpFjZnCTHUFzeOAi5uFDZ0BzBHDDOBFDZYEzWuFje8FjfeZBlhAAAF9klEQVR4nO2c6VrqMBRFCYcWOoGMMimDCIrT5f1f7raAWOhJB9A26bfXz6to1s0mPTkJVioAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYqCiB/DX0LjkitR/mJRasUmt2bbUhjT3DPulxIr05JhGzb4rrWKTHszA8L60hrRwqr6hsMu6ntLUqe4Nhd0ppyLtzG/DdikNaeVVj4bCXZZQkXqt6slQ1EblU7TqTsjQbpTOkPpBRk+Gwn0qmSLRwDwzFFtqFj2oX8Xa7DMaMrRXpZpEWh8FfwyF3S2TovVqRg23VtHD+j2Cci1iKNzybDKo+z2DZ4bCnpZF0TIkhmUp3ujZq7KGwn0shSL1fmbwwlDYpSjeqB5jWIbijcahjF4aCvdDe0UaDcwYQ3+ToXvxdirXJIbaF2+0Psto1FC4ehdvRA9mgqHmmwzanmeUM9S6eKPJpSBjKHTuENPMTGOob4f4rFyTG+pbvNEw4scbCqFph9jaRTIqMdS0eKO3yDIjnUMtizcixk9mKISGD0XacFMoM7TftZtE+mIFpXPo6na8T/TKLDMxhtoVb9acn0K5oWbH+9SNPusTDIWrU+etGdlSpDDUqnijhWwKYwx1Kt7Yci3ZUKPiLdwBzmKoTYeY3qQZTZhDTY73adSSC8YbatJ5s/5JHoUpDLXYZFA/TjDBUNjqH+83aSBfZpINRU15Q5KVaykNle8Q/xzYX2moeuctplxLbah28RZTrqU1FK7KdzNpmJDRNIZK380krruW3VDd4o3rAF9hqG7xRp24ci2Doaj11FQ83q/8BUNFi7eLA/tbDNW8m0mV+HItk6HYKrjJkHbXrjJUsHijZSrBtIbCVq1D3LQkHeCI4SyloWofALMW6TLqPbzdu3YaRcWKN+bAnvWbjS2ip3YqR3uokiLFdNdOfs6sT8GgiSZtO9lRqeKNnpMrbs/w/Y6PgMAxeR4V6hBTL0nQdHZLKzxeortGoqM6dzPP71eyfmu6HKzvmJRVZYq3hHLN9Oprixtq8jwqcryf0AF26hPWb/9Smr7HzqMaHeLL+5VhHLPejeQzTIKjEsVb5H5lOJ8b+fydXk/TlTyrbvGdN+mBvT9/m2Gi3+FH9FZC5lj88b6sA+xUN8PYfJ79ELlj4XczacLOoOPN+fmjAPbfOy98Vosu3iyuA+xU5xWJx3Ref+lIvjZ6qTGOBXeI6TO6zDiteY93sNb/qo5hiwa/vjZ5x0KLN+bA3jEXrJ8fzjfDMw9/ccC9X7Jh9R3HzPuxwM5bpAPstBbs0P14Llpe8M2HPb7tijEb1iZRv+Ze5LS4Tcbl/UpnsCBucfe3hH48D9/z8ylZ0biTvCEfLxzddUGK5/crTaf1yc3fPp7Oaa5DfRrbbX9wr2hGHQt6KFLowN70Xnk/q7MYeKEsn3WibLc25t61geM25FjQ3Uz68n7m7/WZy6cfz0014VNB4p0NK9Ey5FhIh7h5KtdMb7Bi/IisseEkf6LEX1nZsBKtt6cioIji7bsDHLTPLMbvMp5SQ3lYiT6+G3MF3M2kiXfI58MbO7bJZTxjDOVh9WN+dMx9k9HcfxzGn79xNJ9BPHde5hu0+5WVyfrBMffiLTiwD9pn0fKarN4nF88kw31Y+0xYj405t5+rInX9fBp9bjjdTeuGW1/indlzHRusud4htgzPWDLtM6u/i6yeWQxlYfX/49punsUbfRrR9pm/jY2LZ0pDWViD5mOem4wJM4LuvOqk6O2nOuUWq2hYfce89CqRP9HpP7C/kuKZxdB3tNtPkbAWt8Wg0edrYjyzGQZh3T6OUnd6/pIgnq0U8cxq6OPWmLDmrmd91dPF8wrDYCIb0bDm6ld5Th3PqwyLDSvRMEs8rzQU+7BO83fMHs/rDYOVtTHJN6z+b8scz1sM8w7rdfG8zTCQrL3kE1ai5c7xzGtxZn7mrsR129Fi6vcFu3NjV7+BeeMW2qvpn78dqWCKPmwDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgB/4D2uptxMXy7lgAAAAASUVORK5CYII=";function x2({onRefresh:t,children:s,disabled:n=!1}){const[r,a]=l.useState(!1),[o,i]=l.useState(!1),[d,m]=l.useState(0),p=l.useRef(null),c=l.useRef(0),u=Br.isNativePlatform(),x=80,h=120;l.useEffect(()=>{if(n||u)return;const y=p.current;if(!y)return;let j=0,v=0;const T=I=>{v=y.scrollTop,I.touches.length>0&&(j=I.touches[0].clientY,c.current=j)},k=I=>{if(o||v>0)return;const A=I.touches[0];if(!A)return;const C=A.clientY-c.current;if(C>0&&v===0){a(!0);const N=Math.min(C*.5,h);m(N),C>10&&I.preventDefault()}},w=async()=>{if(r){if(d>=x){i(!0);try{await t()}catch(I){console.error("Refresh error:",I)}finally{i(!1)}}a(!1),m(0)}};return y.addEventListener("touchstart",T,{passive:!0}),y.addEventListener("touchmove",k,{passive:!1}),y.addEventListener("touchend",w),()=>{y.removeEventListener("touchstart",T),y.removeEventListener("touchmove",k),y.removeEventListener("touchend",w)}},[t,o,r,d,n,u]);const b=r||o,f=r?Math.min(d/x,1):1,g=r?d/x*360:0;return e.jsxs("div",{ref:p,className:"relative overflow-auto h-full",children:[!u&&b&&e.jsx("div",{className:"absolute left-0 right-0 flex justify-center items-center transition-all z-50",style:{to
13p:o?"10px":`${Math.max(0,d-40)}px`,opacity:f},children:e.jsx("div",{className:"bg-background border border-border rounded-full p-2 shadow-lg",style:{transform:o?"rotate(0deg)":`rotate(${g}deg)`,transition:o?"none":"transform 0.1s ease-out"},children:e.jsx(fe,{className:`w-5 h-5 text-primary ${o?"animate-spin":""}`})})}),e.jsx("div",{style:{transform:!u&&b?`translateY(${d}px)`:"translateY(0)",transition:r?"none":"transform 0.3s ease-out"},children:s})]})}function h2({onCompanySelect:t,onNewFeatureClick:s}){const[n,r]=l.useState(()=>localStorage.getItem("marketingBlockCollapsed")==="true"),{token:a}=pt(),{companies:o,loading:i,error:d,refetch:m}=Pa(a),{logos:p,refetch:c}=Ra(a),{prefetch:u}=Tf();l.useEffect(()=>{const y=()=>{document.hidden||(console.log("Screen visible, refetching logos..."),c())};return document.addEventListener("visibilitychange",y),()=>document.removeEventListener("visibilitychange",y)},[c]),l.useEffect(()=>{o.length>0&&a&&(console.log("=========================================="),console.log("Background prefetch: Starting to prefetch projects for all c
13ompanies"),console.log(`Total companies: ${o.length}`),console.log("=========================================="),o.forEach(y=>{const j=[...y.slackChannels].sort(),v=Rl.NOTION_PROJECTS(j.join(","));console.log(`ð¦ PREFETCH: Company "${y.name}"`),console.log(` Slack Channels: ${JSON.stringify(y.slackChannels)}`),console.log(` Cache Key: ${v}`),u(v,async()=>{var w;console.log(`ð Prefetching projects for ${y.name}...`),console.log(` Requesting with clientNames: ${JSON.stringify(y.slackChannels)}`);const T=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getProjectsByClients",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({clientNames:y.slackChannels})});if(!T.ok)throw new Error(`Failed to prefetch projects for ${y.name}`);const k=await T.json();return console.log(`â Prefetched ${((w=k.projects)==null?void 0:w.length)||0} projects for ${y.name}`),k.projects||[]},cl.TWELVE_HOURS).catch(T=>{console.log(`Prefetch failed for ${y.name}:`,T.message)})}))},[o,a,u]);const x=()=>{const y=!n;r(y),localStorage.setItem("marketingBlockCollapsed",String(y))},h=async()=>{await Promise.all([m(),c()])},b=y=>y.toLowerCase().replace("#",""),f=y=>{const j=o.find(T=>T.name===y);if(j&&j.slackChannels&&j.slackChannels.length>0)for(const T of j.slackChannels){const k=p[T]||p[b(T)];if(k)return k}const v=b(y);return v.includes("chick")||v.includes("fil")?ka:v.includes("figma")?Sa:v.includes("delta")?ni:Vr},g=o.map(y=>({id:y.name.replace("#","").toLowerCase().replace(/\s+/g,"-"),name:y.name.replace("#",""),logoUrl:f(y.name),projectCount:y.projectCount}));return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{}),e.jsx(x2,{onRefresh:h,children:e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs(st.div,{className:"w-full border-2 border-primary/20 rounded-lg overflow-hidden",style:{background:"linear-gradient(to bottom right, var(--secondary), var(--primary))",marginBottom:"var(--spacing-md)",borderRadius:"var(--radius-lg)",borderWidth:"var(--border-width-thick)"},animate:{height:n?"72px":"auto",paddingTop:n?"var(--spacing-md)":"var(--spacing-lg)",paddingBottom:n?"var(--spacing-md)":"var(--spacing-lg)",paddingLeft:"var(--spacing-md)",paddingRight:"var(--spacing-md)"},transition:{duration:.3,ease:"easeInOut"},children:[e.jsx(hs,{children:!n&&e.jsxs(st.div,{className:"flex items-center justify-between",style:{marginBottom:"var(--spacing-md)"},initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.2},children:[e.jsxs("div",{className:"bg-white/90 backdrop-blur-sm rounded-full flex items-center gap-1.5",style:{borderRadius:"var(--radius-full)",paddingTop:"var(--spacing-xs)",paddingBottom:"var(--spacing-xs)",paddingLeft:"var(--spacing-sm)",paddingRight:"var(--spacing-sm)",width:"fit-content"},children:[e.jsx(ws,{style:{width:"14px",height:"14px",color:"var(--primary)"}}),e.jsx("span",{style:{color:"var(--primary)"},children:"Big Update"})]}),e.jsx("button",{onClick:y=>{y.stopPropagation(),x()},className:"hover:bg-white/10 transition-colors rounded",style:{paddingTop:"var(--spacing-xs)",paddingBottom:"var(--spacing-xs)",paddingLeft:"var(--spacing-xs)",paddingRight:"var(--spacing-xs)",borderRadius:"var(--radius-sm)"},"aria-label":"Collapse card",children:e.jsx(st.div,{animate:{rotate:0},transition:{duration:.3,ease:"easeInOut"},children:e.jsx(Rt,{className:"text-white",style:{width:"20px",height:"20px"}})})})]})}),e.jsxs("div",{onClick:n?void 0:s,className:"w-full text-left",style:{cursor:n?"default":"pointer"},children:[e.jsx("div",{className:"text-left",style:{marginBottom:n?"0":"var(--spacing-md)",overflow:"hidden"},children:n?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"relative flex-1",style:{overflow:"hidden",whiteSpace:"nowrap"},children:[e.jsx("style",{children:` 14 @keyframes marquee { 15 0% { transform: translateX(0%); } 16 100% { transform: translateX(-50%); } 17 } 18 .marquee-content { 19 display: inline-block; 20 animation: marquee 15s linear infinite; 21 } 22 `}),e.jsxs("div",{className:"marquee-content",children:[e.jsx("span",{className:"text-white",style:{marginRight:"var(--spacing-2xl)"},children:"AI SEO Optimization Now Available!"}),e.jsx("span",{className:"text-white",style:{marginRight:"var(--spacing-2xl)"},children:"AI SEO Optimization Now Available!"})]})]}),e.jsx("button",{onClick:y=>{y.stopPropagation(),x()},className:"hover:bg-white/10 transition-colors rounded flex-shrink-0",style:{paddingTop:"var(--spacing-xs)",paddingBottom:"var(--spacing-xs)",paddingLeft:"var(--spacing-xs)",paddingRight:"var(--spacing-xs)",borderRadius:"var(--radius-sm)",marginLeft:"var(--spacing-md)"},"aria-label":"Expand card",children:e.jsx(Rt,{className:"text-white",style:{width:"20px",height:"20px",transform:"rotate(90deg)"}})})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-white",style:{marginBottom:"var(--spacing-sm)"},children:"AI SEO Optimization Now Available!"}),e.jsx("p",{className:"text-white/90",children:"Leverage cutting-edge AI to dominate search results"})]})}),e.jsx(hs,{children:!n&&e.jsx(st.div,{className:"bg-white/10 backdrop-blur-sm border border-white/20 rounded-lg",style:{borderRadius:"var(--radius-md)",paddingTop:"var(--spacing-md)",paddingBottom:"var(--spacing-md)",paddingLeft:"var(--spacing-md)",paddingRight:"var(--spacing-md)",marginBottom:"var(--spacing-md)"},initial:{opacity:0,height:0}
22,animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.2},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xo,{className:"text-secondary flex-shrink-0",style:{width:"20px",height:"20px"}}),e.jsxs("div",{className:"text-left",children:[e.jsxs("div",{className:"text-white",children:[e.jsx("span",{style:{fontWeight:"var(--font-weight-bold)"},children:"23x"})," better conversion"]}),e.jsx("div",{className:"text-white/80",style:{fontSize:"0.875rem"},children:"vs traditional SEO"})]})]})})}),e.jsx(hs,{children:!n&&e.jsxs(st.div,{className:"bg-secondary rounded-lg flex items-center justify-between",style:{borderRadius:"var(--radius-md)",paddingTop:"var(--spacing-sm)",paddingBottom:"var(--spacing-sm)",paddingLeft:"var(--spacing-md)",paddingRight:"var(--spacing-md)"},initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.2},children:[e.jsx("span",{style:{color:"var(--foreground)"},children:"Start optimizing today"}),e.jsx(Rt,{className:"flex-shrink-0",style:{width:"20px",height:"20px",color:"var(--foreground)"}})]})})]})]}),e.jsxs("div",{className:"space-y-3",children:[i&&g.length===0&&e.jsx("div",{className:"flex justify-center items-center py-16",children:e.jsx("div",{className:"animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-12 h-12"})})}),d&&g.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx(gs,{className:"w-12 h-12 text-destructive mb-4"}),e.jsx("h3",{className:"text-foreground mb-2",children:"Error Loading Companies"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:d})]}),g.length>0&&g.map(y=>e.jsxs("button",{onClick:()=>t(y.id),className:"w-full bg-card border border-border rounded-lg p-4 flex items-center gap-3 hover:bg-accent transition-colors",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},children:[e.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{width:"56px",height:"56px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border)"},children:y.logoUrl.startsWith("emoji:")?e.jsx("span",{style:{fontSize:"2rem"},children:y.logoUrl.replace("emoji:","")}):e.jsx("img",{src:y.logoUrl,alt:y.name,className:"w-full h-full object-cover",style:{padding:"7px"}})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("h3",{style:{color:"var(--foreground)",marginBottom:"2px",fontSize:"1.25rem"},children:y.name}),e.jsxs("p",{className:"text-muted-foreground",children:[y.projectCount," ",y.projectCount===1?"channel":"channels"]})]})]},y.id)),!i&&!d&&g.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx("span",{style:{fontSize:"3rem",opacity:.4},children:"ð¢"})}),e.jsx("h3",{className:"text-foreground mb-2",children:"No Companies Found"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:"No companies are associated with your account"})]})]})]})})]})}function f2({selectedCompanyId:t,onChannelSelect:s,onSettingsClick:n,onCreditClick:r,onLogoClick:a,onBack:o}){const{token:i}=pt(),{companies:d,loading:m,error:p,refetch:c}=Pa(i),{logos:u}=Ra(i),[x,h]=ee.useState(!1),b=async()=>{if(!x){h(!0);try{await c()}finally{h(!1)}}},f=v=>{const T=u[v]||u[v.replace("#","")];if(T)return T;const k=v.toLowerCase().replace("#","");return k.includes("chick")||k.includes("fil")?ka:k.includes("figma")?Sa:k.includes("delta")?ni:Vr},g=d.find(v=>v.name.replace("#","").toLowerCase().replace(/\s+/g,"-")===t),j=((g==null?void 0:g.slackChannels)||[]).map(v=>({id:v,name:`#${v}`,channelId:`#${v}`,logoUrl:f(v),lastMessage:"Recent activity available",timestamp:"Recently",unreadCount:void 0})).filter((v,T,k)=>T===k.findIndex(w=>w.name===v.name));return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{onBack:o,onLogoClick:a}),e.jsxs("div",{className:"flex-1 bg-card",children:[e.jsx("div",{className:"px-4 py-3 border-b border-border",children:e.jsxs("span",{className:"text-muted-foreground uppercase tracking-wide",style:{fontSize:"12px",fontWeight:"var(--font-weight-medium)"}
22,children:["Channels ",g?`⢠${g.name}`:""]})}),!m&&!p&&g&&e.jsx("div",{className:"px-4 py-3 border-b border-gray-200",children:e.jsxs("button",{onClick:b,disabled:x,className:"flex items-center gap-2 text-primary hover:text-primary/80 transition-colors disabled:opacity-50",children:[e.jsx(yt,{className:`w-4 h-4 ${x?"animate-spin":""}`}),e.jsx("span",{className:"text-sm font-medium",children:x?"Refreshing...":"Refresh Channels"})]})}),m&&e.jsx("div",{className:"flex justify-center items-center py-16",children:e.jsx("div",{className:"animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-12 h-12"})})}),p&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx(gs,{className:"w-12 h-12 text-destructive mb-4"}),e.jsx("h3",{className:"text-foreground mb-2",children:"Error Loading Channels"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:p})]}),!m&&!p&&!g&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx("span",{style:{fontSize:"3rem",opacity:.4},children:"ð¢"})}),e.jsx("h3",{className:"text-foreground mb-2",children:"No Company Selected"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:"Please select a company to view channels"})]}),!m&&!p&&g&&j.length>0&&e.jsx("div",{className:"divide-y divide-gray-100",children:j.map(v=>e.jsxs("div",{onClick:()=>s(v.id),className:"px-4 py-4 hover:bg-accent transition-colors cursor-pointer flex items-center gap-3",children:[e.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border)"},children:v.logoUrl.startsWith("emoji:")?e.jsx("span",{style:{fontSize:"1.75rem"},children:v.logoUrl.replace("emoji:","")}):e.jsx("img",{src:v.logoUrl,alt:v.name,className:"w-full h-full object-cover",style:{padding:"7px"}})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("h3",{className:"text-foreground font-medium truncate",style:{fontSize:"1.25rem"},children:v.name})})]},v.id))}),!m&&!p&&g&&j.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx("span",{style:{fontSize:"3rem",opacity:.4},children:"ð¬"})}),e.jsx("h3",{className:"text-foreground mb-2",children:"No Channels Yet"}),e.jsxs("p",{className:"text-muted-foreground text-center max-w-xs",children:["No channels found for ",g.name]})]})]})]})}function g2({onChannelSelect:t,onLogoClick:s}){const{token:n}=pt(),{companies:r,loading:a,error:o}=Pa(n),{logos:i}=Ra(n),d=c=>{const u=i[c]||i[c.replace("#","")];if(u)return u;const x=c.toLowerCase().replace("#","");return x.includes("chick")||x.includes("fil")?ka:x.includes("figma")?Sa:x.includes("delta")?ni:Vr},p=r.flatMap(c=>(c.slackChannels||[]).map(u=>({id:u,name:`#${u}`,companyName:c.name,companyId:c.id,logoUrl:d(u),hasUnread:!1}))).filter((c,u,x)=>u===x.findIndex(h=>h.name===c.name));return p.sort((c,u)=>c.name.localeCompare(u.name)),e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"flex-1 bg-card",children:[e.jsx("div",{className:"px-4 py-3 border-b border-border",children:e.jsx("span",{className:"text-muted-foreground uppercase tracking-wide",style:{fontSize:"12px",fontWeight:"var(--font-weight-medium)"},children:"All Channels"})}),a&&e.jsx("div",{className:"flex justify-center items-center py-16",children:e.jsx("div",{className:"animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-12 h-12"})})}),o&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx(gs,{className:"w-12 h-12 text-destructive mb-4"}),e.jsx("h3",{className:"text-foreground mb-2",children:"Error Loading Channels"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:o})]}),!a&&!o&&p.length>0&&e.jsx("div",{className:"divide-y divide-gray-100",children:p.map(c=>e.jsx("button",{onClick:()=>t(c.id,c.name,c.logoUrl),className:"w-full px-4 py-4 hover:bg-accent transition-colors text-left",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border)"},children:c.logoUrl.startsWith("emoji:")?e.jsx("span",{style:{fontSize:"1.75rem"},children:c.logoUrl.replace("emoji:","")}):e.jsx("img",{src:c.logoUrl,alt:c.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-foreground font-medium truncate",style:{fontSize:"1.25rem"},children:c.name}),c.hasUnread&&e.jsx("div",{className:"w-2 h-2 bg-blue-600 rounded-full flex-shrink-0"})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:c.companyName})]}),e.jsx("svg",{className:"w-5 h-5 text-muted-foreground flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})},`${c.companyId}-${c.id}`))}),!a&&!o&&p.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx("span",{style:{fontSize:"3rem",opacity:.4},children:"ð¬"})}),e.jsx("h3",{className:"text-foreground mb-2",children:"No Channels Yet"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:"No channels found. Check back later!"})]})]})]})}const b2=Yl("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function Wt({className:t,variant:s,asChild:n=!1,...r}){const a=n?pf:"span";return e.jsx(a,{"data-slot":"badge",className:$e(b2({variant:s}),t),...r})}function y2({name:t,channelId:s,logoUrl:n,lastMessage:r,timestamp:a,unreadCount:o,onClick:i}){return e.jsxs("button",{onClick:i,className:"w-full bg-card border-b border-border p-4 flex items-center gap-3 active:bg-muted/80 transition-colors text-left",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-0.5",children:[e.jsx("h3",{className:"text-card-foreground truncate pr-2",style:{fontSize:"14px",fontWeight:"var(--font-weight-medium)"},children:t}),e.jsx("span",{className:"text-muted-foreground flex-shrink-0",style:{fontSize:"12px"},children:a})]}),e.jsx("p",{className:"text-primary mb-1",style:{fontSize:"12px",fontWeight:"var(--font-weight-normal)"},children:s}),e.jsx("p",{className:"text-muted-foreground truncate",style:{fontSize:"14px"},children:r})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o?e.jsx(Wt,{className:"bg-secondary text-secondary-foreground h-5 min-w-5 rounded-full flex items-center justify-center px-1.5",children:o}):null,e.jsx(Rt,{className:"w-5 h-5 text-muted"})]})]})}const j2=t=>"ðï¸";function v2({selectedCompanyId:t,selectedChannelId:s,onProjectSelect:n,onSettingsClick:r,onCreditClick:a,onLogoClick:o,onBack:i}){const{token:d}=pt(),{companies:m,loading:p}=Pa(d);m.find(T=>T.id===t);const c=s.startsWith("#")?s:`#${s}`,{projects:u,loading:x,error:h,refetch:b}=_0(d,[c]),[f,g]=ee.useState(!1),y=p||x,j=async()=>{g(!0);try{await b()}catch(T){console.error("Failed to refresh projects:",T)}finally{g(!1)}},v=u.map(T=>({id:T.id,name:T.name,channelId:T.clientName.startsWith("#")?T.clientName:`#${T.clientName}`,logoUrl:j2(T.clientName),lastMessage:"Recent activity available",timestamp:"Recently",unreadCount:void 0}));return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{onBack:i,onLogoClick:o}),e.jsxs("div",{className:"flex-1 bg-card",children:[!y&&!h&&e.jsx("div",{className:"px-4 py-3 border-b border-gray-200",children:e.jsxs("button",{onClick:j,disabled:f,className:"flex items-center gap-2 text-primary hover:text-primary/80 transition-colors disabled:opacity-50",children:[e.jsx(yt,{className:`w-4 h-4 ${f?"animate-spin":""}`}),e.jsx("span",{className:"text-sm font-medium",children:f?"Refreshing...":"Refresh Projects"})]})}),y&&e.jsx("div",{className:"flex justify-center items-center py-16",children:e.jsx("div",{className:"animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-12 h-12"})})}),h&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx(gs,{className:"w-12 h-12 text-destructive mb-4"}),e.jsx("h3",{className:"text-foreground mb-2",children:"Error Loading Projects"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:h})]}),!y&&!h&&v.length>0&&e.jsx("div",{className:"divide-y divide-gray-100",children:v.map(T=>{const k=u.find(w=>w.id===T.id);return e.jsx(y2,{...T,onClick:()=>n(T.id,T.name,(k==null?void 0:k.status)||"")},T.id)})}),!y&&!h&&v.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx("span",{style:{fontSize:"3rem",opacity:.4},children:"ð¬"})}),e.jsx("h3",{className:"text-foreground mb-2",children:"No Projects Yet"}),e.jsxs("p",{className:"text-muted-foreground text-center max-w-xs",children:["No projects found for ",c]})]})]})]})}const w2="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODgiIGhlaWdodD0iODgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgc3Ryb2tlPSIjMDAwIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBvcGFjaXR5PSIuMyIgZmlsbD0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIzLjciPjxyZWN0IHg9IjE2IiB5PSIxNiIgd2lkdGg9IjU2IiBoZWlnaHQ9IjU2IiByeD0iNiIvPjxwYXRoIGQ9Im0xNiA1OCAxNi0xOCAzMiAzMiIvPjxjaXJjbGUgY3g9IjUzIiBjeT0iMzUiIHI9IjciLz48L3N2Zz4KCg==";function Dg(t){const[s,n]=l.useState(!1),r=()=>{n(!0)},{src:a,alt:o,style:i,className:d,...m}=t;return s?e.jsx("div",{className:`inline-block bg-gray-100 text-center align-middle ${d??""}`,style:i,children:e.jsx("div",{className:"flex items-center justify-center w-full h-full",children:e.jsx("img",{src:w2,alt:"Error loading image",...m,"data-original-url":a})})}):e.jsx("img",{src:a,alt:o,className:d,style:i,...m,onError:r})}function br({...t}){return e.jsx(xf,{"data-slot":"dialog",...t})}function N2({...t}){return e.jsx(yf,{"data-slot":"dialog-portal",...t})}const Mg=l.forwardRef(({className:t,...s},n)=>e.jsx(au,{ref:n,"data-slot":"dialog-overlay",className:$e("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...s}));Mg.displayName=au.displayName;function yr({className:t,children:s,...n}){return e.jsxs(N2,{"data-slot":"dialog-portal",children:[e.jsx(Mg,{}),e.jsxs(hf,{"data-slot":"dialog-content",className:$e("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 roun
22ded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...n,children:[s,e.jsxs(ff,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(mt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function jr({className:t,...s}){return e.jsx("div",{"data-slot":"dialog-header",className:$e("flex flex-col gap-2 text-center sm:text-left",t),...s})}function Gr({className:t,...s}){return e.jsx("div",{"data-slot":"dialog-footer",className:$e("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function vr({className:t,...s}){return e.jsx(gf,{"data-slot":"dialog-title",className:$e("text-lg leading-none font-semibold",t),...s})}function wr({className:t,...s}){return e.jsx(bf,{"data-slot":"dialog-description",className:$e("text-muted-foreground text-sm",t),...s})}function Jt({className:t,...s}){return e.jsx(tj,{"data-slot":"label",className:$e("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...s})}function k2({open:t,onOpenChange:s,currentLogoUrl:n,projectName:r,onSave:a}){const[o,i]=ee.useState(n);ee.useEffect(()=>{i(n)},[n]);const d=()=>{a(o),s(!1)};return e.jsx(br,{open:t,onOpenChange:s,children:e.jsxs(yr,{className:"sm:max-w-md bg-card border-border",children:[e.jsxs(jr,{children:[e.jsx(vr,{className:"text-card-foreground",children:"Edit Project Logo"}),e.jsxs(wr,{className:"text-muted-foreground",children:["Update the logo for ",r]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Jt,{htmlFor:"logo-url",className:"text-card-foreground",children:"Logo URL"}),e.jsx(it,{id:"logo-url",placeholder:"https://example.com/logo.png",value:o,onChange:m=>i(m.target.value),className:"rounded-xl"})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Jt,{className:"text-card-foreground",children:"Preview"}),e.jsx("div",{className:"w-16 h-16 bg-muted rounded-xl flex items-center justify-center overflow-hidden",children:e.jsx("img",{src:o,alt:"Logo preview",className:"w-full h-full object-cover",onError:m=>{m.currentTarget.src="",m.currentTarget.alt="Invalid URL"}})})]})]}),e.jsxs(Gr,{className:"gap-2",children:[e.jsx(ke,{variant:"outline",onClick:()=>s(!1),className:"rounded-xl",children:"Cancel"}),e.jsx(ke,{onClick:d,className:"rounded-xl",children:"Save Changes"})]})]})})}function Pg({className:t,children:s,...n}){return e.jsxs(sj,{"data-slot":"scroll-area",className:$e("relative",t),...n,children:[e.jsx(nj,{"data-slot":"scroll-area-viewport",className:"focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1",children:s}),e.jsx(S2,{}),e.jsx(rj,{})]})}function S2({className:t,orientation:s="vertical",...n}){return e.jsx(aj,{"data-slot":"scroll-area-scrollbar",orientation:s,className:$e("flex touch-none p-px transition-colors select-none",s==="vertical"&&"h-full w-2.5 border-l border-l-transparent",s==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",t),...n,children:e.jsx(oj,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}function C2({ticketNumber:t,videoThumbnail:s,videoUrl:n,creditValue:r,onApprove:a}){const[o,i]=l.useState(!1),d=()=>{a&&a()};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-card border border-border rounded-lg overflow-hidden max-w-md",children:[e.jsxs("div",{className:"px-4 py-3 bg-primary/5 border-b border-border flex items-center justify-between",children:[e.jsxs("span",{className:"text-card-foreground",style:{fontSize:"14px",fontWeight:"var(--font-weight-semibold)"},children:["Ticket #",t]}),e.jsxs("div",{className:"flex items-center gap-1 text-secondary-foreground bg-secondary/20 px-2 py-1 rounded",children:[e.jsx(tg,{className:"w-4 h-4"}),e.jsxs("span",{style:{fontSize:"14px",fontWeight:"var(--font-weight-semibold)"},children:[r," credits"]})]})]}),e.jsxs("button",{onClick:()=>i(!0),className:"relative w-full aspect-video bg-muted group overflow-hidden",children:[e.jsx(Dg,{src:s,alt:"Video thumbnail",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-black/30 flex items-center justify-center group-hover:bg-black/40 transition-colors",children:e.jsx("div",{className:"bg-primary text-primary-foreground rounded-full p-4 group-hover:scale-110 transition-transform",children:e.jsx(In,{className:"w-8 h-8 fill-current"})})})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("p",{className:"text-muted-foreground mb-3",style:{fontSize:"13px"},children:"Review the proposal video and approve to begin work"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{variant:"destructive",size:"icon",className:"flex-[0.2] aspect-square bg-destructive hover:bg-destructive/90",onClick:()=>console.log("Ticket paused"),children:e.jsx(xg,{className:"w-5 h-5"})}),e.jsx(ke,{onClick:d,className:"flex-[0.8] bg-primary hover:bg-primary/90 text-primary-foreground",style:{fontSize:"15px",fontWeight:"var(--font-weight-semibold)"},children:"Let's go! ð"})]})]})]}),e.jsx(br,{open:o,onOpenChange:i,children:e.jsxs(yr,{className:"max-w-4xl p-0 max-h-[95vh] flex flex-col gap-0",children:[e.jsxs(jr,{className:"px-6 pt-6 pb-4 border-b border-border flex-shrink-0",children:[e.jsxs(vr,{style:{fontSize:"18px",fontWeight:"var(--font-weight-semibold)"},children:["Ticket #",t," - Proposal Video"]}),e.jsx(wr,{children:"Review the proposal video and transcription below"})]}),e.jsx("div",{className:"aspect-video w-full flex-shrink-0 bg-black",children:e.jsx("iframe",{src:n,className:"w-full h-full",frameBorder:"0",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0,title:`Ticket ${t} proposal video`})}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Pg,{className:"h-full",children:e.jsxs("div",{className:"px-6 py-5",children:[e.jsx("h4",{className:"text-card-foreground mb-3",style:{fontSize:"16px",fontWeight:"var(--font-weight-semibold)"},children:"Video Transcription"}),e.jsxs("div",{className:"space-y-3 text-muted-foreground",style:{fontSize:"14px",lineHeight:"1.6"},children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-primary",style:{fontWeight:"var(--font-weight-medium)"},children:"[00:00]"})," Hey there! Thanks for taking the time to review this proposal. I'm excited to walk you through our strategy for optimizing your product pages."]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-primary",style:{fontWeight:"var(--font-weight-medium)"},children:"[00:15]"})," Based on our initial audit, we've identified three key areas that will have the most immediate impact on your conversion rate. First, we're going to add more social proof above the fold - customer reviews, trust badges, and real-time purchase notifications."]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-primary",style:{fontWeight:"var(--font-weight-medium)"},children:"[00:35]"})," Second, we'll simplify your CTA buttons. Right now, there are multiple competing calls-to-action which can create decision paralysis. We'll streamline this to guide customers more effectively through the purchase journey."]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-primary",style:{fontWeight:"var(--font-weight-medium)"},children:"[00:52]"})," Third, we're implementing a size guide widget. Our data shows that uncertainty about sizing is one of the top reasons for cart abandonment in your category. An interactive size guide will address this friction point directly."]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-primary",style:{fontWeight:"var(--font-weight-medium)"},children:"[01:10]"})," We'll also be optimizing your product images and implementing lazy loading to improve page speed. Faster load times directly correlate with higher conversion rates, especially on mobile devices."]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-primary",style:{fontWeight:"var(--font-weight-medium)"},children:"[01:28]"})," The timeline for this project is approximately two weeks, with the first mockups ready for your review within three business days. We'll conduct A/B testing throughout to measure the impact of each change."]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-primary",style:{fontWeight:"var(--font-weight-medium)"},children:"[01:45]"})," This project is estimated at 12 credits, which includes all design work, implementation, testing, and a post-launch review after 30 days to analyze the results."]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-primary",style:{fontWeight:"var(--font-weight-medium)"},children:"[02:00]"}
22),` If you have any questions or would like to discuss any aspect of this proposal, just drop a message in the chat. Otherwise, hit that "Let's go" button and we'll get started right away. Looking forward to working with you on this!`]})]})]})})})]})})]})}function jt({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:$e("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function fs({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:$e("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...s})}function vs({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:$e("leading-none",t),...s})}function vt({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:$e("px-6 [&:last-child]:pb-6",t),...s})}function Kl({...t}){return e.jsx(ij,{"data-slot":"alert-dialog",...t})}function T2({...t}){return e.jsx(pj,{"data-slot":"alert-dialog-portal",...t})}function A2({className:t,...s}){return e.jsx(xj,{"data-slot":"alert-dialog-overlay",className:$e("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...s})}function Ql({className:t,...s}){return e.jsxs(T2,{children:[e.jsx(A2,{}),e.jsx(lj,{"data-slot":"alert-dialog-content",className:$e("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...s})]})}function Tu({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:$e("flex flex-col gap-2 text-center sm:text-left",t),...s})}function Au({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:$e("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function Eu({className:t,...s}){return e.jsx(cj,{"data-slot":"alert-dialog-title",className:$e("text-lg font-semibold",t),...s})}function Iu({className:t,...s}){return e.jsx(dj,{"data-slot":"alert-dialog-description",className:$e("text-muted-foreground text-sm",t),...s})}function Ru({className:t,...s}){return e.jsx(mj,{className:$e(Gl(),t),...s})}function Du({className:t,...s}){return e.jsx(uj,{className:$e(Gl({variant:"outline"}),t),...s})}function Lg({cycle:t,onApprove:s,onDefer:n,disabled:r=!1}){const[a,o]=l.useState(!1),[i,d]=l.useState(!1),[m,p]=l.useState(!1),[c,u]=l.useState(!1),[x,h]=l.useState(!1),b=async()=>{o(!0);try{await s(t.id)&&p(!0)}finally{o(!1)}},f=()=>{h(!0)},g=async()=>{if(!(!n||!t.id)){h(!1),d(!0);try{await n(t.id)&&u(!0)}catch(v){console.error("Error deferring cycle:",v)}finally{d(!1)}}},j=(()=>{if(!t.createdAt)return"Unknown date";try{if(typeof t.createdAt.toDate=="function")return t.createdAt.toDate().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});if(t.createdAt._seconds){const v=new Date(t.createdAt._seconds*1e3);return isNaN(v.getTime())?"Unknown date":v.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}if(t.createdAt.seconds){const v=new Date(t.createdAt.seconds*1e3);return isNaN(v.getTime())?"Unknown date":v.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}}catch(v){return console.error("Error parsing created date:",v),"Unknown date"}return"Unknown date"})();return m?e.jsx(jt,{className:"bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-800",children:e.jsxs(vt,{className:"py-6 flex items-center justify-center gap-2 text-green-700 dark:text-green-400",children:[e.jsx(kt,{className:"w-5 h-5"}),e.jsx("span",{style:{fontSize:"15px",fontWeight:"var(--font-weight-medium)"},children:"Approved! Work will begin shortly."})]})}):c?e.jsx(jt,{className:"bg-muted/50 border-muted-foreground/20",children:e.jsxs(vt,{className:"py-6 flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx("span",{className:"text-lg",children:"â³"}),e.jsx("span",{style:{fontSize:"15px",fontWeight:"var(--font-weight-medium)"},children:"Deferred. Credits released."})]})}):e.jsxs(jt,{className:"overflow-hidden",children:[e.jsxs(fs,{className:"px-4 py-3 bg-primary/5 border-b border-border flex flex-row items-center justify-between space-y-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-card-foreground",style:{fontSize:"14px",fontWeight:"var(--font-weight-semibold)"},children:t.ticketNumber})]}),e.jsxs("div",{className:"flex items-center gap-1 text-secondary-foreground bg-secondary/20 px-2 py-1 rounded",children:[e.jsx(tg,{className:"w-4 h-4"}),e.jsxs("span",{style:{fontSize:"14px",fontWeight:"var(--font-weight-semibold)"},children:[t.creditAmount," credit",t.creditAmount!==1?"s":""]})]})]}),e.jsxs(vt,{className:"p-4",children:[e.jsx("h3",{className:"text-card-foreground mb-2 line-clamp-2",style:{fontSize:"15px",fontWeight:"var(--font-weight-medium)"},children:t.ticketTitle}),e.jsxs("div",{className:"flex items-center gap-4 text-muted-foreground mb-4",style:{fontSize:"13px"},children:[e.jsx("span",{children:t.projectName}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ms,{className:"w-3 h-3"}),e.jsx("span",{children:j})]})]}),e.jsxs("p",{className:"text-muted-foreground mb-4",style:{fontSize:"13px"},children:["Approve this ticket to put ",t.creditAmount," credit",t.creditAmount!==1?"s":""," on hold and begin work."]}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(ke,{onClick:f,disabled:r||i||a,variant:"outline",className:"px-3 border-muted-foreground
22/50 hover:bg-muted/50 hover:border-muted-foreground",children:i?e.jsx(fe,{className:"w-4 h-4 animate-spin text-muted-foreground"}):e.jsx("span",{className:"text-base",children:"â³"})}),e.jsx(ke,{onClick:b,disabled:r||a||i,className:"flex-1 bg-primary hover:bg-primary/90 text-primary-foreground",style:{fontSize:"15px",fontWeight:"var(--font-weight-semibold)"},children:a?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-4 h-4 mr-2 animate-spin"}),"Approving..."]}):"Let's go! ð"})]})]}),e.jsx(Kl,{open:x,onOpenChange:h,children:e.jsxs(Ql,{children:[e.jsxs(Tu,{children:[e.jsx(Eu,{children:"Defer Project Confirmation"}),e.jsx(Iu,{children:"We are going to defer and store the details of this cycle. You can re-enable it at anytime, do you want to proceed?"})]}),e.jsxs(Au,{children:[e.jsx(Du,{children:"No"}),e.jsx(Ru,{onClick:g,children:"Yes"})]})]})})]})}function E2({...t}){return e.jsx(xf,{"data-slot":"sheet",...t})}function I2({...t}){return e.jsx(yf,{"data-slot":"sheet-portal",...t})}function R2({className:t,...s}){return e.jsx(au,{"data-slot":"sheet-overlay",className:$e("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...s})}function D2({className:t,children:s,side:n="right",...r}){return e.jsxs(I2,{children:[e.jsx(R2,{}),e.jsxs(hf,{"data-slot":"sheet-content",className:$e("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",n==="right"&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",n==="left"&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",n==="top"&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",n==="bottom"&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",t),...r,children:[s,e.jsxs(ff,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",children:[e.jsx(mt,{className:"size-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function M2({className:t,...s}){return e.jsx("div",{"data-slot":"sheet-header",className:$e("flex flex-col gap-1.5 p-4",t),...s})}function P2({className:t,...s}){return e.jsx("div",{"data-slot":"sheet-footer",className:$e("mt-auto flex flex-col gap-2 p-4",t),...s})}function L2({className:t,...s}){return e.jsx(gf,{"data-slot":"sheet-title",className:$e("text-foreground font-semibold",t),...s})}function z2({className:t,...s}){return e.jsx(bf,{"data-slot":"sheet-description",className:$e("text-muted-foreground text-sm",t),...s})}function zg({open:t,onOpenChange:s,channelId:n,defaultTicketName:r,description:a,projects:o,allowedClients:i,authToken:d,isCreating:m,onCreateTicket:p}){const[c,u]=ee.useState(r),[x,h]=ee.useState(""),b=!o||o.length===0,[f,g]=ee.useState([]),[y,j]=ee.useState(!1),[v,T]=ee.useState(""),[k,w]=ee.useState([]),[I,A]=ee.useState(!1),E=n?n.replace(/^#/,""):"",C=b?k:o||[];ee.useEffect(()=>{t&&(u(r),h(C.length===1?C[0].id:""),b||(T(""),w([])),b&&E&&T(E))},[t,r]),ee.useEffect(()=>{C.length===1?h(C[0].id):h("")},[C]),ee.useEffect(()=>{if(!(!t||!b||E||f.length>0)){if(i&&i.length>0){g(i.map(S=>({id:S,name:S}))),i.length===1&&T(i[0]);return}j(!0),fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getNotionClients").then(S=>S.json()).then(S=>{S.success&&g(S.clients)}).catch(S=>console.error("Failed to fetch clients:",S)).finally(()=>j(!1))}},[t,b,E,i]),ee.useEffect(()=>{if(!v||!d){w([]);return}A(!0),fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getProjectsByClients",{method:"POST",headers:as(d),body:JSON.stringify({clientNames:[v]})}).then(S=>S.json()).then(S=>w(S.projects||[])).catch(S=>console.error("Failed to fetch projects:",S)).finally(()=>A(!1))},[v,d]);const N=()=>{!c.trim()||!x||p(c.trim(),x)};return e.jsx(E2,{open:t,onOpenChange:s,children:e.jsxs(D2,{side:"bottom",className:"rounded-t-2xl max-w-md",style:{left:0,right:0,marginLeft:"auto",marginRight:"auto"},children:[e.jsxs(M2,{children:[e.jsx(L2,{children:"Create Ticket"}),n&&e.jsxs(z2,{children:["for ",n]})]}),e.jsxs("div",{className:"px-4 flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-foreground mb-1.5 block",children:"Ticket Name"}),e.jsx("input",{type:"text",value:c,onChange:S=>u(S.target.value),className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring",disabled:m})]}),b&&!E&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-foreground mb-1.5 block",children:"Client"}),y?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"}),"Loading clients..."]}
22):e.jsxs("select",{value:v,onChange:S=>T(S.target.value),className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring",disabled:m,children:[e.jsx("option",{value:"",children:"Select a client..."}),f.map(S=>e.jsx("option",{value:S.name,children:S.name},S.id))]})]}),(C.length>1||b&&v||b&&E)&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-foreground mb-1.5 block",children:"Project"}),I?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"}),"Loading projects..."]}):e.jsxs("select",{value:x,onChange:S=>h(S.target.value),className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring",disabled:m||C.length===0,children:[e.jsx("option",{value:"",children:C.length===0?"No projects found":"Select a project..."}),C.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-foreground mb-1.5 block",children:"Description"}),e.jsx("div",{className:"rounded-lg border border-border bg-muted px-3 py-2 text-sm text-muted-foreground max-h-32 overflow-y-auto whitespace-pre-wrap",children:a})]})]}),e.jsxs(P2,{className:"flex-row gap-2",children:[e.jsx(ke,{variant:"outline",onClick:()=>s(!1),disabled:m,className:"flex-1",children:"Cancel"}),e.jsx(ke,{onClick:N,disabled:m||!c.trim()||!x,className:"flex-1",children:m?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):"Create Ticket"})]})]})})}const Qm="https://us-central1-bucky-app-355a3.cloudfunctions.net";function O2(t){const{token:s,user:n}=pt(),[r,a]=l.useState([]),[o,i]=l.useState(!1);l.useEffect(()=>{if(!t){console.log("[useCyclesForChannel] No slackChannelId, clearing cycles"),a([]);return}console.log("[useCyclesForChannel] Subscribing to cycles for channel:",t),i(!0);const c=Re(ge,"cycles"),u=Ge(c,Ve("slackChannelId","==",t),Ve("status","==","pending_approval")),x=qt(u,h=>{const b=h.docs.map(f=>({id:f.id,...f.data()}));console.log(`[useCyclesForChannel] Got ${b.length} cycles for channel ${t}:`,b.map(f=>f.ticketNumber)),a(b),i(!1)},h=>{console.error("[useCyclesForChannel] Error:",h),a([]),i(!1)});return()=>x()},[t]);const d=new Map;r.forEach(c=>{c.ticketNumber&&d.set(c.ticketNumber.toUpperCase(),c)});const m=l.useCallback(async c=>{if(!(n!=null&&n.email))return!1;try{const u=await fetch(`${Qm}/approveCycle`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({cycleId:c,approvedBy:n.uid||n.email})});if(!u.ok)return console.error("[useCyclesForChannel] Non-OK response:",u.statusText),!1;const x=await u.json();return typeof x.success!="boolean"?(console.error("[useCyclesForChannel] Invalid response data:",x),!1):x.success}catch(u){return console.error("[useCyclesForChannel] Approval error:",u),!1}},[n,s]),p=l.useCallback(async c=>{if(!c||!(n!=null&&n.email))return console.error("[useCyclesForChannel] Invalid input: cycleId or user email is missing"),!1;try{const u=await fetch(`${Qm}/deferCycle`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({cycleId:c,deferredBy:n.uid||n.email})});if(!u.ok)return console.error("[useCyclesForChannel] Fetch error:",u.statusText),!1;const x=await u.json();return x.success===void 0?(console.error("[useCyclesForChannel] Invalid response: success field is missing"),!1):x.success}catch(u){return console.error("[useCyclesForChannel] Defer error:",u),!1}},[n,s]);return{cycles:r,cyclesByTicket:d,loading:o,approveCycle:m,deferCycle:p}}const vc="https://us-central1-bucky-app-355a3.cloudfunctions.net";function $2(t){const{token:s}=pt(),[n,r]=l.useState(!0),[a,o]=l.useState(!1),[i,d]=l.useState(!1),[m,p]=l.useState([]),[c,u]=l.useState(null),[x,h]=l.useState([]),b=l.useRef(null),f=l.useCallback(()=>s?{"Content-Type":"application/json",Authorization:`Bearer ${s}`}:{"Content-Type":"application/json"},[s]),g=l.useCallback(async v=>{var T;if(b.current!==v){b.current=v,o(!1);try{const k=await fetch(`${vc}
22/chatbotContext`,{method:"POST",headers:f(),body:JSON.stringify({channelId:v})});if(!k.ok){console.warn("[useBuckyAssistant] Context init failed:",k.status),o(!0);return}const w=await k.json();o(w.ready||!1),((T=w.projectSuggestions)==null?void 0:T.length)>0&&h(w.projectSuggestions),await y(v)}catch(k){console.error("[useBuckyAssistant] initContext error:",k),o(!0)}}},[f]),y=l.useCallback(async v=>{try{const T=await fetch(`${vc}/chatbotMessages?channelId=${encodeURIComponent(v)}`,{method:"GET",headers:f()});if(!T.ok)return;const k=await T.json();k.messages&&p(k.messages)}catch(T){console.error("[useBuckyAssistant] fetchMessages error:",T)}},[f]),j=l.useCallback(async(v,T)=>{if(!(!t||!n||!s)){d(!0);try{const k=await fetch(`${vc}/chatbotChat`,{method:"POST",headers:f(),body:JSON.stringify({message:v,channelId:t,messageTimestamp:T,projectName:c||void 0})});if(!k.ok){console.warn("[useBuckyAssistant] Chat request failed:",k.status);return}const w=await k.json();if(!w.skip&&w.answer){const I={id:w.messageId||`local-${Date.now()}`,triggerMessageText:v,triggerTimestamp:T,response:w.answer,filesReferenced:w.filesReferenced||[],projectContext:c,createdAt:Date.now(),skipped:!1};p(A=>[...A,I])}}catch(k){console.error("[useBuckyAssistant] processMessage error:",k)}finally{d(!1)}}},[t,n,c,s,f]);return{isEnabled:n,setEnabled:r,isReady:a,isProcessing:i,aiMessages:m,selectedProject:c,projectOptions:x,setSelectedProject:u,processMessage:j,initContext:g}}function B2({projectId:t,projectName:s,channelId:n,logoUrl:r,onBack:a,onUpdateLogo:o}){const[i,d]=ee.useState(""),[m,p]=ee.useState(!1),[c,u]=ee.useState(!1),x=ee.useRef(null),h=ee.useRef(null),b=ee.useRef(0),f=ee.useRef(!0),g=ee.useRef(null),{token:y,getToken:j}=pt(),{channelId:v,loading:T,error:k}=W0(y,n),{messages:w,loading:I,error:A,sendMessage:E}=U0(j,v),{cycles:C,cyclesByTicket:N,approveCycle:S,deferCycle:O}=O2(v),R=$2(v),z=H0(t),[D,L]=ee.useState(!1),[$,q]=ee.useState(null),P=Z=>{const Q=Z.triggerMessageText.length>80?Z.triggerMessageText.substring(0,77)+"...":Z.triggerMessageText;q({aiMessageId:Z.aiMessageId,ticketName:Q,description:`**Client Question:** 23${Z.triggerMessageText} 24 25**Bucky AI Analysis:** 26${Z.response}`}),L(!0)},U=async(Z,Q)=>{if($)try{await z.createTicket($.aiMessageId,{ticketName:Z,ticketDescription:$.description,projectId:Q})&&(L(!1),q(null))}catch(K){console.error("Error creating ticket:",K)}};ee.useEffect(()=>{v&&R.isEnabled&&R.initContext(v)},[v,R.isEnabled]);const V=Z=>{const Q=Z.match(/^(TICK-\d+):/i);return Q?Q[1].toUpperCase():null},M=(Z="smooth")=>{var Q;(Q=x.current)==null||Q.scrollIntoView({behavior:Z})};ee.useLayoutEffect(()=>{const Z=h.current;Z&&w.length>0&&(g.current={scrollTop:Z.scrollTop,scrollHeight:Z.scrollHeight})}),ee.useEffect(()=>{const Z=h.current,Q=w.length,K=b.current;if(f.current&&Q>0)M("instant"),f.current=!1;else if(Q>K)M("smooth");else if(Z&&g.current&&Q===K){const X=g.current,se=X.scrollHeight-X.scrollTop-Z.clientHeight,pe=Z.scrollHeight-Z.clientHeight-se;Z.scrollTop=Math.max(0,pe)}b.current=Q},[w]);const F=w.filter(Z=>{const Q=V(Z.text);return!(Q&&N.has(Q))}).map(Z=>{const K=new Date(parseFloat(Z.timestamp)*1e3).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return{id:Z.id,text:Z.text,isOwn:Z.sentFromApp,sender:Z.userName,timestamp:K,type:"text"}}),W=Z=>{if(!Z)return"";let Q=null;return typeof Z.toDate=="function"?Q=Z.toDate():typeof Z._seconds=="number"?Q=new Date(Z._seconds*1e3):typeof Z.seconds=="number"&&(Q=new Date(Z.seconds*1e3)),Q instanceof Date&&!isNaN(Q.getTime())?Q.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""},_=C.map(Z=>({id:`cycle-${Z.id}`,text:`${Z.ticketNumber}: ${Z.ticketTitle}`,isOwn:!1,sender:"Sunbowl",timestamp:W(Z.createdAt),type:"cycle-approval",cycleData:Z})),G=R.aiMessages.map(Z=>{const Q=new Date(Z.createdAt);return{id:`ai-${Z.id}`,text:Z.response,isOwn:!1,sender:"Bucky AI",timestamp:Q.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}),type:"text",aiData:{triggerMessageText:Z.triggerMessageText,response:Z.response,aiMessageId:Z.id}}}),B=[...F,...G,..._],Y=async()=>
26{if(!i.trim()||!v||m)return;const Z=i.trim();p(!0);try{if(await E(Z),d(""),R.isEnabled&&R.isReady){const Q=Date.now()/1e3;R.processMessage(Z,Q)}}catch(Q){console.error("Failed to send message:",Q)}finally{p(!1)}},J=Z=>{o(t,Z)};return(T||I)&&w.length===0?e.jsxs("div",{className:"min-h-screen bg-card flex flex-col items-center justify-center max-w-md mx-auto",children:[e.jsx("div",{className:"mb-4 animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-12 h-12"})}),e.jsx("p",{className:"text-muted-foreground",children:"Loading messages..."})]}):k||A?e.jsxs("div",{className:"min-h-screen bg-card flex flex-col max-w-md mx-auto",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-card border-b border-border px-4 pt-12 pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:a,className:"w-9 h-9 -ml-2 flex items-center justify-center active:bg-muted/80 rounded-full transition-colors",children:e.jsx(fr,{className:"w-6 h-6 text-primary"})}),e.jsx("h2",{className:"text-foreground",style:{fontSize:"16px",fontWeight:"var(--font-weight-semibold)"},children:s})]})}),e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:[e.jsx("div",{className:"text-5xl mb-4",children:"â ï¸"}),e.jsx("h3",{className:"text-foreground mb-2 font-semibold",children:"Error Loading Messages"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:k||A})]})]}):e.jsxs("div",{className:"min-h-screen bg-card flex flex-col max-w-md mx-auto pb-24",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-card border-b border-border px-4 pt-12 pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:a,className:"w-9 h-9 -ml-2 flex items-center justify-center active:bg-muted/80 rounded-full transition-colors",children:e.jsx(fr,{className:"w-6 h-6 text-primary"})}),e.jsx("button",{onClick:()=>u(!0),className:"w-10 h-10 bg-white rounded-xl flex items-center justify-center overflow-hidden shadow-sm active:opacity-70 transition-opacity flex-shrink-0 p-0.5",children:e.jsx(Dg,{src:r,alt:`${s} logo`,className:"w-full h-full object-cover rounded-lg"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h2",{className:"text-foreground truncate",style:{fontSize:"16px",fontWeight:"var(--font-weight-semibold)"},children:s}),e.jsx("p",{className:"text-primary truncate",style:{fontSize:"12px",fontWeight:"var(--font-weight-normal)"},children:n})]}),e.jsx("button",{className:"w-9 h-9 flex items-center justify-center active:bg-muted/80 rounded-full transition-colors",children:e.jsx(rN,{className:"w-5 h-5 text-muted-foreground"})})]})}),e.jsx(q0,{isEnabled:R.isEnabled,onToggle:R.setEnabled,isReady:R.isReady,isProcessing:R.isProcessing,projectOptions:R.projectOptions,selectedProject:R.selectedProject,onSelectProject:R.setSelectedProject}),e.jsxs("div",{ref:h,className:"flex-1 overflow-y-auto py-4",children:[B.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center p-6",children:[e.jsx("div",{className:"text-5xl mb-4",children:"ð¬"}),e.jsx("h3",{className:"text-foreground mb-2 font-semibold",children:"No Messages Yet"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Start a conversation by sending a message below"})]}):B.map(Z=>Z.type==="cycle-approval"&&Z.cycleData?e.jsx("div",{className:"mb-3 px-4",children:e.jsxs("div",{className:"flex flex-col items-start",children:[Z.sender&&e.jsx("span",{className:"text-muted-foreground mb-1 px-3",style:{fontSize:"12px"},children:Z.sender}),e.jsx(Lg,{cycle:Z.cycleData,onApprove:S,onDefer:O}),e.jsx("span",{className:"text-muted-foreground mt-1 px-3",style:{fontSize:"11px"},children:Z.timestamp})]})},Z.id):Z.type==="ticket-approval"&&Z.ticketData?e.jsx("div",{className:"flex justify-start mb-3 px-4",children:e.jsxs("div",{className:"flex flex-col items-start max-w-[85%]",children:[Z.sender&&e.jsx("span",{className:"text-muted-foreground mb-1 px-3",style:{fontSize:"12px"},children:Z.sender}),e.jsx(C2,{ticketNumber:Z.ticketData.ticketNumber,videoThumbnail:Z.ticketData.videoThumbnail,videoUrl:Z.ticketData.videoUrl,creditValue:Z.ticketData.creditValue,onApprove:()=>{var Q;console.log("Ticket approved:",(Q=Z.ticketData)==null?void 0:Q.ticketNumber)}})]})},Z.id):Z.aiData?e.jsxs("div",{children:[e.jsx(Rd,{...Z}),e.jsx("div",{className:"px-7 -mt-1 mb-1",children:z.createdTickets.has(Z.aiData.aiMessageId)?e.jsxs("span",{className:"inline-flex items-center gap-1 text-green-600",style:{fontSize:"12px"},children:[e.jsx(kt,{className:"w-3 h-3"}),"Ticket Created"]}):e.jsxs("button",{onClick:()=>P(Z.aiData),className:"inline-flex items-center gap-1 text-primary hover:text-primary/80 transition-colors",style:{fontSize:"12px"},children:[e.jsx(Ut,{className:"w-3 h-3"}),"Create Ticket"]})})]}
26,Z.id):e.jsx(Rd,{...Z},Z.id)),e.jsx("div",{ref:x})]}),e.jsx("div",{className:"border-t border-border p-3 bg-card",children:e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsx("div",{className:"flex-1 bg-muted rounded-[20px] px-4 py-2",children:e.jsx("textarea",{value:i,onChange:Z=>d(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&!Z.shiftKey&&(Z.preventDefault(),Y())},placeholder:"Message...",disabled:m,className:"w-full bg-transparent resize-none outline-none max-h-24 text-foreground placeholder:text-muted-foreground disabled:opacity-50",rows:1,style:{height:"auto",minHeight:"24px"}})}),e.jsx("button",{onClick:Y,disabled:!i.trim()||m,className:"w-9 h-9 bg-primary rounded-full flex items-center justify-center disabled:opacity-40 disabled:cursor-not-allowed hover:shadow-lg active:scale-95 transition-all flex-shrink-0",children:m?e.jsx(fe,{className:"w-4 h-4 text-primary-foreground animate-spin"}):e.jsx(An,{className:"w-4 h-4 text-primary-foreground ml-0.5"})})]})}),e.jsx(k2,{open:c,onOpenChange:u,currentLogoUrl:r,projectName:s,onSave:J}),e.jsx(zg,{open:D,onOpenChange:L,channelId:n,defaultTicketName:($==null?void 0:$.ticketName)??"",description:($==null?void 0:$.description)??"",projects:z.projects,isCreating:z.isCreating,onCreateTicket:U})]})}function F2({onLogoClick:t}={}){const{token:s}=pt(),[n,r]=l.useState(!1),[a,o]=l.useState(null),[i,d]=l.useState(void 0),[m,p]=l.useState(!1),[c,u]=l.useState(null),{totalCredits:x,projects:h,loading:b,error:f,refreshCredits:g}=rv(s),{logos:y}=Ra(s),j=k=>{const w=k.replace("#",""),I=(y==null?void 0:y[w])||(y==null?void 0:y[w.toLowerCase()]);if(I)return I;const A=w.toLowerCase();return A.includes("chick")||A.includes("fil")?ka:A.includes("figma")?Sa:A.includes("delta")?ni:Vr},v=x??0,T=v/2e3*100;return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{title:"Credits",showTitle:!0,onLogoClick:t}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"bg-primary rounded-2xl p-6 shadow-lg",children:[e.jsx("p",{className:"text-primary-foreground/80 mb-2",children:"Available Credits"}),b?e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-10 h-10"})}),e.jsx("p",{className:"text-primary-foreground text-xl",children:"Loading credits..."})]}):f?e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-primary-foreground text-xl mb-2",children:"Unable to load"}),e.jsx("p",{className:"text-primary-foreground/80 text-sm",children:f})]}):e.jsx("p",{className:"text-primary-foreground mb-4",style:{fontSize:"3rem"},children:v.toLocaleString()}),!b&&!f&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"bg-primary-foreground/20 rounded-full h-2 overflow-hidden backdrop-blur-sm mb-2",children:e.jsx("div",{className:"bg-primary-foreground h-full rounded-full transition-all duration-500",style:{width:`${T}%`}})}),e.jsx("p",{className:"text-primary-foreground/80",children:T>50?"Healthy balance":T>20?"Running low":"Critical - reload soon"})]})]}),e.jsxs("div",{className:"mt-4 flex gap-3",children:[e.jsxs(ke,{className:"flex-1 h-12 rounded-xl shadow-md",onClick:()=>{var k,w;o(((k=h[0])==null?void 0:k.name)||null),d((w=h[0])==null?void 0:w.clientId),r(!0)},disabled:b,children:[e.jsx(Af,{className:"w-4 h-4 mr-2"}),"Buy Credits"]}),e.jsx(ke,{className:"h-12 rounded-xl",variant:"outline",onClick:g,disabled:b,children:e.jsx(yt,{className:`w-4 h-4 ${b?"animate-spin":""}`})})]}),f&&e.jsxs("div",{className:"mt-4 p-4 bg-destructive/10 border border-destructive/20 rounded-xl flex items-start gap-3",children:[e.jsx(gs,{className:"w-5 h-5 text-destructive flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-destructive font-medium mb-1",children:"Error loading credits"}),e.jsx("p",{className:"text-destructive/80 text-sm",children:f})]})]})]}),e.jsxs("div",{className:"px-4 pb-6",children:[e.jsx("h3",{className:"text-muted-foreground uppercase tracking-wide mb-3",style:{fontSize:"12px",fontWeight:"var(--font-weight-medium)"},children:"Credits by Channel"}),b?e.jsx("div",{className:"flex justify-center items-center py-8",children:e.jsx("div",{className:"animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-10 h-10"})})}):h.length>0?e.jsx("div",{className:"space-y-2",children:h.map(k=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-card rounded-xl border border-border",children:[e.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{width:"40px",height:"40px",borderRadius:"8px",border:"1px solid var(--border)"},children:j(k.name).startsWith("emoji:")?e.jsx("span",{style:{fontSize:"1.5rem"},children:j(k.name).replace("emoji:","")}):e.jsx("img",{src:j(k.name),alt:k.name,className:"w-full h-full object-cover",style:{padding:"6px"}})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("p",{className:"text-foreground font-medium truncate",children:["#",k.name]})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("span",{className:"text-primary font-semibold",children:k.credits.toLocaleStr
26ing()}),e.jsx("button",{onClick:w=>{w.stopPropagation(),o(k.name),d(k.clientId),r(!0)},className:"text-xs px-2 py-1 rounded-md bg-primary/10 text-primary hover:bg-primary/20 transition-colors",children:"Buy"}),h.length>1&&e.jsx("button",{onClick:w=>{w.stopPropagation(),u(k.name),p(!0)},className:"text-xs px-2 py-1 rounded-md bg-muted text-muted-foreground hover:bg-accent transition-colors",children:"Transfer"})]})]},k.channelId))}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No channels found"})]})]}),n&&a&&e.jsx(av,{clientId:i,channelName:a,onClose:()=>r(!1),onPurchaseComplete:g}),m&&c&&e.jsx(ov,{channelName:c,channels:h,onClose:()=>p(!1),onTransferComplete:g})]})}function Ca({className:t,...s}){return e.jsx(hj,{"data-slot":"switch",className:$e("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-switch-background focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(fj,{"data-slot":"switch-thumb",className:$e("bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}const Og=[{type:"ticket_assigned_department",label:"New ticket for your team",description:"A ticket was created or assigned to a department you're in.",category:"Tickets",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"ticket_assigned_user",label:"Ticket assigned to you",description:"A ticket was assigned directly to you.",category:"Tickets",audience:"staff",userMutable:!1,defaultEnabled:!0},{type:"ticket_followed",label:"Tickets you follow",description:"Updates to tickets you've chosen to follow.",category:"Tickets",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"ticket_reminder",label:"Ticket reminders",description:"A one-time reminder you set on a ticket fired.",category:"Tickets",audience:"staff",userMutable:!1,defaultEnabled:!0},{type:"chat_slack_relay_failed",label:"Message not delivered to Slack",description:"A reply you sent could not be relayed to a client who is still reading in Slack. They have not seen it.",category:"Messages",audience:"staff",userMutable:!1,defaultEnabled:!0},{type:"team_dm",label:"Team direct messages",description:"Direct messages from teammates.",category:"Messages",audience:"staff",userMutable:!1,defaultEnabled:!0},{type:"customer_message",label:"Project messages",description:"Messages sent to a customer about their project.",category:"Messages",audience:"customer",userMutable:!1,defaultEnabled:!0},{type:"ticket_status",label:"Ticket status updates",description:"Ticket progress surfaced to the customer in-app.",category:"Tickets",audience:"customer",userMutable:!1,defaultEnabled:!0},{type:"release",label:"New Bucky release",description:"A new Bucky build was published.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"promo_campaign_flagged",label:"Promo campaign flagged",description:"A captured promo campaign failed QA.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"promo_client_lapsed",label:"Promo client went quiet",description:"A monitored client stopped sending campaigns for longer than their usual rhythm.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"job_report",label:"Job reports",description:"An AI job-report video is ready for a senior dev to review, or was approved into human QA (ticketJobReports/).",category:"Tickets",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"pr_ready",label:"PR ready",description:"An autonomous run finished with a pull request open for review (aiPipeline/onAiRunFinished.ts).",category:"Tickets",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"ai_pipeline",label:"AI pipeline problems",description:"Something stopped the autonomous pipeline: a run blocked on a decision or failed, the runner is offline with runs pending, or a store has no repo configured. Routine chatter (rush dispatched, gate skips) no longer notifies â see the AI Runs screen.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"theme_sync",label:"Theme sync issues",description:"A mainâstaging theme sync hit a conflict or error.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"content_pack_pending",label:"Content pack awaiting approval",description:"A social distribution pack was pushed and needs one approval.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"content_post_failed",label:"Content post failed",description:"A scheduled social post failed â including dead platform tokens.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"seo_auto_apply",label:"SEO auto-apply digest",description:"AI SEO changes were auto-applied to enrolled stores.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"meeting_tickets_ready",label:"Meeting tickets need triage",description:"A meeting transcript was analyzed and the extracted tickets need a project assigned.",category:"Tickets",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"change_request_stalled",label:"Customer change request needs attention",description:"A customer asked for rework and it has not moved: either nothing picked it up, or the finished work is waiting on a QA review. Escalates at 4h, 24h and 48h.",category:"Tickets",audience:"staff",userMutable:!1,defaultEnabled:!0},{type:"change_request_opened",label:"Customer asked for changes",description:"A customer requested rework on work we already delivered. Carries their note and the ticket the rework is tracked on.",category:"Tickets",audience:"staff",userMutable:!1,defaultEnabled:!0}
26,{type:"send_suppressed",label:"Blocked send to a suppressed contact",description:"We tried to email someone who is blacklisted, retired, deceased, or has left their company, and the send was blocked. Repeated blocks roll up onto one notification.",category:"System",audience:"staff",userMutable:!1,defaultEnabled:!0},{type:"email_delivery_failed",label:"Email bounced or was refused",description:"A hard bounce marked an address undeliverable, or a recipient reported spam / unsubscribed. Hard bounces block that address automatically; spam and unsubscribes are flagged for a human decision.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"intake_session_complete",label:"Client assets received",description:"A client finished an Asset Intake upload session â files are scanned, versioned and ready to review on the Asset Intake screen.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"intake_infected_upload",label:"Infected upload quarantined",description:"A client upload failed the virus scan. The file stays in quarantine and was never stored; the uploader saw a neutral failure message.",category:"System",audience:"staff",userMutable:!1,defaultEnabled:!0},{type:"subscription_ending",label:"Subscription ending",description:"A Stripe or Recharge subscription is set to cancel at period end, or was cancelled outright. Fires once per cancellation.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"subscription_payment_problem",label:"Subscription payment failed or past due",description:"A recurring charge failed, the subscription is past due, or a send-invoice bill went past its due date with nothing retrying it. Fires once per invoice attempt.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"subscription_renewal_upcoming",label:"Yearly renewal in 14 days",description:"An annual subscription (domain, email, WCAG) renews within two weeks.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"subscription_card_expiring",label:"Card expires before next charge",description:"The card on file for a subscription expires before its next billing date, so that charge will fail unless the client updates it.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"subscription_no_payment_method",label:"No card on file before a charge",description:"A subscription (usually one sold ahead of time) will try to charge within two weeks and the customer has no payment method. Send the portal link.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"subscription_weekly_summary",label:"Weekly subscriptions summary",description:"Monday morning roll-up of every subscription charge expected this week (Stripe + Recharge, CAD-converted), with anything past due or ending.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0},{type:"architecture_missing",label:"Client repo has no ARCHITECTURE.md",description:"A client asked a code question and the repo mapped to their live theme has no ARCHITECTURE.md, so the reply drafter skipped the code answer. Sent to Development once per repo every 14 days; clients never see it.",category:"System",audience:"staff",userMutable:!0,defaultEnabled:!0}],Jm=Og.filter(t=>t.audience==="staff"&&t.userMutable),_2=Og.filter(t=>t.audience==="staff"),W2=[{value:"instant",label:"Instant"},{value:"15m",label:"Every 15 min"},{value:"30m",label:"Every 30 min"},{value:"1h",label:"Hourly"}],U2=[{minutes:15,label:"Every 15 minutes"},{minutes:60,label:"Hourly"},{minutes:240,label:"Every 4 hours"},{minutes:1440,label:"Once a day"}];function H2({onBack:t,onLogout:s,onLogoClick:n,onAdminMode:r,onManageLogos:a,chatDigest:o,chatIsStaff:i}){var P;const{user:d,isAdminDomain:m,token:p}=pt(),[c,u]=l.useState((o==null?void 0:o.enabled)??!i),[x,h]=l.useState((o==null?void 0:o.intervalMinutes)??60),[b,f]=l.useState(!1),g=async(U,V)=>{u(U),h(V),f(!0);try{await re("chatUpdateDigest",{enabled:U,intervalMinutes:V}),ce.success(U?"Unread-chat emails on":"Unread-chat emails off")}catch{ce.error("Couldn't save â try again"),u((o==null?void 0:o.enabled)??!i),h((o==null?void 0:o.intervalMinutes)??60)}finally{f(!1)}},[y,j]=l.useState(!1),[v,T]=l.useState(!1),[k,w]=l.useState([]),[I,A]=l.useState(!1),[E,C]=l.useState(null),[N,S]=l.useState("instant"),[O,R
26]=l.useState(!1);l.useEffect(()=>{if(!m)return;let U=!1;return re("getNotificationSettings",{}).then(V=>{U||(w(Array.isArray(V==null?void 0:V.myMutedTypes)?V.myMutedTypes:[]),V!=null&&V.myPushDigestInterval&&S(V.myPushDigestInterval),A(!0))}).catch(V=>{console.error("[settings] load notification prefs failed:",V),U||A(!0)}),()=>{U=!0}},[m,p]);const z=l.useCallback(async(U,V)=>{const M=V?k.filter(W=>W!==U):k.includes(U)?k:[...k,U],F=k;w(M),C(U);try{const W=await re("setMyNotificationMutes",{mutedTypes:M},p??void 0);Array.isArray(W==null?void 0:W.mutedTypes)&&w(W.mutedTypes)}catch(W){w(F),ce.error("Could not save notification setting",{description:W==null?void 0:W.message})}finally{C(null)}},[k,p]),D=l.useCallback(async U=>{if(U===N)return;const V=N;S(U),R(!0);try{const M=await re("setMyPushDigestInterval",{pushDigestInterval:U},p??void 0);M!=null&&M.pushDigestInterval&&S(M.pushDigestInterval)}catch(M){S(V),ce.error("Could not save notification pace",{description:M==null?void 0:M.message})}finally{R(!1)}},[N,p]),L=(d==null?void 0:d.displayName)||((P=d==null?void 0:d.email)==null?void 0:P.split("@")[0])||"User",$=(d==null?void 0:d.email)||"",q=async()=>{j(!0),T(!1);try{console.log("ðï¸ Clearing all cache..."),await qn.clear(),console.log("â
Cache cleared successfully"),T(!0),setTimeout(()=>{console.log("ð Reloading page to fetch fresh data..."),window.location.reload()},1e3)}catch(U){console.error("Error clearing cache:",U),j(!1)}};return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{title:"Settings",showTitle:!0,onLogoClick:n}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsx("div",{className:"bg-card mt-6 mx-4 rounded-2xl p-4 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-16 h-16 bg-primary rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx(ei,{className:"w-8 h-8 text-primary-foreground"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-foreground",children:L}),e.jsx("p",{className:"text-muted-foreground",children:$})]})]})}),o!==void 0&&e.jsxs("div",{className:"mt-6 px-4",children:[e.jsx("h3",{className:"text-muted-foreground uppercase tracking-wide mb-3 px-1",children:"Chat notifications"}),e.jsxs("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm",children:[e.jsxs("div",{className:"p-4 flex items-center gap-3 border-b border-border",children:[e.jsx("div",{className:"w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(Dn,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-foreground font-medium",children:"Email me about unread messages"}),e.jsx("p",{className:"text-muted-foreground",children:"When you're not in the app"})]}),e.jsx(Ca,{checked:c,disabled:b,onCheckedChange:U=>g(U,x)})]}),c&&e.jsxs("div",{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(ms,{className:"w-5 h-5 text-primary"})}),e.jsx("div",{className:"flex-1",children:e.jsx("p",{className:"text-foreground font-medium",children:"How often, at most"})}),e.jsx("select",{value:x,disabled:b,onChange:U=>g(!0,Number(U.target.value)),className:"bg-muted text-foreground rounded-lg px-3 py-2 border border-border",children:U2.map(U=>e.jsx("option",{value:U.minutes,children:U.label},U.minutes))})]})]})]}),m&&r&&e.jsx("div",{className:"mt-6 px-4",children:e.jsx("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm",children:e.jsxs("button",{onClick:r,className:"w-full p-4 flex items-center justify-between hover:bg-muted active:bg-muted/80 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(Ao,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-foreground font-medium",children:"Admin Mode"}),e.jsx("p",{className:"text-muted-foreground",children:"Access admin features"})]})]}),e.jsx(Rt,{className:"w-5 h-5 text-muted"})]})})}),m&&e.jsxs("div",{className:"mt-6 px-4",children:[e.jsx("h3",{className:"text-muted-foreground uppercase tracking-wide mb-3 px-1",children:"Notification pace"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-3 px-1",children:"How often push alerts arrive. Batching quiets constant pings â your Notifications list still updates live, and urgent alerts (client messages, DMs, high-priority) always come through right away."}),e.jsxs("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(ms,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-foreground",children:"Push roll-up"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Group updates and ping on a schedule."})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:W2.map(U=>{const V=N===U.value;return e.jsx("button",{onClick:()=>D(U.value),disabled:!I||O,className:`rounded-xl px-3 py-2 text-sm transition-colors border ${V?"bg-primary text-primary-foreground border-primary":"bg-muted text-foreground border-border hover:bg-muted"}`,style:{opacity:!I||O?.6:1},children:U.label},U.value)})})]})]}),m&&e.jsxs("div",{className:"mt-6 px-4",children:[e.jsx("h3",{className:"text-muted-foreground uppercase tracking-wide mb-3 px-1",children:"Notifications"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-3 px-1",children:"Turn off the notifications you don't want. This silences them everywhere â in-app, push and email â just for you."}),e.jsx("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm",children:Jm.map((U,V)=>{const M=!k.includes(U.type);return e.jsxs("div",{className:`p-4 flex items-center justify-between gap-3 ${V<Jm.length-1?"border-b border-border":""}`,children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(Dn,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-foreground",children:U.label}),e.jsx("p",{className:"text-muted-foreground text-sm",children:U.description})]})]}),e.jsx(Ca,{checked:M,disabled:!I||E===U.type,onCheckedChange:F=>z(U.type,F)})]},U.type)})})]}),a&&e.jsxs("div",{className:"mt-6 px-4",children:[e.jsx("h3",{className:"text-muted-foreground uppercase tracking-wide mb-3 px-1",children:"Company"}),e.jsx("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm",children:e.jsxs("button",{onClick:a,className:"w-full p-4 flex items-center justify-between hover:bg-muted active:bg-muted/80 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(eg,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-foreground font-medium",children:"Company Logo"}),e.jsx("p",{className:"text-muted-foreground",children:"Upload your company logo"})]})]}),e.jsx(Rt,{className:"w-5 h-5 text-muted"})]})})]}),e.jsxs("div",{className:"mt-6 px-4",children:[e.jsx("h3",{className:"text-muted-foreground uppercase tracking-wide mb-3 px-1",children:"Data Management"}),e.jsx("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm",children:e.jsx("button",{onClick:q,disabled:y,className:"w-full p-4 flex items-center justify-between hover:bg-muted active:bg-muted/80 transition-colors disabled:opacity-50",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${v?"bg-green-500/20":"bg-blue-500/20"}`,children:e.jsx(yt,{className:`w-5 h-5 ${v?"text-green-500":"text-blue-500"} ${y?"animate-spin":""}`})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-foreground font-medium",children:v?"Cache Cleared!":"Clear Cache"}),e.jsx("p",{className:"text-muted-foreground",children:v?"All data refreshed":"Refresh all company and project data"})]})]})})})]}),e.jsx("div",{className:"mt-6 px-4",children:e.jsx("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm",children:e.jsxs("button",{onClick:()=>{const U=window.SunbowlCapture;U&&typeof U.startCapture=="function"?U.startCapture():U&&typeof U.activate=="function"&&U.activate()},className:"w-full p-4 flex items-center justify-between hover:bg-muted active:bg-muted/80 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-purple-500/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(mn,{className:"w-5 h-5 text-purple-500"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-foreground font-medium",children:"Send Feedback"}),e.jsx("p",{className:"text-muted-foreground",children:"Help us improve Bucky"})]})]}),e.jsx(Rt,{className:"w-5 h-5 text-muted"})]})})}),e.jsx("div",{className:"mt-6 px-4",children:e.jsxs("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm",children:[e.jsxs("button",{className:"w-full p-4 flex items-center justify-between hover:bg-muted active:bg-muted/80 transition-colors border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-muted rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(wa,{className:"w-5 h-5 text-muted-foreground"})}),e.jsx("p",{className:"text-foreground",children:"About Bucky"})]}),e.jsx(Rt,{className:"w-5 h-5 text-muted"})]}),e.jsx("button",{className:"w-full p-4 flex items-center justify-between hover:bg-muted active:bg-muted/80 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-muted rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(wa,{className:"w-5 h-5 text-muted-foreground"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-foreground",children:"App Version"}),e.jsx("p",{className:"text-muted-foreground",children:"1.0.0 (Build 100)"})]})]})})]})}),e.jsx("div",{className:"mt-6 px-4 pb-8",children:e.jsxs(ke,{onClick:s,variant:"destructive",className:"w-full h-12 rounded-xl",children:[e.jsx(Xw,{className:"w-4 h-4 mr-2"}),"Logout"]})})]})]})}const Zm=[{key:"scoped",label:"Scoped"},{key:"queued",label:"Queued"},{key:"progress",label:"In Progress"},{key:"review",label:"QA Review"},{key:"approval",label:"Your Approval"},{key:"complete",label:"Complete"}],q2={label:"Scoped",tone:"scoped",stageIndex:0,isComplete:!1,isActionable:!1},V2={Backlog:{label:"Scoped",tone:"scoped",stageIndex:0},"In Queue":{label:"Queued",tone:"queued",stageIndex:1},"In Progress":{label:"In progress",tone:"progress",stageIndex:2},"In Review":{label:"In QA review",tone:"review",stageIndex:3}
26,"Client Approval":{label:"Needs your approval",tone:"approval",stageIndex:4,isActionable:!0},Complete:{label:"Complete",tone:"complete",stageIndex:5,isComplete:!0},"Changes Requested":{label:"Changes requested",tone:"changes",stageIndex:3},Parked:{label:"Changes in progress",tone:"changes",stageIndex:4},Cancelled:{label:"Cancelled",tone:"hidden",stageIndex:0},Archived:{label:"Archived",tone:"hidden",stageIndex:0},"Merged (Archived)":{label:"Archived",tone:"hidden",stageIndex:0}};function jo(t){const s=V2[t];return s?{label:s.label,tone:s.tone,stageIndex:s.stageIndex,isComplete:s.isComplete??!1,isActionable:s.isActionable??!1}:{...q2}}function Y2(t){const s=jo(t.status),n=t.blockedByDisplayIds||[];if(n.length>0){const r=n.length===1?n[0]:`${n.slice(0,-1).join(", ")} and ${n[n.length-1]}`;return{...s,label:`Changes in progress â ${r}`}}return t.changeRequestParentDisplayId?{...s,label:`${s.label} · changes to ${t.changeRequestParentDisplayId}`}:s}function $g(t){switch(t){case"scoped":return"var(--muted-foreground)";case"queued":case"progress":return"var(--primary)";case"review":return"#d6a73a";case"approval":return"#caa53f";case"complete":return"#22c55e";case"changes":return"var(--destructive)";case"hidden":default:return"var(--muted-foreground)"}}function G2({status:t}){const s=jo(t),n=s.stageIndex,r=$g(s.tone),a="var(--primary)",o="#22c55e",i="var(--border)";return e.jsx("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",width:"100%",height:"52px",paddingTop:"4px"},children:Zm.map((d,m)=>{const p=m<n,c=m===n;let u,x,h;c?(u=r,x=14,h=!0):p?(u=s.isComplete?o:a,x=10,h=!0):(u=i,x=10,h=!1);const b=m===Zm.length-1,f=m<n?a:i,g=c?r:"var(--muted-foreground)";return e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"16px"},children:[e.jsx("div",{style:{flex:1,height:"2px",backgroundColor:m===0?"transparent":m<=n?a:i}}),e.jsx("div",{style:{width:`${x}px`,height:`${x}px`,borderRadius:"50%",flexShrink:0,backgroundColor:h?u:"transparent",border:h?c?`2px solid ${u}`:"none":`2px solid ${u}`,boxShadow:c?`0 0 0 3px color-mix(in srgb, ${u} 25%, transparent)`:"none",boxSizing:"border-box"}}),e.jsx("div",{style:{flex:1,height:"2px",backgroundColor:b?"transparent":f}})]}),e.jsx("div",{style:{fontSize:"10px",lineHeight:"12px",marginTop:"6px",color:g,textAlign:"center",fontWeight:c?600:400,width:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d.label})]},d.key)})})}function K2(t){if(!t)return null;const s=t.trim();return/^tick-\d+/i.test(s)?s.toUpperCase():null}function Q2(t){if(!t)return null;const s=new Date(t);return isNaN(s.getTime())?null:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function J2(t){return`color-mix(in srgb, ${t} 14%, transparent)`}function Z2({label:t,color:s}){return e.jsx("span",{style:{display:"inline-flex",alignItems:"center",flexShrink:0,padding:"3px 10px",borderRadius:999,backgroundColor:J2(s),color:s,fontSize:11.5,lineHeight:"14px",fontWeight:"var(--font-weight-semibold)",whiteSpace:"nowrap"},children:t})}function Xm({ticket:t,highlighted:s,onApprove:n,onTicketSelect:r}){const a=Y2(t),o=$g(a.tone),i=K2(t.ticketNumber),d=Q2(t.dueDate);return e.jsxs("div",{onClick:()=>r==null?void 0:r(t),role:"button",style:{cursor:"pointer",backgroundColor:s?"color-mix(in srgb, var(--primary) 8%, var(--card))":"var(--card)",border:s?"1.5px solid var(--primary)":"1px solid var(--border)",borderRadius:16,padding:16,boxShadow:s?"0 0 0 3px color-mix(in srgb, var(--primary) 22%, transparent)":"0 1px 2px rgba(0,0,0,0.04)",transition:"box-shadow 0.15s ease, border-color 0.15s ease"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[e.jsxs("div",{style:{minWidth:0,flex:1},children:[i&&e.jsx("div",{style:{fontSize:11,lineHeight:"14px",letterSpacing:"0.04em",color:"var(--muted-foreground)",fontWeight:"var(--font-weight-medium)",marginBottom:3},children:i}),e.jsx("h3",{className:"text-card-foreground",style:{fontSize:15,lineHeight:"20px",fontWeight:"var(--font-weight-semibold)",margin:0},children:t.name})]}),e.jsx(Z2,{label:a.label,color:o})]}),e.jsx("div",{style:{marginTop:14},children:e.jsx(G2,{status:t.status})}),d&&e.jsxs("div",{style:{marginTop:12,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("span",{style:{fontSize:12.5,color:"var(--muted-foreground)"},children:[a.isComplete?"Delivered":"Due"," ",d]}),e.jsx(Rt,{style:{width:16,height:16,color:"var(--muted-foreground)",flexShrink:0}})]}),a.isActionable&&e.jsxs("button",{onClick:m=>{m.stopPropagation(),n==null||n(t)},style:{marginTop:14,width:"100%",display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"11px 16px",borderRadius:12,border:"none",cursor:"pointer",backgroundColor:"var(--secondary)",color:"var(--secondary-foreground)",fontSize:14,fontWeight:"var(--font-weight-semibold)",boxShadow:"0 1px 3px rgba(0,0,0,0.12)"},children:["Review & approve",e.jsx(Ef,{style:{width:16,height:16}})]})]})}function wc(){return e.jsxs("div",{style:{backgroundColor:"var(--card)",border:"1px solid var(--border)",borderRadius:16,padding:16},children:[e.jsx("div",{style:{height:14,width:"40%",borderRadius:6,backgroundColor:"var(--muted)",marginBottom:10}}),e.jsx("div",{style:{height:18,width:"75%",borderRadius:6,backgroundColor:"var(--muted)",marginBottom:16}}),e.jsx("div",{style:{height:8,width:"100%",borderRadius:6,backgroundColor:"var(--muted)"}})]})}function ep({children:t}){return e.jsx("h2",{className:"text-muted-foreground",style:{fontSize:12,letterSpacing:"0.06em",textTransform:"uppercase",fontWeight:"var(--font-weight-semibold)",margin:"0 0 12px"},children:t})}function X2({token:t,projectId:s,projectName:n,ticketDisplayId:r,onBack:a,onApprove:o,onTicketSelect:i,onResolveDeepLinkTicket:d,onLogoClick:m,onNewRequest:p}){const{tickets:c,loading:u}=Cf(t??null,s??null),x=c.filter(j=>jo(j.status).tone!=="hidden"),h=r?r.trim().toUpperCase():null,b=j=>!!h&&((j.ticketNumber||"").trim().toUpperCase()===h||(j.id||"").trim().toUpperCase()===h),f=ee.useRef(!1);ee.useEffect(()=>{if(f.current||u||!h||!d)return;const j=x.find(v=>b(v));j&&(f.current=!0,d(j))},[u,h,c,d]);const g=x.filter(j=>!jo(j.status).isComplete),y=x.filter(j=>jo(j.status).isComplete);return g.sort((j,v)=>{const T=b(j)?0:1,k=b(v)?0:1;return T-k}),e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{onBack:a,onLogoClick:m,contextualTitle:n||"Project status"}),p&&e.jsx("div",{style:{padding:"16px 16px 8px"},children:e.jsxs("button",{onClick:p,className:"bg-primary text-primary-foreground",style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"12px 16px",borderRadius:12,border:"none",cursor:"pointer",fontSize:14.5,fontWeight:"var(--font-weight-semibold)",boxShadow:"0 1px 3px rgba(0,0,0,0.12)"},children:[e.jsx(Ut,{style:{width:18,height:18}}),"New request"]})}),e.jsx("div",{className:"flex-1",style:{padding:"8px 16px 24px"},children:u?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,color:"var(--muted-foreground)",fontSize:14,marginBottom:4},children:[e.jsx("span",{className:"animate-spin",style:{animationDuration:"2s",display:"inline-flex"},children:e.jsx("img",{src:ks,alt:"",style:{width:22,height:22}})}),"Loading your ticketsâ¦"]}),e.jsx(wc,{}),e.jsx(wc,{}),e.jsx(wc,{})]}):x.length===0?e.jsxs("div",{style:{textAlign:"center",padding:"56px 16px",color:"var(--muted-foreground)"},children:[e.jsx("p",{style:{fontSize:15,margin:0},children:"No tickets yet for this project."}),p&&e.jsx("p",{style:{fontSize:13,marginTop:8},children:"Start one with âNew requestâ above."})]}):e.jsxs(e.Fragment,{children:[g.length>0&&e.jsxs("section",{style:{marginBottom:y.length>0?28:0},children:[e.jsx(ep,{children:"In progress"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:14},children:g.map(j=>e.jsx(Xm,{ticket:j,highlighted:b(j),onApprove:o,onTicketSelect:i},j.id))})]}),y.length>0&&e.jsxs("section",{children:[e.jsx(ep,{children:"Completed"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:14},children:y.map(j=>e.jsx(Xm,{ticket:j,highlighted:b(j),onApprove:o,onTicketSelect:i},j.id))})]})]})})]})}const Bg={"Client Approval":"Client Review"},hl=["AI Review","Deferred","Backlog","Blocked","Changes Requested","Need Clarification","Awaiting Approval","In Queue","In Progress","In Review","Client Approval","Merge","Merged Away","Sunset","Parked","Complete","Cancelled","Archived"],Fg=["","Quick Fix","Small Task","Medium Task","Large Task"];function Wr(t){return t?Bg[t]||t:""}const Io=["Development","Marketing","QA","Administration"],_g=["PROSPECT","CLIENT","PAST_CLIENT","SUBSCRIBER","NEWSLETTER","VENDOR","PARTNER","TEAM","SERVICE_ACCOUNT","NOTIFICATION","BLACKLIST","OTHER"],Mu
26={PROSPECT:"Prospect",CLIENT:"Client",PAST_CLIENT:"Past Client",SUBSCRIBER:"Subscriber",NEWSLETTER:"Newsletter",VENDOR:"Vendor",PARTNER:"Partner",TEAM:"Team",SERVICE_ACCOUNT:"Service Account",NOTIFICATION:"Notification",BLACKLIST:"Disabled",OTHER:"Other"},eS=["active","retired","deceased","left_company","unknown"],Wg={active:"Active",retired:"Retired",deceased:"Deceased",left_company:"Left the company",unknown:"Unknown"};function Pu(t){return t||"active"}function Md(t){return Pu(t)!=="active"}const tS=["bounced","no_mx"];function Pd(t){var s,n,r;if(t.doNotContact===!0){const a=(s=t.doNotContactReason)==null?void 0:s.trim();return{suppressed:!0,label:"Do not contact",reason:a?`Do not contact â ${a}`:"Do not contact"}}if((n=t.categories)!=null&&n.includes("BLACKLIST"))return{suppressed:!0,label:"Do not contact",reason:"Do not contact â Disabled"};if(Md(t.personStatus)){const a=Wg[Pu(t.personStatus)],o=(r=t.personStatusNote)==null?void 0:r.trim();return{suppressed:!0,label:a,reason:o?`Contact status is ${a} â ${o}`:`Contact status is ${a}`}}return t.emailStatus&&tS.includes(t.emailStatus)?{suppressed:!0,label:t.emailStatus==="bounced"?"Bounced":"No MX",reason:t.emailStatus==="bounced"?"Email address has hard bounced":"Email domain does not accept mail (no MX record)"}:{suppressed:!1,label:null,reason:null}}const sS={lead:["PROSPECT"],opportunity:["PROSPECT"],customer:["CLIENT"],subscriber:["SUBSCRIBER"],other:["OTHER"]};function nS(t){if(!t)return[];const s=t.trim().toLowerCase();return sS[s]||[]}function sr(t){if(!t)return null;let s=null;try{t instanceof Date?s=t:typeof t.toDate=="function"?s=t.toDate():typeof t.seconds=="number"?s=new Date(t.seconds*1e3):typeof t._seconds=="number"?s=new Date(t._seconds*1e3):(typeof t=="string"||typeof t=="number")&&(s=new Date(t))}catch{return null}return!s||isNaN(s.getTime())?null:s}function el(t){if(t==null)return"";const s=sr(t);return!(s instanceof Date)||isNaN(s.getTime())?"":s.toISOString().split("T")[0]}function nt(t){const s=sr(t);return s?s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):""}const rS=t=>{switch(t){case"Complete":return"â ";case"Backlog":return"â";default:return"ð"}},aS=t=>{switch(t){case"Complete":return"text-blue-600 bg-blue-50";case"In Progress":return"text-yellow-600 bg-yellow-50";case"In Review":return"text-purple-600 bg-purple-50";case"Client Approval":return"text-cyan-700 bg-cyan-50";case"Blocked":return"text-red-600 bg-red-50";case"Backlog":return"text-gray-600 bg-gray-50";case"Cancelled":case"Archived":return"text-gray-400 bg-gray-50";default:return"text-gray-600 bg-gray-50"}};function oS({projectId:t,projectName:s,projectStatus:n,channelName:r,onBack:a,onLogoClick:o,onTicketClick:i,onReviewChanges:d}){const{token:m}=pt(),{tickets:p,loading:c,error:u,hasMore:x,loadingMore:h,loadMore:b}=Cf(m,t),[f,g]=ee.useState(!1),y=ee.useRef(null),[j,v]=ee.useState(()=>localStorage.getItem("ticketFilter")||"All"),[T,k]=ee.useState(!1);ee.useEffect(()=>{localStorage.setItem("ticketFilter",j)},[j]),ee.useEffect(()=>{if(!y.current||!x||h)return;const A=new IntersectionObserver(E=>{E[0].isIntersecting&&(console.log("Loading more tickets via intersection observer"),b())},{threshold:.1});return A.observe(y.current),()=>A.disconnect()},[x,h,b]);const w=p.length>0?Math.round(p.filter(A=>A.status==="Complete").length/p.length*100):0,I=j==="All"?p:p.filter(A=>A.status===j);return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{onBack:a,onLogoClick:o}),!c&&!u&&p.length>0&&e.jsxs("div",{className:"bg-card px-4 py-4 border-b border-border",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Overall Progress"}),e.jsxs("span",{className:"text-sm font-semibold text-primary",children:[w,"%"]})]}),e.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5 overflow-hidden",children:e.jsx("div",{className:"progress-bar-shimmer h-2.5 rounded-full transition-all duration-300",style:{width:`${w}%`}})}),e.jsx("style",{children:` 27 .progress-bar-shimmer { 28 background: linear-gradient( 29 90deg, 30 #3b82f6 0%, 31 #60a5fa 25%, 32 #93c5fd 50%, 33 #60a5fa 75%, 34 #3b82f6 100% 35 ); 36 background-size: 200% 100%; 37 animation: shimmer 2.4s ease-in-out infinite; 38 } 39 40 @keyframes shimmer { 41 0% { 42 background-position: 200% center; 43 } 44 50% { 45 background-position: 0% center; 46 } 47 100% { 48 background-position: -200% center; 49 } 50 } 51 `}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[p.filter(A=>A.status==="Complete").length," completed"]}),e.jsxs("span",{children:[p.length," total tickets"]})]})]}),n==="In Review"&&d&&e.jsx("div",{className:"bg-card px-4 py-4 border-b border-border",children:e.jsxs("button",{onClick:d,className:"w-full flex items-center justify-center gap-2 px-6 py-3 rounded-lg font-medium transition-colors",style:{backgroundColor:"#3b82f6",color:"#ffffff",cursor:"pointer"},onMouseEnter:A=>{A.currentTarget.style.backgroundColor="#2563eb"},onMouseLeave:A=>{A.currentTarget.style.backgroundColor="#3b82f6"},children:[e.jsx(So,{className:"w-5 h-5"}),"Review Changes"]})}),n!=="In Review"&&n!=="Complete"&&e.jsx("div",{className:"bg-card px-4 py-4 border-b border-border",children:e.jsxs("button",{disabled:f,className:"w-full flex items-center justify-center gap-2 px-6 py-3 rounded-lg font-medium transition-colors",style:{backgroundColor:f?"#f87171":"#ef4444",color:"#ffffff",cursor:f?"wait":"pointer",opacity:f?.7:1},onMouseEnter:A=>{f||(A.currentTarget.style.backgroundColor="#dc2626")},onMouseLeave:A=>{f||(A.currentTarget.style.backgroundColor="#ef4444")},onClick:()=>
51{if(f)return;g(!0);const A=window.open("about:blank","_blank");fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/captureActivate",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m}`},body:JSON.stringify({projectId:t})}).then(E=>E.json()).then(E=>{E.activationUrl&&A?A.location.href=E.activationUrl:A&&A.close()}).catch(()=>{A&&A.close()}).finally(()=>g(!1))},children:[f?e.jsx(fe,{className:"w-5 h-5 animate-spin"}):e.jsx(mn,{className:"w-5 h-5"}),f?"Opening Capture...":"Leave Project Feedback"]})}),e.jsxs("div",{className:"flex-1 bg-card",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border flex items-center justify-between",children:[e.jsxs("span",{className:"text-muted-foreground uppercase tracking-wide",style:{fontSize:"12px",fontWeight:"var(--font-weight-medium)"},children:[j==="All"?"All Tickets":j,!c&&!u&&I.length>0&&e.jsxs("span",{className:"ml-2 text-foreground",children:["(",I.length,x?"+":"",")"]})]}),!c&&!u&&p.length>0&&e.jsx("button",{onClick:()=>k(!0),className:`p-2 rounded-lg transition-colors relative ${j!=="All"?"bg-primary hover:bg-primary/90":"hover:bg-accent"}`,children:e.jsx(qw,{className:`w-4 h-4 ${j!=="All"?"text-primary-foreground":"text-muted-foreground"}`})})]}),c&&e.jsx("div",{className:"flex justify-center items-center py-16",children:e.jsx("div",{className:"animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-12 h-12"})})}),u&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx(gs,{className:"w-12 h-12 text-destructive mb-4"}),e.jsx("h3",{className:"text-foreground mb-2",children:"Error Loading Tickets"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:u})]}),!c&&!u&&I.length>0&&e.jsxs("div",{className:"divide-y divide-border",children:[I.map(A=>e.jsx("div",{className:"px-4 py-4 hover:bg-accent transition-colors cursor-pointer",onClick:()=>i==null?void 0:i(A),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl flex-shrink-0 mt-0.5",children:rS(A.status)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-foreground font-medium mb-1",children:A.name}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${aS(A.status)}`,children:A.status}),A.dueDate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Due: ",new Date(A.dueDate).toLocaleDateString()]})]})]})]})},A.id)),x&&e.jsx("div",{ref:y,className:"px-4 py-8 text-center",children:h&&e.jsxs("div",{className:"flex justify-center items-center",children:[e.jsx("div",{className:"animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-8 h-8"})}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading more tickets..."})]})})]}),!c&&!u&&p.length>0&&I.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx("span",{style:{fontSize:"3rem",opacity:.4},children:"ð"})}),e.jsxs("h3",{className:"text-foreground mb-2",children:["No ",j," Tickets"]}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:"No tickets match the selected filter"})]}),!c&&!u&&p.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx("span",{style:{fontSize:"3rem",opacity:.4},children:"ð"})}),e.jsx("h3",{className:"text-foreground mb-2",children:"No Tickets Yet"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:"No tickets found for this project"})]})]}),T&&e.jsx("div",{className:"fixed inset-0 bg-black/50 z-50 flex items-end",onClick:()=>k(!1),children:e.jsxs("div",{className:"bg-card w-full max-w-md mx-auto rounded-t-2xl pb-8",onClick:A=>A.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-4 border-b border-border",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Filter Tickets"}),e.jsx("button",{onClick:()=>k(!1),className:"p-2 hover:bg-accent rounded-lg transition-colors",children:e.jsx(mt,{className:"w-5 h-5 text-foreground"})})]}),e.jsx("div",{className:"p-4",children:["All","Backlog","Blocked","In Progress","In Review","Client Approval","Complete"].map(A=>{const E=A==="All"?p.length:p.filter(C=>C.status===A).length;return e.jsxs("button",{onClick:()=>{v(A),k(!1)},className:`w-full flex items-center justify-between px-4 py-3 rounded-lg mb-2 transition-colors ${j===A?"bg-primary text-primary-foreground":"bg-muted hover:bg-muted/80 text-foreground"}`,children:[e.jsx("span",{className:"font-medium",children:Wr(A)}),e.jsxs("span",{className:`text-sm ${j===A?"text-primary-foreground":"text-muted-foreground"}`,children:[E," ",E===1?"ticket":"tickets"]})]},A)})})]})})]})}function iS(t){const[s,n]=l.useState(null),[r,a]=l.useState(!1),[o,i]=l.useState(null),d=l.useCallback(async(c,u="medium",x="medium")=>{var h;if(!t)return i("Authentication required"),null;a(!0),i(null);try{const b=await fetch("https://estimateticketcredits-jf3ot2tygq-uc.a.run.app",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:c,urgency:u,businessValue:x})});if(!b.ok){const g=await b.json().catch(()=>({}));throw new Error(g.error||`Failed: ${b.status}`)}const f=await b.json();if(f.success&&f.estimate)return f.estimate.confidence==="low"&&((h=f.estimate.reasoning)!=null&&h.includes("Standard estimate"))&&console.warn("â ï¸ Received fallback estimate - AI may have failed"),n(f.estimate),f.estimate;throw new Error("Invalid response format")}catch(b){return i(b.message||"Failed to estimate ticket credits"),n(null),null}finally{a(!1)}},[t]),m=l.useCallback(async c=>{if(!t){i("Authentication required"),a(!1);return}a(!0),i(null);try{const u=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getTicketEstimate",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:c})});if(u.status===404){n(null),a(!1);return}if(!u.ok){const h=await u.json().catch(()=>({}));throw new Error(h.error||`Failed: ${u.status}`)}const x=await u.json();x.success&&x.estimate?n(x.estimate):n(null)}catch(u){i(u.message||"Failed to fetch existing estimate"),n(null)}finally{a(!1)}},[t]),p=l.useCallback(()=>{n(null),i(null)},[]);return{estimate:s,loading:r,error:o,estimateCredits:d,fetchExistingEstimate:m,clearEstimate:p}}function ds({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:$e("resize-none border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-input-background px-3 py-2 text-base transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),...s})}function Ug({open:t,onOpenChange:s,ticketId:n,ticketName:r,authToken:a,onContextAdded:o}){const[i,d]=l.useState(""),[m,p]=l.useState(!1),[c,u]=l.useState(null),x=async()=>
51{if(!i.trim()){u("Please enter some additional context");return}if(!a){u("Authentication required");return}p(!0),u(null);try{const b=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/appendNotionTicket",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:n,additionalContext:i.trim()})});if(!b.ok){let f;try{f=await b.json()}catch{throw new Error("Failed to parse error response")}throw new Error((f==null?void 0:f.error)||"Failed to add context")}d(""),s(!1),o()}catch(b){console.error("Error adding context:",b),u(b.message||"Failed to add context to ticket")}finally{p(!1)}},h=()=>{d(""),u(null),s(!1)};return e.jsx(br,{open:t,onOpenChange:s,children:e.jsxs(yr,{className:"sm:max-w-md bg-card border-border",children:[e.jsxs(jr,{children:[e.jsx(vr,{className:"text-card-foreground",children:"Add More Context"}),e.jsxs(wr,{className:"text-muted-foreground",children:['Provide additional details for "',r,'" to help us estimate more accurately.']})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Jt,{htmlFor:"context",className:"text-card-foreground",children:"Additional Context"}),e.jsx(ds,{id:"context",placeholder:"Add any additional details, requirements, or clarifications about this ticket...",value:i,onChange:b=>{d(b.target.value),u(null)},className:"min-h-[120px] rounded-xl",disabled:m}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This will be appended to the ticket in Notion."})]}),c&&e.jsx("div",{className:"text-sm text-destructive bg-destructive/10 p-3 rounded-lg",children:c})]}),e.jsxs(Gr,{className:"gap-2",children:[e.jsx(ke,{variant:"outline",onClick:h,className:"rounded-xl",disabled:m,children:"Cancel"}),e.jsx(ke,{onClick:x,className:"rounded-xl",disabled:m||!i.trim(),children:m?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):"Save & Re-estimate"})]})]})})}function lS({authToken:t,ticketId:s,ticketName:n,currentMaxCredits:r,ticketStatus:a,initialRushOrder:o,isRushOrder:i,setIsRushOrder:d,onEstimateComplete:m}){const{estimate:p,loading:c,error:u,estimateCredits:x,fetchExistingEstimate:h}=iS(t),[b,f]=l.useState(!1),[g,y]=l.useState(!1),[j,v]=l.useState(!1),[T,k]=l.useState(o||!1),w=i!==void 0?i:T,I=d||k;ee.useEffect(()=>{o!==void 0&&!d&&k(o)},[o,d]),ee.useEffect(()=>{r!=null&&h(s)},[s,r,h]);const A=async()=>{const R=await x(s,"medium","medium");f(!1),R&&m&&m(R.creditRange.max)},E=async()=>{await A()},C=async()=>{if(!t)return;const R=!w,z=w;I(R);try{console.log("Updating rush order status:",R);const D=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/updateTicketRushOrder",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:s,isRushOrder:R})});if(!D.ok){let $;try{$=await D.json()}catch{$={error:"Failed to parse error response"}}throw console.error("Failed to update rush order:",$),new Error($.error||"Failed to update rush order")}let L;try{L=await D.json()}catch($){throw console.error("Failed to parse response:",$),new Error("Failed to parse response")}console.log("Rush order updated successfully:",L)}catch(D){console.error("Error updating rush order:",D),I(z),alert("Failed to update rush order. Please try again.")}},N=R=>{const z={high:"text-green-800 bg-green-50",medium:"text-yellow-800 bg-yellow-50",low:"text-orange-800 bg-orange-50",default:"text-gray-800 bg-gray-50"};return z[R]||z.default},S=R=>{switch(R){case"quick":return"â¡";case"small":return"ð¦";case"medium":return"ð¯";case"large":return"ð";default:return"ð"}},O=R=>{switch(R){case"high":return"â";case"medium":return"ð¸";case"low":return"â ï¸";default:return"ð"}};return a!=="Backlog"&&a!=="Blocked"?null:e.jsxs("div",{className:"bg-card border border-border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"bg-gradient-to-r from-purple-500 to-indigo-600 px-4 py-2",children:e.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-5 h-5 text-white"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"AI Credit Estimation"})]}),p&&e.jsxs("button",{onClick:()=>v(!0),className:"flex items-center gap-2 transition-all hover:gap-3",children:[e.jsxs("span",{className:`px-3 py-1.5 rounded-full text-xs flex items-center gap-1.5 ${N(p.confidence)}`,children:[e.jsx("span",{children:O(p.confidence)}),e.jsxs("span",{style:{fontWeight:700,textDecoration:"underline",textDecorationThickness:"2px",textUnderlineOffset:"3px"},children:[p.confidence.toUpperCase()," CLARITY"]})]}),e.jsx(wa,{className:"w-5 h-5 text-white flex-shrink-0"})]})]})}
51),e.jsxs("div",{className:"p-4",children:[!p&&!c&&!u&&r==null&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Get an AI-powered estimate based on task complexity, clarity, and urgency."}),e.jsxs("button",{onClick:A,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground font-medium py-2 px-4 rounded-lg transition-colors flex items-center justify-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Estimate Credits"]})]}),!p&&!c&&!u&&r!=null&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Credits have been set for this ticket, but no detailed estimate history was found."}),e.jsxs("button",{onClick:A,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground font-medium py-2 px-4 rounded-lg transition-colors flex items-center justify-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Generate New Estimate"]})]}),c&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(fe,{className:"w-8 h-8 text-primary animate-spin mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Analyzing ticket..."})]}),u&&!c&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-destructive/10 rounded-lg",children:[e.jsx(gs,{className:"w-5 h-5 text-destructive flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Estimation Failed"}),e.jsx("p",{className:"text-xs text-destructive/80 mt-1",children:u})]})]}),p&&!c&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-muted rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Estimated Credits"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[S(p.analysisFactors.scopeSize)," ",p.analysisFactors.scopeSize.toUpperCase()]})]}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-3xl font-bold text-foreground",children:p.creditRange.max+(w?2:0)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"credits"}),w&&e.jsx("span",{className:"text-xs text-orange-600 font-medium",children:"(+2 rush)"})]}),r!=null&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-border",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Current estimate:"}),e.jsxs("span",{className:"font-medium text-foreground",children:[r," credits"]})]}),r!==p.creditRange.max&&e.jsx("p",{className:"text-xs text-amber-600 mt-1",children:p.creditRange.max>r?"â ï¸ AI suggests higher":"â
AI suggests lower"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ao,{className:"w-5 h-5 text-yellow-500 fill-yellow-500"}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Rush Order - 2 credits"})]}),e.jsx("button",{onClick:C,style:{backgroundColor:w?"#5ab2d8":"#9ca3af",width:"44px",height:"24px"},className:"relative inline-flex items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-400 cursor-pointer",role:"switch","aria-checked":w,children:e.jsx("span",{style:{transform:w?"translateX(21px)":"translateX(2px)"},className:"inline-block h-5 w-5 rounded-full bg-white shadow-lg transition-transform duration-200 ease-in-out"})})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(gr,{className:"w-4 h-4 text-primary flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Category"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:p.taskCategory})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(gs,{className:"w-4 h-4 text-primary flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Analysis"}),e.jsx("div",{className:"max-h-24 overflow-y-auto overflow-x-auto",children:e.jsx("p",{className:"text-sm text-foreground break-words",children:p.reasoning})})]})]}),e.jsxs("button",{onClick:()=>f(!b),className:"w-full text-sm text-primary hover:text-primary/80 font-medium py-2 transition-colors",children:[b?"Hide":"Show"," Detailed Analysis"]}),b&&e.jsxs("div",{className:"space-y-3 pt-3",children:[p.technicalKeywords.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs font-semibold text-foreground mb-2 uppercase tracking-wide",children:"Technical Keywords"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:p.technicalKeywords.map((R,z)=>e.jsx("span",{className:"px-2 py-1 bg-muted text-xs text-muted-foreground rounded",children:R},z))})]}),p.recommendations&&p.recommendations.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-xs font-semibold text-foreground mb-2 uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Iw,{className:"w-3 h-3"}),"Recommendations"]}),e.jsx("ul",{className:"space-y-1",children:p.recommendations.map((R,z)=>e.jsxs("li",{className:"text-xs text-muted-foreground flex items-start gap-2",children:[e.jsx("span",{className:"text-primary mt-0.5",children:"â¢"}),e.jsx("span",{children:R})]},z))})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>y(!0),className:"flex-1 text-sm bg-primary/10 text-primary hover:bg-primary/20 font-medium py-2 px-4 roun
51ded-lg transition-colors",children:"Add More Context"}),e.jsx("button",{onClick:A,className:"flex-1 text-sm text-muted-foreground hover:text-foreground font-medium py-2 px-4 transition-colors border border-border rounded-lg hover:bg-accent",children:"Re-estimate"})]})]})]}),e.jsx(Ug,{open:g,onOpenChange:y,ticketId:s,ticketName:n,authToken:t,onContextAdded:E}),e.jsx(Kl,{open:j,onOpenChange:v,children:e.jsxs(Ql,{className:"bg-card border-border h-auto max-h-[85vh] !flex !flex-col !gap-0 p-0 overflow-hidden",style:{width:"min(410px, calc(100vw - 2rem))"},children:[e.jsx("div",{className:"flex-shrink-0 px-4 sm:px-6 pt-4 sm:pt-6 pb-3 sm:pb-4 border-b border-border bg-card",children:e.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-card-foreground flex items-center gap-2",children:[e.jsx(wa,{className:"w-4 h-4 sm:w-5 sm:h-5 text-primary"}),"How We Estimate Credits"]})}),e.jsx("div",{className:"overflow-y-auto px-4 sm:px-6 py-4 flex-1 min-h-0",style:{maxHeight:"calc(85vh - 140px)"},children:e.jsxs("div",{className:"text-muted-foreground space-y-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-foreground mb-2",children:"Our Estimation Process"}),e.jsx("p",{className:"text-sm",children:"Our AI model instantly analyzes the ticket and provides a baseline estimate, which our Lead Developer then reviews and refines based on the following criteria:"})]}),e.jsxs("div",{className:"bg-muted rounded-lg p-3 space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"ð Technical Complexity"}),e.jsx("p",{className:"text-xs",children:"How technically challenging is the work? Custom development vs. standard Shopify features."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"ð¯ Clarity Score"}),e.jsx("p",{className:"text-xs",children:"How clear and well-defined are the requirements? Clear specs = more accurate estimates."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"â¡ Urgency Level"}),e.jsx("p",{className:"text-xs",children:"Time sensitivity affects resource allocation (Low: 0.8x | Medium: 1.0x | High: 1.2x | Critical: 1.5x)."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"ð¼ Business Value"}),e.jsx("p",{className:"text-xs",children:"Strategic importance to your business (Low: 0.8x | Medium: 1.0x | High: 1.1x | Strategic: 1.3x)."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"ðï¸ Shopify Specialty"}),e.jsx("p",{className:"text-xs",children:"We're Shopify experts! Standard Shopify work gets a discount (0.7x-1.0x)."})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-foreground mb-2",children:"Credit Ranges by Task Size"}),e.jsxs("div",{className:"bg-muted rounded-lg p-3 space-y-2 text-xs",children:[e.jsx("p",{children:"â¡ Quick tasks: 2-4 credits (content updates, minor styling)"}),e.jsx("p",{children:"ð¦ Small tasks: 5-12 credits (new sections, forms, basic integrations)"}),e.jsx("p",{children:"ð¯ Medium tasks: 15-30 credits (custom features, API integrations)"}),e.jsx("p",{children:"ð Large tasks: 40-80 credits (major builds, c
51omplex systems)"})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-foreground mb-2",children:"Clarity and Estimate"}),e.jsx("p",{className:"text-sm mb-2",children:"Clarity determines the final estimate for your ticket. The higher the clarity in your ticket, the better guaranteed price we can provide."}),e.jsxs("div",{className:"bg-muted rounded-lg p-3 space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"â High Clarity"}),e.jsx("p",{className:"text-xs",children:"Clear, detailed requirements with minimal ambiguity."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"ð¸ Medium Clarity (+3 credits)"}),e.jsx("p",{className:"text-xs",children:"Some details provided. Example: If the initial baseline is 6 credits, your estimate is 9 credits."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"â ï¸ Low Clarity (+5 credits)"}),e.jsx("p",{className:"text-xs",children:"Limited context. Example: If the initial baseline is 6 credits, your estimate is 11 credits."})]})]})]}),e.jsxs("p",{className:"text-sm",children:["ð¡ ",e.jsx("strong",{className:"text-foreground",children:"Pro Tip:"}),' Use "Add More Context" to provide additional details, screenshots, or requirements. This improves both the accuracy and confidence of the estimate!']})]})}),e.jsx("div",{className:"flex-shrink-0 px-4 sm:px-6 pb-4 sm:pb-6 pt-3 sm:pt-4 border-t border-border flex justify-end bg-card",children:e.jsx("button",{onClick:()=>v(!1),className:"inline-flex items-center justify-center rounded-xl text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none bg-primary text-primary-foreground hover:bg-primary/90 h-10 py-2 px-4 w-full sm:w-auto",children:"Got it"})})]})})]})}const cS=t=>{switch(t){case"Complete":return e.jsx(Ns,{className:"w-5 h-5 text-green-600"});case"In Progress":return e.jsx(ms,{className:"w-5 h-5 text-yellow-600"});case"Blocked":return e.jsx(Mm,{className:"w-5 h-5 text-red-600"});default:return e.jsx(Mm,{className:"w-5 h-5 text-gray-600"})}},dS=t=>{switch(t){case"Complete":return"text-green-600 bg-green-50";case"In Progress":return"text-yellow-600 bg-yellow-50";case"In Review":return"text-purple-600 bg-purple-50";case"Client Approval":return"text-cyan-700 bg-cyan-50";case"Blocked":return"text-red-600 bg-red-50";case"Backlog":return"text-gray-600 bg-gray-50";case"Cancelled":case"Archived":return"text-gray-400 bg-gray-50";default:return"text-gray-600 bg-gray-50"}};function uS({ticketId:t,ticketName:s,ticketStatus:n,ticketDueDate:r,ticketNumber:a,maxCredits:o,rushOrder:i,shopifyStoreUrl:d,shopifyThemeId:m,projectName:p,onBack:c,onLogoClick:u}){const{token:x}=pt(),{content:h,shopifyStoreUrl:b,shopifyThemeId:f,pageUrl:g,loading:y,error:j,jobReportVideoUrl:v,videoReviewUrl:T}=sv(x,t),k=b||d,w=f||m,[I,A]=ee.useState(i||!1),[E,C]=ee.useState(o),[N,S]=ee.useState(!1);ee.useEffect(()=>{i!==void 0&&A(i)},[i]),ee.useEffect(()=>{C(o)},[o]);const O=z=>{if(typeof z!="number"||z<0){console.error("Invalid newMaxCredits value:",z);return}console.log("Estimate complete, updating maxCredits to:",z),C(z)},R=async()=>{if(!k||!w){console.warn("Missing required fields for preview URL");return}const z=`${k}${g||""}?preview_theme_id=${w}`;try{await navigator.clipboard.writeText(z),S(!0),setTimeout(()=>S(!1),2e3)}catch(D){console.error("Failed to copy URL:",D)}};return ee.useEffect(()=>{console.log("TicketDetailScreen - ticketNumber:",a),console.log("TicketDetailScreen - maxCredits:",o),console.log("TicketDetailScreen - content:",h),console.log("TicketDetailScreen - contentLoading:",y),console.log("TicketDetailScreen - Full props:",{ticketId:t,ticketName:s,ticketStatus:n,ticketDueDate:r,ticketNumber:a,maxCredits:o})},[t,s,n,r,a,o,h,y]),e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{onBack:c,onLogoClick:u}),e.jsxs("div",{className:"flex-1 bg-card",children:[e.jsxs("div",{className:"px-4 py-6 border-b border-border",children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mb-4",children:s}),e.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-3",children:[a&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Uo,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm",children:"Ticket Number"})]}),e.jsx("span",{className:"text-sm font-medium text-foreground uppercase",children:a})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[cS(n),e.jsx("span",{className:"text-sm",children:"Status"})]}),e.jsx("span",{className:`inline-flex items-end py-1 rounded-full text-sm font-medium uppercase ${dS(n)}`,children:Wr(n)})]}),r&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ss,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm",children:"Due Date"})]}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:new Date(r).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})})]}),E!=null&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(If,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm",children:"Credits"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground",children:E+(I?2:0)}),I&&e.jsx("span",{className:"text-xs text-orange-600 font-medium",children:"(+2 rush)"})]})]})]})]}),e.jsx("div",{className:"px-4 py-4 border-b border-border",children:e.jsx(lS,{authToken:x,ticketId:t,ticketName:s,currentMaxCredits:E,ticketStatus:n,initialRushOrder:i,isRushOrder:I,setIsRushOrder:A,onEstimateComplete:O})}),yo({jobReportVideoUrl:v,videoReviewUrl:T})&&e.jsxs("div",{className:"px-4 py-4 border-b border-border",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground mb-3 uppercase tracking-wide",children:"Job Report"}),e.jsx(df,{url:yo({jobReportVideoUrl:v,videoReviewUrl:T})})]}),k&&w&&e.jsx("div",{className:"px-4 py-4 border-b border-border",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx("a",{href:`${k}${g||""}?preview_theme_id=${w}`,target:"_blank",rel:"noopener noreferrer",className:"flex-1 flex items-center justify-center gap-2 px-6 py-3 rounded-lg font-medium transition-colors",style:{backgroundColor:"#3b82f6",color:"#ffffff"},onMouseEnter:z=>{z.currentTarget.style.backgroundColor="#2563eb"},onMouseLeave:z=>{z.currentTarget.style.backgroundColor="#3b82f6"},children:"Preview Change"}),e.jsx("button",{onClick:R,className:"flex items-center justify-center px-4 py-3 rounded-lg font-medium transition-colors",style:{backgroundColor:N?"#10b981":"#3b82f6",color:"#ffffff"},onMouseEnter:z=>{N||(z.currentTarget.style.backgroundColor="#2563eb")},onMouseLeave:z=>{N||(z.currentTarget.style.backgroundColor="#3b82f6")},children:N?e.jsx(kt,{className:"w-5 h-5"}):e.jsx(Hr,{className:"w-5 h-5"})})]})}),e.jsxs("div",{className:"px-4 py-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground mb-3 uppercase tracking-wide",children:"Ticket Details"}),e.jsxs("div",{className:"overflow-y-auto overflow-x-hidden max-h-[600px] border border-border rounded-lg p-4 bg-muted/30",children:[y&&e.jsx("div",{className:"flex justify-center items-center py-12",children:e.jsx("div",{className:"animate-spin",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-12 h-12"})})}),j&&!y&&e.jsx("div",{className:"flex flex-col items-center justify-center py-12 px-6",children:e.jsx("p",{className:"text-destructive text-center",children:j})}),!y&&!j&&e.jsx("div",{className:"space-y-3 w-full overflow-hidden",children:typeof h=="string"?h.trim()?e.jsx("div",{className:"text-foreground leading-relaxed break-words w-full",style:{whiteSpace:"pre-wrap"},children:h}):e.jsx(gm,{blocks:[]}):e.jsx(gm,{blocks:Array.isArray(h)?h:[]})})]})]})]})]})}function mS({onBack:t,onPhoneRequest:s,onAIRequest:n,onBookMeeting:r,onLogoClick:a}){return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{showTitle:!1,onBack:t,onLogoClick:a}),e.jsx("div",{className:"flex-1 px-4 pt-8 pb-24",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("h2",{className:"text-foreground",children:"New Project Request"}),e.jsx("p",{className:"text-muted-foreground",children:"Choose how you'd like to submit your request"})]}),e.jsxs("div",{className:"space-y-4 pt-6",children:[e.jsx("button",{onClick:s,className:"w-full bg-card border-2 border-border rounded-lg p-6 text-left active:bg-muted/30 transition-colors",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(En,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("h3",{className:"text-card-foreground",children:"Submit by Phone"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"14px"}
vendor: 4,917 bytes, line 51
51,children:"Schedule a call with our team to discuss your project requirements in detail"})]})]})}),e.jsx("button",{onClick:r,className:"w-full bg-card border-2 border-border rounded-lg p-6 text-left active:bg-muted/30 transition-colors",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 w-12 h-12 rounded-full bg-secondary/20 flex items-center justify-center",children:e.jsx(tu,{className:"w-6 h-6 text-secondary-foreground"})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("h3",{className:"text-card-foreground",children:"Book Virtual Meeting"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"14px"},children:"Schedule a video call to walk through your project requirements face-to-face"})]})]})}),e.jsx("button",{onClick:n,className:"w-full bg-card border-2 border-border rounded-lg p-6 text-left active:bg-muted/30 transition-colors",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(ws,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("h3",{className:"text-card-foreground",children:"Bucky AI Enabled"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"14px"},children:"Use Bucky to capture and refine your requirements through an interactive conversation"})]})]})})]}),e.jsx("div",{className:"pt-4",children:e.jsx("div",{className:"bg-primary/5 border border-primary/20 rounded-lg p-4",children:e.jsxs("p",{className:"text-card-foreground",style:{fontSize:"14px",lineHeight:"1.6"},children:[e.jsx("span",{style:{fontWeight:"var(--font-weight-semibold)"},children:"Need help deciding?"})," Phone calls are best for urgent matters, virtual meetings for collaborative planning sessions, and Bucky is perfect for quick requests you can complete on your own time."]})})})]})})]})}function pS({onBack:t,onLogoClick:s}){return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{showTitle:!1,onBack:t,onLogoClick:s}),e.jsxs("div",{className:"flex-1 flex flex-col px-4 pt-6 pb-4",children:[e.jsxs("div",{className:"space-y-4 mb-4",children:[e.jsx("h2",{className:"text-foreground",children:"Book Virtual Meeting"}),e.jsx("p",{className:"text-muted-foreground",children:"Select a time that works best for you to discuss your project"})]}),e.jsx("div",{className:"flex-1 bg-card rounded-lg border border-border overflow-hidden",children:e.jsx("iframe",{src:"https://www.sunbowlsystems.com/dc",className:"w-full h-full",frameBorder:"0",title:"Book a Meeting",style:{minHeight:"600px"}})})]})]})}function xS(t,s){const n={};return(t[t.length-1]===""?[...t,""]:t).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const hS=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,fS=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,gS={};function tp(t,s){return(gS.jsx?fS:hS).test(t)}const bS=/[ \t\n\f\r]/g;function yS(t){return typeof t=="object"?t.type==="text"?sp(t.value):!1:sp(t)}function sp(t){return t.replace(bS,"")===""}class ri{constructor(s,n,r){this.normal=n,this.property=s,r&&(this.space=r)}}ri.prototype.normal={};ri.prototype.property={};ri.prototype.space=void 0;function Hg(t,s){const n={},r={};for(const a of t)Object.assign(n,a.property),Object.assign(r,a.normal);return new ri(n,r,s)}function Ld(t){return t.toLowerCase()}class Os{constructor(s,n){this.attribute=n,this.property=s}}Os.prototype.attribute="";Os.prototype.booleanish=!1;Os.prototype.boolean=!1;Os.prototype.commaOrSpaceSeparated=!1;Os.prototype.commaSeparated=!1;Os.prototype.defined=!1;Os.prototype.mustUseProperty=!1;Os.prototype.number=!1;Os.prototype.overloadedBoolean=!1;Os.prototype.property="";Os.prototype.spaceSeparated=!1;Os.prototype.space=void 0;let jS=0;const gt=Kr(),ts=Kr(),zd=Kr(),Ee=Kr(),Bt=Kr(),ga=Kr(),Fs=Kr();function Kr(){return 2**++jS}const Od=Object.freeze(Object.defineProperty({__proto__:null,boolean:gt,booleanish:ts,commaOrSpaceSeparated:Fs,commaSeparated:ga,number:Ee,overloadedBoolean:zd,spaceSeparated:Bt},Symbol.toStringTag,{value:"Module"})),Nc=Object.keys(Od);class Lu extends Os{constructor(s,n,r,a){let o=-1;if(super(s,n),np(this,"space",a),typeof r=="number")for(;++o<Nc.length;){const i=Nc[o];np(this,Nc[o],(r&Od[i])===Od[i])}}}Lu.prototype.defined=!0;function np(t,s,n){n&&(t[s]=n)}function Ba(t){const s={},n={};for(const[r,a]of Object.entries(t.properties)){const o=new Lu(r,t.transform(t.attributes||{},r),a,t.space);t.mustUseProperty&&t.mustUseProperty.includes(r)&&(o.mustUseProperty=!0),s[r]=o,n[Ld(r)]=r,n[Ld(o.attribute)]=r}return new ri(s,n,t.space)}const qg=Ba({properties:{ariaActiveDescendant:null,ariaAtomic:ts,ariaAutoComplete:null,ariaBusy:ts,ariaChecked:ts,ariaColCount:Ee,ariaColIndex:Ee,ariaColSpan:Ee,ariaControl
vendor: 5,434 bytes, line 51
51s:Bt,ariaCurrent:null,ariaDescribedBy:Bt,ariaDetails:null,ariaDisabled:ts,ariaDropEffect:Bt,ariaErrorMessage:null,ariaExpanded:ts,ariaFlowTo:Bt,ariaGrabbed:ts,ariaHasPopup:null,ariaHidden:ts,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Bt,ariaLevel:Ee,ariaLive:null,ariaModal:ts,ariaMultiLine:ts,ariaMultiSelectable:ts,ariaOrientation:null,ariaOwns:Bt,ariaPlaceholder:null,ariaPosInSet:Ee,ariaPressed:ts,ariaReadOnly:ts,ariaRelevant:null,ariaRequired:ts,ariaRoleDescription:Bt,ariaRowCount:Ee,ariaRowIndex:Ee,ariaRowSpan:Ee,ariaSelected:ts,ariaSetSize:Ee,ariaSort:null,ariaValueMax:Ee,ariaValueMin:Ee,ariaValueNow:Ee,ariaValueText:null,role:null},transform(t,s){return s==="role"?s:"aria-"+s.slice(4).toLowerCase()}});function Vg(t,s){return s in t?t[s]:s}function Yg(t,s){return Vg(t,s.toLowerCase())}const vS=Ba({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:ga,acceptCharset:Bt,accessKey:Bt,action:null,allow:null,allowFullScreen:gt,allowPaymentRequest:gt,allowUserMedia:gt,alt:null,as:null,async:gt,autoCapitalize:null,autoComplete:Bt,autoFocus:gt,autoPlay:gt,blocking:Bt,capture:null,charSet:null,checked:gt,cite:null,className:Bt,cols:Ee,colSpan:null,content:null,contentEditable:ts,controls:gt,controlsList:Bt,coords:Ee|ga,crossOrigin:null,data:null,dateTime:null,decoding:null,default:gt,defer:gt,dir:null,dirName:null,disabled:gt,download:zd,draggable:ts,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:gt,formTarget:null,headers:Bt,height:Ee,hidden:zd,high:Ee,href:null,hrefLang:null,htmlFor:Bt,httpEquiv:Bt,id:null,imageSizes:null,imageSrcSet:null,inert:gt,inputMode:null,integrity:null,is:null,isMap:gt,itemId:null,itemProp:Bt,itemRef:Bt,itemScope:gt,itemType:Bt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:gt,low:Ee,manifest:null,max:null,maxLength:Ee,media:null,method:null,min:null,minLength:Ee,multiple:gt,muted:gt,name:null,nonce:null,noModule:gt,noValidate:gt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:gt,optimum:Ee,pattern:null,ping:Bt,placeholder:null,playsInline:gt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:gt,referrerPolicy:null,rel:Bt,required:gt,reversed:gt,rows:Ee,rowSpan:Ee,sandbox:Bt,scope:null,scoped:gt,seamless:gt,selected:gt,shadowRootClonable:gt,shadowRootDelegatesFocus:gt,shadowRootMode:null,shape:null,size:Ee,sizes:null,slot:null,span:Ee,spellCheck:ts,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Ee,step:null,style:null,tabIndex:Ee,target:null,title:null,translate:null,type:null,typeMustMatch:gt,useMap:null,value:ts,width:Ee,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Bt,axis:null,background:null,bgColor:null,border:Ee,borderColor:null,bottomMargin:Ee,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:gt,declare:gt,event:null,face:null,frame:null,frameBorder:null,hSpace:Ee,leftMargin:Ee,link:null,longDesc:null,lowSrc:null,marginHeight:Ee,marginWidth:Ee,noResize:gt,noHref:gt,noShade:gt,noWrap:gt,object:null,profile:null,prompt:null,rev:null,rightMargin:Ee,rules:null,scheme:null,scrolling:ts,standby:null,summary:null,text:null,topMargin:Ee,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Ee,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:gt,disableRemotePlayback:gt,prefix:null,property:null,results:Ee,security:null,unselectable:null},space:"html",transform:Yg}),wS=Ba({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRen
51dering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Fs,accentHeight:Ee,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Ee,amplitude:Ee,arabicForm:null,ascent:Ee,attributeName:null,attributeType:null,azimuth:Ee,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Ee,by:null,calcMode:null,capHeight:Ee,className:Bt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRen
51dering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Ee,diffuseConstant:Ee,direction:null,display:null,dur:null,divisor:Ee,dominantBaseline:null,download:gt,dx:null,dy:null,edgeMode:null,editable:null,elevation:Ee,enableBackground:null,end:null,event:null,exponent:Ee,externalResourcesRequired:null,fill:null,fillOpacity:Ee,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:ga,g2:ga,glyphName:ga,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Ee,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Ee,horizOriginX:Ee,horizOriginY:Ee,id:null,ideographic:Ee,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Ee,k:Ee,k1:Ee,k2:Ee,k3:Ee,k4:Ee,kernelMatrix:Fs,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Ee,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Ee,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Ee,overlineThickness:Ee,paintOrder:null,panose1:null,path:null,pathLength:Ee,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Bt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Ee,pointsAtY:Ee,pointsAtZ:Ee,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Fs,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Fs,rev:Fs,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Fs,requiredFeatures:Fs,requiredFonts:Fs,requiredFormats:Fs,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Ee,specularExponent:Ee,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Ee,strikethroughThickness:Ee,string:null,stroke:null,strokeDashArray:Fs,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Ee,strokeOpacity:Ee,strokeWidth:null,style:null,surfaceScale:Ee,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Fs,tabIndex:Ee,tableValues:null,target:null,targetX:Ee,targetY:Ee,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Fs,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Ee,underlineThickness:Ee,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Ee,values:null,vAlphabetic:Ee,vMathematical:Ee,vectorEffect:null,vHanging:Ee,vIdeographic:Ee,version:null,vertAdvY:Ee,vertOriginX:Ee,vertOriginY:Ee,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Ee,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Vg}),Gg=Ba({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null}
vendor: 4,749 bytes, lines 51-52
51,space:"xlink",transform(t,s){return"xlink:"+s.slice(5).toLowerCase()}}),Kg=Ba({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Yg}),Qg=Ba({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,s){return"xml:"+s.slice(3).toLowerCase()}}),NS={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},kS=/[A-Z]/g,rp=/-[a-z]/g,SS=/^data[-\w.:]+$/i;function CS(t,s){const n=Ld(s);let r=s,a=Os;if(n in t.normal)return t.property[t.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&SS.test(s)){if(s.charAt(4)==="-"){const o=s.slice(5).replace(rp,AS);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=s.slice(4);if(!rp.test(o)){let i=o.replace(kS,TS);i.charAt(0)!=="-"&&(i="-"+i),s="data"+i}}a=Lu}return new a(r,s)}function TS(t){return"-"+t.toLowerCase()}function AS(t){return t.charAt(1).toUpperCase()}const ES=Hg([qg,vS,Gg,Kg,Qg],"html"),zu=Hg([qg,wS,Gg,Kg,Qg],"svg");function IS(t){return t.join(" ").trim()}var Ou={},ap=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,RS=/\n/g,DS=/^\s*/,MS=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,PS=/^:\s*/,LS=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,zS=/^[;\s]*/,OS=/^\s+|\s+$/g,$S=` 52`,op="/",ip="*",Dr="",BS="comment",FS="declaration";function _S(t,s){if(typeof t!="string")throw new TypeError("First argument must be a string");if(!t)return[];s=s||{};var n=1,r=1;function a(b){var f=b.match(RS);f&&(n+=f.length);var g=b.lastIndexOf($S);r=~g?b.length-g:r+b.length}function o(){var b={line:n,column:r};return function(f){return f.position=new i(b),p(),f}}function i(b){this.start=b,this.end={line:n,column:r},this.source=s.source}i.prototype.content=t;function d(b){var f=new Error(s.source+":"+n+":"+r+": "+b);if(f.reason=b,f.filename=s.source,f.line=n,f.column=r,f.source=t,!s.silent)throw f}function m(b){var f=b.exec(t);if(f){var g=f[0];return a(g),t=t.slice(g.length),f}}function p(){m(DS)}function c(b){var f;for(b=b||[];f=u();)f!==!1&&b.push(f);return b}function u(){var b=o();if(!(op!=t.charAt(0)||ip!=t.charAt(1))){for(var f=2;Dr!=t.charAt(f)&&(ip!=t.charAt(f)||op!=t.charAt(f+1));)++f;if(f+=2,Dr===t.charAt(f-1))return d("End of comment missing");var g=t.slice(2,f-2);return r+=2,a(g),t=t.slice(f),r+=2,b({type:BS,comment:g})}}function x(){var b=o(),f=m(MS);if(f){if(u(),!m(PS))return d("property missing ':'");var g=m(LS),y=b({type:FS,property:lp(f[0].replace(ap,Dr)),value:g?lp(g[0].replace(ap,Dr)):Dr});return m(zS),y}}function h(){var b=[];c(b);for(var f;f=x();)f!==!1&&(b.push(f),c(b));return b}return p(),h()}function lp(t){return t?t.replace(OS,Dr):Dr}var WS=_S,US=il&&il.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ou,"__esModule",{value:!0});Ou.default=qS;const HS=US(WS);function qS(t,s){let n=null;if(!t||typeof t!="string")return n;const r=(0,HS.default)(t),a=typeof s=="function";return r.forEach(o=>{if(o.type!=="declaration")return;const{property:i,value:d}=o;a?s(i,d,o):d&&(n=n||{},n[i]=d)}),n}var Jl={};Object.defineProperty(Jl,"__esModule",{value:!0});Jl.camelCase=void 0;var VS=/^--[a-zA-Z0-9_-]+$/,YS=/-([a-z])/g,GS=/^[^-]+$/,KS=/^-(webkit|moz|ms|o|khtml)-/,QS=/^-(ms)-/,JS=function(t){return!t||GS.test(t)||VS.test(t)},ZS=function(t,s){return s.toUpperCase()},cp=function(t,s){return"".concat(s,"-")},XS=function(t,s){return s===void 0&&(s={}),JS(t)?t:(t=t.toLowerCase(),s.reactCompat?t=t.replace(QS,cp):t=t.replace(KS,cp),t.replace(YS,ZS))};Jl.camelCase=XS;var eC=il&&il.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},tC=eC(Ou),sC=Jl;function $d(t,s){var n={};return!t||typeof t!="string"||(0,tC.default)(t,function(r,a){r&&a&&(n[(0,sC.camelCase)(r,s)]=a)}),n}$d.default=$d;var nC=$d;const rC=af(nC),Jg=Zg("end"),$u=Zg("start");function Zg(t){return s;function s(n){const r=n&&n.position&&n.position[t]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function aC(t){const s=$u(t),n=Jg(t);if(s&&n)return{start:s,end:n}}function vo(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?dp(t.position):"start"in t||"end"in t?dp(t):"line"in t||"column"in t?Bd(t):""}function Bd(t){return up(t&&t.line)+":"+up(t&&t.column)}function dp(t){return Bd(t&&t.start)+"-"+Bd(t&&t.end)}function up(t){return t&&typeof t=="number"?t:1}
vendor: 1,921 bytes, line 52
52class js extends Error{constructor(s,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let a="",o={},i=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof s=="string"?a=s:!o.cause&&s&&(i=!0,a=s.message,o.cause=s),!o.ruleId&&!o.source&&typeof r=="string"){const m=r.indexOf(":");m===-1?o.ruleId=r:(o.source=r.slice(0,m),o.ruleId=r.slice(m+1))}if(!o.place&&o.ancestors&&o.ancestors){const m=o.ancestors[o.ancestors.length-1];m&&(o.place=m.position)}const d=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=d?d.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=d?d.line:void 0,this.name=vo(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=i&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}js.prototype.file="";js.prototype.name="";js.prototype.reason="";js.prototype.message="";js.prototype.stack="";js.prototype.column=void 0;js.prototype.line=void 0;js.prototype.ancestors=void 0;js.prototype.cause=void 0;js.prototype.fatal=void 0;js.prototype.place=void 0;js.prototype.ruleId=void 0;js.prototype.source=void 0;const Bu={}.hasOwnProperty,oC=new Map,iC=/[A-Z]/g,lC=new Set(["table","tbody","thead","tfoot","tr"]),cC=new Set(["td","th"]),Xg="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function dC(t,s){if(!s||s.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=s.filePath||void 0;let r;if(s.development){if(typeof s.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=bC(n,s.jsxDEV)}else{if(typeof s.jsx!="function")throw new TypeError("Expected `jsx` in production options");
vendor: 9,555 bytes, line 52
52if(typeof s.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=gC(n,s.jsx,s.jsxs)}const a={Fragment:s.Fragment,ancestors:[],components:s.components||{},create:r,elementAttributeNameCase:s.elementAttributeNameCase||"react",evaluater:s.createEvaluater?s.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:s.ignoreInvalidStyle||!1,passKeys:s.passKeys!==!1,passNode:s.passNode||!1,schema:s.space==="svg"?zu:ES,stylePropertyNameCase:s.stylePropertyNameCase||"dom",tableCellAlignToStyle:s.tableCellAlignToStyle!==!1},o=eb(a,t,void 0);return o&&typeof o!="string"?o:a.create(t,a.Fragment,{children:o||void 0},void 0)}function eb(t,s,n){if(s.type==="element")return uC(t,s,n);if(s.type==="mdxFlowExpression"||s.type==="mdxTextExpression")return mC(t,s);if(s.type==="mdxJsxFlowElement"||s.type==="mdxJsxTextElement")return xC(t,s,n);if(s.type==="mdxjsEsm")return pC(t,s);if(s.type==="root")return hC(t,s,n);if(s.type==="text")return fC(t,s)}function uC(t,s,n){const r=t.schema;let a=r;s.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=zu,t.schema=a),t.ancestors.push(s);const o=sb(t,s.tagName,!1),i=yC(t,s);let d=_u(t,s);return lC.has(s.tagName)&&(d=d.filter(function(m){return typeof m=="string"?!yS(m):!0})),tb(t,i,o,s),Fu(i,d),t.ancestors.pop(),t.schema=r,t.create(s,o,i,n)}function mC(t,s){if(s.data&&s.data.estree&&t.evaluater){const r=s.data.estree.body[0];return r.type,t.evaluater.evaluateExpression(r.expression)}Ro(t,s.position)}function pC(t,s){if(s.data&&s.data.estree&&t.evaluater)return t.evaluater.evaluateProgram(s.data.estree);Ro(t,s.position)}function xC(t,s,n){const r=t.schema;let a=r;s.name==="svg"&&r.space==="html"&&(a=zu,t.schema=a),t.ancestors.push(s);const o=s.name===null?t.Fragment:sb(t,s.name,!0),i=jC(t,s),d=_u(t,s);return tb(t,i,o,s),Fu(i,d),t.ancestors.pop(),t.schema=r,t.create(s,o,i,n)}function hC(t,s,n){const r={};return Fu(r,_u(t,s)),t.create(s,t.Fragment,r,n)}function fC(t,s){return s.value}function tb(t,s,n,r){typeof n!="string"&&n!==t.Fragment&&t.passNode&&(s.node=r)}function Fu(t,s){if(s.length>0){const n=s.length>1?s:s[0];n&&(t.children=n)}}function gC(t,s,n){return r;function r(a,o,i,d){const p=Array.isArray(i.children)?n:s;return d?p(o,i,d):p(o,i)}}function bC(t,s){return n;function n(r,a,o,i){const d=Array.isArray(o.children),m=$u(r);return s(a,o,i,d,{columnNumber:m?m.column-1:void 0,fileName:t,lineNumber:m?m.line:void 0},void 0)}}function yC(t,s){const n={};let r,a;for(a in s.properties)if(a!=="children"&&Bu.call(s.properties,a)){const o=vC(t,a,s.properties[a]);if(o){const[i,d]=o;t.tableCellAlignToStyle&&i==="align"&&typeof d=="string"&&cC.has(s.tagName)?r=d:n[i]=d}}if(r){const o=n.style||(n.style={});o[t.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function jC(t,s){const n={};for(const r of s.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&t.evaluater){const o=r.data.estree.body[0];o.type;const i=o.expression;i.type;const d=i.properties[0];d.type,Object.assign(n,t.evaluater.evaluateExpression(d.argument))}else Ro(t,s.position);else{const a=r.name;let o;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&t.evaluater){const d=r.value.data.estree.body[0];d.type,o=t.evaluater.evaluateExpression(d.expression)}else Ro(t,s.position);else o=r.value===null?!0:r.value;n[a]=o}return n}function _u(t,s){const n=[];let r=-1;const a=t.passKeys?new Map:oC;for(;++r<s.children.length;){const o=s.children[r];let i;if(t.passKeys){const m=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(m){const p=a.get(m)||0;i=m+"-"+p,a.set(m,p+1)}}const d=eb(t,o,i);d!==void 0&&n.push(d)}return n}function vC(t,s,n){const r=CS(t.schema,s);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?xS(n):IS(n)),r.property==="style"){let a=typeof n=="object"?n:wC(t,String(n));return t.stylePropertyNameCase==="css"&&(a=NC(a)),["style",a]}return[t.elementAttributeNameCase==="react"&&r.space?NS[r.property]||r.property:r.attribute,n]}}function wC(t,s){try{return rC(s,{reactCompat:!0})}catch(n){if(t.ignoreInvalidStyle)return{};const r=n,a=new js("Cannot parse `style` attribute",{ancestors:t.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=t.filePath||void 0,a.url=Xg+"#cannot-parse-style-attribute",a}}function sb(t,s,n){let r;if(!n)r={type:"Literal",value:s};else if(s.includes(".")){const a=s.split(".");let o=-1,i;for(;++o<a.length;){const d=tp(a[o])?{type:"Identifier",name:a[o]}:{type:"Literal",value:a[o]};i=i?{type:"MemberExpression",object:i,property:d,computed:!!(o&&d.type==="Literal"),optional:!1}:d}r=i}else r=tp(s)&&!/^[a-z]/.test(s)?{type:"Identifier",name:s}:{type:"Literal",value:s};if(r.type==="Literal"){const a=r.value;return Bu.call(t.components,a)?t.components[a]:a}if(t.evaluater)return t.evaluater.evaluateExpression(r);Ro(t)}function Ro(t,s){const n=new js("Cannot handle MDX estrees without `createEvaluater`",{ancestors:t.ancestors,place:s,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=t.filePath||void 0,n.url=Xg+"#cannot-handle-mdx-estrees-without-createevaluater",n}function NC(t){const s={};let n;for(n in t)Bu.call(t,n)&&(s[kC(n)]=t[n]);return s}function kC(t){let s=t.replace(iC,SC);return s.slice(0,3)==="ms-"&&(s="-"+s),s}function SC(t){return"-"+t.toLowerCase()}const kc={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},CC={};function TC(t,s){const n=CC,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,a=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return nb(t,r,a)}function nb(t,s,n){if(AC(t)){if("value"in t)return t.type==="html"&&!n?"":t.value;if(s&&"alt"in t&&t.alt)return t.alt;if("children"in t)return mp(t.children,s,n)}return Array.isArray(t)?mp(t,s,n):""}function mp(t,s,n){const r=[];let a=-1;for(;++a<t.length;)r[a]=nb(t[a],s,n);return r.join("")}function AC(t){return!!(t&&typeof t=="object")}const pp=document.createElement("i");function Wu(t){const s="&"+t+";";pp.innerHTML=s;const n=pp.textContent;return n.charCodeAt(n.length-1)===59&&t!=="semi"||n===s?!1:n}function Pn(t,s,n,r){const a=t.length;let o=0,i;if(s<0?s=-s>a?0:a+s:s=s>a?a:s,n=n>0?n:0,r.length<1e4)i=Array.from(r),i.unshift(s,n),t.splice(...i);else for(n&&t.splice(s,n);o<r.length;)i=r.slice(o,o+1e4),i.unshift(s,0),t.splice(...i),o+=1e4,s+=1e4}function en(t,s){return t.length>0?(Pn(t,t.length,0,s),t):s}const xp={}.hasOwnProperty;function EC(t){const s={};let n=-1;for(;++n<t.length;)IC(s,t[n]);return s}function IC(t,s){let n;for(n in s){const a=(xp.call(t,n)?t[n]:void 0)||(t[n]={}),o=s[n];let i;if(o)for(i in o){xp.call(a,i)||(a[i]=[]);const d=o[i];RC(a[i],Array.isArray(d)?d:d?[d]:[])}}}function RC(t,s){let n=-1;const r=[];for(;++n<s.length;)(s[n].add==="after"?t:r).push(s[n]);Pn(t,0,0,r)}function rb(t,s){const n=Number.parseInt(t,s);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function ba(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Sn=Nr(/[A-Za-z]/),Vs=Nr(/[\dA-Za-z]/),DC=Nr(/[#-'*+\--9=?A-Z^-~]/);function Fd(t){return t!==null&&(t<32||t===127)}const _d=Nr(/\d/),MC=Nr(/[\dA-Fa-f]/),PC=Nr(/[!-/:-@[-`{-~]/);function ct(t){return t!==null&&t<-2}function Ms(t){return t!==null&&(t<0||t===32)}function It(t){return t===-2||t===-1||t===32}const LC=Nr(new RegExp("\\p{P}|\\p{S}","u")),zC=Nr(/\s/);function Nr(t){return s;function s(n){return n!==null&&n>-1&&t.test(String.fromCharCode(n))}}function Fa(t){const s=[];let n=-1,r=0,a=0;for(;++n<t.length;){const o=t.charCodeAt(n);let i="";if(o===37&&Vs(t.charCodeAt(n+1))&&Vs(t.charCodeAt(n+2)))a=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(i=String.fromCharCode(o));else if(o>55295&&o<57344){const d=t.charCodeAt(n+1);o<56320&&d>56319&&d<57344?(i=String.fromCharCode(o,d),a=1):i="�"}else i=String.fromCharCode(o);i&&(s.push(t.slice(r,n),encodeURIComponent(i)),r=n+a+1,i=""),a&&(n+=a,a=0)}return s.join("")+t.slice(r)}function Ft(t,s,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let o=0;return i;function i(m){return It(m)?(t.enter(n),d(m)):s(m)}function d(m){return It(m)&&o++<a?(t.consume(m),d):(t.exit(n),s(m))}}const OC={tokenize:$C};function $C(t){const s=t.attempt(this.parser.constructs.contentInitial,r,a);let n;return s;function r(d){if(d===null){t.consume(d);return}return t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),Ft(t,s,"linePrefix")}function a(d){return t.enter("paragraph"),o(d)}function o(d){const m=t.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=m),n=m,i(d)}function i(d){if(d===null){t.exit("chunkText"),t.exit("paragraph"),t.consume(d);return}return ct(d)?(t.consume(d),t.exit("chunkText"),o):(t.consume(d),i)}}const BC={tokenize:FC},hp={tokenize:_C};function FC(t){const s=this,n=[];let r=0,a,o,i;return d;function d(v){if(r<n.length){const T=n[r];return s.containerState=T[1],t.attempt(T[0].continuation,m,p)(v)}return p(v)}function m(v){if(r++,s.containerState._closeFlow){s.containerState._closeFlow=void 0,a&&j();const T=s.events.length;let k=T,w;for(;k--;)if(s.events[k][0]==="exit"&&s.events[k][1].type==="chunkFlow"){w=s.events[k][1].end;break}y(r);let I=T;for(;I<s.events.length;
vendor: 8,745 bytes, line 52
52)s.events[I][1].end={...w},I++;return Pn(s.events,k+1,0,s.events.slice(T)),s.events.length=I,p(v)}return d(v)}function p(v){if(r===n.length){if(!a)return x(v);if(a.currentConstruct&&a.currentConstruct.concrete)return b(v);s.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return s.containerState={},t.check(hp,c,u)(v)}function c(v){return a&&j(),y(r),x(v)}function u(v){return s.parser.lazy[s.now().line]=r!==n.length,i=s.now().offset,b(v)}function x(v){return s.containerState={},t.attempt(hp,h,b)(v)}function h(v){return r++,n.push([s.currentConstruct,s.containerState]),x(v)}function b(v){if(v===null){a&&j(),y(0),t.consume(v);return}return a=a||s.parser.flow(s.now()),t.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:o}),f(v)}function f(v){if(v===null){g(t.exit("chunkFlow"),!0),y(0),t.consume(v);return}return ct(v)?(t.consume(v),g(t.exit("chunkFlow")),r=0,s.interrupt=void 0,d):(t.consume(v),f)}function g(v,T){const k=s.sliceStream(v);if(T&&k.push(null),v.previous=o,o&&(o.next=v),o=v,a.defineSkip(v.start),a.write(k),s.parser.lazy[v.start.line]){let w=a.events.length;for(;w--;)if(a.events[w][1].start.offset<i&&(!a.events[w][1].end||a.events[w][1].end.offset>i))return;const I=s.events.length;let A=I,E,C;for(;A--;)if(s.events[A][0]==="exit"&&s.events[A][1].type==="chunkFlow"){if(E){C=s.events[A][1].end;break}E=!0}for(y(r),w=I;w<s.events.length;)s.events[w][1].end={...C},w++;Pn(s.events,A+1,0,s.events.slice(I)),s.events.length=w}}function y(v){let T=n.length;for(;T-- >v;){const k=n[T];s.containerState=k[1],k[0].exit.call(s,t)}n.length=v}function j(){a.write([null]),o=void 0,a=void 0,s.containerState._closeFlow=void 0}}function _C(t,s,n){return Ft(t,t.attempt(this.parser.constructs.document,s,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function fp(t){if(t===null||Ms(t)||zC(t))return 1;if(LC(t))return 2}function Uu(t,s,n){const r=[];let a=-1;for(;++a<t.length;){const o=t[a].resolveAll;o&&!r.includes(o)&&(s=o(s,n),r.push(o))}return s}const Wd={name:"attention",resolveAll:WC,tokenize:UC};function WC(t,s){let n=-1,r,a,o,i,d,m,p,c;for(;++n<t.length;)if(t[n][0]==="enter"&&t[n][1].type==="attentionSequence"&&t[n][1]._close){for(r=n;r--;)if(t[r][0]==="exit"&&t[r][1].type==="attentionSequence"&&t[r][1]._open&&s.sliceSerialize(t[r][1]).charCodeAt(0)===s.sliceSerialize(t[n][1]).charCodeAt(0)){if((t[r][1]._close||t[n][1]._open)&&(t[n][1].end.offset-t[n][1].start.offset)%3&&!((t[r][1].end.offset-t[r][1].start.offset+t[n][1].end.offset-t[n][1].start.offset)%3))continue;m=t[r][1].end.offset-t[r][1].start.offset>1&&t[n][1].end.offset-t[n][1].start.offset>1?2:1;const u={...t[r][1].end},x={...t[n][1].start};gp(u,-m),gp(x,m),i={type:m>1?"strongSequence":"emphasisSequence",start:u,end:{...t[r][1].end}},d={type:m>1?"strongSequence":"emphasisSequence",start:{...t[n][1].start},end:x},o={type:m>1?"strongText":"emphasisText",start:{...t[r][1].end},end:{...t[n][1].start}},a={type:m>1?"strong":"emphasis",start:{...i.start},end:{...d.end}},t[r][1].end={...i.start},t[n][1].start={...d.end},p=[],t[r][1].end.offset-t[r][1].start.offset&&(p=en(p,[["enter",t[r][1],s],["exit",t[r][1],s]])),p=en(p,[["enter",a,s],["enter",i,s],["exit",i,s],["enter",o,s]]),p=en(p,Uu(s.parser.constructs.insideSpan.null,t.slice(r+1,n),s)),p=en(p,[["exit",o,s],["enter",d,s],["exit",d,s],["exit",a,s]]),t[n][1].end.offset-t[n][1].start.offset?(c=2,p=en(p,[["enter",t[n][1],s],["exit",t[n][1],s]])):c=0,Pn(t,r-1,n-r+3,p),n=r+p.length-c-2;break}}for(n=-1;++n<t.length;)t[n][1].type==="attentionSequence"&&(t[n][1].type="data");return t}function UC(t,s){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,a=fp(r);let o;return i;function i(m){return o=m,t.enter("attentionSequence"),d(m)}function d(m){if(m===o)return t.consume(m),d;const p=t.exit("attentionSequence"),c=fp(m),u=!c||c===2&&a||n.includes(m),x=!a||a===2&&c||n.includes(r);return p._open=!!(o===42?u:u&&(a||!x)),p._close=!!(o===42?x:x&&(c||!u)),s(m)}}function gp(t,s){t.column+=s,t.offset+=s,t._bufferIndex+=s}const HC={name:"autolink",tokenize:qC};function qC(t,s,n){let r=0;return a;function a(h){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(h),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),o}function o(h){return Sn(h)?(t.consume(h),i):h===64?n(h):p(h)}function i(h){return h===43||h===45||h===46||Vs(h)?(r=1,d(h)):p(h)}function d(h){return h===58?(t.consume(h),r=0,m):(h===43||h===45||h===46||Vs(h))&&r++<32?(t.consume(h),d):(r=0,p(h))}function m(h){return h===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(h),t.exit("autolinkMarker"),t.exit("autolink"),s):h===null||h===32||h===60||Fd(h)?n(h):(t.consume(h),m)}function p(h){return h===64?(t.consume(h),c):DC(h)?(t.consume(h),p):n(h)}function c(h){return Vs(h)?u(h):n(h)}function u(h){return h===46?(t.consume(h),r=0,c):h===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(h),t.exit("autolinkMarker"),t.exit("autolink"),s):x(h)}function x(h){if((h===45||Vs(h))&&r++<63){const b=h===45?x:u;return t.consume(h),b}return n(h)}}const Zl={partial:!0,tokenize:VC};function VC(t,s,n){return r;function r(o){return It(o)?Ft(t,a,"linePrefix")(o):a(o)}function a(o){return o===null||ct(o)?s(o):n(o)}}const ab={continuation:{tokenize:GC},exit:KC,name:"blockQuote",tokenize:YC};function YC(t,s,n){const r=this;return a;function a(i){if(i===62){const d=r.containerState;return d.open||(t.enter("blockQuote",{_container:!0}),d.open=!0),t.enter("blockQuotePrefix"),t.enter("blockQuoteMarker"),t.consume(i),t.exit("blockQuoteMarker"),o}return n(i)}function o(i){return It(i)?(t.enter("blockQuotePrefixWhitespace"),t.consume(i),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),s):(t.exit("blockQuotePrefix"),s(i))}}function GC(t,s,n){const r=this;return a;function a(i){return It(i)?Ft(t,o,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(i):o(i)}function o(i){return t.attempt(ab,s,n)(i)}}function KC(t){t.exit("blockQuote")}const ob={name:"characterEscape",tokenize:QC};function QC(t,s,n){return r;function r(o){return t.enter("characterEscape"),t.enter("escapeMarker"),t.consume(o),t.exit("escapeMarker"),a}function a(o){return PC(o)?(t.enter("characterEscapeValue"),t.consume(o),t.exit("characterEscapeValue"),t.exit("characterEscape"),s):n(o)}}const ib={name:"characterReference",tokenize:JC};function JC(t,s,n){const r=this;let a=0,o,i;return d;function d(u){return t.enter("characterReference"),t.enter("characterReferenceMarker"),t.consume(u),t.exit("characterReferenceMarker"),m}function m(u){return u===35?(t.enter("characterReferenceMarkerNumeric"),t.consume(u),t.exit("characterReferenceMarkerNumeric"),p):(t.enter("characterReferenceValue"),o=31,i=Vs,c(u))}function p(u){return u===88||u===120?(t.enter("characterReferenceMarkerHexadecimal"),t.consume(u),t.exit("characterReferenceMarkerHexadecimal"),t.enter("characterReferenceValue"),o=6,i=MC,c):(t.enter("characterReferenceValue"),o=7,i=_d,c(u))}function c(u){if(u===59&&a){const x=t.exit("characterReferenceValue");return i===Vs&&!Wu(r.sliceSerialize(x))?n(u):(t.enter("characterReferenceMarker"),t.consume(u),t.exit("characterReferenceMarker"),t.exit("characterReference"),s)}return i(u)&&a++<o?(t.consume(u),c):n(u)}}const bp={partial:!0,tokenize:XC},yp={concrete:!0,name:"codeFenced",tokenize:ZC};function ZC(t,s,n){const r=this,a={partial:!0,tokenize:k};let o=0,i=0,d;return m;function m(w){return p(w)}function p(w){const I=r.events[r.events.length-1];return o=I&&I[1].type==="linePrefix"?I[2].sliceSerialize(I[1],!0).length:0,d=w,t.enter("codeFenced"),t.enter("codeFencedFence"),t.enter("codeFencedFenceSequence"),c(w)}function c(w){return w===d?(i++,t.consume(w),c):i<3?n(w):(t.exit("codeFencedFenceSequence"),It(w)?Ft(t,u,"whitespace")(w):u(w))}function u(w){return w===null||ct(w)?(t.exit("codeFencedFence"),r.interrupt?s(w):t.check(bp,f,T)(w)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),x(w))}function x(w){return w===null||ct(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),u(w)):It(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),Ft(t,h,"whitespace")(w)):w===96&&w===d?n(w):(t.consume(w),x)}function h(w){return w===null||ct(w)?u(w):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),b(w))}function b(w){return w===null||ct(w)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),u(w)):w===96&&w===d?n(w):(t.consume(w),b)}function f(w){return t.attempt(a,T,g)(w)}function g(w){return t.enter("lineEnding"),t.consume(w),t.exit("lineEnding"),y}function y(w){return o>0&&It(w)?Ft(t,j,"linePrefix",o+1)(w):j(w)}function j(w){return w===null||ct(w)?t.check(bp,f,T)(w):(t.enter("co
52deFlowValue"),v(w))}function v(w){return w===null||ct(w)?(t.exit("codeFlowValue"),j(w)):(t.consume(w),v)}function T(w){return t.exit("codeFenced"),s(w)}function k(w,I,A){let E=0;return C;function C(z){return w.enter("lineEnding"),w.consume(z),w.exit("lineEnding"),N}function N(z){return w.enter("codeFencedFence"),It(z)?Ft(w,S,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(z):S(z)}function S(z){return z===d?(w.enter("codeFencedFenceSequence"),O(z)):A(z)}function O(z){return z===d?(E++,w.consume(z),O):E>=i?(w.exit("codeFencedFenceSequence"),It(z)?Ft(w,R,"whitespace")(z):R(z)):A(z)}function R(z){return z===null||ct(z)?(w.exit("codeFencedFence"),I(z)):A(z)}}}function XC(t,s,n){const r=this;return a;function a(i){return i===null?n(i):(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),o)}function o(i){return r.parser.lazy[r.now().line]?n(i):s(i)}}const Sc={name:"codeIndented",tokenize:t4},e4={partial:!0,tokenize:s4};function t4(t,s,n){const r=this;return a;function a(p){return t.enter("codeIndented"),Ft(t,o,"linePrefix",5)(p)}function o(p){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?i(p):n(p)}function i(p){return p===null?m(p):ct(p)?t.attempt(e4,i,m)(p):(t.enter("codeFlowValue"),d(p))}function d(p){return p===null||ct(p)?(t.exit("codeFlowValue"),i(p)):(t.consume(p),d)}function m(p){return t.exit("codeIndented"),s(p)}}function s4(t,s,n){const r=this;return a;function a(i){return r.parser.lazy[r.now().line]?n(i):ct(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),a):Ft(t,o,"linePrefix",5)(i)}function o(i){const d=r.events[r.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?s(i):ct(i)?a(i):n(i)}}const n4={name:"codeText",previous:a4,resolve:r4,tokenize:o4};function r4(t){let s=t.length-4,n=3,r,a;if((t[n][1].type==="lineEnding"||t[n][1].type==="space")&&(t[s][1].type==="lineEnding"||t[s][1].type==="space")){for(r=n;++r<s;)if(t[r][1].type==="codeTextData"){t[n][1].type="codeTextPadding",t[s][1].type="codeTextPadding",n+=2,s-=2;break}}for(r=n-1,s++;++r<=s;)a===void 0?r!==s&&t[r][1].type!=="lineEnding"&&(a=r):(r===s||t[r][1].type==="lineEnding")&&(t[a][1].type="codeTextData",r!==a+2&&(t[a][1].end=t[r-1][1].end,t.splice(a+2,r-a-2),s-=r-a-2,r=a+2),a=void 0);return t}function a4(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function o4(t,s,n){let r=0,a,o;return i;function i(u){return t.enter("codeText"),t.enter("codeTextSequence"),d(u)}function d(u){return u===96?(t.consume(u),r++,d):(t.exit("codeTextSequence"),m(u))}function m(u){return u===null?n(u):u===32?(t.enter("space"),t.consume(u),t.exit("space"),m):u===96?(o=t.enter("codeTextSequence"),a=0,c(u)):ct(u)?(t.enter("lineEnding"),t.consume(u),t.exit("lineEnding"),m):(t.enter("codeTextData"),p(u))}function p(u){return u===null||u===32||u===96||ct(u)?(t.exit("codeTextData"),m(u)):(t.consume(u),p)}function c(u){return u===96?(t.consume(u),a++,c):a===r?(t.exit("codeTextSequence"),t.exit("codeText"),s(u)):(o.type="codeTextData",p(u))}}class i4{constructor(s){this.left=s?[...s]:[],this.right=[]}get(s){if(s<0||s>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+s+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return s<this.left.length?this.left[s]:this.right[this.right.length-s+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(s,n){const r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(s,r):s>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-s+this.left.length).reverse():this.left.slice(s).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(s,n,r){const a=n||0;this.setCursor(Math.trunc(s));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return r&&Ya(this.left,r),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(s){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(s)}pushMany(s){this.setCursor(Number.POSITIVE_INFINITY),Ya(this.left,s)}unshift(s){this.setCursor(0),this.right.push(s)}unshiftMany(s){this.setCursor(0),Ya(this.right,s.reverse())}setCursor(s){if(!(s===this.left.length||s>this.left.length&&this.right.length===0||s<0&&this.left.length===0))if(s<this.left.length){const n=this.left.splice(s,Number.POSITIVE_INFINITY);Ya(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-s,Number.POSITIVE_INFINITY);Ya(this.left,n.reverse())}}}function Ya(t,s){let n=0;if(s.length<1e4)t.push(...s);else for(;n<s.length;)t.push(...s.slice(n,n+1e4)),n+=1e4}function lb(t){const s={};let n=-1,r,a,o,i,d,m,p;const c=new i4(t);for(;++n<c.length;){for(;n in s;)n=s[n];if(r=c.get(n),n&&r[1].type==="chunkFlow"&&c.get(n-1)[1].type==="listItemPrefix"&&(m=r[1]._tokenizer.events,o=0,o<m.length&&m[o][1].type==="lineEndingBlank"&&(o+=2),o<m.length&&m[o][1].type==="content"))for(;++o<m.length&&m[o][1].type!=="content";)m[o][1].type==="chunkText"&&(m[o][1]._isInFirstContentOfListItem=!0,o++);if(r[0]==="enter")r[1].contentType&&(Object.assign(s,l4(c,n)),n=s[n],p=!0);else if(r[1]._container){for(o=n,a=void 0;o--;)if(i=c.get(o),i[1].type==="lineEnding"||i[1].type==="lineEndingBlank")i[0]==="enter"&&(a&&(c.get(a)[1].type="lineEndingBlank"),i[1].type="lineEnding",a=o);else if(!(i[1].type==="linePrefix"||i[1].type==="listItemIndent"))break;a&&(r[1].end={...c.get(a)[1].start},d=c.slice(a,n),d.unshift(r),c.splice(a,n-a+1,d))}}return Pn(t,0,Number.POSITIVE_INFINITY,c.slice(0)),!p}function l4(t,s){const n=t.get(s)[1],r=t.get(s)[2];let a=s-1;const o=[];let i=n._tokenizer;i||(i=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(i._contentTypeTextTrailing=!0));const d=i.events,m=[],p={};let c,u,x=-1,h=n,b=0,f=0;const g=[f];for(;h;){for(;t.get(++a)[1]!==h;);o.push(a),h._tokenizer||(c=r.sliceStream(h),h.next||c.push(null),u&&i.defineSki
vendor: 22,718 bytes, line 52
52p(h.start),h._isInFirstContentOfListItem&&(i._gfmTasklistFirstContentOfListItem=!0),i.write(c),h._isInFirstContentOfListItem&&(i._gfmTasklistFirstContentOfListItem=void 0)),u=h,h=h.next}for(h=n;++x<d.length;)d[x][0]==="exit"&&d[x-1][0]==="enter"&&d[x][1].type===d[x-1][1].type&&d[x][1].start.line!==d[x][1].end.line&&(f=x+1,g.push(f),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(i.events=[],h?(h._tokenizer=void 0,h.previous=void 0):g.pop(),x=g.length;x--;){const y=d.slice(g[x],g[x+1]),j=o.pop();m.push([j,j+y.length-1]),t.splice(j,2,y)}for(m.reverse(),x=-1;++x<m.length;)p[b+m[x][0]]=b+m[x][1],b+=m[x][1]-m[x][0]-1;return p}const c4={resolve:u4,tokenize:m4},d4={partial:!0,tokenize:p4};function u4(t){return lb(t),t}function m4(t,s){let n;return r;function r(d){return t.enter("content"),n=t.enter("chunkContent",{contentType:"content"}),a(d)}function a(d){return d===null?o(d):ct(d)?t.check(d4,i,o)(d):(t.consume(d),a)}function o(d){return t.exit("chunkContent"),t.exit("content"),s(d)}function i(d){return t.consume(d),t.exit("chunkContent"),n.next=t.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,a}}function p4(t,s,n){const r=this;return a;function a(i){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),Ft(t,o,"linePrefix")}function o(i){if(i===null||ct(i))return n(i);const d=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?s(i):t.interrupt(r.parser.constructs.flow,n,s)(i)}}function cb(t,s,n,r,a,o,i,d,m){const p=m||Number.POSITIVE_INFINITY;let c=0;return u;function u(y){return y===60?(t.enter(r),t.enter(a),t.enter(o),t.consume(y),t.exit(o),x):y===null||y===32||y===41||Fd(y)?n(y):(t.enter(r),t.enter(i),t.enter(d),t.enter("chunkString",{contentType:"string"}),f(y))}function x(y){return y===62?(t.enter(o),t.consume(y),t.exit(o),t.exit(a),t.exit(r),s):(t.enter(d),t.enter("chunkString",{contentType:"string"}),h(y))}function h(y){return y===62?(t.exit("chunkString"),t.exit(d),x(y)):y===null||y===60||ct(y)?n(y):(t.consume(y),y===92?b:h)}function b(y){return y===60||y===62||y===92?(t.consume(y),h):h(y)}function f(y){return!c&&(y===null||y===41||Ms(y))?(t.exit("chunkString"),t.exit(d),t.exit(i),t.exit(r),s(y)):c<p&&y===40?(t.consume(y),c++,f):y===41?(t.consume(y),c--,f):y===null||y===32||y===40||Fd(y)?n(y):(t.consume(y),y===92?g:f)}function g(y){return y===40||y===41||y===92?(t.consume(y),f):f(y)}}function db(t,s,n,r,a,o){const i=this;let d=0,m;return p;function p(h){return t.enter(r),t.enter(a),t.consume(h),t.exit(a),t.enter(o),c}function c(h){return d>999||h===null||h===91||h===93&&!m||h===94&&!d&&"_hiddenFootnoteSupport"in i.parser.constructs?n(h):h===93?(t.exit(o),t.enter(a),t.consume(h),t.exit(a),t.exit(r),s):ct(h)?(t.enter("lineEnding"),t.consume(h),t.exit("lineEnding"),c):(t.enter("chunkString",{contentType:"string"}),u(h))}function u(h){return h===null||h===91||h===93||ct(h)||d++>999?(t.exit("chunkString"),c(h)):(t.consume(h),m||(m=!It(h)),h===92?x:u)}function x(h){return h===91||h===92||h===93?(t.consume(h),d++,u):u(h)}}function ub(t,s,n,r,a,o){let i;return d;function d(x){return x===34||x===39||x===40?(t.enter(r),t.enter(a),t.consume(x),t.exit(a),i=x===40?41:x,m):n(x)}function m(x){return x===i?(t.enter(a),t.consume(x),t.exit(a),t.exit(r),s):(t.enter(o),p(x))}function p(x){return x===i?(t.exit(o),m(i)):x===null?n(x):ct(x)?(t.enter("lineEnding"),t.consume(x),t.exit("lineEnding"),Ft(t,p,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),c(x))}function c(x){return x===i||x===null||ct(x)?(t.exit("chunkString"),p(x)):(t.consume(x),x===92?u:c)}function u(x){return x===i||x===92?(t.consume(x),c):c(x)}}function wo(t,s){let n;return r;function r(a){return ct(a)?(t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),n=!0,r):It(a)?Ft(t,r,n?"linePrefix":"lineSuffix")(a):s(a)}}const x4={name:"definition",tokenize:f4},h4={partial:!0,tokenize:g4};function f4(t,s,n){const r=this;let a;return o;function o(h){return t.enter("definition"),i(h)}function i(h){return db.call(r,t,d,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function d(h){return a=ba(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),h===58?(t.enter("definitionMarker"),t.consume(h),t.exit("definitionMarker"),m):n(h)}function m(h){return Ms(h)?wo(t,p)(h):p(h)}function p(h){return cb(t,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function c(h){return t.attempt(h4,u,u)(h)}function u(h){return It(h)?Ft(t,x,"whitespace")(h):x(h)}function x(h){return h===null||ct(h)?(t.exit("definition"),r.parser.defined.push(a),s(h)):n(h)}}function g4(t,s,n){return r;function r(d){return Ms(d)?wo(t,a)(d):n(d)}function a(d){return ub(t,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(d)}function o(d){return It(d)?Ft(t,i,"whitespace")(d):i(d)}function i(d){return d===null||ct(d)?s(d):n(d)}}const b4={name:"hardBreakEscape",tokenize:y4};function y4(t,s,n){return r;function r(o){return t.enter("hardBreakEscape"),t.consume(o),a}function a(o){return ct(o)?(t.exit("hardBreakEscape"),s(o)):n(o)}}const j4={name:"headingAtx",resolve:v4,tokenize:w4};function v4(t,s){let n=t.length-2,r=3,a,o;return t[r][1].type==="whitespace"&&(r+=2),n-2>r&&t[n][1].type==="whitespace"&&(n-=2),t[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&t[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(a={type:"atxHeadingText",start:t[r][1].start,end:t[n][1].end},o={type:"chunkText",start:t[r][1].start,end:t[n][1].end,contentType:"text"},Pn(t,r,n-r+1,[["enter",a,s],["enter",o,s],["exit",o,s],["exit",a,s]])),t}function w4(t,s,n){let r=0;return a;function a(c){return t.enter("atxHeading"),o(c)}function o(c){return t.enter("atxHeadingSequence"),i(c)}function i(c){return c===35&&r++<6?(t.consume(c),i):c===null||Ms(c)?(t.exit("atxHeadingSequence"),d(c)):n(c)}function d(c){return c===35?(t.enter("atxHeadingSequence"),m(c)):c===null||ct(c)?(t.exit("atxHeading"),s(c)):It(c)?Ft(t,d,"whitespace")(c):(t.enter("atxHeadingText"),p(c))}function m(c){return c===35?(t.consume(c),m):(t.exit("atxHeadingSequence"),d(c))}function p(c){return c===null||c===35||Ms(c)?(t.exit("atxHeadingText"),d(c)):(t.consume(c),p)}}const N4=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],jp=["pre","script","style","textarea"],k4={concrete:!0,name:"htmlFlow",resolveTo:T4,tokenize:A4},S4={partial:!0,tokenize:I4},C4={partial:!0,tokenize:E4};function T4(t){let s=t.length;for(;s--&&!(t[s][0]==="enter"&&t[s][1].type==="htmlFlow"););return s>1&&t[s-2][1].type==="linePrefix"&&(t[s][1].start=t[s-2][1].start,t[s+1][1].start=t[s-2][1].start,t.splice(s-2,2)),t}function A4(t,s,n){const r=this;let a,o,i,d,m;return p;function p(M){return c(M)}function c(M){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(M),u}function u(M){return M===33?(t.consume(M),x):M===47?(t.consume(M),o=!0,f):M===63?(t.consume(M),a=3,r.interrupt?s:P):Sn(M)?(t.consume(M),i=String.fromCharCode(M),g):n(M)}function x(M){return M===45?(t.consume(M),a=2,h):M===91?(t.consume(M),a=5,d=0,b):Sn(M)?(t.consume(M),a=4,r.interrupt?s:P):n(M)}function h(M){return M===45?(t.consume(M),r.interrupt?s:P):n(M)}function b(M){const F="CDATA[";return M===F.charCodeAt(d++)?(t.consume(M),d===F.length?r.interrupt?s:S:b):n(M)}function f(M){return Sn(M)?(t.consume(M),i=String.fromCharCode(M),g):n(M)}function g(M){if(M===null||M===47||M===62||Ms(M)){const F=M===47,W=i.toLowerCase();return!F&&!o&&jp.includes(W)?(a=1,r.interrupt?s(M):S(M)):N4.includes(i.toLowerCase())?(a=6,F?(t.consume(M),y):r.interrupt?s(M):S(M)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(M):o?j(M):v(M))}return M===45||Vs(M)?(t.consume(M),i+=String.fromCharCode(M),g):n(M)}function y(M){return M===62?(t.consume(M),r.interrupt?s:S):n(M)}function j(M){return It(M)?(t.consume(M),j):C(M)}function v(M){return M===47?(t.consume(M),C):M===58||M===95||Sn(M)?(t.consume(M),T):It(M)?(t.consume(M),v):C(M)}function T(M){return M===45||M===46||M===58||M===95||Vs(M)?(t.consume(M),T):k(M)}function k(M){return M===61?(t.consume(M),w):It(M)?(t.consume(M),k):v(M)}function w(M){return M===null||M===60||M===61||M===62||M===96?n(M):M===34||M===39?(t.consume(M),m=M,I):It(M)?(t.consume(M),w):A(M)}function I(M){return M===m?(t.consume(M),m=null,E):M===null||ct(M)?n(M):(t.consume(M),I)}function A(M){return M===null||M===34||M===39||M===47||M===60||M===61||M===62||M===96||Ms(M)?k(M):(t.consume(M),A)}function E(M){return M===47||M===62||It(M)?v(M):n(M)}function C(M){return M===62?(t.consume(M),N):n(M)}function N(M){return M===null||ct(M)?S(M):It(M)?(t.consume(M),N):n(M)}function S(M){return M===45&&a===2?(t.consume(M),D):M===60&&a===1?(t.consume(M),L):M===62&&a===4?(t.consume(M),U):M===63&&a===3?(t.consume(M),P):M===93&&a===5?(t.consume(M),q):ct(M)&&(a===6||a===7)?(t.exit("htmlFlowData"),t.check(S4,V,O)(M)):M===null||ct(M)?(t.exit("htmlFlowData"),O(M)):(t.consume(M),S)}function O(M){return t.check(C4,R,V)(M)}function R(M){return t.enter("lineEnding"),t.consume(M),t.exit("lineEnding"),z}function z(M){return M===null||ct(M)?O(M):(t.enter("htmlFlowData"),S(M))}function D(M){return M===45?(t.consume(M),P):S(M)}function L(M){return M===47?(t.consume(M),i="",$):S(M)}function $(M){if(M===62){const F=i.toLowerCase();return jp.includes(F)?(t.consume(M),U):S(M)}return Sn(M)&&i.length<8?(t.consume(M),i+=String.fromCharCode(M),$):S(M)}function q(M){return M===93?(t.consume(M),P):S(M)}function P(M){return M===62?(t.consume(M),U):M===45&&a===2?(t.consume(M),P):S(M)}function U(M){return M===null||ct(M)?(t.exit("htmlFlowData"),V(M)):(t.consume(M),U)}function V(M){return t.exit("htmlFlow"),s(M)}}function E4(t,s,n){const r=this;return a;function a(i){return ct(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),o):n(i)}function o(i){return r.parser.lazy[r.now().line]?n(i):s(i)}}function I4(t,s,n){return r;function r(a){return t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),t.attempt(Zl,s,n)}}const R4={name:"htmlText",tokenize:D4};function D4(t,s,n){const r=this;let a,o,i;return d;function d(P){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(P),m}function m(P){return P===33?(t.consume(P),p):P===47?(t.consume(P),k):P===63?(t.consume(P),v):Sn(P)?(t.consume(P),A):n(P)}function p(P){return P===45?(t.consume(P),c):P===91?(t.consume(P),o=0,b):Sn(P)?(t.consume(P),j):n(P)}function c(P){return P===45?(t.consume(P),h):n(P)}function u(P){return P===null?n(P):P===45?(t.consume(P),x):ct(P)?(i=u,L(P)):(t.consume(P),u)}function x(P){return P===45?(t.consume(P),h):u(P)}function h(P){return P===62?D(P):P===45?x(P):u(P)}function b(P){const U="CDATA[";return P===U.charCodeAt(o++)?(t.consume(P),o===U.length?f:b):n(P)}function f(P){return P===null?n(P):P===93?(t.consume(P),g):ct(P)?(i=f,L(P)):(t.consume(P),f)}function g(P){return P===93?(t.consume(P),y):f(P)}function y(P){return P===62?D(P):P===93?(t.consume(P),y):f(P)}function j(P){return P===null||P===62?D(P):ct(P)?(i=j,L(P)):(t.consume(P),j)}function v(P){return P===null?n(P):P===63?(t.consume(P),T):ct(P)?(i=v,L(P)):(t.consume(P),v)}function T(P){return P===62?D(P):v(P)}function k(P){return Sn(P)?(t.consume(P),w):n(P)}function w(P){return P===45||Vs(P)?(t.consume(P),w):I(P)}function I(P){return ct(P)?(i=I,L(P)):It(P)?(t.consume(P),I):D(P)}function A(P){return P===45||Vs(P)?(t.consume(P),A):P===47||P===62||Ms(P)?E(P):n(P)}function E(P){return P===47?(t.consume(P),D):P===58||P===95||Sn(P)?(t.consume(P),C):ct(P)?(i=E,L(P)):It(P)?(t.consume(P),E):D(P)}function C(P){return P===45||P===46||P===58||P===95||Vs(P)?(t.consume(P),C):N(P)}function N(P){return P===61?(t.consume(P),S):ct(P)?(i=N,L(P)):It(P)?(t.consume(P),N):E(P)}function S(P){return P===null||P===60||P===61||P===62||P===96?n(P):P===34||P===39?(t.consume(P),a=P,O):ct(P)?(i=S,L(P)):It(P)?(t.consume(P),S):(t.consume(P),R)}function O(P){return P===a?(t.consume(P),a=void 0,z):P===null?n(P):ct(P)?(i=O,L(P)):(t.consume(P),O)}function R(P){return P===null||P===34||P===39||P===60||P===61||P===96?n(P):P===47||P===62||Ms(P)?E(P):(t.consume(P),R)}function z(P){return P===47||P===62||Ms(P)?E(P):n(P)}function D(P){return P===62?(t.consume(P),t.exit("htmlTextData"),t.exit("htmlText"),s):n(P)}function L(P){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(P),t.exit("lineEnding"),$}function $(P){return It(P)?Ft(t,q,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):q(P)}function q(P){return t.enter("htmlTextData"),i(P)}}const Hu={name:"labelEnd",resolveAll:z4,resolveTo:O4,tokenize:$4},M4={tokenize:B4},P4={tokenize:F4},L4={tokenize:_4};function z4(t){let s=-1;const n=[];for(;++s<t.length;){const r=t[s][1];if(n.push(t[s]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const a=r.type==="labelImage"?4:2;r.type="data",s+=a}}return t.length!==n.length&&Pn(t,0,t.length,n),t}function O4(t,s){let n=t.length,r=0,a,o,i,d;for(;n--;)if(a=t[n][1],o){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;t[n][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(i){if(t[n][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(o=n,a.type!=="labelLink")){r=2;break}}else a.type==="labelEnd"&&(i=n);const m={type:t[o][1].type==="labelLink"?"link":"image",start:{...t[o][1].start},end:{...t[t.length-1][1].end}},p={type:"label",start:{...t[o][1].start},end:{...t[i][1].end}},c={type:"labelText",start:{...t[o+r+2][1].end},end:{...t[i-2][1].start}};return d=[["enter",m,s],["enter",p,s]],d=en(d,t.slice(o+1,o+r+3)),d=en(d,[["enter",c,s]]),d=en(d,Uu(s.parser.constructs.insideSpan.null,t.slice(o+r+4,i-3),s)),d=en(d,[["exit",c,s],t[i-2],t[i-1],["exit",p,s]]),d=en(d,t.slice(i+1)),d=en(d,[["exit",m,s]]),Pn(t,o,t.length,d),t}function $4(t,s,n){const r=this;let a=r.events.length,o,i;for(;a--;)if((r.events[a][1].type==="labelImage"||r.events[a][1].type==="labelLink")&&!r.events[a][1]._balanced){o=r.events[a][1];break}return d;function d(x){return o?o._inactive?u(x):(i=r.parser.defined.includes(ba(r.sliceSerialize({start:o.end,end:r.now()}))),t.enter("labelEnd"),t.enter("labelMarker"),t.consume(x),t.exit("labelMarker"),t.exit("labelEnd"),m):n(x)}function m(x){return x===40?t.attempt(M4,c,i?c:u)(x):x===91?t.attempt(P4,c,i?p:u)(x):i?c(x):u(x)}function p(x){return t.attempt(L4,c,u)(x)}function c(x){return s(x)}function u(x){return o._balanced=!0,n(x)}}function B4(t,s,n){return r;function r(u){return t.enter("resource"),t.enter("resourceMarker"),t.consume(u),t.exit("resourceMarker"),a}function a(u){return Ms(u)?wo(t,o)(u):o(u)}function o(u){return u===41?c(u):cb(t,i,d,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(u)}function i(u){return Ms(u)?wo(t,m)(u):c(u)}function d(u){return n(u)}function m(u){return u===34||u===39||u===40?ub(t,p,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(u):c(u)}function p(u){return Ms(u)?wo(t,c)(u):c(u)}function c(u){return u===41?(t.enter("resourceMarker"),t.consume(u),t.exit("resourceMarker"),t.exit("resource"),s):n(u)}}function F4(t,s,n){const r=this;return a;function a(d){return db.call(r,t,o,i,"reference","referenceMarker","referenceString")(d)}function o(d){return r.parser.defined.includes(ba(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?s(d):n(d)}function i(d){return n(d)}}function _4(t,s,n){return r;function r(o){return t.enter("reference"),t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),a}function a(o){return o===93?(t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),t.exit("reference"),s):n(o)}}const W4={name:"labelStartImage",resolveAll:Hu.resolveAll,tokenize:U4};function U4(t,s,n){const r=this;return a;function a(d){return t.enter("labelImage"),t.enter("labelImageMarker"),t.consume(d),t.exit("labelImageMarker"),o}function o(d){return d===91?(t.enter("labelMarker"),t.consume(d),t.exit("labelMarker"),t.exit("labelImage"),i):n(d)}function i(d){return d===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(d):s(d)}}const H4={name:"labelStartLink",resolveAll:Hu.resolveAll,tokenize:q4};function q4(t,s,n){const r=this;return a;function a(i){return t.enter("labelLink"),t.enter("labelMarker"),t.consume(i),t.exit("labelMarker"),t.exit("labelLink"),o}function o(i){return i===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(i):s(i)}}const Cc={name:"lineEnding",tokenize:V4};function V4(t,s){return n;function n(r){return t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),Ft(t,s,"linePrefix")}}const tl={name:"thematicBreak",tokenize:Y4};function Y4(t,s,n){let r=0,a;return o;function o(p){return t.enter("thematicBreak"),i(p)}function i(p){return a=p,d(p)}function d(p){return p===a?(t.enter("thematicBreakSequence"),m(p)):r>=3&&(p===null||ct(p))?(t.exit("thematicBreak"),s(p)):n(p)}function m(p){return p===a?(t.consume(p),r++,m):(t.exit("thematicBreakSequence"),It(p)?Ft(t,d,"whitespace")(p):d(p))}}const Is={continuation:{tokenize:J4},exit:X4,name:"list",tokenize:Q4},G4={partial:!0,tokenize:e5},K4={partial:!0,tokenize:Z4};function Q4(t,s,n){const r=this,a=r.events[r.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,i=0;return d;function d(h){const b=r.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(b==="listUnordered"?!r.containerState.marker||h===r.containerState.marker:_d(h)){if(r.containerState.type||(r.containerState.type=b,t.enter(b,{_container:!0})),b==="listUnordered")return t.enter("listItemPrefix"),h===42||h===45?t.check(tl,n,p)(h):p(h);if(!r.interrupt||h===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),m(h)}return n(h)}function m(h){return _d(h)&&++i<10?(t.consume(h),m):(!r.interrupt||i<2)&&(r.containerState.marker?h===r.containerState.marker:h===41||h===46)?(t.exit("listItemValue"),p(h)):n(h)}function p(h){return t.enter("listItemMarker"),t.consume(h),t.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||h,t.check(Zl,r.interrupt?n:c,t.attempt(G4,x,u))}function c(h){return r.containerState.initialBlankLine=!0,o++,x(h)}function u(h){return It(h)?(t.enter("listItemPrefixWhitespace"),t.consume(h),t.exit("listItemPrefixWhitespace"),x):n(h)}function x(h){return r.containerState.size=o+r.sliceSerialize(t.exit("listItemPrefix"),!0).length,s(h)}}function J4(t,s,n){const r=this;return r.containerState._closeFlow=void 0,t.check(Zl,a,o);function a(d){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Ft(t,s,"listItemIndent",r.containerState.size+1)(d)}function o(d){return r.containerState.furtherBlankLines||!It(d)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,i(d)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,t.attempt(K4,s,i)(d))}function i(d){return r.containerState._closeFlow=!0,r.interrupt=void 0,Ft(t,t.attempt(Is,s,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(d)}}function Z4(t,s,n){const r=this;return Ft(t,a,"listItemIndent",r.containerState.size+1);function a(o){const i=r.events[r.events.length-1];return i&&i[1].type==="listItemIndent"&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?s(o):n(o)}}function X4(t){t.exit(this.containerState.type)}function e5(t,s,n){const r=this;return Ft(t,a,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(o){const i=r.events[r.events.length-1];return!It(o)&&i&&i[1].type==="listItemPrefixWhitespace"?s(o):n(o)}}const vp={name:"setextUnderline",resolveTo:t5,tokenize:s5};function t5(t,s){let n=t.length,r,a,o;for(;n--;)if(t[n][0]==="enter"){if(t[n][1].type==="content"){r=n;break}t[n][1].type==="paragraph"&&(a=n)}else t[n][1].type==="content"&&t.splice(n,1),!o&&t[n][1].type==="definition"&&(o=n);const i={type:"setextHeading",start:{...t[r][1].start},end:{...t[t.length-1][1].end}};return t[a][1].type="setextHeadingText",o?(t.splice(a,0,["enter",i,s]),t.splice(o+1,0,["exit",t[r][1],s]),t[r][1].end={...t[o][1].end}):t[r][1]=i,t.push(["exit",i,s]),t}function s5(t,s,n){const r=this;let a;return o;function o(p){let c=r.events.length,u;for(;c--;)if(r.events[c][1].type!=="lineEnding"&&r.events[c][1].type!=="linePrefix"&&r.events[c][1].type!=="content"){u=r.events[c][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||u)?(t.enter("setextHeadingLine"),a=p,i(p)):n(p)}function i(p){return t.enter("setextHeadingLineSequence"),d(p)}function d(p){return p===a?(t.consume(p),d):(t.exit("setextHeadingLineSequence"),It(p)?Ft(t,m,"lineSuffix")(p):m(p))}function m(p){return p===null||ct(p)?(t.exit("setextHeadingLine"),s(p)):n(p)}}const n5={tokenize:r5};function r5(t){const s=this,n=t.attempt(Zl,r,t.attempt(this.parser.constructs.flowInitial,a,Ft(t,t.attempt(this.parser.constructs.flow,a,t.attempt(c4,a)),"linePrefix")));return n;function r(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),s.currentConstruct=void 0,n}function a(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),s.currentConstruct=void 0,n}}const a5={resolveAll:pb()},o5=mb("string"),i5=mb("text");function mb(t){return{resolveAll:pb(t==="text"?l5:void 0),tokenize:s};function s(n){const r=this,a=this.parser.constructs[t],o=n.attempt(a,i,d);return i;function i(c){return p(c)?o(c):d(c)}function d(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),m}function m(c){return p(c)?(n.exit("data"),o(c)):(n.consume(c),m)}function p(c){if(c===null)return!0;const u=a[c];let x=-1;if(u)for(;++x<u.length;){const h=u[x];if(!h.previous||h.previous.call(r,r.previous))return!0}return!1}}}function pb(t){return s;function s(n,r){let a=-1,o;for(;++a<=n.length;)o===void 0?n[a]&&n[a][1].type==="data"&&(o=a,a++):(!n[a]||n[a][1].type!=="data")&&(a!==o+2&&(n[o][1].end=n[a-1][1].end,n.splice(o+2,a-o-2),a=o+2),o=void 0);return t?t(n,r):n}}function l5(t,s){let n=0;for(;++n<=t.length;)if((n===t.length||t[n][1].type==="lineEnding")&&t[n-1][1].type==="data"){const r=t[n-1][1],a=s.sliceStream(r);let o=a.length,i=-1,d=0,m;
vendor: 4,597 bytes, lines 52-54
52for(;o--;){const p=a[o];if(typeof p=="string"){for(i=p.length;p.charCodeAt(i-1)===32;)d++,i--;if(i)break;i=-1}else if(p===-2)m=!0,d++;else if(p!==-1){o++;break}}if(s._contentTypeTextTrailing&&n===t.length&&(d=0),d){const p={type:n===t.length||m||d<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?i:r.start._bufferIndex+i,_index:r.start._index+o,line:r.end.line,column:r.end.column-d,offset:r.end.offset-d},end:{...r.end}};r.end={...p.start},r.start.offset===r.end.offset?Object.assign(r,p):(t.splice(n,0,["enter",p,s],["exit",p,s]),n+=2)}n++}return t}const c5={42:Is,43:Is,45:Is,48:Is,49:Is,50:Is,51:Is,52:Is,53:Is,54:Is,55:Is,56:Is,57:Is,62:ab},d5={91:x4},u5={[-2]:Sc,[-1]:Sc,32:Sc},m5={35:j4,42:tl,45:[vp,tl],60:k4,61:vp,95:tl,96:yp,126:yp},p5={38:ib,92:ob},x5={[-5]:Cc,[-4]:Cc,[-3]:Cc,33:W4,38:ib,42:Wd,60:[HC,R4],91:H4,92:[b4,ob],93:Hu,95:Wd,96:n4},h5={null:[Wd,a5]},f5={null:[42,95]},g5={null:[]},b5=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:f5,contentInitial:d5,disable:g5,document:c5,flow:m5,flowInitial:u5,insideSpan:h5,string:p5,text:x5},Symbol.toStringTag,{value:"Module"}));function y5(t,s,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const a={},o=[];let i=[],d=[];const m={attempt:I(k),check:I(w),consume:j,enter:v,exit:T,interrupt:I(w,{interrupt:!0})},p={code:null,containerState:{},defineSkip:f,events:[],now:b,parser:t,previous:null,sliceSerialize:x,sliceStream:h,write:u};let c=s.tokenize.call(p,m);return s.resolveAll&&o.push(s),p;function u(N){return i=en(i,N),g(),i[i.length-1]!==null?[]:(A(s,0),p.events=Uu(o,p.events,p),p.events)}function x(N,S){return v5(h(N),S)}function h(N){return j5(i,N)}function b(){const{_bufferIndex:N,_index:S,line:O,column:R,offset:z}=r;return{_bufferIndex:N,_index:S,line:O,column:R,offset:z}}function f(N){a[N.line]=N.column,C()}function g(){let N;for(;r._index<i.length;){const S=i[r._index];if(typeof S=="string")for(N=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===N&&r._bufferIndex<S.length;)y(S.charCodeAt(r._bufferIndex));else y(S)}}function y(N){c=c(N)}function j(N){ct(N)?(r.line++,r.column=1,r.offset+=N===-3?2:1,C()):N!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===i[r._index].length&&(r._bufferIndex=-1,r._index++)),p.previous=N}function v(N,S){const O=S||{};return O.type=N,O.start=b(),p.events.push(["enter",O,p]),d.push(O),O}function T(N){const S=d.pop();return S.end=b(),p.events.push(["exit",S,p]),S}function k(N,S){A(N,S.from)}function w(N,S){S.restore()}function I(N,S){return O;function O(R,z,D){let L,$,q,P;return Array.isArray(R)?V(R):"tokenize"in R?V([R]):U(R);function U(_){return G;function G(B){const Y=B!==null&&_[B],J=B!==null&&_.null,H=[...Array.isArray(Y)?Y:Y?[Y]:[],...Array.isArray(J)?J:J?[J]:[]];return V(H)(B)}}function V(_){return L=_,$=0,_.length===0?D:M(_[$])}function M(_){return G;function G(B){return P=E(),q=_,_.partial||(p.currentConstruct=_),_.name&&p.parser.constructs.disable.null.includes(_.name)?W():_.tokenize.call(S?Object.assign(Object.create(p),S):p,m,F,W)(B)}}function F(_){return N(q,P),z}function W(_){return P.restore(),++$<L.length?M(L[$]):D}}}function A(N,S){N.resolveAll&&!o.includes(N)&&o.push(N),N.resolve&&Pn(p.events,S,p.events.length-S,N.resolve(p.events.slice(S),p)),N.resolveTo&&(p.events=N.resolveTo(p.events,p))}function E(){const N=b(),S=p.previous,O=p.currentConstruct,R=p.events.length,z=Array.from(d);return{from:R,restore:D};function D(){r=N,p.previous=S,p.currentConstruct=O,p.events.length=R,d=z,C()}}function C(){r.line in a&&r.column<2&&(r.column=a[r.line],r.offset+=a[r.line]-1)}}function j5(t,s){const n=s.start._index,r=s.start._bufferIndex,a=s.end._index,o=s.end._bufferIndex;let i;if(n===a)i=[t[n].slice(r,o)];else{if(i=t.slice(n,a),r>-1){const d=i[0];typeof d=="string"?i[0]=d.slice(r):i.shift()}o>0&&i.push(t[a].slice(0,o))}return i}function v5(t,s){let n=-1;const r=[];let a;for(;++n<t.length;){const o=t[n];let i;if(typeof o=="string")i=o;else switch(o){case-5:{i="\r";break}case-4:{i=` 53`;break}case-3:{i=`\r 54`;break}case-2:{i=s?" ":" ";break}case-1:{if(!s&&a)continue;i=" ";break}default:i=String.fromCharCode(o)}a=o===-2,r.push(i)}return r.join("")}function w5(t){const r={constructs:EC([b5,...(t||{}).extensions||[]]),content:a(OC),defined:[],document:a(BC),flow:a(n5),lazy:{},string:a(o5),text:a(i5)};return r;function a(o){return i;function i(d){return y5(r,o,d)}}}function N5(t){for(;!lb(t););return t}const wp=/[\0\t\n\r]/g;function k5(){let t=1,s="",n=!0,r;return a;function a(o,i,d){const m=[];let p,c,u,x,h;
vendor: 18,748 bytes, lines 54-58
54for(o=s+(typeof o=="string"?o.toString():new TextDecoder(i||void 0).decode(o)),u=0,s="",n&&(o.charCodeAt(0)===65279&&u++,n=void 0);u<o.length;){if(wp.lastIndex=u,p=wp.exec(o),x=p&&p.index!==void 0?p.index:o.length,h=o.charCodeAt(x),!p){s=o.slice(u);break}if(h===10&&u===x&&r)m.push(-3),r=void 0;else switch(r&&(m.push(-5),r=void 0),u<x&&(m.push(o.slice(u,x)),t+=x-u),h){case 0:{m.push(65533),t++;break}case 9:{for(c=Math.ceil(t/4)*4,m.push(-2);t++<c;)m.push(-1);break}case 10:{m.push(-4),t=1;break}default:r=!0,t=1}u=x+1}return d&&(r&&m.push(-5),s&&m.push(s),m.push(null)),m}}const S5=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function C5(t){return t.replace(S5,T5)}function T5(t,s,n){if(s)return s;if(n.charCodeAt(0)===35){const a=n.charCodeAt(1),o=a===120||a===88;return rb(n.slice(o?2:1),o?16:10)}return Wu(n)||t}const xb={}.hasOwnProperty;function A5(t,s,n){return typeof s!="string"&&(n=s,s=void 0),E5(n)(N5(w5(n).document().write(k5()(t,s,!0))))}function E5(t){const s={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Ne),autolinkProtocol:E,autolinkEmail:E,atxHeading:o(X),blockQuote:o(J),characterEscape:E,characterReference:E,codeFenced:o(H),codeFencedFenceInfo:i,codeFencedFenceMeta:i,codeIndented:o(H,i),codeText:o(Z,i),codeTextData:E,data:E,codeFlowValue:E,definition:o(Q),definitionDestinationString:i,definitionLabelString:i,definitionTitleString:i,emphasis:o(K),hardBreakEscape:o(se),hardBreakTrailing:o(se),htmlFlow:o(pe,i),htmlFlowData:E,htmlText:o(pe,i),htmlTextData:E,image:o(me),label:i,link:o(Ne),listItem:o(ae),listItemValue:x,listOrdered:o(at,u),listUnordered:o(at),paragraph:o(xe),reference:M,referenceString:i,resourceDestinationString:i,resourceTitleString:i,setextHeading:o(X),strong:o(ze),thematicBreak:o(ht)},exit:{atxHeading:m(),atxHeadingSequence:k,autolink:m(),autolinkEmail:Y,autolinkProtocol:B,blockQuote:m(),characterEscapeValue:C,characterReferenceMarkerHexadecimal:W,characterReferenceMarkerNumeric:W,characterReferenceValue:_,characterReference:G,codeFenced:m(g),codeFencedFence:f,codeFencedFenceInfo:h,codeFencedFenceMeta:b,codeFlowValue:C,codeIndented:m(y),codeText:m(z),codeTextData:C,data:C,definition:m(),definitionDestinationString:T,definitionLabelString:j,definitionTitleString:v,emphasis:m(),hardBreakEscape:m(S),hardBreakTrailing:m(S),htmlFlow:m(O),htmlFlowData:C,htmlText:m(R),htmlTextData:C,image:m(L),label:q,labelText:$,lineEnding:N,link:m(D),listItem:m(),listOrdered:m(),listUnordered:m(),paragraph:m(),referenceString:F,resourceDestinationString:P,resourceTitleString:U,resource:V,setextHeading:m(A),setextHeadingLineSequence:I,setextHeadingText:w,strong:m(),thematicBreak:m()}};hb(s,(t||{}).mdastExtensions||[]);const n={};return r;function r(ue){let we={type:"root",children:[]};const Be={stack:[we],tokenStack:[],config:s,enter:d,exit:p,buffer:i,resume:c,data:n},Ye=[];let rt=-1;for(;++rt<ue.length;)if(ue[rt][1].type==="listOrdered"||ue[rt][1].type==="listUnordered")if(ue[rt][0]==="enter")Ye.push(rt);else{const te=Ye.pop();rt=a(ue,te,rt)}for(rt=-1;++rt<ue.length;){const te=s[ue[rt][0]];xb.call(te,ue[rt][1].type)&&te[ue[rt][1].type].call(Object.assign({sliceSerialize:ue[rt][2].sliceSerialize},Be),ue[rt][1])}if(Be.tokenStack.length>0){const te=Be.tokenStack[Be.tokenStack.length-1];(te[1]||Np).call(Be,void 0,te[0])}for(we.position={start:ir(ue.length>0?ue[0][1].start:{line:1,column:1,offset:0}),end:ir(ue.length>0?ue[ue.length-2][1].end:{line:1,column:1,offset:0})},rt=-1;++rt<s.transforms.length;)we=s.transforms[rt](we)||we;return we}function a(ue,we,Be){let Ye=we-1,rt=-1,te=!1,ve,Ae,We,ie;for(;++Ye<=Be;){const Ue=ue[Ye];switch(Ue[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ue[0]==="enter"?rt++:rt--,ie=void 0;break}case"lineEndingBlank":{Ue[0]==="enter"&&(ve&&!ie&&!rt&&!We&&(We=Ye),ie=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ie=void 0}if(!rt&&Ue[0]==="enter"&&Ue[1].type==="listItemPrefix"||rt===-1&&Ue[0]==="exit"&&(Ue[1].type==="listUnordered"||Ue[1].type==="listOrdered")){if(ve){let Te=Ye;for(Ae=void 0;Te--;){const He=ue[Te];if(He[1].type==="lineEnding"||He[1].type==="lineEndingBlank"){if(He[0]==="exit")continue;Ae&&(ue[Ae][1].type="lineEndingBlank",te=!0),He[1].type="lineEnding",Ae=Te}else if(!(He[1].type==="linePrefix"||He[1].type==="blockQuotePrefix"||He[1].type==="blockQuotePrefixWhitespace"||He[1].type==="blockQuoteMarker"||He[1].type==="listItemIndent"))break}We&&(!Ae||We<Ae)&&(ve._spread=!0),ve.end=Object.assign({},Ae?ue[Ae][1].start:Ue[1].end),ue.splice(Ae||Ye,0,["exit",ve,Ue[2]]),Ye++,Be++}if(Ue[1].type==="listItemPrefix"){const Te={type:"listItem",_spread:!1,start:Object.assign({},Ue[1].start),end:void 0};ve=Te,ue.splice(Ye,0,["enter",Te,Ue[2]]),Ye++,Be++,We=void 0,ie=!0}}}return ue[we][1]._spread=te,Be}function o(ue,we){return Be;function Be(Ye){d.call(this,ue(Ye),Ye),we&&we.call(this,Ye)}}function i(){this.stack.push({type:"fragment",children:[]})}function d(ue,we,Be){this.stack[this.stack.length-1].children.push(ue),this.stack.push(ue),this.tokenStack.push([we,Be||void 0]),ue.position={start:ir(we.start),end:void 0}}function m(ue){return we;function we(Be){ue&&ue.call(this,Be),p.call(this,Be)}}function p(ue,we){const Be=this.stack.pop(),Ye=this.tokenStack.pop();if(Ye)Ye[0].type!==ue.type&&(we?we.call(this,ue,Ye[0]):(Ye[1]||Np).call(this,ue,Ye[0]));else throw new Error("Cannot close `"+ue.type+"` ("+vo({start:ue.start,end:ue.end})+"): itâs not open");Be.position.end=ir(ue.end)}function c(){return TC(this.stack.pop())}function u(){this.data.expectingFirstListItemValue=!0}function x(ue){if(this.data.expectingFirstListItemValue){const we=this.stack[this.stack.length-2];we.start=Number.parseInt(this.sliceSerialize(ue),10),this.data.expectingFirstListItemValue=void 0}}function h(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.lang=ue}function b(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.meta=ue}function f(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function g(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.value=ue.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function y(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.value=ue.replace(/(\r?\n|\r)$/g,"")}function j(ue){const we=this.resume(),Be=this.stack[this.stack.length-1];Be.label=we,Be.identifier=ba(this.sliceSerialize(ue)).toLowerCase()}function v(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.title=ue}function T(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.url=ue}function k(ue){const we=this.stack[this.stack.length-1];if(!we.depth){const Be=this.sliceSerialize(ue).length;we.depth=Be}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function I(ue){const we=this.stack[this.stack.length-1];we.depth=this.sliceSerialize(ue).codePointAt(0)===61?1:2}function A(){this.data.setextHeadingSlurpLineEnding=void 0}function E(ue){const Be=this.stack[this.stack.length-1].children;let Ye=Be[Be.length-1];(!Ye||Ye.type!=="text")&&(Ye=Le(),Ye.position={start:ir(ue.start),end:void 0},Be.push(Ye)),this.stack.push(Ye)}function C(ue){const we=this.stack.pop();we.value+=this.sliceSerialize(ue),we.position.end=ir(ue.end)}function N(ue){const we=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Be=we.children[we.children.length-1];Be.position.end=ir(ue.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&s.canContainEols.includes(we.type)&&(E.call(this,ue),C.call(this,ue))}function S(){this.data.atHardBreak=!0}function O(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.value=ue}function R(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.value=ue}function z(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.value=ue}function D(){const ue=this.stack[this.stack.length-1];if(this.data.inReference){const we=this.data.referenceType||"shortcut";ue.type+="Reference",ue.referenceType=we,delete ue.url,delete ue.title}else delete ue.identifier,delete ue.label;this.data.referenceType=void 0}function L(){const ue=this.stack[this.stack.length-1];if(this.data.inReference){const we=this.data.referenceType||"shortcut";ue.type+="Reference",ue.referenceType=we,delete ue.url,delete ue.title}else delete ue.identifier,delete ue.label;this.data.referenceType=void 0}function $(ue){const we=this.sliceSerialize(ue),Be=this.stack[this.stack.length-2];Be.label=C5(we),Be.identifier=ba(we).toLowerCase()}function q(){const ue=this.stack[this.stack.length-1],we=this.resume(),Be=this.stack[this.stack.length-1];if(this.data.inReference=!0,Be.type==="link"){const Ye=ue.children;Be.children=Ye}else Be.alt=we}function P(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.url=ue}function U(){const ue=this.resume(),we=this.stack[this.stack.length-1];we.title=ue}function V(){this.data.inReference=void 0}function M(){this.data.referenceType="collapsed"}function F(ue){const we=this.resume(),Be=this.stack[this.stack.length-1];Be.label=we,Be.identifier=ba(this.sliceSerialize(ue)).toLowerCase(),this.data.referenceType="full"}function W(ue){this.data.characterReferenceType=ue.type}function _(ue){const we=this.sliceSerialize(ue),Be=this.data.characterReferenceType;let Ye;Be?(Ye=rb(we,Be==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ye=Wu(we);const rt=this.stack[this.stack.length-1];rt.value+=Ye}function G(ue){const we=this.stack.pop();we.position.end=ir(ue.end)}function B(ue){C.call(this,ue);const we=this.stack[this.stack.length-1];we.url=this.sliceSerialize(ue)}function Y(ue){C.call(this,ue);const we=this.stack[this.stack.length-1];we.url="mailto:"+this.sliceSerialize(ue)}function J(){return{type:"blockquote",children:[]}}function H(){return{type:"code",lang:null,meta:null,value:""}}function Z(){return{type:"inlineCode",value:""}}function Q(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function K(){return{type:"emphasis",children:[]}}function X(){return{type:"heading",depth:0,children:[]}}function se(){return{type:"break"}}function pe(){return{type:"html",value:""}}function me(){return{type:"image",title:null,url:"",alt:null}}function Ne(){return{type:"link",title:null,url:"",children:[]}}function at(ue){return{type:"list",ordered:ue.type==="listOrdered",start:null,spread:ue._spread,children:[]}}function ae(ue){return{type:"listItem",spread:ue._spread,checked:null,children:[]}}function xe(){return{type:"paragraph",children:[]}}function ze(){return{type:"strong",children:[]}}function Le(){return{type:"text",value:""}}function ht(){return{type:"thematicBreak"}}}function ir(t){return{line:t.line,column:t.column,offset:t.offset}}function hb(t,s){let n=-1;for(;++n<s.length;){const r=s[n];Array.isArray(r)?hb(t,r):I5(t,r)}}function I5(t,s){let n;for(n in s)if(xb.call(s,n))switch(n){case"canContainEols":{const r=s[n];r&&t[n].push(...r);break}case"transforms":{const r=s[n];r&&t[n].push(...r);break}case"enter":case"exit":{const r=s[n];r&&Object.assign(t[n],r);break}}}function Np(t,s){throw t?new Error("Cannot close `"+t.type+"` ("+vo({start:t.start,end:t.end})+"): a different token (`"+s.type+"`, "+vo({start:s.start,end:s.end})+") is open"):new Error("Cannot close document, a token (`"+s.type+"`, "+vo({start:s.start,end:s.end})+") is still open")}function R5(t){const s=this;s.parser=n;function n(r){return A5(r,{...s.data("settings"),...t,extensions:s.data("micromarkExtensions")||[],mdastExtensions:s.data("fromMarkdownExtensions")||[]})}}function D5(t,s){const n={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(s),!0)};return t.patch(s,n),t.applyData(s,n)}function M5(t,s){const n={type:"element",tagName:"br",properties:{},children:[]};return t.patch(s,n),[t.applyData(s,n),{type:"text",value:` 55`}]}function P5(t,s){const n=s.value?s.value+` 56`:"",r={};s.lang&&(r.className=["language-"+s.lang]);let a={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return s.meta&&(a.data={meta:s.meta}),t.patch(s,a),a=t.applyData(s,a),a={type:"element",tagName:"pre",properties:{},children:[a]},t.patch(s,a),a}function L5(t,s){const n={type:"element",tagName:"del",properties:{},children:t.all(s)};return t.patch(s,n),t.applyData(s,n)}function z5(t,s){const n={type:"element",tagName:"em",properties:{},children:t.all(s)};return t.patch(s,n),t.applyData(s,n)}function O5(t,s){const n=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",r=String(s.identifier).toUpperCase(),a=Fa(r.toLowerCase()),o=t.footnoteOrder.indexOf(r);let i,d=t.footnoteCounts.get(r);d===void 0?(d=0,t.footnoteOrder.push(r),i=t.footnoteOrder.length):i=o+1,d+=1,t.footnoteCounts.set(r,d);const m={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+a,id:n+"fnref-"+a+(d>1?"-"+d:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(i)}]};t.patch(s,m);const p={type:"element",tagName:"sup",properties:{},children:[m]};return t.patch(s,p),t.applyData(s,p)}function $5(t,s){const n={type:"element",tagName:"h"+s.depth,properties:{},children:t.all(s)};return t.patch(s,n),t.applyData(s,n)}function B5(t,s){if(t.options.allowDangerousHtml){const n={type:"raw",value:s.value};return t.patch(s,n),t.applyData(s,n)}}function fb(t,s){const n=s.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(s.label||s.identifier)+"]"),s.type==="imageReference")return[{type:"text",value:"!["+s.alt+r}];const a=t.all(s),o=a[0];o&&o.type==="text"?o.value="["+o.value:a.unshift({type:"text",value:"["});const i=a[a.length-1];return i&&i.type==="text"?i.value+=r:a.push({type:"text",value:r}),a}function F5(t,s){const n=String(s.identifier).toUpperCase(),r=t.definitionById.get(n);if(!r)return fb(t,s);const a={src:Fa(r.url||""),alt:s.alt};r.title!==null&&r.title!==void 0&&(a.title=r.title);const o={type:"element",tagName:"img",properties:a,children:[]};return t.patch(s,o),t.applyData(s,o)}function _5(t,s){const n={src:Fa(s.url)};s.alt!==null&&s.alt!==void 0&&(n.alt=s.alt),s.title!==null&&s.title!==void 0&&(n.title=s.title);const r={type:"element",tagName:"img",properties:n,children:[]};return t.patch(s,r),t.applyData(s,r)}function W5(t,s){const n={type:"text",value:s.value.replace(/\r?\n|\r/g," ")};t.patch(s,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return t.patch(s,r),t.applyData(s,r)}function U5(t,s){const n=String(s.identifier).toUpperCase(),r=t.definitionById.get(n);if(!r)return fb(t,s);const a={href:Fa(r.url||"")};r.title!==null&&r.title!==void 0&&(a.title=r.title);const o={type:"element",tagName:"a",properties:a,children:t.all(s)};return t.patch(s,o),t.applyData(s,o)}function H5(t,s){const n={href:Fa(s.url)};s.title!==null&&s.title!==void 0&&(n.title=s.title);const r={type:"element",tagName:"a",properties:n,children:t.all(s)};return t.patch(s,r),t.applyData(s,r)}function q5(t,s,n){const r=t.all(s),a=n?V5(n):gb(s),o={},i=[];if(typeof s.checked=="boolean"){const c=r[0];let u;c&&c.type==="element"&&c.tagName==="p"?u=c:(u={type:"element",tagName:"p",properties:{},children:[]},r.unshift(u)),u.children.length>0&&u.children.unshift({type:"text",value:" "}),u.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:s.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let d=-1;for(;++d<r.length;){const c=r[d];(a||d!==0||c.type!=="element"||c.tagName!=="p")&&i.push({type:"text",value:` 57`}),c.type==="element"&&c.tagName==="p"&&!a?i.push(...c.children):i.push(c)}const m=r[r.length-1];m&&(a||m.type!=="element"||m.tagName!=="p")&&i.push({type:"text",value:` 58`});const p={type:"element",tagName:"li",properties:o,children:i};return t.patch(s,p),t.applyData(s,p)}function V5(t){let s=!1;if(t.type==="list"){s=t.spread||!1;const n=t.children;let r=-1;for(;!s&&++r<n.length;)s=gb(n[r])}return s}function gb(t){const s=t.spread;return s??t.children.length>1}function Y5(t,s){const n={},r=t.all(s);let a=-1;for(typeof s.start=="number"&&s.start!==1&&(n.start=s.start);++a<r.length;){const i=r[a];if(i.type==="element"&&i.tagName==="li"&&i.properties&&Array.isArray(i.properties.className)&&i.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const o={type:"element",tagName:s.ordered?"ol":"ul",properties:n,children:t.wrap(r,!0)};return t.patch(s,o),t.applyData(s,o)}function G5(t,s){const n={type:"element",tagName:"p",properties:{},children:t.all(s)};return t.patch(s,n),t.applyData(s,n)}function K5(t,s){const n={type:"root",children:t.wrap(t.all(s))};return t.patch(s,n),t.applyData(s,n)}function Q5(t,s){const n={type:"element",tagName:"strong",properties:{},children:t.all(s)};return t.patch(s,n),t.applyData(s,n)}function J5(t,s){const n=t.all(s),r=n.shift(),a=[];if(r){const i={type:"element",tagName:"thead",properties:{},children:t.wrap([r],!0)};t.patch(s.children[0],i),a.push(i)}if(n.length>0){const i={type:"element",tagName:"tbody",properties:{},children:t.wrap(n,!0)},d=$u(s.children[1]),m=Jg(s.children[s.children.length-1]);d&&m&&(i.position={start:d,end:m}),a.push(i)}const o={type:"element",tagName:"table",properties:{},children:t.wrap(a,!0)};return t.patch(s,o),t.applyData(s,o)}function Z5(t,s,n){const r=n?n.children:void 0,o=(r?r.indexOf(s):1)===0?"th":"td",i=n&&n.type==="table"?n.align:void 0,d=i?i.length:s.children.length;let m=-1;const p=[];for(;++m<d;){const u=s.children[m],x={},h=i?i[m]:void 0;h&&(x.align=h);let b={type:"element",tagName:o,properties:x,children:[]};u&&(b.children=t.all(u),t.patch(u,b),b=t.applyData(u,b)),p.push(b)}const c={type:"element",tagName:"tr",properties:{},children:t.wrap(p,!0)};return t.patch(s,c),t.applyData(s,c)}function X5(t,s){const n={type:"element",tagName:"td",properties:{},children:t.all(s)};return t.patch(s,n),t.applyData(s,n)}const kp=9,Sp=32;function e3(t){const s=String(t),n=/\r?\n|\r/g;let r=n.exec(s),a=0;const o=[];for(;r;)o.push(Cp(s.slice(a,r.index),a>0,!0),r[0]),a=r.index+r[0].length,r=n.exec(s);return o.push(Cp(s.slice(a),a>0,!1)),o.join("")}function Cp(t,s,n){let r=0,a=t.length;if(s){let o=t.codePointAt(r);for(;o===kp||o===Sp;)r++,o=t.codePointAt(r)}if(n){let o=t.codePointAt(a-1);for(;o===kp||o===Sp;)a--,o=t.codePointAt(a-1)}return a>r?t.slice(r,a):""}function t3(t,s){const n={type:"text",value:e3(String(s.value))};return t.patch(s,n),t.applyData(s,n)}function s3(t,s){const n={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(s,n),t.applyData(s,n)}const n3={blockquote:D5,break:M5,code:P5,delete:L5,emphasis:z5,footnoteReference:O5,heading:$5,html:B5,imageReference:F5,image:_5,inlineCode:W5,linkReference:U
vendor: 4,616 bytes, line 58
585,link:H5,listItem:q5,list:Y5,paragraph:G5,root:K5,strong:Q5,table:J5,tableCell:X5,tableRow:Z5,text:t3,thematicBreak:s3,toml:hi,yaml:hi,definition:hi,footnoteDefinition:hi};function hi(){}const bb=-1,Xl=0,No=1,fl=2,qu=3,Vu=4,Yu=5,Gu=6,yb=7,jb=8,Tp=typeof self=="object"?self:globalThis,r3=(t,s)=>{const n=(a,o)=>(t.set(o,a),a),r=a=>{if(t.has(a))return t.get(a);const[o,i]=s[a];switch(o){case Xl:case bb:return n(i,a);case No:{const d=n([],a);for(const m of i)d.push(r(m));return d}case fl:{const d=n({},a);for(const[m,p]of i)d[r(m)]=r(p);return d}case qu:return n(new Date(i),a);case Vu:{const{source:d,flags:m}=i;return n(new RegExp(d,m),a)}case Yu:{const d=n(new Map,a);for(const[m,p]of i)d.set(r(m),r(p));return d}case Gu:{const d=n(new Set,a);for(const m of i)d.add(r(m));return d}case yb:{const{name:d,message:m}=i;return n(new Tp[d](m),a)}case jb:return n(BigInt(i),a);case"BigInt":return n(Object(BigInt(i)),a);case"ArrayBuffer":return n(new Uint8Array(i).buffer,i);case"DataView":{const{buffer:d}=new Uint8Array(i);return n(new DataView(d),i)}}return n(new Tp[o](i),a)};return r},Ap=t=>r3(new Map,t)(0),Xr="",{toString:a3}={},{keys:o3}=Object,Ga=t=>{const s=typeof t;if(s!=="object"||!t)return[Xl,s];const n=a3.call(t).slice(8,-1);switch(n){case"Array":return[No,Xr];case"Object":return[fl,Xr];case"Date":return[qu,Xr];case"RegExp":return[Vu,Xr];case"Map":return[Yu,Xr];case"Set":return[Gu,Xr];case"DataView":return[No,n]}return n.includes("Array")?[No,n]:n.includes("Error")?[yb,n]:[fl,n]},fi=([t,s])=>t===Xl&&(s==="function"||s==="symbol"),i3=(t,s,n,r)=>{const a=(i,d)=>{const m=r.push(i)-1;return n.set(d,m),m},o=i=>{if(n.has(i))return n.get(i);let[d,m]=Ga(i);switch(d){case Xl:{let c=i;switch(m){case"bigint":d=jb,c=i.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+m);c=null;break;case"undefined":return a([bb],i)}return a([d,c],i)}case No:{if(m){let x=i;return m==="DataView"?x=new Uint8Array(i.buffer):m==="ArrayBuffer"&&(x=new Uint8Array(i)),a([m,[...x]],i)}const c=[],u=a([d,c],i);for(const x of i)c.push(o(x));return u}case fl:{if(m)switch(m){case"BigInt":return a([m,i.toString()],i);case"Boolean":case"Number":case"String":return a([m,i.valueOf()],i)}if(s&&"toJSON"in i)return o(i.toJSON());const c=[],u=a([d,c],i);for(const x of o3(i))(t||!fi(Ga(i[x])))&&c.push([o(x),o(i[x])]);return u}case qu:return a([d,i.toISOString()],i);case Vu:{const{source:c,flags:u}=i;return a([d,{source:c,flags:u}],i)}case Yu:{const c=[],u=a([d,c],i);for(const[x,h]of i)(t||!(fi(Ga(x))||fi(Ga(h))))&&c.push([o(x),o(h)]);return u}case Gu:{const c=[],u=a([d,c],i);for(const x of i)(t||!fi(Ga(x)))&&c.push(o(x));return u}}const{message:p}=i;return a([d,{name:m,message:p}],i)};return o},Ep=(t,{json:s,lossy:n}={})=>{const r=[];return i3(!(s||n),!!s,new Map,r)(t),r},gl=typeof structuredClone=="function"?(t,s)=>s&&("json"in s||"lossy"in s)?Ap(Ep(t,s)):structuredClone(t):(t,s)=>Ap(Ep(t,s));function l3(t,s){const n=[{type:"text",value:"â©"}];return s>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(s)}]}),n}function c3(t,s){return"Back to reference "+(t+1)+(s>1?"-"+s:"")}function d3(t){const s=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",n=t.options.footnoteBackContent||l3,r=t.options.footnoteBackLabel||c3,a=t.options.footnoteLabel||"Footnotes",o=t.options.footnoteLabelTagName||"h2",i=t.options.footnoteLabelProperties||{className:["sr-only"]},d=[];let m=-1;for(;++m<t.footnoteOrder.length;){const p=t.footnoteById.get(t.footnoteOrder[m]);if(!p)continue;const c=t.all(p),u=String(p.identifier).toUpperCase(),x=Fa(u.toLowerCase());let h=0;const b=[],f=t.footnoteCounts.get(u);for(;f!==void 0&&++h<=f;){b.length>0&&b.push({type:"text",value:" "});let j=typeof n=="string"?n:n(m,h);typeof j=="string"&&(j={type:"text",value:j}),b.push({type:"element",tagName:"a",properties:{href:"#"+s+"fnref-"+x+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(m,h),className:["data-footnote-backref"]},children:Array.isArray(j)?j:[j]})}const g=c[c.length-1];if(g&&g.type==="element"&&g.tagName==="p"){const j=g.children[g.children.length-1];j&&j.type==="text"?j.value+=" ":g.children.push({type:"text",value:" "}),g.children.push(...b)}else c.push(...b);const y={type:"element",tagName:"li",properties:{id:s+"fn-"+x},children:t.wrap(c,!0)};t.patch(p,y),d.push(y)}if(d.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...gl(i),id:"footnote-label"},children:[{type:"text",value:a}]}
vendor: 18,218 bytes, lines 58-64
58,{type:"text",value:` 59`},{type:"element",tagName:"ol",properties:{},children:t.wrap(d,!0)},{type:"text",value:` 60`}]}}const vb=function(t){if(t==null)return x3;if(typeof t=="function")return ec(t);if(typeof t=="object")return Array.isArray(t)?u3(t):m3(t);if(typeof t=="string")return p3(t);throw new Error("Expected function, string, or object as test")};function u3(t){const s=[];let n=-1;for(;++n<t.length;)s[n]=vb(t[n]);return ec(r);function r(...a){let o=-1;for(;++o<s.length;)if(s[o].apply(this,a))return!0;return!1}}function m3(t){const s=t;return ec(n);function n(r){const a=r;let o;for(o in t)if(a[o]!==s[o])return!1;return!0}}function p3(t){return ec(s);function s(n){return n&&n.type===t}}function ec(t){return s;function s(n,r,a){return!!(h3(n)&&t.call(this,n,typeof r=="number"?r:void 0,a||void 0))}}function x3(){return!0}function h3(t){return t!==null&&typeof t=="object"&&"type"in t}const wb=[],f3=!0,Ip=!1,g3="skip";function b3(t,s,n,r){let a;typeof s=="function"&&typeof n!="function"?(r=n,n=s):a=s;const o=vb(a),i=r?-1:1;d(t,void 0,[])();function d(m,p,c){const u=m&&typeof m=="object"?m:{};if(typeof u.type=="string"){const h=typeof u.tagName=="string"?u.tagName:typeof u.name=="string"?u.name:void 0;Object.defineProperty(x,"name",{value:"node ("+(m.type+(h?"<"+h+">":""))+")"})}return x;function x(){let h=wb,b,f,g;if((!s||o(m,p,c[c.length-1]||void 0))&&(h=y3(n(m,c)),h[0]===Ip))return h;if("children"in m&&m.children){const y=m;if(y.children&&h[0]!==g3)for(f=(r?y.children.length:-1)+i,g=c.concat(y);f>-1&&f<y.children.length;){const j=y.children[f];if(b=d(j,f,g)(),b[0]===Ip)return b;f=typeof b[1]=="number"?b[1]:f+i}}return h}}}function y3(t){return Array.isArray(t)?t:typeof t=="number"?[f3,t]:t==null?wb:[t]}function Nb(t,s,n,r){let a,o,i;typeof s=="function"&&typeof n!="function"?(o=void 0,i=s,a=n):(o=s,i=n,a=r),b3(t,o,d,a);function d(m,p){const c=p[p.length-1],u=c?c.children.indexOf(m):void 0;return i(m,u,c)}}const Ud={}.hasOwnProperty,j3={};function v3(t,s){const n=s||j3,r=new Map,a=new Map,o=new Map,i={...n3,...n.handlers},d={all:p,applyData:N3,definitionById:r,footnoteById:a,footnoteCounts:o,footnoteOrder:[],handlers:i,one:m,options:n,patch:w3,wrap:S3};return Nb(t,function(c){if(c.type==="definition"||c.type==="footnoteDefinition"){const u=c.type==="definition"?r:a,x=String(c.identifier).toUpperCase();u.has(x)||u.set(x,c)}}),d;function m(c,u){const x=c.type,h=d.handlers[x];if(Ud.call(d.handlers,x)&&h)return h(d,c,u);if(d.options.passThrough&&d.options.passThrough.includes(x)){if("children"in c){const{children:f,...g}=c,y=gl(g);return y.children=d.all(c),y}return gl(c)}return(d.options.unknownHandler||k3)(d,c,u)}function p(c){const u=[];if("children"in c){const x=c.children;let h=-1;for(;++h<x.length;){const b=d.one(x[h],c);if(b){if(h&&x[h-1].type==="break"&&(!Array.isArray(b)&&b.type==="text"&&(b.value=Rp(b.value)),!Array.isArray(b)&&b.type==="element")){const f=b.children[0];f&&f.type==="text"&&(f.value=Rp(f.value))}Array.isArray(b)?u.push(...b):u.push(b)}}}return u}}function w3(t,s){t.position&&(s.position=aC(t))}function N3(t,s){let n=s;if(t&&t.data){const r=t.data.hName,a=t.data.hChildren,o=t.data.hProperties;if(typeof r=="string")if(n.type==="element")n.tagName=r;else{const i="children"in n?n.children:[n];n={type:"element",tagName:r,properties:{},children:i}}n.type==="element"&&o&&Object.assign(n.properties,gl(o)),"children"in n&&n.children&&a!==null&&a!==void 0&&(n.children=a)}return n}function k3(t,s){const n=s.data||{},r="value"in s&&!(Ud.call(n,"hProperties")||Ud.call(n,"hChildren"))?{type:"text",value:s.value}:{type:"element",tagName:"div",properties:{},children:t.all(s)};return t.patch(s,r),t.applyData(s,r)}function S3(t,s){const n=[];let r=-1;for(s&&n.push({type:"text",value:` 61`});++r<t.length;)r&&n.push({type:"text",value:` 62`}),n.push(t[r]);return s&&t.length>0&&n.push({type:"text",value:` 63`}),n}function Rp(t){let s=0,n=t.charCodeAt(s);for(;n===9||n===32;)s++,n=t.charCodeAt(s);return t.slice(s)}function Dp(t,s){const n=v3(t,s),r=n.one(t,void 0),a=d3(n),o=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` 64`},a),o}function C3(t,s){return t&&"run"in t?async function(n,r){const a=Dp(n,{file:r,...s});await t.run(a,r)}:function(n,r){return Dp(n,{file:r,...t||s})}}function Mp(t){if(t)throw t}var sl=Object.prototype.hasOwnProperty,kb=Object.prototype.toString,Pp=Object.defineProperty,Lp=Object.getOwnPropertyDescriptor,zp=function(s){return typeof Array.isArray=="function"?Array.isArray(s):kb.call(s)==="[object Array]"},Op=function(s){if(!s||kb.call(s)!=="[object Object]")return!1;var n=sl.call(s,"constructor"),r=s.constructor&&s.constructor.prototype&&sl.call(s.constructor.prototype,"isPrototypeOf");if(s.constructor&&!n&&!r)return!1;var a;for(a in s);return typeof a>"u"||sl.call(s,a)},$p=function(s,n){Pp&&n.name==="__proto__"?Pp(s,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):s[n.name]=n.newValue},Bp=function(s,n){if(n==="__proto__")if(sl.call(s,n)){if(Lp)return Lp(s,n).value}else return;return s[n]},T3=function t(){var s,n,r,a,o,i,d=arguments[0],m=1,p=arguments.length,c=!1;for(typeof d=="boolean"&&(c=d,d=arguments[1]||{},m=2),(d==null||typeof d!="object"&&typeof d!="function")&&(d={});m<p;++m)if(s=arguments[m],s!=null)for(n in s)r=Bp(d,n),a=Bp(s,n),d!==a&&(c&&a&&(Op(a)||(o=zp(a)))?(o?(o=!1,i=r&&zp(r)?r:[]):i=r&&Op(r)?r:{},$p(d,{name:n,newValue:t(c,i,a)})):typeof a<"u"&&$p(d,{name:n,newValue:a}));return d};const Tc=af(T3);function Hd(t){if(typeof t!="object"||t===null)return!1;const s=Object.getPrototypeOf(t);return(s===null||s===Object.prototype||Object.getPrototypeOf(s)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}function A3(){const t=[],s={run:n,use:r};return s;function n(...a){let o=-1;const i=a.pop();if(typeof i!="function")throw new TypeError("Expected function as last argument, not "+i);d(null,...a);function d(m,...p){const c=t[++o];let u=-1;if(m){i(m);return}for(;++u<a.length;)(p[u]===null||p[u]===void 0)&&(p[u]=a[u]);a=p,c?E3(c,d)(...p):i(null,...p)}}function r(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return t.push(a),s}}function E3(t,s){let n;return r;function r(...i){const d=t.length>i.length;let m;d&&i.push(a);try{m=t.apply(this,i)}catch(p){const c=p;if(d&&n)throw c;return a(c)}d||(m&&m.then&&typeof m.then=="function"?m.then(o,a):m instanceof Error?a(m):o(m))}function a(i,...d){n||(n=!0,s(i,...d))}function o(i){a(null,i)}}const wn={basename:I3,dirname:R3,extname:D3,join:M3,sep:"/"};function I3(t,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');ai(t);let n=0,r=-1,a=t.length,o;if(s===void 0||s.length===0||s.length>t.length){for(;a--;)if(t.codePointAt(a)===47){if(o){n=a+1;break}}else r<0&&(o=!0,r=a+1);return r<0?"":t.slice(n,r)}if(s===t)return"";let i=-1,d=s.length-1;for(;a--;)if(t.codePointAt(a)===47){if(o){n=a+1;break}}else i<0&&(o=!0,i=a+1),d>-1&&(t.codePointAt(a)===s.codePointAt(d--)?d<0&&(r=a):(d=-1,r=i));return n===r?r=i:r<0&&(r=t.length),t.slice(n,r)}function R3(t){if(ai(t),t.length===0)return".";let s=-1,n=t.length,r;for(;--n;)if(t.codePointAt(n)===47){if(r){s=n;break}}else r||(r=!0);return s<0?t.codePointAt(0)===47?"/":".":s===1&&t.codePointAt(0)===47?"//":t.slice(0,s)}function D3(t){ai(t);let s=t.length,n=-1,r=0,a=-1,o=0,i;for(;s--;){const d=t.codePointAt(s);if(d===47){if(i){r=s+1;break}continue}n<0&&(i=!0,n=s+1),d===46?a<0?a=s:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||n<0||o===0||o===1&&a===n-1&&a===r+1?"":t.slice(a,n)}function M3(...t){let s=-1,n;for(;++s<t.length;)ai(t[s]),t[s]&&(n=n===void 0?t[s]:n+"/"+t[s]);return n===void 0?".":P3(n)}function P3(t){ai(t);const s=t.codePointAt(0)===47;let n=L3(t,!s);return n.length===0&&!s&&(n="."),n.length>0&&t.codePointAt(t.length-1)===47&&(n+="/"),s?"/"+n:n}function L3(t,s){let n="",r=0,a=-1,o=0,i=-1,d,m;for(;++i<=t.length;){if(i<t.length)d=t.codePointAt(i);else{if(d===47)break;d=47}if(d===47){if(!(a===i-1||o===1))if(a!==i-1&&o===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(m=n.lastIndexOf("/"),m!==n.length-1){m<0?(n="",r=0):(n=n.slice(0,m),r=n.length-1-n.lastIndexOf("/")),a=i,o=0;continue}}else if(n.length>0){n="",r=0,a=i,o=0;continue}}s&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+t.slice(a+1,i):n=t.slice(a+1,i),r=i-a-1;a=i,o=0}else d===46&&o>-1?o++:o=-1}return n}function ai(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}const z3={cwd:O3};function O3(){return"/"}function qd(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function $3(t){if(typeof t=="string")t=new URL(t);else if(!qd(t)){const s=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw s.code="ERR_INVALID_ARG_TYPE",s}if(t.protocol!=="file:"){const s=new TypeError("The URL must be of scheme file");throw s.code="ERR_INVALID_URL_SCHEME",s}return B3(t)}function B3(t){if(t.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const s=t.pathname;let n=-1;for(;++n<s.length;)if(s.codePointAt(n)===37&&s.codePointAt(n+1)===50){const r=s.codePointAt(n+2);if(r===70||r===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(s)}const Ac=["history","path","basename","stem","extname","dirname"];class Sb{constructor(s){let n;s?qd(s)?n={path:s}:typeof s=="string"||F3(s)?n={value:s}:n=s:n={},this.cwd="cwd"in n?"":z3.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Ac.length;){const o=Ac[r];o in n&&n[o]!==void 0&&n[o]!==null&&(this[o]=o==="history"?[...n[o]]:n[o])}let a;for(a in n)Ac.includes(a)||(this[a]=n[a])}get basename(){return typeof this.path=="string"?wn.basename(this.path):void 0}set basename(s){Ic(s,"basename"),Ec(s,"basename"),this.path=wn.join(this.dirname||"",s)}get dirname(){return typeof this.path=="string"?wn.dirname(this.path):void 0}set dirname(s){Fp(this.basename,"dirname"),this.path=wn.join(s||"",this.basename)}get extname(){return typeof this.path=="string"?wn.extname(this.path):void 0}set extname(s){if(Ec(s,"extname"),Fp(this.dirname,"extname"),s){if(s.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(s.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=wn.join(this.dirname,this.stem+(s||""))}get path(){return this.history[this.history.length-1]}set path(s){qd(s)&&(s=$3(s)),Ic(s,"path"),this.path!==s&&this.history.push(s)}get stem(){return typeof this.path=="string"?wn.basename(this.path,this.extname):void 0}set stem(s){Ic(s,"stem"),Ec(s,"stem"),this.path=wn.join(this.dirname||"",s+(this.extname||""))}fail(s,n,r){const a=this.message(s,n,r);throw a.fatal=!0,a}info(s,n,r){const a=this.message(s,n,r);return a.fatal=void 0,a}message(s,n,r){const a=new js(s,n,r);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(s){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(s||void 0).decode(this.value)}}function Ec(t,s){if(t&&t.includes(wn.sep))throw new Error("`"+s+"` cannot be a path: did not expect `"+wn.sep+"`")}function Ic(t,s){if(!t)throw new Error("`"+s+"` cannot be empty")}function Fp(t,s){if(!t)throw new Error("Setting `"+s+"` requires `path` to be set too")}function F3(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const _3=function(t){const r=this.constructor.prototype,a=r[t],o=function(){return a.apply(o,arguments)};return Object.setPrototypeOf(o,r),o},W3={}.hasOwnProperty;class Ku extends _3{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=A3()}copy(){const s=new Ku;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];s.use(...r)}return s.data(Tc(!0,{},this.namespace)),s}data(s,n){return typeof s=="string"?arguments.length===2?(Mc("data",this.frozen),this.namespace[s]=n,this):W3.call(this.namespace,s)&&this.namespace[s]||void 0:s?(Mc("data",this.frozen),this.namespace=s,this):this.namespace}freeze(){if(this.frozen)return this;const s=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const a=n.call(s,...r);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(s){this.freeze();const n=gi(s),r=this.parser||this.Parser;return Rc("parse",r),r(String(n),n)}process(s,n){const r=this;return this.freeze(),Rc("process",this.parser||this.Parser),Dc("process",this.compiler||this.Compiler),n?a(void 0,n):new Promise(a);function a(o,i){const d=gi(s),m=r.parse(d);r.run(m,d,function(c,u,x){if(c||!u||!x)return p(c);const h=u,b=r.stringify(h,x);q3(b)?x.value=b:x.result=b,p(c,x)});function p(c,u){c||!u?i(c):o?o(u):n(void 0,u)}}}processSync(s){let n=!1,r;return this.freeze(),Rc("processSync",this.parser||this.Parser),Dc("processSync",this.compiler||this.Compiler),this.process(s,a),Wp("processSync","process",n),r;function a(o,i){n=!0,Mp(o),r=i}}run(s,n,r){_p(s),this.freeze();const a=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?o(void 0,r):new Promise(o);function o(i,d){const m=gi(n);a.run(s,m,p);function p(c,u,x){const h=u||s;c?d(c):i?i(h):r(void 0,h,x)}}}runSync(s,n){let r=!1,a;return this.run(s,n,o),Wp("runSync","run",r),a;function o(i,d){Mp(i),a=d,r=!0}}stringify(s,n){this.freeze();const r=gi(n),a=this.compiler||this.Compiler;return Dc("stringify",a),_p(s),a(s,r)}use(s,...n){const r=this.attachers,a=this.namespace;if(Mc("use",this.frozen),s!=null)if(typeof s=="function")m(s,n);else if(typeof s=="object")Array.isArray(s)?d(s):i(s);else throw new TypeError("Expected usable value, not `"+s+"`");return this;function o(p){if(typeof p=="function")m(p,[]);else if(typeof p=="object")if(Array.isArray(p)){const[c,...u]=p;m(c,u)}else i(p);else throw new TypeError("Expected usable value, not `"+p+"`")}function i(p){if(!("plugins"in p)&&!("settings"in p))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");d(p.plugins),p.settings&&(a.settings=Tc(!0,a.settings,p.settings))}function d(p){let c=-1;if(p!=null)if(Array.isArray(p))for(;++c<p.length;){const u=p[c];o(u)}else throw new TypeError("Expected a list of plugins, not `"+p+"`")}function m(p,c){let u=-1,x=-1;for(;++u<r.length;)if(r[u][0]===p){x=u;break}if(x===-1)r.push([p,...c]);else if(c.length>0){let[h,...b]=c;const f=r[x][1];Hd(f)&&Hd(h)&&(h=Tc(!0,f,h)),r[x]=[p,h,...b]}}}}const U3=new Ku().freeze();function Rc(t,s){if(typeof s!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Dc(t,s){if(typeof s!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Mc(t,s){if(s)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function _p(t){if(!Hd(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Wp(t,s,n){if(!n)throw new Error("`"+t+"` finished async. Use `"+s+"` instead")}function gi(t){return H3(t)?t:new Sb(t)}function H3(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function q3(t){return typeof t=="string"||V3(t)}function V3(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const Y3="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Up=[],Hp={allowDangerousHtml:!0},G3=/^(https?|ircs?|mailto|xmpp)$/i,K3=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Ta(t){const s=Q3(t),n=J3(t);return Z3(s.runSync(s.parse(n),n),t)}function Q3(t){const s=t.rehypePlugins||Up,n=t.remarkPlugins||Up,r=t.remarkRehypeOptions?{...t.remarkRehypeOptions,...Hp}:Hp;return U3().use(R5).use(n).use(C3,r).use(s)}function J3(t){const s=t.children||"",n=new Sb;return typeof s=="string"&&(n.value=s),n}function Z3(t,s){const n=s.allowedElements,r=s.allowElement,a=s.components,o=s.disallowedElements,i=s.skipHtml,d=s.unwrapDisallowed,m=s.urlTransform||X3;for(const c of K3)Object.hasOwn(s,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+Y3+c.id,void 0);return Nb(t,p),dC(t,{Fragment:e.Fragment,components:a,ignoreInvalidStyle:!0,jsx:e.jsx,jsxs:e.jsxs,passKeys:!0,passNode:!0});function p(c,u,x){if(c.type==="raw"&&x&&typeof u=="number")return i?x.children.splice(u,1):x.children[u]={type:"text",value:c.value},u;if(c.type==="element"){let h;for(h in kc)if(Object.hasOwn(kc,h)&&Object.hasOwn(c.properties,h)){const b=c.properties[h],f=kc[h];(f===null||f.includes(c.tagName))&&(c.properties[h]=m(String(b||""),h,c))}}
64if(c.type==="element"){let h=n?!n.includes(c.tagName):o?o.includes(c.tagName):!1;if(!h&&r&&typeof u=="number"&&(h=!r(c,u,x)),h&&x&&typeof u=="number")return d&&c.children?x.children.splice(u,1,...c.children):x.children.splice(u,1),u}}}function X3(t){const s=t.indexOf(":"),n=t.indexOf("?"),r=t.indexOf("#"),a=t.indexOf("/");return s===-1||a!==-1&&s>a||n!==-1&&s>n||r!==-1&&s>r||G3.test(t.slice(0,s))?t:""}function eT(){const{token:t}=pt(),[s,n]=l.useState([]),[r,a]=l.useState(!1),[o,i]=l.useState(null),d=l.useRef(`chat-${Date.now()}`),m=l.useCallback(async c=>{if(!c.trim()||r)return;const u={id:`user-${Date.now()}`,text:c.trim(),role:"user",timestamp:new Date,status:"sent"};n(x=>[...x,u]),a(!0),i(null);try{const x=await re("buckyAiChat",{message:c.trim(),conversationId:d.current},t||void 0),h={id:x.messageId||`ai-${Date.now()}`,text:x.answer,role:"assistant",timestamp:new Date,status:"sent"};n(b=>[...b,h])}catch(x){console.error("[useBuckyChat] sendMessage error:",x),i(x instanceof Error?x.message:"Failed to get response"),n(h=>[...h,{id:`error-${Date.now()}`,text:"Sorry, I couldn't process that right now. Please try again.",role:"assistant",timestamp:new Date,status:"error"}])}finally{a(!1)}},[t,r]),p=l.useCallback(()=>{n([]),i(null),d.current=`chat-${Date.now()}`},[]);return{messages:s,isLoading:r,error:o,sendMessage:m,clearChat:p}}function tT({message:t,userQuestion:s,isTicketCreated:n,onCreateTicket:r}){const a=t.role==="user";return e.jsxs("div",{children:[e.jsx("div",{className:`flex ${a?"justify-end":"justify-start"} px-4`,children:e.jsxs("div",{className:`max-w-[85%] flex flex-col ${a?"items-end":"items-start"}`,children:[!a&&e.jsxs("div",{className:"flex items-center gap-2 mb-1 px-1",children:[e.jsx("img",{src:Eo,alt:"Bucky",className:"w-5 h-5 object-contain"}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"Bucky"})]}),e.jsx("div",{className:`rounded-2xl px-4 py-3 ${a?"bg-primary text-primary-foreground rounded-br-md":"bg-muted text-foreground rounded-bl-md"} ${t.status==="error"?"border border-destructive/30":""}`,children:a?e.jsx("p",{className:"leading-relaxed whitespace-pre-wrap",children:t.text}):e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert [&>p]:mb-2 [&>p:last-child]:mb-0 [&>ul]:mb-2 [&>ol]:mb-2 [&>pre]:bg-background/50 [&>pre]:rounded [&>pre]:p-2 [&>pre]:text-xs",children:e.jsx(Ta,{children:t.text})})}),e.jsx("span",{className:"text-muted-foreground text-xs mt-1 px-1",children:t.timestamp.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})})]})}),!a&&t.status!=="error"&&r&&e.jsx("div",{className:"px-5 mt-1 mb-1",children:n?e.jsxs("span",{className:"inline-flex items-center gap-1 text-green-600",style:{fontSize:"12px"},children:[e.jsx(kt,{className:"w-3 h-3"}),"Ticket Created"]}):e.jsxs("button",{onClick:r,className:"inline-flex items-center gap-1 text-primary hover:text-primary/80 transition-colors",style:{fontSize:"12px"},children:[e.jsx(Ut,{className:"w-3 h-3"}),"Create Ticket"]})})]})}function sT(){return e.jsx("div",{className:"flex justify-start px-4",children:e.jsxs("div",{className:"flex flex-col items-start",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 px-1",children:[e.jsx("img",{src:Eo,alt:"Bucky",className:"w-5 h-5 object-contain"}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"Bucky is thinking..."})]}),e.jsx("style",{children:` 65 @keyframes typingDot { 66 0%, 60%, 100% { opacity: 0.3; transform: translateY(0); } 67 30% { opacity: 1; transform: translateY(-4px); } 68 } 69 .typing-dot { animation: typingDot 1.4s infinite ease-in-out; } 70 .typing-dot:nth-child(2) { animation-delay: 0.2s; } 71 .typing-dot:nth-child(3) { animation-delay: 0.4s; } 72 `}),e.jsxs("div",{className:"bg-muted rounded-2xl rounded-bl-md px-5 py-4 flex items-center gap-2",children:[e.jsx("div",{className:"typing-dot w-2.5 h-2.5 bg-muted-foreground rounded-full"}),e.jsx("div",{className:"typing-dot w-2.5 h-2.5 bg-muted-foreground rounded-full"}),e.jsx("div",{className:"typing-dot w-2.5 h-2.5 bg-muted-foreground rounded-full"})]})]})})}function nT({onBack:t,onLogoClick:s}){const{messages:n,isLoading:r,sendMessage:a,clearChat:o}=eT(),{token:i}=pt(),[d,m]=l.useState(""),p=l.useRef(null),c=l.useRef(null),{companies:u}=Pa(i),x=l.useMemo(()=>{const C=[];return u.forEach(N=>
72{N.slackChannels.forEach(S=>{C.includes(S)||C.push(S)})}),C},[u]),[h,b]=l.useState(new Set),[f,g]=l.useState(!1),[y,j]=l.useState(!1),[v,T]=l.useState(null),k=l.useCallback(C=>{var N,S;if(!n)return"";for(let O=C-1;O>=0;O--)if(((N=n[O])==null?void 0:N.role)==="user")return((S=n[O])==null?void 0:S.text)||"";return""},[n]),w=l.useCallback((C,N)=>{const S=N.length>80?N.substring(0,77)+"...":N;T({messageId:C.id,ticketName:S,description:`**Client Question:** 73${N} 74 75**Bucky AI Analysis:** 76${C.text}`}),j(!0)},[]),I=l.useCallback(async(C,N)=>{if(!(!i||!v||!C.trim()||!N.trim())){g(!0);try{const S=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/createNotionTicket",{method:"POST",headers:as(i),body:JSON.stringify({projectId:N,ticketName:C,ticketDescription:v.description})}),O=await S.json();if(!S.ok)throw new Error(O.error||"Failed to create ticket");b(R=>new Set(R).add(v.messageId)),j(!1),T(null)}catch(S){console.error("[AIAssistantScreen] Create ticket error:",S)}finally{g(!1)}}},[i,v]);l.useEffect(()=>{var C;(C=p.current)==null||C.scrollIntoView({behavior:"smooth"})},[n,r]),l.useEffect(()=>{c.current&&(c.current.style.height="auto",c.current.style.height=`${Math.min(c.current.scrollHeight,120)}px`)},[d]);const A=()=>{!d.trim()||r||(a(d),m(""),c.current&&(c.current.style.height="auto"))},E=C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),A())};return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsxs("div",{className:"bg-card border-b border-border",children:[e.jsx(Xe,{showTitle:!1,onBack:t,onLogoClick:s}),e.jsxs("div",{className:"px-4 pb-4 flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full overflow-hidden bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx("img",{src:Eo,alt:"Bucky",className:"w-10 h-10 object-contain"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-card-foreground font-semibold",children:"Bucky"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Your AI project assistant"})]}),n.length>0&&e.jsx(ke,{variant:"ghost",size:"sm",onClick:o,className:"text-muted-foreground hover:text-foreground",title:"New conversation",children:e.jsx(zs,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto py-6 space-y-4",children:[n.length===0&&!r&&e.jsxs("div",{className:"px-4 text-center mt-12 space-y-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mx-auto",children:e.jsx("img",{src:Eo,alt:"Bucky",className:"w-12 h-12 object-contain"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-card-foreground",children:"Hey there!"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1 max-w-xs mx-auto",children:"I'm Bucky, your AI project assistant. Tell me about what you need help with and I'll capture your requirements."})]}),e.jsx("div",{className:"flex flex-wrap justify-center gap-2 mt-4",children:["I need changes to my homepage","Can you help with a new feature?","I have a bug to report"].map(C=>e.jsx("button",{onClick:()=>{var N;m(C),(N=c.current)==null||N.focus()},className:"text-xs bg-muted hover:bg-muted/80 text-foreground rounded-full px-3 py-1.5 transition-colors",children:C},C))})]}),n.map((C,N)=>e.jsx(tT,{message:C,userQuestion:C.role==="assistant"?k(N):void 0,isTicketCreated:h.has(C.id),onCreateTicket:C.role==="assistant"&&C.status!=="error"?()=>w(C,k(N)):void 0},C.id)),r&&e.jsx(sT,{}),e.jsx("div",{ref:p})]}),e.jsx("div",{className:"bg-card border-t border-border px-4 py-4",children:e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsx("div",{className:"flex-1 bg-input-background border border-border rounded-lg overflow-hidden",children:e.jsx("textarea",{ref:c,value:d,onChange:C=>m(C.target.value),onKeyDown:E,placeholder:"Ask Bucky anything...",className:"w-full px-4 py-3 bg-transparent resize-none outline-none text-foreground placeholder:text-muted-foreground",rows:1,style:{maxHeight:"120px",fontFamily:"Montserrat, sans-serif"},disabled:r})}),e.jsx(ke,{onClick:A,disabled:!d.trim()||r,className:"flex-shrink-0 bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",children:r?e.jsx(fe,{className:"w-5 h-5 animate-spin"}):e.jsx(An,{className:"w-5 h-5"})})]})}),e.jsx(zg,{open:y,onOpenChange:j,defaultTicketName:(v==null?void 0:v.ticketName)??"",description:(v==null?void 0:v.description)??"",allowedClients:x.length>0?x:void 0,authToken:i,isCreating:f,onCreateTicket:I})]})}function rT({projectTitle:t,channelId:s,logoUrl:n,completionDate:r,onBack:a,onLogoClick:o,onBookCall:i}){return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{showTitle:!1,onLogoClick:o}),e.jsx("div",{className:"px-4 pt-2 pb-3 bg-background",children:e.jsxs("button",{onClick:a,className:"flex items-center gap-2 text-primary hover:text-primary/80 transition-colors",children:[e.jsx(dt,{className:"w-5 h-5"}),e.jsx("span",{style:{fontSize:"16px",fontWeight:"var(--font-weight-medium)"},children:"Back"})]})}),e.jsx("div",{className:"px-4 pb-4 bg-background",children:e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsx("div",{className:"w-14 h-14 flex-shrink-0",children:e.jsx("div",{className:"w-14 h-14 bg-muted rounded-xl flex items-center justify-center overflow-hidden shadow-sm",children:e.jsx("img",{src:n,alt:`${t} logo`,className:"w-full h-full object-cover"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-foreground mb-1",style:{fontSize:"20px",fontWeight:"var(--font-weight-semibold)"},children:t}),e.jsx("p",{className:"text-primary mb-1",style:{fontSize:"14px"},children:s}),e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",style:{fontSize:"13px"},children:[e.jsx(Ns,{className:"w-4 h-4 text-primary"}),"Completed ",r]})]})]})}),e.jsxs("div",{className:"flex-1 px-4 space-y-4",children:[e.jsxs(jt,{className:"bg-card border-border shadow-sm",children:[e.jsx(fs,{className:"pb-3",children:e.jsx(vs,{style:{fontSize:"16px",fontWeight:"var(--font-weight-semibold)"},children:"Project Summary"})}),e.jsxs(vt,{className:"space-y-3",children:[e.jsx("p",{className:"text-card-foreground",style:{fontSize:"14px",lineHeight:"1.6"},children:"This project has been successfully completed. All deliverables have been reviewed and approved by your team."}),e.jsx(Rg,{className:"bg-border"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",style:{fontSize:"13px"},children:"Status"}),e.jsx("span",{className:"text-primary",style:{fontSize:"13px",fontWeight:"var(--font-weight-medium)"},children:"Completed"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",style:{fontSize:"13px"},children:"Completion Date"}),e.jsx("span",{className:"text-card-foreground",style:{fontSize:"13px",fontWeight:"var(--font-weight-medium)"},children:r})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",style:{fontSize:"13px"},children:"Total Duration"}),e.jsx("span",{className:"text-card-foreground",style:{fontSize:"13px",fontWeight:"var(--font-weight-medium)"},children:"3 weeks"})]})]})]})]}),e.jsxs(jt,{className:"bg-card border-border shadow-sm",children:[e.jsx(fs,{className:"pb-3",children:e.jsx(vs,{style:{fontSize:"16px",fontWeight:"var(--font-weight-semibold)"},children:"Key Deliverables"})}),e.jsxs(vt,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Mn,{className:"w-5 h-5 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-card-foreground",style:{fontSize:"14px",fontWeight:"var(--font-weight-medium)"},children:"Final Report"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"12px"},children:"PDF ⢠2.4 MB"})]}),e.jsx(ke,{variant:"ghost",size:"sm",className:"flex-shrink-0",children:e.jsx(zr,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Fr,{className:"w-5 h-5 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-card-foreground",style:{fontSize:"14px",fontWeight:"var(--font-weight-medium)"},children:"Analytics Dashboard"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"12px"},children:"Interactive data visualization"})]}),e.jsx(ke,{variant:"ghost",size:"sm",className:"flex-shrink-0",children:e.jsx(zr,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Mn,{className:"w-5 h-5 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-card-foreground",style:{fontSize:"14px",fontWeight:"var(--font-weight-medium)"},children:"Implementation Guide"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"12px"},children:"PDF ⢠1.8 MB"})]}),e.jsx(ke,{variant:"ghost",size:"sm",className:"flex-shrink-0",children:e.jsx(zr,{className:"w-4 h-4"})})]})]})]}),e.jsxs(jt,{className:"bg-card border-border shadow-sm",children:[e.jsx(fs,{className:"pb-3",children:e.jsx(vs,{style:{fontSize:"16px",fontWeight:"var(--font-weight-semibold)"},children:"Key Results"})}),e.jsx(vt,{children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"text-center p-3 bg-primary/5 rounded-lg",children:[e.jsx("p",{className:"text-primary",style:{fontSize:"24px",fontWeight:"var(--font-weight-semibold)"},children:"+34%"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"12px"},children:"Conversion Rate"})]}),e.jsxs("div",{className:"text-center p-3 bg-primary/5 rounded-lg",children:[e.jsx("p",{className:"text-primary",style:{fontSize:"24px",fontWeight:"var(--font-weight-semibold)"},children:"+28%"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"12px"},children:"Revenue Growth"})]}),e.jsxs("div",{className:"text-center p-3 bg-primary/5 rounded-lg",children:[e.jsx("p",{className:"text-primary",style:{fontSize:"24px",fontWeight:"var(--font-weight-semibold)"},children:"-18%"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"12px"},children:"Cart Abandonment"})]}),e.jsxs("div",{className:"text-center p-3 bg-primary/5 rounded-lg",children:[e.jsx("p",{className:"text-primary",style:{fontSize:"24px",fontWeight:"var(--font-weight-semibold)"},children:"+42%"}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"12px"},children:"Page Speed"})]})]})})]}),e.jsxs(jt,{className:"shadow-sm mb-6",style:{backgroundColor:"#2d3143",borderColor:"#2d3143"},children:[e.jsx(fs,{className:"pb-3",children:e.jsx(vs,{style:{fontSize:"16px",fontWeight:"var(--font-weight-semibold)",color:"white"},children:"Recommended Next Steps"})}),e.jsxs(vt,{children:[e.jsxs("ul",{className:"space-y-2 mb-4",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"flex-shrink-0",style:{fontSize:"14px",color:"white"},children:"â¢"}),e.jsx("span",{style:{fontSize:"14px",color:"white"},children:"Schedule follow-up review in 30 days"})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"flex-shrink-0",style:{fontSize:"14px",color:"white"},children:"â¢"}),e.jsx("span",{style:{fontSize:"14px",color:"white"},children:"Implement recommended optimizations"})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"flex-shrink-0",style:{fontSize:"14px",color:"white"},children:"â¢"}),e.jsx("span",{style:{fontSize:"14px",color:"white"},children:"Monitor KPIs using analytics dashboard"})]})]}),e.jsx(ke,{onClick:i,className:"w-full bg-secondary text-secondary-foreground hover:bg-secondary/90",children:"Book a Call with Our Team"})]})]})]})]})}const aT=t=>!t.isAdminMode&&(!t.isAdminDomain||t.isImpersonating);function oT({activeTab:t,onTabChange:s,showStrategy:n=!1}){const r=[{id:"home",label:"Projects",icon:Qw},{id:"messages",label:"Messages",icon:mn},...n?[{id:"strategy",label:"Strategy",icon:gr}]:[],{id:"credits",label:"Credits",icon:yN},{id:"settings",label:"Settings",icon:vu}];return e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border max-w-md mx-auto bottom-nav",children:e.jsx("div",{className:"flex items-center justify-around px-2 pt-2 pb-2",children:r.map(a=>{const o=a.icon,i=t===a.id;return e.jsxs("button",{onClick:()=>s(a.id),className:`flex flex-col items-center justify-center gap-1 ${r.length>4?"px-2":"px-4"} py-2 rounded-xl transition-all ${i?"text-primary":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(o,{className:`w-6 h-6 ${i?"scale-110":""} transition-transform`}),e.jsx("span",{style:{fontSize:"12px",fontWeight:i?"var(--font-weight-medium)":"var(--font-weight-normal)"},children:a.label})]},a.id)})})})}const iT={pending:"bg-amber-100 text-amber-800",good:"bg-emerald-100 text-emerald-700",bad:"bg-destructive/10 text-destructive",neutral:"bg-muted text-muted-foreground"};function bi({title:t,children:s}){return e.jsxs("section",{className:"rounded-xl border border-border bg-card p-4 mb-4",children:[e.jsx("h2",{className:"font-semibold text-foreground mb-3",children:t}),s]})}const mo=({children:t})=>e.jsx("p",{className:"text-sm text-muted-foreground",children:t}),ea={textAlign:"left",fontWeight:500,padding:"6px 8px 6px 0",whiteSpace:"nowrap"},ta={padding:"6px 8px 6px 0",whiteSpace:"nowrap"};function lT({entry:t}){const s=t.strategy,n=lv(t.weekly_metrics);return e.jsxs(e.Fragment,{children:[e.jsxs(bi,{title:"This month",children:[!s&&e.jsx(mo,{children:"Your plan for this month is being written up. Check back soon."}),s&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.phase&&e.jsx("span",{className:"text-xs px-2 rounded-full bg-muted text-muted-foreground",style:{paddingTop:2,paddingBottom:2},children:s.phase}),bm(s)&&e.jsx("span",{className:"text-xs text-muted-foreground",children:bm(s)})]}),s.month_objective&&e.jsx("p",{className:"font-medium text-foreground",children:s.month_objective}),s.success_metric&&e.jsxs("p",{className:"text-sm text-foreground",children:[e.jsx("span",{className:"text-muted-foreground",children:"Success looks like: "}),s.success_metric]})]})]}),e.jsxs(bi,{title:"What we changed",children:[t.changes.length===0&&e.jsx(mo,{children:"No changes in the last few months."}),t.changes.map((r,a)=>{const o=cv(r.outcome);return e.jsxs("div",{className:a?"border-t border-border":"",style:{paddingTop:a?12:0,paddingBottom:12},children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:dv(r.change_type)}),e.jsx("span",{className:`text-xs px-2 rounded-full ${iT[o.tone]}`,style:{paddingTop:2,paddingBottom:2},children:o.label}),jm(r)&&e.jsx("span",{className:"text-xs text-muted-foreground",children:jm(r)})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:[xc(r.date),vm(r.platform),r.campaign].filter(
76Boolean).join(" · ")}),ym(r)&&e.jsx("p",{className:"text-sm text-foreground",children:ym(r)}),r.note&&e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:r.note}),r.expected_effect&&e.jsxs("p",{className:"text-sm text-foreground",children:[e.jsx("span",{className:"text-muted-foreground",children:"Expected: "}),r.expected_effect]})]},a)})]}),e.jsxs(bi,{title:"Weekly results",children:[n.length===0&&e.jsx(mo,{children:"Weekly results show here once the first week is in."}),n.map(r=>e.jsxs("div",{className:"mb-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground mb-2",children:vm(r.platform)}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"text-sm text-foreground",style:{width:"100%",borderCollapse:"collapse"},children:[e.jsx("thead",{className:"text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{style:ea,children:"Week of"}),e.jsx("th",{style:ea,children:"Spend"}),e.jsx("th",{style:ea,children:"Revenue"}),e.jsx("th",{style:ea,children:"ROAS"}),e.jsx("th",{style:ea,children:"Orders"}),e.jsx("th",{style:ea,children:"New-cust. CPA"})]})}),e.jsx("tbody",{children:r.rows.map((a,o)=>e.jsxs("tr",{className:"border-t border-border",children:[e.jsx("td",{style:ta,children:xc(a.week_start)}),e.jsx("td",{style:ta,children:hc(a.spend)}),e.jsx("td",{style:ta,children:hc(a.revenue)}),e.jsx("td",{style:ta,children:uv(a.roas)}),e.jsxs("td",{style:ta,children:[mv(a.orders),typeof a.new_orders=="number"?` (${a.new_orders} new)`:""]}),e.jsx("td",{style:ta,children:hc(a.cpa_new)})]},`${a.week_start}-${o}`))})]})})]},r.platform))]}),e.jsxs(bi,{title:"Waiting on you",children:[t.open_asks.length===0&&e.jsx(mo,{children:"Nothing right now. Thank you!"}),e.jsx("ul",{className:"space-y-3",children:t.open_asks.map((r,a)=>e.jsxs("li",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:r.ask}),e.jsx("p",{className:"text-xs text-muted-foreground",children:[r.first_asked?`Asked ${xc(r.first_asked)}`:null,r.blocks?`Holding up: ${r.blocks}`:null].filter(Boolean).join(" · ")})]},a))})]})]})}function cT({getProof:t,onLogoClick:s}){const{data:n,loading:r,error:a,refresh:o}=iv(t),i=l.useMemo(()=>(n==null?void 0:n.clients)??[],[n]),[d,m]=l.useState(null);l.useEffect(()=>{i.length&&!i.some(c=>c.client_id===d)&&m(i[0].client_id)},[i,d]);const p=i.find(c=>c.client_id===d)??null;return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-md mx-auto pb-24",children:[e.jsx(Xe,{title:"Strategy",showTitle:!0,onLogoClick:s}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground",children:(p==null?void 0:p.name)??"Your ad strategy"}),(p==null?void 0:p.primary_kpi)&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Main goal: ",p.primary_kpi]})]}),e.jsx("button",{onClick:o,className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground","aria-label":"Refresh",children:e.jsx(yt,{style:{width:14,height:14}})})]}),i.length>1&&e.jsx("div",{className:"flex flex-wrap gap-2 mb-4",role:"tablist","aria-label":"Company",children:i.map(c=>e.jsx("button",{role:"tab","aria-selected":c.client_id===d,onClick:()=>m(c.client_id),className:`text-sm px-3 py-1 rounded-full border ${c.client_id===d?"bg-primary text-primary-foreground border-transparent":"border-border bg-card text-foreground"}`,children:c.name??c.client_id},c.client_id))}),a&&e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/10 p-4 mb-4 text-sm text-destructive",children:a}),r&&!n&&e.jsx(mo,{children:"Loading your strategyâ¦"}),n&&i.length===0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card p-6 text-center","data-testid":"strategy-empty",children:[e.jsx(gr,{className:"text-muted-foreground mx-auto mb-3",style:{width:32,height:32}}),e.jsx("p",{className:"font-medium text-foreground mb-1",children:"No ad strategy to show yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"When Sunbowl runs your paid ads, your monthly plan, every change we make and weekly results appear here."})]}),p&&e.jsx(lT,{entry:p})]})]})}const dT=["Operations","Sales","Marketing","AI","QA & Delivery","Themes","Settings"],qp=[{id:"impersonate",title:"Impersonate Customer",desc:"View the app as a customer",icon:Ul,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onImpersonate",category:"Operations"},{id:"capacity",title:"Capacity Calendar",desc:"View project scheduling & capacity",icon:Ss,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onCapacity",category:"Operations"},{id:"subscriptions",title:"Subscriptions",desc:"Stripe & Recharge charges calendar, renewals & past due",icon:Pw,iconClass:"text-emerald-600",bgClass:"bg-emerald-600/10",handler:"onSubscriptions",category:"Operations"},{id:"bookingsAdmin",title:"Bookings",desc:"Upcoming meetings & pre-meeting briefs",
76icon:Mw,iconClass:"text-teal-600",bgClass:"bg-teal-600/10",handler:"onBookingsAdmin",category:"Operations"},{id:"databases",title:"Databases",desc:"Browse tickets, projects, clients & more",icon:Fw,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onDatabases",category:"Operations"},{id:"vacation",title:"Vacation & Travel Days",desc:"Manage team vacation & blackout dates",icon:pg,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onVacationDays",category:"Operations"},{id:"createProject",title:"Create Project",desc:"Add a new client project",icon:ng,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onCreateProject",category:"Operations"},{id:"clientSetup",title:"Client Setup",desc:"Audit config gaps & onboard new clients",icon:bu,iconClass:"text-rose-600",bgClass:"bg-rose-600/10",handler:"onClientSetup",category:"Operations"},{id:"assetIntake",title:"Asset Intake",desc:"Client uploads, requests & version chains",icon:ju,iconClass:"text-teal-600",bgClass:"bg-teal-600/10",handler:"onAssetIntake",category:"Operations"},{id:"chatAccounts",title:"Chat Accounts",desc:"Account tree, members & managers, join requests",icon:Hl,iconClass:"text-teal-600",bgClass:"bg-teal-600/10",handler:"onChatAccounts",category:"Operations"},{id:"communications",title:"Communications",desc:"All incoming communications",icon:mn,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onCommunications",category:"Operations"},{id:"legacyHub",title:"Slack-era Hub",desc:"The pre-bridge Slack mirror, read-only reference",icon:mn,iconClass:"text-muted-foreground",bgClass:"bg-muted",handler:"onLegacyHub",category:"Operations"},{id:"timeline",title:"Client Timeline",desc:"Full interaction history per client",icon:ms,iconClass:"text-cyan-600",bgClass:"bg-cyan-600/10",handler:"onTimeline",category:"Operations"},{id:"transcriptTickets",title:"Meeting Tickets",desc:"Assign projects to tickets extracted from calls",icon:Mn,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onTranscriptTickets",category:"Operations"},{id:"projectPresentation",title:"Project Presentation",desc:"Present project tickets to clients",icon:hg,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onProjectPresentation",category:"Operations"},{id:"creditCruncher",title:"Credit Cruncher",desc:"Get work done",icon:Yw,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onCreditCruncher",category:"Operations"},{id:"sales",title:"Sales",desc:"Manage orders and customers",icon:Af,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onSales",category:"Sales"},{id:"salesDrafts",title:"Sales Drafts",desc:"Approve agent-written outreach before it sends",icon:Tn,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onSalesDrafts",category:"Sales"},{id:"estimator",title:"Estimator",desc:"Estimate ticket credits",icon:uo,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onEstimator",category:"Sales"},{id:"chatLeads",title:"Chat Leads",desc:"Public chatbot conversations & quotes",icon:_l,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onChatLeads",category:"Sales"},{id:"conversionAnalytics",title:"Conversion Analytics",desc:"Store conversion rates vs industry benchmarks",icon:Fr,iconClass:"text-emerald-600",bgClass:"bg-emerald-600/10",handler:"onConversionAnalytics",category:"Sales"},{id:"profitProjections",title:"Profit Projections",desc:"5-year revenue impact of CR improvements",icon:yu,iconClass:"text-green-600",bgClass:"bg-green-600/10",handler:"onProfitProjections",category:"Sales"},{id:"marketingResearch",title:"Marketing Research",desc:"AI-powered store analysis for ad campaigns",icon:Xo,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onMarketingResearch",category:"Marketing"},{id:"saviDashboard",title:"SAVI â AI Visibility",desc:"AI mention & citation index per client",icon:ws,iconClass:"text-violet-600",bgClass:"bg-violet-600/10",handler:"onSaviDashboard",category:"Marketing"},{id:"seoReview",title:"SEO Review",desc:"Review AI-generated SEO suggestions",icon:Pt,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onSEOReview",category:"Marketing"},{id:"seoAutomation",title:"SEO Automation",desc:"Auto-apply AI SEO fixes per shop",icon:Pt,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onSeoAutomation",category:"Marketing"},{id:"siteAudit",title:"Site Audit",desc:"Analyze website performance and SEO",icon:Id,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onSiteAudit",category:"Marketing"},{id:"dmarcMonitoring",title:"DMARC Monitoring",desc:"Email auth health across client domains",icon:Tn,iconClass:"text-sky-600",bgClass:"bg-sky-600/10",handler:"onDmarcMonitoring",category:"Marketing"},{id:"promoEmailReview",title:"Promo Email Review",desc:"Capture & QA client campaign emails before send",icon:Tn,iconClass:"text-violet-600",bgClass:"bg-violet-600/10",handler:"onPromoEmailReview",category:"Marketing"},{id:"reportRecommendations",title:"Report Recommendations",desc:"Review AI report summaries & generate audio",icon:bN,iconClass:"text-teal-600",bgClass:"bg-teal-600/10",handler:"onReportRecommendations",category:"Marketing"},{id:"clientLedger",title:"Client Ledger",desc:"Paid-ads strategy, holds, changes & asks per client",icon:Rw,iconClass:"text-emerald-600",bgClass:"bg-emerald-600/10",handler:"onClientLedger",category:"Marketing"},{id:"contentQueue",title:"Content Queue",desc:"Approve social distribution packs â one gate per episode",icon:An,iconClass:"text-violet-600",bgClass:"bg-violet-600/10",handler:"onContentQueue",category:"Marketing"},{id:"aiRuns",title:"AI Runs",desc:"Monitor autonomous pipeline runs & PRs",icon:Fl,iconClass:"text-violet-600",bgClass:"bg-violet-600/10",handler:"onAiRuns",category:"AI"},{id:"aiInsights",title:"AI Insights",desc:"User behavior analysis from Clarity",icon:ws,iconClass:"text-purple-500",bgClass:"bg-purple-500/10",handler:"onAIInsights",category:"AI"},{id:"modelCompare",title:"Model Compare",desc:"Compare AI model quality & speed",icon:ws,iconClass:"text-amber-600",bgClass:"bg-amber-600/10",handler:"onModelCompare",category:"AI"},{id:"adminQA",title:"Admin QA Review",desc:"Review all pending QA tickets",icon:Xi,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onAdminQAReview",category:"QA & Delivery"},{id:"jobReports",title:"Job Reports",desc:"Review AI job videos before human QA",icon:gu,iconClass:"text-emerald-600",bgClass:"bg-emerald-600/10",handler:"onJobReports",category:"QA & Delivery"},{id:"clientMockups",title:"Client Mockups",desc:"Mockup links by customer, ready to copy",icon:dg,iconClass:"text-violet-600",bgClass:"bg-violet-600/10",handler:"onClientMockups",category:"QA & Delivery"},{id:"duplicateMerge",title:"Duplicate Merge",desc:"Detect & merge duplicate tickets",icon:Hr,iconClass:"text-purple-600",bgClass:"bg-purple-600/10",handler:"onDuplicateMerge",category:"QA & Delivery"},{id:"themeDeploy",title:"Theme Deploy",desc:"Merge staging to production",icon:Or,iconClass:"text-green-600",bgClass:"bg-green-600/10",handler:"onThemeDeploy",category:"Themes"},{id:"themeSync",title:"Theme Sync",desc:"Keep staging in sync with main",icon:yt,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onThemeSync",category:"Themes"},{id:"themeManagement",title:"Theme Previews",desc:"Assign preview themes to projects",icon:mg,iconClass:"text-indigo-600",bgClass:"bg-indigo-600/10",handler:"onThemeManagement",category:"Themes"},{id:"logoManagement",title:"Logo Management",desc:"Upload logos for all c
76ompanies",icon:ig,iconClass:"text-primary",bgClass:"bg-primary/10",handler:"onLogoManagement",category:"Settings"},{id:"notificationSettings",title:"Notifications",desc:"Switch team notification types on or off",icon:Dn,iconClass:"text-amber-600",bgClass:"bg-amber-600/10",handler:"onNotificationSettings",category:"Settings"},{id:"dialerSettings",title:"Dialer",desc:"Verify your number for click-to-call",icon:En,iconClass:"text-sky-600",bgClass:"bg-sky-600/10",handler:"onDialerSettings",category:"Settings"},{id:"functionWarming",title:"Server Warming",desc:"Keep-warm pinger â turn OFF before deploys",icon:sg,iconClass:"text-orange-500",bgClass:"bg-orange-500/10",handler:"onFunctionWarming",category:"Settings"}];function Vp({card:t,onClick:s,favorite:n,onToggleFavorite:r}){const a=t.icon;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:s,className:"flex-1 bg-card border border-border rounded-lg p-4 flex items-center gap-3 hover:bg-accent transition-colors active:scale-[0.98]",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},children:[e.jsx("div",{className:`flex-shrink-0 ${t.bgClass} rounded-lg flex items-center justify-center`,style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)"},children:e.jsx(a,{className:t.iconClass,style:{width:"24px",height:"24px"}})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:t.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.desc})]})]}),e.jsx("button",{type:"button",onClick:()=>r(t.id),title:n?"Remove from favorites":"Pin to favorites","aria-label":n?"Remove from favorites":"Pin to favorites",className:`flex-shrink-0 p-1 ${n?"text-amber-600":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(mN,{style:{width:"18px",height:"18px"},fill:n?"currentColor":"none"})})]})}function Yp({title:t}){return e.jsx("h2",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",style:{margin:"20px 0 8px",paddingLeft:2},children:t})}function uT({onLogoClick:t,onLogoManagement:s,onSiteAudit:n,onCommunications:r,onCreditCruncher:a,onEstimator:o,onSales:i,onImpersonate:d,onCapacity:m,onAdminQAReview:p,onSEOReview:c,onCreateProject:u,onAIInsights:x,onVacationDays:h,onTranscriptTickets:b,onProjectPresentation:f,onMarketingResearch:g,onAiRuns:y,onChatLeads:j,onThemeDeploy:v,onThemeSync:T,onSeoAutomation:k,onThemeManagement:w,onDatabases:I,onDuplicateMerge:A,onModelCompare:E,onConversionAnalytics:C,onProfitProjections:N,onTimeline:S,onBookingsAdmin:O,onDmarcMonitoring:R,onSaviDashboard:z,onClientSetup:D,onPromoEmailReview:L,onReportRecommendations:$,onJobReports:q,onNotificationSettings:P,onDialerSettings:U,onSubscriptions:V,onFunctionWarming:M,onSalesDrafts:F,onAssetIntake:W,onContentQueue:_,onChatAccounts:G,onLegacyHub:B,onClientMockups:Y,onClientLedger:J}){const{user:H,token:Z}=pt(),[Q,K]=l.useState([]),[X,se]=l.useState(""),pe={onLegacyHub:B,onImpersonate:d,onCapacity:m,onVacationDays:h,onCreateProject:u,onLogoManagement:s,onAdminQAReview:p,onSEOReview:c,onAIInsights:x,onCommunications:r,onSales:i,onEstimator:o,onSiteAudit:n,onCreditCruncher:a,onTranscriptTickets:b,onProjectPresentation:f,onMarketingResearch:g,onAiRuns:y,onChatLeads:j,onThemeDeploy:v,onThemeSync:T,onSeoAutomation:k,onThemeManagement:w,onDatabases:I,onDuplicateMerge:A,onModelCompare:E,onConversionAnalytics:C,onProfitProjections:N,onTimeline:S,onBookingsAdmin:O,onDmarcMonitoring:R,onSaviDashboard:z,onClientSetup:D,onPromoEmailReview:L,onReportRecommendations:$,onJobReports:q,onSalesDrafts:F,onNotificationSettings:P,onDialerSettings:U,onSubscriptions:V,onFunctionWarming:M,onAssetIntake:W,onContentQueue:_,onChatAccounts:G,onClientMockups:Y,onClientLedger:J};l.useEffect(()=>{H!=null&&H.uid&&(async()=>{try{const xe=await ps(ut(ge,"userPreferences",H.uid));if(xe.exists()){const ze=xe.data();Array.isArray(ze.adminCardFavorites)&&K(ze.adminCardFavorites.filter(Le=>typeof Le=="string"))}}catch(xe){console.error("Failed to load admin favorites:",xe)}})()},[H==null?void 0:H.uid]);const me=l.useCallback(xe=>{K(ze=>{const Le=ze.includes(xe)?ze.filter(ht=>ht!==xe):[...ze,xe];return H!=null&&H.uid&&lf("userPreferences",H.uid,{adminCardFavorites:Le},Z||void 0,!0).catch(ht=>console.error("Failed to save admin favorites:",ht)),Le})},[H==null?void 0:H.uid,Z]),Ne=l.useMemo(()=>{const xe=X.trim().toLowerCase();return xe?qp.filter(ze=>ze.title.toLowerCase().includes(xe)||ze.desc.toLowerCase().includes(xe)||ze.category.toLowerCase().includes(xe)):qp},[X]),at=l.useMemo(()=>Ne.filter(xe=>Q.includes(xe.id)),[Ne,Q]),ae=l.useMemo(()=>dT.map(xe=>({category:xe,cards:Ne.filter(ze=>ze.category===xe)})).filter(xe=>xe.cards.length>0),[Ne]);return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:t}),e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:"Admin Panel"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage your Bucky app settings"})]}),e.jsxs("div",{style:{position:"relative"},children:[e.jsx(Pt,{className:"text-muted-foreground",style:{position:"absolute",left:12,top:"50%",transform:"translateY(-50%)",width:16,height:16,pointerEvents:"none"}}),e.jsx("input",{type:"text",value:X,onChange:xe=>se(xe.target.value),placeholder:"Filter featuresâ¦",className:"bg-card border border-border text-sm text-foreground focus:outline-none focus:border-primary",style:{width:"100%",padding:"10px 12px 10px 36px",borderRadius:10}})]}),Ne.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground",style:{marginTop:24,textAlign:"center"},children:["Nothing matches â",X.trim(),"â"]}
76),at.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Yp,{title:"â
Favorites"}),e.jsx("div",{className:"space-y-3",children:at.map(xe=>e.jsx(Vp,{card:xe,onClick:pe[xe.handler],favorite:!0,onToggleFavorite:me},`fav-${xe.id}`))})]}),ae.map(({category:xe,cards:ze})=>e.jsxs(ee.Fragment,{children:[e.jsx(Yp,{title:xe}),e.jsx("div",{className:"space-y-3",children:ze.map(Le=>e.jsx(Vp,{card:Le,onClick:pe[Le.handler],favorite:Q.includes(Le.id),onToggleFavorite:me},Le.id))})]},xe))]})]})}function mT({onBack:t,onLogoClick:s}){const{token:n}=pt(),{logos:r,loading:a,refetch:o}=Ra(n),[i,d]=l.useState(""),[m,p]=l.useState(null),[c,u]=l.useState(null),[x,h]=l.useState(null),[b,f]=l.useState(""),[g,y]=l.useState(!1),j=l.useMemo(()=>Object.keys(r).sort((A,E)=>A.toLowerCase().localeCompare(E.toLowerCase())),[r]),v=l.useMemo(()=>{if(!i.trim())return j;const A=i.toLowerCase();return j.filter(E=>E.toLowerCase().includes(A))},[j,i]),T=A=>new Promise((E,C)=>{const N=new FileReader;N.readAsDataURL(A),N.onload=()=>E(N.result),N.onerror=()=>C(new Error("Failed to read file"))}),k=async(A,E)=>{if(!n){h("No authentication token available");return}if(!A.trim()){h("Company name is required");return}p(A),h(null),u(null);try{const C=await T(E);console.log("Uploading logo for:",A);const N=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/updateCompanyLogo",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({companyName:A,logoData:C})});if(!N.ok){const S=await N.json().catch(()=>({error:"Unknown error"}));throw new Error(S.error||`Failed to upload logo (${N.status})`)}await qn.remove(Rl.COMPANY_LOGOS),await new Promise(S=>setTimeout(S,500)),await o(),u(A),f(""),y(!1),setTimeout(()=>u(null),3e3)}catch(C){console.error("Logo upload error:",C),h(C.message||"Failed to upload logo")}finally{p(null)}},w=A=>{const E=document.createElement("input");E.type="file",E.accept="image/*",E.onchange=C=>{var S;const N=(S=C.target.files)==null?void 0:S[0];N&&A(N)},E.click()},I=()=>{b.trim()&&(y(!1),w(A=>k(b.trim(),A)))};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onBack:t,onLogoClick:s}),e.jsxs("div",{className:"max-w-2xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:"Logo Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Upload and manage logos for all companies"})]}),e.jsxs("div",{className:"mb-6 space-y-3",children:[e.jsxs("div",{className:"relative flex items-center",children:[e.jsx(Pt,{className:"absolute left-3 w-5 h-5 text-muted-foreground pointer-events-none"}),e.jsx(it,{type:"text",placeholder:"Search companies...",value:i,onChange:A=>d(A.target.value),className:"w-full !pl-[2.5rem] !pr-[2.5rem]"}),i&&e.jsx("button",{onClick:()=>d(""),className:"absolute right-3 text-muted-foreground hover:text-foreground",children:e.jsx(mt,{className:"w-5 h-5"})})]}),g?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(it,{type:"text",placeholder:"Enter channel or company name...",value:b,onChange:A=>f(A.target.value),onKeyDown:A=>{A.key==="Enter"&&I(),A.key==="Escape"&&(y(!1),f(""))},autoFocus:!0}),e.jsxs(ke,{onClick:I,disabled:!b.trim(),children:[e.jsx(pl,{className:"w-4 h-4 mr-2"}),"Upload"]}),e.jsx(ke,{variant:"outline",onClick:()=>{y(!1),f("")},children:"Cancel"})]}):e.jsx(ke,{onClick:()=>y(!0),variant:"outline",className:"w-full",children:"+ Add New Company Logo"})]}),x&&e.jsxs(st.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"mb-4 p-4 bg-destructive/10 border border-destructive/20 rounded-lg flex items-start gap-3",children:[e.jsx(gs,{className:"w-5 h-5 text-destructive flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-destructive font-medium",children:"Upload Failed"}),e.jsx("p",{className:"text-sm text-destructive/80 mt-1",children:x})]})]}),a&&e.jsx("div",{className:"flex justify-center items-center py-16",children:e.jsx(fe,{className:"w-8 h-8 text-primary animate-spin"})}),!a&&e.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:[v.length," of ",j.length," companies"]}),!a&&e.jsx("div",{className:"grid grid-cols-2 gap-3",children:v.map(A=>{const E=r[A]||Vr,C=m===A,N=c===A;return e.jsx(st.div,{className:"bg-card border border-border rounded-lg p-4",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},whileHover:{scale:1.01},children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border)"},children:e.jsx("img",{src:E,alt:A,className:"w-full h-full object-cover",style:{padding:"4px"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium text-foreground text-sm truncate",children:A}),e.jsx("div",{className:"mt-1",children:e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(it,{type:"file",accept:"image/*",className:"hidden",onChange:S=>{var R;const O=(R=S.target.files)==null?void 0:R[0];O&&k(A,O)},disabled:C}),e.jsx(ke,{type:"button",size:"sm",variant:"ghost",disabled:C,className:"pointer-events-none h-7 px-2 text-xs",children:C?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-3 h-3 mr-1 animate-spin"}),"Uploading..."]}):N?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-3 h-3 mr-1 text-green-600"}),"Done"]}):e.jsxs(e.Fragment,{children:[e.jsx(pl,{className:"w-3 h-3 mr-1"}),"Change"]})})]})})]})]})},A)})}),!a&&v.length===0&&i&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-16 h-16 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx(Pt,{className:"w-8 h-8 text-muted-foreground opacity-50"})}),e.jsx("h3",{className:"text-foreground mb-2",children:"No Results"}),e.jsxs("p",{className:"text-muted-foreground text-center max-w-xs mb-4",children:['No companies match "',i,'"']}),e.jsxs(ke,{onClick:()=>{f(i),y(!0)},children:['+ Add "',i,'" as New']})]}
76),!a&&j.length===0&&!i&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-16 h-16 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx("span",{style:{fontSize:"2rem",opacity:.4},children:"ð¢"})}),e.jsx("h3",{className:"text-foreground mb-2",children:"No Logos Yet"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:'Click "Add New Company Logo" to upload your first logo'})]})]})]})}function pT({onBack:t,onLogoClick:s}){const{token:n}=pt(),{companies:r,loading:a,error:o}=Pa(n),{logos:i,refetch:d}=Ra(n),[m,p]=l.useState(null),[c,u]=l.useState(null),[x,h]=l.useState(null),b=j=>j.toLowerCase().replace(/[^a-z0-9]/g,"-"),f=(j,v)=>{const T=b(j);return v.find(k=>b(k)===T)||v[0]},g=async(j,v)=>{if(!n){h("No authentication token available");return}const T=r.find(k=>k.name===j);if(!T||!T.slackChannels||T.slackChannels.length===0){h("No Slack channels found for this company");return}p(j),h(null),u(null);try{const k=await new Promise((E,C)=>{const N=new FileReader;N.readAsDataURL(v),N.onload=()=>{E(N.result)},N.onerror=()=>{C(new Error("Failed to read file"))}});console.log("=========================================="),console.log("UPLOADING LOGO FOR COMPANY:",j),console.log("Slack channels for this company:",T.slackChannels),console.log("Number of channels:",T.slackChannels.length),console.log("==========================================");const w=f(j,T.slackChannels);console.log(`Primary channel selected: "${w}"`),console.log("(This prevents overwriting logos for shared channels)"),console.log(`Uploading logo for primary channel: "${w}"`);const I=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/updateCompanyLogo",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({companyName:w,logoData:k})});if(!I.ok){const E=await I.json().catch(()=>({error:"Unknown error"}));throw console.error("Upload failed for channel:",w,E),new Error(E.error||`Failed to upload logo for ${w} (${I.status})`)}const A=await I.json();console.log(`â Logo uploaded successfully for channel: "${w}"`),await qn.remove(Rl.COMPANY_LOGOS),console.log("Cleared company logos cache"),await new Promise(E=>setTimeout(E,500)),await d(),console.log("Logos refetched"),u(j),setTimeout(()=>u(null),3e3)}catch(k){console.error("Logo upload error:",k),h(k.message||"Failed to upload logo"),p(null)}finally{p(null)}},y=j=>{const v=r.find(T=>T.name===j);if(v&&v.slackChannels&&v.slackChannels.length>0){const T=v.slackChannels[0],k=i[T]||i[T.replace("#","")];if(k)return k}return Vr};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onBack:t,onLogoClick:s}),e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:"Company Logo Manager"}),e.jsx("p",{className:"text-muted-foreground",children:"Upload and manage company logos"})]}),x&&e.jsxs(st.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"mb-4 p-4 bg-destructive/10 border border-destructive/20 rounded-lg flex items-start gap-3",children:[e.jsx(gs,{className:"w-5 h-5 text-destructive flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-destructive font-medium",children:"Upload Failed"}),e.jsx("p",{className:"text-sm text-destructive/80 mt-1",children:x})]})]}),a&&e.jsx("div",{className:"flex justify-center items-center py-16",children:e.jsx(fe,{className:"w-8 h-8 text-primary animate-spin"})}),o&&!a&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx(gs,{className:"w-12 h-12 text-destructive mb-4"}),e.jsx("h3",{className:"text-foreground mb-2",children:"Error Loading Companies"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:o})]}),!a&&!o&&e.jsx("div",{className:"space-y-3",children:r.map(j=>{const v=j.name.replace("#",""),T=y(j.name),k=m===v,w=c===v;return e.jsx(st.div,{className:"bg-card border border-border rounded-lg p-4",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},whileHover:{scale:1.01},children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex-shrink-0 bg-white rounded-lg flex items-center justify-center overflow-hidden",style:{width:"64px",height:"64px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border)"},children:T.startsWith("emoji:")?e.jsx("span",{style:{fontSize:"2rem"},children:T.replace("emoji:","")}):e.jsx("img",{src:T,alt:v,className:"w-full h-full object-cover",style:{padding:"7px"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:v}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-2",children:[j.projectCount," ",j.projectCount===1?"channel":"channels"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(it,{type:"file",accept:"image/*",className:"hidden",onChange:I=>{var E;const A=(E=I.target.files)==null?void 0:E[0];A&&g(v,A)},disabled:k}),e.jsx(ke,{type:"button",size:"sm",variant:"outline",disabled:k,className:"pointer-events-none",children:k?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-4 h-4 mr-2 animate-spin"}),"Uploading..."]}):w?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"w-4 h-4 mr-2 text-green-600"}),"Uploaded"]}):e.jsxs(e.Fragment,{children:[e.jsx(pl,{className:"w-4 h-4 mr-2"}),"Upload Logo"]})})]})})]})]})},v)})}),!a&&!o&&r.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[e.jsx("div",{className:"w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4",children:e.jsx("span",{style:{fontSize:"3rem",opacity:.4},children:"ð¢"})}),e.jsx("h3",{className:"text-foreground mb-2",children:"No Companies Found"}),e.jsx("p",{className:"text-muted-foreground text-center max-w-xs",children:"No companies are available to manage"})]})]})]})}function xT({onBack:t,onLogoClick:s}){const{user:n,token:r}=pt(),[a,o]=l.useState("menu"),[i,d]=l.useState(!1),[m,p]=l.useState(""),[c,u]=l.useState(null),[x,h]=l.useState(null),[b,f]=l.useState(null),[g,y]=l.useState(!1),[j,v]=l.useState([]),[T,k]=l.useState(!1),[w,I]=l.useState(""),[A,E]=l.useState(null),C=l.useCallback(async U=>{if(n){k(!0),h(null);try{const V=r||await n.getIdToken(),M=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getRecentTickets",{method:"POST",headers:{Authorization:`Bearer ${V}`,"Content-Type":"application/json"},body:JSON.stringify({search:U||void 0,limit:10})});if(!M.ok){const W=await M.json();throw new Error("Failed to fetch recent tickets")}const F=await M.json();F.success&&F.tickets&&v(F.tickets)}catch(V){console.error("Error fetching recent tickets:",V.message||"An unexpected error occurred"),h("Failed to fetch recent tickets")}finally{k(!1)}}},[n,r]);l.useEffect(()=>{a==="single"&&j.length===0&&C()},[a,j.length,C]);const N=()=>{w.trim()?C(w.trim()):C()},S=U=>{E(U),p(U.id)},O=async()=>{d(!0),h(null),u(null);try{if(!n)throw new Error("Authentication required");const U=r||await n.getIdToken(),V=await fetch("https://batchreestimatetickets-jf3ot2tygq-uc.a.run.app",{method:"POST",headers:{Authorization:`Bearer ${U}`,"Content-Type":"application/json"},body:JSON.stringify({overwriteExisting:g})});if(!V.ok){const F=await V.json();throw new Error(F.error||`Failed: ${V.status}`)}const M=await V.json();if(M.success&&M.results)u(M.results);else throw new Error("Invalid response format")}catch(U){console.error("Error in bulk estimation:",U),h(U.message||"Failed to complete bulk estimation")}finally{d(!1)}},R=async()=>
76{if(!m.trim()){h("Please enter a ticket ID");return}d(!0),h(null),f(null);try{if(!n)throw new Error("Authentication required");const U=r||await n.getIdToken(),V=await fetch("https://estimateticketcredits-jf3ot2tygq-uc.a.run.app",{method:"POST",headers:{Authorization:`Bearer ${U}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:m.trim(),urgency:"medium",businessValue:"medium"})});if(!V.ok){const F=await V.json();throw new Error(F.error||`Failed: ${V.status}`)}const M=await V.json();if(M.success&&M.estimate)f(M.estimate);else throw new Error("Invalid response format")}catch(U){console.error("Error estimating single ticket:",U),h(U.message||"Failed to estimate ticket")}finally{d(!1)}},z=async()=>{await O()},D=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",style:{borderRadius:"var(--radius-md)"},children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx("div",{className:"flex-shrink-0 bg-blue-100 rounded-lg p-2",style:{borderRadius:"var(--radius-sm)"},children:e.jsx(Zi,{className:"text-blue-600",size:24})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-blue-900 mb-2",children:"Estimate All Open Tickets?"}),e.jsx("p",{className:"text-sm text-blue-800 mb-3",children:"This will estimate all tickets in your Notion database with the following statuses:"}),e.jsxs("ul",{className:"text-sm text-blue-800 space-y-1 mb-3",children:[e.jsxs("li",{children:["⢠",e.jsx("strong",{children:"Backlog"})]}),e.jsxs("li",{children:["⢠",e.jsx("strong",{children:"To Do"})]}),e.jsxs("li",{children:["⢠",e.jsx("strong",{children:"In Progress"})]}),e.jsxs("li",{children:["⢠",e.jsx("strong",{children:"In Review"})]})]}),e.jsx("p",{className:"text-sm text-blue-800",children:"Each ticket will be analyzed by AI and updated with:"}),e.jsxs("ul",{className:"text-sm text-blue-800 space-y-1 mt-2",children:[e.jsx("li",{children:"⢠Credits Min and Max"}),e.jsx("li",{children:"⢠Internal Time Estimate"}),e.jsx("li",{children:"⢠Ticket Complexity"})]})]})]}),e.jsx("div",{className:"bg-yellow-50 border border-yellow-200 rounded p-3 mt-3",style:{borderRadius:"var(--radius-sm)"},children:e.jsxs("p",{className:"text-xs text-yellow-800",children:[e.jsx("strong",{children:"Note:"})," This process may take several minutes depending on the number of tickets."]})})]}),e.jsx("div",{className:"bg-card border border-border rounded-lg p-4",style:{borderRadius:"var(--radius-md)"},children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:g,onChange:U=>y(U.target.checked),className:"mt-1 w-4 h-4 text-primary bg-background border-border rounded focus:ring-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-foreground",children:"Overwrite existing estimates"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"By default, tickets that already have credit estimates will be skipped. Enable this to re-estimate all tickets, even those with existing values."})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{onClick:()=>{o("bulk"),O()},className:"flex-1 bg-primary text-primary-foreground py-3 px-4 rounded font-semibold hover:bg-primary/90 flex items-center justify-center gap-2",style:{borderRadius:"var(--radius-sm)"},children:[e.jsx(Zi,{size:20}),"Start Bulk Estimation"]}),e.jsx("button",{onClick:()=>{o("menu"),h(null),y(!1)},className:"px-4 py-3 bg-secondary text-secondary-foreground rounded font-semibold hover:bg-secondary/90",style:{borderRadius:"var(--radius-sm)"},children:"Cancel"})]})]}),L=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",style:{borderRadius:"var(--radius-md)"},children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx("div",{className:"flex-shrink-0 bg-blue-100 rounded-lg p-2",style:{borderRadius:"var(--radius-sm)"},children:e.jsx(uo,{className:"text-blue-600",size:24})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-blue-900 mb-2",children:"Estimate Outstanding Tickets?"}),e.jsx("p",{className:"text-sm text-blue-800 mb-3",children:"This will estimate all open tickets (same as bulk estimation). These statuses will be included:"}),e.jsxs("ul",{className:"text-sm text-blue-800 space-y-1 mb-3",children:[e.jsxs("li",{children:["⢠",e.jsx("strong",{children:"Backlog"})]}),e.jsxs("li",{children:["⢠",e.jsx("strong",{children:"To Do"})]}),e.jsxs("li",{children:["⢠",e.jsx("strong",{children:"In Progress"})]}),e.jsxs("li",{children:["⢠",e.jsx("strong",{children:"In Review"})]})]}),e.jsx("p",{className:"text-sm text-blue-800",children:"Each ticket will be analyzed by AI and updated with credits, time, and complexity estimates."})]})]}),e.jsx("div",{className:"bg-yellow-50 border border-yellow-200 rounded p-3 mt-3",style:{borderRadius:"var(--radius-sm)"},children:e.jsxs("p",{className:"text-xs text-yellow-800",children:[e.jsx("strong",{children:"Note:"})," This may take several minutes."]})})]}),e.jsx("div",{className:"bg-card border border-border rounded-lg p-4",style:{borderRadius:"var(--radius-md)"},children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:g,onChange:U=>y(U.target.checked),className:"mt-1 w-4 h-4 text-primary bg-background border-border rounded focus:ring-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-foreground",children:"Overwrite existing estimates"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"By default, tickets that already have credit estimates will be skipped. Enable this to re-estimate all tickets, even those with existing values."})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{onClick:()=>{o("outstanding"),z()},className:"flex-1 bg-primary text-primary-foreground py-3 px-4 roun
76ded font-semibold hover:bg-primary/90 flex items-center justify-center gap-2",style:{borderRadius:"var(--radius-sm)"},children:[e.jsx(uo,{size:20}),"Start Estimation"]}),e.jsx("button",{onClick:()=>{o("menu"),h(null),y(!1)},className:"px-4 py-3 bg-secondary text-secondary-foreground rounded font-semibold hover:bg-secondary/90",style:{borderRadius:"var(--radius-sm)"},children:"Cancel"})]})]}),$=()=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs(st.button,{onClick:()=>o("bulk-confirm"),className:"w-full bg-card border border-border rounded-lg p-4 flex items-center gap-3 hover:bg-accent transition-colors",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},whileTap:{scale:.98},children:[e.jsx("div",{className:"flex-shrink-0 bg-primary/10 rounded-lg flex items-center justify-center",style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)"},children:e.jsx(Zi,{className:"text-primary",style:{width:"24px",height:"24px"}})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Estimate in Bulk"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Estimate all open tickets"})]})]}),e.jsxs(st.button,{onClick:()=>o("single"),className:"w-full bg-card border border-border rounded-lg p-4 flex items-center gap-3 hover:bg-accent transition-colors",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},whileTap:{scale:.98},children:[e.jsx("div",{className:"flex-shrink-0 bg-primary/10 rounded-lg flex items-center justify-center",style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)"},children:e.jsx(Mn,{className:"text-primary",style:{width:"24px",height:"24px"}})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Estimate Single Ticket"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Estimate a specific ticket by ID"})]})]}),e.jsxs(st.button,{onClick:()=>o("outstanding-confirm"),className:"w-full bg-card border border-border rounded-lg p-4 flex items-center gap-3 hover:bg-accent transition-colors",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},whileTap:{scale:.98},children:[e.jsx("div",{className:"flex-shrink-0 bg-primary/10 rounded-lg flex items-center justify-center",style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)"},children:e.jsx(uo,{className:"text-primary",style:{width:"24px",height:"24px"}})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Estimate Outstanding Tickets"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Estimate tickets without estimates"})]})]})]}),q=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",style:{borderRadius:"var(--radius-md)"},children:[e.jsx("label",{htmlFor:"searchTicket",className:"block text-sm font-medium text-foreground mb-2",children:"Search by Ticket Number"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{id:"searchTicket",type:"text",value:w,onChange:U=>I(U.target.value),onKeyDown:U=>U.key==="Enter"&&N(),placeholder:"TICK-123 or search by name...",className:"flex-1 px-3 py-2 bg-background border border-border rounded text-foreground",style:{borderRadius:"var(--radius-sm)"},disabled:T}),e.jsx("button",{onClick:N,disabled:T,className:"px-4 py-2 bg-secondary text-secondary-foreground rounded font-medium hover:bg-secondary/90 flex items-center gap-2",style:{borderRadius:"var(--radius-sm)"},children:T?e.jsx(fe,{className:"animate-spin",size:18}):e.jsx(Pt,{size:18})}),e.jsx("button",{onClick:()=>{I(""),C()},disabled:T,className:"px-4 py-2 bg-secondary text-secondary-foreground rounded font-medium hover:bg-secondary/90 flex items-center gap-2",style:{borderRadius:"var(--radius-sm)"},title:"Refresh recent tickets",children:e.jsx(yt,{size:18,className:T?"animate-spin":""})})]})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg",style:{borderRadius:"var(--radius-md)"},children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border flex items-center justify-between",children:[e.jsxs("h3",{className:"font-medium text-foreground flex items-center gap-2",children:[e.jsx(ms,{size:16,className:"text-muted-foreground"}),w?"Search Results":"Recent Tickets"]}),T&&e.jsx(fe,{className:"animate-spin text-muted-foreground",size:16})]}),e.jsx("div",{className:"divide-y divide-border max-h-64 overflow-y-auto",children:j.length===0&&!T?e.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:w?"No tickets found matching your search":"No recent tickets found"}):j.map(U=>e.jsxs(st.button,{onClick:()=>S(U),className:`w-full px-4 py-3 text-left hover:bg-accent transition-colors flex items-center gap-3 ${(A==null?void 0:A.id)===U.id?"bg-primary/10":""}`,whileTap:{scale:.98},children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-xs bg-primary/10 text-primary px-2 py-0.5 rounded",children:U.ticketNumber}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${U.status==="Complete"?"bg-green-100 text-green-700":U.status==="In Progress"?"bg-blue-100 text-blue-700":U.status==="In Review"?"bg-purple-100 text-purple-700":U.status==="Client Approval"?"bg-cyan-100 text-cyan-700":"bg-gray-100 text-gray-700"}`,children:Wr(U.status)}),U.creditsMax!==null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[U.creditsMax," credits"]})]}),e.jsx("p",{className:"text-sm text-foreground truncate",children:U.name})]}),(A==null?void 0:A.id)===U.id&&e.jsx(kt,{size:18,className:"text-primary flex-shrink-0"})]},U.id))})]}),A&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",style:{borderRadius:"var(--radius-md)"},children:e.jsxs("div",{className:"flex items-center gap-2 text-blue-900 text-sm",children:[e.jsx(kt,{size:16}),e.jsx("span",{className:"font-medium",children:"Selected:"}),e.jsx("span",{className:"font-mono",children:A.ticketNumber}),e.jsx("span",{className:"text-blue-700 truncate flex-1",children:A.name})]})}),e.jsxs("details",{className:"bg-card border border-border rounded-lg",style:{borderRadius:"var(--radius-md)"},children:[e.jsx("summary",{className:"px-4 py-3 cursor-pointer text-sm text-muted-foreground hover:text-foreground",children:"Or enter Notion ID manually..."}),e.jsx("div",{className:"px-4 pb-4",children:e.jsx("input",{type:"text",value:m,onChange:U=>{p(U.target.value),E(null)},placeholder:"Enter Notion ticket ID (e.g., 29bc197b-3ae7-8176-9c32-d9395dcf013c)",className:"w-full px-3 py-2 bg-background border border-border rounded text-foreground text-sm",style:{borderRadius:"var(--radius-sm)"},disabled:i})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:R,disabled:i||!m.trim(),className:"flex-1 bg-primary text-primary-foreground py-3 px-4 roun
76ded font-semibold hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2",style:{borderRadius:"var(--radius-sm)"},children:i?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"animate-spin",size:20}),"Estimating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(uo,{size:20}),"Estimate Ticket"]})}),e.jsx("button",{onClick:()=>{o("menu"),p(""),f(null),E(null),I(""),h(null)},disabled:i,className:"px-4 py-3 bg-secondary text-secondary-foreground rounded font-semibold hover:bg-secondary/90",style:{borderRadius:"var(--radius-sm)"},children:"Cancel"})]}),b&&e.jsxs("div",{className:"bg-green-50 border border-green-200 rounded-lg p-4",style:{borderRadius:"var(--radius-md)"},children:[e.jsx("h3",{className:"font-semibold text-green-900 mb-3",children:"Estimation Complete!"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-green-700",children:"Estimated Credits:"}),e.jsx("span",{className:"font-semibold text-green-900",children:b.estimatedCredits})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-green-700",children:"Credit Range:"}),e.jsxs("span",{className:"font-semibold text-green-900",children:[b.creditRange.min," - ",b.creditRange.max]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-green-700",children:"Estimated Hours:"}),e.jsxs("span",{className:"font-semibold text-green-900",children:[b.estimatedHours,"h"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-green-700",children:"Complexity:"}),e.jsx("span",{className:"font-semibold text-green-900 capitalize",children:b.analysisFactors.scopeSize})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-green-700",children:"Confidence:"}),e.jsx("span",{className:"font-semibold text-green-900 capitalize",children:b.confidence})]}),b.reasoning&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-green-200",children:[e.jsx("span",{className:"text-green-700 font-medium",children:"Reasoning:"}),e.jsx("p",{className:"text-green-800 mt-1",children:b.reasoning})]})]})]})]}),P=()=>e.jsxs("div",{className:"space-y-4",children:[i&&e.jsxs("div",{className:"bg-yellow-50 border border-yellow-200 rounded-lg p-4 flex items-center gap-3",style:{borderRadius:"var(--radius-md)"},children:[e.jsx(fe,{className:"animate-spin text-yellow-600",size:24}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-yellow-900",children:"Estimating tickets..."}),e.jsx("p",{className:"text-sm text-yellow-700",children:"This may take several minutes"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-green-50 border border-green-200 rounded-lg p-4",style:{borderRadius:"var(--radius-md)"},children:[e.jsx("h3",{className:"font-semibold text-green-900 mb-3",children:"Estimation Complete!"}),e.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-900",children:c.total}),e.jsx("div",{className:"text-sm text-green-700",children:"Total"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:c.success}),e.jsx("div",{className:"text-sm text-green-700",children:"Estimated"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:c.skipped||0}),e.jsx("div",{className:"text-sm text-green-700",children:"Skipped"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-red-600",children:c.failed}),e.jsx("div",{className:"text-sm text-green-700",children:"Failed"})]})]})]}),c.errors&&c.errors.length>0&&e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",style:{borderRadius:"var(--radius-md)"},children:[e.jsx("h4",{className:"font-semibold text-red-900 mb-2",children:"Errors:"}),e.jsx("div",{className:"space-y-1 max-h-60 overflow-y-auto",children:c.errors.map((U,V)=>e.jsxs("div",{className:"text-sm text-red-800",children:[e.jsxs("span",{className:"font-mono text-xs",children:[U.ticketId.slice(0,8),"..."]}),": ",U.error]},V))})]}),e.jsx("button",{onClick:()=>{o("menu"),u(null),h(null)},className:"w-full bg-primary text-primary-foreground py-3 px-4 roun
76ded font-semibold hover:bg-primary/90",style:{borderRadius:"var(--radius-sm)"},children:"Back to Menu"})]})]});return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("button",{onClick:t,className:"flex items-center gap-2 text-muted-foreground hover:text-foreground mb-4 transition-colors",children:[e.jsx(dt,{size:20}),e.jsx("span",{children:"Back"})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:"Ticket Estimator"}),e.jsxs("p",{className:"text-muted-foreground",children:[a==="menu"&&"Choose an estimation method",a==="single"&&"Estimate a single ticket",a==="bulk-confirm"&&"Confirm bulk estimation",a==="outstanding-confirm"&&"Confirm outstanding tickets estimation",(a==="bulk"||a==="outstanding")&&"Running batch estimation"]})]}),x&&e.jsxs("div",{className:"mb-4 bg-red-50 border border-red-200 rounded-lg p-4",style:{borderRadius:"var(--radius-md)"},children:[e.jsx("p",{className:"text-red-900 font-semibold",children:"Error"}),e.jsx("p",{className:"text-red-700 text-sm",children:x})]}),a==="menu"&&$(),a==="single"&&q(),a==="bulk-confirm"&&D(),a==="outstanding-confirm"&&L(),(a==="bulk"||a==="outstanding")&&P()]})]})}function hT({onLogoClick:t,onBack:s,onDollarOrders:n}){return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:t}),e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("button",{onClick:s,className:"mb-4 flex items-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(dt,{style:{width:"20px",height:"20px"}}),e.jsx("span",{children:"Back to Admin"})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:"Sales"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage orders and customers"})]}),e.jsx("div",{className:"space-y-3",children:e.jsxs(st.button,{onClick:n,className:"w-full bg-card border border-border rounded-lg p-4 flex items-center gap-3 hover:bg-accent transition-colors",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},whileTap:{scale:.98},children:[e.jsx("div",{className:"flex-shrink-0 bg-primary/10 rounded-lg flex items-center justify-center",style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)"},children:e.jsx(yu,{className:"text-primary",style:{width:"24px",height:"24px"}})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"$1 Orders"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"View all $1 Fix for The Shopify Problem purchases"})]})]})})]})]})}const jn="https://us-central1-bucky-app-355a3.cloudfunctions.net";function fT(){const[t,s]=l.useState(!1),[n,r]=l.useState(null),{user:a}=pt(),o=async()=>{if(!a)throw new Error("User not authenticated");return await a.getIdToken()};return{loading:t,error:n,getSubscriptions:async g=>{try{s(!0),r(null);const y=await o(),j=await fetch(`${jn}/getRechargeSubscriptions`,{method:"POST",headers:{Authorization:`Bearer ${y}`,"Content-Type":"application/json"},body:JSON.stringify({email:g})});if(!j.ok)throw new Error("Failed to fetch subscriptions");const v=await j.json();return{subscriptions:v.subscriptions||[],customer:v.customer||null}}catch(y){return console.error("Failed to fetch subscriptions:",y),r(y.message),{subscriptions:[],customer:null}}finally{s(!1)}},getAllSubscriptions:async()=>{try{s(!0),r(null);const g=await o(),y=await fetch(`${jn}/getAllRechargeSubscriptions`,{method:"POST",headers:{Authorization:`Bearer ${g}`,"Content-Type":"application/json"}});if(!y.ok)throw new Error("Failed to fetch all subscriptions");return(await y.json()).subscriptions||[]}catch(g){return console.error("Failed to fetch all subscriptions:",g),r(g.message),[]}finally{s(!1)}},getAllOnetimes:async()=>{try{s(!0),r(null);const g=await o(),y=await fetch(`${jn}/getAllRechargeOnetimes`,{method:"POST",headers:{Authorization:`Bearer ${g}`,"Content-Type":"application/json"}});if(!y.ok)throw new Error("Failed to fetch all one-times");return(await y.json()).onetimes||[]}catch(g){return console.error("Failed to fetch all one-times:",g),r(g.message),[]}finally{s(!1)}},getSubscription:async g=>{var y;try{s(!0),r(null);const j=await o(),v=await fetch(`${jn}/getRechargeSubscription`,{method:"POST",headers:{Authorization:`Bearer ${j}`,"Content-Type":"application/json"},body:JSON.stringify({data:{subscriptionId:g}})});if(!v.ok)throw new Error("Failed to fetch subscription");return((y=(await v.json()).result)==null?void 0:y.subscription)||null}catch(j){return console.error("Failed to fetch subscription:",j),r(j.message),null}finally{s(!1)}},updateSubscription:async(g,y)=>{try{s(!0),r(null);const j=await o();if(!(await fetch(`${jn}/updateRechargeSubscription`,{method:"POST",headers:{Authorization:`Bearer ${j}`,"Content-Type":"application/json"},body:JSON.stringify({data:{subscriptionId:g,updates:y}})})).ok)throw new Error("Failed to update subscription");return!0}catch(j){return console.error("Failed to update subscription:",j),r(j.message),!1}finally{s(!1)}},cancelSubscription:async(g,y)=>{try{s(!0),r(null);const j=await o();if(!(await fetch(`${jn}/cancelRechargeSubscription`,{method:"POST",headers:{Authorization:`Bearer ${j}`,"Content-Type":"application/json"},body:JSON.stringify({data:{subscriptionId:g,cancellationReason:y}})})).ok)throw new Error("Failed to cancel subscription");return!0}catch(j){return console.error("Failed to cancel subscription:",j),r(j.message),!1}finally{s(!1)}},skipCharge:async(g,y)=>{try{s(!0),r(null);const j=await o();if(!(await fetch(`${jn}/skipRechargeCharge`,{method:"POST",headers:{Authorization:`Bearer ${j}`,"Content-Type":"application/json"},body:JSON.stringify({data:{subscriptionId:g,date:y}})})).ok)throw new Error("Failed to skip charge");return!0}catch(j){return console.error("Failed to skip charge:",j),r(j.message),!1}finally{s(!1)}},getCustomer:async(g,y)=>{var j;try{s(!0),r(null);const v=await o(),T=await fetch(`${jn}/getRechargeCustomer`,{method:"POST",headers:{Authorization:`Bearer ${v}`,"Content-Type":"application/json"},body:JSON.stringify({data:{email:g,customerId:y}})});if(!T.ok)throw new Error("Failed to fetch customer");return((j=(await T.json()).result)==null?void 0:j.customer)||null}catch(v){return console.error("Failed to fetch customer:",v),r(v.message),null}finally{s(!1)}},getOrders:async(g,y)=>{var j;try{s(!0),r(null);const v=await o(),T=await fetch(`${jn}/getRechargeOrders`,{method:"POST",headers:{Authorization:`Bearer ${v}`,"Content-Type":"application/json"},body:JSON.stringify({data:{customerId:g,limit:y}})});if(!T.ok)throw new Error("Failed to fetch orders");return((j=(await T.json()).result)==null?void 0:j.orders)||[]}catch(v){return console.error("Failed to fetch orders:",v),r(v.message),[]}finally{s(!1)}},createOneTimeCharge:async(g,y,j,v=1)=>{var T,k;try{s(!0),r(null);const w=await o(),I=await fetch(`${jn}/createRechargeOneTimeCharge`,{method:"POST",headers:{Authorization:`Bearer ${w}`,"Content-Type":"application/json"},body:JSON.stringify({data:{addressId:g,externalProductId:y,externalVariantId:j,quantity:v}})});if(!I.ok)throw new Error("Failed to create one-time charge");return((k=(T=(await I.json()).result)==null?void 0:T.onetime)==null?void 0:k.id)||null}catch(w){return console.error("Failed to create one-time charge:",w),r(w.message),null}finally{s(!1)}}}}function gT({onLogoClick:t,onBack:s}){const{user:n}=pt(),{getAllSubscriptions:r,getAllOnetimes:a,createOneTimeCharge:o,loading:i,error:d}=fT(),[m,p]=l.useState([]),[c,u]=l.useState(!0),[x,h]=l.useState(null),[b,f]=l.useState(new Map);l.useEffect(()=>{n&&g()},[n]);const g=async()=>{try{u(!0);const[w,I]=await Promise.all([r().catch(S=>(console.error("Failed to fetch subscriptions:",S),[])),a().catch(S=>(console.error("Failed to fetch one-times:",S),[]))]),E=w.filter(S=>{var O,R,z;return((O=S==null?void 0:S.product_title)==null?void 0:O.toLowerCase().includes("$1 fix"))||((R=S==null?void 0:S.product_title)==null?void 0:R.toLowerCase().includes("1 fix"))||((z=S==null?void 0:S.product_title)==null?void 0:z.toLowerCase().includes("shopify problem"))||parseFloat((S==null?void 0:S.price)||0)===1}).map(S=>({id:(S==null?void 0:S.id)||0,customerId:(S==null?void 0:S.customer_id)||0,addressId:(S==null?void 0:S.address_id)||0,customerEmail:(S==null?void 0:S.customer_email)||"N/A",customerFirstName:(S==null?void 0:S.customer_first_name)||"N/A",customerLastName:(S==null?void 0:S.customer_last_name)||"",productTitle:(S==null?void 0:S.product_title)||"Unknown Product",status:(S==null?void 0:S.status)||"UNKNOWN",createdAt:(S==null?void 0:S.created_at)||"",nextChargeDate:(S==null?void 0:S.next_charge_scheduled_at)||"",price:(S==null?void 0:S.price)||0,quantity:(S==null?void 0:S.quantity)||1}));p(E);const C=I.filter(S=>{var O;return((O=S==null?void 0:S.external_product_id)==null?void 0:O.ecommerce)==="8529863475371"}),N=new Map;
76C.forEach(S=>{N.set((S==null?void 0:S.customer_id)||0,(S==null?void 0:S.id)||0)}),f(N)}catch(w){console.error("Failed to fetch $1 subscriptions:",w)}finally{u(!1)}},y=w=>{if(!w)return"N/A";const I=new Date(w);return isNaN(I.getTime())?"Invalid Date":I.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})},j=w=>{const I={ACTIVE:"text-green-600 bg-green-50",CANCELLED:"text-red-600 bg-red-50",EXPIRED:"text-gray-600 bg-gray-50",DEFAULT:"text-yellow-600 bg-yellow-50"};return I[w.toUpperCase()]||I.DEFAULT},v="8529863475371",T="45650263933099",k=async(w,I,A)=>{h(I);try{const E=await o(w,v,T,1);E?(f(C=>new Map(C).set(I,E)),ce.success(`Site Audit ordered successfully for ${A}!`)):ce.error("Failed to order Site Audit. Please try again.")}catch{ce.error("An error occurred while ordering the audit.")}finally{h(null)}};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Oa,{richColors:!0,position:"top-center"}),e.jsx(Xe,{onLogoClick:t}),e.jsxs("div",{className:"max-w-4xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("button",{onClick:s,className:"mb-4 flex items-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(dt,{style:{width:"20px",height:"20px"}}),e.jsx("span",{children:"Back to Sales"})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:"$1 Recharge Subscriptions"}),e.jsx("p",{className:"text-muted-foreground",children:'Customers with "$1 Fix for The Shopify Problem" subscriptions'})]}),(c||i)&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}),d&&!c&&e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-red-700",children:[e.jsx("p",{className:"font-semibold",children:"Error loading subscriptions"}),e.jsx("p",{className:"text-sm",children:d})]}),!c&&!i&&!d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 text-sm text-muted-foreground",children:["Found ",m.length," subscription",m.length!==1?"s":""]}),m.length===0?e.jsxs("div",{className:"bg-card border border-border rounded-lg p-8 text-center",children:[e.jsx(Om,{className:"mx-auto mb-4 text-muted-foreground",style:{width:"48px",height:"48px"}}),e.jsx("p",{className:"text-foreground font-semibold mb-2",children:"No subscriptions found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No customers have subscribed to the $1 Fix product yet."})]}):e.jsx("div",{className:"space-y-3",children:m.map(w=>e.jsxs(st.div,{className:"bg-card border border-border rounded-lg p-3",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.3},children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 bg-primary/10 rounded-lg flex items-center justify-center",style:{width:"32px",height:"32px",borderRadius:"var(--radius-sm)"},children:e.jsx(ei,{className:"text-primary",style:{width:"16px",height:"16px"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"font-semibold text-sm text-foreground truncate",children:[w.customerFirstName," ",w.customerLastName]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Tn,{style:{width:"12px",height:"12px"}}),e.jsx("span",{className:"truncate",children:w.customerEmail})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("span",{className:"text-sm font-semibold text-foreground",children:["$",w.price]}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${j(w.status)}`,children:w.status})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-2 pt-2 border-t border-border",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ss,{style:{width:"12px",height:"12px"}}),e.jsx("span",{children:y(w.createdAt)})]}),w.status.toUpperCase()==="ACTIVE"&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(yt,{style:{width:"12px",height:"12px"}}),e.jsx("span",{children:y(w.nextChargeDate)})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Om,{style:{width:"12px",height:"12px"}}),e.jsxs("span",{children:["Ã",w.quantity]})]})]}),b.has(w.customerId)?e.jsxs("div",{className:"flex items-center gap-1 px-3 py-1 rounded text-xs font-medium border",style:{borderRadius:"var(--radius-sm)",backgroundColor:"#f0fdf4",color:"#15803d",borderColor:"#bbf7d0"},children:[e.jsx(Id,{style:{width:"14px",height:"14px"}}),e.jsxs("span",{children:["Order #",b.get(w.customerId)]})]}):e.jsx("button",{onClick:()=>k(w.addressId,w.customerId,`${w.customerFirstName} ${w.customerLastName}`),disabled:x===w.customerId,className:"flex items-center gap-1 px-3 py-1 bg-primary text-primary-foreground rounded text-xs font-medium hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",style:{borderRadius:"var(--radius-sm)"},children:x===w.customerId?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-3 w-3 border-b-2 border-white"}),e.jsx("span",{children:"Processing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Id,{style:{width:"14px",height:"14px"}}),e.jsx("span",{children:"Order Audit"})]})})]})]},w.id))})]})]})]})}function bT({email:t,onExit:s}){return e.jsxs("div",{className:"fixed top-0 left-0 right-0 bg-orange-500 text-white px-4 py-2 flex items-center justify-between shadow-lg z-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ul,{className:"w-5 h-5"}),e.jsxs("span",{className:"text-sm font-medium",children:["Impersonating: ",e.jsx("span",{className:"font-bold",children:t})]})]}),e.jsxs("button",{onClick:s,className:"flex items-center gap-1 px-3 py-1 bg-white text-orange-500 rounded-md text-sm font-medium hover:bg-orange-50 transition-colors",children:[e.jsx(mt,{className:"w-4 h-4"}),"Exit Impersonation"]})]})}function yT({onClose:t,onImpersonate:s}){const[n,r]=l.useState(""),a=o=>{o.preventDefault(),n.trim()&&(s(n.trim()),t())};return e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-card rounded-lg shadow-xl max-w-md w-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ul,{className:"w-5 h-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Impersonate Customer"})]}),e.jsx("button",{onClick:t,className:"p-1 hover:bg-accent rounded transition-colors",children:e.jsx(mt,{className:"w-5 h-5 text-muted-foreground"})})]}),e.jsxs("form",{onSubmit:a,className:"p-6",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-foreground mb-2",children:"Customer Email"}),e.jsx("input",{type:"email",id:"email",value:n,onChange:o=>r(o.target.value),placeholder:"[email protected]",className:"w-full px-4 py-2 border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary bg-background text-foreground",autoF
76ocus:!0,required:!0}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Enter the email address of the customer you want to impersonate. You'll see their projects and data."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{type:"button",onClick:t,className:"flex-1 px-4 py-2 border border-border rounded-lg text-foreground hover:bg-accent transition-colors",children:"Cancel"}),e.jsx("button",{type:"submit",className:"flex-1 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors font-medium",children:"Start Impersonating"})]})]})]})})}const jT="https://us-central1-bucky-app-355a3.cloudfunctions.net";function Cb(t){const{token:s,user:n}=pt(),[r,a]=l.useState([]),[o,i]=l.useState(!0),[d,m]=l.useState(null),[p,c]=l.useState(!1),[u,x]=l.useState(0);l.useEffect(()=>{if(!t){a([]),i(!1);return}i(!0),m(null);const y=Re(ge,"cycles"),j=Ge(y,Ve("projectId","==",t),Ve("status","==","pending_approval"),Nt("createdAt","desc")),v=qt(j,T=>{const k=T.docs.map(w=>({id:w.id,...w.data()}));console.log(`[usePendingApprovals] Real-time update: ${k.length} pending cycles`),a(k),i(!1),m(null)},T=>{console.error("[usePendingApprovals] Subscription error:",T),m(T.message||"Failed to load pending approvals"),i(!1)});return()=>{console.log("[usePendingApprovals] Unsubscribing from real-time updates"),v()}},[t,u]);const h=l.useCallback(()=>{x(y=>y+1)},[]),b=l.useCallback(async(y,j)=>{if(!y)return m("Invalid cycleId"),!1;const v=j==="approve"?"approve":"defer";if(!(n!=null&&n.email))return m(`You must be logged in to ${v} cycles`),!1;c(!0),m(null);try{const T=await fetch(`${jT}/${j}Cycle`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({cycleId:y,[`${j}dBy`]:n.uid||n.email})});if(!T.ok){const w=await T.json();throw new Error(w.error||`Failed to ${v} cycle`)}const k=await T.json();if(k.success)return!0;throw new Error(k.error||"Unknown error")}catch(T){return console.error(`[usePendingApprovals] ${v.charAt(0).toUpperCase()+v.slice(1)} error:`,T),m(T.message||`Failed to ${v} cycle`),!1}finally{c(!1)}},[n,s]),f=l.useCallback(async y=>b(y,"approve"),[b]),g=l.useCallback(async y=>b(y,"defer"),[b]);return{cycles:r,loading:o,error:d,pendingCount:r.length,refresh:h,approveCycle:f,deferCycle:g,approving:p}}function vT({projectId:t,projectName:s,onBack:n}){const{cycles:r,loading:a,error:o,pendingCount:i,refresh:d,approveCycle:m,approving:p}=Cb(t);return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background border-b border-border",children:e.jsx("div",{className:"max-w-2xl mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[n&&e.jsx(ke,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0",children:e.jsx(dt,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-foreground",style:{fontSize:"18px",fontWeight:"var(--font-weight-semibold)"},children:"Pending Approvals"}),s&&e.jsx("p",{className:"text-muted-foreground",style:{fontSize:"13px"},children:s})]})]}),e.jsxs(ke,{variant:"outline",size:"sm",onClick:d,disabled:a,className:"gap-2",children:[e.jsx(yt,{className:`w-4 h-4 ${a?"animate-spin":""}`}),"Refresh"]})]})})}),e.jsxs("div",{className:"max-w-2xl mx-auto px-4 py-6",children:[a&&r.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx("div",{className:"animate-spin mb-3",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"Loading",className:"w-12 h-12"})}),e.jsx("p",{style:{fontSize:"14px"},children:"Loading pending approvals..."})]}),o&&e.jsx("div",{className:"bg-destructive/10 border border-destructive/30 rounded-lg p-4 mb-6",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(gs,{className:"w-5 h-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-destructive",style:{fontSize:"14px",fontWeight:"var(--font-weight-medium)"},children:"Failed to load approvals"}),e.jsx("p",{className:"text-destructive/80 mt-1",style:{fontSize:"13px"},children:o}),e.jsx(ke,{variant:"outline",size:"sm",onClick:d,className:"mt-3",children:"Try Again"})]})]})}),!a&&!o&&r.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center mb-4",children:e.jsx(fu,{className:"w-8 h-8 text-green-600 dark:text-green-400"})}),e.jsx("h2",{className:"text-foreground mb-2",style:{fontSize:"16px",fontWeight:"var(--font-weight-semibold)"},children:"All caught up!"}),e.jsx("p",{className:"text-muted-foreground max-w-sm",style:{fontSize:"14px"}
76,children:"You don't have any pending approvals right now. When new work is proposed, it will appear here."})]}),r.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2 mb-2",children:e.jsxs("span",{className:"text-muted-foreground",style:{fontSize:"14px"},children:[i," pending approval",i!==1?"s":""]})}),r.map(c=>e.jsx(Lg,{cycle:c,onApprove:m,disabled:p},c.id))]})]})]})}const wT="https://us-central1-bucky-app-355a3.cloudfunctions.net",NT=()=>{const{cycleId:t}=zl(),s=Qo(),[n,r]=l.useState("minting"),[a,o]=l.useState("");l.useEffect(()=>{if(!t){r("error"),o("Missing cycle ID.");return}let d=!1;return(async()=>{try{const m=await fetch(`${wT}/mintCycleApprovalToken`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cycleId:t})}),p=await m.json();if(d)return;if(!m.ok){if(p.state==="not_found"||m.status===404){r("not_found");return}throw new Error(p.error||"Failed to open approval")}if(p.state==="ready"&&p.token&&p.tokenId){window.location.replace(`/approve-email?token=${encodeURIComponent(p.token)}&tokenId=${encodeURIComponent(p.tokenId)}`);return}p.state==="already_approved"?r("already_approved"):p.state==="cancelled"?r("cancelled"):p.state==="deferred"?r("deferred"):r("error")}catch(m){if(d)return;r("error"),o(m.message||"Something went wrong loading this approval.")}})(),()=>{d=!0}},[t]);const i=(d,m,p)=>e.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#f5f5f5",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"},children:e.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"16px",boxShadow:"0 4px 6px rgba(0, 0, 0, 0.1)",maxWidth:"440px",width:"100%",padding:"40px 32px",textAlign:"center"},children:[e.jsx("div",{style:{fontSize:"40px",marginBottom:"16px"},children:d}),e.jsx("h1",{style:{color:"#1f2937",margin:"0 0 8px",fontSize:"20px",fontWeight:700},children:m}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",lineHeight:1.5,margin:"0 0 24px"},children:p}),e.jsx("button",{onClick:()=>s("/",{replace:!0}),style:{padding:"10px 20px",backgroundColor:"#3b82f6",color:"#ffffff",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:600,cursor:"pointer"},children:"Go to Bucky"})]})});return n==="minting"?e.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#f5f5f5",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"},children:e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{width:"40px",height:"40px",border:"3px solid #e5e7eb",borderTopColor:"#22c55e",borderRadius:"50%",animation:"spin 1s linear infinite",margin:"0 auto 16px"}}),e.jsx("p",{style:{color:"#6b7280",margin:0},children:"Opening approvalâ¦"}),e.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})}):n==="already_approved"?i("â","Already Approved","This work has already been approved. No further action is needed."):n==="cancelled"?i("â","Approval Cancelled","This approval was cancelled and is no longer open for review."):n==="deferred"?i("â¸","Approval Deferred","This approval was deferred. Your Sunbowl team member will reach out to reopen it."):n==="not_found"?i("â ","Approval Not Found","We couldn't find this approval. The link may be outdated."):i("â ","Unable to Open Approval",a||"Something went wrong. Please contact your Sunbowl team member.")};function kT({count:t,projectName:s,onClick:n}){return t===0?null:e.jsxs("div",{className:"fixed top-0 left-0 right-0 bg-primary text-primary-foreground px-4 py-2 flex items-center justify-between shadow-lg z-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dn,{className:"w-5 h-5"}),e.jsxs("span",{className:"text-sm font-medium",children:["You have"," ",e.jsxs("span",{className:"font-bold",children:[t," pending approval",t!==1?"s":""]}),s&&e.jsxs("span",{className:"opacity-80",children:[" for ",s]})]})]}),e.jsxs("button",{onClick:n,className:"flex items-center gap-1 px-3 py-1 bg-primary-foreground text-primary rounded-md text-sm font-medium hover:opacity-90 transition-opacity",children:["Review",e.jsx(Rt,{className:"w-4 h-4"})]})]})}const Tr="https://us-central1-bucky-app-355a3.cloudfunctions.net";function Pc(t,s){const n=t/100;return`${{cad:"CA$",usd:"$",eur:"â¬"}[(s||"usd").toLowerCase()]||"$"}${n.toFixed(0)}`}const ST={visa:"Visa",mastercard:"Mastercard",amex:"Amex",discover:"Discover",diners:"Diners",jcb:"JCB",unionpay:"UnionPay"};function CT(t){return ST[t==null?void 0:t.toLowerCase()]||(t?t[0].toUpperCase()+t.slice(1):"Card")}function TT(t){try{const s=new URL(t),n=s.hostname.replace(/^www\./,"");if(n==="loom.com"){const r=s.pathname.match(/^\/(?:share|embed)\/([a-zA-Z0-9]+)/);if(r)return`https://www.loom.com/embed/${r[1]}`}if(n==="youtu.be"){const r=s.pathname.replace(/^\//,"");if(r)return`https://www.youtube.com/embed/${r}`}if(n==="youtube.com"||n==="m.youtube.com"){const r=s.searchParams.get("v");if(r)return`https://www.youtube.com/embed/${r}`;const a=s.pathname.match(/^\/shorts\/([a-zA-Z0-9_-]+)/);if(a)return`https://www.youtube.com/embed/${a[1]}`}
76if(n==="vimeo.com"){const r=s.pathname.split("/").filter(Boolean)[0];if(r&&/^\d+$/.test(r))return`https://player.vimeo.com/video/${r}`}return null}catch{return null}}function AT(){var O,R,z,D;const[t]=Zo(),s=t.get("token"),n=t.get("tokenId"),r=t.get("payment"),a=t.get("sessionId"),[o,i]=l.useState("loading"),[d,m]=l.useState(""),[p,c]=l.useState(null),[u,x]=l.useState(!1),[h,b]=l.useState(!1),[f,g]=l.useState(!1),[y,j]=l.useState(null);l.useEffect(()=>{if(!s||!n){i("error"),m("Invalid approval link. Please check your email and try again.");return}if(r==="success"&&a){E();return}v()},[s,n]);const v=async()=>{var L,$;if(!(!s||!n)){i("loading");try{const q=await fetch(`${Tr}/getApprovalDetails`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n})}),P=await q.json();if(!q.ok){if((L=P.error)!=null&&L.includes("already been used")){i("already_approved");return}if(($=P.error)!=null&&$.includes("expired")){i("expired");return}throw new Error("Failed to load details")}c(P),b(!!P.rushApplied),i("ready")}catch{i("error"),m("Something went wrong. Please try again.")}}},T=async()=>{if(!(!s||!n)){i("confirming");try{const L=await fetch(`${Tr}/approveViaEmailToken`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n})}),$=await L.json();if(!L.ok){if($.alreadyApproved){i("already_approved");return}if($.expired){i("expired");return}throw new Error($.error||"Approval failed")}j({ticketNumber:$.cycle.ticketNumber,ticketTitle:$.cycle.ticketTitle,projectName:$.cycle.projectName,creditAmount:$.cycle.creditAmount}),i("success")}catch(L){i("error"),m(L.message||"Something went wrong. Please try again.")}}},k=async L=>{if(!(!s||!n||f)){g(!0),m("");try{const $=await fetch(`${Tr}/setApprovalRush`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n,rush:L})}),q=await $.json();if(!$.ok)throw new Error(q.error||"Could not update rush");b(L),await v()}catch($){m($.message||"Could not update rush. Please try again.")}finally{g(!1)}}},w=async(L,$)=>{if(!(!s||!n)){i("transferring");try{const q=await fetch(`${Tr}/transferAndApprove`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n,sourceProjectId:L,transferCount:$})}),P=await q.json();if(!q.ok){if(P.alreadyApproved){i("already_approved");return}throw new Error(P.error||"Transfer failed")}j({ticketNumber:P.cycle.ticketNumber,ticketTitle:P.cycle.ticketTitle,projectName:P.cycle.projectName,creditAmount:P.cycle.creditAmount}),i("success")}catch(q){i("error"),m(q.message||"Transfer failed. Please try again.")}}},I=async()=>{if(!(!s||!n||!(p!=null&&p.cardOnFile))){m(""),i("confirming");try{const L=await fetch(`${Tr}/chargeCardOnFileAndApprove`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n,authorized:!0})}),$=await L.json();if(!L.ok){if($.alreadyApproved){i("already_approved");return}if($.expired){i("expired");return}if($.requiresCheckout){i("ready"),m($.error||"Couldn't charge the card on file. Please use a different card.");return}throw new Error($.error||"Charge failed")}j({ticketNumber:$.cycle.ticketNumber,ticketTitle:$.cycle.ticketTitle,projectName:$.cycle.projectName,creditAmount:$.cycle.creditAmount}),i("success")}catch(L){i("ready"),m(L.message||"Could not charge the card on file. Please try again.")}}},A=async()=>{if(!s||!n||!p)return;const L=p.creditBalance.required-p.creditBalance.currentProject.available,$=Math.max(L,1);try{const q=await fetch(`${Tr}/createCreditCheckout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n,creditCount:$})}),P=await q.json();if(!q.ok)throw new Error(P.error||"Failed to start checkout");window.location.href=P.checkoutUrl}catch(q){m(q.message||"Failed to start checkout")}},E=async()=>{if(!(!s||!n||!a)){i("confirming");try{const L=await fetch(`${Tr}/verifyPaymentAndApprove`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n,sessionId:a})}),$=await L.json();if(!L.ok){if($.alreadyApproved){i("already_approved");return}throw new Error($.error||"Payment verification failed")}j({ticketNumber:$.cycle.ticketNumber,ticketTitle:$.cycle.ticketTitle,projectName:$.cycle.projectName,creditAmount:$.cycle.creditAmount}),i("success")}catch(L){i("error"),m(L.message||"Payment verification failed.")}}},C=p&&(p.planSummary||((O=p.planChanges)==null?void 0:O.length)>0),N=p&&!p.creditBalance.sufficient,S=p?p.creditBalance.required-p.creditBalance.currentProject.available:0;return e.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#f5f5f5",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"},children:e.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"16px",boxShadow:"0 4px 6px rgba(0, 0, 0, 0.1)",maxWidth:"520px",width:"100%",overflow:"hidden"},children:[e.jsxs("div",{style:{textAlign:"center",padding:"40px 32px 24px"},children:[e.jsx("img",{src:"https://cdn.shopify.com/s/files/1/0359/6033/files/icon_933c651a-afcc-4ec2-9889-741d130c5a59.png?v=1764225392",alt:"Sunbowl",width:50,height:50,style:{display:"block",margin:"0 auto 16px"}}),e.jsx("h1",{style:{color:"#1f2937",margin:"0 0 4px",fontSize:"22px",fontWeight:700},children:o==="success"?"Approved!":o==="already_approved"?"Already Approved":"Work Approval"}),e.jsx("p",{style:{color:"#6b7280",margin:0,fontSize:"14px"},children:(p==null?void 0:p.projectName)||"Sunbowl Systems"})]}),e.jsxs("div",{style:{padding:"0 32px 32px"},children:[o==="loading"&&e.jsxs("div",{style:{textAlign:"center",padding:"20px 0"},children:[e.jsx("div",{style:{width:"40px",height:"40px",border:"3px solid #e5e7eb",borderTopColor:"#22c55e",borderRadius:"50%",animation:"spin 1s linear infinite",margin:"0 auto 16px"}}),e.jsx("p",{style:{color:"#6b7280",margin:0},children:"Loading details..."}),e.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),o==="ready"&&p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"16px",marginBottom:"16
76px"},children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 4px"},children:"Ticket"}),e.jsxs("p",{style:{color:"#1f2937",fontSize:"16px",fontWeight:600,margin:"0 0 12px"},children:[p.ticketNumber," â ",p.ticketTitle]}),e.jsxs("div",{style:{display:"flex",gap:"24px"},children:[e.jsxs("div",{children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 2px"},children:"Credits"}),e.jsx("p",{style:{color:"#1f2937",fontSize:"20px",fontWeight:700,margin:0},children:p.creditAmount})]}),p.estimatedTimeline&&e.jsxs("div",{children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 2px"},children:"Timeline"}),e.jsx("p",{style:{color:"#1f2937",fontSize:"16px",fontWeight:600,margin:0},children:p.estimatedTimeline})]})]})]}),p.videoReviewUrl&&(()=>{const L=TT(p.videoReviewUrl);return e.jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"16px",marginBottom:"16px"},children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 10px",fontWeight:600},children:"Video Walkthrough"}),L?e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:"56.25%",height:0,borderRadius:"8px",overflow:"hidden",backgroundColor:"#000"},children:e.jsx("iframe",{src:L,title:"Video review",allow:"fullscreen; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",border:0}})}):ll(p.videoReviewUrl)?e.jsx(Co,{src:p.videoReviewUrl}):e.jsx("a",{href:p.videoReviewUrl,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-block",color:"#3b82f6",fontSize:"14px",fontWeight:500,textDecoration:"none",wordBreak:"break-all"},children:"Watch video â"})]})})(),((R=p.qaBefore)==null?void 0:R[0])&&((z=p.qaAfter)==null?void 0:z[0])&&e.jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"16px",marginBottom:"16px"},children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 4px",fontWeight:600},children:"Before & After"}),e.jsx("p",{style:{color:"#9ca3af",fontSize:"12px",margin:"0 0 10px"},children:"Drag the handle to compare the page before and after our changes."}),e.jsx("div",{style:{borderRadius:"8px",overflow:"hidden",border:"1px solid #e5e7eb",backgroundColor:"#fff"},children:e.jsx(Pl,{beforeImageUrl:p.qaBefore[0],afterImageUrl:p.qaAfter[0],ticketId:p.ticketNumber,savedAlignmentOffset:p.savedAlignmentOffset,readOnly:!0})})]}),p.jobContent&&e.jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"16px",marginBottom:"16px"},children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 8px",fontWeight:600},children:"The Work"}),e.jsx("p",{style:{color:"#374151",fontSize:"14px",lineHeight:1.6,margin:0,whiteSpace:"pre-wrap"},children:p.jobContent})]}),C&&e.jsxs("div",{style:{backgroundColor:"#f0fdf4",borderRadius:"12px",border:"1px solid #bbf7d0",padding:"16px",marginBottom:"16px"},children:[e.jsx("p",{style:{color:"#166534",fontSize:"13px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 8px",fontWeight:600},children:"What We'll Do"}),p.planSummary&&e.jsx("p",{style:{color:"#374151",fontSize:"14px",lineHeight:1.6,margin:"0 0 10px"},children:p.planSummary}),((D=p.planChanges)==null?void 0:D.length)>0&&e.jsx("div",{style:{margin:0,padding:0},children:p.planChanges.map((L,$)=>e.jsx("div",{style:{padding:"6px 0 6px 12px",borderLeft:"3px solid #22c55e",marginBottom:"6px",color:"#374151",fontSize:"14px",lineHeight:1.5},children:L.description},$))})]}),e.jsxs("div",{style:{backgroundColor:p.creditBalance.sufficient?"#f0fdf4":"#fef3c7",borderRadius:"12px",border:`1px solid ${p.creditBalance.sufficient?"#bbf7d0":"#fde68a"}`,padding:"16px",marginBottom:"16px"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsxs("div",{children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 2px"},children:"Available Credits"}),e.jsx("p",{style:{color:p.creditBalance.sufficient?"#166534":"#92400e",fontSize:"24px",fontWeight:700,margin:0},children:p.creditBalance.currentProject.available})]}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 2px"},children:"Required"}),e.jsx("p",{style:{color:"#1f2937",fontSize:"24px",fontWeight:700,margin:0},children:p.creditBalance.required})]})]}),!p.creditBalance.sufficient&&e.jsxs("p",{style:{color:"#92400e",fontSize:"13px",margin:"8px 0 0",fontWeight:500},children:["You need ",S," more credit",S!==1?"s":""," to approve this work."]})]}),e.jsxs("label",{style:{display:"flex",alignItems:"flex-start",ga
76p:"10px",backgroundColor:h?"#fff7ed":"#f9fafb",border:`1px solid ${h?"#fed7aa":"#e5e7eb"}`,borderRadius:"12px",padding:"14px 16px",marginBottom:"16px",cursor:f?"wait":"pointer",opacity:f?.7:1},children:[e.jsx("input",{type:"checkbox",checked:h,disabled:f,onChange:L=>k(L.target.checked),style:{marginTop:"2px",flexShrink:0,width:"16px",height:"16px",accentColor:"#f97316"}}),e.jsxs("div",{children:[e.jsx("p",{style:{color:"#9a3412",fontSize:"14px",fontWeight:600,margin:"0 0 2px"},children:"â¡ Rush this order"}),e.jsxs("p",{style:{color:"#6b7280",fontSize:"13px",lineHeight:1.5,margin:0},children:["Bumps your work to the front of the queue for ",e.jsx("strong",{children:"+1 credit"}),"."]})]})]}),p.creditBalance.sufficient&&e.jsx("button",{onClick:T,style:{display:"block",width:"100%",padding:"14px",backgroundColor:"#22c55e",color:"#ffffff",border:"none",borderRadius:"8px",fontSize:"16px",fontWeight:600,cursor:"pointer",marginBottom:"8px"},children:"Confirm Approval"}),N&&p.creditBalance.siblingProjects.length>0&&e.jsxs("div",{style:{marginBottom:"12px"},children:[e.jsx("p",{style:{color:"#374151",fontSize:"14px",fontWeight:500,margin:"0 0 8px"},children:"Transfer credits from another project:"}),p.creditBalance.siblingProjects.map(L=>{const $=Math.min(L.available,S);return e.jsxs("button",{onClick:()=>w(L.projectId,$),style:{display:"block",width:"100%",padding:"12px 16px",backgroundColor:"#eff6ff",color:"#1d4ed8",border:"1px solid #bfdbfe",borderRadius:"8px",fontSize:"14px",fontWeight:500,cursor:"pointer",textAlign:"left",marginBottom:"6px"},children:["Transfer ",$," credit",$!==1?"s":""," from ",L.projectName,e.jsxs("span",{style:{color:"#6b7280",fontSize:"12px",display:"block",marginTop:"2px"},children:["(",L.available," available)"]})]},L.projectId)})]}),N&&p.cardOnFile&&e.jsxs("div",{style:{marginBottom:"12px"},children:[e.jsxs("div",{style:{backgroundColor:"#eff6ff",border:"1px solid #bfdbfe",borderRadius:"8px",padding:"12px 14px",marginBottom:"10px",fontSize:"13px",color:"#1e3a8a"},children:[e.jsxs("p",{style:{margin:"0 0 4px",fontWeight:600},children:["Card on file: ",CT(p.cardOnFile.brand)," â¢â¢",p.cardOnFile.last4]}),p.pricing&&e.jsxs("p",{style:{margin:0,color:"#1e40af"},children:[Pc(p.pricing.creditPriceCents,p.pricing.currency),"/credit ·"," ",e.jsxs("strong",{children:[Pc(p.pricing.creditPriceCents*S,p.pricing.currency)," ",p.pricing.currency.toUpperCase()]})," ","for ",S," credit",S!==1?"s":""]})]}),e.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"8px",padding:"10px",backgroundColor:"#f9fafb",borderRadius:"8px",border:"1px solid #e5e7eb",marginBottom:"10px",cursor:"pointer",fontSize:"13px",color:"#374151",lineHeight:1.4},children:[e.jsx("input",{type:"checkbox",checked:u,onChange:L=>x(L.target.checked),style:{marginTop:"2px",flexShrink:0}}),e.jsxs("span",{children:["I'm authorized to approve this charge on behalf of"," ",e.jsx("strong",{children:p.projectName||"this project"}),"."]})]}),e.jsx("button",{onClick:I,disabled:!u,style:{display:"block",width:"100%",padding:"14px",backgroundColor:u?"#22c55e":"#9ca3af",color:"#ffffff",border:"none",borderRadius:"8px",fontSize:"16px",fontWeight:600,cursor:u?"pointer":"not-allowed"},children:p.pricing?`Charge ${Pc(p.pricing.creditPriceCents*S,p.pricing.currency)} ${p.pricing.currency.toUpperCase()} & Approve`:"Charge Card on File & Approve"})]}),N&&e.jsx("button",{onClick:A,style:{display:"block",width:"100%",padding:p.cardOnFile?"10px":"14px",backgroundColor:p.cardOnFile?"transparent":"#3b82f6",color:p.cardOnFile?"#3b82f6":"#ffffff",border:p.cardOnFile?"1px solid #bfdbfe":"none",borderRadius:"8px",fontSize:p.cardOnFile?"14px":"16px",fontWeight:p.cardOnFile?500:600,cursor:"pointer"},children:p.cardOnFile?"Use a different card â":`Buy ${S} Credit${S!==1?"s":""} & Approve`}),d&&e.jsx("p",{style:{color:"#dc2626",fontSize:"13px",margin:"12px 0 0",textAlign:"center"},children:d})]}),(o==="confirming"||o==="transferring")&&e.jsxs("div",{style:{textAlign:"center",padding:"20px 0"},children:[e.jsx("div",{style:{width:"40px",height:"40px",border:"3px solid #e5e7eb",borderTopColor:"#22c55e",borderRadius:"50%",animation:"spin 1s linear infinite",margin:"0 auto 16px"}}),e.jsx("p",{style:{color:"#6b7280",margin:0}
76,children:o==="transferring"?"Transferring credits and approving...":"Processing approval..."}),e.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),o==="success"&&y&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{width:"56px",height:"56px",backgroundColor:"#dcfce7",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:"28px"},children:"â"}),e.jsxs("p",{style:{color:"#374151",fontSize:"15px",lineHeight:1.6,margin:"0 0 16px"},children:[e.jsx("strong",{children:y.ticketNumber})," â ",y.ticketTitle]}),e.jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"8px",padding:"16px",marginBottom:"16px"},children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"13px",margin:"0 0 4px"},children:"Credits on hold"}),e.jsx("p",{style:{color:"#1f2937",fontSize:"24px",fontWeight:700,margin:0},children:y.creditAmount})]}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"Work will begin shortly. You can close this page."})]}),o==="already_approved"&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{width:"56px",height:"56px",backgroundColor:"#dbeafe",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:"28px"},children:"â"}),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:"This work has already been approved."}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"No further action needed. You can close this page."})]}),o==="expired"&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{width:"56px",height:"56px",backgroundColor:"#fef3c7",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:"28px"},children:"â²"}),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:"This approval link has expired."}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"Please contact your Sunbowl team member for a new approval link."})]}),o==="error"&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{width:"56px",height:"56px",backgroundColor:"#fee2e2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:"28px"},children:"â"}),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:d||"Something went wrong."}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"Please contact your Sunbowl team member for assistance."})]})]}),e.jsx("div",{style:{textAlign:"center",padding:"16px 32px",borderTop:"1px solid #e5e7eb"},children:e.jsxs("p",{style:{color:"#9ca3af",margin:0,fontSize:"12px"},children:["Sunbowl Systems · ",e.jsx("a",{href:"https://sunbowl.ca",style:{color:"#3b82f6",textDecoration:"none"},children:"sunbowl.ca"})]})})]})})}const yi="https://us-central1-bucky-app-355a3.cloudfunctions.net",Ka={backgroundColor:"#f9fafb",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"16px",marginBottom:"16px"},Qa={color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 8px",fontWeight:600};function lr(t,s=!0){return{display:"block",width:s?"100%":"auto",padding:"14px",backgroundColor:t,color:"#ffffff",border:"none",borderRadius:"8px",fontSize:"16px",fontWeight:600,cursor:"pointer",marginBottom:"10px"}}function ET(){var C,N,S,O,R,z;const[t]=Zo(),s=t.get("token"),n=t.get("tokenId"),r=t.get("action"),[a,o]=l.useState("loading"),[i,d]=l.useState(""),[m,p]=l.useState(null),[c,u]=l.useState(null),[x,h]=l.useState(""),[b,f]=l.useState(""),[g,y]=l.useState("");l.useEffect(()=>{if(!s||!n){o("error"),d("Invalid review link. Please check your email and try again.");return}j()},[s,n]);const j=async()=>{o("loading");try{const D=await fetch(`${yi}/getTicketReviewDetails`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n})}),L=await D.json();if(!D.ok){if(L.expired){o("expired");return}throw new Error("Failed to load review")}p(L),u({launchUrl:L.launchUrl,scheduleUrl:L.scheduleUrl}),r==="schedule"?o("scheduleForm"):L.alreadyApproved?o("publish"):o("ready")}catch{o("error"),d("Something went wrong. Please try again.")}},v=async()=>{o("approving");try{const D=await fetch(`${yi}/approveTicketReview`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n})}),L=await D.json();if(!D.ok){if(L.expired){o("expired");return}throw new Error(L.error||"Approval failed")}u(L.publish),o("publish")}catch(D){o("error"),d(D.message||"Something went wrong. Please try again.")}},T=()=>
76{c!=null&&c.launchUrl&&(window.location.href=c.launchUrl)},k=async()=>{if(b){o("scheduling");try{const D=await fetch(`${yi}/scheduleTicketLaunch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n,launchAt:new Date(b).toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone})}),L=await D.json();if(!D.ok){if(L.expired){o("expired");return}throw new Error(L.error||"Could not schedule the launch")}y(L.whenLabel||new Date(b).toLocaleString()),o("scheduled")}catch(D){o("scheduleForm"),d(D.message||"Could not schedule the launch. Please try again.")}}},w=async()=>{o("changesSubmitting");try{const D=await fetch(`${yi}/requestTicketChanges`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n,note:x.trim()})}),L=await D.json();if(!D.ok){if(L.expired){o("expired");return}throw new Error(L.error||"Could not submit your request")}o("changesDone")}catch(D){o("changesForm"),d(D.message||"Could not submit your request. Please try again.")}},I=a==="publish"?"Approved â publish your changes":a==="scheduled"?"Launch scheduled":a==="changesDone"?"Changes requested":"Review your work",A=D=>e.jsxs("div",{style:{textAlign:"center",padding:"20px 0"},children:[e.jsx("div",{style:{width:"40px",height:"40px",border:"3px solid #e5e7eb",borderTopColor:"#22c55e",borderRadius:"50%",animation:"spin 1s linear infinite",margin:"0 auto 16px"}}),e.jsx("p",{style:{color:"#6b7280",margin:0},children:D}),e.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),E=(D,L)=>e.jsx("div",{style:{width:"56px",height:"56px",backgroundColor:D,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:"28px"},children:L});return e.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#f5f5f5",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"},children:e.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"16px",boxShadow:"0 4px 6px rgba(0, 0, 0, 0.1)",maxWidth:"560px",width:"100%",overflow:"hidden"},children:[e.jsxs("div",{style:{textAlign:"center",padding:"40px 32px 24px"},children:[e.jsx("img",{src:"https://cdn.shopify.com/s/files/1/0359/6033/files/icon_933c651a-afcc-4ec2-9889-741d130c5a59.png?v=1764225392",alt:"Sunbowl",width:50,height:50,style:{display:"block",margin:"0 auto 16px"}}),e.jsx("h1",{style:{color:"#1f2937",margin:"0 0 4px",fontSize:"22px",fontWeight:700},children:I}),e.jsx("p",{style:{color:"#6b7280",margin:0,fontSize:"14px"},children:(m==null?void 0:m.projectName)||"Sunbowl Systems"})]}),e.jsxs("div",{style:{padding:"0 32px 32px"},children:[a==="loading"&&A("Loading your work..."),a==="approving"&&A("Approving..."),a==="scheduling"&&A("Scheduling your launch..."),a==="changesSubmitting"&&A("Sending your request..."),a==="ready"&&m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:Ka,children:[e.jsx("p",{style:Qa,children:"Ticket"}),e.jsxs("p",{style:{color:"#1f2937",fontSize:"16px",fontWeight:600,margin:0},children:[m.ticketNumber," â ",m.ticketTitle]})]}),m.videoReviewUrl&&(()=>{const D=uf(m.videoReviewUrl);return e.jsxs("div",{style:Ka,children:[e.jsx("p",{style:Qa,children:"Video walkthrough"}),D?e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:"56.25%",height:0,borderRadius:"8px",overflow:"hidden",backgroundColor:"#000"},children:e.jsx("iframe",{src:D,title:"Video review",allow:"fullscreen; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",border:0}})}):ll(m.videoReviewUrl)?e.jsx(Co,{src:m.videoReviewUrl}):e.jsx("a",{href:m.videoReviewUrl,target:"_blank",rel:"noopener noreferrer",style:{color:"#3b82f6",fontSize:"14px",fontWeight:500,textDecoration:"none",wordBreak:"break-all"},children:"Watch video â"})]})})(),m.storeUrl&&e.jsx("a",{href:m.storeUrl,target:"_blank",rel:"noopener noreferrer",style:{...lr("#111827"),display:"flex",alignItems:"center",justifyContent:"center",gap:"8px",textDecoration:"none",boxSizing:"border-box"},children:"View it in your store â"}),m.summary&&e.jsxs("div",{style:Ka,children:[e.jsx("p",{style:Qa,children:"What we did"}),e.jsx("p",{style:{color:"#374151",fontSize:"14px",lineHeight:1.6,margin:0,whiteSpace:"pre-wrap"},children:m.summary})]}),(C=m.qaBefore)!=null&&C[0]&&((N=m.qaAfter)!=null&&N[0])?e.jsxs("div",{style:Ka,children:[e.jsx("p",{style:Qa,children:"Before & after"}),e.jsx("p",{style:{color:"#9ca3af",fontSize:"12px",margin:"0 0 10px"},children:"Drag the handle to compare the page before and after our changes."}),e.jsx("div",{style:{borderRadius:"8px",overflow:"hidden",border:"1px solid #e5e7eb",backgroundColor:"#fff"},children:e.jsx(Pl,{beforeImageUrl:m.qaBefore[0],afterImageUrl:m.qaAfter[0],ticketId:m.ticketNumber,savedAlignmentOffset:m.savedAlignmentOffset,readOnly:!0})})]}):(((S=m.qaBefore)==null?void 0:S.length)>0||((O=m.qaAfter)==null?void 0:O.length)>0)&&e.jsxs("div",{style:Ka,children:[e.jsx("p",{style:Qa,children:"Before & after"}),e.jsxs("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap"},children:[(R=m.qaBefore)==null?void 0:R.map((D,L)=>e.jsxs("a",{href:D,target:"_blank",rel:"noopener noreferrer",style:{flex:"1 1 45%"},children:[e.jsx("span",{style:{display:"block",color:"#9ca3af",fontSize:"11px",marginBottom:"4px"},children:"Before"}),e.jsx("img",{src:D,alt:"Before",style:{width:"100%",borderRadius:"8px",border:"1px solid #e5e7eb"}})]},`b${L}`)),(z=m.qaAfter)==null?void 0:z.map((D,L)=>e.jsxs("a",{href:D,target:"_blank",rel:"noopener noreferrer",style:{flex:"1 1 45%"},children:[e.jsx("span",{style:{display:"block",color:"#9ca3af",fontSize:"11px",marginBottom:"4px"},children:"After"}),e.jsx("img",{src:D,alt:"After",style:{width:"100%",borderRadius:"8px",border:"1px solid #e5e7eb"}})]},`a${L}`))]})]}),e.jsx("button",{onClick:v,style:lr("#22c55e"),children:"Approve this work"}),e.jsx("button",{onClick:()=>{d(""),o("changesForm")},style:{...lr("transparent"),color:"#6b7280",border:"1px solid #e5e7eb",marginBottom:0},children:"Request changes"})]}),a==="publish"&&c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{textAlign:"center",marginBottom:"8px"},children:[E("#dcfce7","â"),e.jsxs("p",{style:{color:"#374151",fontSize:"15px",lineHeight:1.6,margin:"0 0 4px"},children:[e.jsx("strong",{children:m==null?void 0:m.ticketNumber})," â ",m==null?void 0:m.ticketTitle]}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:"0 0 20px"},children:"Approved. The last step is publishing it to your live store."})]}),e.jsx("button",{onClick:T,style:lr("#22c55e"),children:"Put it live now"}),e.jsx("button",{onClick:()=>{d(""),o("scheduleForm")},style:lr("#3b82f6"),children:"Schedule a launch time"}),e.jsx("p",{style:{color:"#9ca3af",fontSize:"13px",textAlign:"center",margin:"4px 0 0"}
76,children:'"Put it live now" opens the Launch page in your Sunbowl app.'})]}),a==="scheduleForm"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{color:"#374151",fontSize:"15px",lineHeight:1.6,margin:"0 0 16px"},children:"Pick a date and time and the Sunbowl team will publish your changes for you."}),e.jsx("input",{type:"datetime-local",value:b,min:new Date().toISOString().slice(0,16),onChange:D=>f(D.target.value),style:{width:"100%",boxSizing:"border-box",padding:"12px",fontSize:"15px",borderRadius:"8px",border:"1px solid #d1d5db",marginBottom:"12px"}}),e.jsx("button",{onClick:k,disabled:!b,style:{...lr(b?"#3b82f6":"#9ca3af"),cursor:b?"pointer":"not-allowed"},children:"Schedule launch"}),i&&e.jsx("p",{style:{color:"#dc2626",fontSize:"13px",margin:"4px 0 0",textAlign:"center"},children:i})]}),a==="scheduled"&&e.jsxs("div",{style:{textAlign:"center"},children:[E("#dbeafe","ð"),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:"Your launch is scheduled for"}),e.jsx("p",{style:{color:"#1f2937",fontSize:"18px",fontWeight:700,margin:"0 0 12px"},children:g}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"No further action needed â we'll handle the launch. You can close this page."})]}),a==="changesForm"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{color:"#374151",fontSize:"15px",lineHeight:1.6,margin:"0 0 12px"},children:"Tell us what needs changing and we'll get right on it."}),e.jsx("textarea",{value:x,onChange:D=>h(D.target.value),rows:5,placeholder:"What would you like changed?",style:{width:"100%",boxSizing:"border-box",padding:"12px",fontSize:"15px",borderRadius:"8px",border:"1px solid #d1d5db",marginBottom:"12px",resize:"vertical"}}),e.jsx("button",{onClick:w,disabled:!x.trim(),style:{...lr(x.trim()?"#f59e0b":"#9ca3af"),cursor:x.trim()?"pointer":"not-allowed"},children:"Send request"}),e.jsx("button",{onClick:()=>o("ready"),style:{...lr("transparent"),color:"#6b7280",border:"1px solid #e5e7eb",marginBottom:0},children:"Back"}),i&&e.jsx("p",{style:{color:"#dc2626",fontSize:"13px",margin:"8px 0 0",textAlign:"center"},children:i})]}),a==="changesDone"&&e.jsxs("div",{style:{textAlign:"center"},children:[E("#fef3c7","â"),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:"Thanks â we've received your request."}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"Your Sunbowl team will make the changes and send it back for review. You can close this page."})]}),a==="expired"&&e.jsxs("div",{style:{textAlign:"center"},children:[E("#fef3c7","â²"),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:"This review link has expired."}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"Please contact your Sunbowl team member for a new link."})]}),a==="error"&&e.jsxs("div",{style:{textAlign:"center"},children:[E("#fee2e2","â"),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:i||"Something went wrong."}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"Please contact your Sunbowl team member for assistance."})]})]}),e.jsx("div",{style:{textAlign:"center",padding:"16px 32px",borderTop:"1px solid #e5e7eb"},children:e.jsxs("p",{style:{color:"#9ca3af",margin:0,fontSize:"12px"},children:["Sunbowl Systems · ",e.jsx("a",{href:"https://sunbowl.ca",style:{color:"#3b82f6",textDecoration:"none"},children:"sunbowl.ca"})]})})]})})}const Gp="https://us-central1-bucky-app-355a3.cloudfunctions.net",IT={backgroundColor:"#f9fafb",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"16px",marginBottom:"16px"},RT={color:"#6b7280",fontSize:"12px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 8px",fontWeight:600},Lc={color:"#374151",fontSize:"15px",fontWeight:600,margin:"0 0 8px",lineHeight:1.5},zc={width:"100%",boxSizing:"border-box",padding:"12px",fontSize:"15px",borderRadius:"8px",border:"1px solid #d1d5db",marginBottom:"20px",resize:"vertical"};function DT(t){return{display:"block",width:"100%",padding:"14px",backgroundColor:t,color:"#ffffff",border:"none",borderRadius:"8px",fontSize:"16px",fontWeight:600,cursor:"pointer",marginBottom:"10px"}}function MT(){const[t]=Zo(),s=t.get("token"),n=t.get("tokenId"),[r,a]=l.useState("loading"),[o,i]=l.useState(""),[d,m]=l.useState(null),[p,
76c]=l.useState(""),[u,x]=l.useState(""),[h,b]=l.useState(""),[f,g]=l.useState(!1);l.useEffect(()=>{if(!s||!n){a("error"),i("Invalid questionnaire link. Please check your email and try again.");return}y()},[s,n]);const y=async()=>{a("loading");try{const I=await fetch(`${Gp}/getQaQuestionnaireDetails`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n})}),A=await I.json();if(!I.ok){if(A.expired){a("expired");return}throw new Error("Failed to load questionnaire")}m(A),A.answers?(c(A.answers.expectations||""),x(A.answers.expectedDeliverable||""),b(A.answers.watchOut||"")):A.draft&&(c(A.draft.expectations||""),x(A.draft.expectedDeliverable||""),b(A.draft.watchOut||""),g(!0)),a("ready")}catch{a("error"),i("Something went wrong. Please try again.")}},j=!!(p.trim()||u.trim()||h.trim()),v=async()=>{if(j){i(""),a("submitting");try{const I=await fetch(`${Gp}/submitQaQuestionnaire`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s,tokenId:n,expectations:p.trim(),expectedDeliverable:u.trim(),watchOut:h.trim(),aiAssisted:f})}),A=await I.json();if(!I.ok){if(A.expired){a("expired");return}throw new Error(A.error||"Could not submit your answers")}a("done")}catch(I){a("ready"),i(I.message||"Could not submit your answers. Please try again.")}}},T=r==="done"?"Thank you!":"A quick questionnaire",k=I=>e.jsxs("div",{style:{textAlign:"center",padding:"20px 0"},children:[e.jsx("div",{style:{width:"40px",height:"40px",border:"3px solid #e5e7eb",borderTopColor:"#22c55e",borderRadius:"50%",animation:"spin 1s linear infinite",margin:"0 auto 16px"}}),e.jsx("p",{style:{color:"#6b7280",margin:0},children:I}),e.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),w=(I,A)=>e.jsx("div",{style:{width:"56px",height:"56px",backgroundColor:I,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",fontSize:"28px"},children:A});return e.jsx("div",{style:{minHeight:"100vh",backgroundColor:"#f5f5f5",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"},children:e.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"16px",boxShadow:"0 4px 6px rgba(0, 0, 0, 0.1)",maxWidth:"560px",width:"100%",overflow:"hidden"},children:[e.jsxs("div",{style:{textAlign:"center",padding:"40px 32px 24px"},children:[e.jsx("img",{src:"https://cdn.shopify.com/s/files/1/0359/6033/files/icon_933c651a-afcc-4ec2-9889-741d130c5a59.png?v=1764225392",alt:"Sunbowl",width:50,height:50,style:{display:"block",margin:"0 auto 16px"}}),e.jsx("h1",{style:{color:"#1f2937",margin:"0 0 4px",fontSize:"22px",fontWeight:700},children:T}),e.jsx("p",{style:{color:"#6b7280",margin:0,fontSize:"14px"},children:(d==null?void 0:d.projectName)||"Sunbowl Systems"})]}),e.jsxs("div",{style:{padding:"0 32px 32px"},children:[r==="loading"&&k("Loading your questionnaire..."),r==="submitting"&&k("Sending your answers..."),r==="ready"&&d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:IT,children:[e.jsx("p",{style:RT,children:"Ticket"}),e.jsxs("p",{style:{color:"#1f2937",fontSize:"16px",fontWeight:600,margin:0},children:[d.ticketNumber," â ",d.ticketTitle]})]}),e.jsxs("p",{style:{color:"#374151",fontSize:"15px",lineHeight:1.6,margin:"0 0 20px"},children:["Hi ",d.recipientName,", I'm Liz â I handle QA at Sunbowl. A few quick answers help me make sure the team delivers exactly what you're picturing."]}),e.jsx("p",{style:Lc,children:"Can you give me a brief description of your expectations?"}),e.jsx("textarea",{value:p,onChange:I=>c(I.target.value),rows:4,placeholder:"In your own words, what should this accomplish?",style:zc}),e.jsx("p",{style:Lc,children:"What are you expecting to see when this is delivered to you for review?"}),e.jsx("textarea",{value:u,onChange:I=>x(I.target.value),rows:4,placeholder:"What does âdone rightâ look like to you?",style:zc}),e.jsx("p",{style:Lc,children:"Is there anything specific I should keep my eye out for?"}),e.jsx("textarea",{value:h,onChange:I=>b(I.target.value),rows:4,placeholder:"Pet peeves, edge cases, must-nots â anything at all.",style:zc}),e.jsx("button",{onClick:v,disabled:!j,style:{...DT(j?"#22c55e":"#9ca3af"),cursor:j?"pointer":"not-allowed"},children:d.alreadySubmitted?"Update my answers":"Send to Liz"}),o&&e.jsx("p",{style:{color:"#dc2626",fontSize:"13px",margin:"4px 0 0",textAlign:"center"},children:o})]}),r==="done"&&e.jsxs("div",{style:{textAlign:"center"},children:[w("#dcfce7","ð¯"),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:"Thanks â Liz and the team have exactly what they need."}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"We'll be in touch when your work is ready to review. You can close this page."})]}),r==="expired"&&e.jsxs("div",{style:{textAlign:"center"},children:[w("#fef3c7","â²"),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:"This questionnaire link has expired."}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"Please contact your Sunbowl team member for a new link."})]}),r==="error"&&e.jsxs("div",{style:{textAlign:"center"},children:[w("#fee2e2","â"),e.jsx("p",{style:{color:"#374151",fontSize:"15px",margin:"0 0 8px"},children:o||"Something went wrong."}),e.jsx("p",{style:{color:"#6b7280",fontSize:"14px",margin:0},children:"Please contact your Sunbowl team member for assistance."})]})]}),e.jsx("div",{style:{textAlign:"center",padding:"16px 32px",borderTop:"1px solid #e5e7eb"},children:e.jsxs("p",{style:{color:"#9ca3af",margin:0,fontSize:"12px"},children:["Sunbowl Systems · ",e.jsx("a",{href:"https://sunbowl.ca",style:{color:"#3b82f6",textDecoration:"none"},children:"sunbowl.ca"})]})})]})})}function PT(t){const[s,n]=l.useState(null),[r,a]=l.useState(!0),[o,i]=l.useState(null),[d,m]=l.useState(!1),[p,c]=l.useState(!1),u=l.useRef(null),x=l.useRef(new Map),h=l.useRef(null),b=l.useRef(null),f=l.useRef(new Map),g=l.useCallback(async k=>{var w,I;
76try{a(!0),i(null),console.log("ð
Fetching capacity schedule from Firebase...",k);const A=await re("getCapacitySchedule",k,void 0,{timeoutMs:3e5});console.log("â
Capacity schedule received:",A),console.log("ð Total scheduled tickets:",((w=A.scheduledTickets)==null?void 0:w.length)||0),console.log("ð Total projects:",((I=A.schedule)==null?void 0:I.length)||0);const E={schedule:A.schedule.map(N=>({...N,startDate:new Date(N.startDate),endDate:new Date(N.endDate),launchDate:N.launchDate?new Date(N.launchDate):void 0})),nextAvailableDate:new Date(A.nextAvailableDate),totalCapacityDays:A.totalCapacityDays,totalCapacityHours:A.totalCapacityHours,upcomingLaunches:A.upcomingLaunches.map(N=>({...N,launchDate:new Date(N.launchDate),bufferStart:new Date(N.bufferStart),bufferEnd:new Date(N.bufferEnd)})),scheduledTickets:(A.scheduledTickets||[]).map(N=>({...N,date:new Date(N.date),promisedDate:N.promisedDate?new Date(N.promisedDate):void 0})),blackoutDates:A.blackoutDates||[]};n(E);const C=new Map;E.schedule.forEach(N=>C.set(N.projectId,N.order)),f.current=C,a(!1)}catch(A){console.error("â Error fetching capacity schedule:",A),i(A.message||"Failed to fetch capacity schedule"),a(!1)}},[]),y=l.useCallback(async k=>{const w=k.map((I,A)=>({projectId:I,priority:A+1})).filter(I=>f.current.get(I.projectId)!==I.priority);if(w.length===0){console.log("â
No priority changes to save"),b.current=null;return}console.log(`ð Saving ${w.length} changed projects (of ${k.length} total)`),m(!0);try{await re("updateProjectOrder",{projects:w});for(const I of w)f.current.set(I.projectId,I.priority);console.log("â
Project order saved to Notion")}catch(I){console.error("â Failed to save project order:",I),i("Failed to save project order.")}finally{m(!1),b.current=null}},[]),j=l.useCallback(k=>{if(!s)return;const w=new Set(k),I=k.map(E=>s.schedule.find(C=>C.projectId===E)).filter(E=>E!==void 0).map((E,C)=>({...E,order:C+1})),A=s.schedule.filter(E=>!w.has(E.projectId));n({...s,schedule:[...I,...A]}),b.current=k,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{b.current&&y(b.current)},5e3)},[s,y]),v=l.useCallback(async()=>{const k=x.current;if(k.size===0)return;const w=Array.from(k.entries()).map(([I,A])=>({ticketId:I,sortOrder:A}));x.current=new Map,console.log(`ð Saving ${w.length} ticket sort order(s)`),c(!0);try{await re("updateTicketOrder",{tickets:w}),console.log("â
Ticket order saved")}catch(I){console.error("â Failed to save ticket order:",I),i("Failed to save ticket order.")}finally{c(!1)}},[]),T=l.useCallback(k=>{if(k.length===0)return;const w=new Map(k.map(I=>[I.ticketNotionId,I.sortOrder]));n(I=>I&&{...I,scheduledTickets:I.scheduledTickets.map(A=>w.has(A.ticketNotionId)?{...A,capacitySortOrder:w.get(A.ticketNotionId)}:A)});for(const I of k)x.current.set(I.ticketNotionId,I.sortOrder);u.current&&clearTimeout(u.current),u.current=setTimeout(()=>v(),5e3)},[v]);return l.useEffect(()=>()=>{h.current&&clearTimeout(h.current),b.current&&y(b.current),u.current&&clearTimeout(u.current),x.current.size>0&&v()},[y,v]),l.useEffect(()=>{g(t)},[g]),{schedule:s,loading:r,error:o,refetch:g,updateProjectOrder:j,updateTicketOrder:T,isSaving:d,savingTicketOrder:p}}const LT=["queued","investigating","plan_ready","approved","approved_manual","awaiting_approval","implementing","verifying","failed","rejected","deferred"];function zT(t){const[s,n]=l.useState([]),[r,a]=l.useState([]),[o,i]=l.useState([]),[d,m]=l.useState(0),[p,c]=l.useState(!0),[u,x]=l.useState(null),h=l.useRef(!0);l.useEffect(()=>()=>{h.current=!1},[]),l.useEffect(()=>{const v=Ge(Re(ge,"ticketPipeline"),Ve("status","in",LT),Nt("createdAt","desc"),Tt(200));return qt(v,k=>{if(!h.current)return;const w=k.docs.map(I=>({id:I.id,...I.data()}));n(w),c(!1)},k=>{console.error("[useTicketPipeline] Snapshot error:",k),h.current&&(x(k.message),c(!1))})},[]),l.useEffect(()=>{(async()=>{try{const T=Ge(Re(ge,"ticketPipeline"),Ve("status","==","complete")),k=await G0(T);h.current&&m(k.data().count)}catch(T){console.warn("[useTicketPipeline] Complete count error:",T)}})()},[s]);const b=l.useCallback(async()=>{try{const v=Ge(Re(ge,"ticketPipeline"),Ve("status","==","complete"),Nt("createdAt","desc"),Tt(50)),k=(await Ze(v)).docs.map(w=>({id:w.id,...w.data()}));h.current&&a(k)}catch(v){console.error("[useTicketPipeline] Load completed error:",v)}},[]),f=l.useCallback(async()=>{try{const v=Ge(Re(ge,"ticketPipeline"),Ve("status","==","cancelled"),Nt("createdAt","desc"),Tt(100)),k=(await Ze(v)).docs.map(w=>({id:w.id,...w.data()}));h.current&&i(k)}catch(v){console.error("[useTicketPipeline] Load cancelled error:",v)}},[]),g=l.useCallback(async(v,T)=>{if(!t)throw new Error("Not authenticated");x(null);try{await re("updatePipelineTicket",{pipelineId:v,...T})}catch(k){const w=k.message||"Failed to update pipeline";throw h.current&&x(w),k}},[t]),y=l.useCallback(async v=>{if(!t)throw new Error("Not authenticated");x(null);try{await re("cancelTicketInPipeline",{pipelineId:v})}catch(T){const k=T.message||"Failed to cancel ticket";throw h.current&&x(k),T}},[t]),j=l.useCallback(()=>{},[]);return{pipelines:s,completedPipelines:r,completeCount:d,loading:p,error:u,updatePipeline:g,cancelTicket:y,loadCompleted:b,cancelledPipelines:o,loadCancelled:f,refresh:j}}function OT({project:t,tickets:s,onClose:n,onTicketClick:r,onViewInDatabase:a}){if(!t)return null;const o=c=>c.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",year:"numeric"}),i=(c,u)=>c.getMonth()===u.getMonth()?`${c.toLocaleDateString("en-US",{month:"short"})} ${c.getDate()}-${u.getDate()}`:`${o(c)} - ${o(u)}`;s.reduce((c,u)=>{const x="Active";return c[x]||(c[x]=[]),c[x].push(u),c},{});const d=Array.from(new Map(s.map(c=>[c.ticketId,c])).values()),m=d.reduce((c,u)=>c+u.estimatedMinutes/60,0);console.log("Project:",t.projectName),console.log("Project estimated minutes:",t.estimatedMinutes),console.log("Project estimated hours:",t.estimatedMinutes/60),console.log("Tickets found:",d.length),console.log("Tickets total hours:",m),console.log("Tickets:",d.map(c=>({id:c.ticketId,name:c.ticketName,minutes:c.estimatedMinutes,hours:c.estimatedMinutes/60})));const p={"In Progress":"bg-green-500","In Review":"bg-orange-500","Client Approval":"bg-cyan-500",Backlog:"bg-gray-500",Blocked:"bg-red-500",Deferred:"bg-yellow-500"};return e.jsx(hs,{children:e.jsx(st.div,{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.75)"},initial:{opacity:0}
76,animate:{opacity:1},exit:{opacity:0},onClick:n,children:e.jsxs(st.div,{className:"bg-card border border-border rounded-xl shadow-2xl max-w-4xl w-full flex flex-col overflow-hidden",style:{height:"90vh",maxHeight:"800px"},initial:{scale:.9,y:20},animate:{scale:1,y:0},exit:{scale:.9,y:20},onClick:c=>c.stopPropagation(),children:[e.jsx("div",{className:"bg-primary text-primary-foreground px-6 py-4 rounded-t-xl flex-shrink-0",children:e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-8 h-8 rounded-full bg-primary-foreground text-primary text-sm font-bold",children:t.order}),e.jsx("h2",{className:"text-2xl font-bold",children:t.projectName})]}),(t.clientName||t.department)&&e.jsx("div",{className:"text-lg opacity-90 ml-11",children:t.clientName&&t.department?`${t.clientName} ⢠${t.department}`:t.clientName||t.department})]}),e.jsx("button",{className:"text-primary-foreground/80 hover:text-primary-foreground p-2 hover:bg-primary-foreground/10 rounded-lg transition-colors",onClick:n,children:e.jsx(mt,{className:"w-6 h-6"})})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-accent border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ss,{className:"w-5 h-5 text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Schedule"})]}),e.jsx("p",{className:"text-sm font-semibold text-foreground",children:i(t.startDate,t.endDate)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[t.estimatedDays," day",t.estimatedDays!==1?"s":""]})]}),e.jsxs("div",{className:"bg-accent border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ms,{className:"w-5 h-5 text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Project Estimate"})]}),e.jsxs("p",{className:"text-sm font-semibold text-foreground",children:[(t.estimatedMinutes/60).toFixed(1),"h"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"All active tickets"})]}),e.jsxs("div",{className:"bg-accent border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-lg",children:"ð«"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Tickets"})]}),e.jsx("p",{className:"text-sm font-semibold text-foreground",children:d.length}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[m.toFixed(1),"h (Backlog + In Progress)"]})]}),e.jsxs("div",{className:"bg-accent border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ms,{className:"w-5 h-5 text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Time Left to Complete"})]}),e.jsxs("p",{className:"text-sm font-semibold text-foreground",children:[m.toFixed(1),"h"]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(m/6).toFixed(1)," days @ 6h/day"]})]}),t.launchDate&&e.jsxs("div",{className:"bg-accent border border-orange-500/50 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ul,{className:"w-5 h-5 text-orange-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Launch"})]}),e.jsx("p",{className:"text-sm font-semibold text-foreground",children:o(t.launchDate)}),e.jsx("p",{className:"text-xs text-orange-500 mt-1",children:"Launch window"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-block px-3 py-1 rounded-full text-xs font-medium text-white ${p[t.status]||"bg-gray-500"}`,children:t.status}),t.isInLaunchBuffer&&e.jsx("span",{className:"inline-block px-3 py-1 rounded-full text-xs font-medium bg-orange-500 text-white",children:"ð In Launch Buffer"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx("span",{children:"ð«"}),"Tickets (",d.length,")"]}),d.length===0?e.jsx("div",{className:"bg-accent border border-border rounded-lg p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No tickets found for this project"})}):e.jsx("div",{className:"space-y-2",children:d.map(c=>{const u=s.filter(h=>h.ticketId===c.ticketId),x=Array.from(new Set(u.map(h=>h.date.toLocaleDateString("en-US",{month:"short",day:"numeric"})))).join(", ");return e.jsx("button",{className:"w-full text-left bg-card border border-border rounded-lg p-4 hover:bg-accent transition-colors cursor-pointer",onClick:()=>r==null?void 0:r(c),children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-sm font-semibold text-primary",children:c.ticketId}),e.jsx("h4",{className:"font-medium text-foreground",children:c.ticketName})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ms,{className:"w-4 h-4"}),(c.estimatedMinutes/60).toFixed(1),"h"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ss,{className:"w-4 h-4"}),x]})]})]}),e.jsx(Rt,{className:"w-5 h-5 text-muted-foreground shrink-0 mt-1"})]})},c.ticketId)})})]})]}),e.jsxs("div",{className:"flex-shrink-0 bg-accent border-t border-border px-6 py-4 rounded-b-xl flex gap-3 justify-between",children:[e.jsxs("button",{className:"px-4 py-2 bg-card border border-border hover:bg-accent text-foreground font-medium rounded-lg transition-colors flex items-center gap-2 text-sm",onClick:c=>{c.stopPropagation(),a&&(a(t.projectId),n())},children:[e.jsx(Da,{className:"w-4 h-4"}),"View Project"]}),e.jsx("button",{className:"px-6 py-2 bg-card border border-border hover:bg-accent text-foreground font-semibold rounded-lg transition-colors",onClick:n,children:"Close"})]})]})})})}function Xt(t){const{collectionName:s,orderByField:n="updatedAt",orderDirection:r="desc",maxResults:a,statusField:o,activeStatuses:i}=t,[d,m]=l.useState([]),[p,c]=l.useState(!0),[u,x]=l.useState(null),h=l.useRef(!0);l.useEffect(()=>{h.current=!0;const y=[];o&&i&&i.length>0&&y.push(Ve(o,"in",i.slice(0,30))),y.push(Nt(n,r)),a&&y.push(Tt(a));const j=Ge(Re(ge,s),...y),v=qt(j,T=>
76{if(!h.current)return;const k=T.docs.map(w=>({id:w.id,...w.data()}));m(k),c(!1)},T=>{h.current&&(console.error(`[useFirestoreTable] ${s} error:`,T),x(T.message),c(!1))});return()=>{h.current=!1,v()}},[s,n,r,a,o,i==null?void 0:i.join(",")]);const b=l.useCallback(async(y,j)=>{const v=ut(ge,s,y);await er(v,{...j,updatedAt:ss()})},[s]),f=l.useCallback(async y=>(await Ma(Re(ge,s),{...y,createdAt:ss(),updatedAt:ss()})).id,[s]),g=l.useCallback(async y=>{await ru(ut(ge,s,y))},[s]);return{rows:d,loading:p,error:u,updateRow:b,createRow:f,deleteRow:g}}function Oc(t){if(!t)return"";const s=Number(t);return Number.isFinite(s)?(s/100).toFixed(2):""}function De({title:t}){return e.jsx("div",{className:"border-t border-border",style:{paddingTop:12,marginTop:4},children:e.jsx("h3",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:t})})}function oe({label:t,value:s,field:n,editField:r,editValue:a,onEdit:o,onSave:i,onEditValueChange:d,options:m,optionLabels:p,multiline:c,numeric:u,currency:x,checkbox:h,checked:b,onDirectSave:f,buttonGroup:g,lookupItems:y,onLookupSelect:j,date:v,readOnly:T}){const k=l.useRef(!1);if(T){const w=x?s?`$${Oc(s)}`:"-":s||"-";return e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:w})]})}return x?r===n?e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsxs("div",{className:"bg-background border border-primary rounded-lg",style:{marginTop:4,display:"flex",alignItems:"center",paddingLeft:12},children:[e.jsx("span",{style:{color:"var(--muted-foreground, #6b7280)",fontSize:14,marginRight:6,pointerEvents:"none",userSelect:"none"},children:"$"}
76),e.jsx("input",{autoFocus:!0,type:"number",step:"0.01",min:"0",value:a,onChange:w=>d(w.target.value),onKeyDown:w=>{w.key==="Enter"&&i(),w.key==="Escape"&&(k.current=!0,o("",""))},onBlur:()=>{k.current||i(),k.current=!1},className:"text-sm text-foreground",style:{flex:1,minWidth:0,padding:"8px 22px 8px 0",border:"none",background:"transparent",outline:"none"}})]})]}):e.jsxs("div",{onClick:()=>o(n,Oc(s)),className:"cursor-pointer group",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsx("p",{className:"text-sm text-foreground mt-1 group-hover:text-primary transition-colors",children:s?`$${Oc(s)}`:e.jsx("span",{className:"text-muted-foreground italic",children:"empty"})})]}):v&&f?e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsx("input",{type:"date",value:s,onChange:w=>f(n,w.target.value||null),className:"bg-background border border-border text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/30",style:{display:"block",width:"100%",padding:"8px 12px",borderRadius:8,marginTop:4}})]}):h&&f?e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsx("button",{onClick:()=>f(n,!b),className:b?"bg-primary":"bg-border",style:{width:40,height:24,borderRadius:12,position:"relative",transition:"background-color 0.2s"},children:e.jsx("span",{style:{position:"absolute",top:4,left:b?20:4,width:16,height:16,borderRadius:8,backgroundColor:"white",transition:"left 0.2s"}})})]}):y&&j?r===n?e.jsx($T,{label:t,items:y,searchValue:a,onSearchChange:d,onSelect:w=>{j(w),o("","")},onCancel:()=>o("","")}):e.jsxs("div",{onClick:()=>o(n,""),className:"cursor-pointer group",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsx("p",{className:"text-sm text-foreground mt-1 group-hover:text-primary transition-colors",children:s||e.jsx("span",{className:"text-muted-foreground italic",children:"empty"})})]}):g&&m&&f?e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:6},children:m.filter(Boolean).map(w=>e.jsx("button",{onClick:()=>f(n,w===s?"":w),className:w===s?"bg-primary text-primary-foreground":"bg-card text-foreground border border-border",style:{padding:"4px 12px",borderRadius:9999,fontSize:13,fontWeight:500,transition:"all 0.15s"},children:(p==null?void 0:p[w])??w},w))})]}):m&&f?e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsx("select",{value:s,onChange:w=>f(n,w.target.value),className:"w-full mt-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground",children:m.map(w=>e.jsx("option",{value:w,children:(p==null?void 0:p[w])??w},w))})]}):r===n?c?e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsx("textarea",{autoFocus:!0,value:a,onChange:w=>d(w.target.value),onKeyDown:w=>{w.key==="Escape"&&(k.current=!0,o("",""))},onBlur:()=>{k.current||i(),k.current=!1},rows:6,className:"w-full mt-1 px-3 py-2 bg-background border border-primary rounded-lg text-sm text-foreground focus:outline-none resize-y"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}
76),e.jsx("input",{autoFocus:!0,type:u?"number":"text",value:a,onChange:w=>d(w.target.value),onKeyDown:w=>{w.key==="Enter"&&i(),w.key==="Escape"&&(k.current=!0,o("",""))},onBlur:()=>{k.current||i(),k.current=!1},className:"w-full mt-1 px-3 py-2 bg-background border border-primary rounded-lg text-sm text-foreground focus:outline-none"})]}):e.jsxs("div",{onClick:()=>o(n,s),className:"cursor-pointer group",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsx("p",{className:"text-sm text-foreground mt-1 group-hover:text-primary transition-colors",children:s||e.jsx("span",{className:"text-muted-foreground italic",children:"empty"})})]})}function $T({label:t,items:s,searchValue:n,onSearchChange:r,onSelect:a,onCancel:o}){const i=l.useMemo(()=>{const d=s.filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(!n)return d;const m=n.toLowerCase();return d.filter(p=>p.label.toLowerCase().includes(m))},[s,n]);return e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}
76),e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search...",value:n,onChange:d=>r(d.target.value),onKeyDown:d=>{d.key==="Escape"&&o()},className:"bg-background border border-primary text-sm text-foreground focus:outline-none",style:{width:"100%",padding:"8px 12px",borderRadius:8,marginTop:4}}),e.jsxs("div",{className:"border border-border bg-card",style:{maxHeight:200,overflowY:"auto",borderRadius:8,marginTop:4},children:[i.length===0&&e.jsx("p",{className:"text-muted-foreground text-sm",style:{padding:"8px 12px"},children:"No results"}),i.map(d=>e.jsx("button",{onClick:()=>a(d),className:"text-foreground hover:bg-accent text-sm",style:{display:"block",width:"100%",textAlign:"left",padding:"8px 12px"},children:d.label},d.id))]})]})}function Cs({title:t,subtitle:s,onClose:n,footer:r,children:a,onPrev:o,onNext:i,hasPrev:d,hasNext:m,positionLabel:p}){const c=!!(o||i);return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.75)",padding:16},children:e.jsxs("div",{className:"bg-card border border-border shadow-2xl flex flex-col",style:{maxHeight:"90vh",width:"100%",maxWidth:560,borderRadius:12,overflow:"hidden"},children:[e.jsx("div",{className:"bg-primary text-primary-foreground",style:{padding:"16px 20px",flexShrink:0},children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[s&&e.jsx("span",{className:"bg-primary-foreground text-primary",style:{display:"inline-block",fontSize:13,fontWeight:700,fontFamily:"monospace",padding:"2px 8px",borderRadius:4,marginBottom:6},children:s}),e.jsx("h2",{style:{fontSize:18,fontWeight:600,lineHeight:1.3},children:t})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginLeft:8,flexShrink:0},children:[c&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:o,disabled:!d,"aria-label":"Previous",title:"Previous (â)",className:"text-primary-foreground/80 hover:text-primary-foreground disabled:opacity-30 disabled:cursor-not-allowed",style:{padding:4,display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(fr,{style:{width:22,height:22}})}),p&&e.jsx("span",{className:"text-primary-foreground/80",style:{fontSize:11,fontVariantNumeric:"tabular-nums",minWidth:36,textAlign:"center"},children:p}),e.jsx("button",{onClick:i,disabled:!m,"aria-label":"Next",title:"Next (â)",className:"text-primary-foreground/80 hover:text-primary-foreground disabled:opacity-30 disabled:cursor-not-allowed",style:{padding:4,display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(Rt,{style:{width:22,height:22}})})]}),e.jsx("button",{onClick:n,className:"text-primary-foreground/80 hover:text-primary-foreground",style:{padding:4},children:e.jsx(mt,{style:{width:22,height:22}})})]})]})}),e.jsx("div",{style:{overflowY:"auto",minHeight:0,flex:1,padding:"16px 20px"},className:"space-y-3",children:a}),r&&e.jsx("div",{className:"bg-accent border-t border-border",style:{padding:"12px 20px",flexShrink:0},children:r})]})})}function BT(t){if(!t)return"";try{return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return""}}function FT({ticketId:t,authToken:s,onClose:n,onFollowChange:r}){const[a,o]=l.useState([]),[i,d]=l.useState(!0),[m,p]=l.useState(""),[c,u]=l.useState(""),[x,h]=l.useState(!1),[b,f]=l.useState(null),g=l.useCallback(async()=>{try{const v=await re("listTicketReminders",{ticketId:t},s||void 0);o(Array.isArray(v==null?void 0:v.reminders)?v.reminders:[])}catch(v){f(v.message||"Failed to load reminders")}finally{d(!1)}},[t,s]);l.useEffect(()=>{g()},[g]);const y=l.useCallback(async()=>{if(f(null),!m){f("Pick a date and time");return}const v=new Date(m).getTime();if(Number.isNaN(v)){f("Invalid date");return}if(v<=Date.now()){f("Pick a time in the future");return}h(!0);try{await re("setTicketReminder",{ticketId:t,fireAt:v,note:c.trim()},s||void 0),p(""),u(""),r==null||r(!0),await g()}catch(T){f(T.message||"Failed to set reminder")}finally{h(!1)}},[m,c,t,s,r,g]),j=l.useCallback(async v=>{o(T=>T.filter(k=>k.id!==v));try{await re("cancelTicketReminder",{reminderId:v},s||void 0)}catch{await g()}},[s,g]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{onClick:n,style:{position:"fixed",inset:0,zIndex:40}}),e.jsxs("div",{style:{position:"absolute",bottom:"100%",right:0,marginBottom:8,zIndex:41,width:320,background:"var(--card, #fff)",border:"1px solid var(--border, #e5e7eb)",borderRadius:12,boxShadow:"0 12px 32px rgba(0,0,0,0.18)",padding:14},onClick:v=>v.stopPropagation(),children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[e.jsx(ms,{style:{width:15,height:15,color:"#9a7d2e"}}),e.jsx("span",{style:{fontSize:13,fontWeight:700,color:"var(--foreground, #111)"},children:"Reminders"})]}),i?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,color:"var(--muted-foreground, #6b7280)"},children:[e.jsx(fe,{style:{width:13,height:13,animation:"spin 1s linear infinite"}})," Loadingâ¦"]}):a.length===0?e.jsx("div",{style:{fontSize:12,color:"var(--muted-foreground, #6b7280)",marginBottom:10},children:"No reminders yet."}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:10},children:a.map(v=>e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"6px 8px",background:"var(--muted, #f3f4f6)",borderRadius:8},children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600,color:"var(--foreground, #111)"},children:BT(v.fireAt)}),v.note&&e.jsx("div",{style:{fontSize:11,color:"var(--muted-foreground, #6b7280)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.note})]}),e.jsx("button",{onClick:()=>j(v.id),title:"Cancel reminder",style:{display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,borderRadius:6,border:"none",background:"transparent",curs
vendor: 4,934 bytes, line 76
76or:"pointer",color:"var(--muted-foreground, #6b7280)"},children:e.jsx(mt,{style:{width:14,height:14}})})]},v.id))}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx("input",{type:"datetime-local",value:m,onChange:v=>p(v.target.value),style:{width:"100%",padding:"7px 9px",borderRadius:8,border:"1px solid var(--border, #e5e7eb)",fontSize:12,background:"var(--background, #fff)",color:"var(--foreground, #111)"}}),e.jsx("input",{type:"text",value:c,onChange:v=>u(v.target.value),placeholder:"Note (optional) â e.g. follow up on hero image",style:{width:"100%",padding:"7px 9px",borderRadius:8,border:"1px solid var(--border, #e5e7eb)",fontSize:12,background:"var(--background, #fff)",color:"var(--foreground, #111)"}}),b&&e.jsx("div",{style:{fontSize:11,color:"#dc2626"},children:b}),e.jsxs("button",{onClick:y,disabled:x,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,padding:"8px 12px",borderRadius:8,border:"none",fontSize:12,fontWeight:600,cursor:x?"default":"pointer",opacity:x?.6:1,background:"#9a7d2e",color:"#fff"},children:[x?e.jsx(fe,{style:{width:13,height:13,animation:"spin 1s linear infinite"}}):e.jsx(Ut,{style:{width:13,height:13}}),"Set reminder"]}),e.jsx("div",{style:{fontSize:10,color:"var(--muted-foreground, #6b7280)",textAlign:"center"},children:"Setting a reminder follows this ticket."})]})]})]})}function _T(t,s,n="long"){return new Intl.DateTimeFormat("en-US",{hour:"numeric",timeZone:t,timeZoneName:n}).format(s).split(/\s/g).slice(2).join(" ")}const $c={},po={};function Pr(t,s){try{const r=($c[t]||($c[t]=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"longOffset"}).format))(s).split("GMT")[1];return r in po?po[r]:Kp(r,r.split(":"))}catch{if(t in po)return po[t];const n=t==null?void 0:t.match(WT);return n?Kp(t,n.slice(1)):NaN}}const WT=/([+-]\d\d):?(\d\d)?/;function Kp(t,s){const n=+(s[0]||0),r=+(s[1]||0),a=+(s[2]||0)/60;return po[t]=n*60+r>0?n*60+r+a:n*60-r-a}class Cn extends Date{constructor(...s){super(),s.length>1&&typeof s[s.length-1]=="string"&&(this.timeZone=s.pop()),this.internal=new Date,isNaN(Pr(this.timeZone,this))?this.setTime(NaN):s.length?typeof s[0]=="number"&&(s.length===1||s.length===2&&typeof s[1]!="number")?this.setTime(s[0]):typeof s[0]=="string"?this.setTime(+new Date(s[0])):s[0]instanceof Date?this.setTime(+s[0]):(this.setTime(+new Date(...s)),Tb(this),Vd(this)):this.setTime(Date.now())}static tz(s,...n){return n.length?new Cn(...n,s):new Cn(Date.now(),s)}withTimeZone(s){return new Cn(+this,s)}getTimezoneOffset(){const s=-Pr(this.timeZone,this);return s>0?Math.floor(s):Math.ceil(s)}setTime(s){return Date.prototype.setTime.apply(this,arguments),Vd(this),+this}[Symbol.for("constructDateFrom")](s){return new Cn(+new Date(s),this.timeZone)}}const Qp=/^(get|set)(?!UTC)/;Object.getOwnPropertyNames(Date.prototype).forEach(t=>{if(!Qp.test(t))return;const s=t.replace(Qp,"$1UTC");Cn.prototype[s]&&(t.startsWith("get")?Cn.prototype[t]=function(){return this.internal[s]()}:(Cn.prototype[t]=function(){return Date.prototype[s].apply(this.internal,arguments),UT(this),+this},Cn.prototype[s]=function(){return Date.prototype[s].apply(this,arguments),Vd(this),+this}))});function Vd(t){t.internal.setTime(+t),t.internal.setUTCSeconds(t.internal.getUTCSeconds()-Math.round(-Pr(t.timeZone,t)*60))}function UT(t){Date.prototype.setFullYear.call(t,t.internal.getUTCFullYear(),t.internal.getUTCMonth(),t.internal.getUTCDate()),Date.prototype.setHours.call(t,t.internal.getUTCHours(),t.internal.getUTCMinutes(),t.internal.getUTCSeconds(),t.internal.getUTCMilliseconds()),Tb(t)}function Tb(t){const s=Pr(t.timeZone,t),n=s>0?Math.floor(s):Math.ceil(s),r=new Date(+t);r.setUTCHours(r.getUTCHours()-1);const a=-new Date(+t).getTimezoneOffset(),o=-new Date(+r).getTimezoneOffset(),i=a-o,d=Date.prototype.getHours.apply(t)!==t.internal.getUTCHours();i&&d&&t.internal.setUTCMinutes(t.internal.getUTCMinutes()+i);const m=a-n;m&&Date.prototype.setUTCMinutes.call(t,Date.prototype.getUTCMinutes.call(t)+m);const p=new Date(+t);p.setUTCSeconds(0);const c=a>0?p.getSeconds():(p.getSeconds()-60)%60,u=Math.round(-(Pr(t.timeZone,t)*60))%60;(u||c)&&(t.internal.setUTCSeconds(t.internal.getUTCSeconds()+u),Date.prototype.setUTCSeconds.call(t,Date.prototype.getUTCSeconds.call(t)+u+c));const x=Pr(t.timeZone,t),h=x>0?Math.floor(x):Math.ceil(x),f=-new Date(+t).getTimezoneOffset()-h,g=h!==n,y=f-m;if(g&&y){Date.prototype.setUTCMinutes.call(t,Date.prototype.getUTCMinutes.call(t)+y);const j=Pr(t.timeZone,t),v=j>0?Math.floor(j):Math.ceil(j),T=h-v;T&&(t.internal.setUTCMinutes(t.internal.getUTCMinutes()+T),Date.prototype.setUTCMinutes.call(t,Date.prototype.getUTCMinutes.call(t)+T))}}class bs extends Cn{static tz(s,...n){return n.length?new bs(...n,s):new bs(Date.now(),s)}toISOString(){const[s,n,r]=this.tzComponents(),a=`${s}${n}:${r}`;return this.internal.toISOString().slice(0,-1)+a}toString(){return`${this.toDateString()}
76 ${this.toTimeString()}`}toDateString(){const[s,n,r,a]=this.internal.toUTCString().split(" ");return`${s==null?void 0:s.slice(0,-1)} ${r} ${n} ${a}`}toTimeString(){const s=this.internal.toUTCString().split(" ")[4],[n,r,a]=this.tzComponents();return`${s} GMT${n}${r}${a} (${_T(this.timeZone,this)})`}toLocaleString(s,n){return Date.prototype.toLocaleString.call(this,s,{...n,timeZone:(n==null?void 0:n.timeZone)||this.timeZone})}toLocaleDateString(s,n){return Date.prototype.toLocaleDateString.call(this,s,{...n,timeZone:(n==null?void 0:n.timeZone)||this.timeZone})}toLocaleTimeString(s,n){return Date.prototype.toLocaleTimeString.call(this,s,{...n,timeZone:(n==null?void 0:n.timeZone)||this.timeZone})}tzComponents(){const s=this.getTimezoneOffset(),n=s>0?"-":"+",r=String(Math.floor(Math.abs(s)/60)).padStart(2,"0"),a=String(Math.abs(s)%60).padStart(2,"0");return[n,r,a]}withTimeZone(s){return new bs(+this,s)}[Symbol.for("constructDateFrom")](s){return new bs(+new Date(s),this.timeZone)}}const Ab=6048e5,HT=864e5,Jp=Symbol.for("constructDateFrom");function ns(t,s){return typeof t=="function"?t(s):t&&typeof t=="object"&&Jp in t?t[Jp](s):t instanceof Date?new t.constructor(s):new Date(s)}function Lt(t,s){return ns(s||t,t)}function Eb(t,s,n){const r=Lt(t,n==null?void 0:n.in);return isNaN(s)?ns(t,NaN):(s&&r.setDate(r.getDate()+s),r)}function Ib(t,s,n){const r=Lt(t,n==null?void 0:n.in);if(isNaN(s))return ns(t,NaN);if(!s)return r;const a=r.getDate(),o=ns(t,r.getTime());o.setMonth(r.getMonth()+s+1,0);const i=o.getDate();return a>=i?o:(r.setFullYear(o.getFullYear(),o.getMonth(),a),r)}let qT={};function oi(){return qT}function Aa(t,s){var d,m,p,c;const n=oi(),r=(s==null?void 0:s.weekStartsOn)??((m=(d=s==null?void 0:s.locale)==null?void 0:d.options)==null?void 0:m.weekStartsOn)??n.weekStartsOn??((c=(p=n.locale)==null?void 0:p.options)==null?void 0:c.weekStartsOn)??0,a=Lt(t,s==null?void 0:s.in),o=a.getDay(),i=(o<r?7:0)+o-r;return a.setDate(a.getDate()-i),a.setHours(0,0,0,0),a}function Do(t,s){return Aa(t,{...s,weekStartsOn:1})}function Rb(t,s){const n=Lt(t,s==null?void 0:s.in),r=n.getFullYear(),a=ns(n,0);a.setFullYear(r+1,0,4),a.setHours(0,0,0,0);const o=Do(a),i=ns(n,0);i.setFullYear(r,0,4),i.setHours(0,0,0,0);const d=Do(i);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function Zp(t){const s=Lt(t),n=new Date(Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()));return n.setUTCFullYear(s.getFullYear()),+t-+n}function _a(t,...s){const n=ns.bind(null,s.find(r=>typeof r=="object"));return s.map(n)}function Mo(t,s){const n=Lt(t,s==null?void 0:s.in);return n.setHours(0,0,0,0),n}function Db(t,s,n){const[r,a]=_a(n==null?void 0:n.in,t,s),o=Mo(r),i=Mo(a),d=+o-Zp(o),m=+i-Zp(i);return Math.round((d-m)/HT)}function VT(t,s){const n=Rb(t,s),r=ns(t,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Do(r)}function YT(t,s,n){return Eb(t,s*7,n)}function GT(t,s,n){return Ib(t,s*12,n)}function KT(t,s){let n,r=s==null?void 0:s.in;return t.forEach(a=>{!r&&typeof a=="object"&&(r=ns.bind(null,a));const o=Lt(a,r);(!n||n<o||isNaN(+o))&&(n=o)}),ns(r,n||NaN)}function QT(t,s){let n,r=s==null?void 0:s.in;return t.forEach(a=>{!r&&typeof a=="object"&&(r=ns.bind(null,a));const o=Lt(a,r);(!n||n>o||isNaN(+o))&&(n=o)}),ns(r,n||NaN)}function JT(t,s,n){const[r,a]=_a(n==null?void 0:n.in,t,s);return+Mo(r)==+Mo(a)}function Mb(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function ZT(t){return!(!Mb(t)&&typeof t!="number"||isNaN(+Lt(t)))}function XT(t,s,n){const[r,a]=_a(n==null?void 0:n.in,t,s),o=r.getFullYear()-a.getFullYear(),i=r.getMonth()-a.getMonth();return o*12+i}function e6(t,s){const n=Lt(t,s==null?void 0:s.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(23,59,59,999),n}function Pb(t,s){const[n,r]=_a(t,s.start,s.end);return{start:n,end:r}}function t6(t,s){const{start:n,end:r}=Pb(s==null?void 0:s.in,t);let a=+n>+r;const o=a?+n:+r,i=a?r:n;i.setHours(0,0,0,0),i.setDate(1);let d=1;const m=[];for(;+i<=o;)m.push(ns(n,i)),i.setMonth(i.getMonth()+d);return a?m.reverse():m}function s6(t,s){const n=Lt(t,s==null?void 0:s.in);return n.setDate(1),n.setHours(0,0,0,0),n}function n6(t,s){const n=Lt(t,s==null?void 0:s.in),r=n.getFullYear();return n.setFullYear(r+1,0,0),n.setHours(23,59,59,999),n}
vendor: 5,386 bytes, line 76
76function Lb(t,s){const n=Lt(t,s==null?void 0:s.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}function r6(t,s){const{start:n,end:r}=Pb(s==null?void 0:s.in,t);let a=+n>+r;const o=a?+n:+r,i=a?r:n;i.setHours(0,0,0,0),i.setMonth(0,1);let d=1;const m=[];for(;+i<=o;)m.push(ns(n,i)),i.setFullYear(i.getFullYear()+d);return a?m.reverse():m}function zb(t,s){var d,m,p,c;const n=oi(),r=(s==null?void 0:s.weekStartsOn)??((m=(d=s==null?void 0:s.locale)==null?void 0:d.options)==null?void 0:m.weekStartsOn)??n.weekStartsOn??((c=(p=n.locale)==null?void 0:p.options)==null?void 0:c.weekStartsOn)??0,a=Lt(t,s==null?void 0:s.in),o=a.getDay(),i=(o<r?-7:0)+6-(o-r);return a.setDate(a.getDate()+i),a.setHours(23,59,59,999),a}function a6(t,s){return zb(t,{...s,weekStartsOn:1})}const o6={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},i6=(t,s,n)=>{let r;const a=o6[t];return typeof a=="string"?r=a:s===1?r=a.one:r=a.other.replace("{{count}}",s.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function Bc(t){return(s={})=>{const n=s.width?String(s.width):t.defaultWidth;return t.formats[n]||t.formats[t.defaultWidth]}}const l6={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},c6={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},d6={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},u6={date:Bc({formats:l6,defaultWidth:"full"}),time:Bc({formats:c6,defaultWidth:"full"}),dateTime:Bc({formats:d6,defaultWidth:"full"})},m6={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},p6=(t,s,n,r)=>m6[t];function Ja(t){return(s,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let a;if(r==="formatting"&&t.formattingValues){const i=t.defaultFormattingWidth||t.defaultWidth,d=n!=null&&n.width?String(n.width):i;a=t.formattingValues[d]||t.formattingValues[i]}else{const i=t.defaultWidth,d=n!=null&&n.width?String(n.width):t.defaultWidth;a=t.values[d]||t.values[i]}const o=t.argumentCallback?t.argumentCallback(s):s;return a[o]}}const x6={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},h6={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},f6={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},g6={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},b6={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},y6={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},j6=(t,s)=>{const n=Number(t),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},v6={ordinalNumber:j6,era:Ja({values:x6,defaultWidth:"wide"}),quarter:Ja({values:h6,defaultWidth:"wide",argumentCallback:t=>t-1}),month:Ja({values:f6,defaultWidth:"wide"}),day:Ja({values:g6,defaultWidth:"wide"}),dayPeriod:Ja({values:b6,defaultWidth:"wide",formattingValues:y6,defaultFormattingWidth:"wide"})};function Za(t){return(s,n={})=>{const r=n.width,a=r&&t.matchPatterns[r]||t.matchPatterns[t.defaultMatchWidth],o=s.match(a);if(!o)return null;const i=o[0],d=r&&t.parsePatterns[r]||t.parsePatterns[t.defaultParseWidth],m=Array.isArray(d)?N6(d,u=>u.test(i)):w6(d,u=>u.test(i));let p;p=t.valueCallback?t.valueCallback(m):m,p=n.valueCallback?n.valueCallback(p
vendor: 9,213 bytes, line 76
76):p;const c=s.slice(i.length);return{value:p,rest:c}}}function w6(t,s){for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&s(t[n]))return n}function N6(t,s){for(let n=0;n<t.length;n++)if(s(t[n]))return n}function k6(t){return(s,n={})=>{const r=s.match(t.matchPattern);if(!r)return null;const a=r[0],o=s.match(t.parsePattern);if(!o)return null;let i=t.valueCallback?t.valueCallback(o[0]):o[0];i=n.valueCallback?n.valueCallback(i):i;const d=s.slice(a.length);return{value:i,rest:d}}}const S6=/^(\d+)(th|st|nd|rd)?/i,C6=/\d+/i,T6={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},A6={any:[/^b/i,/^(a|c)/i]},E6={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},I6={any:[/1/i,/2/i,/3/i,/4/i]},R6={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},D6={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},M6={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},P6={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},L6={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},z6={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},O6={ordinalNumber:k6({matchPattern:S6,parsePattern:C6,valueCallback:t=>parseInt(t,10)}),era:Za({matchPatterns:T6,defaultMatchWidth:"wide",parsePatterns:A6,defaultParseWidth:"any"}),quarter:Za({matchPatterns:E6,defaultMatchWidth:"wide",parsePatterns:I6,defaultParseWidth:"any",valueCallback:t=>t+1}),month:Za({matchPatterns:R6,defaultMatchWidth:"wide",parsePatterns:D6,defaultParseWidth:"any"}),day:Za({matchPatterns:M6,defaultMatchWidth:"wide",parsePatterns:P6,defaultParseWidth:"any"}),dayPeriod:Za({matchPatterns:L6,defaultMatchWidth:"any",parsePatterns:z6,defaultParseWidth:"any"})},Qu={code:"en-US",formatDistance:i6,formatLong:u6,formatRelative:p6,localize:v6,match:O6,options:{weekStartsOn:0,firstWeekContainsDate:1}};function $6(t,s){const n=Lt(t,s==null?void 0:s.in);return Db(n,Lb(n))+1}function Ob(t,s){const n=Lt(t,s==null?void 0:s.in),r=+Do(n)-+VT(n);return Math.round(r/Ab)+1}function $b(t,s){var c,u,x,h;const n=Lt(t,s==null?void 0:s.in),r=n.getFullYear(),a=oi(),o=(s==null?void 0:s.firstWeekContainsDate)??((u=(c=s==null?void 0:s.locale)==null?void 0:c.options)==null?void 0:u.firstWeekContainsDate)??a.firstWeekContainsDate??((h=(x=a.locale)==null?void 0:x.options)==null?void 0:h.firstWeekContainsDate)??1,i=ns((s==null?void 0:s.in)||t,0);i.setFullYear(r+1,0,o),i.setHours(0,0,0,0);const d=Aa(i,s),m=ns((s==null?void 0:s.in)||t,0);m.setFullYear(r,0,o),m.setHours(0,0,0,0);const p=Aa(m,s);return+n>=+d?r+1:+n>=+p?r:r-1}function B6(t,s){var d,m,p,c;const n=oi(),r=(s==null?void 0:s.firstWeekContainsDate)??((m=(d=s==null?void 0:s.locale)==null?void 0:d.options)==null?void 0:m.firstWeekContainsDate)??n.firstWeekContainsDate??((c=(p=n.locale)==null?void 0:p.options)==null?void 0:c.firstWeekContainsDate)??1,a=$b(t,s),o=ns((s==null?void 0:s.in)||t,0);return o.setFullYear(a,0,r),o.setHours(0,0,0,0),Aa(o,s)}function Bb(t,s){const n=Lt(t,s==null?void 0:s.in),r=+Aa(n,s)-+B6(n,s);return Math.round(r/Ab)+1}function Mt(t,s){const n=t<0?"-":"",r=Math.abs(t).toString().padStart(s,"0");return n+r}const cr={y(t,s){const n=t.getFullYear(),r=n>0?n:1-n;return Mt(s==="yy"?r%100:r,s.length)},M(t,s){const n=t.getMonth();return s==="M"?String(n+1):Mt(n+1,2)},d(t,s){return Mt(t.getDate(),s.length)},a(t,s){const n=t.getHours()/12>=1?"pm":"am";switch(s){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(t,s){return Mt(t.getHours()%12||12,s.length)},H(t,s){return Mt(t.getHours(),s.length)},m(t,s){return Mt(t.getMinutes(),s.length)},s(t,s){return Mt(t.getSeconds(),s.length)},S(t,s){const n=s.length,r=t.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return Mt(a,s.length)}},sa={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Xp={G:function(t,s,n){const r=t.getFullYear()>0?1:0;switch(s){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(t,s,n){if(s==="yo"){const r=t.getFullYear(),a=r>0?r:1-r;return n.ordinalNumber(a,{unit:"year"})}return cr.y(t,s)},Y:function(t,s,n,r){const a=$b(t,r),o=a>0?a:1-a;if(s==="YY"){const i=o%100;return Mt(i,2)}return s==="Yo"?n.ordinalNumber(o,{unit:"year"}):Mt(o,s.length)},R:function(t,s){const n=Rb(t);return Mt(n,s.length)},u:function(t,s){const n=t.getFullYear();return Mt(n,s.length)},Q:function(t,s,n){const r=Math.ceil((t.getMonth()+1)/3);switch(s){case"Q":return String(r);case"QQ":return Mt(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(t,s,n){const r=Math.ceil((t.getMonth()+1)/3);switch(s){case"q":return String(r);case"qq":return Mt(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(t,s,n){const r=t.getMonth();switch(s){case"M":case"MM":return cr.M(t,s);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(t,s,n){const r=t.getMonth();switch(s){case"L":return String(r+1);case"LL":return Mt(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(t,s,n,r){const a=Bb(t,r);return s==="wo"?n.ordinalNumber(a,{unit:"week"}):Mt(a,s.length)},I:function(t,s,n){const r=Ob(t);return s==="Io"?n.ordinalNumber(r,{unit:"week"}):Mt(r,s.length)},d:function(t,s,n){return s==="do"?n.ordinalNumber(t.getDate(),{unit:"date"}):cr.d(t,s)},D:function(t,s,n){const r=$6(t);return s==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Mt(r,s.length)},E:function(t,s,n){const r=t.getDay();switch(s){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(t,s,n,r){const a=t.getDay(),o=(a-r.weekStartsOn+8)%7||7;switch(s){case"e":return String(o);case"ee":return Mt(o,2);case"eo":return n.ordinalNumber(o,{unit:"day"});case"eee":return n.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(a,{width:"short",context:"formatting"});case"eeee":default:return n.day(a,{width:"wide",context:"formatting"})}},c:function(t,s,n,r){const a=t.getDay(),o=(a-r.weekStartsOn+8)%7||7;switch(s){case"c":return String(o);case"cc":return Mt(o,s.length);case"co":return n.ordinalNumber(o,{unit:"day"});case"ccc":return n.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(a,{width:"narrow",context:"standalone"});case"cccccc":return n.day(a,{width:"short",context:"standalone"});case"cccc":default:return n.day(a,{width:"wide",context:"standalone"})}},i:function(t,s,n){const r=t.getDay(),a=r===0?7:r;switch(s){case"i":return String(a);case"ii":return Mt(a,s.length);case"io":return n.ordinalNumber(a,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(t,s,n){const a=t.getHours()/12>=1?"pm":"am";switch(s){case"a":case"aa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(t,s,n){const r=t.getHours();let a;switch(r===12?a=sa.noon:r===0?a=sa.midnight:a=r/12>
vendor: 15,213 bytes, line 76
76=1?"pm":"am",s){case"b":case"bb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(t,s,n){const r=t.getHours();let a;switch(r>=17?a=sa.evening:r>=12?a=sa.afternoon:r>=4?a=sa.morning:a=sa.night,s){case"B":case"BB":case"BBB":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(t,s,n){if(s==="ho"){let r=t.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return cr.h(t,s)},H:function(t,s,n){return s==="Ho"?n.ordinalNumber(t.getHours(),{unit:"hour"}):cr.H(t,s)},K:function(t,s,n){const r=t.getHours()%12;return s==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Mt(r,s.length)},k:function(t,s,n){let r=t.getHours();return r===0&&(r=24),s==="ko"?n.ordinalNumber(r,{unit:"hour"}):Mt(r,s.length)},m:function(t,s,n){return s==="mo"?n.ordinalNumber(t.getMinutes(),{unit:"minute"}):cr.m(t,s)},s:function(t,s,n){return s==="so"?n.ordinalNumber(t.getSeconds(),{unit:"second"}):cr.s(t,s)},S:function(t,s){return cr.S(t,s)},X:function(t,s,n){const r=t.getTimezoneOffset();if(r===0)return"Z";switch(s){case"X":return tx(r);case"XXXX":case"XX":return Rr(r);case"XXXXX":case"XXX":default:return Rr(r,":")}},x:function(t,s,n){const r=t.getTimezoneOffset();switch(s){case"x":return tx(r);case"xxxx":case"xx":return Rr(r);case"xxxxx":case"xxx":default:return Rr(r,":")}},O:function(t,s,n){const r=t.getTimezoneOffset();switch(s){case"O":case"OO":case"OOO":return"GMT"+ex(r,":");case"OOOO":default:return"GMT"+Rr(r,":")}},z:function(t,s,n){const r=t.getTimezoneOffset();switch(s){case"z":case"zz":case"zzz":return"GMT"+ex(r,":");case"zzzz":default:return"GMT"+Rr(r,":")}},t:function(t,s,n){const r=Math.trunc(+t/1e3);return Mt(r,s.length)},T:function(t,s,n){return Mt(+t,s.length)}};function ex(t,s=""){const n=t>0?"-":"+",r=Math.abs(t),a=Math.trunc(r/60),o=r%60;return o===0?n+String(a):n+String(a)+s+Mt(o,2)}function tx(t,s){return t%60===0?(t>0?"-":"+")+Mt(Math.abs(t)/60,2):Rr(t,s)}function Rr(t,s=""){const n=t>0?"-":"+",r=Math.abs(t),a=Mt(Math.trunc(r/60),2),o=Mt(r%60,2);return n+a+s+o}const sx=(t,s)=>{switch(t){case"P":return s.date({width:"short"});case"PP":return s.date({width:"medium"});case"PPP":return s.date({width:"long"});case"PPPP":default:return s.date({width:"full"})}},Fb=(t,s)=>{switch(t){case"p":return s.time({width:"short"});case"pp":return s.time({width:"medium"});case"ppp":return s.time({width:"long"});case"pppp":default:return s.time({width:"full"})}},F6=(t,s)=>{const n=t.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return sx(t,s);let o;switch(r){case"P":o=s.dateTime({width:"short"});break;case"PP":o=s.dateTime({width:"medium"});break;case"PPP":o=s.dateTime({width:"long"});break;case"PPPP":default:o=s.dateTime({width:"full"});break}return o.replace("{{date}}",sx(r,s)).replace("{{time}}",Fb(a,s))},_6={p:Fb,P:F6},W6=/^D+$/,U6=/^Y+$/,H6=["D","DD","YY","YYYY"];function q6(t){return W6.test(t)}function V6(t){return U6.test(t)}function Y6(t,s,n){const r=G6(t,s,n);if(console.warn(r),H6.includes(t))throw new RangeError(r)}function G6(t,s,n){const r=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${s}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const K6=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Q6=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,J6=/^'([^]*?)'?$/,Z6=/''/g,X6=/[a-zA-Z]/;function eA(t,s,n){var c,u,x,h,b,f,g,y;const r=oi(),a=(n==null?void 0:n.locale)??r.locale??Qu,o=(n==null?void 0:n.firstWeekContainsDate)??((u=(c=n==null?void 0:n.locale)==null?void 0:c.options)==null?void 0:u.firstWeekContainsDate)??r.firstWeekContainsDate??((h=(x=r.locale)==null?void 0:x.options)==null?void 0:h.firstWeekContainsDate)??1,i=(n==null?void 0:n.weekStartsOn)??((f=(b=n==null?void 0:n.locale)==null?void 0:b.options)==null?void 0:f.weekStartsOn)??r.weekStartsOn??((y=(g=r.locale)==null?void 0:g.options)==null?void 0:y.weekStartsOn)??0,d=Lt(t,n==null?void 0:n.in);if(!ZT(d))throw new RangeError("Invalid time value");let m=s.match(Q6).map(j=>{const v=j[0];if(v==="p"||v==="P"){const T=_6[v];return T(j,a.formatLong)}return j}).join("").match(K6).map(j=>{if(j==="''")return{isToken:!1,value:"'"};const v=j[0];if(v==="'")return{isToken:!1,value:tA(j)};if(Xp[v])return{isToken:!0,value:j};if(v.match(X6))throw new RangeError("Format string contains an unescaped latin alphabet character `"+v+"`");return{isToken:!1,value:j}});a.localize.preprocessor&&(m=a.localize.preprocessor(d,m));const p={firstWeekContainsDate:o,weekStartsOn:i,locale:a};return m.map(j=>{if(!j.isToken)return j.value;const v=j.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&V6(v)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&q6(v))&&Y6(v,s,String(t));const T=Xp[v[0]];return T(d,v,a.localize,p)}).join("")}function tA(t){const s=t.match(J6);return s?s[1].replace(Z6,"'"):t}function sA(t,s){const n=Lt(t,s==null?void 0:s.in),r=n.getFullYear(),a=n.getMonth(),o=ns(n,0);return o.setFullYear(r,a+1,0),o.setHours(0,0,0,0),o.getDate()}function nA(t,s){return Lt(t,s==null?void 0:s.in).getMonth()}function rA(t,s){return Lt(t,s==null?void 0:s.in).getFullYear()}function aA(t,s){return+Lt(t)>+Lt(s)}function oA(t,s){return+Lt(t)<+Lt(s)}function iA(t,s,n){const[r,a]=_a(n==null?void 0:n.in,t,s);return r.getFullYear()===a.getFullYear()&&r.getMonth()===a.getMonth()}function lA(t,s,n){const[r,a]=_a(n==null?void 0:n.in,t,s);return r.getFullYear()===a.getFullYear()}function cA(t,s,n){const r=Lt(t,n==null?void 0:n.in),a=r.getFullYear(),o=r.getDate(),i=ns(t,0);i.setFullYear(a,s,15),i.setHours(0,0,0,0);const d=sA(i);return r.setMonth(s,Math.min(o,d)),r}function dA(t,s,n){const r=Lt(t,n==null?void 0:n.in);return isNaN(+r)?ns(t,NaN):(r.setFullYear(s),r)}const nx=5,uA=4;function mA(t,s){const n=s.startOfMonth(t),r=n.getDay()>0?n.getDay():7,a=s.addDays(t,-r+1),o=s.addDays(a,nx*7-1);return s.getMonth(t)===s.getMonth(o)?nx:uA}function _b(t,s){const n=s.startOfMonth(t),r=n.getDay();return r===1?n:r===0?s.addDays(n,-1*6):s.addDays(n,-1*(r-1))}function pA(t,s){const n=_b(t,s),r=mA(t,s);return s.addDays(n,r*7-1)}class Ks{constructor(s,n){this.Date=Date,this.today=()=>{var r;return(r=this.overrides)!=null&&r.today?this.overrides.today():this.options.timeZone?bs.tz(this.options.timeZone):new this.Date},this.newDate=(r,a,o)=>{var i;return(i=this.overrides)!=null&&i.newDate?this.overrides.newDate(r,a,o):this.options.timeZone?new bs(r,a,o,this.options.timeZone):new Date(r,a,o)},this.addDays=(r,a)=>{var o;return(o=this.overrides)!=null&&o.addDays?this.overrides.addDays(r,a):Eb(r,a)},this.addMonths=(r,a)=>{var o;return(o=this.overrides)!=null&&o.addMonths?this.overrides.addMonths(r,a):Ib(r,a)},this.addWeeks=(r,a)=>{var o;return(o=this.overrides)!=null&&o.addWeeks?this.overrides.addWeeks(r,a):YT(r,a)},this.addYears=(r,a)=>{var o;return(o=this.overrides)!=null&&o.addYears?this.overrides.addYears(r,a):GT(r,a)},this.differenceInCalendarDays=(r,a)=>{var o;return(o=this.overrides)!=null&&o.differenceInCalendarDays?this.overrides.differenceInCalendarDays(r,a):Db(r,a)},this.differenceInCalendarMonths=(r,a)=>{var o;return(o=this.overrides)!=null&&o.differenceInCalendarMonths?this.overrides.differenceInCalendarMonths(r,a):XT(r,a)},this.eachMonthOfInterval=r=>{var a;return(a=this.overrides)!=null&&a.eachMonthOfInterval?this.overrides.eachMonthOfInterval(r):t6(r)},this.eachYearOfInterval=r=>{var d;const a=(d=this.overrides)!=null&&d.eachYearOfInterval?this.overrides.eachYearOfInterval(r):r6(r),o=new Set(a.map(m=>this.getYear(m)));if(o.size===a.length)return a;const i=[];return o.forEach(m=>{i.push(new Date(m,0,1))}),i},this.endOfBroadcastWeek=r=>{var a;return(a=this.overrides)!=null&&a.endOfBroadcastWeek?this.overrides.endOfBroadcastWeek(r):pA(r,this)},this.endOfISOWeek=r=>{var a;return(a=this.overrides)!=null&&a.endOfISOWeek?this.overrides.endOfISOWeek(r):a6(r)},this.endOfMonth=r=>{var a;return(a=this.overrides)!=null&&a.endOfMonth?this.overrides.endOfMonth(r):e6(r)},this.endOfWeek=(r,a)=>{var o;return(o=this.overrides)!=null&&o.endOfWeek?this.overrides.endOfWeek(r,a):zb(r,this.options)},this.endOfYear=r=>{var a;return(a=this.overrides)!=null&&a.endOfYear?this.overrides.endOfYear(r):n6(r)},this.format=(r,a,o)=>{var d;const i=(d=this.overrides)!=null&&d.format?this.overrides.format(r,a,this.options):eA(r,a,this.options);return this.options.numerals&&this.options.numerals!=="latn"?this.replaceDigits(i):i},this.getISOWeek=r=>{var a;return(a=this.overrides)!=null&&a.getISOWeek?this.overrides.getISOWeek(r):Ob(r)},this.getMonth=(r,a)=>{var o;return(o=this.overrides)!=null&&o.getMonth?this.overrides.getMonth(r,this.options):nA(r,this.options)},this.getYear=(r,a)=>{var o;return(o=this.overrides)!=null&&o.getYear?this.overrides.getYear(r,this.options):rA(r,this.options)},this.getWeek=(r,a)=>{var o;return(o=this.overrides)!=null&&o.getWeek?this.overrides.getWeek(r,this.options):Bb(r,this.options)},this.isAfter=(r,a)=>{var o;return(o=this.overrides)!=null&&o.isAfter?this.overrides.isAfter(r,a):aA(r,a)},this.isBefore=(r,a)=>{var o;return(o=this.overrides)!=null&&o.isBefore?this.overrides.isBefore(r,a):oA(r,a)},this.isDate=r=>{var a;return(a=this.overrides)!=null&&a.isDate?this.overrides.isDate(r):Mb(r)},this.isSameDay=(r,a)=>{var o;return(o=this.overrides)!=null&&o.isSameDay?this.overrides.isSameDay(r,a):JT(r,a)},this.isSameMonth=(r,a)=>{var o;return(o=this.overrides)!=null&&o.isSameMonth?this.overrides.isSameMonth(r,a):iA(r,a)},this.isSameYear=(r,a)=>{var o;return(o=this.overrides)!=null&&o.isSameYear?this.overrides.isSameYear(r,a):lA(r,a)},this.max=r=>{var a;return(a=this.overrides)!=null&&a.max?this.overrides.max(r):KT(r)},this.min=r=>{var a;return(a=this.overrides)!=null&&a.min?this.overrides.min(r):QT(r)},this.setMonth=(r,a)=>{var o;return(o=this.overrides)!=null&&o.setMonth?this.overrides.setMonth(r,a):cA(r,a)},this.setYear=(r,a)=>{var o;return(o=this.overrides)!=null&&o.setYear?this.overrides.setYear(r,a):dA(r,a)},this.startOfBroadcastWeek=(r,a)=>{var o;return(o=this.overrides)!=null&&o.startOfBroadcastWeek?this.overrides.startOfBroadcastWeek(r,this):_b(r,this)},this.startOfDay=r=>{var a;return(a=this.overrides)!=null&&a.startOfDay?this.overrides.startOfDay(r):Mo(r)},this.startOfISOWeek=r=>{var a;return(a=this.overrides)!=null&&a.startOfISOWeek?this.overrides.startOfISOWeek(r):Do(r)},this.startOfMonth=r=>{var a;return(a=this.overrides)!=null&&a.startOfMonth?this.overrides.startOfMonth(r):s6(r)},this.startOfWeek=(r,a)=>{var o;return(o=this.overrides)!=null&&o.startOfWeek?this.overrides.startOfWeek(r,this.options):Aa(r,this.options)},this.startOfYear=r=>{var a;return(a=this.overrides)!=null&&a.startOfYear?this.overrides.startOfYear(r):Lb(r)},this.options={locale:Qu,...s},this.overrides=n}getDigitMap(){const{numerals:s="latn"}=this.options,n=new Intl.NumberFormat("en-US",{numberingSystem:s}),r={};for(let a=0;a<10;a++)r[a.toString()]=n.format(a);return r}replaceDigits(s){const n=this.getDigitMap();return s.replace(/\d/g,r=>n[r]||r)}formatNumber(s){return this.replaceDigits(s.toString())}getMonthYearOrder(){var n;const s=(n=this.options.locale)==null?void 0:n.code;return s&&Ks.yearFirstLocales.has(s)?"year-first":"month-first"}formatMonthYear(s){const{locale:n,timeZone:r,numerals:a}=this.options,o=n==null?void 0:n.code;if(o&&Ks.yearFirstLocales.has(o))try{return new Intl.DateTimeFormat(o,{month:"long",year:"numeric",timeZone:r,numberingSystem:a}).format(s)}catch{}const i=this.getMonthYearOrder()==="year-first"?"y LLLL":"LLLL y";return this.format(s,i)}}Ks.yearFirstLocales=new Set(["eu","hu","ja","ja-Hira","ja-JP","ko","ko-KR","lt","lt-LT","lv","lv-LV","mn","mn-MN","zh","zh-CN","zh-HK","zh-TW"]);const Bn=new Ks;class Wb{constructor(s,n,r=Bn){this.date=s,this.displayMonth=n,this.outside=!!(n&&!r.isSameMonth(s,n)),this.dateLib=r}isEqualTo(s){return this.dateLib.isSameDay(s.date,this.date)&&this.dateLib.isSameMonth(s.displayMonth,this.displayMonth)}}class xA{constructor(s,n){this.date=s,this.weeks=n}}class hA{constructor(s,n){this.days=n,this.weekNumber=s}}function fA(t){return ee.createElement("button",{...t})}function gA(t){return ee.createElement("span",{...t})}function bA(t){const{size:s=24,orientation:n="left",className:r}=t;return ee.createElement("svg",{className:r,width:s,height:s,viewBox:"0 0 24 24"},n==="up"&&ee.createElement("polygon",{points:"6.77 17 12.5 11.43 18.24 17 20 15.28 12.5 8 5 15.28"}),n==="down"&&ee.createElement("polygon",{points:"6.77 8 12.5 13.57 18.24 8 20 9.72 12.5 17 5 9.72"}),n==="left"&&ee.createElement("polygon",{points:"16 18.112 9.81111111 12 16 5.87733333 14.0888889 4 6 12 14.0888889 20"}),n==="right"&&ee.createElement("polygon",{points:"8 18.112 14.18888889 12 8 5.87733333 9.91111111 4 18 12 9.91111111 20"}))}function yA(t){const{day:s,modifiers:n,...r}=t;return ee.createElement("td",{...r})}function jA(t){const{day:s,modifiers:n,...r}=t,a=ee.useRef(null);return ee.useEffect(()=>{var o;n.focused&&((o=a.current)==null||o.focus())},[n.focused]),ee.createElement("button",{ref:a,...r})}var et;(function(t){t.Root="root",t.Chevron="chevron",t.Day="day",t.DayButton="day_button",t.CaptionLabel="caption_label",t.Dropdowns="dropdowns",t.Dropdown="dropdown",t.DropdownRoot="dropdown_root",t.Footer="footer",t.MonthGrid="month_grid",t.MonthCaption="month_caption",t.MonthsDropdown="months_dropdown",t.Month="month",t.Months="months",t.Nav="nav",t.NextMonthButton="button_next",t.PreviousMonthButton="button_previous",t.Week="week",t.Weeks="weeks",t.Weekday="weekday",t.Weekdays="weekdays",t.WeekNumber="week_number",t.WeekNumberHeader="week_number_header",t.YearsDropdown="years_dropdown"})(et||(et={}));var Gt;(function(t){t.disabled="disabled",t.hidden="hidden",t.outside="outside",t.focused="focused",t.today="today"})(Gt||(Gt={}));var dn;(function(t){t.range_end="range_end",t.range_middle="range_middle",t.range_start="range_start",t.selected="selected"})(dn||(dn={}));var Ws;(function(t){t.weeks_before_enter="weeks_before_enter",t.weeks_before_exit="weeks_before_exit",t.weeks_after_enter="weeks_after_enter",t.weeks_after_exit="weeks_after_exit",t.caption_after_enter="caption_after_enter",t.caption_after_exit="caption_after_exit",t.caption_before_enter="caption_before_enter",t.caption_before_exit="caption_before_exit"})(Ws||(Ws={}));function vA(t){const{options:s,className:n,components:r,classNames:a,...o}=t,i=[a[et.Dropdown],n].join(" "),d=s==null?void 0:s.find(({value:m})=>m===o.value);return ee.createElement("span",{"data-disabled":o.disabled,className:a[et.DropdownRoot]},ee.createElement(r.Select,{className:i,...o},s==null?void 0:s.map(({value:m,label:p,disabled:c})=>ee.createElement(r.Option,{key:m,value:m,disabled:c},p))),ee.createElement("span",{className:a[et.CaptionLabel],"aria-hidden":!0},d==null?void 0:d.label,ee.createElement(r.Chevron,{orientation:"down",size:18,className:a[et.Chevron]}
vendor: 30,275 bytes, line 76
76)))}function wA(t){return ee.createElement("div",{...t})}function NA(t){return ee.createElement("div",{...t})}function kA(t){const{calendarMonth:s,displayIndex:n,...r}=t;return ee.createElement("div",{...r},t.children)}function SA(t){const{calendarMonth:s,displayIndex:n,...r}=t;return ee.createElement("div",{...r})}function CA(t){return ee.createElement("table",{...t})}function TA(t){return ee.createElement("div",{...t})}const Ub=l.createContext(void 0);function ii(){const t=l.useContext(Ub);if(t===void 0)throw new Error("useDayPicker() must be used within a custom component.");return t}function AA(t){const{components:s}=ii();return ee.createElement(s.Dropdown,{...t})}function EA(t){const{onPreviousClick:s,onNextClick:n,previousMonth:r,nextMonth:a,...o}=t,{components:i,classNames:d,labels:{labelPrevious:m,labelNext:p}}=ii(),c=l.useCallback(x=>{a&&(n==null||n(x))},[a,n]),u=l.useCallback(x=>{r&&(s==null||s(x))},[r,s]);return ee.createElement("nav",{...o},ee.createElement(i.PreviousMonthButton,{type:"button",className:d[et.PreviousMonthButton],tabIndex:r?void 0:-1,"aria-disabled":r?void 0:!0,"aria-label":m(r),onClick:u},ee.createElement(i.Chevron,{disabled:r?void 0:!0,className:d[et.Chevron],orientation:"left"})),ee.createElement(i.NextMonthButton,{type:"button",className:d[et.NextMonthButton],tabIndex:a?void 0:-1,"aria-disabled":a?void 0:!0,"aria-label":p(a),onClick:c},ee.createElement(i.Chevron,{disabled:a?void 0:!0,orientation:"right",className:d[et.Chevron]})))}function IA(t){const{components:s}=ii();return ee.createElement(s.Button,{...t})}function RA(t){return ee.createElement("option",{...t})}function DA(t){const{components:s}=ii();return ee.createElement(s.Button,{...t})}function MA(t){const{rootRef:s,...n}=t;return ee.createElement("div",{...n,ref:s})}function PA(t){return ee.createElement("select",{...t})}function LA(t){const{week:s,...n}=t;return ee.createElement("tr",{...n})}function zA(t){return ee.createElement("th",{...t})}function OA(t){return ee.createElement("thead",{"aria-hidden":!0},ee.createElement("tr",{...t}))}function $A(t){const{week:s,...n}=t;return ee.createElement("th",{...n})}function BA(t){return ee.createElement("th",{...t})}function FA(t){return ee.createElement("tbody",{...t})}function _A(t){const{components:s}=ii();return ee.createElement(s.Dropdown,{...t})}const WA=Object.freeze(Object.defineProperty({__proto__:null,Button:fA,CaptionLabel:gA,Chevron:bA,Day:yA,DayButton:jA,Dropdown:vA,DropdownNav:wA,Footer:NA,Month:kA,MonthCaption:SA,MonthGrid:CA,Months:TA,MonthsDropdown:AA,Nav:EA,NextMonthButton:IA,Option:RA,PreviousMonthButton:DA,Root:MA,Select:PA,Week:LA,WeekNumber:$A,WeekNumberHeader:BA,Weekday:zA,Weekdays:OA,Weeks:FA,YearsDropdown:_A},Symbol.toStringTag,{value:"Module"}));function Kn(t,s,n=!1,r=Bn){let{from:a,to:o}=t;const{differenceInCalendarDays:i,isSameDay:d}=r;return a&&o?(i(o,a)<0&&([a,o]=[o,a]),i(s,a)>=(n?1:0)&&i(o,s)>=(n?1:0)):!n&&o?d(o,s):!n&&a?d(a,s):!1}function Hb(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function Ju(t){return!!(t&&typeof t=="object"&&"from"in t)}function qb(t){return!!(t&&typeof t=="object"&&"after"in t)}function Vb(t){return!!(t&&typeof t=="object"&&"before"in t)}function Yb(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function Gb(t,s){return Array.isArray(t)&&t.every(s.isDate)}function Qn(t,s,n=Bn){const r=Array.isArray(s)?s:[s],{isSameDay:a,differenceInCalendarDays:o,isAfter:i}=n;return r.some(d=>{if(typeof d=="boolean")return d;if(n.isDate(d))return a(t,d);if(Gb(d,n))return d.includes(t);if(Ju(d))return Kn(d,t,!1,n);if(Yb(d))return Array.isArray(d.dayOfWeek)?d.dayOfWeek.includes(t.getDay()):d.dayOfWeek===t.getDay();if(Hb(d)){const m=o(d.before,t),p=o(d.after,t),c=m>0,u=p<0;return i(d.before,d.after)?u&&c:c||u}return qb(d)?o(t,d.after)>0:Vb(d)?o(d.before,t)>0:typeof d=="function"?d(t):!1})}function UA(t,s,n,r,a){const{disabled:o,hidden:i,modifiers:d,showOutsideDays:m,broadcastCalendar:p,today:c}=s,{isSameDay:u,isSameMonth:x,startOfMonth:h,isBefore:b,endOfMonth:f,isAfter:g}=a,y=n&&h(n),j=r&&f(r),v={[Gt.focused]:[],[Gt.outside]:[],[Gt.disabled]:[],[Gt.hidden]:[],[Gt.today]:[]},T={};for(const k of t){const{date:w,displayMonth:I}=k,A=!!(I&&!x(w,I)),E=!!(y&&b(w,y)),C=!!(j&&g(w,j)),N=!!(o&&Qn(w,o,a)),S=!!(i&&Qn(w,i,a))||E||C||!p&&!m&&A||p&&m===!1&&A,O=u(w,c??a.today());A&&v.outside.push(k),N&&v.disabled.push(k),S&&v.hidden.push(k),O&&v.today.push(k),d&&Object.keys(d).forEach(R=>{const z=d==null?void 0:d[R];z&&Qn(w,z,a)&&(T[R]?T[R].push(k):T[R]=[k])})}return k=>{const w={[Gt.focused]:!1,[Gt.disabled]:!1,[Gt.hidden]:!1,[Gt.outside]:!1,[Gt.today]:!1},I={};for(const A in v){const E=v[A];w[A]=E.some(C=>C===k)}for(const A in T)I[A]=T[A].some(E=>E===k);return{...w,...I}}}function HA(t,s,n={}){return Object.entries(t).filter(([,a])=>a===!0).reduce((a,[o])=>(n[o]?a.push(n[o]):s[Gt[o]]?a.push(s[Gt[o]]):s[dn[o]]&&a.push(s[dn[o]]),a),[s[et.Day]])}function qA(t){return{...WA,...t}}function VA(t){const s={"data-mode":t.mode??void 0,"data-required":"required"in t?t.required:void 0,"data-multiple-months":t.numberOfMonths&&t.numberOfMonths>1||void 0,"data-week-numbers":t.showWeekNumber||void 0,"data-broadcast-calendar":t.broadcastCalendar||void 0,"data-nav-layout":t.navLayout||void 0};return Object.entries(t).forEach(([n,r])=>{n.startsWith("data-")&&(s[n]=r)}),s}function YA(){const t={};for(const s in et)t[et[s]]=`rdp-${et[s]}`;for(const s in Gt)t[Gt[s]]=`rdp-${Gt[s]}`;for(const s in dn)t[dn[s]]=`rdp-${dn[s]}`;for(const s in Ws)t[Ws[s]]=`rdp-${Ws[s]}`;return t}function Kb(t,s,n){return(n??new Ks(s)).formatMonthYear(t)}const GA=Kb;function KA(t,s,n){return(n??new Ks(s)).format(t,"d")}function QA(t,s=Bn){return s.format(t,"LLLL")}function JA(t,s,n){return(n??new Ks(s)).format(t,"cccccc")}function ZA(t,s=Bn){return t<10?s.formatNumber(`0${t.toLocaleString()}`):s.formatNumber(`${t.toLocaleString()}`)}function XA(){return""}function Qb(t,s=Bn){return s.format(t,"yyyy")}const eE=Qb,tE=Object.freeze(Object.defineProperty({__proto__:null,formatCaption:Kb,formatDay:KA,formatMonthCaption:GA,formatMonthDropdown:QA,formatWeekNumber:ZA,formatWeekNumberHeader:XA,formatWeekdayName:JA,formatYearCaption:eE,formatYearDropdown:Qb},Symbol.toStringTag,{value:"Module"}));function sE(t){return t!=null&&t.formatMonthCaption&&!t.formatCaption&&(t.formatCaption=t.formatMonthCaption),t!=null&&t.formatYearCaption&&!t.formatYearDropdown&&(t.formatYearDropdown=t.formatYearCaption),{...tE,...t}}function nE(t,s,n,r,a){const{startOfMonth:o,startOfYear:i,endOfYear:d,eachMonthOfInterval:m,getMonth:p}=a;return m({start:i(t),end:d(t)}).map(x=>{const h=r.formatMonthDropdown(x,a),b=p(x),f=s&&x<o(s)||n&&x>o(n)||!1;return{value:b,label:h,disabled:f}})}function rE(t,s={},n={}){let r={...s==null?void 0:s[et.Day]};return Object.entries(t).filter(([,a])=>a===!0).forEach(([a])=>{r={...r,...n==null?void 0:n[a]}}),r}function aE(t,s,n){const r=t.today(),a=s?t.startOfISOWeek(r):t.startOfWeek(r),o=[];for(let i=0;i<7;i++){const d=t.addDays(a,i);o.push(d)}return o}function oE(t,s,n,r,a=!1){if(!t||!s)return;const{startOfYear:o,endOfYear:i,eachYearOfInterval:d,getYear:m}=r,p=o(t),c=i(s),u=d({start:p,end:c});return a&&u.reverse(),u.map(x=>{const h=n.formatYearDropdown(x,r);return{value:m(x),label:h,disabled:!1}})}function Jb(t,s,n,r){let a=(r??new Ks(n)).format(t,"PPPP");return s.today&&(a=`Today, ${a}`),s.selected&&(a=`${a}, selected`),a}const iE=Jb;function Zb(t,s,n){return(n??new Ks(s)).formatMonthYear(t)}const lE=Zb;function cE(t,s,n,r){let a=(r??new Ks(n)).format(t,"PPPP");return s!=null&&s.today&&(a=`Today, ${a}`),a}function dE(t){return"Choose the Month"}function uE(){return""}function mE(t){return"Go to the Next Month"}function pE(t){return"Go to the Previous Month"}function xE(t,s,n){return(n??new Ks(s)).format(t,"cccc")}function hE(t,s){return`Week ${t}`}function fE(t){return"Week Number"}function gE(t){return"Choose the Year"}const bE=Object.freeze(Object.defineProperty({__proto__:null,labelCaption:lE,labelDay:iE,labelDayButton:Jb,labelGrid:Zb,labelGridcell:cE,labelMonthDropdown:dE,labelNav:uE,labelNext:mE,labelPrevious:pE,labelWeekNumber:hE,labelWeekNumberHeader:fE,labelWeekday:xE,labelYearDropdown:gE},Symbol.toStringTag,{value:"Module"})),li=t=>t instanceof HTMLElement?t:null,Fc=t=>[...t.querySelectorAll("[data-animated-month]")??[]],yE=t=>li(t.querySelector("[data-animated-month]")),_c=t=>li(t.querySelector("[data-animated-caption]")),Wc=t=>li(t.querySelector("[data-animated-weeks]")),jE=t=>li(t.querySelector("[data-animated-nav]")),vE=t=>li(t.querySelector("[data-animated-weekdays]"));function wE(t,s,{classNames:n,months:r,focused:a,dateLib:o}){const i=l.useRef(null),d=l.useRef(r),m=l.useRef(!1);l.useLayoutEffect(()=>{const p=d.current;if(d.current=r,!s||!t.current||!(t.current instanceof HTMLElement)||r.length===0||p.length===0||r.length!==p.length)return;const c=o.isSameMonth(r[0].date,p[0].date),u=o.isAfter(r[0].date,p[0].date),x=u?n[Ws.caption_after_enter]:n[Ws.caption_before_enter],h=u?n[Ws.weeks_after_enter]:n[Ws.weeks_before_enter],b=i.current,f=t.current.cloneNode(!0);if(f instanceof HTMLElement?(Fc(f).forEach(v=>{if(!(v instanceof HTMLElement))return;const T=yE(v);T&&v.contains(T)&&v.removeChild(T);const k=_c(v);k&&k.classList.remove(x);const w=Wc(v);w&&w.classList.remove(h)}),i.current=f):i.current=null,m.current||c||a)return;const g=b instanceof HTMLElement?Fc(b):[],y=Fc(t.current);if(y!=null&&y.every(j=>j instanceof HTMLElement)&&g&&g.every(j=>j instanceof HTMLElement)){m.current=!0,t.current.style.isolation="isolate";const j=jE(t.current);j&&(j.style.zIndex="1"),y.forEach((v,T)=>{const k=g[T];if(!k)return;v.style.position="relative",v.style.overflow="hidden";const w=_c(v);w&&w.classList.add(x);const I=Wc(v);I&&I.classList.add(h);const A=()=>{m.current=!1,t.current&&(t.current.style.isolation=""),j&&(j.style.zIndex=""),w&&w.classList.remove(x),I&&I.classList.remove(h),v.style.position="",v.style.overflow="",v.contains(k)&&v.removeChild(k)};k.style.pointerEvents="none",k.style.position="absolute",k.style.overflow="hidden",k.setAttribute("aria-hidden","true");const E=vE(k);E&&(E.style.opacity="0");const C=_c(k);C&&(C.classList.add(u?n[Ws.caption_before_exit]:n[Ws.caption_after_exit]),C.addEventListener("animationend",A));const N=Wc(k);N&&N.classList.add(u?n[Ws.weeks_before_exit]:n[Ws.weeks_after_exit]),v.insertBefore(k,v.firstChild)})}})}function NE(t,s,n,r){const a=t[0],o=t[t.length-1],{ISOWeek:i,fixedWeeks:d,broadcastCalendar:m}=n??{},{addDays:p,differenceInCalendarDays:c,differenceInCalendarMonths:u,endOfBroadcastWeek:x,endOfISOWeek:h,endOfMonth:b,endOfWeek:f,isAfter:g,startOfBroadcastWeek:y,startOfISOWeek:j,startOfWeek:v}=r,T=m?y(a,r):i?j(a):v(a),k=m?x(o):i?h(b(o)):f(b(o)),w=c(k,T),I=u(o,a)+1,A=[];for(let N=0;N<=w;N++){const S=p(T,N);if(s&&g(S,s))break;A.push(S)}const C=(m?35:42)*I;if(d&&A.length<C){const N=C-A.length;for(let S=0;S<N;S++){const O=p(A[A.length-1],1);A.push(O)}}return A}function kE(t){const s=[];return t.reduce((n,r)=>{const a=r.weeks.reduce((o,i)=>o.concat(i.days.slice()),s.slice());return n.concat(a.slice())},s.slice())}function SE(t,s,n,r){const{numberOfMonths:a=1}=n,o=[];for(let i=0;i<a;i++){const d=r.addMonths(t,i);if(s&&d>s)break;o.push(d)}return o}function rx(t,s,n,r){const{month:a,defaultMonth:o,today:i=r.today(),numberOfMonths:d=1}=t;let m=a||o||i;const{differenceInCalendarMonths:p,addMonths:c,startOfMonth:u}=r;if(n&&p(n,m)<d-1){const x=-1*(d-1);m=c(n,x)}return s&&p(m,s)<0&&(m=s),u(m)}function CE(t,s,n,r){const{addDays:a,endOfBroadcastWeek:o,endOfISOWeek:i,endOfMonth:d,endOfWeek:m,getISOWeek:p,getWeek:c,startOfBroadcastWeek:u,startOfISOWeek:x,startOfWeek:h}=r,b=t.reduce((f,g)=>{const y=n.broadcastCalendar?u(g,r):n.ISOWeek?x(g):h(g),j=n.broadcastCalendar?o(g):n.ISOWeek?i(d(g)):m(d(g)),v=s.filter(I=>I>=y&&I<=j),T=n.broadcastCalendar?35:42;if(n.fixedWeeks&&v.length<T){const I=s.filter(A=>{const E=T-v.length;return A>j&&A<=a(j,E)});v.push(...I)}const k=v.reduce((I,A)=>{const E=n.ISOWeek?p(A):c(A),C=I.find(S=>S.weekNumber===E),N=new Wb(A,g,r);return C?C.days.push(N):I.push(new hA(E,[N])),I},[]),w=new xA(g,k);return f.push(w),f},[]);return n.reverseMonths?b.reverse():b}function TE(t,s){let{startMonth:n,endMonth:r}=t;const{startOfYear:a,startOfDay:o,startOfMonth:i,endOfMonth:d,addYears:m,endOfYear:p,newDate:c,today:u}=s,{fromYear:x,toYear:h,fromMonth:b,toMonth:f}=t;!n&&b&&(n=b),!n&&x&&(n=s.newDate(x,0,1)),!r&&f&&(r=f),!r&&h&&(r=c(h,11,31));const g=t.captionLayout==="dropdown"||t.captionLayout==="dropdown-years";return n?n=i(n):x?n=c(x,0,1):!n&&g&&(n=a(m(t.today??u(),-100))),r?r=d(r):h?r=c(h,11,31):!r&&g&&(r=p(t.today??u())),[n&&o(n),r&&o(r)]}function AE(t,s,n,r){if(n.disableNavigation)return;const{pagedNavigation:a,numberOfMonths:o=1}=n,{startOfMonth:i,addMonths:d,differenceInCalendarMonths:m}=r,p=a?o:1,c=i(t);if(!s)return d(c,p);if(!(m(s,t)<o))return d(c,p)}function EE(t,s,n,r){if(n.disableNavigation)return;const{pagedNavigation:a,numberOfMonths:o}=n,{startOfMonth:i,addMonths:d,differenceInCalendarMonths:m}=r,p=a?o??1:1,c=i(t);if(!s)return d(c,-p);if(!(m(c,s)<=0))return d(c,-p)}function IE(t){const s=[];return t.reduce((n,r)=>n.concat(r.weeks.slice()),s.slice())}function tc(t,s){const[n,r]=l.useState(t);return[s===void 0?n:s,r]}function RE(t,s){const[n,r]=TE(t,s),{startOfMonth:a,endOfMonth:o}=s,i=rx(t,n,r,s),[d,m]=tc(i,t.month?i:void 0);l.useEffect(()=>{const w=rx(t,n,r,s);m(w)},[t.timeZone]);const p=SE(d,r,t,s),c=NE(p,t.endMonth?o(t.endMonth):void 0,t,s),u=CE(p,c,t,s),x=IE(u),h=kE(u),b=EE(d,n,t,s),f=AE(d,r,t,s),{disableNavigation:g,onMonthChange:y}=t,j=w=>x.some(I=>I.days.some(A=>A.isEqualTo(w))),v=w=>{if(g)return;let I=a(w);n&&I<a(n)&&(I=a(n)),r&&I>a(r)&&(I=a(r)),m(I),y==null||y(I)};return{months:u,weeks:x,days:h,navStart:n,navEnd:r,previousMonth:b,nextMonth:f,goToMonth:v,goToDay:w=>{j(w)||v(w.date)}}}var Nn;(function(t){t[t.Today=0]="Today",t[t.Selected=1]="Selected",t[t.LastFocused=2]="LastFocused",t[t.FocusedModifier=3]="FocusedModifier"})(Nn||(Nn={}));function ax(t){return!t[Gt.disabled]&&!t[Gt.hidden]&&!t[Gt.outside]}function DE(t,s,n,r){let a,o=-1;for(const i of t){const d=s(i);ax(d)&&(d[Gt.focused]&&o<Nn.FocusedModifier?(a=i,o=Nn.FocusedModifier):r!=null&&r.isEqualTo(i)&&o<Nn.LastFocused?(a=i,o=Nn.LastFocused):n(i.date)&&o<Nn.Selected?(a=i,o=Nn.Selected):d[Gt.today]&&o<Nn.Today&&(a=i,o=Nn.Today))}return a||(a=t.find(i=>ax(s(i)))),a}function ME(t,s,n,r,a,o,i){const{ISOWeek:d,broadcastCalendar:m}=o,{addDays:p,addMonths:c,addWeeks:u,addYears:x,endOfBroadcastWeek:h,endOfISOWeek:b,endOfWeek:f,max:g,min:y,startOfBroadcastWeek:j,startOfISOWeek:v,startOfWeek:T}=i;let w={day:p,week:u,month:c,year:x,startOfWeek:I=>m?j(I,i):d?v(I):T(I),endOfWeek:I=>m?h(I):d?b(I):f(I)}[t](n,s==="after"?1:-1);return s==="before"&&r?w=g([r,w]):s==="after"&&a&&(w=y([a,w])),w}function Xb(t,s,n,r,a,o,i,d=0){if(d>365)return;const m=ME(t,s,n.date,r,a,o,i),p=!!(o.disabled&&Qn(m,o.disabled,i)),c=!!(o.hidden&&Qn(m,o.hidden,i)),u=m,x=new Wb(m,u,i);return!p&&!c?x:Xb(t,s,x,r,a,o,i,d+1)}function PE(t,s,n,r,a){const{autoFocus:o}=t,[i,d]=l.useState(),m=DE(s.days,n,r||(()=>!1),i),[p,c]=l.useState(o?m:void 0);return{isFocusTarget:f=>!!(m!=null&&m.isEqualTo(f)),setFocused:c,focused:p,blur:()=>{d(p),c(void 0)},moveFocus:(f,g)=>{if(!p)return;const y=Xb(f,g,p,s.navStart,s.navEnd,t,a);y&&(t.disableNavigation&&!s.days.some(v=>v.isEqualTo(y))||(s.goToDay(y),c(y)))}}}function LE(t,s){const{selected:n,required:r,onSelect:a}=t,[o,i]=tc(n,a?n:void 0),d=a?n:o,{isSameDay:m}=s,p=h=>(d==null?void 0:d.some(b=>m(b,h)))??!1,{min:c,max:u}=t;return{selected:d,select:(h,b,f)=>{let g=[...d??[]];if(p(h)){if((d==null?void 0:d.length)===c||r&&(d==null?void 0:d.length)===1)return;g=d==null?void 0:d.filter(y=>!m(y,h))}else(d==null?void 0:d.length)===u?g=[h]:g=[...g,h];return a||i(g),a==null||a(g,h,b,f),g},isSelected:p}}function zE(t,s,n=0,r=0,a=!1,o=Bn){const{from:i,to:d}=s||{},{isSameDay:m,isAfter:p,isBefore:c}=o;let u;if(!i&&!d)u={from:t,to:n>0?void 0:t};else if(i&&!d)m(i,t)?n===0?u={from:i,to:t}:a?u={from:i,to:void 0}:u=void 0:c(t,i)?u={from:t,to:i}:u={from:i,to:t};else if(i&&d)if(m(i,t)&&m(d,t))a?u={from:i,to:d}:u=void 0;else if(m(i,t))u={from:i,to:n>0?void 0:t};else if(m(d,t))u={from:t,to:n>0?void 0:t};else if(c(t,i))u={from:t,to:d};else if(p(t,i))u={from:i,to:t};else if(p(t,d))u={from:i,to:t};else throw new Error("Invalid range");if(u!=null&&u.from&&(u!=null&&u.to)){const x=o.differenceInCalendarDays(u.to,u.from);r>0&&x>r?u={from:t,to:void 0}:n>1&&x<n&&(u={from:t,to:void 0})}return u}function OE(t,s,n=Bn){const r=Array.isArray(s)?s:[s];let a=t.from;const o=n.differenceInCalendarDays(t.to,t.from),i=Math.min(o,6);for(let d=0;d<=i;d++){if(r.includes(a.getDay()))return!0;a=n.addDays(a,1)}return!1}function ox(t,s,n=Bn){return Kn(t,s.from,!1,n)||Kn(t,s.to,!1,n)||Kn(s,t.from,!1,n)||Kn(s,t.to,!1,n)}function $E(t,s,n=Bn){const r=Array.isArray(s)?s:[s];if(r.filter(d=>typeof d!="function").some(d=>typeof d=="boolean"?d:n.isDate(d)?Kn(t,d,!1,n):Gb(d,n)?d.some(m=>Kn(t,m,!1,n)):Ju(d)?d.from&&d.to?ox(t,{from:d.from,to:d.to},n):!1:Yb(d)?OE(t,d.dayOfWeek,n):Hb(d)?n.isAfter(d.before,d.after)?ox(t,{from:n.addDays(d.after,1),to:n.addDays(d.before,-1)},n):Qn(t.from,d,n)||Qn(t.to,d,n):qb(d)||Vb(d)?Qn(t.from,d,n)||Qn(t.to,d,n):!1))return!0;const i=r.filter(d=>typeof d=="function");if(i.length){let d=t.from;const m=n.differenceInCalendarDays(t.to,t.from);for(let p=0;p<=m;p++){if(i.some(c=>c(d)))return!0;d=n.addDays(d,1)}}return!1}function BE(t,s){const{disabled:n,excludeDisabled:r,selected:a,required:o,onSelect:i}=t,[d,m]=tc(a,i?a:void 0),p=i?a:d;return{selected:p,select:(x,h,b)=>{const{min:f,max:g}=t,y=x?zE(x,p,f,g,o,s):void 0;return r&&n&&(y!=null&&y.from)&&y.to&&$E({from:y.from,to:y.to},n,s)&&(y.from=x,y.to=void 0),i||m(y),i==null||i(y,x,h,b),y},isSelected:x=>p&&Kn(p,x,!1,s)}}function FE(t,s){const{selected:n,required:r,onSelect:a}=t,[o,i]=tc(n,a?n:void 0),d=a?n:o,{isSameDay:m}=s;return{selected:d,select:(u,x,h)=>{let b=u;return!r&&d&&d&&m(u,d)&&(b=void 0),a||i(b),a==null||a(b,u,x,h),b},isSelected:u=>d?m(d,u):!1}}function _E(t,s){const n=FE(t,s),r=LE(t,s),a=BE(t,s);switch(t.mode){case"single":return n;case"multiple":return r;case"range":return a;default:return}}function WE(t){var He;let s=t;s.timeZone&&(s={...t},s.today&&(s.today=new bs(s.today,s.timeZone)),s.month&&(s.month=new bs(s.month,s.timeZone)),s.defaultMonth&&(s.defaultMonth=new bs(s.defaultMonth,s.timeZone)),s.startMonth&&(s.startMonth=new bs(s.startMonth,s.timeZone)),s.endMonth&&(s.endMonth=new bs(s.endMonth,s.timeZone)),s.mode==="single"&&s.selected?s.selected=new bs(s.selected,s.timeZone):s.mode==="multiple"&&s.selected?s.selected=(He=s.selected)==null?void 0:He.map(Oe=>new bs(Oe,s.timeZone)):s.mode==="range"&&s.selected&&(s.selected={from:s.selected.from?new bs(s.selected.from,s.timeZone):void 0,to:s.selected.to?new bs(s.selected.to,s.timeZone):void 0}));const{components:n,formatters:r,labels:a,dateLib:o,locale:i,classNames:d}=l.useMemo(()=>{const Oe={...Qu,...s.locale};return{dateLib:new Ks({locale:Oe,weekStartsOn:s.broadcastCalendar?1:s.weekStartsOn,firstWeekContainsDate:s.firstWeekContainsDate,useAdditionalWeekYearTokens:s.useAdditionalWeekYearTokens,useAdditionalDayOfYearTokens:s.useAdditionalDayOfYearTokens,timeZone:s.timeZone,numerals:s.numerals},s.dateLib),components:qA(s.components),formatters:sE(s.formatters),labels:{...bE,...s.labels},locale:Oe,classNames:{...YA(),...s.classNames}}},[s.locale,s.broadcastCalendar,s.weekStartsOn,s.firstWeekContainsDate,s.useAdditionalWeekYearTokens,s.useAdditionalDayOfYearTokens,s.timeZone,s.numerals,s.dateLib,s.components,s.formatters,s.labels,s.classNames]),{captionLayout:m,mode:p,navLayout:c,numberOfMonths:u=1,onDayBlur:x,onDayClick:h,onDayFocus:b,onDayKeyDown:f,onDayMouseEnter:g,onDayMouseLeave:y,onNextClick:j,onPrevClick:v,showWeekNumber:T,styles:k}=s,{formatCaption:w,formatDay:I,formatMonthDropdown:A,formatWeekNumber:E,formatWeekNumberHeader:C,formatWeekdayName:N,formatYearDropdown:S}=r,O=RE(s,o),{days:R,months:z,navStart:D,navEnd:L,previousMonth:$,nextMonth:q,goToMonth:P}=O,U=UA(R,s,D,L,o),{isSelected:V,select:M,selected:F}=_E(s,o)??{},{blur:W,focused:_,isFocusTarget:G,moveFocus:B,setFocused:Y}=PE(s,O,U,V??(()=>!1),o),{labelDayButton:J,labelGridcell:H,labelGrid:Z,labelMonthDropdown:Q,labelNav:K,labelPrevious:X,labelNext:se,labelWeekday:pe,labelWeekNumber:me,labelWeekNumberHeader:Ne,labelYearDropdown:at}=a,ae=l.useMemo(()=>aE(o,s.ISOWeek),[o,s.ISOWeek]),xe=p!==void 0||h!==void 0,ze=l.useCallback(()=>{$&&(P($),v==null||v($))},[$,P,v]),Le=l.useCallback(()=>{q&&(P(q),j==null||j(q))},[P,q,j]),ht=l.useCallback((Oe,Je)=>de=>{de.preventDefault(),de.stopPropagation(),Y(Oe),M==null||M(Oe.date,Je,de),h==null||h(Oe.date,Je,de)},[M,h,Y]),ue=l.useCallback((Oe,Je)=>de=>{Y(Oe),b==null||b(Oe.date,Je,de)},[b,Y]),we=l.useCallback((Oe,Je)=>de=>{W(),x==null||x(Oe.date,Je,de)},[W,x]),Be=l.useCallback((Oe,Je)=>de=>{const je={ArrowLeft:[de.shiftKey?"month":"day",s.dir==="rtl"?"after":"before"],ArrowRight:[de.shiftKey?"month":"day",s.dir==="rtl"?"before":"after"],ArrowDown:[de.shiftKey?"year":"week","after"],ArrowUp:[de.shiftKey?"year":"week","before"],PageUp:[de.shiftKey?"year":"month","before"],PageDown:[de.shiftKey?"year":"month","after"],Home:["startOfWeek","before"],End:["endOfWeek","after"]};if(je[de.key]){de.preventDefault(),de.stopPropagation();const[qe,he]=je[de.key];B(qe,he)}f==null||f(Oe.date,Je,de)},[B,f,s.dir]),Ye=l.useCallback((Oe,Je)=>de=>{g==null||g(Oe.date,Je,de)},[g]),rt=l.useCallback((Oe,Je)=>de=>{y==null||y(Oe.date,Je,de)},[y]),te=l.useCallback(Oe=>Je=>{const de=Number(Je.target.value),je=o.setMonth(o.startOfMonth(Oe),de);P(je)},[o,P]),ve=l.useCallback(Oe=>Je=>{const de=Number(Je.target.value),je=o.setYear(o.startOfMonth(Oe),de);P(je)},[o,P]),{className:Ae,style:We}=l.useMemo(()=>({className:[d[et.Root],s.className].filter(Boolean).join(" "),style:{...k==null?void 0:k[et.Root],...s.style}}),[d,s.className,s.style,k]),ie=VA(s),Ue=l.useRef(null);wE(Ue,!!s.animate,{classNames:d,months:z,focused:_,dateLib:o});const Te={dayPickerProps:s,selected:F,select:M,isSelected:V,months:z,nextMonth:q,previousMonth:$,goToMonth:P,getModifiers:U,components:n,classNames:d,styles:k,labels:a,formatters:r};return ee.createElement(Ub.Provider,{value:Te},ee.createElement(n.Root,{rootRef:s.animate?Ue:void 0,className:Ae,style:We,dir:s.dir,id:s.id,lang:s.lang,nonce:s.nonce,title:s.title,role:s.role,"aria-label":s["aria-label"],"aria-labelledby":s["aria-labelledby"],...ie},ee.createElement(n.Months,{className:d[et.Months],style:k==null?void 0:k[et.Months]},!s.hideNavigation&&!c&&ee.createElement(n.Nav,{"data-animated-nav":s.animate?"true":void 0,className:d[et.Nav],style:k==null?void 0:k[et.Nav],"aria-label":K(),onPreviousClick:ze,onNextClick:Le,previousMonth:$,nextMonth:q}),z.map((Oe,Je)=>ee.createElement(n.Month,{"data-animated-month":s.animate?"true":void 0,className:d[et.Month],style:k==null?void 0:k[et.Month],key:Je,displayIndex:Je,calendarMonth:Oe},c==="around"&&!s.hideNavigation&&Je===0&&ee.createElement(n.PreviousMonthButton,{type:"button",className:d[et.PreviousMonthButton],tabIndex:$?void 0:-1,"aria-disabled":$?void 0:!0,"aria-label":X($),onClick:ze,"data-animated-button":s.animate?"true":void 0},ee.createElement(n.Chevron,{disabled:$?void 0:!0,className:d[et.Chevron],orientation:s.dir==="rtl"?"right":"left"})),ee.createElement(n.MonthCaption,{"data-animated-caption":s.animate?"true":void 0,className:d[et.MonthCaption],style:k==null?void 0:k[et.MonthCaption],calendarMonth:Oe,displayIndex:Je},m!=null&&m.startsWith("dropdown")?ee.createElement(n.DropdownNav,{className:d[et.Dropdowns],style:k==null?void 0:k[et.Dropdowns]},(()=>{const de=m==="dropdown"||m==="dropdown-months"?ee.createElement(n.MonthsDropdown,{key:"month",className:d[et.MonthsDropdown],"aria-label":Q(),classNames:d,components:n,disabled:!!s.disableNavigation,onChange:te(Oe.date),options:nE(Oe.date,D,L,r,o),style:k==null?void 0:k[et.Dropdown],value:o.getMonth(Oe.date)}):ee.createElement("span",{key:"month"},A(Oe.date,o)),je=m==="dropdown"||m==="dropdown-years"?ee.createElement(n.YearsDropdown,{key:"year",className:d[et.YearsDropdown],"aria-label":at(o.options),classNames:d,components:n,disabled:!!s.disableNavigation,onChange:ve(Oe.date),options:oE(D,L,r,o,!!s.reverseYears),style:k==null?void 0:k[et.Dropdown],value:o.getYear(Oe.date)}):ee.createElement("span",{key:"year"},S(Oe.date,o));return o.getMonthYearOrder()==="year-first"?[je,de]:[de,je]})(),ee.createElement("span",{role:"status","aria-live":"polite",style:{border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"absolute",width:"1px",whiteSpace:"nowrap",wordWrap:"normal"}},w(Oe.date,o.options,o))):ee.createElement(n.CaptionLabel,{className:d[et.CaptionLabel],role:"status","aria-live":"polite"},w(Oe.date,o.options,o))),c==="around"&&!s.hideNavigation&&Je===u-1&&ee.createElement(n.NextMonthButton,{type:"button",className:d[et.NextMonthButton],tabIndex:q?void 0:-1,"aria-disabled":q?void 0:!0,"aria-label":se(q),onClick:Le,"data-animated-button":s.animate?"true":void 0},ee.createElement(n.Chevron,{disabled:q?void 0:!0,className:d[et.Chevron],orientation:s.dir==="rtl"?"left":"right"})),Je===u-1&&c==="after"&&!s.hideNavigation&&ee.createElement(n.Nav,{"data-animated-nav":s.animate?"true":void 0,className:d[et.Nav],style:k==null?void 0:k[et.Nav],"aria-label":K(),onPreviousClick:ze,onNextClick:Le,previousMonth:$,nextMonth:q}),ee.createElement(n.MonthGrid,{role:"grid","aria-multiselectable":p==="multiple"||p==="range","aria-label":Z(Oe.date,o.options,o)||void 0,className:d[et.MonthGrid],style:k==null?void 0:k[et.MonthGrid]},!s.hideWeekdays&&ee.createElement(n.Weekdays,{"data-animated-weekdays":s.animate?"true":void 0,className:d[et.Weekdays],style:k==null?void 0:k[et.Weekdays]},T&&ee.createElement(n.WeekNumberHeader,{"aria-label":Ne(o.options),className:d[et.WeekNumberHeader],style:k==null?void 0:k[et.WeekNumberHeader],scope:"col"},C()),ae.map(de=>ee.createElement(n.Weekday,{"aria-label":pe(de,o.options,o),className:d[et.Weekday],key:String(de),style:k==null?void 0:k[et.Weekday],scope:"col"},N(de,o.options,o)))),ee.createElement(n.Weeks,{"data-animated-weeks":s.animate?"true":void 0,className:d[et.Weeks],style:k==null?void 0:k[et.Weeks]},Oe.weeks.map(de=>ee.createElement(n.Week,{className:d[et.Week],key:de.weekNumber,style:k==null?void 0:k[et.Week],week:de},T&&ee.createElement(n.WeekNumber,{week:de,style:k==null?void 0:k[et.WeekNumber],"aria-label":me(de.weekNumber,{locale:i}),className:d[et.WeekNumber],scope:"row",role:"rowheader"},E(de.weekNumber,o)),de.days.map(je=>{const{date:qe}=je,he=U(je);if(he[Gt.focused]=!he.hidden&&!!(_!=null&&_.isEqualTo(je)),he[dn.selected]=(V==null?void 0:V(qe))||he.selected,Ju(F)){const{from:es,to:_e}=F;he[dn.range_start]=!!(es&&_e&&o.isSameDay(qe,es)),he[dn.range_end]=!!(es&&_e&&o.isSameDay(qe,_e)),he[dn.range_middle]=Kn(F,qe,!0,o)}const lt=rE(he,k,s.modifiersStyles),tt=HA(he,d,s.modifiersClassNames),Se=!xe&&!he.hidden?H(qe,he,o.options,o):void 0;return ee.createElement(n.Day,{key:`${o.format(qe,"yyyy-MM-dd")}_${o.format(je.displayMonth,"yyyy-MM")}`,day:je,modifiers:he,className:tt.join(" "),style:lt,role:"gridcell","aria-selected":he.selected||void 0,"aria-label":Se,"data-day":o.format(qe,"yyyy-MM-dd"),"data-month":je.outside?o.format(qe,"yyyy-MM"):void 0,"data-selected":he.selected||void 0,"data-disabled":he.disabled||void 0,"data-hidden":he.hidden||void 0,"data-outside":je.outside||void 0,"data-focused":he.focused||void 0,"data-today":he.today||void 0},!he.hidden&&xe?ee.createElement(n.DayButton,{className:d[et.DayButton],style:k==null?void 0:k[et.DayButton],type:"button",day:je,modifiers:he,disabled:he.disabled||void 0,tabIndex:G(je)?0:-1,"aria-label":J(qe,he,o.options,o),onClick:ht(je,he),onBlur:we(je,he),onFocus:ue(je,he),onKeyDown:Be(je,he),onMouseEnter:Ye(je,he),onMouseLeave:rt(je,he)},I(qe,o.options,o)):!he.hidden&&I(je.date,o.options,o))})))))))),s.footer&&ee.createElement(n.Footer,{className:d[et.Footer],style:k==null?void 0:k[et.Footer],role:"status","aria-live":"polite"},s.footer)))}function UE({className:t,classNames:s,showOutsideDays:n=!0,...r}){return e.jsx(WE,{showOutsideDays:n,className:$e("p-3",t),classNames:{months:"flex flex-col sm:flex-row gap-2",month:"flex flex-col gap-4",caption:"hidden",caption_label:"hidden",nav:"hidden",nav_button:"hidden",nav_button_previous:"hidden",nav_button_next:"hidden",table:"w-full table table-fixed",head_row:"",head_cell:"text-muted-foreground w-[14.2857%] font-normal text-[0.8rem] text-center p-1",row:"",cell:$e("w-[14.2857%] relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-range-end)]:rounded-r-md",r.mode==="range"?"[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md":"[&:has([aria-selected])]:rounded-md"),day:$e(Gl({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_start:"day-range-start aria-selected:bg-primary aria-selected:text-primary-foreground",day_range_end:"day-range-end aria-selected:bg-primary aria-selected:text-primary-foreground",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground aria-selected:text-muted-foreground",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...s},components:{IconLeft:({className:a,...o})=>e.jsx(fr,{className:$e("size-4",a),...o}),IconRight:({className:a,...o})=>e.jsx(Rt,{className:$e("size-4",a),...o})},...r})}function Uc(t){return t?t.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric"}):void 0}function HE(t){if(!t)return;const s=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${s}-${n}-${r}`}function qE({ticketId:t,ticketTitle:s,ticketNumber:n,clientName:r,clientId:a,firestoreClientId:o,creditsMax:i,pipelineId:d,plan:m,investigation:p,onClose:c}){var J;
76const[u,x]=l.useState("loading"),[h,b]=l.useState([]),[f,g]=l.useState(""),[y,j]=l.useState(null),[v,T]=l.useState(null),[k,w]=l.useState(new Set),[I,A]=l.useState(void 0),[E,C]=l.useState(new Date),[N,S]=l.useState(!1),[O,R]=l.useState(!0),[z,D]=l.useState(i?String(i):"1"),[L,$]=l.useState(""),[q,P]=l.useState([]);l.useEffect(()=>{U()},[]),l.useEffect(()=>{let H=!1;return(async()=>{R(!0);try{const Z=await re("getTicketCompletionEstimate",{ticketId:t});if(!H&&(Z!=null&&Z.completionDate)){const[Q,K,X]=String(Z.completionDate).split("-").map(Number);let se=new Date(Q,K-1,X);const pe=new Date;pe.setHours(0,0,0,0),se<pe&&(se=pe),A(se),C(se)}}catch{}finally{H||R(!1)}})(),()=>{H=!0}},[t]);const U=async()=>{x("loading");try{const H=await re("getClientContacts",{clientName:r,clientId:a,firestoreClientId:o});b(H.contacts||[]),g(H.companyName||r),j(H.creditPriceCents??null),T(H.currency??null),x("select")}catch(H){$(H.message||"Failed to load contacts"),x("error")}},V=H=>{w(Z=>{const Q=new Set(Z);return Q.has(H)?Q.delete(H):Q.add(H),Q})},M=async()=>{var Q;if(k.size===0)return;x("sending");const H=[],Z=[];for(const K of k){const X=h.find(se=>se.email===K);try{await re("sendApprovalEmail",{ticketId:t,recipientEmail:K,recipientName:X?`${X.firstName} ${X.lastName}`.trim():void 0,ticketTitle:s,ticketNumber:n,creditAmount:parseInt(z)||1,estimatedTimeline:Uc(I),promisedDate:HE(I),projectName:f||r,clientName:r,clientId:a,pipelineId:d,planSummary:m==null?void 0:m.summary,planApproach:m==null?void 0:m.approach,planChanges:(Q=m==null?void 0:m.changes)==null?void 0:Q.map(se=>({description:se.description,changeType:se.changeType})),investigationSummary:p==null?void 0:p.analysis}),H.push(K)}catch(se){Z.push(`${K}: ${se.message}`)}}H.length>0?(P(H),x("success")):($(Z.join("; ")),x("error"))},F="https://cdn.shopify.com/s/files/1/0359/6033/files/icon_933c651a-afcc-4ec2-9889-741d130c5a59.png?v=1764225392",W=k.size===1?(()=>{const H=h.find(Z=>k.has(Z.email));return(H?`${H.firstName} ${H.lastName}`.trim():"")||"there"})():"there",_=f||r||"your project",G=parseInt(z)||0,B=z?G:"TBD",Y=Uc(I)||"To be determined";return e.jsxs("div",{style:{position:"fixed",inset:0,zIndex:100,display:"flex",alignItems:"center",justifyContent:"center",padding:"16px"},children:[e.jsx("div",{onClick:c,style:{position:"absolute",inset:0,backgroundColor:"rgba(0,0,0,0.5)"}}),e.jsxs("div",{className:"bg-card border border-border",style:{position:"relative",borderRadius:"12px",maxWidth:"500px",width:"100%",maxHeight:"80vh",overflowY:"auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 20px",borderBottom:"1px solid var(--border, #e5e7eb)"},children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-foreground",style:{margin:0,fontSize:"16px",fontWeight:600},children:"Email for Approval"}),e.jsxs("p",{className:"text-muted-foreground",style:{margin:"2px 0 0",fontSize:"13px"},children:[n," · ",f||r]})]}),e.jsx("button",{onClick:c,className:"text-muted-foreground hover:text-foreground",style:{background:"none",border:"none",cursor:"pointer",fontSize:"20px",lineHeight:1,padding:"4px"},children:"Ã"})]}),e.jsxs("div",{style:{padding:"16px 20px"},children:[u==="loading"&&e.jsxs("div",{style:{textAlign:"center",padding:"32px 0"},children:[e.jsx("div",{className:"animate-spin",style:{width:"32px",height:"32px",border:"3px solid #e5e7eb",borderTopColor:"#3b82f6",borderRadius:"50%",margin:"0 auto 12px"}}),e.jsx("p",{className:"text-muted-foreground",style:{margin:0,fontSize:"14px"},children:"Loading contacts..."})]}),u==="select"&&e.jsxs(e.Fragment,{children:[h.length===0?e.jsx("div",{style:{textAlign:"center",padding:"24px 0"},children:e.jsxs("p",{className:"text-muted-foreground",style:{margin:0,fontSize:"14px"},children:['No contacts found for "',r,'".']})}):e.jsxs("div",{style:{marginBottom:"16px"},children:[e.jsxs("p",{className:"text-foreground",style:{margin:"0 0 8px",fontSize:"13px",fontWeight:500},children:["Select contacts to email (",h.length," found)"]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:h.map(H=>e.jsxs("label",{className:"bg-background border border-border hover:bg-accent",style:{display:"flex",alignItems:"center",gap:"12px",padding:"10px 12px",borderRadius:"8px",cursor:"pointer",transition:"background-color 0.15s"},children:[e.jsx("input",{type:"checkbox",checked:k.has(H.email),onChange:()=>V(H.email),style:{width:"16px",height:"16px",accentColor:"#3b82f6"}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("p",{className:"text-foreground",style:{margin:0,fontSize:"14px",fontWeight:500},children:[H.firstName," ",H.lastName]}),e.jsxs("p",{className:"text-muted-foreground",style:{margin:"1px 0 0",fontSize:"12px"},children:[H.email,H.jobTitle?` · ${H.jobTitle}`:""]})]})]},H.id))})]}),e.jsxs("div",{className:"bg-background border border-border",style:{borderRadius:"8px",padding:"12px",marginBottom:"16
76px"},children:[e.jsx("p",{className:"text-muted-foreground",style:{margin:"0 0 4px",fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Ticket"}),e.jsx("p",{className:"text-foreground",style:{margin:0,fontSize:"14px",fontWeight:500},children:s})]}),e.jsxs("div",{style:{display:"flex",gap:"12px",marginBottom:"16px"},children:[e.jsxs("div",{style:{flex:"0 0 100px"},children:[e.jsx("label",{className:"text-foreground",style:{display:"block",fontSize:"13px",fontWeight:500,marginBottom:"4px"},children:"Credits"}),e.jsx("input",{type:"number",min:"1",value:z,onChange:H=>D(H.target.value),className:"bg-background text-foreground border border-border",style:{width:"100%",padding:"8px 12px",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box"}})]}),e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{className:"text-foreground",style:{display:"block",fontSize:"13px",fontWeight:500,marginBottom:"4px"},children:"Estimated Completion"}),e.jsx("button",{type:"button",onClick:()=>S(H=>!H),className:"bg-background text-foreground border border-border hover:bg-accent",style:{width:"100%",padding:"8px 12px",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",textAlign:"left",cursor:"pointer"},children:O?"Calculatingâ¦":I?Uc(I):"Select date"})]})]}),N&&e.jsxs("div",{className:"bg-background border border-border",style:{borderRadius:"8px",padding:"12px",marginBottom:"16px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px"},children:[e.jsx("button",{type:"button",onClick:()=>{const H=new Date(E);H.setMonth(H.getMonth()-1),C(H)},className:"hover:bg-accent text-foreground",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",borderRadius:"6px"},children:e.jsx(fr,{style:{width:"18px",height:"18px"}})}),e.jsx("span",{className:"text-foreground",style:{fontSize:"14px",fontWeight:500},children:E.toLocaleDateString("en-US",{month:"long",year:"numeric"})}),e.jsx("button",{type:"button",onClick:()=>{const H=new Date(E);H.setMonth(H.getMonth()+1),C(H)},className:"hover:bg-accent text-foreground",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",borderRadius:"6px"},children:e.jsx(Rt,{style:{width:"18px",height:"18px"}})})]}),e.jsx("div",{style:{display:"flex",justifyContent:"center"},children:e.jsx(UE,{mode:"single",selected:I,onSelect:H=>{A(H),S(!1)},month:E,onMonthChange:C,disabled:H=>{const Z=new Date;return Z.setHours(0,0,0,0),H<Z},className:"rounded-md border"})})]}),e.jsxs("button",{onClick:M,disabled:k.size===0,style:{width:"100%",padding:"12px",backgroundColor:k.size>0?"#3b82f6":"#9ca3af",color:"#ffffff",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:600,cursor:k.size>0?"pointer":"not-allowed",opacity:k.size>0?1:.6},children:["Send Approval Email",k.size>1?"s":"",k.size>0?` (${k.size})`:""]}),e.jsx("button",{onClick:()=>x("preview"),style:{width:"100%",padding:"10px",backgroundColor:"transparent",color:"#6b7280",border:"1px solid #e5e7eb",borderRadius:"8px",fontSize:"13px",fontWeight:500,cursor:"pointer",marginTop:"8px"},children:"Preview Email"})]}),u==="preview"&&e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[e.jsx("p",{className:"text-foreground",style:{margin:0,fontSize:"13px",fontWeight:500},children:"Email preview"}),e.jsx("button",{onClick:()=>x("select"),className:"text-muted-foreground hover:text-foreground",style:{background:"none",border:"none",cursor:"pointer",fontSize:"13px"},children:"Back"})]}),e.jsxs("div",{className:"bg-background border border-border",style:{borderRadius:"8px",padding:"10px 12px",marginBottom:"12px",fontSize:"12px"},children:[e.jsxs("div",{style:{display:"flex",gap:"8px",marginBottom:"3px"},children:[e.jsx("span",{className:"text-muted-foreground",style:{flex:"0 0 52px"},children:"Subject"}),e.jsxs("span",{className:"text-foreground",style:{fontWeight:600},children:["Approval Required: ",s]})]}),e.jsxs("div",{style:{display:"flex",gap:"8px",marginBottom:"3px"},children:[e.jsx("span",{className:"text-muted-foreground",style:{flex:"0 0 52px"},children:"From"}),e.jsx("span",{className:"text-foreground",children:"Sunbowl Systems <[email protected]>"})]}),e.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e.jsx("span",{className:"text-muted-foreground",style:{flex:"0 0 52px"},children:"To"}),e.jsx("span",{className:"text-foreground",style:{wordBreak:"break-all"},children:k.size>0?Array.from(k).join(", "):"select recipientsâ¦"})]})]}),e.jsx("div",{style:{backgroundColor:"#f5f5f5",borderRadius:"12px",padding:"16px 12px"},children:e.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"12px",boxShadow:"0 2px 4px rgba(0,0,0,0.08)",overflow:"hidden"},children:[e.jsxs("div",{style:{textAlign:"center",padding:"24px 20px 12px"},children:[e.jsx("img",{src:F,alt:"Sunbowl",width:48,height:48,style:{display:"block",margin:"0 auto 12px"}}),e.jsx("p",{style:{color:"#1f2937",margin:"0 0 4px",fontSize:"18px",fontWeight:700},children:"Approval Required"}),e.jsx("p",{style:{color:"#6b7280",margin:0,fontSize:"13px"},children:_})]}),e.jsxs("div",{style:{padding:"0 20px 20px"},children:[e.jsxs("p",{style:{color:"#374151",fontSize:"13px",lineHeight:1.6,margin:"0 0 4px"},children:["Hi ",W,","]}
76),e.jsx("p",{style:{color:"#374151",fontSize:"13px",lineHeight:1.6,margin:"0 0 14px"},children:"We've prepared a plan for the following work and need your approval to proceed."}),e.jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:"8px",border:"1px solid #e5e7eb",padding:"12px",marginBottom:"12px"},children:[e.jsxs("div",{style:{paddingBottom:"10px",borderBottom:"1px solid #e5e7eb",marginBottom:"10px"},children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"10px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 3px"},children:"Ticket"}),e.jsxs("p",{style:{color:"#1f2937",fontSize:"13px",fontWeight:600,margin:0},children:[n," â ",s]})]}),e.jsxs("div",{style:{display:"flex",gap:"16px"},children:[e.jsxs("div",{children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"10px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 1px"},children:"Credits"}),e.jsx("p",{style:{color:"#1f2937",fontSize:"16px",fontWeight:700,margin:0},children:B})]}),e.jsxs("div",{children:[e.jsx("p",{style:{color:"#6b7280",fontSize:"10px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 1px"},children:"Estimated Completion"}),e.jsx("p",{style:{color:"#1f2937",fontSize:"13px",fontWeight:600,margin:0},children:Y})]})]})]}),(m==null?void 0:m.summary)&&e.jsxs("div",{style:{backgroundColor:"#f0fdf4",borderRadius:"8px",border:"1px solid #bbf7d0",padding:"12px",marginBottom:"12px"},children:[e.jsx("p",{style:{color:"#166534",fontSize:"10px",textTransform:"uppercase",letterSpacing:"0.5px",margin:"0 0 6px",fontWeight:600},children:"What We'll Do"}),e.jsx("p",{style:{color:"#374151",fontSize:"12px",lineHeight:1.5,margin:"0 0 8px"},children:m.summary}),((J=m.changes)==null?void 0:J.length)>0&&m.changes.map((H,Z)=>e.jsx("div",{style:{padding:"4px 0 4px 8px",borderLeft:"3px solid #22c55e",marginBottom:"4px",color:"#374151",fontSize:"12px",lineHeight:1.4},children:H.description},Z))]}),e.jsxs("div",{style:{textAlign:"center",padding:"8px 0 4px"},children:[e.jsx("div",{style:{display:"inline-block",backgroundColor:"#22c55e",color:"#ffffff",padding:"12px 40px",borderRadius:"8px",fontSize:"15px",fontWeight:600},children:"Approve Work"}),e.jsx("p",{style:{color:"#9ca3af",fontSize:"11px",margin:"10px 0 0"},children:"This link expires in 7 days."})]})]}),e.jsxs("div",{style:{padding:"14px 20px",backgroundColor:"#f9fafb",borderTop:"1px solid #e5e7eb"},children:[e.jsxs("p",{style:{color:"#4b5563",margin:"0 0 8px",fontSize:"12px",lineHeight:1.6},children:["By approving, ",e.jsxs("strong",{children:[B," credit",G!==1?"s":""]})," will be reserved for this work. Credits are only deducted upon completion."]}),e.jsx("p",{style:{color:"#6b7280",margin:0,fontSize:"11px"},children:"Have questions? Reply to this email and we'll be happy to help."})]}),e.jsx("div",{style:{textAlign:"center",padding:"14px 20px",borderTop:"1px solid #e5e7eb"},children:e.jsxs("p",{style:{color:"#9ca3af",margin:0,fontSize:"11px",lineHeight:1.5},children:["Sent by Sunbowl Systems",e.jsx("br",{}),"sunbowl.ca"]})})]})})]}),u==="sending"&&e.jsxs("div",{style:{textAlign:"center",padding:"32px 0"},children:[e.jsx("div",{className:"animate-spin",style:{width:"32px",height:"32px",border:"3px solid #e5e7eb",borderTopColor:"#3b82f6",borderRadius:"50%",margin:"0 auto 12px"}}),e.jsxs("p",{className:"text-muted-foreground",style:{margin:0,fontSize:"14px"},children:["Sending approval email",k.size>1?"s":"","..."]})]}),u==="success"&&e.jsxs("div",{style:{textAlign:"center",padding:"24px 0"},children:[e.jsx("div",{style:{width:"48px",height:"48px",backgroundColor:"#dcfce7",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 12px",fontSize:"24px",color:"#16a34a"},children:"â"}),e.jsxs("p",{className:"text-foreground",style:{margin:"0 0 8px",fontSize:"15px",fontWeight:500},children:["Approval email",q.length>1?"s":""," sent!"]}),e.jsx("div",{style:{marginBottom:"16px"},children:q.map(H=>e.jsx("p",{className:"text-muted-foreground",style:{margin:"2px 0",fontSize:"13px"},children:H},H))}),e.jsx("button",{onClick:c,className:"bg-primary text-primary-foreground hover:bg-primary/90",style:{padding:"10px 24px",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:500,cursor:"pointer"},children:"Done"})]}),u==="error"&&e.jsxs("div",{style:{textAlign:"center",padding:"24px 0"},children:[e.jsx("div",{style:{width:"48px",height:"48px",backgroundColor:"#fee2e2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 12px",fontSize:"24px",color:"#dc2626"},children:"â"}),e.jsx("p",{className:"text-foreground",style:{margin:"0 0 8px",fontSize:"15px",fontWeight:500},children:"Error"}),e.jsx("p",{className:"text-muted-foreground",style:{margin:"0 0 16px",fontSize:"13px"},children:L}),e.jsx("button",{onClick:U,className:"bg-primary text-primary-foreground hover:bg-primary/90",style:{padding:"10px 24px",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:500,cursor:"pointer"},children:"Try Again"})]})]})]})]})}function ey({ticketId:t,ticketTitle:s,ticketNumber:n,clientName:r,clientId:a,firestoreClientId:o,onSent:i,onClose:d}){const[m,p]=l.useState("loading"),[c,u]=l.useState([]),[x,h]=l.useState(""),[b,f]=l.useState(new Set),[g,y]=l.useState("");l.useEffect(()=>{j()},[]);const j=async()=>{p("loading");try{const k=await re("getClientContacts",{clientName:r,clientId:a,firestoreClientId:o}),w=k.contacts||[];
76u(w),h(k.companyName||r),w.length===1&&f(new Set([w[0].email])),p("select")}catch(k){y(k.message||"Failed to load contacts"),p("error")}},v=k=>{f(w=>{const I=new Set(w);return I.has(k)?I.delete(k):I.add(k),I})},T=async()=>{if(b.size!==0){p("sending");try{const k=Array.from(b).map(w=>{const I=c.find(A=>A.email===w);return{email:w,name:I?`${I.firstName} ${I.lastName}`.trim():""}});await re("sendTicketReviewEmail",{ticketId:t,recipients:k}),i()}catch(k){y(k.message||"Failed to send review email"),p("error")}}};return e.jsxs("div",{style:{position:"fixed",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",padding:"16px"},children:[e.jsx("div",{onClick:d,style:{position:"absolute",inset:0,backgroundColor:"rgba(0,0,0,0.5)"}}),e.jsxs("div",{className:"bg-card border border-border",style:{position:"relative",borderRadius:"12px",maxWidth:"500px",width:"100%",maxHeight:"80vh",overflowY:"auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 20px",borderBottom:"1px solid var(--border, #e5e7eb)"},children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-foreground",style:{margin:0,fontSize:"16px",fontWeight:600},children:"Send for client review"}),e.jsxs("p",{className:"text-muted-foreground",style:{margin:"2px 0 0",fontSize:"13px"},children:[n," · ",x||r]})]}),e.jsx("button",{onClick:d,className:"text-muted-foreground hover:text-foreground",style:{background:"none",border:"none",cursor:"pointer",fontSize:"20px",lineHeight:1,padding:"4px"},children:"Ã"})]}),e.jsxs("div",{style:{padding:"16px 20px"},children:[m==="loading"&&e.jsxs("div",{style:{textAlign:"center",padding:"32px 0"},children:[e.jsx("div",{className:"animate-spin",style:{width:"32px",height:"32px",border:"3px solid #e5e7eb",borderTopColor:"#3b82f6",borderRadius:"50%",margin:"0 auto 12px"}}),e.jsx("p",{className:"text-muted-foreground",style:{margin:0,fontSize:"14px"},children:"Loading contacts..."})]}),m==="select"&&e.jsxs(e.Fragment,{children:[c.length===0?e.jsx("div",{style:{textAlign:"center",padding:"24px 0"},children:e.jsxs("p",{className:"text-muted-foreground",style:{margin:0,fontSize:"14px"},children:['No contacts found for "',r,'". Add a contact for this client, then try again.']})}):e.jsxs("div",{style:{marginBottom:"16px"},children:[e.jsxs("p",{className:"text-foreground",style:{margin:"0 0 8px",fontSize:"13px",fontWeight:500},children:["Who should review & approve this? (",c.length," contact",c.length===1?"":"s",")"]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:c.map(k=>e.jsxs("label",{className:"bg-background border border-border hover:bg-accent",style:{display:"flex",alignItems:"center",gap:"12px",padding:"10px 12px",borderRadius:"8px",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:b.has(k.email),onChange:()=>v(k.email),style:{width:"16px",height:"16px",accentColor:"#3b82f6"}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("p",{className:"text-foreground",style:{margin:0,fontSize:"14px",fontWeight:500},children:`${k.firstName} ${k.lastName}`.trim()||k.email}),e.jsxs("p",{className:"text-muted-foreground",style:{margin:"1px 0 0",fontSize:"12px"},children:[k.email,k.jobTitle?` · ${k.jobTitle}`:""]})]})]},k.id))})]}),e.jsxs("div",{className:"bg-background border border-border",style:{borderRadius:"8px",padding:"12px",marginBottom:"16px"},children:[e.jsx("p",{className:"text-muted-foreground",style:{margin:"0 0 4px",fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Ticket"}),e.jsx("p",{className:"text-foreground",style:{margin:0,fontSize:"14px",fontWeight:500},children:s})]}),e.jsxs("button",{onClick:T,disabled:b.size===0,style:{width:"100%",padding:"12px",backgroundColor:b.size>0?"#22c55e":"#9ca3af",color:"#fff",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:600,cursor:b.size>0?"pointer":"not-allowed",opacity:b.size>0?1:.6},children:["Send review email",b.size>1?"s":"",b.size>0?` (${b.size})`:""]})]}),m==="sending"&&e.jsxs("div",{style:{textAlign:"center",padding:"32px 0"},children:[e.jsx("div",{className:"animate-spin",style:{width:"32px",height:"32px",border:"3px solid #e5e7eb",borderTopColor:"#22c55e",borderRadius:"50%",margin:"0 auto 12px"}}),e.jsx("p",{className:"text-muted-foreground",style:{margin:0,fontSize:"14px"},children:"Sending & moving to Client Review..."})]}),m==="error"&&e.jsxs("div",{style:{textAlign:"center",padding:"24px 0"},children:[e.jsx("div",{style:{width:"48px",height:"48px",backgroundColor:"#fee2e2",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 12px",fontSize:"24px",color:"#dc2626"},children:"â"}),e.jsx("p",{className:"text-foreground",style:{margin:"0 0 8px",fontSize:"15px",fontWeight:500},children:"Error"}),e.jsx("p",{className:"text-muted-foreground",style:{margin:"0 0 16px",fontSize:"13px"},children:g}),e.jsx("button",{onClick:j,className:"bg-primary text-primary-foreground hover:bg-primary/90",style:{padding:"10px 24px",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:500,cursor:"pointer"},children:"Try Again"})]})]})]})]})}const ji="https://us-central1-bucky-app-355a3.cloudfunctions.net";function ty(){const{token:t}=pt(),[s,n]=l.useState(!1),[r,a]=l.useState(!1),[o,i]=l.useState(!1),[d,m]=l.useState(null),p=l.useCallback(async h=>{if(!t)return null;n(!0),m(null);try{const b=await fetch(`${ji}/detectDuplicates`,{method:"POST",headers:as(t),body:JSON.stringify({projectId:h})}),f=await b.json();if(!b.ok)throw new Error(f.error||"Detection failed");return f}catch(b){return m(b.message),null}finally{n(!1)}},[t]),c=l.useCallback(async h=>{if(!t)return null;a(!0),m(null);try{const b=await fetch(`${ji}/mergeTickets`,{method:"POST",headers:as(t),body:JSON.stringify(h)}),f=await b.json();if(!b.ok)throw new Error(f.error||"Merge failed");return f}catch(b){return m(b.message),null}finally{a(!1)}},[t]),u=l.useCallback(async h=>{if(!t)return null;m(null);try{const b=await fetch(`${ji}/previewMergedContent`,{method:"POST",headers:as(t),body:JSON.stringify({ticketIds:h})}),f=await b.json();if(!b.ok)throw new Error(f.error||"Preview failed");return f.summary}catch(b){return m(b.message),null}},[t]),x=l.useCallback(async h=>{if(!t)return null;i(!0),m(null);try{const b=await fetch(`${ji}/unmergeTicket`,{method:"POST",headers:as(t),body:JSON.stringify({mergedTicketId:h})}),f=await b.json();if(!b.ok)throw new Error(f.error||"Unmerge failed");return f}catch(b){return m(b.message),null}finally{i(!1)}},[t]);return{detectDuplicates:p,mergeTickets:c,unmergeTicket:x,previewMergedContent:u,detecting:s,merging:r,unmerging:o,error:d,clearError:()=>m(null)}}function Zu(){const[t,s]=l.useState(!1);return l.useEffect(()=>{var o;const n=(o=window.electron)==null?void 0:o.voice;if(!n)return;let r=!1;n.isLiveCapturing().then(i=>{r||s(!!i)}).catch(i=>{console.error("[voice] failed to read Live capture state:",i)});const a=n.onLiveCaptureChanged(i=>{s(!!i)});return()=>{r=!0,a==null||a()}},[]),t}const VE=[{field:"mobilePhone",label:"mobile"},{field:"phone",label:"phone"}];function YE({ticketId:t,clientId:s,iconOnly:n=!1}){const r=ti(),a=Vl(),o=Zu(),[i,d]=l.useState([]),[m,p]=l.useState(!1),[c,u]=l.useState(!1),[x,h]=l.useState(s??null);l.useEffect(()=>{if(s){h(s);return}if(!r||!t)return;let T=!1;return ps(ut(ge,"tickets",t)).then(k=>{var w;T||h(((w=k.data())==null?void 0:w.clientId)??null)}
76).catch(k=>{console.error("[voice] resolving ticket clientId failed:",k)}),()=>{T=!0}},[s,t,r]);const b=x;if(l.useEffect(()=>{if(!r||!b)return;let T=!1;return u(!0),Ze(Ge(Re(ge,"contacts"),Ve("clientIds","array-contains",b))).then(k=>{if(T)return;const w=[];k.docs.forEach(I=>{const A=I.data(),E=[A.firstName,A.lastName].filter(Boolean).join(" ").trim()||A.email||"Unnamed contact";VE.forEach(({field:C,label:N})=>{const S=si(A[C]);S&&(w.some(O=>O.number===S)||w.push({id:`${I.id}:${C}`,name:E,number:S,label:N,isPrimary:!!A.isPrimary}))})}),w.sort((I,A)=>Number(A.isPrimary)-Number(I.isPrimary)),d(w)}).catch(k=>{console.error("[voice] loading client contacts failed:",k)}).finally(()=>{T||u(!1)}),()=>{T=!0}},[b,r]),!a||!r||!b||!c&&i.length===0)return null;const f=a.phase!=="idle",g=f||o||c,y=o?"Bucky Live is using the microphone â end the meeting to place a call":f?"You are already on a call":"Call a contact at this client",j=T=>{p(!1),a.startCall({to:T.number,displayName:T.name,ticketId:t,clientId:b,contactId:T.id.split(":")[0]})},v=i.length===1?i[0]:null;return e.jsxs("div",{className:"relative",children:[n?e.jsx("button",{onClick:()=>v?j(v):p(T=>!T),disabled:g,title:y,"aria-label":y,className:"text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:cursor-not-allowed",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:36,height:36,borderRadius:9,border:"none",background:"transparent",transition:"background 120ms ease, color 120ms ease"},children:e.jsx(En,{style:{width:16,height:16}})}):e.jsxs("button",{onClick:()=>v?j(v):p(T=>!T),disabled:g,title:y,"aria-label":y,className:"flex items-center gap-2 px-3 py-2 rounded-xl bg-primary/10 text-primary hover:opacity-80 disabled:opacity-40 disabled:cursor-not-allowed transition-colors",children:[e.jsx(En,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm",children:"Call"}),!v&&e.jsx(Ot,{className:"w-4 h-4"})]}),m&&!v&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0",style:{zIndex:40},onClick:()=>p(!1),"aria-hidden":"true"}),e.jsx("div",{className:`absolute z-50 bg-card border border-border rounded-xl shadow-lg overflow-hidden ${n?"left-0":"right-0 mt-1"}`,style:n?{width:256,bottom:"100%",marginBottom:4}:{width:256},children:i.map((T,k)=>e.jsxs("button",{onClick:()=>j(T),className:`w-full text-left p-3 hover:bg-muted transition-colors ${k>0?"border-t border-border":""}`,children:[e.jsxs("p",{className:"text-foreground text-sm truncate",children:[T.name,T.isPrimary?" ⢠primary":""]}),e.jsxs("p",{className:"text-muted-foreground text-sm",children:[cn(T.number)," (",T.label,")"]})]},T.id))})]})]})}const GE=new Set(["no-answer","busy","failed","canceled"]);function KE(t){return t.ticketId?{field:"ticketId",value:t.ticketId}:t.clientId?{field:"clientId",value:t.clientId}:t.createdBy?{field:"createdBy",value:t.createdBy}:null}function QE(t){return t.ticketDisplayId?t.ticketDisplayId:t.ticketId?"On a ticket":null}function JE(t){return t.summary?null:t.summaryState==="pending"?t.recordingSid?"Recap on the way.":"Waiting for the recording.":t.summaryState==="failed"?`Recap failed${t.summaryError?`: ${t.summaryError}`:"."}`:null}function ZE({summary:t}){const[s,n]=l.useState(!1),r=t.decisions.length>0||t.commitments.length>0||t.followUps.length>0;return e.jsxs("div",{className:"mt-2 rounded-xl bg-muted",style:{padding:"8px 10px"},children:[e.jsx("p",{className:"text-foreground text-sm font-medium",children:t.headline}),t.overview&&e.jsx("p",{className:"text-foreground text-sm mt-1",style:{whiteSpace:"pre-wrap"},children:t.overview}),r&&e.jsxs("button",{onClick:()=>n(a=>!a),className:"text-muted-foreground text-xs mt-1 inline-flex items-center gap-1 hover:text-foreground",children:[s?e.jsx(hr,{className:"w-3 h-3"}):e.jsx(Ot,{className:"w-3 h-3"}),s?"Less":"Decisions, commitments and follow-ups"]}),s&&e.jsxs("div",{className:"text-sm text-foreground",children:[t.decisions.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-muted-foreground text-xs uppercase tracking-wider",children:"Decisions"}),e.jsx("ul",{style:{margin:0,paddingLeft:18},children:t.decisions.map((a,o)=>e.jsx("li",{children:a},o))})]}),t.commitments.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-muted-foreground text-xs uppercase tracking-wider",children:"Commitments"}),e.jsx("ul",{style:{margin:0,paddingLeft:18},children:t.commitments.map((a,o)=>e.jsxs("li",{children:[a.text,a.owner?e.jsxs("span",{className:"text-muted-foreground",children:[" â ",a.owner]}):null,a.dueDate?e.jsxs("span",{className:"text-muted-foreground",children:[" · ",a.dueDate]}):null]},o))})]}),t.followUps.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-muted-foreground text-xs uppercase tracking-wider",children:"Follow-ups"}),e.jsx("ul",{style:{margin:0,paddingLeft:18},children:t.followUps.map((a,o)=>e.jsx("li",{children:a},o))})]})]})]})}function XE({callSid:t}){const[s,n]=l.useState(!1),r=async()=>
76{if(!s){n(!0);try{const a=await re("retryCallSummary",{callSid:t},void 0,{timeoutMs:54e4});a!=null&&a.ok?ce.success("Recap ready"):ce.error((a==null?void 0:a.error)||"The recap failed again")}catch(a){console.error("[voice] recap retry failed:",a),ce.error((a==null?void 0:a.message)||"Could not retry the recap")}finally{n(!1)}}};return e.jsxs("button",{onClick:r,disabled:s,className:"text-primary text-sm mt-1 inline-flex items-center gap-1 hover:underline disabled:opacity-50",children:[e.jsx(yt,{className:`w-3 h-3${s?" animate-spin":""}`}),s?"Summarisingâ¦":"Retry recap"]})}function eI({callSid:t,seconds:s}){const[n,r]=l.useState(null),[a,o]=l.useState(!1);l.useEffect(()=>()=>{n&&URL.revokeObjectURL(n)},[n]);const i=async()=>{if(!(a||n)){o(!0);try{const d=await re("getCallRecording",{callSid:t},void 0,{timeoutMs:12e4}),m=Uint8Array.from(atob(d.base64),p=>p.charCodeAt(0));r(URL.createObjectURL(new Blob([m],{type:d.mimeType||"audio/mpeg"})))}catch(d){console.error("[voice] recording fetch failed:",d),ce.error((d==null?void 0:d.message)||"Could not load the recording")}finally{o(!1)}}};return n?e.jsx("audio",{controls:!0,autoPlay:!0,src:n,className:"mt-2 w-full",style:{maxWidth:360}}):e.jsxs("button",{onClick:i,disabled:a,className:"text-primary text-sm mt-2 inline-flex items-center gap-1 hover:underline disabled:opacity-50",children:[e.jsx(In,{className:"w-3 h-3"}),a?"Loading recordingâ¦":`Play recording${s?` (${Su(s)})`:""}`]})}function Xu({ticketId:t,clientId:s,createdBy:n,max:r=20,title:a="Calls"}){const o=ti(),[i,d]=l.useState([]),[m,p]=l.useState(!1),[c,u]=l.useState(null),x=KE({ticketId:t,clientId:s,createdBy:n});return l.useEffect(()=>{if(!o||!x)return;const h=Ge(Re(ge,"calls"),Ve(x.field,"==",x.value),Nt("startedAt","desc"),Tt(r)),b=qt(h,f=>{d(f.docs.map(g=>({id:g.id,...g.data()}))),p(!0)},f=>{console.error("[voice] call history subscription failed:",f),p(!0)});return()=>b()},[x==null?void 0:x.field,x==null?void 0:x.value,r,o]),!o||m&&i.length===0?null:e.jsxs("div",{className:"mt-4",children:[e.jsx(Sg,{open:!!c,call:c,onClose:()=>u(null)}),e.jsx("h3",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-1",children:a}),e.jsx("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm",children:i.map((h,b)=>{var v,T;const f=GE.has(h.status||""),g=(T=(v=h.startedAt)==null?void 0:v.toDate)==null?void 0:T.call(v),y=QE(h),j=JE(h);return e.jsxs("div",{className:`p-3 flex items-start gap-3 ${b>0?"border-t border-border":""}`,children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-muted flex items-center justify-center flex-shrink-0",children:f?e.jsx(iN,{className:"w-4 h-4 text-destructive"}):h.status==="completed"?e.jsx(cN,{className:"w-4 h-4 text-primary"}):e.jsx(oN,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-foreground text-sm truncate",children:cn(h.to)}),y&&e.jsxs("span",{className:"text-xs text-muted-foreground bg-muted rounded-full inline-flex items-center gap-1",style:{padding:"1px 8px"},children:[e.jsx(_r,{className:"w-3 h-3"}),y]})]}),e.jsxs("p",{className:"text-muted-foreground text-sm",children:[g?g.toLocaleString():"â",h.durationSeconds?` ⢠${Su(h.durationSeconds)}`:f?` ⢠${h.status}`:"",h.createdByEmail?` ⢠${h.createdByEmail}`:""]}),h.summary&&e.jsx(ZE,{summary:h.summary}),j&&e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:j}),h.summaryState==="failed"&&h.recordingSid&&e.jsx(XE,{callSid:h.id}),h.recordingSid&&e.jsx(eI,{callSid:h.id,seconds:h.recordingDurationSeconds}),h.notes&&e.jsx("p",{className:"text-foreground text-sm mt-1",children:h.notes}),e.jsxs("button",{onClick:()=>u({callSid:h.id,clientId:h.clientId??null,ticketId:h.ticketId??null,ticketDisplayId:h.ticketDisplayId??null}),className:"text-muted-foreground text-xs mt-2 inline-flex items-center gap-1 hover:text-foreground",children:[e.jsx(_r,{className:"w-3 h-3"}),h.ticketId?"Change ticket":"Attach to ticket"]})]})]},h.id)})})]})}const tI={ghost:{bg:"transparent",fg:"var(--muted-foreground)",hbg:"var(--muted)",hfg:"var(--foreground)"},ghostDanger:{bg:"transparent",fg:"var(--muted-foreground)",hbg:"#fee2e2",hfg:"#b91c1c"},active:{bg:"rgba(236,203,123,0.28)",fg:"#9a7d2e",hbg:"rgba(236,203,123,0.42)",hfg:"#7a6324"},primary:{bg:"#0ea5e9",fg:"#ffffff",hbg:"#0284c7",hfg:"#ffffff"},danger:{bg:"#ef4444",fg:"#ffffff",hbg:"#dc2626",hfg:"#ffffff"}};function na({icon:t,label:s,onClick:n,variant:r="ghost",disabled:a=!1,busy:o=!1}){const i=tI[r];return e.jsx("button",{type:"button",onClick:n,disabled:a||o,title:s,"aria-label":s,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:36,height:36,borderRadius:9,border:"none",background:i.bg,color:i.fg,cursor:a||o?"default":"pointer",opacity:a?.5:1,transition:"background 120ms ease, color 120ms ease"},onMouseEnter:d=>{a||o||(d.currentTarget.style.background=i.hbg,d.currentTarget.style.color=i.hfg)},onMouseLeave:d=>{d.currentTarget.style.background=i.bg,d.currentTarget.style.color=i.fg},children:o?e.jsx(fe,{style:{width:16,height:16,animation:"spin 1s linear infinite"}}):e.jsx(t,{style:{width:16,height:16}})})}function sI(t){return t?t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(0)} KB`:t<1024*1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${(t/1024/1024/1024).toFixed(2)} GB`:"0 B"}function nI({ticketId:t,clientId:s,projectId:n,projectName:r,authToken:a}
76){const[o,i]=l.useState(null),[d,m]=l.useState(null),[p,c]=l.useState(!1),[u,x]=l.useState(!1);l.useEffect(()=>{let y=!1;if(i(null),m(null),x(!1),!(!s||!a))return(async()=>{try{const j=await fetch(`https://us-central1-bucky-app-355a3.cloudfunctions.net/intakeTicketAssets?ticket=${encodeURIComponent(t)}`,{headers:{Authorization:`Bearer ${a}`}});if(!j.ok)throw new Error(`Failed to load project files (${j.status})`);const v=await j.json();y||i({project:v.projectAssets||[],others:v.otherClientAssets||[]})}catch(j){y||m((j==null?void 0:j.message)||"Failed to load project files")}})(),()=>{y=!0}},[t,s,n,a]);const h=l.useCallback(async y=>{if(!(p||y.length===0)){c(!0),m(null);try{const j=await re("intakeZipAssets",{assetIds:y},a||void 0);j!=null&&j.url&&window.open(j.url,"_blank")}catch(j){m((j==null?void 0:j.message)||"Zip failed")}finally{c(!1)}}},[p,a]);if(!s)return null;const b=(o==null?void 0:o.project)||[],f=(o==null?void 0:o.others)||[];if(o&&b.length===0&&f.length===0&&!d)return null;const g=y=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("div",{className:"bg-muted",style:{width:32,height:32,borderRadius:6,overflow:"hidden",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:y.thumbUrl?e.jsx("img",{src:y.thumbUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):e.jsx(Hw,{size:14,className:"text-muted-foreground"})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("p",{className:"text-sm text-foreground",style:{margin:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y.filename}),e.jsx("p",{className:"text-xs text-muted-foreground",style:{margin:0},children:sI(y.sizeBytes)})]}),e.jsxs("a",{href:y.downloadUrl,className:"text-primary",title:`Download ${y.filename}`,style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:12,textDecoration:"none",flexShrink:0},children:[e.jsx(zr,{size:14})," Download"]})]},y.id);return e.jsxs(e.Fragment,{children:[e.jsx(De,{title:n?`Project Files${r?` â ${r}`:""}`:"Client Files"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[d&&e.jsx("span",{style:{fontSize:12,color:"#dc2626"},children:d}),!o&&!d&&e.jsxs("span",{className:"text-xs text-muted-foreground",style:{display:"inline-flex",alignItems:"center",gap:6},children:[e.jsx(fe,{size:12,style:{animation:"spin 1s linear infinite"}})," Loading filesâ¦"]}),b.map(g),n&&o&&b.length===0&&!d&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No files assigned to this project yet."}),(b.length>0||!n&&f.length>0)&&e.jsxs("button",{type:"button",disabled:p,onClick:()=>h((b.length>0?b:f).map(y=>y.id)),className:"text-primary border border-border bg-card",style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12,fontWeight:500,padding:"6px 10px",borderRadius:8,width:"fit-content",cursor:p?"default":"pointer"},children:[p?e.jsx(fe,{size:13,style:{animation:"spin 1s linear infinite"}}):e.jsx(zr,{size:13}),p?"Zippingâ¦":"Download all (.zip)"]}),n&&f.length>0&&e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>x(!u),className:"text-muted-foreground hover:text-foreground",style:{border:"none",background:"transparent",cursor:"pointer",fontSize:12,padding:0},children:[u?"â¾":"â¸"," Other files for ",`this client (${f.length})`]}),u&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:8},children:f.map(g)})]})]})]})}const rI={sent_for_approval:{label:"Approval email sent",color:"text-blue-500",dot:"#3b82f6"},approved:{label:"Cycle approved",color:"text-green-500",dot:"#22c55e"},portal_opened:{label:"Approval page opened",color:"text-yellow-500",dot:"#eab308"},rush_requested:{label:"Rush requested",color:"text-orange-500",dot:"#f97316"},rush_removed:{label:"Rush removed",color:"text-muted-foreground",dot:"#9ca3af"},approved_card_on_file:{label:"Approved â card charged",color:"text-green-500",dot:"#22c55e"},process_email_sent:{label:"Process email sent",color:"text-blue-500",dot:"#3b82f6"},qa_questionnaire_sent:{label:"QA questionnaire sent",color:"text-blue-500",dot:"#3b82f6"},qa_questionnaire_submitted:{label:"QA questionnaire submitted",color:"text-cyan-500",dot:"#06b6d4"},review_requested:{label:"Review email sent",color:"text-blue-500",dot:"#3b82f6"},reminder_sent:{label:"Reminder sent",color:"text-orange-500",dot:"#f97316"},client_approved:{label:"Approved by client",color:"text-green-500",dot:"#22c55e"},changes_requested:{label:"Changes requested",color:"text-orange-500",dot:"#f97316"},launch_scheduled:{label:"Launch scheduled",color:"text-green-500",dot:"#22c55e"},email_delivered:{label:"Email delivered",color:"text-blue-400",dot:"#60a5fa"},email_opened:{label:"Email opened",color:"text-cyan-500",dot:"#06b6d4"},email_bounced:{label:"Email bounced",color:"text-red-500",dot:"#ef4444"},email_blocked:{label:"Email blocked",color:"text-red-500",dot:"#ef4444"},email_spam:{label:"Marked as spam",color:"text-red-500",dot:"#ef4444"},email_unsubscribed:{label:"Unsubscribed",color:"text-red-500",dot:"#ef4444"}};function ur(t){var s;return((s=sr(t))==null?void 0:s.getTime())??0}function aI(t){const s=ur(t);
76return s?new Date(s).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):""}function Hc(t){const s=ur(t);return s?new Date(s).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):""}function ix(t){const s=Math.floor(t/6e4),n=Math.floor(s/1440),r=Math.floor(s%1440/60),a=s%60;return n>0?`${n}d ${r}h`:r>0?`${r}h ${a}m`:`${a}m`}function sy({ticket:t,rows:s,updateRow:n,deleteRow:r,onClose:a,onSelect:o,onPrev:i,onNext:d,hasPrev:m,hasNext:p,positionLabel:c,onAfterWrite:u}){var fn,Vt,rr,Cr,Qr;const[x,h]=l.useState(t),[b,f]=l.useState(null),[g,y]=l.useState(""),j=l.useRef(!1),v=l.useRef(null),T=l.useRef(null),[k,w]=l.useState(!1),[I,A]=l.useState(!1),{unmergeTicket:E,unmerging:C,error:N}=ty(),[S,O]=l.useState(!1);l.useEffect(()=>{h(t),f(null),O(!1),w(!1),A(!1)},[t.id]);const{rows:R}=Xt({collectionName:"clients",orderByField:"name",orderDirection:"asc"}),{rows:z}=Xt({collectionName:"clientProjects",orderByField:"name",orderDirection:"asc"}),{rows:D}=Xt({collectionName:"shopifyStores",orderByField:"name",orderDirection:"asc"}),L=l.useMemo(()=>R.map(le=>({id:le.id,label:le.name})),[R]),$=l.useMemo(()=>D.map(le=>({id:le.id,label:le.myshopifyUrl||le.name})),[D]),q=l.useMemo(()=>x.clientId?z.filter(le=>le.clientId===x.clientId).map(le=>({id:le.id,label:le.name})):z.map(le=>({id:le.id,label:le.name})),[z,x.clientId]),P=l.useCallback(async le=>{await n(x.id,le),h(Ie=>({...Ie,...le})),u==null||u()},[x.id,n,u]),U=l.useCallback(()=>{var Ht,At;const le=(((Ht=v.current)==null?void 0:Ht.value)||"").trim(),Ie=(((At=T.current)==null?void 0:At.value)||"").trim(),Ke=Ie?{name:le,email:Ie}:null,Fe=x.clientApprover||null;((Fe==null?void 0:Fe.name)||"")===((Ke==null?void 0:Ke.name)||"")&&((Fe==null?void 0:Fe.email)||"")===((Ke==null?void 0:Ke.email)||"")||P({clientApprover:Ke})},[P,x.clientApprover]),V=l.useCallback(async le=>{await P({clientId:le.id,clientName:le.label,projectId:null,projectName:null})},[P]),M=l.useCallback(async le=>{await P({projectId:le.id,projectName:le.label})},[P]),F=l.useCallback(async le=>{await P({shopifyStoreId:le.id,shopifyStoreUrl:le.label})},[P]),W=(le,Ie)=>{f(le),y(Ie)},_=l.useCallback(async()=>{if(!b)return;const Ie=["creditsMin","creditsMax","internalTimeInMins"].includes(b)?g===""?null:Number(g):g;await P({[b]:Ie}),f(null)},[b,g,P]),G=(()=>{const le=x.promisedDate,Ie=le!=null&&le.toMillis?le.toMillis():le!=null&&le.seconds?le.seconds*1e3:typeof le=="string"?Date.parse(le):null;return Ie?new Date(Ie).toISOString().slice(0,10):""})(),B=le=>le?ja.fromDate(new Date(`${le}T00:00:00Z`)):null,[Y,J]=l.useState(null),H=l.useCallback(async(le,Ie)=>{if(le==="promisedDate"){await P({promisedDate:B(Ie)});return}if(le==="status"&&Ie==="In Queue"&&!x.promisedDate){J({date:"",loading:!0});try{const Ke=await re("getTicketCompletionEstimate",{ticketId:x.id});J({date:typeof(Ke==null?void 0:Ke.completionDate)=="string"?Ke.completionDate:"",loading:!1})}catch{J({date:"",loading:!1})}return}await P({[le]:Ie})},[P,x.id,x.promisedDate]),Z=l.useCallback(async()=>{Y!=null&&Y.date&&(await P({promisedDate:B(Y.date),status:"In Queue",inQueueAt:ja.now()}),J(null))},[P,Y]),[Q,K]=l.useState(null),X=l.useCallback(async le=>{try{const Ie=await ps(ut(ge,"creditEstimates",le));if(!Ie.exists()){K(null);return}const Ke=Ie.data();if(!Ke||typeof Ke!="object")throw new Error("Invalid estimate data");K(Ke)}catch(Ie){console.error("Error loading estimate:",Ie),K(null)}},[]);l.useEffect(()=>{X(x.id)},[x.id,X]);const{user:se}=pt(),[pe,me]=l.useState(null);l.useEffect(()=>{let le=!1;if(!se){me(null);return}return se.getIdToken().then(Ie=>{le||me(Ie)}).catch(()=>{}),()=>{le=!0}},[se]);const Ne=l.useRef(null),[at,ae]=l.useState(!1),[xe,ze]=l.useState(!1),[Le,ht]=l.useState(null),ue=l.useCallback(async le=>{if(!se){ht("Authentication required");return}ze(!0),ht(null);try{const Ie=pe||await se.getIdToken(),Ke=await new Promise((At,gn)=>{const Zs=new FileReader;Zs.readAsDataURL(le),Zs.onload=()=>At(Zs.result),Zs.onerror=()=>gn(new Error("Failed to read file"))}),Fe=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/uploadTicketAttachment",{method:"POST",headers:{Authorization:`Bearer ${Ie}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:x.id,fileName:le.name,contentType:le.type,dataBase64:Ke})});if(!Fe.ok){let At="Upload failed";try{At=(await Fe.json()).error||At}catch{}throw new Error(At)}const{attachment:Ht}=await Fe.json();h(At=>({...At,attachments:[...At.attachments||[],Ht]}))}catch(Ie){ht((Ie==null?void 0:Ie.message)||"Upload failed")}finally{ze(!1)}},[se,pe,x.id]),we=l.useCallback(le=>{le&&Array.from(le).forEach(Ie=>{ue(Ie)})},[ue]),Be=l.useCallback(async le=>{if(!se){ht("Authentication required");return}if(window.confirm("Remove this attachment?")){ht(null);try{const Ie=pe||await se.getIdToken(),Ke=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/removeTicketAttachment",{method:"POST",headers:{Authorization:`Bearer ${Ie}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:x.id,url:le})});if(!Ke.ok){let Fe="Remove failed";try{Fe=(await Ke.json()).error||Fe}catch{}throw new Error(Fe)}h(Fe=>({...Fe,attachments:(Fe.attachments||[]).filter(Ht=>(typeof Ht=="string"?Ht:Ht.url)!==le)}))}catch(Ie){ht((Ie==null?void 0:Ie.message)||"Remove failed")}}},[se,pe,x.id]),[Ye,rt]=l.useState(!1),[te,ve]=l.useState(!1),[Ae,We]=l.useState(null),[ie,Ue]=l.useState(!1),[Te,He]=l.useState(!1),[Oe,Je]=l.useState(!1),[de,je]=l.useState(!1),[qe,he]=l.useState(!1);l.useEffect(()=>{je(!1)},[t.id]);const lt=l.useCallback(async()=>{he(!0);try{await r(x.id),a()}catch(le){console.error("Error deleting ticket:",le)}finally{he(!1)}},[r,x.id,a]);l.useEffect(()=>{Ue(!!(se!=null&&se.uid&&Array.isArray(x.followers)&&x.followers.includes(se.uid)))},[se==null?void 0:se.uid,x.followers]);const tt=l.useCallback(async()=>
76{if(!(se!=null&&se.uid)||Te)return;const le=!ie;Ue(le),He(!0);try{const Ie=await re("toggleTicketFollow",{ticketId:x.id},pe||void 0);typeof(Ie==null?void 0:Ie.following)=="boolean"&&Ue(Ie.following)}catch{Ue(!le)}finally{He(!1)}},[se==null?void 0:se.uid,Te,ie,x.id,pe]),Se=l.useCallback(async le=>{if(!se){We("Authentication required");return}ve(!0),We(null);try{const Ie=pe||await se.getIdToken();if(!Ie)throw new Error("Failed to retrieve authentication token");const Ke=await fetch("https://estimateticketcredits-jf3ot2tygq-uc.a.run.app",{method:"POST",headers:{Authorization:`Bearer ${Ie}`,"Content-Type":"application/json"},body:JSON.stringify({ticketId:le,urgency:"medium",businessValue:"medium"})});if(!Ke.ok){let Fe={};try{Fe=await Ke.json()}catch{}throw new Error(Fe.error||`Failed: ${Ke.status}`)}await X(le)}catch(Ie){console.error("Error re-estimating ticket:",Ie),We(Ie.message||"Failed to re-scope ticket")}finally{ve(!1)}},[se,pe,X]),es=l.useCallback(async()=>{await Se(x.id)},[x.id,Se]),_e=x.status==="In Review"||x.status==="Client Approval",St=l.useCallback(async()=>{if(x.status==="In Review"||x.status==="Client Approval"){A(!0);return}await P({status:"Awaiting Approval"}),w(!0)},[x.status,P]),$t=l.useCallback(async()=>{A(!1),x.status!=="Client Approval"&&await P({status:"Client Approval"})},[x.status,P]),Ct=l.useCallback(async()=>{b&&await _(),a()},[b,_,a]);l.useEffect(()=>{if(b)return;const le=Ke=>{if(Ke instanceof HTMLElement){const Fe=Ke.tagName;return Fe==="INPUT"||Fe==="TEXTAREA"||Ke.isContentEditable}return!1},Ie=Ke=>{le(Ke.target)||(Ke.key==="ArrowLeft"&&m&&i?(Ke.preventDefault(),i()):Ke.key==="ArrowRight"&&p&&d&&(Ke.preventDefault(),d()))};return window.addEventListener("keydown",Ie),()=>window.removeEventListener("keydown",Ie)},[b,i,d,m,p]);const ot={editField:b,editValue:g,onEdit:W,onSave:_,onEditValueChange:y};return e.jsxs(e.Fragment,{children:[e.jsxs(Cs,{title:x.displayId,onClose:a,onPrev:i,onNext:d,hasPrev:m,hasNext:p,positionLabel:c,footer:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%",gap:12},children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:6},children:de?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#b91c1c"},children:"Delete this ticket?"}),e.jsx(na,{icon:kt,label:"Confirm delete",variant:"danger",busy:qe,onClick:lt}),e.jsx(na,{icon:mt,label:"Keep ticket",variant:"ghost",onClick:()=>je(!1)})]}):e.jsxs(e.Fragment,{children:[e.jsx(na,{icon:zs,label:"Delete ticket",variant:"ghostDanger",onClick:()=>je(!0)}),e.jsx("div",{style:{width:1,height:20,background:"var(--border)",margin:"0 4px"}}),e.jsx(na,{icon:ie?Xf:Dn,label:ie?"Following â click to stop":"Follow for updates",variant:ie?"active":"ghost",busy:Te,onClick:tt}),e.jsxs("div",{style:{position:"relative"},children:[e.jsx(na,{icon:Zf,label:"Reminders",variant:Oe?"active":"ghost",onClick:()=>Je(le=>!le)}),Oe&&e.jsx(FT,{ticketId:x.id,authToken:pe,onClose:()=>Je(!1),onFollowChange:Ue})]}),e.jsx(YE,{ticketId:x.id,clientId:x.clientId,iconOnly:!0})]})}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsxs("button",{onClick:St,style:{display:"inline-flex",alignItems:"center",gap:6,height:36,padding:"0 16px",borderRadius:9,fontSize:13,fontWeight:600,cursor:"pointer",backgroundColor:"transparent",color:"#0ea5e9",border:"1px solid #0ea5e9",transition:"background-color 120ms ease"},onMouseEnter:le=>{le.currentTarget.style.backgroundColor="#e0f2fe"},onMouseLeave:le=>{le.currentTarget.style.backgroundColor="transparent"},children:[e.jsx(An,{style:{width:15,height:15}}),_e?"Send for Review":"Send for Approval"]}),e.jsx(na,{icon:kt,label:"Save & close",variant:"primary",onClick:Ct})]})]}),children:[e.jsx(De,{title:"Details"}),e.jsx(oe,{label:"Name",value:x.name,field:"name",...ot}),e.jsx(oe,{label:"Status",value:x.status,field:"status",...ot,options:hl,optionLabels:Bg,onDirectSave:H}),Y&&e.jsxs("div",{style:{background:"color-mix(in srgb, var(--secondary, #eccb7b) 18%, var(--card, #fff))",border:"1px solid var(--secondary, #eccb7b)",borderRadius:8,padding:"10px 12px",display:"flex",flexDirection:"column",gap:8},children:[e.jsx("div",{className:"text-sm text-foreground",style:{fontWeight:600},children:"Estimated completion before queuing"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[`The customer's ticket card counts down to this date and the lane gets "approved â we're on it". `,Y.loading?"Calculating from capacityâ¦"
76:"Pre-filled from today's capacity forecast."]}),e.jsx("input",{type:"date",value:Y.date,onChange:le=>J({date:le.target.value,loading:!1}),className:"bg-background border border-border text-sm text-foreground",style:{display:"block",width:"100%",padding:"8px 12px",borderRadius:8}}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx("button",{onClick:()=>J(null),className:"text-sm text-muted-foreground",style:{padding:"6px 12px"},children:"Cancel"}),e.jsx("button",{onClick:Z,disabled:!Y.date||Y.loading,className:"bg-primary text-primary-foreground text-sm",style:{padding:"6px 14px",borderRadius:8,fontWeight:600,opacity:!Y.date||Y.loading?.5:1},children:"Approve & queue"})]})]}),e.jsx(oe,{label:"Estimated completion",value:G,field:"promisedDate",...ot,date:!0,onDirectSave:H}),e.jsx(oe,{label:"Complexity",value:x.ticketComplexity||"",field:"ticketComplexity",...ot,options:Fg,onDirectSave:H,buttonGroup:!0}),e.jsx(oe,{label:"Rush Order",value:"",field:"rushOrder",...ot,checkbox:!0,checked:x.rushOrder,onDirectSave:H}),e.jsx(De,{title:"Client & Project"}),e.jsx(oe,{label:"Client",value:x.clientName||"",field:"clientName",...ot,lookupItems:L,onLookupSelect:V}),e.jsx(oe,{label:"Project",value:x.projectName||"",field:"projectName",...ot,lookupItems:q,onLookupSelect:M}),e.jsx(oe,{label:"Shopify Store",value:x.shopifyStoreUrl||"",field:"shopifyStoreUrl",...ot,lookupItems:$,onLookupSelect:F}),e.jsx(oe,{label:"Department",value:x.department||"",field:"department",...ot,options:["",...Io],onDirectSave:H}),e.jsx(De,{title:"Content"}),b==="content"?e.jsx("div",{children:e.jsx("textarea",{autoFocus:!0,value:g,onChange:le=>y(le.target.value),onKeyDown:le=>{le.key==="Escape"&&(j.current=!0,f(null))},onBlur:()=>{j.current||_(),j.current=!1},rows:10,className:"bg-background border border-primary text-sm text-foreground focus:outline-none",style:{width:"100%",padding:"8px 12px",borderRadius:8,resize:"vertical"}})}):e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Content"}),e.jsxs("button",{onClick:()=>W("content",x.content||""),className:"text-muted-foreground hover:text-foreground",style:{display:"flex",alignItems:"center",gap:4,fontSize:12},children:[e.jsx(Na,{style:{width:12,height:12}})," Edit"]})]}),e.jsx("div",{className:"bg-background border border-border text-sm text-foreground prose prose-sm dark:prose-invert max-w-none prose-headings:mt-3 prose-headings:mb-1 prose-p:my-1 prose-ul:my-1 prose-ol:my-1 prose-li:my-0",style:{padding:12,borderRadius:8,maxHeight:300,overflowY:"auto"},children:x.content?e.jsx(Ta,{children:x.content}):e.jsx("span",{className:"text-muted-foreground italic",children:"No content"})})]}),e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"Attachments"}),(()=>{const le=(x.attachments||[]).map(Fe=>typeof Fe=="string"?{url:Fe,name:Fe.split("/").pop()||"file",isImage:/\.(png|jpe?g|gif|webp|svg)$/i.test(Fe)}:Fe),Ie=le.filter(Fe=>Fe.isImage),Ke=le.filter(Fe=>!Fe.isImage);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[Ie.length>0&&e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8},children:Ie.map((Fe,Ht)=>e.jsxs("div",{style:{position:"relative"},children:[e.jsx("a",{href:Fe.url,target:"_blank",rel:"noopener noreferrer",style:{display:"block",aspectRatio:"1",borderRadius:8,overflow:"hidden",border:"1px solid var(--border)"},children:e.jsx("img",{src:Fe.url,alt:Fe.name,style:{width:"100%",height:"100%",objectFit:"cover"}})}),e.jsx("button",{type:"button",title:"Remove attachment",onClick:At=>{At.preventDefault(),At.stopPropagation(),Be(Fe.url)},style:{position:"absolute",top:4,right:4,width:22,height:22,borderRadius:"50%",border:"none",background:"rgba(0,0,0,0.6)",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:0},children:e.jsx(mt,{size:13})})]},Ht))}),Ke.map((Fe,Ht)=>e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:6,width:"fit-content"},children:[e.jsxs("a",{href:Fe.url,target:"_blank",rel:"noopener noreferrer",className:"bg-background border border-border text-sm text-foreground",style:{display:"inline-flex",alignItems:"center",gap:8,padding:"6px 10px",borderRadius:8,textDecoration:"none"},children:[e.jsx(mm,{size:14})," ",Fe.name]}),e.jsx("button",{type:"button",title:"Remove attachment",onClick:()=>void Be(Fe.url),className:"text-muted-foreground hover:text-red-600",style:{border:"none",background:"transparent",curs
76or:"pointer",padding:2,display:"inline-flex"},children:e.jsx(mt,{size:14})})]},Ht)),e.jsxs("div",{onDragOver:Fe=>{Fe.preventDefault(),ae(!0)},onDragLeave:()=>ae(!1),onDrop:Fe=>{Fe.preventDefault(),ae(!1),we(Fe.dataTransfer.files)},onClick:()=>{var Fe;return(Fe=Ne.current)==null?void 0:Fe.click()},className:`flex flex-col items-center justify-center gap-2 border-2 border-dashed rounded-lg cursor-pointer transition-colors ${at?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"}`,style:{padding:16},children:[xe?e.jsx(fe,{className:"animate-spin",size:18}):e.jsx(mm,{size:18,className:"text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:xe?"Uploadingâ¦":at?"Drop files here":"Drop images/files here or click to browse"}),e.jsx("input",{ref:Ne,type:"file",multiple:!0,className:"hidden",onChange:Fe=>{we(Fe.target.files),Fe.target.value=""}})]}),Le&&e.jsx("span",{style:{fontSize:12,color:"#dc2626"},children:Le})]})})()]}),e.jsx(nI,{ticketId:x.id,clientId:x.clientId||null,projectId:x.projectId||null,projectName:x.projectName||null,authToken:pe}),((fn=x.screenshots)==null?void 0:fn.length)>0&&(()=>{var Zs;const le=x.screenshots.filter(Yt=>Yt.includes("_viewport")),Ie=x.screenshots.filter(Yt=>Yt.includes("_fullpage")),Ke=x.screenshots.filter(Yt=>!Yt.includes("_viewport")&&!Yt.includes("_fullpage")),Fe=x.captureMousePosition,Ht=x.captureViewport,At=Fe&&Ht&&Fe.x>0&&Fe.y>0?`${Fe.x/Ht.width*100}% ${Fe.y/(Ht.height*3)*100}%`:"center center",gn=(Yt,is,ne)=>e.jsx("a",{href:Yt,target:"_blank",rel:"noopener noreferrer",style:{display:"block",width:"100%",aspectRatio:ne?"16/9":"1",borderRadius:10,overflow:"hidden",border:"1px solid var(--border)"},children:e.jsx("img",{src:Yt,alt:ne?`Viewport ${is+1}`:`Full Page ${is+1}`,style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:ne?"center center":At}})},is);return e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"Capture"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[le.length>0&&e.jsxs("div",{children:[e.jsx("span",{style:{fontSize:11,fontWeight:600,color:"var(--muted-foreground)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:6,display:"block"},children:"Viewport"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:le.map((Yt,is)=>gn(Yt,is,!0))})]}),Ie.length>0&&e.jsxs("div",{children:[e.jsx("span",{style:{fontSize:11,fontWeight:600,color:"var(--muted-foreground)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:6,display:"block"},children:"Full Page"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Ie.map((Yt,is)=>gn(Yt,is,!1))})]}),Ke.length>0&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Ke.map((Yt,is)=>gn(Yt,is,!1))})]}),x.pageUrl&&e.jsxs("div",{style:{fontSize:12,color:"var(--muted-foreground)",marginTop:8},children:["Page: ",e.jsx("a",{href:x.pageUrl,target:"_blank",rel:"noopener noreferrer",style:{color:"#5ab2d8"},children:x.pageUrl})]}),e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",marginTop:8,fontSize:12,color:"var(--muted-foreground)"},children:[x.captureViewport&&e.jsxs("span",{children:["Viewport: ",x.captureViewport.width,"x",x.captureViewport.height," @",x.captureViewport.deviceScaleFactor,"x"]}),x.captureBrowser&&e.jsxs("span",{children:["Browser: ",x.captureBrowser]}),x.captureOS&&e.jsxs("span",{children:["OS: ",x.captureOS]}),x.captureScrollDepth!=null&&e.jsxs("span",{children:["Scroll: ",x.captureScrollDepth,"%"]})]}),((Zs=x.captureConsoleErrors)==null?void 0:Zs.length)>0&&e.jsxs("div",{style:{marginTop:8},children:[e.jsxs("span",{style:{fontSize:11,fontWeight:600,color:"#dc2626",textTransform:"uppercase",letterSpacing:"0.05em"},children:["Console Errors (",x.captureConsoleErrors.length,")"]}),e.jsx("div",{style:{marginTop:4,padding:"8px 10px",borderRadius:6,backgroundColor:"rgba(220,38,38,0.06)",border:"1px solid rgba(220,38,38,0.15)",maxHeight:120,overflowY:"auto"},children:x.captureConsoleErrors.map((Yt,is)=>e.jsx("div",{style:{fontSize:11,fontFamily:"monospace",color:"#dc2626",marginBottom:is<x.captureConsoleErrors.length-1?4:0},children:Yt.message},is))})]})]})})(),e.jsx(De,{title:"Scope & Credits"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(oe,{label:"Credits Min",value:x.creditsMin!=null?String(x.creditsMin):"",field:"creditsMin",...ot,numeric:!0}),e.jsx(oe,{label:"Credits Max",value:x.creditsMax!=null?String(x.creditsMax):"",field:"creditsMax",...ot,numeric:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(oe,{label:"Internal Time Estimate",value:x.internalTimeEstimate||"",field:"internalTimeEstimate",...ot}),e.jsx(oe,{label:"Internal Time (mins)",value:x.internalTimeInMins!=null?String(x.internalTimeInMins):"",field:"internalTimeInMins",...ot,numeric:!0})]}),Q&&e.jsxs("div",{className:"bg-background border border-border",style:{padding:12,borderRadius:8},children:[e.jsx("label",{className:"text-xs text-muted-foreground",style:{display:"block",marginBottom:8},children:"AI Estimate"}),e.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap",marginBottom:10},children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Credits"}),e.jsx("p",{className:"text-foreground",style:{fontSize:18,fontWeight:600},children:Q.estimatedCredits})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Hours"}),e.jsxs("p",{className:"text-foreground",style:{fontSize:18,fontWeight:600},children:[Q.estimatedHours,"h"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Confidence"}),e.jsx("p",{style:{fontSize:13,fontWeight:500,marginTop:2,color:Q.confidence==="high"?"#15803d":Q.confidence==="medium"?"#b45309":"#dc2626"},children:Q.confidence})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Category"}),e.jsx("p",{className:"text-foreground",style:{fontSize:13,marginTop:2},children:Q.taskCategory})]})]}),e.jsxs("div",{style:{marginBottom:8},children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Reasoning"}),e.jsx("p",{className:"text-foreground",style:{fontSize:13,marginTop:2,lineHeight:1.5},children:Q.reasoning})]}),((Vt=Q.recommendations)==null?void 0:Vt.length)>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Recommendations"}),e.jsx("ul",{style:{margin:"4px 0 0 16px",fontSize:13,lineHeight:1.5},className:"text-foreground",children:Q.recommendations.map((le,Ie)=>
76e.jsx("li",{children:le},Ie))})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[e.jsxs("button",{onClick:()=>rt(!0),disabled:te||!pe,style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,padding:"8px 12px",borderRadius:8,border:"none",fontSize:13,fontWeight:600,cursor:te||!pe?"not-allowed":"pointer",backgroundColor:"rgba(90,178,216,0.12)",color:"#0c7aa3",opacity:te||!pe?.6:1},children:[e.jsx(ws,{style:{width:14,height:14}}),"Add More Context"]}),e.jsx("button",{onClick:()=>Se(x.id),disabled:te||!pe,style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,padding:"8px 12px",borderRadius:8,border:"1px solid var(--border)",fontSize:13,fontWeight:600,cursor:te||!pe?"not-allowed":"pointer",backgroundColor:"transparent",color:"var(--foreground)",opacity:te||!pe?.6:1},children:te?e.jsxs(e.Fragment,{children:[e.jsx(fe,{style:{width:14,height:14},className:"animate-spin"}),"Re-scopingâ¦"]}):e.jsx(e.Fragment,{children:"Re-scope"})})]}),Ae&&e.jsx("div",{style:{marginTop:8,fontSize:12,color:"#dc2626"},children:Ae})]}),e.jsx(De,{title:"QA / Stakeholder"}),e.jsx(oe,{label:"Skip QA (no questionnaire)",value:"",field:"qaExempt",...ot,checkbox:!0,checked:!!x.qaExempt,onDirectSave:H}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Approver Name"}),e.jsx("input",{ref:v,defaultValue:((rr=x.clientApprover)==null?void 0:rr.name)||"",onBlur:U,placeholder:"Stakeholder / final say",className:"bg-background border border-border text-sm text-foreground focus:outline-none focus:border-primary",style:{width:"100%",padding:"8px 12px",borderRadius:8,marginTop:4}},`approver-name-${x.id}`)]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Approver Email"}),e.jsx("input",{ref:T,type:"email",defaultValue:((Cr=x.clientApprover)==null?void 0:Cr.email)||"",onBlur:U,placeholder:"[email protected]",className:"bg-background border border-border text-sm text-foreground focus:outline-none focus:border-primary",style:{width:"100%",padding:"8px 12px",borderRadius:8,marginTop:4}},`approver-email-${x.id}`)]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",style:{margin:"8px 0 4px"},children:`Liz emails this person a QA questionnaire when the ticket enters "In Queue". If left blank, the client's primary contact is used.`}),x.qaRequirements&&e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"Client QA Requirements"}),e.jsxs("div",{className:"bg-background border border-border",style:{padding:12,borderRadius:8},children:[[{label:"Expectations",value:x.qaRequirements.expectations},{label:"Expecting to see at review",value:x.qaRequirements.expectedDeliverable},{label:"Keep an eye out for",value:x.qaRequirements.watchOut}].map(le=>e.jsxs("div",{style:{marginBottom:10},children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:le.label}),e.jsx("p",{className:"text-sm text-foreground",style:{margin:"2px 0 0",whiteSpace:"pre-wrap"},children:le.value||"â"})]},le.label)),e.jsxs("p",{className:"text-xs text-muted-foreground",style:{margin:"4px 0 0"},children:["Submitted by ",x.qaRequirements.submittedBy,x.qaRequirements.submittedAt?` · ${nt(x.qaRequirements.submittedAt)}`:""]})]})]}),!x.qaRequirements&&x.qaRequirementsDraft&&e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"AI-suggested QA answers (draft)"}),e.jsxs("div",{className:"bg-background border border-dashed border-border",style:{padding:12,borderRadius:8},children:[[{label:"Expectations",value:x.qaRequirementsDraft.expectations},{label:"Expecting to see at review",value:x.qaRequirementsDraft.expectedDeliverable},{label:"Keep an eye out for",value:x.qaRequirementsDraft.watchOut}].map(le=>e.jsxs("div",{style:{marginBottom:10},children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:le.label}),e.jsx("p",{className:"text-sm text-foreground",style:{margin:"2px 0 0",whiteSpace:"pre-wrap"},children:le.value||"â"})]},le.label)),e.jsxs("p",{className:"text-xs text-muted-foreground",style:{margin:"4px 0 0"},children:["⨠Pre-filled for the client to review & confirm",x.qaRequirementsDraft.generatedAt?` · ${nt
76(x.qaRequirementsDraft.generatedAt)}`:""]})]})]}),x.qaReviewNotes&&x.qaReviewNotes.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"QA Notes"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:x.qaReviewNotes.map(le=>e.jsxs("div",{className:"bg-background border border-border text-sm text-foreground",style:{padding:10,borderRadius:8},children:[e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:le.text}),e.jsxs("div",{className:"text-muted-foreground",style:{fontSize:11,marginTop:4},children:[le.authorName||le.authorEmail||"Staff",le.createdAt?` · ${nt(le.createdAt)}`:"",le.editedAt?" · edited":""]})]},le.id))})]}),e.jsx(De,{title:"Summary"}),b==="summary"?e.jsx("div",{children:e.jsx("textarea",{autoFocus:!0,value:g,onChange:le=>y(le.target.value),onKeyDown:le=>{le.key==="Escape"&&(j.current=!0,f(null))},onBlur:()=>{j.current||_(),j.current=!1},rows:6,className:"bg-background border border-primary text-sm text-foreground focus:outline-none",style:{width:"100%",padding:"8px 12px",borderRadius:8,resize:"vertical"}})}):e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Completion Summary"}),e.jsxs("button",{onClick:()=>W("summary",x.summary||""),className:"text-muted-foreground hover:text-foreground",style:{display:"flex",alignItems:"center",gap:4,fontSize:12},children:[e.jsx(Na,{style:{width:12,height:12}})," Edit"]})]}),e.jsx("div",{className:"bg-background border border-border text-sm text-foreground prose prose-sm dark:prose-invert max-w-none prose-headings:mt-3 prose-headings:mb-1 prose-p:my-1 prose-ul:my-1 prose-ol:my-1 prose-li:my-0",style:{padding:12,borderRadius:8,maxHeight:300,overflowY:"auto"},children:x.summary?e.jsx(Ta,{children:x.summary}):e.jsx("span",{className:"text-muted-foreground italic",children:"No summary yet"})})]}),yo(x)&&e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"Job Report"}),e.jsx(df,{url:yo(x),maxHeight:360}),e.jsxs("div",{style:{display:"flex",gap:12,marginTop:6,fontSize:12,color:"var(--muted-foreground)"},children:[e.jsx("span",{children:x.jobReportVideoUrl?"AI job report video":"Manual review video"}),e.jsx("a",{href:yo(x),target:"_blank",rel:"noopener noreferrer",style:{color:"#5ab2d8"},children:"Open video â"})]})]}),e.jsx(De,{title:"Links"}),e.jsx(oe,{label:"Page URL",value:x.pageUrl||"",field:"pageUrl",...ot}),e.jsx(oe,{label:"Shopify Theme ID",value:x.shopifyThemeId||"",field:"shopifyThemeId",...ot}),e.jsx(oe,{label:"Video Review URL",value:x.videoReviewUrl||"",field:"videoReviewUrl",...ot}),((Qr=x.mergeInfo)==null?void 0:Qr.isMerged)&&e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"Merge Info"}),e.jsxs("div",{style:{padding:"12px 0",fontSize:13},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:x.mergeInfo.sourceTicketDisplayIds.map(le=>{const Ie=s.find(Ke=>Ke.displayId===le);return e.jsxs("button",{onClick:Ke=>{Ke.stopPropagation(),Ie&&o(Ie)},style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",borderRadius:6,border:"1px solid #e2e8f0",backgroundColor:"#fef3c7",cursor:Ie?"pointer":"default",opacity:Ie?1:.6,transition:"background-color 0.15s"},onMouseEnter:Ke=>{Ie&&(Ke.currentTarget.style.backgroundColor="#fde68a")},onMouseLeave:Ke=>{Ke.currentTarget.style.backgroundColor="#fef3c7"},title:Ie?Ie.name:le,children:[e.jsx("span",{style:{fontSize:12,fontFamily:"monospace",fontWeight:600,color:"#92400e"},children:le}),Ie&&e.jsx("span",{style:{fontSize:11,color:"#78716c",maxWidth:120,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Ie.name})]},le)})}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",color:"#a1a1aa"},children:[e.jsx("svg",{width:"32",height:"20",viewBox:"0 0 32 20",fill:"none",children:e.jsx("path",{d:"M2 10h22M20 4l6 6-6 6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e.jsx("span",{style:{fontSize:9,marginTop:1},children:"merged into"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderRadius:6,border:"2px s
76olid #c4b5fd",backgroundColor:"#f3e8ff"},children:[e.jsx("span",{style:{fontSize:12,fontFamily:"monospace",fontWeight:700,color:"#7c3aed"},children:x.displayId}),e.jsx("span",{style:{fontSize:11,color:"#6d28d9",maxWidth:120,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.name})]})]}),e.jsxs("div",{style:{marginTop:10,display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:8},children:[e.jsxs("div",{className:"text-xs text-muted-foreground",style:{display:"flex",gap:12},children:[e.jsx("span",{children:nt(x.mergeInfo.mergedAt)}),e.jsxs("span",{children:["by ",x.mergeInfo.mergedBy]})]}),S?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{className:"text-xs text-destructive",style:{fontWeight:500},children:"Restore original tickets?"}),e.jsx("button",{disabled:C,onClick:async()=>{await E(x.id)&&(O(!1),a())},style:{fontSize:11,padding:"2px 10px",borderRadius:4,fontWeight:600,backgroundColor:"#dc2626",color:"#fff",border:"none",cursor:C?"wait":"pointer",opacity:C?.6:1},children:C?"Unmerging...":"Yes, unmerge"}),e.jsx("button",{onClick:()=>O(!1),style:{fontSize:11,padding:"2px 10px",borderRadius:4,fontWeight:500,border:"1px solid #d4d4d8",cursor:"pointer"},className:"bg-background text-foreground",children:"Cancel"})]}):e.jsxs("button",{onClick:()=>O(!0),className:"text-xs text-muted-foreground hover:text-destructive",style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",borderRadius:4,border:"1px solid transparent",transition:"all 0.15s"},onMouseEnter:le=>{le.currentTarget.style.borderColor="#fca5a5",le.currentTarget.style.backgroundColor="#fef2f2"},onMouseLeave:le=>{le.currentTarget.style.borderColor="transparent",le.currentTarget.style.backgroundColor="transparent"},children:[e.jsx(jg,{size:12}),"Unmerge"]})]}),N&&e.jsx("div",{className:"text-xs text-destructive",style:{marginTop:6},children:N})]})]}),x.archivedByMerge&&(()=>{const le=s.find(Ie=>Ie.id===x.archivedByMerge);return e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"Merge Info"}),e.jsxs("div",{style:{padding:"12px 0",fontSize:13},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",borderRadius:6,border:"1px dashed #d4d4d8",backgroundColor:"#fef3c7",opacity:.8},children:[e.jsx("span",{style:{fontSize:12,fontFamily:"monospace",fontWeight:600,color:"#92400e",textDecoration:"line-through"},children:x.displayId}),e.jsx("span",{style:{fontSize:11,color:"#78716c",maxWidth:120,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.name})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",color:"#a1a1aa"},children:[e.jsx("svg",{width:"32",height:"20",viewBox:"0 0 32 20",fill:"none",children:e.jsx("path",{d:"M2 10h22M20 4l6 6-6 6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e.jsx("span",{style:{fontSize:9,marginTop:1},children:"merged into"})]}),le?e.jsxs("button",{onClick:Ie=>{Ie.stopPropagation(),o(le)},style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderRadius:6,border:"2px solid #c4b5fd",backgroundColor:"#f3e8ff",cursor:"pointer",transition:"background-color 0.15s"},onMouseEnter:Ie=>{Ie.currentTarget.style.backgroundColor="#ede9fe"},onMouseLeave:Ie=>{Ie.currentTarget.style.backgroundColor="#f3e8ff"},title:le.name,children:[e.jsx("span",{style:{fontSize:12,fontFamily:"monospace",fontWeight:700,color:"#7c3aed"},children:le.displayId}),e.jsx("span",{style:{fontSize:11,color:"#6d28d9",maxWidth:120,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:le.name})]}):e.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderRadius:6,border:"2px solid #c4b5fd",backgroundColor:"#f3e8ff"},children:e.jsx("span",{style:{fontSize:12,fontFamily:"monospace",fontWeight:600,color:"#7c3aed"},children:"Merged Ticket"})})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",style:{marginTop:10},children:["This ticket was archived when it was merged into ",le?le.displayId:"another ticket","."]})]})]})})(),e.jsx(De,{title:"Metadata"}),(()=>{const le=x.approvalHistory||[],Ie=Math.min(...le.filter(At=>At.action==="approved"||At.action==="approved_card_on_file").map(At=>
76ur(At.timestamp)).filter(Boolean),1/0),Ke=ur(x.clientApprovedAt)||Math.min(...le.filter(At=>At.action==="client_approved").map(At=>ur(At.timestamp)).filter(Boolean),1/0),Fe=ur(x.createdAt);let Ht="";return Fe&&Ke!==1/0&&Ke>Fe?Ht=ix(Ke-Fe):Fe&&x.status!=="Complete"&&(Ht=`${ix(Date.now()-Fe)} (so far)`),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"10px 16px"},children:[e.jsx(oe,{label:"Created",value:Hc(x.createdAt),field:"",...ot,readOnly:!0}),e.jsx(oe,{label:"Updated",value:Hc(x.updatedAt),field:"",...ot,readOnly:!0}),e.jsx(oe,{label:"Approved",value:Ie!==1/0?Hc(Ie):"â",field:"",...ot,readOnly:!0}),e.jsx(oe,{label:"Total Time",value:Ht||"â",field:"",...ot,readOnly:!0})]})})(),(x.approvalHistory||[]).length>0&&e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"Approval History"}),e.jsx("div",{className:"space-y-2",children:[...x.approvalHistory].sort((le,Ie)=>ur(le.timestamp)-ur(Ie.timestamp)).map((le,Ie)=>{const Ke=rI[le.action]||{label:le.action,color:"text-muted-foreground",dot:"#9ca3af"};return e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{style:{width:8,height:8,borderRadius:9999,backgroundColor:Ke.dot,marginTop:5,flexShrink:0}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:`text-xs font-semibold ${Ke.color}`,children:Ke.label}),le.details&&e.jsx("span",{className:"text-xs text-muted-foreground",style:{marginLeft:6},children:le.details})]}),e.jsx("span",{className:"text-muted-foreground",style:{fontSize:11,whiteSpace:"nowrap",marginTop:1},children:aI(le.timestamp)})]},Ie)})})]}),e.jsx(Xu,{ticketId:x.id})]}),e.jsx(Ug,{open:Ye,onOpenChange:rt,ticketId:x.id,ticketName:x.name,authToken:pe,onContextAdded:es}),k&&e.jsx(qE,{ticketId:x.id,ticketTitle:x.name,ticketNumber:x.displayId,clientName:x.clientName||"",clientId:x.shopifyStoreUrl||void 0,firestoreClientId:x.clientId||void 0,creditsMax:x.creditsMax,onClose:()=>w(!1)}),I&&e.jsx(ey,{ticketId:x.id,ticketTitle:x.name,ticketNumber:x.displayId,clientName:x.clientName||"",clientId:x.shopifyStoreUrl||void 0,firestoreClientId:x.clientId||void 0,onSent:$t,onClose:()=>A(!1)})]})}function ci(t,s,n){const r=t.slice();return r.splice(n<0?r.length+n:n,0,r.splice(s,1)[0]),r}function oI(t,s){return t.reduce((n,r,a)=>{const o=s.get(r);return o&&(n[a]=o),n},Array(t.length))}function vi(t){return t!==null&&t>=0}function iI(t,s){if(t===s)return!0;if(t.length!==s.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==s[n])return!1;return!0}function lI(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}const ny=t=>{let{rects:s,activeIndex:n,overIndex:r,index:a}=t;const o=ci(s,r,n),i=s[a],d=o[a];return!d||!i?null:{x:d.left-i.left,y:d.top-i.top,scaleX:d.width/i.width,scaleY:d.height/i.height}},wi={scaleX:1,scaleY:1},em=t=>{var s;let{activeIndex:n,activeNodeRect:r,index:a,rects:o,overIndex:i}=t;const d=(s=o[n])!=null?s:r;if(!d)return null;if(a===n){const p=o[i];return p?{x:0,y:n<i?p.top+p.height-(d.top+d.height):p.top-d.top,...wi}:null}const m=cI(o,a,n);return a>n&&a<=i?{x:0,y:-d.height-m,...wi}:a<n&&a>=i?{x:0,y:d.height+m,...wi}:{x:0,y:0,...wi}};function cI(t,s,n){const r=t[s],a=t[s-1],o=t[s+1];return r?n<s?a?r.top-(a.top+a.height):o?o.top-(r.top+r.height):0:o?o.top-(r.top+r.height):a?r.top-(a.top+a.height):0:0}const ry="Sortable",ay=ee.createContext({activeIndex:-1,containerId:ry,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:ny,disabled:{draggable:!1,droppable:!1}});function tm(t){let{children:s,id:n,items:r,strategy:a=ny,disabled:o=!1}=t;const{active:i,dragOverlay:d,droppableRects:m,over:p,measureDroppableContainers:c}=bv(),u=yv(ry,n),x=d.rect!==null,h=l.useMemo(()=>r.map(w=>typeof w=="object"&&"id"in w?w.id:w),[r]),b=i!=null,f=i?h.indexOf(i.id):-1,g=p?h.indexOf(p.id):-1,y=l.useRef(h),j=!iI(h,y.current),v=g!==-1&&f===-1||j,T=lI(o);Rf(()=>{j&&b&&c(h)},[j,h,b,c]),l.useEffect(()=>{y.current=h},[h]);const k=l.useMemo(()=>({activeIndex:f,containerId:u,disabled:T,disableTransforms:v,items:h,overIndex:g,useDragOverlay:x,sortedRects:oI(h,m),strategy:a}),[f,u,T.draggable,T.droppable,v,h,g,m,x,a]);return ee.createElement(ay.Provider,{value:k},s)}const dI=t=>{let{id:s,items:n,activeIndex:r,overIndex:a}=t;return ci(n,r,a).indexOf(s)},uI=t=>{let{containerId:s,isSorting:n,wasDragging:r,index:a,items:o,newIndex:i,previousItems:d,previousContainerId:m,transition:p}=t;
76return!p||!r||d!==o&&a===i?!1:n?!0:i!==a&&s===m},mI={duration:200,easing:"ease"},oy="transform",pI=lu.Transition.toString({property:oy,duration:0,easing:"linear"}),xI={roleDescription:"sortable"};function hI(t){let{disabled:s,index:n,node:r,rect:a}=t;const[o,i]=l.useState(null),d=l.useRef(n);return Rf(()=>{if(!s&&n!==d.current&&r.current){const m=a.current;if(m){const p=Sv(r.current,{ignoreTransform:!0}),c={x:m.left-p.left,y:m.top-p.top,scaleX:m.width/p.width,scaleY:m.height/p.height};(c.x||c.y)&&i(c)}}n!==d.current&&(d.current=n)},[s,n,r,a]),l.useEffect(()=>{o&&i(null)},[o]),o}function sc(t){let{animateLayoutChanges:s=uI,attributes:n,disabled:r,data:a,getNewIndex:o=dI,id:i,strategy:d,resizeObserverConfig:m,transition:p=mI}=t;const{items:c,containerId:u,activeIndex:x,disabled:h,disableTransforms:b,sortedRects:f,overIndex:g,useDragOverlay:y,strategy:j}=l.useContext(ay),v=fI(r,h),T=c.indexOf(i),k=l.useMemo(()=>({sortable:{containerId:u,index:T,items:c},...a}),[u,a,T,c]),w=l.useMemo(()=>c.slice(c.indexOf(i)),[c,i]),{rect:I,node:A,isOver:E,setNodeRef:C}=ou({id:i,data:k,disabled:v.droppable,resizeObserverConfig:{updateMeasurementsFor:w,...m}}),{active:N,activatorEvent:S,activeNodeRect:O,attributes:R,setNodeRef:z,listeners:D,isDragging:L,over:$,setActivatorNodeRef:q,transform:P}=iu({id:i,data:k,attributes:{...xI,...n},disabled:v.draggable}),U=Nv(C,z),V=!!N,M=V&&!b&&vi(x)&&vi(g),F=!y&&L,W=F&&M?P:null,G=M?W??(d??j)({rects:f,activeNodeRect:O,activeIndex:x,overIndex:g,index:T}):null,B=vi(x)&&vi(g)?o({id:i,items:c,activeIndex:x,overIndex:g}):T,Y=N==null?void 0:N.id,J=l.useRef({activeId:Y,items:c,newIndex:B,containerId:u}),H=c!==J.current.items,Z=s({active:N,containerId:u,isDragging:L,isSorting:V,id:i,index:T,items:c,newIndex:J.current.newIndex,previousItems:J.current.items,previousContainerId:J.current.containerId,transition:p,wasDragging:J.current.activeId!=null}),Q=hI({disabled:!Z,index:T,node:A,rect:I});return l.useEffect(()=>{V&&J.current.newIndex!==B&&(J.current.newIndex=B),u!==J.current.containerId&&(J.current.containerId=u),c!==J.current.items&&(J.current.items=c)},[V,B,u,c]),l.useEffect(()=>{if(Y===J.current.activeId)return;if(Y!=null&&J.current.activeId==null){J.current.activeId=Y;return}const X=setTimeout(()=>{J.current.activeId=Y},50);return()=>clearTimeout(X)},[Y]),{active:N,activeIndex:x,attributes:R,data:k,rect:I,index:T,newIndex:B,items:c,isOver:E,isSorting:V,isDragging:L,listeners:D,node:A,overIndex:g,over:$,setNodeRef:U,setActivatorNodeRef:q,setDroppableNodeRef:C,setDraggableNodeRef:z,transform:Q??G,transition:K()};function K(){if(Q||H&&J.current.newIndex===T)return pI;if(!(F&&!kv(S)||!p)&&(V||Z))return lu.Transition.toString({...p,property:oy})}}function fI(t,s){var n,r;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t==null?void 0:t.draggable)!=null?n:s.draggable,droppable:(r=t==null?void 0:t.droppable)!=null?r:s.droppable}}function bl(t){if(!t)return!1;const s=t.data.current;return!!(s&&"sortable"in s&&typeof s.sortable=="object"&&"containerId"in s.sortable&&"items"in s.sortable&&"index"in s.sortable)}const gI=[xr.Down,xr.Right,xr.Up,xr.Left],sm=(t,s)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:o,over:i,scrollableAncestors:d}}=s;if(gI.includes(t.code)){if(t.preventDefault(),!n||!r)return;const m=[];o.getEnabled().forEach(u=>{if(!u||u!=null&&u.disabled)return;const x=a.get(u.id);if(x)switch(t.code){case xr.Down:r.top<x.top&&m.push(u);break;case xr.Up:r.top>x.top&&m.push(u);break;case xr.Left:r.left>x.left&&m.push(u);break;case xr.Right:r.left<x.left&&m.push(u);break}});const p=Df({collisionRect:r,droppableRects:a,droppableContainers:m});let c=jv(p,"id");if(c===(i==null?void 0:i.id)&&p.length>1&&(c=p[1].id),c!=null){const u=o.get(n.id),x=o.get(c),h=x?a.get(x.id):null,b=x==null?void 0:x.node.current;if(b&&h&&u&&x){const g=vv(b).some((w,I)=>d[I]!==w),y=iy(u,x),j=bI(u,x),v=g||!y?{x:0,y:0}:{x:j?r.width-h.width:0,y:j?r.height-h.height:0},T={x:h.left,y:h.top};return v.x&&v.y?T:wv(T,v)}}}};function iy(t,s){return!bl(t)||!bl(s)?!1:t.data.current.sortable.containerId===s.data.current.sortable.containerId}function bI(t,s){return!bl(t)||!bl(s)||!iy(t,s)?!1:t.data.current.sortable.index<s.data.current.sortable.index}function yI(t,s){const n=[],r=new Date(t);r.setHours(0,0,0,0);for(let a=0;a<s;a++)n.push(new Date(r)),r.setDate(r.getDate()+1);return n}function jI(){return yI(new Date,21)}function yl(t){const s=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${s}-${n}-${r}`}function ly(t,s){const n=t.getDay();return n===0||n===6?!0:s.has(yl(t))}function Ni(t){return`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`}function xo(t,s){return t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()}function cy(t){return new Date(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}function lx(t,s){const n=new Date(t);let r=s;for(;r>0;)n.setDate(n.getDate()+1),n.getDay()!==0&&n.getDay()!==6&&r--;return n}const vI={2:"#fef08a",3:"#fed7aa"},wI="#fecaca",NI="#fde68a",cx="capacityCalendar.hideCompletedProjects";function kI(t){if(!t)return;switch(t.trim().toLowerCase()){case"blocked":return"rgba(239, 68, 68, 0.15)";case"waiting on client":return"rgba(59, 130, 246, 0.15)";case"ready":return"rgba(34, 197, 94, 0.15)";case"in review":return"rgba(234, 179, 8, 0.15)";default:return}}function SI({project:t,dayColumns:s,dayKeyToCol:n,totalCols:r,gridTemplateColumns:a,isSaving:o,onProjectClick:i,today:d,blackoutSet:m,allTicketsDone:p,ticketMinutes:c,startDayIndex:u,promisedDates:x}){const{attributes:h,listeners:b,setNodeRef:f,transform:g,transition:y,isDragging:j}=sc({id:t.projectId,disabled:o}),v=g?`translate3d(0, ${Math.round(g.y)}
76px, 0)`:void 0,T=kI(t.subStatus),k={transform:v,transition:y,zIndex:j?50:void 0,position:j?"relative":void 0,display:"grid",gridTemplateColumns:a,height:"2.5rem",backgroundColor:T},w=t.launchDate?cy(t.launchDate):void 0,I=6,A=c/60,E=A>0?Math.max(1,Math.ceil(A/I)):0;let C=-1,N=-1;if(E>0&&u!==void 0){C=u+2;let R=0;for(let z=u;z<s.length&&R<E;z++)ly(s[z],m)||(R++,N=z+3);R<E&&(N=r+2)}const S=A.toFixed(1),O=E;return e.jsxs("div",{ref:f,style:k,className:`items-center h-10 border-b border-border/30 last:border-b-0 ${j?"shadow-lg bg-card rounded-lg opacity-95":""}`,...h,children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-2 min-w-0 border-r border-border",style:{gridColumn:1,gridRow:1},children:[e.jsx("button",{...b,className:`flex-shrink-0 p-0.5 rounded hover:bg-accent transition-colors ${o?"opacity-30 cursor-not-allowed":"cursor-grab active:cursor-grabbing"}`,tabIndex:-1,"aria-label":"Drag to reorder",children:e.jsx(Yr,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("button",{className:"text-left min-w-0 truncate text-xs font-medium text-foreground hover:underline",onClick:()=>i(t),title:`${t.projectName}${t.clientName?` - ${t.clientName}`:""}`,children:[p&&"â
",t.projectName]})]}),s.map((R,z)=>{const D=R.getDay(),L=D===0||D===6,$=!L&&m.has(yl(R)),q=L||$,P=!q&&w&&xo(R,w),U=!q&&w&&!P&&(xo(R,lx(w,1))||xo(R,lx(w,2))),V=x==null?void 0:x.find(F=>xo(R,F));let M;return $?M="#1f2937":(P||U)&&(M=NI),e.jsx("div",{className:"border-r border-border/20",style:{gridColumn:z+2,gridRow:1,alignSelf:"stretch",backgroundColor:M,minWidth:$?"24px":void 0},children:(P||V)&&e.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",gap:2,fontSize:"0.75rem",lineHeight:1},children:[P&&e.jsx("span",{title:`Launch: ${w.toLocaleDateString()}`,children:"ð"}),V&&e.jsx("span",{title:`Promised to customer: ${V.toLocaleDateString()}`,children:"ð"})]})},z)}),C>0&&N>0&&e.jsx("div",{className:"rounded-md cursor-pointer hover:opacity-80 transition-opacity bg-gray-200",style:{gridColumn:`${C} / ${N}
76`,gridRow:1,height:"1.75rem",alignSelf:"center",margin:"0 2px"},onClick:()=>i(t),title:`${t.projectName}${t.clientName?` - ${t.clientName}`:""} 77${S}h estimate (${O} day${O!==1?"s":""})`})]})}function CI({projects:t,scheduledTickets:s,onProjectClick:n,onReorder:r,isSaving:a,blackoutDates:o}){const[i,d]=l.useState(()=>localStorage.getItem(cx)==="true"),m=A=>{d(A),localStorage.setItem(cx,String(A))},p=Ho(Rn(Yo,{activationConstraint:{distance:5}}),Rn(Vo,{coordinateGetter:sm})),c=l.useMemo(()=>jI(),[]),u=l.useMemo(()=>{const A=new Date;return A.setHours(0,0,0,0),A},[]),x=l.useMemo(()=>new Set(o??[]),[o]),{projectTicketMinutes:h,projectsWithNoTickets:b}=l.useMemo(()=>{const A=new Map,E=new Set;if(s){const N=new Set;for(const S of s)N.has(S.ticketId)||(N.add(S.ticketId),E.add(S.projectId),A.set(S.projectId,(A.get(S.projectId)||0)+S.estimatedMinutes))}const C=new Set;for(const N of t)E.has(N.projectId)||C.add(N.projectId);return{projectTicketMinutes:A,projectsWithNoTickets:C}},[t,s]),f=l.useMemo(()=>{const A=new Map;if(!s)return A;const E=new Set;for(const C of s){if(!C.promisedDate)continue;const N=cy(C.promisedDate),S=`${C.projectId}|${Ni(N)}`;E.has(S)||(E.add(S),A.has(C.projectId)||A.set(C.projectId,[]),A.get(C.projectId).push(N))}return A},[s]),g=b.size,y=l.useMemo(()=>i?t.filter(A=>!b.has(A.projectId)):t,[t,b,i]),j=l.useMemo(()=>{const E=new Map,C=[];for(let S=0;S<c.length;S++)!ly(c[S],x)&&c[S]>=u&&C.push(S);let N=0;for(const S of t){const O=h.get(S.projectId)||0,R=O>0?Math.max(1,Math.ceil(O/60/6)):0;R>0&&N<C.length&&(E.set(S.projectId,C[N]),N+=R)}return E},[t,h,c,x,u]),v=l.useMemo(()=>{const A=new Map;return c.forEach((E,C)=>A.set(Ni(E),C)),A},[c]),T=c.length,k=l.useMemo(()=>`300px ${c.map(E=>{const C=E.getDay();return!(C===0||C===6)&&x.has(yl(E))?"0.5fr":"1fr"}).join(" ")}`,[c,x]),w=l.useMemo(()=>{const A=new Map;for(const E of t){const C=new Date(E.startDate);C.setHours(0,0,0,0);const N=new Date(E.endDate);N.setHours(0,0,0,0);for(const S of c)if(S>=C&&S<=N){const O=Ni(S);A.set(O,(A.get(O)??0)+1)}}return A},[t,c]);function I(A){const{active:E,over:C}=A;if(!C||E.id===C.id)return;const N=t.findIndex(R=>R.projectId===E.id),S=t.findIndex(R=>R.projectId===C.id);if(N===-1||S===-1)return;const O=ci(t,N,S);r(O.map(R=>R.projectId))}return t.length===0?e.jsx("div",{className:"bg-card border border-border rounded-lg p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No projects in queue"})}):e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[a?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-primary"}),"Saving order to Notion..."]}):e.jsx("span",{}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-muted-foreground cursor-pointer whitespace-nowrap",children:[e.jsx("input",{type:"checkbox",checked:i,onChange:A=>m(A.target.checked),className:"w-4 h-4 rounded border-border text-primary focus:ring-primary"}),"Hide completed projects",g>0&&e.jsxs("span",{className:"text-xs opacity-70",children:["(",g,")"]})]})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg overflow-x-auto",children:[e.jsxs("div",{className:"grid border-b border-border text-xs font-medium text-muted-foreground",style:{gridTemplateColumns:k},children:[e.jsx("div",{className:"p-2 border-r border-border bg-muted",children:"Project"}),c.map((A,E)=>{const C=A.getDay(),N=["S","M","T","W","T","F","S"][C],S=C===0||C===6,O=!S&&x.has(yl(A)),R=S||O,z=!R&&xo(A,u),D=C===1&&E>0;let L;if(!R){const q=w.get(Ni(A))??0;q>=4?L=wI:q>=2&&(L=vI[q])}let $;return O?$="#1f2937":L?$=L:z&&($="rgba(126,204,238,0.1)"),e.jsxs("div",{className:`p-1 text-center border-r border-border/30 ${z?"font-bold text-primary":""} ${O?"text-white":S?"text-muted-foreground/50":""} ${D?"border-l-2 border-l-border":""}`,style:{backgroundColor:$,minWidth:O?"24px":void 0},children:[e.jsx("div",{children:N}),e.jsx("div",{className:"text-[10px]",children:A.getDate()})]},E)})]}),y.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"All projects complete â uncheck âHide completed projectsâ to see them."}):e.jsx(qo,{sensors:p,collisionDetection:cu,onDragEnd:I,children:e.jsx(tm,{items:y.map(A=>A.projectId),strategy:em,children:y.map(A=>e.jsx(SI,{project:A,dayColumns:c,dayKeyToCol:v,totalCols:T,gridTemplateColumns:k,isSaving:a,onProjectClick:n,today:u,blackoutSet:x,allTicketsDone:b.has(A.projectId),ticketMinutes:h.get(A.projectId)||0,startDayIndex:j.get(A.projectId),promisedDates:f.get(A.projectId)},A.projectId))})})]})]})}const qc=1e3,TI={"In Queue":"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300","In Progress":"bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300","In Review":"bg-
77amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300","Changes Requested":"bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300",Parked:"bg-muted text-muted-foreground"},Vc={none:{label:"Not in Pipeline",color:"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300"},queued:{label:"Needs Investigation",color:"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300"},investigating:{label:"Investigating...",color:"bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300"},plan_ready:{label:"Plan Ready",color:"bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300"},awaiting_approval:{label:"Awaiting Approval",color:"bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300"},approved:{label:"Approved",color:"bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300"},approved_manual:{label:"Approved",color:"bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300"},implementing:{label:"In Progress",color:"bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300"},verifying:{label:"In Progress",color:"bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300"},failed:{label:"Needs Attention",color:"bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300"},rejected:{label:"Needs Attention",color:"bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300"},deferred:{label:"Deferred",color:"bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300"},cancelled:{label:"Cancelled",color:"bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400"}};function dy({status:t,loading:s,ticketStatus:n}){if(s)return e.jsx("span",{className:"inline-block w-24 h-5 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"});if(t==="none"&&n){const a=TI[n]||Vc.none.color;return e.jsx("span",{className:`text-xs font-medium px-2 py-0.5 rounded-full whitespace-nowrap ${a}`,children:n})}const r=Vc[t]||Vc.none;return e.jsx("span",{className:`text-xs font-medium px-2 py-0.5 rounded-full whitespace-nowrap ${r.color}`,children:r.label})}function AI({merged:t,pipelinesLoading:s,disabled:n,onTicketClick:r,onNavigateToPipeline:a}){const{ticket:o,pipeline:i}=t,d=(i==null?void 0:i.status)||"none",m=i==null?void 0:i.id,{attributes:p,listeners:c,setNodeRef:u,transform:x,transition:h,isDragging:b}=sc({id:o.ticketId,disabled:n}),f={transform:x?`translate3d(0, ${Math.round(x.y)}px, 0)`:void 0,transition:h,zIndex:b?50:void 0,position:b?"relative":void 0};return e.jsxs("div",{ref:u,style:f,className:`flex items-center gap-3 px-3 py-3 bg-card hover:bg-accent/30 transition-colors ${b?"shadow-lg rounded-lg opacity-95":""}`,...p,children:[e.jsx("button",{...c,tabIndex:-1,"aria-label":"Drag to reorder",className:`flex-shrink-0 p-0.5 rounded hover:bg-accent transition-colors ${n?"opacity-30 cursor-not-allowed":"cursor-grab active:cursor-grabbing"}`,children:e.jsx(Yr,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("button",{className:"flex-1 flex items-center gap-3 text-left min-w-0",onClick:()=>r(o),children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground shrink-0",children:o.ticketId}),e.jsx("span",{className:"text-sm text-foreground truncate",children:o.ticketName}),e.jsxs("span",{className:"text-xs text-muted-foreground truncate shrink-0 max-w-[40%] hidden sm:inline",children:[o.projectName,o.clientName?` · ${o.clientName}`:""]}),e.jsx(Rt,{className:"w-4 h-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsx(dy,{status:d,loading:s,ticketStatus:o.status}),e.jsx("span",{className:"text-xs text-muted-foreground shrink-0 w-12 text-right",children:o.estimatedMinutes>=60?`${(o.estimatedMinutes/60).toFixed(1)}h`:`${o.estimatedMinutes}m`}),m&&a&&e.jsx("button",{title:"Open in Pipeline",className:"p-1 rounded hover:bg-blue-100 dark:hover:bg-blue-900/30 text-blue-500 shrink-0",onClick:g=>{g.stopPropagation(),a(m)},children:e.jsx(Bw,{className:"w-4 h-4"})})]})}function EI({scheduledTickets:t,projects:s,pipelines:n,pipelinesLoading:r,updatePipeline:a,cancelledPipelines:o,loadCancelled:i,onTicketClick:d,onNavigateToPipeline:m,onReorderTicket:p,savingTicketOrder:c}
77){const[u,x]=l.useState("queue"),[h,b]=l.useState(null),[f,g]=l.useState(null),[y,j]=l.useState(!1),[v,T]=l.useState("all"),k=Ho(Rn(Yo,{activationConstraint:{distance:5}}),Rn(Vo,{coordinateGetter:sm}));l.useEffect(()=>{u==="archived"&&i()},[u,i]);const w=l.useMemo(()=>{const R=new Map;for(const z of n)R.set(z.ticketNumber,z);return R},[n]),I=l.useMemo(()=>{const R=new Map;for(const P of t){const U=R.get(P.ticketId);(!U||P.date<U.date)&&R.set(P.ticketId,P)}const z=Array.from(R.values()),D=new Map;for(const P of s)D.set(P.projectId,P.order);const q=[...z.map(P=>({ticket:P,pipeline:w.get(P.ticketId)||null})).filter(P=>{var U;return((U=P.pipeline)==null?void 0:U.status)!=="cancelled"})].sort((P,U)=>{const V=D.get(P.ticket.projectId)??999,M=D.get(U.ticket.projectId)??999;if(V!==M)return V-M;const F=P.ticket.date.getTime(),W=U.ticket.date.getTime();return F!==W?F-W:P.ticket.ticketId.localeCompare(U.ticket.ticketId)}).map((P,U)=>({...P,effectiveKey:P.ticket.capacitySortOrder??U*qc}));return q.sort((P,U)=>P.effectiveKey!==U.effectiveKey?P.effectiveKey-U.effectiveKey:P.ticket.ticketId.localeCompare(U.ticket.ticketId)),q},[t,s,w]),A=l.useMemo(()=>{const R=new Map;for(const z of I)z.ticket.status==="In Queue"&&!R.has(z.ticket.projectId)&&R.set(z.ticket.projectId,z.ticket.projectName);return Array.from(R.entries()).map(([z,D])=>({projectId:z,projectName:D}))},[I]);l.useEffect(()=>{v!=="all"&&!A.some(R=>R.projectId===v)&&T("all")},[A,v]);const E=l.useMemo(()=>I.filter(R=>R.ticket.status==="In Queue").filter(R=>v==="all"||R.ticket.projectId===v).map(R=>R.ticket.ticketId),[I,v]),C=async()=>{if(E.length!==0)try{await navigator.clipboard.writeText(E.join(", ")),j(!0),setTimeout(()=>j(!1),1500)}catch(R){console.error("Failed to copy ticket IDs:",R)}};function N(R){const{active:z,over:D}=R;if(!D||z.id===D.id)return;const L=I.findIndex(M=>M.ticket.ticketId===z.id),$=I.findIndex(M=>M.ticket.ticketId===D.id);if(L===-1||$===-1)return;const q=ci(I,L,$),P=q[$-1],U=q[$+1];let V;P?U?V=(P.effectiveKey+U.effectiveKey)/2:V=P.effectiveKey+qc:V=((U==null?void 0:U.effectiveKey)??0)-qc,p([{ticketNotionId:q[$].ticket.ticketNotionId,sortOrder:V}])}const S=l.useMemo(()=>{const R=new Map;for(const z of o){const D=z.projectName||z.clientName||"Unknown";R.has(D)||R.set(D,[]),R.get(D).push(z)}return Array.from(R.entries()).sort(([z],[D])=>z.localeCompare(D))},[o]),O=async R=>{b(R);try{await a(R,{status:"queued"}),await i()}finally{b(null),g(null)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("button",{onClick:()=>x("queue"),className:`px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${u==="queue"?"bg-primary text-primary-foreground":"bg-card border border-border text-muted-foreground hover:text-foreground"}`,children:"Queue"}),e.jsxs("button",{onClick:()=>x("archived"),className:`px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${u==="archived"?"bg-primary text-primary-foreground":"bg-card border border-border text-muted-foreground hover:text-foreground"}`,children:["Archived",o.length>0&&e.jsxs("span",{className:"ml-1.5 text-xs opacity-70",children:["(",o.length,")"]})]}),u==="queue"&&e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsxs("select",{value:v,onChange:R=>T(R.target.value),title:"Scope the copied ticket IDs to a project",className:"px-3 py-1.5 rounded-full text-sm font-medium bg-card border border-border text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-primary transition-colors cursor-pointer",children:[e.jsx("option",{value:"all",children:"All projects"}),A.map(R=>e.jsx("option",{value:R.projectId,children:R.projectName},R.projectId))]}),e.jsxs("button",{type:"button",title:E.length===0?"No In Queue tickets to copy":`Copy ${E.length} In Queue ticket ID${E.length===1?"":"s"}${v==="all"?"":" for this project"}`,disabled:E.length===0,onClick:C,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium bg-card border border-border text-muted-foreground hover:text-foreground disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:[y?e.jsx(kt,{className:"w-4 h-4 text-green-600"}):e.jsx(Hr,{className:"w-4 h-4"}),y?"Copied":`Copy In Queue IDs${E.length?` (${E.length})`:""}`]})]})]}),u==="queue"&&e.jsxs(e.Fragment,{children:[c&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-primary"}),"Saving ticket orderâ¦"]}),I.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No tickets in the queue for the current filter."}):e.jsx("div",{className:"bg-card border border-border rounded-lg overflow-hidden divide-y divide-border",children:e.jsx(qo,{sensors:k,collisionDetection:cu,onDragEnd:N,children:e.jsx(tm,{items:I.map(R=>R.ticket.ticketId),strategy:em,children:I.map(R=>
77e.jsx(AI,{merged:R,pipelinesLoading:r,disabled:c,onTicketClick:d,onNavigateToPipeline:m},R.ticket.ticketId))})})})]}),u==="archived"&&(S.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No archived tickets."}):e.jsx("div",{className:"space-y-6",children:S.map(([R,z])=>e.jsxs("div",{className:"bg-card border border-border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-accent/50 border-b border-border flex items-center justify-between",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:R}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[z.length," ticket",z.length!==1?"s":""]})]}),e.jsx("div",{className:"divide-y divide-border",children:z.map(D=>{const L=h===D.id,$=(f==null?void 0:f.pipelineId)===D.id;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 hover:bg-accent/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground shrink-0",children:D.ticketNumber}),e.jsx("span",{className:"text-sm text-foreground truncate",children:D.ticketName})]}),e.jsx(dy,{status:"cancelled",loading:!1}),e.jsx("div",{className:"shrink-0",children:$&&f?e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Restore?"}),e.jsx("button",{className:"px-2 py-1 rounded bg-green-500 text-white hover:bg-green-600 disabled:opacity-50",disabled:L,onClick:()=>O(D.id),children:L?"...":"Yes"}),e.jsx("button",{className:"px-2 py-1 rounded bg-gray-200 dark:bg-gray-700 text-foreground hover:bg-gray-300 dark:hover:bg-gray-600",onClick:()=>g(null),children:"No"})]}):e.jsx("button",{title:"Restore to pipeline",className:"p-1 rounded hover:bg-green-100 dark:hover:bg-green-900/30 text-green-600",onClick:()=>g({ticketId:D.ticketNumber,pipelineId:D.id}),children:e.jsx(gg,{className:"w-4 h-4"})})})]},D.id)})})]},R))}))]})}const dx="capacityCalendar.selectedDepartment",ux="capacityCalendar.departmentsList";function II({onLogoClick:t,onBack:s,onNavigateToPipeline:n,onViewTicketInDatabase:r,onViewProjectInDatabase:a}){const o=localStorage.getItem(dx)||"all",i=localStorage.getItem(ux),d=i?JSON.parse(i):[],m=Array.from(new Set([...Io,...d])).sort(),[p,c]=l.useState(o),[u,x]=l.useState(m),[h,b]=l.useState({includeBlocked:!0,includeDeferred:!0,department:o==="all"?void 0:o}),[f,g]=l.useState("all"),[y,j]=l.useState(!1),[v,T]=l.useState("list"),[k,w]=l.useState(null),[I,A]=l.useState(null),{schedule:E,loading:C,error:N,refetch:S,updateProjectOrder:O,updateTicketOrder:R,isSaving:z,savingTicketOrder:D}=PT(h),{token:L}=pt(),{pipelines:$,loading:q,updatePipeline:P,cancelledPipelines:U,loadCancelled:V}=zT(L),{rows:M,updateRow:F,deleteRow:W}=Xt({collectionName:"tickets",orderByField:"updatedAt",orderDirection:"desc"}),_=l.useRef(!1),G=ae=>{const xe=M.find(ze=>ze.id===ae.ticketNotionId);xe&&A(xe)},B=l.useMemo(()=>{if(!E)return[];const ae=new Set,xe=[];for(const ze of E.scheduledTickets){if(ae.has(ze.ticketId))continue;ae.add(ze.ticketId);const Le=M.find(ht=>ht.id===ze.ticketNotionId);Le&&xe.push(Le)}return xe},[E,M]),Y=l.useMemo(()=>I?B.findIndex(ae=>ae.id===I.id):-1,[B,I]),J=Y>0,H=Y>=0&&Y<B.length-1,Z=()=>{A(null),_.current&&(_.current=!1,S(h))};l.useEffect(()=>{if(E){const ae=Array.from(new Set(E.schedule.map(xe=>xe.department).filter(Boolean)));x(xe=>{const ze=Array.from(new Set([...Io,...xe,...ae])).sort();return ze.length>xe.length&&localStorage.setItem(ux,JSON.stringify(ze)),ze})}},[E]);const Q=ae=>{c(ae),localStorage.setItem(dx,ae);const xe=ae==="all"?void 0:ae;if(h.department!==xe){const ze={...h,department:xe};b(ze),S(ze)}},K=(E==null?void 0:E.schedule.filter(ae=>f==="all"?!0:ae.status===f).length)||0,X=(E==null?void 0:E.schedule.filter(ae=>f==="all"?!(!y&&ae.status==="Deferred"):ae.status===f))||[],se=X.reduce((ae,xe)=>ae+xe.estimatedMinutes/60,0),pe=X.reduce((ae,xe)=>ae+xe.estimatedDays,0),me=(()=>{if(X.length===0)return console.log("â ï¸ No filtered projects, using schedule.nextAvailableDate"),(E==null?void 0:E.nextAvailableDate)||new Date;console.log("ð All projects in schedule:",E==null?void 0:E.schedule.map(ze=>({name:ze.projectName,status:ze.status,department:ze.department,endDate:ze.endDate}))),console.log("ð Filtered projects:",X.map(ze=>({name:ze.projectName,status:ze.status,department:ze.department,endDate:ze.endDate})));const ae=X[X.length-1];if(!ae||!ae.endDate)return console.error("ð¨ Missing end date for the last project:",ae),new Date;console.log("ð¯ Last filtered project:",ae.projectName,"ends on:",ae.endDate);const xe=new Date(ae.endDate);return isNaN(xe.getTime())?(console.error("ð¨ Invalid date for the last project:",ae.endDate),new Date):(xe.setDate(xe.getDate()+1),console.log("ð
Calculated next available:",xe),xe)})(),Ne=ae=>ae.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),at=(ae,xe)=>ae.getMonth()===xe.getMonth()?`${ae.toLocaleDateString("en-US",{month:"short"})} ${ae.getDate()}-${xe.getDate()}`:`${Ne(ae)} - ${Ne(xe)}`;return C?e.jsxs("div",{className:"min-h-screen bg-background flex flex-col items-center justify-center",children:[e.jsx("div",{style:{width:96,height:96,marginBottom:24},children:e.jsx("img",{src:ks,alt:"Loading",style:{width:96,height:96,display:"block",animation:"spin 1.5s linear infinite"}})}),e.jsx("p",{className:"text-muted-foreground",children:"Loading c
77apacity schedule..."})]}):N?e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(Xe,{onLogoClick:t,onBack:s}),e.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:e.jsxs("div",{className:"bg-red-500 text-white p-4 rounded-lg",children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Error Loading Schedule"}),e.jsx("p",{children:N}),e.jsx("button",{onClick:()=>S(h),className:"mt-4 px-4 py-2 bg-white text-red-500 rounded-md hover:bg-red-50",children:"Try Again"})]})})]}):E?e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:t,onBack:s}),e.jsxs("div",{className:"max-w-4xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Capacity Calendar"}),e.jsx("button",{onClick:()=>S(h),className:"p-2 hover:bg-accent rounded-lg transition-colors",title:"Refresh",children:e.jsx(yt,{className:"w-5 h-5 text-muted-foreground"})})]}),e.jsx("p",{className:"text-muted-foreground",children:"Sequential project scheduling"})]}),u.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Filter by Department"}),e.jsxs("select",{value:p,onChange:ae=>Q(ae.target.value),className:"w-full px-3 py-2 bg-card border border-border rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-primary",children:[e.jsx("option",{value:"all",children:"All Departments"}),u.map(ae=>e.jsx("option",{value:ae,children:ae},ae))]})]}),e.jsxs("div",{className:"flex gap-2 mb-6",children:[e.jsx("button",{onClick:()=>T("list"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${v==="list"?"bg-primary text-primary-foreground":"bg-card border border-border text-foreground hover:bg-accent"}`,children:"Dashboard"}),e.jsx("button",{onClick:()=>T("calendar"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${v==="calendar"?"bg-primary text-primary-foreground":"bg-card border border-border text-foreground hover:bg-accent"}`,children:"Calendar View"}),e.jsx("button",{onClick:()=>T("tickets"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${v==="tickets"?"bg-primary text-primary-foreground":"bg-card border border-border text-foreground hover:bg-accent"}`,children:"Ticket Queue"})]}),v==="list"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-6",children:[e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ss,{className:"w-5 h-5 text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Next Available"})]}),e.jsx("p",{className:"text-xl font-bold text-foreground",children:Ne(me)})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ms,{className:"w-5 h-5 text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Time till clear"})]}),e.jsxs("p",{className:"text-xl font-bold text-foreground",children:[se.toFixed(1),"h"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["(",pe," days)"]})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Xo,{className:"w-5 h-5 text-primary"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Projects Queued"})]}),e.jsx("p",{className:"text-xl font-bold text-foreground",children:E.schedule.length})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ul,{className:"w-5 h-5 text-orange-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Launches"})]}),e.jsx("p",{className:"text-xl font-bold text-foreground",children:E.upcomingLaunches.length})]})]}),(()=>{const ae=new Date;ae.setHours(0,0,0,0);const xe=new Date(ae);xe.setDate(xe.getDate()+28);const ze=E.upcomingLaunches.filter(Le=>{const ht=new Date(Le.launchDate);return ht.setHours(0,0,0,0),ht>=ae&&ht<=xe});return ze.length===0?null:e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-3",children:"ð Upcoming Launches (Next 4 Weeks)"}),e.jsx("div",{className:"space-y-2",children:ze.map((Le,ht)=>e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-foreground",children:Le.projectName}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Launch Date: ",Ne(Le.launchDate)]})]})})},ht))})]})})(),e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Project Queue"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[K," of ",E.schedule.length," projects"]})]}),e.jsx("div",{className:"mb-3",children:e.jsxs("label",{className:"flex items-center gap-2 text-sm text-muted-foreground cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:y,onChange:ae=>j(ae.target.checked),className:"w-4 h-4 rounded border-border text-primary focus:ring-primary"}),"Show Deferred"]})}),e.jsxs("div",{className:"flex gap-2 mb-4 overflow-x-auto pb-2",children:[e.jsx("button",{onClick:()=>g("all"),className:`px-3 py-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${f==="all"?"bg-primary text-primary-foreground":"bg-card border border-border text-foreground hover:bg-accent"}`,children:"All"}),e.jsx("button",{onClick:()=>g("In Progress"),className:`px-3 py-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${f==="In Progress"?"bg-green-500 text-white":"bg-card border border-border text-foreground hover:bg-accent"}`,children:"In Progress"}),e.jsx("button",{onClick:()=>g("In Review"),className:`px-3 py-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${f==="In Review"?"bg-orange-500 text-white":"bg-card border border-border text-foreground hover:bg-accent"}`,children:"In Review"}),e.jsx("button",{onClick:()=>g("Backlog"),className:`px-3 py-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${f==="Backlog"?"bg-muted text-foreground":"bg-card border border-border text-foreground hover:bg-accent"}`,children:"Backlog"}),e.jsx("button",{onClick:()=>g("Blocked"),className:`px-3 py-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${f==="Blocked"?"bg-red-500 text-white":"bg-card border border-border text-foreground hover:bg-accent"}`,children:"Blocked"})]}),X.length===0?e.jsx("div",{className:"bg-card border border-border rounded-lg p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:f==="all"?"No projects in queue":`No ${f} projects`})}):e.jsx("div",{className:"space-y-3",children:X.map((ae,xe)=>e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 hover:bg-accent transition-colors cursor-pointer",onClick:()=>w(ae),children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-sm font-bold",children:ae.order}),e.jsx("h3",{className:"font-semibold text-foreground",children:ae.projectName})]}),(ae.clientName||ae.department)&&e.jsx("p",{className:"text-sm text-muted-foreground ml-8",children:ae.clientName&&ae.department?`${ae.clientName} ⢠${ae.department}`:ae.clientName||ae.department})]}),e.jsx("div",{className:"text-right",children:e.jsx("span",{className:`inline-block px-2 py-1 rounded text-xs font-medium ${ae.status==="In Progress"?"bg-green-500 text-white":ae.status==="In Review"?"bg-orange-500 text-white":ae.status==="Deferred"?"bg-yellow-500 text-white":ae.status==="Blocked"?"bg-red-500 text-white":"bg-muted text-muted-foreground"}`,children:ae.status})})]}),e.jsxs("div",{className:"ml-8 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{children:["ð
",at(ae.startDate,ae.endDate)]}),e.jsxs("span",{children:["â±ï¸ ",ae.estimatedDays," day",ae.estimatedDays!==1?"s":""]}),e.jsxs("span",{children:["ð ",(ae.estimatedMinutes/60).toFixed(1),"h"]})]}),ae.launchDate&&e.jsxs("div",{className:"flex items-center gap-1 text-sm text-orange-500",children:[e.jsx(ul,{className:"w-4 h-4"}
77),e.jsxs("span",{children:["Launch: ",Ne(ae.launchDate)]})]})]})]},ae.projectId))})]})]}),v==="calendar"&&e.jsx(CI,{projects:X,scheduledTickets:E.scheduledTickets,onProjectClick:ae=>w(ae),onReorder:O,isSaving:z,blackoutDates:E.blackoutDates}),v==="tickets"&&e.jsx(EI,{scheduledTickets:E.scheduledTickets,projects:E.schedule,pipelines:$,pipelinesLoading:q,updatePipeline:P,cancelledPipelines:U,loadCancelled:V,onTicketClick:G,onNavigateToPipeline:n,onReorderTicket:R,savingTicketOrder:D})]}),e.jsx(OT,{project:k,tickets:k?(E==null?void 0:E.scheduledTickets.filter(ae=>ae.projectId===k.projectId))||[]:[],onClose:()=>w(null),onTicketClick:ae=>{w(null),G(ae)},onViewInDatabase:a}),I&&e.jsx(sy,{ticket:I,rows:M,updateRow:F,deleteRow:W,onClose:Z,onSelect:A,onPrev:()=>{J&&A(B[Y-1])},onNext:()=>{H&&A(B[Y+1])},hasPrev:J,hasNext:H,positionLabel:Y>=0?`${Y+1}/${B.length}`:void 0,onAfterWrite:()=>{_.current=!0}})]}):null}const uy=({currentStep:t,totalSteps:s,onStepClick:n,stepLabels:r})=>{const a=t/s*100,o=r||["Speed","Structure","Content","Marketing","Visual","Pricing"];return e.jsxs("div",{children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2 mb-2 overflow-hidden",children:e.jsx("div",{className:"h-2 rounded-full transition-all duration-300 relative",style:{width:`${a}%`,background:"linear-gradient(90deg, var(--primary), var(--secondary), var(--primary))",backgroundSize:"200% 100%",animation:"pulse-gradient 3s ease-in-out infinite"}})}),e.jsx("style",{children:` 78 @keyframes pulse-gradient { 79 0%, 100% { 80 background-position: 0% 50%; 81 } 82 50% { 83 background-position: 100% 50%; 84 } 85 } 86 `}),e.jsx("div",{className:"flex justify-between text-sm",children:o.map((i,d)=>e.jsx("button",{onClick:()=>n==null?void 0:n(d+1),className:`px-2 py-1 rounded-lg transition-all cursor-pointer hover:opacity-80 ${d+1===t?"font-bold text-primary bg-primary/10 border-2 border-primary":d+1<t?"font-semibold text-secondary-foreground":"text-muted-foreground"}`,children:i},i))})]})},di=({open:t,onOpenChange:s,title:n,description:r,confirmLabel:a="Confirm",cancelLabel:o="Cancel",destructive:i,onConfirm:d})=>e.jsx(Kl,{open:t,onOpenChange:s,children:e.jsxs(Ql,{children:[e.jsxs(Tu,{children:[e.jsx(Eu,{children:n}),e.jsx(Iu,{children:r})]}),e.jsxs(Au,{children:[e.jsx(Du,{children:o}),e.jsx(Ru,{className:i?"bg-red-600 text-white hover:bg-red-700":void 0,onClick:d,children:a})]})]})}),mx=({data:t,onNext:s,editMode:n,onEditRecommendation:r,onDeleteRecommendation:a})=>{const[o,i]=ee.useState(new Set),[d,m]=ee.useState(null);l.useEffect(()=>{t.score>=90&&va({particleCount:100,spread:70,origin:{y:.6}})},[t.score]);const p=c=>{i(u=>{const x=new Set(u);return x.has(c)?x.delete(c):x.add(c),x})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8 mt-12",children:[e.jsx("h1",{className:"mb-4 text-foreground",style:{fontSize:"24px",fontWeight:700},children:"Speed Issues"}),e.jsxs("div",{className:"flex justify-center gap-4 mb-4",children:[e.jsxs("div",{className:"w-24 h-24 bg-card border border-border rounded-xl p-3 flex flex-col items-center justify-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"MOBILE"}),e.jsx("div",{className:`text-2xl font-bold ${(t.mobileScore??t.score)>=80?"text-green-600":(t.mobileScore??t.score)>=50?"text-yellow-600":"text-red-600"}`,children:t.mobileScore??t.score})]}),e.jsxs("div",{className:"w-24 h-24 bg-card border border-border rounded-xl p-3 flex flex-col items-center justify-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"DESKTOP"}),e.jsx("div",{className:`text-2xl font-bold ${(t.desktopScore??t.score)>=80?"text-green-600":(t.desktopScore??t.score)>=50?"text-yellow-600":"text-red-600"}`,children:t.desktopScore??t.score})]})]}),e.jsx("div",{className:"flex justify-center mb-4",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-1",children:"TOTAL SCORE"}),e.jsxs("div",{className:`text-5xl font-bold ${t.score>=80?"text-green-600":t.score>=50?"text-yellow-600":"text-red-600"}`,children:[t.score,"/100"]})]})}),t.realWorldLoad&&e.jsxs("div",{className:`mt-6 p-4 rounded-xl border ${t.realWorldLoad.warning?"bg-red-50 border-red-200":"bg-card border-border"}`,children:[e.jsx("div",{className:"text-sm font-semibold text-muted-foreground mb-3",children:"REAL-WORLD PERFORMANCE"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-2xl font-bold text-foreground",children:[(t.realWorldLoad.totalBytes/(1024*1024)).toFixed(1),"MB"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Page Size"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-foreground",children:t.realWorldLoad.estimatedTime3G}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"3G Load"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-foreground",children:t.realWorldLoad.estimatedTime4G}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"4G Load"})]})]}),t.realWorldLoad.warning&&e.jsxs("div",{className:"mt-3 text-sm text-red-600 font-medium text-center",children:["â ï¸ ",t.realWorldLoad.warning]})]})]}),e.jsx("div",{className:"bg-primary/10 border border-primary/20 rounded-2xl p-4 mb-6",children:e.jsx("p",{className:"text-foreground",children:"Site speed directly impacts your conversion rate. For every second of delay, you lose 7% of potential customers. Here's what's slowing down your site:"})}),e.jsx("div",{className:"space-y-4",children:t.recommendations.map((c,u)=>{const x=o.has(u);return e.jsxs("div",{onClick:()=>!n&&p(u),style:{borderWidth:"4px",borderStyle:"solid",borderColor:c.effort==="small"?"#22c55e":c.effort==="medium"?"#eab308":c.effort==="large"?"#ef4444":"var(--border)",transform:x&&!n?"scale(1.05)":"scale(1)",boxShadow:x&&!n?"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)":"none",transition:"transform 0.3s ease, box-shadow 0.3s ease"},className:`bg-card rounded-2xl p-6 relative ${n?"":"cursor-pointer"}`,children:[n&&a&&e.jsx("button",{onClick:h=>{h.stopPropagation(),m(u)},className:"absolute top-4 right-4 p-2 bg-red-100 text-red-600 rounded-full hover:bg-red-200 transition-colors",title:"Delete recommendation",children:e.jsx(zs,{className:"w-4 h-4"})}),!n&&c.effort&&e.jsx("div",{className:`absolute top-4 right-4 px-3 py-1 rounded-full text-xs font-semibold ${c.effort==="small"?"bg-green-100 text-green-700":c.effort==="medium"?"bg-yellow-100 text-yellow-700":"bg-red-100 text-red-700"}`,children:c.effort==="small"?"Easy":c.effort==="medium"?"Medium":"Complex"}),n&&r?e.jsx("input",{type:"text",value:c.title,onChange:h=>
86r(u,"title",h.target.value),className:"text-xl font-semibold mb-2 text-foreground pr-12 w-full bg-transparent border-b-2 border-dashed border-amber-300 focus:border-amber-500 focus:outline-none",onClick:h=>h.stopPropagation()}):e.jsx("h3",{className:"text-xl font-semibold mb-2 text-foreground pr-20",children:c.title}),n&&r?e.jsx("textarea",{value:c.description,onChange:h=>r(u,"description",h.target.value),className:"text-muted-foreground mb-3 w-full bg-transparent border-2 border-dashed border-amber-300 focus:border-amber-500 focus:outline-none rounded p-2 min-h-[80px] resize-y",onClick:h=>h.stopPropagation()}):e.jsx("p",{className:"text-muted-foreground mb-3",children:c.description}),e.jsxs("div",{className:"bg-green-50 border-l-4 border-green-500 p-3 rounded",children:[e.jsx("span",{className:"text-sm font-medium text-green-900",children:"Impact: "}),n&&r?e.jsx("input",{type:"text",value:c.impact,onChange:h=>r(u,"impact",h.target.value),className:"text-sm text-green-800 bg-transparent border-b border-dashed border-green-400 focus:border-green-600 focus:outline-none w-full",onClick:h=>h.stopPropagation()}):e.jsx("span",{className:"text-sm text-green-800",children:c.impact})]})]},u)})}),e.jsx("div",{className:"h-24"}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4 shadow-lg z-20",children:e.jsxs("div",{className:"max-w-4xl mx-auto grid grid-cols-2 gap-4",children:[e.jsx("div",{}),e.jsx("button",{onClick:s,className:"bg-primary text-primary-foreground px-8 py-3 rounded-xl font-semibold hover:bg-primary/90 transition-colors shadow-md",children:"Next: Structure Issues â"})]})}),e.jsx(di,{open:d!==null,onOpenChange:c=>{c||m(null)},title:"Delete this recommendation?",description:"This recommendation will be removed from the presentation.",confirmLabel:"Delete",destructive:!0,onConfirm:()=>{d!==null&&a&&a(d),m(null)}})]})},px=({data:t,onNext:s,onBack:n,editMode:r,onEditRecommendation:a,onDeleteRecommendation:o})=>{const[i,d]=ee.useState(new Set),[m,p]=ee.useState(null);l.useEffect(()=>{t.score>=90&&va({particleCount:100,spread:70,origin:{y:.6}})},[t.score]);const c=u=>{d(x=>{const h=new Set(x);return h.has(u)?h.delete(u):h.add(u),h})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8 mt-12",children:[e.jsx("h1",{className:"mb-2 text-foreground",style:{fontSize:"24px",fontWeight:700},children:"Structure Issues"}),e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx("span",{className:"text-lg text-muted-foreground",children:"Your Score:"}),e.jsxs("span",{className:`text-4xl font-bold ${t.score>=80?"text-green-600":t.score>=50?"text-yellow-600":"text-red-600"}`,children:[t.score,"/100"]})]})]}),e.jsx("div",{className:"bg-primary/10 border border-primary/20 rounded-2xl p-4 mb-6",children:e.jsx("p",{className:"text-foreground",children:"Your site's structure affects both user experience and search engine rankings. Broken links frustrate users, while proper SSL and mobile responsiveness are essential for credibility and SEO."})}),e.jsx("div",{className:"space-y-4",children:t.recommendations.map((u,x)=>{const h=i.has(x);return e.jsxs("div",{onClick:()=>!r&&c(x),style:{borderWidth:"4px",borderStyle:"solid",borderColor:u.effort==="small"?"#22c55e":u.effort==="medium"?"#eab308":u.effort==="large"?"#ef4444":"var(--border)",transform:h&&!r?"scale(1.05)":"scale(1)",boxShadow:h&&!r?"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)":"none",transition:"transform 0.3s ease, box-shadow 0.3s ease"},className:`bg-card rounded-2xl p-6 relative ${r?"":"cursor-pointer"}`,children:[r&&o&&e.jsx("button",{onClick:b=>{b.stopPropagation(),p(x)},className:"absolute top-4 right-4 p-2 bg-red-100 text-red-600 rounded-full hover:bg-red-200 transition-colors",title:"Delete recommendation",children:e.jsx(zs,{className:"w-4 h-4"})}),!r&&u.effort&&e.jsx("div",{className:`absolute top-4 right-4 px-3 py-1 rounded-full text-xs font-semibold ${u.effort==="small"?"bg-green-100 text-green-700":u.effort==="medium"?"bg-yellow-100 text-yellow-700":"bg-red-100 text-red-700"}`,children:u.effort==="small"?"Easy":u.effort==="medium"?"Medium":"Complex"}),r&&a?e.jsx("input",{type:"text",value:u.title,onChange:b=>a(x,"title",b.target.value),className:"text-xl font-semibold mb-2 text-foreground pr-12 w-full bg-transparent border-b-2 border-dashed border-amber-300 focus:border-amber-500 focus:outline-none",onClick:b=>b.stopPropagation()}):e.jsx("h3",{className:"text-xl font-semibold mb-2 text-foreground pr-20",children:u.title}),r&&a?e.jsx("textarea",{value:u.description,onChange:b=>a(x,"description",b.target.value),className:"text-muted-foreground mb-3 w-full bg-transparent border-2 border-dashed border-amber-300 focus:border-amber-500 focus:outline-none rounded p-2 min-h-[80px] resize-y",onClick:b=>b.stopPropagation()}):e.jsx("p",{className:"text-muted-foreground mb-3",children:u.description}),e.jsxs("div",{className:"bg-green-50 border-l-4 border-green-500 p-3 rounded",children:[e.jsx("span",{className:"text-sm font-medium text-green-900",children:"Impact: "}),r&&a?e.jsx("input",{type:"text",value:u.impact,onChange:b=>a(x,"impact",b.target.value),className:"text-sm text-green-800 bg-transparent border-b border-dashed border-green-400 focus:border-green-600 focus:outline-none w-full",onClick:b=>b.stopPropagation()}):e.jsx("span",{className:"text-sm text-green-800",children:u.impact})]})]},x)})}),e.jsx("div",{className:"h-24"}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4 shadow-lg z-20",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex gap-4",children:[e.jsx("button",{onClick:n,className:"flex-1 bg-card border-2 border-border text-foreground px-6 py-3 rounded-xl font-semibold hover:bg-muted transition-colors shadow-sm",children:"â Back"}),e.jsx("button",{onClick:s,className:"flex-1 bg-primary text-primary-foreground px-6 py-3 rounded-xl font-semibold hover:bg-primary/90 transition-colors shadow-md",children:"Next: Content Issues â"})]})}),e.jsx(di,{open:m!==null,onOpenChange:u=>{u||p(null)},title:"Delete this recommendation?",description:"This recommendation will be removed from the presentation.",confirmLabel:"Delete",destructive:!0,onConfirm:()=>{m!==null&&o&&o(m),p(null)}})]})},xx=({data:t,onNext:s,onBack:n,editMode:r,onEditRecommendation:a,onDeleteRecommendation:o})=>{const[i,d]=ee.useState(new Set),[m,p]=ee.useState(null);l.useEffect(()=>{t.score>=90&&va({particleCount:100,spread:70,origin:{y:.6}})},[t.score]);const c=u=>{d(x=>{const h=new Set(x);return h.has(u)?h.delete(u):h.add(u),h})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8 mt-12",children:[e.jsx("h1",{className:"mb-2 text-foreground",style:{fontSize:"24px",fontWeight:700},children:"Content Issues"}),e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx("span",{className:"text-lg text-muted-foreground",children:"Your Score:"}),e.jsxs("span",{className:`text-4xl font-bold ${t.score>=80?"text-green-600":t.score>=50?"text-yellow-600":"text-red-600"}`,children:[t.score,"/100"]})]})]}),e.jsx("div",{className:"bg-primary/10 border border-primary/20 rounded-2xl p-4 mb-6",children:e.jsx("p",{className:"text-foreground",children:"Clear communication builds trust and drives action. Your headline should immediately tell visitors what you do and why it matters. Trust signals like testimonials and credentials reassure potential customers."})}),e.jsx("div",{className:"space-y-4",children:t.recommendations.map((u,x)=>{const h=i.has(x);return e.jsxs("div",{onClick:()=>!r&&c(x),style:{borderWidth:"4px",borderStyle:"solid",borderColor:u.effort==="small"?"#22c55e":u.effort==="medium"?"#eab308":u.effort==="large"?"#ef4444":"var(--border)",transform:h&&!r?"scale(1.05)":"scale(1)",boxShadow:h&&!r?"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)":"none",transition:"transform 0.3s ease, box-shadow 0.3s ease"},className:`bg-card rounded-2xl p-6 relative ${r?"":"cursor-pointer"}`,children:[r&&o&&e.jsx("button",{onClick:b=>{b.stopPropagation(),p(x)},className:"absolute top-4 right-4 p-2 bg-red-100 text-red-600 rounded-full hover:bg-red-200 transition-colors",title:"Delete recommendation",children:e.jsx(zs,{className:"w-4 h-4"})}),!r&&u.effort&&e.jsx("div",{className:`absolute top-4 right-4 px-3 py-1 rounded-full text-xs font-semibold ${u.effort==="small"?"bg-green-100 text-green-700":u.effort==="medium"?"bg-yellow-100 text-yellow-700":"bg-red-100 text-red-700"}`,children:u.effort==="small"?"Easy":u.effort==="medium"?"Medium":"Complex"}),r&&a?e.jsx("input",{type:"text",value:u.title,onChange:b=>a(x,"title",b.target.value),className:"text-xl font-semibold mb-2 text-foreground pr-12 w-full bg-transparent border-b-2 border-dashed border-amber-300 focus:border-amber-500 focus:outline-none",onClick:b=>b.stopPropagation()}):e.jsx("h3",{className:"text-xl font-semibold mb-2 text-foreground pr-20",children:u.title}),r&&a?e.jsx("textarea",{value:u.description,onChange:b=>a(x,"description",b.target.value),className:"text-muted-foreground mb-3 w-full bg-transparent border-2 border-dashed border-amber-300 focus:border-amber-500 focus:outline-none rounded p-2 min-h-[80px] resize-y",onClick:b=>b.stopPropagation()}):e.jsx("p",{className:"text-muted-foreground mb-3",children:u.description}),e.jsxs("div",{className:"bg-green-50 border-l-4 border-green-500 p-3 rounded",children:[e.jsx("span",{className:"text-sm font-medium text-green-900",children:"Impact: "}),r&&a?e.jsx("input",{type:"text",value:u.impact,onChange:b=>a(x,"impact",b.target.value),className:"text-sm text-green-800 bg-transparent border-b border-dashed border-green-400 focus:border-green-600 focus:outline-none w-full",onClick:b=>b.stopPropagation()}):e.jsx("span",{className:"text-sm text-green-800",children:u.impact})]})]},x)})}),e.jsx("div",{className:"h-24"}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4 shadow-lg z-20",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex gap-4",children:[e.jsx("button",{onClick:n,className:"flex-1 bg-card border-2 border-border text-foreground px-6 py-3 rounded-xl font-semibold hover:bg-muted transition-colors shadow-sm",children:"â Back"}),e.jsx("button",{onClick:s,className:"flex-1 bg-primary text-primary-foreground px-6 py-3 rounded-xl font-semibold hover:bg-primary/90 transition-colors shadow-md",children:"Next: Marketing & SEO â"})]})}),e.jsx(di,{open:m!==null,onOpenChange:u=>{u||p(null)},title:"Delete this recommendation?",description:"This recommendation will be removed from the presentation.",confirmLabel:"Delete",destructive:!0,onConfirm:()=>{m!==null&&o&&o(m),p(null)}})]})},hx=({data:t,onNext:s,onBack:n,editMode:r,onEditRecommendation:a,onDeleteRecommendation:o})=>{var u,x,h,b;const[i,d]=ee.useState(new Set),[m,p]=ee.useState(null);l.useEffect(()=>{t.score>=90&&va({particleCount:100,spread:70,origin:{y:.6}})},[t.score]);const c=f=>{d(g=>{const y=new Set(g);return y.has(f)?y.delete(f):y.add(f),y})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8 mt-12",children:[e.jsx("h1",{className:"mb-2 text-foreground",style:{fontSize:"24px",fontWeight:700},children:"Marketing & SEO"}),e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx("span",{className:"text-lg text-muted-foreground",children:"Your Score:"}),e.jsxs("span",{className:`text-4xl font-bold ${t.score>=80?"text-green-600":t.score>=50?"text-yellow-600":"text-red-600"}`,children:[t.score,"/100"]})]})]}),e.jsx("div",{className:"bg-primary/10 border border-primary/20 rounded-2xl p-4 mb-6",children:e.jsx("p",{className:"text-foreground",children:"SEO and analytics are critical for long-term growth. Proper meta tags help search engines understand your content, while analytics show you what's working and where to improve. A solid content strategy attracts and converts visitors."})}),t.seoData&&e.jsxs("div",{className:"space-y-4 mb-8",children:[e.jsxs("div",{className:"bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-2xl p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-blue-800 mb-4",children:"Organic Search Presence"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-blue-600",children:((u=t.seoData.organicKeywords)==null?void 0:u.toLocaleStr
86ing())||0}),e.jsx("div",{className:"text-sm text-gray-600",children:"Keywords Ranked"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-green-600",children:((x=t.seoData.organicTraffic)==null?void 0:x.toLocaleString())||0}),e.jsx("div",{className:"text-sm text-gray-600",children:"Organic Traffic/mo"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-orange-600",children:((h=t.seoData.paidTraffic)==null?void 0:h.toLocaleString())||0}),e.jsx("div",{className:"text-sm text-gray-600",children:"Paid Traffic/mo"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-purple-600",children:((b=t.seoData.totalSearchVolume)==null?void 0:b.toLocaleString())||0}),e.jsx("div",{className:"text-sm text-gray-600",children:"Total Search Vol"})]})]})]}),t.seoData.topKeywords&&t.seoData.topKeywords.length>0&&e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-4",children:"Top Ranking Keywords"}),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-border",children:[e.jsx("th",{className:"text-left py-2 px-3 font-medium text-muted-foreground",children:"Keyword"}),e.jsx("th",{className:"text-center py-2 px-3 font-medium text-muted-foreground",children:"Position"}),e.jsx("th",{className:"text-center py-2 px-3 font-medium text-muted-foreground",children:"Change"}),e.jsx("th",{className:"text-center py-2 px-3 font-medium text-muted-foreground",children:"Volume"}),e.jsx("th",{className:"text-center py-2 px-3 font-medium text-muted-foreground",children:"Intent"})]})}),e.jsx("tbody",{children:t.seoData.topKeywords.slice(0,8).map((f,g)=>{var j,v,T;const y=f.previousPosition?f.previousPosition-f.position:0;return e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("td",{className:"py-2 px-3 max-w-[200px] truncate",title:f.keyword,children:f.keyword}),e.jsx("td",{className:"text-center py-2 px-3",children:e.jsx("span",{className:`font-semibold ${f.position<=3?"text-green-600":f.position<=10?"text-yellow-600":"text-gray-600"}`,children:f.position})}),e.jsxs("td",{className:"text-center py-2 px-3",children:[y!==0&&e.jsx("span",{className:`text-xs font-medium ${y>0?"text-green-600":"text-red-600"}`,children:y>0?`â${y}`:`â${Math.abs(y)}`}),y===0&&e.jsx("span",{className:"text-gray-400",children:"â"})]}),e.jsx("td",{className:"text-center py-2 px-3 text-gray-600",children:(j=f.searchVolume)==null?void 0:j.toLocaleString()}),e.jsx("td",{className:"text-center py-2 px-3",children:e.jsxs("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${f.intent==="commercial"?"bg-orange-100 text-orange-700":f.intent==="transactional"?"bg-green-100 text-green-700":f.intent==="informational"?"bg-blue-100 text-blue-700":"bg-purple-100 text-purple-700"}`,children:[(v=f.intent)==null?void 0:v.charAt(0).toUpperCase(),(T=f.intent)==null?void 0:T.slice(1)]})})]},g)})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[t.seoData.positionChanges&&e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-4",children:"Position Changes (Year)"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 px-3 py-1 bg-green-100 rounded-lg",children:[e.jsx("span",{className:"text-green-600 font-bold",children:"â"}),e.jsx("span",{className:"text-green-700 font-semibold",children:t.seoData.positionChanges.improved||0})]}),e.jsxs("div",{className:"flex items-center gap-1 px-3 py-1 bg-red-100 rounded-lg",children:[e.jsx("span",{className:"text-red-600 font-bold",children:"â"}),e.jsx("span",{className:"text-red-700 font-semibold",children:t.seoData.positionChanges.declined||0})]}),e.jsxs("div",{className:"flex items-center gap-1 px-3 py-1 bg-gray-100 rounded-lg",children:[e.jsx("span",{className:"text-gray-600",children:"="}),e.jsx("span",{className:"text-gray-700 font-semibold",children:t.seoData.positionChanges.unchanged||0})]})]})]}),t.seoData.keywordsByIntent&&e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-4",children:"Keyword Intent Mix"}),e.jsx("div",{className:"space-y-3",children:(()=>{const f=t.seoData.keywordsByIntent,g=(f.commercial||0)+(f.informational||0)+(f.navigational||0)+(f.transactional||0),y=j=>g>0?Math.round(j/g*100):0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Commercial"}),e.jsxs("span",{className:"text-sm text-orange-600 font-semibold",children:[y(f.commercial||0),"%"]})]}),e.jsx("div",{className:"h-3 bg-gray-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-orange-500 transition-all",style:{width:`${y(f.commercial||0)}%`}})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Informational"}),e.jsxs("span",{className:"text-sm text-blue-600 font-semibold",children:[y(f.informational||0),"%"]})]}),e.jsx("div",{className:"h-3 bg-gray-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-500 transition-all",style:{width:`${y(f.informational||0)}%`}})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Navigational"}),e.jsxs("span",{className:"text-sm text-purple-600 font-semibold",children:[y(f.navigational||0),"%"]})]}),e.jsx("div",{className:"h-3 bg-gray-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-purple-500 transition-all",style:{width:`${y(f.navigational||0)}%`}})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Transactional"}),e.jsxs("span",{className:"text-sm text-green-600 font-semibold",children:[y(f.transactional||0),"%"]})]}),e.jsx("div",{className:"h-3 bg-gray-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-green-500 transition-all",style:{width:`${y(f.transactional||0)}%`}})})]})]})})()})]})]})]}),e.jsx("div",{className:"space-y-4",children:t.recommendations.map((f,g)=>{const y=i.has(g);return e.jsxs("div",{onClick:()=>!r&&c(g),style:{borderWidth:"4px",borderStyle:"solid",borderColor:f.effort==="small"?"#22c55e":f.effort==="medium"?"#eab308":f.effort==="large"?"#ef4444":"var(--border)",transform:y&&!r?"scale(1.05)":"scale(1)",boxShadow:y&&!r?"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)":"none",transition:"transform 0.3s ease, box-shadow 0.3s ease"},className:`bg-card rounded-2xl p-6 relative ${r?"":"cursor-pointer"}`,children:[r&&o&&e.jsx("button",{onClick:j=>{j.stopPropagation(),p(g)},className:"absolute top-4 right-4 p-2 bg-red-100 text-red-600 rounded-full hover:bg-red-200 transition-colors",title:"Delete recommendation",children:e.jsx(zs,{className:"w-4 h-4"})}),!r&&f.effort&&e.jsx("div",{className:`absolute top-4 right-4 px-3 py-1 rounded-full text-xs font-semibold ${f.effort==="small"?"bg-green-100 text-green-700":f.effort==="medium"?"bg-yellow-100 text-yellow-700":"bg-red-100 text-red-700"}`,children:f.effort==="small"?"Easy":f.effort==="medium"?"Medium":"Complex"}),r&&a?e.jsx("input",{type:"text",value:f.title,onChange:j=>a(g,"title",j.target.value),className:"text-xl font-semibold mb-2 text-foreground pr-12 w-full bg-transparent border-b-2 border-dashed border-amber-300 focus:border-amber-500 focus:outline-none",onClick:j=>j.stopPropagation()}):e.jsx("h3",{className:"text-xl font-semibold mb-2 text-foreground pr-20",children:f.title}),r&&a?e.jsx("textarea",{value:f.description,onChange:j=>a(g,"description",j.target.value),className:"text-muted-foreground mb-3 w-full bg-transparent border-2 border-dashed border-amber-300 focus:border-amber-500 focus:outline-none rounded p-2 min-h-[80px] resize-y",onClick:j=>j.stopPropagation()}):e.jsx("p",{className:"text-muted-foreground mb-3",children:f.description}),e.jsxs("div",{className:"bg-green-50 border-l-4 border-green-500 p-3 rounded",children:[e.jsx("span",{className:"text-sm font-medium text-green-900",children:"Impact: "}),r&&a?e.jsx("input",{type:"text",value:f.impact,onChange:j=>a(g,"impact",j.target.value),className:"text-sm text-green-800 bg-transparent border-b border-dashed border-green-400 focus:border-green-600 focus:outline-none w-full",onClick:j=>j.stopPropagation()}):e.jsx("span",{className:"text-sm text-green-800",children:f.impact})]})]},g)})}),e.jsx("div",{className:"h-24"}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4 shadow-lg z-20",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex gap-4",children:[e.jsx("button",{onClick:n,className:"flex-1 bg-card border-2 border-border text-foreground px-6 py-3 rounded-xl font-semibold hover:bg-muted transition-colors shadow-sm",children:"â Back"}),e.jsx("button",{onClick:s,className:"flex-1 bg-primary text-primary-foreground px-6 py-3 rounded-xl font-semibold hover:bg-primary/90 transition-colors shadow-md",children:"Next: Build Your Plan â"})]})}),e.jsx(di,{open:m!==null,onOpenChange:f=>{f||p(null)},title:"Delete this recommendation?",description:"This recommendation will be removed from the presentation.",confirmLabel:"Delete",destructive:!0,onConfirm:()=>{m!==null&&o&&o(m),p(null)}})]})},RI=t=>({"top-left":{x:25,y:25},"top-center":{x:50,y:25},"top-right":{x:75,y:25},"center-left":{x:25,y:50},center:{x:50,y:50},"center-right":{x:75,y:50},"bottom-left":{x:25,y:75},"bottom-center":{x:50,y:75},"bottom-right":{x:75,y:75}})[t]||{x:50,y:50},DI=({strokeWidth:t=.3})=>e.jsxs("svg",{className:"absolute inset-0 w-full h-full pointer-events-none",viewBox:"0 0 100 100",preserveAspectRatio:"none",children:[e.jsx("line",{x1:"33.33",y1:"0",x2:"33.33",y2:"100",stroke:"rgba(0,0,0,0.9)",strokeWidth:t}),e.jsx("line",{x1:"66.66",y1:"0",x2:"66.66",y2:"100",stroke:"rgba(0,0,0,0.9)",strokeWidth:t}),e.jsx("line",{x1:"0",y1:"33.33",x2:"100",y2:"33.33",stroke:"rgba(0,0,0,0.9)",strokeWidth:t}),e.jsx("line",{x1:"0",y1:"66.66",x2:"100",y2:"66.66",stroke:"rgba(0,0,0,0.9)",strokeWidth:t}),e.jsx("circle",{cx:"33.33",cy:"33.33",r:"1.5",fill:"rgba(0,0,0,0.9)"}),e.jsx("circle",{cx:"66.66",cy:"33.33",r:"1.5",fill:"rgba(0,0,0,0.9)"}),e.jsx("circle",{cx:"33.33",cy:"66.66",r:"1.5",fill:"rgba(0,0,0,0.9)"}),e.jsx("circle",{cx:"66.66",cy:"66.66",r:"1.5",fill:"rgba(0,0,0,0.9)"})]}),MI=({strokeWidth:t=7})=>e.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none",viewBox:"0 0 1092.96 1756.18",preserveAspectRatio:"xMidYMid meet",children:e.jsxs("g",{fill:"none",stroke:"#FFD700",strokeMiterlimit:10,strokeWidth:t,children:[e.jsx("path",{d:"M829.67,1276.73c0-20.51-16.59-37.1-37.1-37.1"}),e.jsx("path",{d:"M769.58,1336.33c33.18,0,60.03-26.85,60.03-60.03"}),e.jsx("path",{d:"M673.14,1239.1c0,53.69,43.45,97.14,97.13,97.14"}),e.jsx("path",{d:"M830.46,1083.04c-86.88,0-157.18,70.3-157.18,157.18"}),e.jsx("path",{d:"M1082.96,1337.61c0-140.58-113.74-254.33-254.31-254.33"}),e.jsx("path",{d:"M671.08,1746.18c227.45,0,411.51-184.05,411.51-411.51"}
86),e.jsx("path",{d:"M10,1079.71c0,368.05,297.8,665.87,665.82,665.87"}),e.jsx("path",{d:"M1088.36,10c-595.5,0-1077.37,481.87-1077.37,1077.37"})]})}),PI=({strokeWidth:t=.4})=>e.jsxs("svg",{className:"absolute inset-0 w-full h-full pointer-events-none",viewBox:"0 0 100 100",preserveAspectRatio:"none",children:[e.jsx("line",{x1:"0",y1:"100",x2:"50",y2:"50",stroke:"rgba(0,150,255,0.8)",strokeWidth:t*2}),e.jsx("line",{x1:"100",y1:"100",x2:"50",y2:"50",stroke:"rgba(0,150,255,0.8)",strokeWidth:t*2}),e.jsx("line",{x1:"0",y1:"0",x2:"50",y2:"50",stroke:"rgba(0,150,255,0.6)",strokeWidth:t*1.5,strokeDasharray:"3,2"}),e.jsx("line",{x1:"100",y1:"0",x2:"50",y2:"50",stroke:"rgba(0,150,255,0.6)",strokeWidth:t*1.5,strokeDasharray:"3,2"}),e.jsx("line",{x1:"0",y1:"50",x2:"100",y2:"50",stroke:"rgba(0,150,255,0.5)",strokeWidth:t,strokeDasharray:"5,3"}),e.jsx("polygon",{points:"50,45 47,52 53,52",fill:"rgba(0,150,255,0.9)"}),e.jsx("circle",{cx:"50",cy:"50",r:"2",fill:"rgba(0,150,255,0.9)"})]}),LI=({strokeWidth:t=.3})=>e.jsxs("svg",{className:"absolute inset-0 w-full h-full pointer-events-none",viewBox:"0 0 100 100",preserveAspectRatio:"none",children:[e.jsx("rect",{x:"5",y:"5",width:"90",height:"20",fill:"rgba(150,200,150,0.25)",stroke:"rgba(0,128,0,0.6)",strokeWidth:t,strokeDasharray:"3,2",rx:"2"}),e.jsx("rect",{x:"5",y:"30",width:"15",height:"40",fill:"rgba(150,200,150,0.25)",stroke:"rgba(0,128,0,0.6)",strokeWidth:t,strokeDasharray:"3,2",rx:"2"}),e.jsx("rect",{x:"80",y:"30",width:"15",height:"40",fill:"rgba(150,200,150,0.25)",stroke:"rgba(0,128,0,0.6)",strokeWidth:t,strokeDasharray:"3,2",rx:"2"}),e.jsx("rect",{x:"25",y:"30",width:"50",height:"45",fill:"none",stroke:"rgba(0,128,0,0.8)",strokeWidth:t*2,rx:"2"}),e.jsx("text",{x:"50",y:"55",textAnchor:"middle",fontSize:"4",fill:"rgba(0,128,0,0.9)",fontWeight:"bold",children:"CONTENT"}),e.jsx("rect",{x:"5",y:"80",width:"90",height:"15",fill:"rgba(150,200,150,0.25)",stroke:"rgba(0,128,0,0.6)",strokeWidth:t,strokeDasharray:"3,2",rx:"2"})]}),zI=({location:t,strokeWidth:s=.4})=>{const n=RI(t);return e.jsxs("svg",{className:"absolute inset-0 w-full h-full pointer-events-none",viewBox:"0 0 100 100",preserveAspectRatio:"none",children:[e.jsx("line",{x1:n.x,y1:"0",x2:n.x,y2:"100",stroke:"rgba(220,20,60,0.5)",strokeWidth:s,strokeDasharray:"4,2"}),e.jsx("line",{x1:"0",y1:n.y,x2:"100",y2:n.y,stroke:"rgba(220,20,60,0.5)",strokeWidth:s,strokeDasharray:"4,2"}),e.jsx("circle",{cx:n.x,cy:n.y,r:"12",fill:"none",stroke:"rgba(220,20,60,0.4)",strokeWidth:s}),e.jsx("circle",{cx:n.x,cy:n.y,r:"8",fill:"none",stroke:"rgba(220,20,60,0.6)",strokeWidth:s}),e.jsx("circle",{cx:n.x,cy:n.y,r:"4",fill:"none",stroke:"rgba(220,20,60,0.8)",strokeWidth:s*1.5}),e.jsx("circle",{cx:n.x,cy:n.y,r:"1.5",fill:"rgba(220,20,60,0.9)"}),e.jsx("text",{x:n.x,y:n.y-16,textAnchor:"middle",fontSize:"3.5",fill:"rgba(220,20,60,1)",fontWeight:"bold",children:"FOCAL"})]})},fx=({techniques:t,selectedOverlay:s,onSelect:n,focalScore:r=0})=>{const a=[{key:"ruleOfThirds",label:"Thirds",score:t.ruleOfThirds.score,color:"bg-gray-700"},{key:"goldenRatio",label:"Golden",score:t.goldenRatio.score,color:"bg-orange-500"},{key:"leadingLines",label:"Lines",score:t.leadingLines.score,color:"bg-blue-500"},{key:"negativeSpace",label:"Space",score:t.negativeSpace.score,color:"bg-green-500"},{key:"focalPoint",label:"Focal",score:r,color:"bg-red-500"}];return e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map(o=>e.jsxs("button",{onClick:i=>{i.stopPropagation(),n(s===o.key?"none":o.key)},className:`px-2 py-0.5 rounded text-[10px] font-medium transition-colors ${s===o.key?`${o.color} text-white`:"bg-white/80 text-gray-700 hover:bg-white"}`,children:[o.label," (",o.score,")"]},o.key))})},gx=({data:t,onNext:s,onBack:n})=>{var j,v,T,k,w,I,A,E;const[r,a]=l.useState(null),[o,i]=l.useState(!1),[d,m]=l.useState({}),p=C=>{var z,D,L,$,q,P;if(!((z=C.composition)!=null&&z.compositionTechniques))return"ruleOfThirds";const N=C.composition.compositionTechniques,S=((D=C.composition.focalPoint)==null?void 0:D.effectiveness)||0,O=[{key:"ruleOfThirds",score:((L=N.ruleOfThirds)==null?void 0:L.score)||0},{key:"goldenRatio",score:(($=N.goldenRatio)==null?void 0:$.score)||0},{key:"leadingLines",score:((q=N.leadingLines)==null?void 0:q.score)||0},{key:"negativeSpace",score:((P=N.negativeSpace)==null?void 0:P.score)||0},{key:"focalPoint",score:S}];let R=O[0];for(let U=1;U<O.length;U++)O[U].score>R.score&&(R=O[U]);return R.key},c=C=>d[C]!==void 0?d[C]:p(t.pages[C]),u=(C,N)=>{m(S=>({...S,[C]:N}))},x=(C,N,S)=>{var O,R;switch(C){case"ruleOfThirds":return e.jsx(DI,{strokeWidth:S});case"goldenRatio":return e.jsx(MI,{});case"leadingLines":return e.jsx(PI,{strokeWidth:S});case"negativeSpace":return e.jsx(LI,{strokeWidth:S});case"focalPoint":return e.jsx(zI,{location:((R=(O=N.composition)==null?void 0:O.focalPoint)==null?void 0:R.location)||"center",strokeWidth:S});case"none":default:return null}},h=C=>C>=80?"text-green-600":C>=50?"text-yellow-600":"text-red-600",b=C=>C>=80?"bg-green-100 text-green-800":C>
86=50?"bg-yellow-100 text-yellow-800":"bg-red-100 text-red-800",f=C=>{a(C),i(!0)},g=()=>{i(!1),a(null)},y=r!==null?t.pages[r]:null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8 mt-12",children:[e.jsx("h1",{className:"mb-2 text-foreground",style:{fontSize:"24px",fontWeight:700},children:"Visual Design & Composition"}),e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx("span",{className:"text-lg text-muted-foreground",children:"Your Score:"}),e.jsxs("span",{className:`text-4xl font-bold ${h(t.score)}`,children:[t.score,"/100"]})]})]}),t.analysisPending&&e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-2xl p-4 mb-6",children:e.jsx("p",{className:"text-amber-800",children:"Visual analysis is pending. Screenshots have been captured but AI composition analysis hasn't been run yet."})}),t.overallAnalysis&&!t.analysisPending&&e.jsx("div",{className:"bg-primary/10 border border-primary/20 rounded-2xl p-4 mb-6",children:e.jsx("p",{className:"text-foreground",children:t.overallAnalysis})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Page Screenshots"}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:(j=t.pages)==null?void 0:j.map((C,N)=>{var S,O,R,z,D,L,$,q,P,U,V,M,F,W,_,G;return e.jsxs("div",{className:"bg-card border-2 border-border rounded-xl overflow-hidden cursor-pointer hover:border-primary transition-colors",onClick:()=>f(N),children:[e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden bg-muted",children:[e.jsx("img",{src:(S=C.screenshot)==null?void 0:S.storageUrl,alt:`${(O=C.screenshot)==null?void 0:O.pageType} screenshot`,className:"w-full h-full object-cover object-top"}),x(c(N),C,.3),e.jsx("div",{className:"absolute top-2 right-2 z-[5]",children:e.jsx("div",{className:`px-2 py-1 rounded-full font-bold text-sm ${b(C.score)}`,children:C.score})}),e.jsx("div",{className:"absolute top-2 left-2 z-[5] bg-black/70 text-white px-2 py-1 rounded-lg text-xs font-medium capitalize",children:(R=C.screenshot)==null?void 0:R.pageType}),((z=C.composition)==null?void 0:z.compositionTechniques)&&!t.analysisPending&&e.jsx("div",{className:"absolute bottom-2 left-2 right-2 z-[5]",children:e.jsx(fx,{techniques:C.composition.compositionTechniques,selectedOverlay:c(N),onSelect:B=>u(N,B),focalScore:((D=C.composition.focalPoint)==null?void 0:D.effectiveness)||0})})]}),C.composition&&!t.analysisPending&&e.jsxs("div",{className:"p-2 bg-muted/80 border-t border-border",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-1 text-[10px]",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Focal:"}),e.jsx("span",{className:"font-semibold text-foreground truncate",children:(($=(L=C.composition.focalPoint)==null?void 0:L.location)==null?void 0:$.split("-")[0])||"center"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Flow:"}),e.jsx("span",{className:"font-semibold text-foreground capitalize truncate",children:((q=C.composition.visualFlow)==null?void 0:q.pattern)||"linear"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Thirds:"}),e.jsx("span",{className:"font-semibold text-foreground",children:((U=(P=C.composition.compositionTechniques)==null?void 0:P.ruleOfThirds)==null?void 0:U.score)||0})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Space:"}),e.jsx("span",{className:"font-semibold text-foreground",children:((M=(V=C.composition.compositionTechniques)==null?void 0:V.negativeSpace)==null?void 0:M.score)||0})]})]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5",children:[e.jsxs("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium text-white ${(F=C.composition.ctaProminence)!=null&&F.visible?"bg-green-500":"bg-red-500"}`,children:["CTA ",(W=C.composition.ctaProminence)!=null&&W.visible?"â":"â"]}),e.jsxs("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium text-white ${(_=C.composition.ctaProminence)!=null&&_.thumbZoneOptimal?"bg-green-500":"bg-yellow-500"}`,children:["Thumb ",(G=C.composition.ctaProminence)!=null&&G.thumbZoneOptimal?"â":"~"]})]})]}),e.jsx("div",{className:"p-2 bg-muted/50 text-center border-t border-border",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Tap for details"})})]},N)})})]}),t.recommendations&&t.recommendations.length>
860&&!t.analysisPending&&e.jsxs("div",{className:"space-y-4 mt-8",children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Recommendations"}),t.recommendations.slice(0,3).map((C,N)=>e.jsxs("div",{className:"bg-card border-2 border-border rounded-2xl p-5",children:[e.jsx("h3",{className:"text-lg font-semibold mb-2 text-foreground",children:C.title}),e.jsx("p",{className:"text-muted-foreground",children:C.description}),C.impact&&e.jsxs("div",{className:"mt-3 bg-green-50 border-l-4 border-green-500 p-3 rounded",children:[e.jsx("span",{className:"text-sm font-medium text-green-900",children:"Impact: "}),e.jsx("span",{className:"text-sm text-green-800",children:C.impact})]})]},N))]}),e.jsx("div",{className:"h-24"}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4 shadow-lg z-20 no-print",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex gap-4",children:[e.jsx("button",{onClick:n,className:"flex-1 bg-card border-2 border-border text-foreground px-6 py-3 rounded-xl font-semibold hover:bg-muted transition-colors shadow-sm",children:"â Back"}),e.jsx("button",{onClick:s,className:"flex-1 bg-primary text-primary-foreground px-6 py-3 rounded-xl font-semibold hover:bg-primary/90 transition-colors shadow-md",children:"Next: Build Your Plan â"})]})}),o&&y&&e.jsx("div",{className:"fixed inset-0 bg-black/90 z-50 overflow-y-auto",onClick:g,children:e.jsx("div",{className:"min-h-full flex items-start justify-center p-4 py-8",children:e.jsxs("div",{className:"bg-card rounded-2xl max-w-lg w-full",onClick:C=>C.stopPropagation(),children:[e.jsxs("div",{className:"sticky top-0 bg-card rounded-t-2xl border-b border-border p-4 flex items-center justify-between z-10",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("h2",{className:"text-xl font-bold text-foreground capitalize",children:[(v=y.screenshot)==null?void 0:v.pageType," Page"]}),e.jsx("div",{className:`px-3 py-1 rounded-full font-bold ${b(y.score)}`,children:y.score})]}),e.jsx("button",{onClick:g,className:"p-2 hover:bg-muted rounded-full transition-colors",children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),e.jsxs("div",{className:"bg-muted p-4",children:[e.jsx("div",{className:"flex justify-center",children:e.jsxs("div",{className:"relative",style:{maxWidth:"375px"},children:[e.jsx("img",{src:(T=y.screenshot)==null?void 0:T.storageUrl,alt:`${(k=y.screenshot)==null?void 0:k.pageType} screenshot`,className:"w-full max-h-[60vh] object-contain rounded-lg"}),e.jsx("div",{className:"absolute inset-0 rounded-lg overflow-hidden",children:x(c(r),y,.2)})]})}),((w=y.composition)==null?void 0:w.compositionTechniques)&&!t.analysisPending&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx(fx,{techniques:y.composition.compositionTechniques,selectedOverlay:c(r),onSelect:C=>u(r,C),focalScore:((I=y.composition.focalPoint)==null?void 0:I.effectiveness)||0})})]}),e.jsxs("div",{className:"p-4 space-y-4",children:[y.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:y.summary}),y.composition&&!t.analysisPending&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-muted/50 rounded-xl p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-2 text-sm",children:"Focal Point"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Location:"}),e.jsx("span",{className:"ml-1 text-foreground",children:y.composition.focalPoint.location})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Effectiveness:"}),e.jsxs("span",{className:`ml-1 font-medium ${h(y.composition.focalPoint.effectiveness)}`,children:[y.composition.focalPoint.effectiveness,"%"]})]})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-xl p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-2 text-sm",children:"Visual Flow"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Pattern:"}),e.jsx("span",{className:"ml-1 text-foreground capitalize",children:y.composition.visualFlow.pattern})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Strength:"}),e.jsxs("span",{className:`ml-1 font-medium ${h(y.composition.visualFlow.strength)}`,children:[y.composition.visualFlow.strength,"%"]})]})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-xl p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-2 text-sm",children:"Composition Techniques"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Rule of Thirds:"}),e.jsx("span",{className:`font-medium ${h(y.composition.compositionTechniques.ruleOfThirds.score)}`,children:y.composition.compositionTechniques.ruleOfThirds.score})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Golden Ratio:"}),e.jsx("span",{className:`font-medium ${h(y.composition.compositionTechniques.goldenRatio.score)}`,children:y.composition.compositionTechniques.goldenRatio.score})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Leading Lines:"}),e.jsx("span",{className:`font-medium ${h(y.composition.compositionTechniques.leadingLines.score)}`,children:y.composition.compositionTechniques.leadingLines.score})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Negative Space:"}),e.jsx("span",{className:`font-medium ${h(y.composition.compositionTechniques.negativeSpace.score)}`,children:y.composition.compositionTechniques.negativeSpace.score})]})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-xl p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-2 text-sm",children:"Mobile & CTA"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"CTA Visible:"}),e.jsx("span",{className:y.composition.ctaProminence.visible?"text-green-600":"text-red-600",children:y.composition.ctaProminence.visible?"Yes":"No"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Thumb Zone:"}),e.jsx("span",{className:y.composition.ctaProminence.thumbZoneOptimal?"text-green-600":"text-yellow-600",children:y.composition.ctaProminence.thumbZoneOptimal?"Optimal":"Needs Work"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tap Targets:"}),e.jsx("span",{className:"text-foreground capitalize",children:y.composition.mobileOptimization.tapTargetSize})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Content Density:"}),e.jsx("span",{className:"text-foreground capitalize",children:y.composition.mobileOptimization.contentDensity})]})]})]}),((A=y.strengths)==null?void 0:A.length)>0&&e.jsxs("div",{className:"bg-green-50 rounded-xl p-3",children:[e.jsx("h4",{className:"font-semibold text-green-800 mb-2 text-sm",children:"Strengths"}),e.jsx("ul",{className:"text-xs text-green-700 space-y-1",children:y.strengths.map((C,N)=>e.jsxs("li",{children:["⢠",C]},N))})]}),((E=y.improvements)==null?void 0:E.length)>0&&e.jsxs("div",{className:"bg-amber-50 rounded-xl p-3",children:[e.jsx("h4",{className:"font-semibold text-amber-800 mb-2 text-sm",children:"Improvements"}),e.jsx("ul",{className:"text-xs text-amber-700 space-y-1",children:y.improvements.map((C,N)=>e.jsxs("li",{children:["⢠",C]},N))})]})]}),e.jsx("button",{onClick:g,className:"w-full bg-primary text-primary-foreground px-6 py-3 rounded-xl font-semibold hover:bg-primary/90 transition-colors",children:"Close"})]})]})})})]})},ho=({title:t,category:s,recommendations:n,selectedRecs:r,onToggleCategory:a,onToggleRecommendation:o})=>{const d=n.map((p,c)=>`${s}-${c}`).every(p=>r[p]),m=n.reduce((p,c)=>p+(c.maxCredits||0),0);return e.jsxs(e.Fragment,{children:[e.jsx("style",{children:` 87 @keyframes strikethrough { 88 from { 89 transform: scaleX(0); 90 } 91 to { 92 transform: scaleX(1); 93 } 94 } 95 `}),e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4 pb-4 border-b border-border",children:[e.jsx("input",{type:"checkbox",checked:d,onChange:()=>a(s,n),className:"w-5 h-5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-lg font-bold text-foreground",children:t}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[m," total credits"]})]}),e.jsx("button",{onClick:()=>a(s,n),className:"text-sm text-primary hover:underline font-medium",children:d?"Deselect All":"Select All"})]}),e.jsx("div",{className:"space-y-3",children:n.map((p,c)=>{const u=`${s}-${c}`,x=r[u];return e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-xl transition-all ${x?"bg-background":"bg-muted opacity-60"}`,children:[e.jsx("input",{type:"checkbox",checked:x,onChange:()=>o(u),className:"w-4 h-4"}),e.jsx("div",{className:"flex-1",children:e.jsxs("span",{className:`relative ${x?"text-foreground":"text-muted-foreground"}`,style:{transition:"color 0.3s ease"},children:[p.title,!x&&e.jsx("span",{style:{position:"absolute",left:0,top:"50%",width:"100%",height:"2px",backgroundColor:"currentColor",transformOrigin:"left",animation:"strikethrough 0.4s ease-out forwards"}})]})}),e.jsxs("div",{className:"text-right",children:[e.jsxs("span",{className:`font-medium ${x?"text-primary":"text-muted-foreground"}`,children:[p.maxCredits||0," credits"]}),!x&&e.jsx("div",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:"DEFERRED"})]})]},u)})})]})]})},OI={usd:"$",cad:"CA$",eur:"â¬"},$I=.2;
95function BI(t){return t.toLowerCase()==="cad"?2e4:15e3}function ra(t,s){return`${OI[s.toLowerCase()]||"$"}${t.toLocaleString()}`}const my=({selectedCredits:t,paymentPlan:s,setPaymentPlan:n,onCapturePayment:r,loading:a,paymentCaptured:o,setPaymentCaptured:i,creditPriceCents:d,currency:m="usd",allItemsSelected:p=!1})=>{const c=m.toLowerCase(),u=c.toUpperCase(),h=(d??BI(c))/100,b=t*h,f=p?h*(1-$I):h,g=t*f,y=b-g,j=y>0?Math.round(y/b*100):0,v=h*10,T=Math.ceil(t/10),k=T*v,w=()=>{r()};return e.jsxs("div",{className:"bg-muted/50 border border-border rounded-2xl p-6 shadow-sm",children:[e.jsx("h3",{className:"text-xl font-bold mb-6 text-center text-foreground",children:"Choose Your Payment Plan"}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6 mb-6",children:[e.jsxs("div",{onClick:()=>n("upfront"),style:s==="upfront"?{backgroundColor:"#fef9e7"}:{},className:`border-2 rounded-2xl p-4 m-4 cursor-pointer transition-all ${s==="upfront"?"border-green-500 shadow-lg":"border-border bg-card hover:border-green-300 hover:shadow-md"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h4",{className:"text-lg text-foreground",style:{fontWeight:"bold"},children:"Pay Upfront"}),e.jsx("input",{type:"radio",checked:s==="upfront",onChange:()=>n("upfront"),className:"w-5 h-5"})]}),e.jsxs("div",{className:"mb-6 text-center",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-1 uppercase tracking-wide",children:"Total Price"}),p&&y>0&&e.jsx("div",{className:"text-sm text-muted-foreground line-through",style:{marginBottom:2},children:ra(b,c)}),e.jsxs("div",{className:"font-bold text-green-600 mb-2",style:{fontSize:"48px",lineHeight:"1"},children:[ra(g,c),e.jsx("span",{style:{fontSize:"20px",marginLeft:"6px"},children:u})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[t," credits à ",ra(f,c),"/credit"]})]}),e.jsx("div",{className:"flex justify-center",children:e.jsxs("div",{className:"space-y-2 text-sm text-foreground",children:[p&&y>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-green-600",children:"â"}),e.jsxs("span",{children:["Save ",e.jsxs("span",{className:"font-bold text-green-600",children:[j,"%"]})," ","(",e.jsxs("span",{className:"font-bold text-green-600",children:[ra(y,c)," ",u," savings"]}),")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-green-600",children:"â"}),e.jsx("span",{children:"Complete in 30 days"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-green-600",children:"â"}),e.jsx("span",{children:"Priority support"})]})]})})]}),e.jsxs("div",{onClick:()=>n("monthly"),style:s==="monthly"?{backgroundColor:"#fef9e7"}:{},className:`border-2 rounded-2xl p-4 m-4 cursor-pointer transition-all ${s==="monthly"?"border-primary shadow-lg":"border-border bg-card hover:border-primary/50 hover:shadow-md"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h4",{className:"text-lg text-foreground",style:{fontWeight:"bold"},children:"Monthly Payments"}),e.jsx("input",{type:"radio",checked:s==="monthly",onChange:()=>n("monthly"),className:"w-5 h-5"})]}),e.jsxs("div",{className:"mb-6 text-center",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-1 uppercase tracking-wide",children:"Monthly Payment"}),e.jsxs("div",{className:"font-bold text-primary mb-2",style:{fontSize:"48px",lineHeight:"1"},children:[ra(v,c),e.jsx("span",{style:{fontSize:"24px"},children:"/mo"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["for ",T," month",T!==1?"s":""," = ",ra(k,c)," ",u," total"]})]}),e.jsx("div",{className:"flex justify-center",children:e.jsxs("div",{className:"space-y-2 text-sm text-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"â"}),e.jsx("span",{children:"Manageable monthly cost"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"â"}),e.jsx("span",{children:"Continuous improvements"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"â"}),e.jsx("span",{children:"Flexible prioritization"})]})]})})]})]}),e.jsx("button",{onClick:w,disabled:!s||a||o,style:o?{backgroundColor:"#22c55e"}:{},className:`mt-4 px-8 py-3 rounded-xl text-center shadow-md transition-all w-full ${o?"text-white cursor-default":"bg-primary text-primary-foreground hover:bg-primary/90 disabled:bg-gray-400 disabled:cursor-not-allowed"}`,children:o?e.jsxs("div",{className:"flex items-center justify-center gap-3",style:{fontWeight:"bold",fontSize:"18px"},children:[e.jsx("div",{className:"w-8 h-8 bg-white rounded-full flex items-center justify-center",children:e.jsx("span",{style:{color:"#22c55e"},className:"text-xl font-bold",children:"â"})}),e.jsx("span",{children:"Payment Accepted"})]}):a?e.jsx("div",{style:{fontWeight:"bold",fontSize:"18px"},children:"Processing Payment..."}):s==="upfront"?e.jsx("div",{style:{fontWeight:"bold",fontSize:"18px"},children:"Approve & Generate Project"}):s==="monthly"?e.jsx("div",{style:{fontWeight:"bold",fontSize:"18px"},children:"Work with your cashflow without breaking the bank"}):e.jsx("div",{style:{fontWeight:"bold",fontSize:"18px"},children:"Select a payment plan to continue"})})]})},FI=({selectedChannel:t,setSelectedChannel:s,onChannelSelected:n,isNewChannel:r,setIsNewChannel:a,confirmExistingChannel:o,setConfirmExistingChannel:i})=>{const{user:d,token:m}=pt(),[p,c]=l.useState([]),[u,x]=l.useState(!0),[h,b]=l.useState(""),[f,g]=l.useState(!1);l.useEffect(()=>{(async()=>
95{if(d)try{x(!0);const N=await re("getSlackChannels",{},m||void 0);c(N.channels||[])}catch(N){console.error("Failed to fetch Slack channels:",N.message,N.code)}finally{x(!1)}})()},[d,m]);const y=p.filter(C=>C.name.toLowerCase().includes(h.toLowerCase())),j=C=>C.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").slice(0,16),v=C=>{const N=j(C);return N.length>0&&N.length<=16},T=ee.useMemo(()=>(p==null?void 0:p.map(C=>j(C.name).toLowerCase()))??[],[p]),k=C=>{try{const N=j(C).toLowerCase(),S=T.includes(N);return console.log("Checking if channel exists:",N,"Result:",S,"All channels:",(p==null?void 0:p.map(O=>O.name))??[]),S}catch(N){return console.error("Error formatting channel name:",N),!1}},w=C=>{console.log("Selected existing channel:",C),s(C),b(C),a(!1),i(!1),g(!1)},I=()=>{const C=j(h);if(console.log("Attempting to create channel:",C),!C||C.length===0){console.log("Invalid: empty name");return}if(!v(h)){console.log("Invalid: does not meet requirements");return}console.log("Creating new channel:",C),s(C),b(C),a(!0),i(!1),g(!1),n()},A=C=>{const N=C.replace(/^#/,""),S=j(N);b(S),s(""),g(!0),a(!1),i(!1)},E=C=>{i(C),C&&n()};return e.jsxs("div",{className:"bg-muted/50 border border-border rounded-2xl p-6 shadow-sm mb-6",children:[e.jsx("h3",{className:"text-xl font-bold mb-4 text-center text-foreground",children:"Select Slack Channel"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4 text-center",children:"Choose an existing channel or create a new one (lowercase, 1-16 chars, dashes instead of spaces)"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"#"}),e.jsx("input",{type:"text",value:h,onChange:C=>A(C.target.value),onFocus:()=>g(!0),placeholder:"Search or enter channel name...",className:"flex-1 px-4 py-3 bg-card border border-border rounded-xl focus:outline-none focus:ring-2 focus:ring-primary",disabled:u})]}),f&&!u&&e.jsxs("div",{className:"absolute w-full bg-card border border-border rounded-xl shadow-lg max-h-60 overflow-y-auto z-10 mt-1",children:[y.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-4 py-2 text-xs text-muted-foreground uppercase tracking-wide bg-muted/50",children:"Existing Channels"}),y.map(C=>e.jsxs("button",{onClick:()=>w(C.name),className:"w-full text-left px-4 py-3 hover:bg-muted transition-colors flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"#"}),e.jsx("span",{className:"text-foreground",children:C.name}),C.isPrivate&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"ð Private"})]},C.id))]}):null,h.trim()&&!k(h)&&v(h)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-4 py-2 text-xs text-muted-foreground uppercase tracking-wide bg-muted/50 border-t border-border",children:"Create New"}),e.jsx("button",{onClick:I,className:"w-full text-left px-4 py-3 hover:bg-muted transition-colors flex items-center gap-2 text-primary font-medium",children:e.jsxs("span",{children:['+ Create channel "#',j(h),'"']})})]}),h.trim()&&!v(h)&&e.jsx("div",{className:"px-4 py-3 text-sm text-red-500",children:"Invalid channel name. Must be 1-16 characters, lowercase, no special characters."})]}),t&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-xl flex items-center gap-2",children:[e.jsx("span",{className:"text-blue-600 text-xl",children:"â¹ï¸"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-blue-800",children:r?"New channel will be created:":"Existing channel selected:"}),e.jsxs("div",{className:"text-blue-900 font-bold",children:["#",t]})]})]}),!r&&e.jsx("div",{className:"p-4 bg-yellow-50 border border-yellow-200 rounded-xl",children:e.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:C=>E(C.target.checked),className:"mt-1 w-5 h-5"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-yellow-900",children:"Create project in existing channel"}),e.jsxs("div",{className:"text-sm text-yellow-700 mt-1",children:["This will add a new project to the existing #",t," channel. The channel may already contain other projects."]})]})]})}),r&&e.jsxs("div",{className:"p-3 bg-green-50 border border-green-200 rounded-xl flex items-center gap-2",children:[e.jsx("span",{className:"text-green-600 text-xl",children:"â"}),e.jsx("div",{className:"text-sm text-green-800",children:"Ready to create new channel"})]})]})]}),u&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Loading channels..."})]})]})},bx=({audit:t,selectedRecs:s,setSelectedRecs:n,paymentPlan:r,setPaymentPlan:a,totals:o,onBack:i,onApprove:d,loading:m})=>{var v,T,k,w,I,A,E,C;const[p,c]=ee.useState(!1),[u,x]=ee.useState(""),[h,b]=ee.useState(!1),[f,g]=ee.useState(!1),y=(N,S)=>{const O=S.map((D,L)=>`${N}-${L}`),R=O.every(D=>s[D]),z={...s};O.forEach(D=>{z[D]=!R}),n(z)},j=N=>
95{n({...s,[N]:!s[N]})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8 mt-12",children:[e.jsx("h1",{className:"mb-2 text-foreground",style:{fontSize:"24px",fontWeight:700},children:"Let's Build Your Plan"}),e.jsx("p",{className:"text-muted-foreground",children:"Everything will be addressed eventually. Let's prioritize what to tackle first."})]}),((T=(v=t.speedData)==null?void 0:v.recommendations)==null?void 0:T.length)>0&&e.jsx(ho,{title:"SPEED ISSUES",category:"speed",recommendations:t.speedData.recommendations,selectedRecs:s,onToggleCategory:y,onToggleRecommendation:j}),((w=(k=t.structureData)==null?void 0:k.recommendations)==null?void 0:w.length)>0&&e.jsx(ho,{title:"STRUCTURE ISSUES",category:"structure",recommendations:t.structureData.recommendations,selectedRecs:s,onToggleCategory:y,onToggleRecommendation:j}),((A=(I=t.communicationData)==null?void 0:I.recommendations)==null?void 0:A.length)>0&&e.jsx(ho,{title:"COMMUNICATION ISSUES",category:"communication",recommendations:t.communicationData.recommendations,selectedRecs:s,onToggleCategory:y,onToggleRecommendation:j}),((C=(E=t.marketingData)==null?void 0:E.recommendations)==null?void 0:C.length)>0&&e.jsx(ho,{title:"MARKETING & SEO",category:"marketing",recommendations:t.marketingData.recommendations,selectedRecs:s,onToggleCategory:y,onToggleRecommendation:j}),e.jsxs("div",{className:"bg-card border-2 border-primary rounded-2xl p-6 text-center shadow-sm",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-1 uppercase tracking-wide",children:"SELECTED WORK"}),e.jsxs("div",{className:"text-4xl font-bold text-primary mb-1",children:[o.selected," credits"]}),o.deferred>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["(",o.deferred," credits deferred)"]})]}),e.jsx(my,{selectedCredits:o.selected,paymentPlan:r,setPaymentPlan:a,onCapturePayment:()=>alert("Payment capture will be implemented shortly"),loading:!1,paymentCaptured:p,setPaymentCaptured:c}),p&&e.jsx(FI,{selectedChannel:u,setSelectedChannel:x,onChannelSelected:()=>{},isNewChannel:h,setIsNewChannel:b,confirmExistingChannel:f,setConfirmExistingChannel:g}),e.jsx("div",{className:"h-24"}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4 shadow-lg z-20",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex gap-4",children:[e.jsx("button",{onClick:i,className:"flex-1 bg-card border-2 border-border text-foreground px-6 py-3 rounded-xl font-semibold hover:bg-muted transition-colors shadow-sm",children:"â Back"}),e.jsx("button",{onClick:()=>d(u,h),disabled:!p||!u||!h&&!f||m,className:`flex-1 px-6 py-3 rounded-xl transition-colors shadow-md ${m?"bg-primary text-primary-foreground cursor-wait disabled:bg-primary disabled:text-primary-foreground disabled:opacity-100":p&&u&&(h||f)?"bg-primary text-primary-foreground hover:bg-primary/90":"bg-gray-400 text-gray-600 cursor-not-allowed"}`,style:{fontWeight:"bold"},children:m?e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-4 border-white border-t-transparent"}),e.jsx("span",{children:"Starting Project..."})]}):"Start Project"})]})})]})},_I=({isOpen:t,onClose:s,projectId:n,ticketCount:r,slackChannelName:a})=>t?e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4",children:[e.jsxs("div",{className:"bg-card border-2 border-primary rounded-2xl p-8 max-w-md w-full shadow-2xl",style:{animation:"scaleIn 0.3s ease-out"},children:[e.jsx("div",{className:"flex justify-center mb-8 mt-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(fu,{className:"text-primary",size:80,strokeWidth:2}),e.jsx("div",{className:"absolute inset-0 rounded-full bg-primary/20",style:{animation:"ping 1s ease-out"}})]})}),e.jsx("h2",{className:"text-3xl font-bold text-center text-foreground mb-6",children:"Project Created!"}),e.jsxs("div",{className:"space-y-4 mb-4 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"Your project has been successfully started."}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3 mx-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Tickets Created:"}),e.jsx("span",{className:"font-semibold text-primary",children:r})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Slack Channel:"}),e.jsxs("span",{className:"font-semibold text-foreground",children:["#",a]})]})]})]}),e.jsx("div",{className:"px-4 mb-4",children:e.jsx("button",{onClick:s,className:"w-full bg-primary text-primary-foreground py-3 rounded-xl font-bold hover:bg-primary/90 transition-colors shadow-md",children:"Back to Dashboard"})})]}),e.jsx("style",{children:` 96 @keyframes scaleIn { 97 from { 98 transform: scale(0.9); 99 opacity: 0; 100 } 101 to { 102 transform: scale(1); 103 opacity: 1; 104 } 105 } 106 107 @keyframes ping { 108 0% { 109 transform: scale(1); 110 opacity: 0.5; 111 } 112 100% { 113 transform: scale(2); 114 opacity: 0; 115 } 116 } 117 `})]}):null,WI=()=>{const{auditId:t}=zl(),s=Qo(),{token:n,isAdminDomain:r}=pt(),[a,o]=l.useState(null),[i,d]=l.useState(1),[m,p]=l.useState({}),[c,u]=l.useState(null),[x,h]=l.useState(!0),[b,f]=l.useState(!1),[g,y]=l.useState(!1),[j,v]=l.useState(null),[T,k]=l.useState(!1),[w,I]=l.useState(null),[A,E]=l.useState(!1),[C,N]=l.useState(!1),[S,O]=l.useState(!1),[R,z]=l.useState(!1),D=async()=>{var H,Z,Q,K;try{if(!t)throw new Error("Invalid audit ID");console.log("Loading audit:",t);const X=await ps(ut(ge,"siteAudits",t));if(console.log("Audit doc exists:",X.exists()),X.exists()){const se=X.data();if(console.log("Audit data:",se),!se||typeof se!="object")throw new Error("Invalid audit data");o({...se,id:X.id});const pe={};
117(((H=se.speedData)==null?void 0:H.recommendations)||[]).forEach((me,Ne)=>{pe[`speed-${Ne}`]=!0}),(((Z=se.structureData)==null?void 0:Z.recommendations)||[]).forEach((me,Ne)=>{pe[`structure-${Ne}`]=!0}),(((Q=se.communicationData)==null?void 0:Q.recommendations)||[]).forEach((me,Ne)=>{pe[`communication-${Ne}`]=!0}),(((K=se.marketingData)==null?void 0:K.recommendations)||[]).forEach((me,Ne)=>{pe[`marketing-${Ne}`]=!0}),console.log("Initial selection:",pe),p(pe),h(!1)}else console.error("Audit not found:",t),v("Audit not found"),h(!1)}catch(X){console.error("Error loading audit:",X),v(`Error loading audit: ${X}`),h(!1)}};l.useEffect(()=>{if(!t){console.log("No auditId provided"),h(!1);return}D()},[t]);const L=()=>{var K,X,se,pe;if(!a)return{selected:0,deferred:0};let H=0,Z=0;return[{name:"speed",recs:((K=a.speedData)==null?void 0:K.recommendations)||[]},{name:"structure",recs:((X=a.structureData)==null?void 0:X.recommendations)||[]},{name:"communication",recs:((se=a.communicationData)==null?void 0:se.recommendations)||[]},{name:"marketing",recs:((pe=a.marketingData)==null?void 0:pe.recommendations)||[]}].forEach(({name:me,recs:Ne})=>{Ne.forEach((at,ae)=>{const xe=`${me}-${ae}`,ze=at.maxCredits||0;m[xe]?H+=ze:Z+=ze})}),{selected:H,deferred:Z}},$=()=>{i<6&&(d(i+1),window.scrollTo(0,0))},q=()=>{i>1&&(d(i-1),window.scrollTo(0,0))},P=H=>{d(H),window.scrollTo(0,0)},U=async(H,Z)=>{if(!c){ce.warning("Please select a payment plan");return}const Q=L();if(Q.selected===0){ce.warning("Please select at least one recommendation");return}if(!H){ce.warning("Please select a Slack channel");return}f(!0),await new Promise(K=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{setTimeout(K,50)})})});try{const K=Object.entries(m).filter(([se,pe])=>pe).map(([se])=>se);console.log("Calling finalizeAuditSale with:",{auditId:t,selectedRecommendations:K,paymentPlan:c,selectedCredits:Q.selected,slackChannel:H,isNewChannel:Z});const X=await re("finalizeAuditSale",{auditId:t,selectedRecommendations:K,paymentPlan:c,selectedCredits:Q.selected,slackChannel:H,isNewChannel:Z},n||void 0);I({projectId:X.projectId,ticketCount:X.ticketCount,slackChannelName:X.slackChannelName}),k(!0)}catch(K){console.error("Failed to finalize sale:",K),ce.error(`Failed to create project: ${K.message}`)}finally{f(!1)}},V=()=>{k(!1),s("/admin")},M=()=>{window.print()},F=async()=>{if(!a)return;const H=prompt("Enter email address to send the audit report:");if(!H)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(H)){ce.warning("Please enter a valid email address");return}const Q=prompt("Enter recipient name (optional):")||void 0;y(!0);try{const K=await re("sendAuditEmail",{auditId:a.id,domain:a.domain,recipientEmail:H,recipientName:Q},n||void 0);ce.success(`Email sent successfully to ${K.sentTo}!`)}catch(K){console.error("Failed to send email:",K),ce.error("Failed to send email. Please try again later.")}finally{y(!1)}},W=(H,Z,Q,K)=>{if(!a)return;const X=`${H}Data`,se=a[X];if(!(se!=null&&se.recommendations))return;const pe=[...se.recommendations];pe[Z]={...pe[Z],[Q]:K},o({...a,[X]:{...se,recommendations:pe}}),O(!0)},_=(H,Z)=>{if(!a)return;const Q=`${H}Data`,K=a[Q];if(!(K!=null&&K.recommendations))return;const X=K.recommendations.filter((pe,me)=>me!==Z),se={};Object.entries(m).forEach(([pe,me])=>{const[Ne,at]=pe.split("-"),ae=parseInt(at);Ne===H?ae<Z?se[pe]=me:ae>Z&&(se[`${Ne}-${ae-1}`]=me):se[pe]=me}),o({...a,[Q]:{...K,recommendations:X}}),p(se),O(!0)},G=async()=>{if(!(!a||!t)){N(!0);try{const H=ut(ge,"siteAudits",t);await er(H,{speedData:a.speedData,structureData:a.structureData,communicationData:a.communicationData,marketingData:a.marketingData}),O(!1),E(!1),ce.success("Changes saved successfully!")}catch(H){console.error("Failed to save changes:",H),ce.error(`Failed to save changes: ${H.message}`)}finally{N(!1)}}},B=()=>{E(!1),O(!1),h(!0),D()},Y=()=>{if(S){z(!0);return}B()};if(x)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-16 w-16 border-b-4 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading presentation..."})]})});if(j||!a)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center max-w-md mx-auto px-4",children:[e.jsx("div",{className:"text-destructive text-6xl mb-4",children:"â ï¸"}),e.jsx("h2",{className:"text-2xl font-bold mb-2 text-foreground",children:"Unable to Load Presentation"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:j||"Audit not found"}),e.jsx("button",{onClick:()=>s("/admin"),className:"bg-primary text-primary-foreground px-6 py-3 rounded-xl font-medium hover:bg-primary/90 transition-colors",children:"Back to Admin"})]})});const J=L();return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"bg-card border-b border-border sticky top-0 z-10 shadow-sm overflow-hidden",children:e.jsxs("div",{className:"max-w-4xl mx-auto px-4",children:[e.jsx("div",{style:{transform:i===6?"translateY(-100%)":"translateY(0)",transition:"transform 0.5s ease-in-out",opacity:i===6?0:1,height:i===6?0:"auto"},children:e.jsxs("div",{className:"py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h1",{className:"text-xl font-bold text-foreground",children:["Site Audit: ",a.domain]}),e.jsxs("div",{className:"flex items-center gap-2 no-print",children:[r&&e.jsx(e.Fragment,{children:A?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:G,disabled:C||!S,className:"flex items-center gap-2 px-3 py-2 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:C?"#4ade80":"#16a34a"},onMouseOver:H=>!C&&(H.currentTarget.style.backgroundColor="#15803d"),onMouseOut:H=>!C&&(H.currentTarget.style.backgroundColor="#16a34a"),title:"Save Changes",children:[e.jsx(ml,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:C?"Saving...":"Save"})]}),e.jsxs("button",{onClick:Y,className:"flex items-center gap-2 px-3 py-2 text-white rounded-lg transition-colors",style:{backgroundColor:"#6b7280"},onMouseOver:H=>H.currentTarget.style.backgroundColor="#4b5563",onMouseOut:H=>
117H.currentTarget.style.backgroundColor="#6b7280",title:"Cancel Edit",children:[e.jsx(mt,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Cancel"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>E(!0),className:"flex items-center gap-2 px-3 py-2 text-white rounded-lg transition-colors",style:{backgroundColor:"#f59e0b"},onMouseOver:H=>H.currentTarget.style.backgroundColor="#d97706",onMouseOut:H=>H.currentTarget.style.backgroundColor="#f59e0b",title:"Edit Recommendations",children:[e.jsx(Na,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Edit"})]}),e.jsxs("button",{onClick:F,disabled:g,className:"flex items-center gap-2 px-3 py-2 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:g?"#4ade80":"#16a34a"},onMouseOver:H=>!g&&(H.currentTarget.style.backgroundColor="#15803d"),onMouseOut:H=>!g&&(H.currentTarget.style.backgroundColor="#16a34a"),title:"Email Report",children:[e.jsx(Tn,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:g?"Sending...":"Email"})]})]})}),e.jsxs("button",{onClick:M,className:"flex items-center gap-2 px-3 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",title:"Download as PDF",children:[e.jsx(fg,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"PDF"})]})]})]}),e.jsx(uy,{currentStep:i,totalSteps:6,onStepClick:P})]})}),i===6&&e.jsxs("div",{style:{animation:"slideDown 0.5s ease-in-out"},className:"py-2 text-center",children:[e.jsx("div",{className:"text-muted-foreground mb-1 uppercase tracking-wide",style:{fontSize:"24px",fontWeight:"bold"},children:"ESTIMATED PRICE"}),e.jsxs("div",{className:"mb-0.5",style:{color:"#16a34a",fontWeight:"bold",fontSize:"48px"},children:["$",(J.selected*200).toLocaleString()]}),e.jsxs("div",{className:"text-sm text-primary font-semibold",children:[J.selected," credits"]})]})]})}),e.jsx("style",{children:` 118 /* Screen-only content (hidden when printing) */ 119 .print-only { 120 display: none; 121 } 122 123 @keyframes slideDown { 124 from { 125 transform: translateY(-20px); 126 opacity: 0; 127 } 128 to { 129 transform: translateY(0); 130 opacity: 1; 131 } 132 } 133 134 @media print { 135 /* Page setup for US Letter */ 136 @page { 137 size: letter; 138 margin: 0.5in 0.5in 0.6in 0.5in; 139 } 140 141 /* Hide screen-only, show print-only */ 142 .screen-only { 143 display: none !important; 144 } 145 146 .print-only { 147 display: block !important; 148 } 149 150 /* Hide interactive elements and spacers */ 151 .no-print, 152 button:not(.no-hide), 153 .sticky, 154 .fixed, 155 .h-24 { 156 display: none !important; 157 } 158 159 /* Reset positioning and sizing */ 160 body { 161 margin: 0; 162 padding: 0; 163 font-size: 10pt; 164 line-height: 1.3; 165 background: white !important; 166 } 167 168 /* Force white backgrounds for print */ 169 html, body, .min-h-screen, .bg-background, .bg-card, .bg-muted { 170 background: white !important; 171 background-color: white !important; 172 } 173 174 /* Keep colored elements that should print in color */ 175 .bg-green-50, .bg-green-100, .bg-yellow-100, .bg-red-100, .bg-primary\\/10 { 176 -webkit-print-color-adjust: exact !important; 177 print-color-adjust: exact !important; 178 } 179 180 /* Container width for print */ 181 .max-w-4xl { 182 max-width: 100% !important; 183 padding: 0 !important; 184 } 185 186 /* Show all content at once */ 187 .min-h-screen { 188 min-height: auto !important; 189 padding-top: 0 !important; 190 padding-bottom: 0 !important; 191 } 192 193 /* Page breaks */ 194 .page-break-before { 195 page-break-before: always; 196 break-before: page; 197 } 198 199 .page-break-after { 200 page-break-after: always; 201 break-after: page; 202 } 203 204 /* Prevent cards from breaking across pages */ 205 .bg-card, 206 .rounded-2xl, 207 .border-l-4 { 208 break-inside: avoid !important; 209 page-break-inside: avoid !important; 210 } 211 212 /* Prevent awkward breaks */ 213 h1, h2, h3, h4, h5, h6 { 214 page-break-after: avoid; 215 break-after: avoid; 216 } 217 218 /* Print in color */ 219 * { 220 -webkit-print-color-adjust: exact !important; 221 print-color-adjust: exact !important; 222 } 223 224 /* Remove box shadows for print */ 225 * { 226 box-shadow: none !important; 227 } 228 229 /* ===== COVER PAGE ===== */ 230 .text-9xl { 231 font-size: 60pt !important; 232 line-height: 1 !important; 233 } 234 235 .text-5xl { 236 font-size: 22pt !important; 237 } 238 239 .text-4xl { 240 font-size: 18pt !important; 241 } 242 243 .text-3xl { 244 font-size: 14pt !important; 245 } 246 247 .text-2xl { 248 font-size: 12pt !important; 249 } 250 251 /* Reduce cover page spacing */ 252 .my-12 { 253 margin-top: 20px !important; 254 margin-bottom: 20px !important; 255 } 256 257 .mt-16 { 258 margin-top: 24px !important; 259 } 260 261 .mt-12 { 262 margin-top: 16px !important; 263 } 264 265 .mb-8 { 266 margin-bottom: 12px !important; 267 } 268 269 .mb-6 { 270 margin-bottom: 8px !important; 271 } 272 273 /* Category score grid on cover */ 274 .grid-cols-5 { 275 gap: 6px !important; 276 } 277 278 .grid-cols-5 > div { 279 padding: 8px !important; 280 } 281 282 /* ===== CONTENT PAGES ===== */ 283 284 /* Section headers */ 285 .text-xl { 286 font-size: 13pt !important; 287 } 288 289 .text-lg { 290 font-size: 11pt !important; 291 } 292 293 .text-base { 294 font-size: 10pt !important; 295 } 296 297 .text-sm { 298 font-size: 9pt !important; 299 } 300 301 .text-xs { 302 font-size: 8pt !important; 303 } 304 305 /* Compact recommendation cards */ 306 .space-y-4 > * + * { 307 margin-top: 8px !important; 308 } 309 310 .space-y-6 > * + * { 311 margin-top: 10px !important; 312 } 313 314 /* Card padding reduction */ 315 .p-6 { 316 padding: 10px !important; 317 } 318 319 .p-4 { 320 padding: 8px !important; 321 } 322 323 .p-3 { 324 padding: 6px !important; 325 } 326 327 /* Impact box styling */ 328 .border-l-4.border-green-500 { 329 padding: 6px 8px !important; 330 margin-top: 6px !important; 331 } 332 333 /* Reduce margin on explanation boxes */ 334 .bg-primary\\/10 { 335 padding: 8px 12px !important; 336 margin-bottom: 12px !important; 337 } 338 339 /* Score display area */ 340 .gap-4 { 341 gap: 8px !important; 342 } 343 344 .gap-3 { 345 gap: 6px !important; 346 } 347 348 /* Score boxes */ 349 .w-24.h-24 { 350 width: 70px !important; 351 height: 70px !important; 352 padding: 6px !important; 353 } 354 355 /* Rounded corners smaller for print */ 356 .rounded-2xl { 357 border-radius: 8px !important; 358 } 359 360 .rounded-xl { 361 border-radius: 6px !important; 362 } 363 364 /* Border widths */ 365 .border-2 { 366 border-width: 1px !important; 367 } 368 369 /* Real world performance box */ 370 .grid-cols-3 { 371 gap: 12px !important; 372 } 373 374 /* Logo sizing */ 375 .h-16 { 376 height: 48px !important; 377 } 378 379 /* Ensure text doesn't overflow */ 380 .truncate { 381 overflow: visible !important; 382 white-space: normal !important; 383 } 384 } 385 `}),e.jsxs("div",{className:"max-w-4xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"screen-only",children:[i===1&&e.jsx(mx,{data:a.speedData,onNext:$,editMode:A,onEditRecommendation:(H,Z,Q)=>
385W("speed",H,Z,Q),onDeleteRecommendation:H=>_("speed",H)}),i===2&&e.jsx(px,{data:{...a.structureData,score:a.structureData.score??a.structureScore??0},onNext:$,onBack:q,editMode:A,onEditRecommendation:(H,Z,Q)=>W("structure",H,Z,Q),onDeleteRecommendation:H=>_("structure",H)}),i===3&&e.jsx(xx,{data:a.communicationData,onNext:$,onBack:q,editMode:A,onEditRecommendation:(H,Z,Q)=>W("communication",H,Z,Q),onDeleteRecommendation:H=>_("communication",H)}),i===4&&e.jsx(hx,{data:a.marketingData,onNext:$,onBack:q,editMode:A,onEditRecommendation:(H,Z,Q)=>W("marketing",H,Z,Q),onDeleteRecommendation:H=>_("marketing",H)}),i===5&&(a.visualData?e.jsx(gx,{data:{score:a.visualData.score||0,pages:a.visualData.pages||[],overallAnalysis:a.visualData.overallAnalysis||"",recommendations:a.visualData.recommendations||[],analysisPending:a.visualData.analysisPending},onNext:$,onBack:q}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8 mt-12",children:[e.jsx("h1",{className:"mb-2 text-foreground",style:{fontSize:"24px",fontWeight:700},children:"Visual Design & Composition"}),e.jsx("div",{className:"text-muted-foreground",children:"Visual analysis data not available for this audit."})]}),e.jsx("div",{className:"h-24"}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4 shadow-lg z-20 no-print",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex gap-4",children:[e.jsx("button",{onClick:q,className:"flex-1 bg-card border-2 border-border text-foreground px-6 py-3 rounded-xl font-semibold hover:bg-muted transition-colors shadow-sm",children:"â Back"}),e.jsx("button",{onClick:$,className:"flex-1 bg-primary text-primary-foreground px-6 py-3 rounded-xl font-semibold hover:bg-primary/90 transition-colors shadow-md",children:"Next: Build Your Plan â"})]})})]})),i===6&&e.jsx(bx,{audit:a,selectedRecs:m,setSelectedRecs:p,paymentPlan:c,setPaymentPlan:u,totals:J,onBack:q,onApprove:U,loading:b})]}),e.jsxs("div",{className:"print-only",children:[e.jsxs("div",{className:"page-break-after flex flex-col justify-between min-h-screen",style:{paddingTop:"50px",paddingBottom:"30px"},children:[e.jsx("div",{className:"text-center",children:e.jsx("img",{src:T0,alt:"Sunbowl",className:"h-16 mx-auto mb-8"})}),e.jsxs("div",{className:"text-center flex-1 flex flex-col justify-center",children:[e.jsx("h1",{className:"text-5xl font-bold mb-6 text-foreground",style:{letterSpacing:"-0.02em"},children:"Website Audit Report"}),e.jsxs("div",{className:"mb-8",children:[e.jsx("div",{className:"text-2xl text-muted-foreground mb-2",children:"for"}),e.jsx("h2",{className:"text-4xl font-semibold text-foreground",children:a.domain})]}),e.jsxs("div",{className:"my-12",children:[e.jsx("div",{className:"text-9xl font-bold mb-3",style:{color:a.overallScore>=80?"#16a34a":a.overallScore>=50?"#eab308":"#dc2626",lineHeight:"1"},children:a.overallScore}),e.jsx("p",{className:"text-2xl font-medium text-muted-foreground",children:"Overall Performance Score"})]}),e.jsxs("div",{className:"mt-16 grid grid-cols-5 gap-3 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center p-4 border-2 border-border rounded-xl bg-card",children:[e.jsx("div",{className:"text-3xl font-bold mb-2",style:{color:a.speedData.score>=80?"#16a34a":a.speedData.score>=50?"#eab308":"#dc2626"},children:a.speedData.score}),e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Speed"})]}),e.jsxs("div",{className:"text-center p-4 border-2 border-border rounded-xl bg-card",children:[e.jsx("div",{className:"text-3xl font-bold mb-2",style:{color:(a.structureData.score??a.structureScore??0)>=80?"#16a34a":(a.structureData.score??a.structureScore??0)>=50?"#eab308":"#dc2626"},children:a.structureData.score??a.structureScore??0}),e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Structure"})]}),e.jsxs("div",{className:"text-center p-4 border-2 border-border rounded-xl bg-card",children:[e.jsx("div",{className:"text-3xl font-bold mb-2",style:{color:a.communicationData.score>=80?"#16a34a":a.communicationData.score>=50?"#eab308":"#dc2626"},children:a.communicationData.score}),e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Communication"})]}),e.jsxs("div",{className:"text-center p-4 border-2 border-border rounded-xl bg-card",children:[e.jsx("div",{className:"text-3xl font-bold mb-2",style:{color:a.marketingData.score>=80?"#16a34a":a.marketingData.score>=50?"#eab308":"#dc2626"},children:a.marketingData.score}),e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Marketing"})]}),a.visualData&&e.jsxs("div",{className:"text-center p-4 border-2 border-border rounded-xl bg-card",children:[e.jsx("div",{className:"text-3xl font-bold mb-2",style:{color:(a.visualData.score||0)>=80?"#16a34a":(a.visualData.score||0)>=50?"#eab308":"#dc2626"},children:a.visualData.score||0}),e.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Visual"})]})]})]}),e.jsx("div",{className:"text-center text-sm text-muted-foreground mt-12",children:e.jsxs("p",{children:["Generated by Sunbowl ⢠",new Date().toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"})]})})]}),e.jsx("div",{className:"page-break-after",children:e.jsx(mx,{data:a.speedData,onNext:$})}),e.jsx("div",{className:"page-break-after",children:e.jsx(px,{data:{...a.structureData,score:a.structureData.score??a.structureScore??0},onNext:$,onBack:q})}),e.jsx("div",{className:"page-break-after",children:e.jsx(xx,{data:a.communicationData,onNext:$,onBack:q})}),e.jsx("div",{className:"page-break-after",children:e.jsx(hx,{data:a.marketingData,onNext:$,onBack:q})}),a.visualData&&e.jsx("div",{className:"page-break-after",children:e.jsx(gx,{data:{score:a.visualData.score||0,pages:a.visualData.pages||[],overallAnalysis:a.visualData.overallAnalysis||"",recommendations:a.visualData.recommendations||[],analysisPending:a.visualData.analysisPending},onNext:$,onBack:q})}),e.jsx("div",{children:e.jsx(bx,{audit:a,selectedRecs:m,setSelectedRecs:p,paymentPlan:c,setPaymentPlan:u,totals:J,onBack:q,onApprove:U,loading:b})})]})]}),w&&e.jsx(_I,{isOpen:T,onClose:V,projectId:w.projectId,ticketCount:w.ticketCount,slackChannelName:w.slackChannelName}),e.jsx(di,{open:R,onOpenChange:z,title:"Discard unsaved changes?",description:"You have unsaved changes. Are you sure you want to cancel?",confirmLabel:"Discard changes",cancelLabel:"Keep editing",destructive:!0,onConfirm:()=>{z(!1),B()}})]})};function tn({className:t,...s}){return e.jsx("div",{"data-slot":"skeleton",className:$e("bg-accent animate-pulse rounded-md",t),...s})}const kn={bowlBlue:"#7ECCEE",sunGold:"#DDCB77",grey:"#56585A",text:"rgba(0,0,0,0.8)",lightBlue:"#e8f6fc"};function UI(){if(document.querySelector('link[href*="Montserrat"]'))return;const t=document.createElement("link");t.rel="stylesheet",t.href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&display=swap",document.head.appendChild(t)}function HI(){return e.jsxs("div",{className:"flex flex-col items-center gap-3 pb-4",children:[e.jsx(tn,{className:"h-8 w-40"}),e.jsx(tn,{className:"h-4 w-56"})]})}function qI({teamMember:t}){return e.jsxs("div",{className:"flex items-center gap-3 rounded-xl px-5 py-3",style:{backgroundColor:kn.lightBlue,border:`1px solid ${kn.bowlBlue}33`},children:[t.photoUrl?e.jsx("img",{src:t.photoUrl,alt:t.name,className:"h-11 w-11 rounded-full object-cover ring-2",style:{"--tw-ring-color":kn.bowlBlue}}):e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-full text-sm font-semibold text-white",style:{backgroundColor:kn.bowlBlue},children:t.name.split(" ").map(s=>s[0]).join("").toUpperCase().slice(0,2)}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",style:{color:kn.grey,fontFamily:"'Montserrat', sans-serif"},children:t.name}),t.title&&e.jsx("p",{className:"text-xs",style:{color:kn.grey+"aa"},children:t.title})]})]})}function yx({branding:t,teamMember:s,isEmbed:n,isLoading:r,children:a}){return l.useEffect(()=>{UI()},[]),e.jsx("div",{className:n?"flex min-h-screen items-center justify-center bg-white p-4":"flex min-h-screen items-center justify-center px-4 py-8 sm:py-12",style:{fontFamily:"'Montserrat', sans-serif",color:kn.text,...n?{}:{backgroundColor:"#f7f8fa"}},children:e.jsxs("div",{className:"mx-auto w-full max-w-4xl",children:[!n&&e.jsx("div",{className:"mb-8 text-center",children:r?e.jsx(HI,{}):t?e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("img",{src:"/sunbowl-logo.svg",alt:"Sunbowl",className:"h-8 w-auto sm:h-9"}),t.tagline&&e.jsx("p",{className:"text-sm font-light",style:{color:kn.grey,fontFamily:"'Montserrat', sans-serif"},children:t.tagline})]}):null}),!r&&s&&e.jsx("div",{className:"mb-6 flex justify-center",children:e.jsx(qI,{teamMember:s})}),e.jsx("div",{className:n?"":"rounded-2xl border bg-white p-5 shadow-sm sm:p-8",style:n?{}:{borderColor:"#e5e7eb"},children:a}),!n&&e.jsxs("div",{className:"mt-6 flex flex-col items-center gap-1",children:[e.jsx("svg",{width:"40",height:"8",viewBox:"0 0 40 8",fill:"none",children:e.jsx("path",{d:"M2 2C5.5 6 8.5 6 12 2C15.5 6 18.5 6 22 2C25.5 6 28.5 6 32 2C35.5 6 38 6 38 2",stroke:kn.sunGold,strokeWidth:"2",strokeLinecap:"round"})}),e.jsx("p",{className:"text-xs font-light",style:{color:kn.grey+"88"},children:"Powered by Sunbowl"})]})]})})}function VI({meetingTypes:t,onSelect:s}){return e.jsxs("div",{className:"space-y-5",style:{fontFamily:"'Montserrat', sans-serif"},children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:"text-lg font-bold",style:{color:"#56585A"},children:"Select a Meeting Type"}),e.jsx("p",{className:"mt-1 text-sm font-light",style:{color:"#56585Aaa"},children:"Choose the type of meeting you'd like to book."})]}),e.jsx("div",{className:"space-y-3",children:t.map(n=>e.jsx(jt,{className:"cursor-pointer transition-all hover:shadow-md",style:{borderColor:"#e5e7eb"},onClick:()=>s(n),onMouseEnter:r=>r.currentTarget.style.borderColor="#7ECCEE",onMouseLeave:r=>r.currentTarget.style.borderColor="#e5e7eb",children:e.jsxs(vt,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold",style:{color:"#56585A"},children:n.name}),n.description&&e.jsx("p",{className:"mt-0.5 text-sm font-light",style:{color:"#56585Aaa"},children:n.description}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-1 text-xs",style:{color:"#7ECCEE"},children:[e.jsx(ms,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium",children:[n.durationMinutes," min"]})]})]}),e.jsx(Rt,{className:"h-5 w-5 shrink-0",style:{color:"#7ECCEE"}})]})},n.id))})]})}function YI(t,s){const n=t.toLocaleDateString("en-US",{month:"short"}),r=s.toLocaleDateString("en-US",{month:"short"}),a=t.getDate(),o=s.getDate(),i=t.getFullYear();return n===r?`${n} ${a} â ${o}, ${i}`:`${n} ${a} â ${r} ${o}, ${i}`}function GI({currentWeekStart:t,currentWeekEnd:s,onPrevWeek:n,onNextWeek:r,canGoPrev:a}){const o=s||(()=>{const i=new Date(t);return i.setDate(i.getDate()+4),i})();return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ke,{variant:"ghost",size:"icon",onClick:n,disabled:!a,"aria-label":"Previous dates",children:e.jsx(fr,{className:"h-5 w-5"})}),e.jsx("span",{className:"text-sm font-medium",style:{color:"#56585A",fontFamily:"'Montserrat', sans-serif"},children:YI(t,o)}),e.jsx(ke,{variant:"ghost",size:"icon",onClick:r,"aria-label":"Next dates",children:e.jsx(Rt,{className:"h-5 w-5"})})]})}
385const jx=[{group:"North America",zones:[{value:"America/New_York",label:"New York (ET)"},{value:"America/Chicago",label:"Chicago (CT)"},{value:"America/Denver",label:"Denver (MT)"},{value:"America/Los_Angeles",label:"Los Angeles (PT)"},{value:"America/Anchorage",label:"Alaska (AKT)"},{value:"Pacific/Honolulu",label:"Hawaii (HST)"},{value:"America/Phoenix",label:"Arizona (MST)"},{value:"America/Toronto",label:"Toronto (ET)"},{value:"America/Vancouver",label:"Vancouver (PT)"},{value:"America/Edmonton",label:"Edmonton (MT)"},{value:"America/Winnipeg",label:"Winnipeg (CT)"},{value:"America/Halifax",label:"Halifax (AT)"},{value:"America/St_Johns",label:"St. John's (NT)"}]},{group:"Europe",zones:[{value:"Europe/London",label:"London (GMT/BST)"},{value:"Europe/Paris",label:"Paris (CET)"},{value:"Europe/Berlin",label:"Berlin (CET)"},{value:"Europe/Amsterdam",label:"Amsterdam (CET)"}]},{group:"Asia / Pacific",zones:[{value:"Asia/Tokyo",label:"Tokyo (JST)"},{value:"Asia/Shanghai",label:"Shanghai (CST)"},{value:"Asia/Kolkata",label:"India (IST)"},{value:"Asia/Dubai",label:"Dubai (GST)"},{value:"Australia/Sydney",label:"Sydney (AEST)"},{value:"Pacific/Auckland",label:"Auckland (NZST)"}]}];function KI({timezone:t,onChange:s}){var r;const n=jx.some(a=>a.zones.some(o=>o.value===t));return e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",fontFamily:"'Montserrat', sans-serif"},children:[e.jsx(ag,{style:{width:14,height:14,color:"#7ECCEE",flexShrink:0}}),e.jsxs("div",{style:{position:"relative"},children:[e.jsxs("select",{value:t,onChange:a=>s(a.target.value),style:{appearance:"none",WebkitAppearance:"none",background:"none",border:"none",fontSize:"13px",fontWeight:500,color:"#56585A",fontFamily:"'Montserrat', sans-serif",paddingRight:"18px",cursor:"pointer",outline:"none"},children:[!n&&e.jsx("optgroup",{label:"Detected",children:e.jsx("option",{value:t,children:(r=t.split("/").pop())==null?void 0:r.replace(/_/g," ")})}),jx.map(a=>e.jsx("optgroup",{label:a.group,children:a.zones.map(o=>e.jsx("option",{value:o.value,children:o.label},o.value))},a.group))]}),e.jsx(Ot,{style:{position:"absolute",right:0,top:"50%",transform:"translateY(-50%)",width:14,height:14,color:"#aaa",pointerEvents:"none"}})]})]})}function QI(t,s){try{const n=new Date(t);if(isNaN(n.getTime()))throw new Error("Invalid ISO string");return n.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZone:s})}catch(n){return console.error("Error formatting slot time:",n),"Invalid Time"}}function Yc({slot:t,isSelected:s,onClick:n,timezone:r}){const a=QI(t.start,r);return e.jsx("button",{type:"button",onClick:n,className:$e("w-full rounded-lg border px-3 py-2 text-sm font-medium transition-all","hover:scale-[1.02] hover:shadow-sm focus-visible:outline-none focus-visible:ring-2",t.preference==="deprioritized"&&!s&&"border-gray-200 bg-white text-gray-400 opacity-60 hover:opacity-80"),style:{fontFamily:"'Montserrat', sans-serif",...t.preference==="preferred"&&!s?{borderColor:"#7ECCEE",backgroundColor:"#e8f6fc",color:"#3a8ba8"}:{},...t.preference==="standard"&&!s?{borderColor:"#e5e7eb",backgroundColor:"white",color:"#56585A"}:{},...s?{borderColor:"#7ECCEE",backgroundColor:"#d0effa",color:"#2a7a96",boxShadow:"0 0 0 2px #7ECCEE"}:{}},children:a})}function JI(t,s){const n=t.toLocaleDateString("en-US",{weekday:"short",timeZone:s}),r=t.toLocaleDateString("en-US",{month:"short",day:"numeric",timeZone:s});return{weekday:n,dateStr:r}}function ZI({date:t,slots:s,selectedSlot:n,onSlotSelect:r,bookerTimezone:a}){const{weekday:o,dateStr:i}=JI(t,a),d=s.filter(x=>x.preference==="preferred"),m=s.filter(x=>x.preference==="standard"),p=s.filter(x=>x.preference==="deprioritized"),c=d.length>0,u=s.length>0;return e.jsxs("div",{className:"flex min-w-[120px] flex-1 flex-col",children:[e.jsxs("div",{className:"mb-3 text-center",children:[e.jsx("div",{className:"text-sm font-semibold text-gray-900",children:o}),e.jsx("div",{className:"text-xs text-gray-500",children:i})]}),u?e.jsxs("div",{className:"flex flex-col gap-1.5",children:[c&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-0.5 text-center text-[10px] font-medium uppercase tracking-wider",style:{color:"#3a8ba8"},children:"Preferred"}),d.map(x=>e.jsx(Yc,{slot:x,isSelected:(n==null?void 0:n.start)===x.start,onClick:()=>r(x),timezone:a},x.start)),(m.length>0||p.length>0)&&e.jsx("div",{className:"my-1 border-t border-gray-100"})]}),m.map(x=>e.jsx(Yc,{slot:x,isSelected:(n==null?void 0:n.start)===x.start,onClick:()=>r(x),timezone:a},x.start)),p.length>0&&(d.length>0||m.length>0)&&e.jsx("div",{className:"my-1 border-t border-gray-100"}),p.map(x=>e.jsx(Yc,{slot:x,isSelected:(n==null?void 0:n.start)===x.start,onClick:()=>r(x),timezone:a},x.start))]}):e.jsx("div",{className:"flex flex-1 items-start justify-center pt-4",children:e.jsx("span",{className:"text-xs text-gray-400",children:"No availability"})})]})}function py({...t}){return e.jsx(gj,{"data-slot":"popover",...t})}function xy({...t}){return e.jsx(bj,{"data-slot":"popover-trigger",...t})}function hy({className:t,align:s="center",sideOffset:n=4,...r}){return e.jsx(yj,{children:e.jsx(jj,{"data-slot":"popover-content",align:s,sideOffset:n,className:$e("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:sli
385de-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",t),...r})})}function Mr(t,s){var i,d,m;const n=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),r=(i=n.find(p=>p.type==="year"))==null?void 0:i.value,a=(d=n.find(p=>p.type==="month"))==null?void 0:d.value,o=(m=n.find(p=>p.type==="day"))==null?void 0:m.value;return`${r}-${a}-${o}`}function XI(t,s,n){const r=new Map;for(const a of s)r.set(Mr(a,n),[]);for(const a of Object.keys(t))for(const o of t[a]){const i=Mr(new Date(o.start),n),d=r.get(i);d&&d.push(o)}return r}function eR(t,s){const n=t.toLocaleDateString("en-US",{weekday:"short",timeZone:s}),r=t.toLocaleDateString("en-US",{day:"numeric",timeZone:s});return{weekday:n,day:r}}function Xa(t,s){return s.find(n=>n.date===t)||null}function tR({weekDates:t,slots:s,blockedDays:n=[],selectedSlot:r,onSlotSelect:a,bookerTimezone:o,isLoading:i}){const[d,m]=l.useState(()=>{for(let g=0;g<t.length;g++){const y=Mr(t[g],o);if(!Xa(y,n))return g}return 0});ee.useEffect(()=>{if(!i)for(let g=0;g<t.length;g++){const y=Mr(t[g],o);if(!Xa(y,n)){m(g);return}}},[n,i]);const p=i?new Map:XI(s,t,o),c=e.jsx("div",{className:"hidden md:flex md:gap-3",children:t.map(g=>{const y=Mr(g,o),j=i?null:Xa(y,n);if(j)return e.jsx(sR,{date:g,blocked:j,timezone:o},y);if(i){const v=g.toLocaleDateString("en-US",{weekday:"short",timeZone:o}),T=g.toLocaleDateString("en-US",{month:"short",day:"numeric",timeZone:o});return e.jsxs("div",{style:{flex:1,minWidth:"100px",display:"flex",flexDirection:"column"},children:[e.jsxs("div",{style:{marginBottom:"12px",textAlign:"center"},children:[e.jsx("div",{style:{fontSize:"14px",fontWeight:600,color:"#56585A"},children:v}),e.jsx("div",{style:{fontSize:"12px",color:"#9ca3af"},children:T})]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:Array.from({length:3}).map((k,w)=>e.jsx("div",{style:{height:"36px",borderRadius:"8px",backgroundColor:"#e5e7eb",animation:"pulse 1.5s ease-in-out infinite",animationDelay:`${w*.15}s`}},w))})]},y)}return e.jsx(ZI,{date:g,slots:p.get(y)||[],selectedSlot:r,onSlotSelect:a,bookerTimezone:o},y)})}),u=t[d],x=u?Mr(u,o):"",h=Xa(x,n),b=p.get(x)||[],f=e.jsxs("div",{className:"md:hidden",children:[e.jsx("div",{className:"mb-4 flex gap-1",children:t.map((g,y)=>{const{weekday:j,day:v}=eR(g,o),T=Mr(g,o),k=Xa(T,n),I=(p.get(T)||[]).length>0,A=y===d,E=!!k,C=(k==null?void 0:k.reason)==="holiday",N=(k==null?void 0:k.reason)==="vacation",S=(k==null?void 0:k.reason)==="weekend",O=e.jsxs("button",{type:"button",onClick:()=>{S||m(y)},disabled:S,className:$e("flex flex-1 flex-col items-center rounded-lg py-2 text-center transition-all",S&&"cursor-not-allowed"),style:{fontFamily:"'Montserrat', sans-serif",...S?{backgroundColor:"#2a2a2a",color:"#888",opacity:.5}:C?{backgroundColor:"#DDCB77",color:"white"}:N?{backgroundColor:"#7ECCEE",color:"white",opacity:.7}:A?{backgroundColor:"#56585A",color:"white"}:I||i?{backgroundColor:"white",color:"#56585A",border:"1px solid #e5e7eb"}:{backgroundColor:"#f9fafb",color:"#9ca3af",border:"1px solid #f3f4f6"}},children:[e.jsx("span",{className:"text-[10px] font-medium",children:j}),e.jsx("span",{className:"text-base font-semibold leading-tight",children:v}),!E&&I&&!A&&e.jsx("span",{className:"mt-0.5 h-1.5 w-1.5 rounded-full",style:{backgroundColor:"#7ECCEE"}})]},T);return C||N?e.jsxs(py,{children:[e.jsx(xy,{asChild:!0,children:O}),e.jsx(hy,{className:"w-auto px-3 py-2 text-xs font-medium",style:{fontFamily:"'Montserrat', sans-serif",backgroundColor:"white",color:"#56585A",border:"1px solid #e5e7eb"},children:k.label})]},T):O})}),i?e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"8px"},children:[e.jsx("style",{children:"@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }"}),Array.from({length:9}).map((g,y)=>e.jsx("div",{style:{height:"44px",borderRadius:"8px",backgroundColor:"#e5e7eb",animation:"pulse 1.5s ease-in-out infinite",animationDelay:`${y*.1}s`}},y))]}):h?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12",children:[e.jsx("div",{className:"rounded-lg px-5 py-3 text-sm font-medium text-center",style:{fontFamily:"'Montserrat', sans-serif",...h.reason==="holiday"?{backgroundColor:"#f9f5e8",color:"#856404",border:"1px solid #DDCB77"}
385:h.reason==="vacation"?{backgroundColor:"#e8f6fc",color:"#3a8ba8",border:"1px solid #7ECCEE"}:{backgroundColor:"#f3f4f6",color:"#56585A"}},children:h.label}),e.jsx("p",{className:"text-xs text-gray-400",children:"Not available for booking"})]}):b.length===0?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("p",{className:"text-sm text-gray-400",children:"No available times on this day"})}):e.jsx(nR,{slots:b,selectedSlot:r,onSlotSelect:a,timezone:o})]});return e.jsxs(e.Fragment,{children:[f,c]})}function sR({date:t,blocked:s,timezone:n}){const r=t.toLocaleDateString("en-US",{weekday:"short",timeZone:n}),a=t.toLocaleDateString("en-US",{month:"short",day:"numeric",timeZone:n}),o=s.reason==="weekend",i=s.reason==="holiday",d=s.reason==="vacation",m=o?{bg:"#ebebeb",headerColor:"#aaa",dateColor:"#ccc",labelColor:"#999"}:i?{bg:"#f9f5e8",headerColor:"#b8960c",dateColor:"#DDCB77",labelColor:"#856404"}:{bg:"#e8f6fc",headerColor:"#3a8ba8",dateColor:"#7ECCEE",labelColor:"#3a8ba8"},p=e.jsxs("div",{className:"flex min-w-[100px] flex-1 flex-col",children:[e.jsxs("div",{className:"mb-3 text-center",children:[e.jsx("div",{className:"text-sm font-semibold",style:{color:m.headerColor},children:r}),e.jsx("div",{className:"text-xs",style:{color:m.dateColor},children:a})]}),e.jsxs("div",{className:$e("flex flex-1 flex-col items-center justify-center rounded-lg py-6",(i||d)&&"cursor-pointer hover:opacity-80 transition-opacity"),style:{backgroundColor:m.bg,minHeight:"80px"},children:[i&&e.jsxs("svg",{className:"mb-1",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:m.labelColor,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"}),e.jsx("line",{x1:"4",y1:"22",x2:"4",y2:"15"})]}),e.jsx("span",{className:"text-[10px] font-medium text-center px-1",style:{color:m.labelColor},children:o?"":s.label})]})]});return i||d?e.jsxs(py,{children:[e.jsx(xy,{asChild:!0,children:p}),e.jsxs(hy,{className:"w-auto px-3 py-2 text-sm font-medium",style:{fontFamily:"'Montserrat', sans-serif",backgroundColor:"white",color:"#56585A",border:"1px solid #e5e7eb"},children:[s.label,e.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:"Not available for booking"})]})]}):p}function nR({slots:t,selectedSlot:s,onSlotSelect:n,timezone:r}){const a=t.filter(d=>d.preference==="preferred"),o=t.filter(d=>d.preference==="standard"),i=t.filter(d=>d.preference==="deprioritized");return e.jsxs("div",{className:"space-y-4",children:[a.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium uppercase tracking-wider",style:{color:"#3a8ba8",fontFamily:"'Montserrat', sans-serif"},children:"Recommended times"}),e.jsx(Gc,{slots:a,selectedSlot:s,onSlotSelect:n,timezone:r})]}),o.length>0&&e.jsxs("div",{children:[a.length>0&&e.jsx("p",{className:"mb-2 text-xs font-medium uppercase tracking-wider text-gray-400",children:"More times"}),e.jsx(Gc,{slots:o,selectedSlot:s,onSlotSelect:n,timezone:r})]}),i.length>0&&e.jsx("div",{children:e.jsx(Gc,{slots:i,selectedSlot:s,onSlotSelect:n,timezone:r})})]})}function Gc({slots:t,selectedSlot:s,onSlotSelect:n,timezone:r}){return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:t.map(a=>{const o=new Date(a.start).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZone:r}),i=(s==null?void 0:s.start)===a.start;return e.jsx("button",{type:"button",onClick:()=>n(a),className:$e("rounded-lg border px-2 py-2.5 text-sm font-medium transition-all","active:scale-95",a.preference==="standard"&&!i&&"border-gray-200 bg-white text-gray-900",a.preference==="deprioritized"&&!i&&"border-gray-200 bg-white text-gray-400",i&&"ring-2"),style:{fontFamily:"'Montserrat', sans-serif",...a.preference==="preferred"&&!i?{borderColor:"#7ECCEE",backgroundColor:"#e8f6fc",color:"#3a8ba8"}:{},...i?{borderColor:"#7ECCEE",backgroundColor:"#d0effa",color:"#2a7a96",boxShadow:"0 0 0 2px #7ECCEE"}:{}},children:o},a.start)})})}const rR="https://us-central1-bucky-app-355a3.cloudfunctions.net";function aR(t,s){const n=[],r=new Date(t);r.setHours(0,0,0,0);for(let a=0;a<s;a++)n.push(new Date(r)),r.setDate(r.getDate()+1);return n}function vx(t){const s=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${s}-${n}-${r}`}function oR({slug:t,meetingTypeId:s,durationMinutes:n,bookerTimezone:r,onTimezoneChange:a,onSlotSelect:o,initialSlotsPromise:i,withTeamMember:d}){const[m,p]=l.useState(0),[c,u]=l.useState({}),[x,h]=l.useState([]),[b,f]=l.useState(null),[g,y]=l.useState(!0),[j,v]=l.useState(null),T=l.useRef(!1),k=7,w=new Date;w.setHours(0,0,0,0);const I=new Date(w);I.setDate(I.getDate()+m*k);const A=aR(I,k),E=A[0],C=A[A.length-1],N=l.useCallback(async()=>
385{if(y(!0),v(null),!A||A.length===0){console.error("Invalid visibleDates provided"),v("Invalid date range. Please try again."),y(!1);return}const O=vx(A[0]),R=vx(A[A.length-1]);if(!O||!R){console.error("Failed to convert dates to ISO format"),v("Invalid date range. Please try again."),y(!1);return}if(m===0&&!d&&i&&!T.current){T.current=!0;try{const z=await i;u(z.slots||{}),h(z.blockedDays||[]),y(!1);return}catch{}}try{const z=await fetch(`${rR}/getAvailableSlots`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:t,startDate:O,endDate:R,meetingTypeId:s,withTeamMember:d||void 0})});if(!z.ok)throw new Error("Failed to load available times");const D=await z.json();u(D.slots||{}),h(D.blockedDays||[])}catch(z){console.error("Error fetching slots:",z),v("Unable to load available times. Please try again."),u({}),h([])}finally{y(!1)}},[t,s,m,i,d]);l.useEffect(()=>{N()},[N]),l.useEffect(()=>{f(null)},[m]);const S=O=>{f(O),o(O)};return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:[e.jsx(GI,{currentWeekStart:E,currentWeekEnd:C,onPrevWeek:()=>p(O=>Math.max(0,O-1)),onNextWeek:()=>p(O=>O+1),canGoPrev:m>0}),j&&e.jsxs("div",{className:"rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700",children:[j,e.jsx("button",{type:"button",className:"ml-2 font-medium underline hover:no-underline",onClick:N,children:"Retry"})]}),g&&e.jsx("p",{style:{textAlign:"center",fontSize:"13px",color:"#56585Aaa",fontFamily:"'Montserrat', sans-serif"},children:"Loading availability..."}),e.jsx(tR,{weekDates:A,slots:c,blockedDays:x,selectedSlot:b,onSlotSelect:S,bookerTimezone:r,isLoading:g}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:"8px"},children:[e.jsx(KI,{timezone:r,onChange:a}),e.jsxs("span",{style:{fontSize:"12px",color:"#56585Aaa",fontFamily:"'Montserrat', sans-serif"},children:[n,"-minute meeting"]})]})]})}function iR(t,s){const n=new Date(t),r=n.toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:s}),a=n.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZone:s,timeZoneName:"short"});return{date:r,time:a}}function lR(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function cR(t){const s=t.trim();return s?/^https?:\/\//i.test(s)?s:`https://${s.replace(/^\/+/,"")}`:""}function dR({selectedSlot:t,meetingType:s,teamMemberName:n,bookerTimezone:r,onSubmit:a,onBack:o,isSubmitting:i,initialData:d}){const[m,p]=l.useState((d==null?void 0:d.name)||""),[c,u]=l.useState((d==null?void 0:d.email)||""),[x,h]=l.useState((d==null?void 0:d.companyUrl)||""),[b,f]=l.useState((d==null?void 0:d.topic)||""),[g,y]=l.useState({});l.useEffect(()=>{d!=null&&d.name&&!m&&p(d.name),d!=null&&d.email&&!c&&u(d.email),d!=null&&d.companyUrl&&!x&&h(d.companyUrl),d!=null&&d.topic&&!b&&f(d.topic)},[d]);const{date:j,time:v}=iR(t.start,r),T=()=>{const w={};return m.trim()||(w.name="Name is required"),c.trim()?lR(c.trim())||(w.email="Please enter a valid email address"):w.email="Email is required",y(w),Object.keys(w).length===0},k=w=>{w.preventDefault(),T()&&a({name:m.trim(),email:c.trim(),companyUrl:cR(x),topic:b.trim()})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{type:"button",onClick:o,className:"flex items-center gap-1 text-sm text-gray-500 transition-colors hover:text-gray-700",children:[e.jsx(dt,{className:"h-4 w-4"}),"Back to calendar"]}),e.jsx("div",{style:{borderRadius:"10px",border:"1px solid #7ECCEE33",backgroundColor:"#e8f6fc",padding:"16px"},children:e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"12px"},children:[e.jsx("div",{style:{marginTop:2,borderRadius:"9999px",backgroundColor:"#d0effa",padding:"8px"},children:e.jsx(Ss,{style:{width:16,height:16,color:"#7ECCEE"}})}),e.jsxs("div",{children:[e.jsx("p",{style:{fontWeight:600,color:"#56585A",fontFamily:"'Montserrat', sans-serif"},children:j}),e.jsx("p",{style:{fontSize:"14px",color:"#56585Aaa",fontFamily:"'Montserrat', sans-serif"},children:v}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-xs text-gray-500",children:[e.jsx(ms,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.durationMinutes," min"]}),n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:"·"}),e.jsxs("span",{children:["with ",n]})]})]})]})]})}),e.jsxs("form",{onSubmit:k,className:"space-y-4",children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[e.jsx("label",{htmlFor:"booking-name",style:{fontSize:"14px",fontWeight:500,color:"#56585A",fontFamily:"'Montserrat', sans-serif"},children:"Full Name *"}),e.jsx("input",{id:"booking-name",type:"text",placeholder:"Jane Smith",value:m,onChange:w=>p(w.target.value),style:{border:g.name?"1px solid #ef4444":"1px solid #d1d5db",borderRadius:"8px",padding:"10px 12px",fontSize:"14px",fontFamily:"'Montserrat', sans-serif",color:"#56585A",outline:"none",width:"100%",boxSizing:"border-box"},onFocus:w=>{g.name||(w.target.style.borderColor="#7ECCEE")},onBlur:w=>{g.name||(w.target.style.borderColor="#d1d5db")}}),g.name&&e.jsx("p",{style:{fontSize:"12px",color:"#ef4444"},children:g.name})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[e.jsx("label",{htmlFor:"booking-email",style:{fontSize:"14px",fontWeight:500,color:"#56585A",fontFamily:"'Montserrat', sans-serif"},children:"Email *"}),e.jsx("input",{id:"booking-email",type:"email",placeholder:"[email protected]",value:c,onChange:w=>u(w.target.value),style:{border:g.email?"1px solid #ef4444":"1px solid #d1d5db",borderRadius:"8px",padding:"10px 12px",fontSize:"14px",fontFamily:"'Montserrat', sans-serif",color:"#56585A",outline:"none",width:"100%",boxSizing:"border-box"},onFocus:w=>{g.email||(w.target.style.borderColor="#7ECCEE")},onBlur:w=>{g.email||(w.target.style.borderColor="#d1d5db")}}),g.email&&e.jsx("p",{style:{fontSize:"12px",color:"#ef4444"},children:g.email})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[e.jsx("label",{htmlFor:"booking-company",style:{fontSize:"14px",fontWeight:500,color:"#56585A",fontFamily:"'Montserrat', sans-serif"},children:"Company Website"}),e.jsx("input",{id:"booking-company",type:"text",inputMode:"url",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,placeholder:"company.com",value:x,onChange:w=>h(w.target.value),style:{border:"1px solid #d1d5db",borderRadius:"8px",padding:"10px 12px",fontSize:"14px",fontFamily:"'Montserrat', sans-serif",color:"#56585A",outline:"none",width:"100%",boxSizing:"border-box"},onFocus:w=>{w.target.style.borderColor="#7ECCEE"},onBlur:w=>{w.target.style.borderColor="#d1d5db"}})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[e.jsx("label",{htmlFor:"booking-topic",style:{fontSize:"14px",fontWeight:500,color:"#56585A",fontFamily:"'Montserrat', sans-serif"}
385,children:"What would you like to discuss?"}),e.jsx("textarea",{id:"booking-topic",placeholder:"Tell us a bit about what you'd like to cover...",value:b,onChange:w=>f(w.target.value),rows:3,style:{border:"1px solid #d1d5db",borderRadius:"8px",padding:"10px 12px",fontSize:"14px",fontFamily:"'Montserrat', sans-serif",color:"#56585A",outline:"none",width:"100%",boxSizing:"border-box",resize:"vertical"},onFocus:w=>{w.target.style.borderColor="#7ECCEE"},onBlur:w=>{w.target.style.borderColor="#d1d5db"}})]}),e.jsx("button",{type:"submit",disabled:i,style:{width:"100%",padding:"12px",borderRadius:"8px",border:"none",backgroundColor:"#7ECCEE",color:"white",fontSize:"15px",fontWeight:600,fontFamily:"'Montserrat', sans-serif",cursor:i?"not-allowed":"pointer",opacity:i?.6:1,transition:"opacity 0.2s"},children:i?"Confirming...":"Confirm Booking"})]})]})}function uR(t,s){const n=new Date(t),r=n.toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric",timeZone:s}),a=n.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZone:s,timeZoneName:"short"});return{date:r,time:a}}function mR({bookingResult:t,meetingType:s,teamMemberName:n,bookerTimezone:r,onBookAnother:a}){const o=n||t.teamMemberName||"Team",{date:i,time:d}=uR(t.startTime,r);return ee.useEffect(()=>{window.parent!==window&&window.parent.postMessage({type:"BOOKING_COMPLETE",bookingId:t.bookingId,meetLink:t.meetLink,startTime:t.startTime,teamMemberName:t.teamMemberName},"*")},[t]),e.jsxs("div",{className:"flex flex-col items-center space-y-6 py-8 text-center",style:{fontFamily:"'Montserrat', sans-serif"},children:[e.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-full",style:{backgroundColor:"#e8f6fc"},children:e.jsx(kt,{className:"h-8 w-8",style:{color:"#7ECCEE"},strokeWidth:3})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",style:{color:"#56585A"},children:"You're booked!"}),e.jsx("p",{className:"mt-1 text-sm font-light",style:{color:"#56585Aaa"},children:"A calendar invitation has been sent to your email."})]}),e.jsxs("div",{className:"w-full max-w-sm rounded-xl border p-5 text-left",style:{backgroundColor:"#f7f8fa",borderColor:"#e5e7eb"},children:[e.jsx("h3",{className:"mb-3 font-semibold",style:{color:"#56585A"},children:s.name}),e.jsxs("div",{className:"space-y-2.5 text-sm",style:{color:"#56585A"},children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(Ss,{className:"h-4 w-4 shrink-0",style:{color:"#7ECCEE"}}),e.jsx("span",{children:i})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(ms,{className:"h-4 w-4 shrink-0",style:{color:"#7ECCEE"}}),e.jsxs("span",{children:[d," · ",s.durationMinutes," min"]})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(ei,{className:"h-4 w-4 shrink-0",style:{color:"#7ECCEE"}}),e.jsx("span",{children:o})]}),t.meetLink&&e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(tu,{className:"h-4 w-4 shrink-0",style:{color:"#DDCB77"}}),e.jsx("a",{href:t.meetLink,target:"_blank",rel:"noopener noreferrer",className:"truncate underline",style:{color:"#7ECCEE"},children:"Join Google Meet"})]})]})]}),e.jsx("svg",{width:"40",height:"8",viewBox:"0 0 40 8",fill:"none",children:e.jsx("path",{d:"M2 2C5.5 6 8.5 6 12 2C15.5 6 18.5 6 22 2C25.5 6 28.5 6 32 2C35.5 6 38 6 38 2",stroke:"#DDCB77",strokeWidth:"2",strokeLinecap:"round"})}),e.jsx(ke,{variant:"outline",onClick:a,style:{borderColor:"#7ECCEE",color:"#3a8ba8",fontFamily:"'Montserrat', sans-serif"},children:"Book another meeting"})]})}function pR({mode:t,onModeChange:s,calendarEnabled:n,aiEnabled:r,children:a}){return n&&r?e.jsxs("div",{className:"w-full",children:[e.jsxs("div",{className:"relative flex overflow-hidden",style:{backgroundColor:"#e8e8e8",fontFamily:"'Montserrat', sans-serif",borderRadius:"9999px",padding:"4px",marginBottom:"24px"},children:[e.jsx("div",{style:{position:"absolute",top:"4px",bottom:"4px",borderRadius:"9999px",backgroundColor:"#7ECCEE",width:"calc(50% - 4px)",left:t==="calendar"?"4px":"calc(50%)",transition:"left 0.3s ease-in-out"}}),n&&e.jsxs("button",{type:"button",onClick:()=>s("calendar"),style:{position:"relative",zIndex:10,display:"flex",flex:1,alignItems:"center",justifyContent:"center",gap:"6px",borderRadius:"9999px",padding:"10px 0",fontSize:"14px",fontWeight:500,color:t==="calendar"?"white":"#56585A",background:"none",border:"none",cursor:"pointer",transition:"color 0.2s"},children:[e.jsx(Ss,{style:{width:16,height:16}}),"Pick a Time"]}),r&&e.jsxs("button",{type:"button",onClick:()=>s("ai"),style:{position:"relative",zIndex:10,display:"flex",flex:1,alignItems:"center",justifyContent:"center",gap:"6px",borderRadius:"9999px",padding:"10px 0",fontSize:"14px",fontWeight:500,color:t==="ai"?"white":"#56585A",background:"none",border:"none",cursor:"pointer",transition:"color 0.2s"},children:[e.jsx(_l,{style:{width:16,height:16}}),"Let Us Help"]})]}),a]}):e.jsx(e.Fragment,{children:a})}function xR({slot:t,onClick:s}){return e.jsxs("button",{type:"button",onClick:s,className:"group flex w-full items-center gap-3 rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 text-left transition-all hover:scale-[1.01] hover:shadow-md",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-blue-100 text-blue-600",children:e.jsx(Ss,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.displayText}),t.teamMemberSlug&&e.jsxs("p",{className:"mt-0.5 truncate text-xs text-gray-500",children:["with ",t.teamMemberSlug]})]}),e.jsx(Rt,{className:"h-4 w-4 shrink-0 text-gray-400 transition-transform group-hover:translate-x-0.5"})]})}function hR({role:t,content:s,suggestedSlots:n,onSlotSelect:r}){return t==="user"?e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx("div",{style:{maxWidth:"80%",borderRadius:"18px 18px 4px 18px",backgroundColor:"#7ECCEE",color:"#1a1a1a",padding:"10px 16px",fontSize:"14px",fontFamily:"'Montserrat', sans-serif",lineHeight:1.5},children:s})}):e.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"flex-end"},children:[e.jsx("div",{style:{marginBottom:4,flexShrink:0},children:e.jsx(Fl,{style:{width:18,height:18,color:"#7ECCEE"}})}),e.jsxs("div",{style:{minWidth:0,flex:1},children:[e.jsx("div",{style:{maxWidth:"90%",borderRadius:"18px 18px 18px 4px",backgroundColor:"#f3f4f6",color:"#56585A",padding:"10px 16px",fontSize:"14px",fontFamily:"'Montserrat', sans-serif",lineHeight:1.5},children:s}),n&&n.length>0&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px",paddingLeft:4,marginTop:8},children:n.map((a,o)=>e.jsx(xR,{slot:a,onClick:()=>r==null?void 0:r(a)},`${a.start}-${o}`))})]})]})}const fR="https://us-central1-bucky-app-355a3.cloudfunctions.net";function gR({slug:t,teamMemberName:s,isGeneral:n,onSlotSelect:r,onReadyToBook:a,onConversationUpdate:o}){const i={role:"assistant",content:n?"Welcome to Sunbowl Systems! I'd love to help you find the right person to talk to. What can we help you with?":`Hi! I'll help you find a time to meet with ${s}
385. What would you like to discuss?`},[d,m]=l.useState([i]),[p,c]=l.useState(""),[u,x]=l.useState(!1),h=l.useRef(null),b=l.useRef(null);l.useEffect(()=>{o&&d.length>1&&o(d.map(({role:j,content:v})=>({role:j,content:v})))},[d]),l.useEffect(()=>{var j;(j=h.current)==null||j.scrollIntoView({behavior:"smooth"})},[d,u]);const f=l.useCallback(async()=>{const j=p.trim();if(!j||u)return;const v={role:"user",content:j},T=[...d,v];m(T),c(""),x(!0);try{const k=T.map(({role:E,content:C})=>({role:E,content:C})),w=await fetch(`${fR}/bookingAiAssist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:t,message:j,history:k})});if(!w.ok)throw new Error("Failed to get AI response");const I=await w.json(),A={role:"assistant",content:I.response||I.message||"I'm sorry, I couldn't process that. Could you rephrase?",suggestedSlots:I.suggestedSlots};m(E=>[...E,A]),I.readyToBook&&a({slot:{start:I.readyToBook.start,end:I.readyToBook.end,preference:"standard",teamMemberSlug:I.readyToBook.teamMemberSlug},name:I.readyToBook.name,email:I.readyToBook.email,companyUrl:I.readyToBook.companyUrl,topic:I.readyToBook.topic,meetingTypeId:I.readyToBook.meetingTypeId})}catch(k){console.error("AI assist error:",k),m(w=>[...w,{role:"assistant",content:"Sorry, something went wrong on my end. Please try again or pick a time from the calendar instead."}])}finally{x(!1)}},[p,u,d,t,a]),g=j=>{var A;const v={start:j.start,end:j.end,preference:"standard",teamMemberSlug:j.teamMemberSlug},T=d.filter(E=>E.role==="user"),k=T.map(E=>E.content).join(" "),w=k.match(/[\w.-]+@[\w.-]+\.\w+/),I=k.match(/(?:my name is|i'm|i am|name:?)\s+([A-Z][a-z]+(?: [A-Z][a-z]+)*)/i);w||I?a({slot:v,name:I==null?void 0:I[1],email:w==null?void 0:w[0],topic:(A=T[0])==null?void 0:A.content}):r(v)},y=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),f())};return e.jsxs("div",{className:"flex h-[480px] flex-col rounded-lg border border-gray-200",children:[e.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:e.jsxs("div",{className:"space-y-4",children:[d.map((j,v)=>e.jsx(hR,{role:j.role,content:j.content,suggestedSlots:j.suggestedSlots,onSlotSelect:g},v)),u&&e.jsxs("div",{className:"flex gap-2.5",children:[e.jsx("div",{className:"mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-gray-100",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("span",{className:"h-1.5 w-1.5 animate-bounce rounded-full bg-gray-400 [animation-delay:-0.3s]"}),e.jsx("span",{className:"h-1.5 w-1.5 animate-bounce rounded-full bg-gray-400 [animation-delay:-0.15s]"}),e.jsx("span",{className:"h-1.5 w-1.5 animate-bounce rounded-full bg-gray-400"})]})}),e.jsx("div",{className:"rounded-tr-lg rounded-br-lg rounded-bl-lg bg-gray-100 px-4 py-3",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("span",{className:"h-2 w-2 animate-bounce rounded-full bg-gray-400 [animation-delay:-0.3s]"}),e.jsx("span",{className:"h-2 w-2 animate-bounce rounded-full bg-gray-400 [animation-delay:-0.15s]"}),e.jsx("span",{className:"h-2 w-2 animate-bounce rounded-full bg-gray-400"})]})})]}),e.jsx("div",{ref:h})]})}),e.jsx("div",{className:"border-t border-gray-200 px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:b,type:"text",value:p,onChange:j=>c(j.target.value),onKeyDown:y,placeholder:"Type a message...",disabled:u,className:"flex-1 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"}),e.jsx(ke,{type:"button",size:"icon",onClick:f,disabled:!p.trim()||u,className:"shrink-0",children:e.jsx(An,{className:"h-4 w-4"})})]})})]})}function bR({label:t,checked:s,onChange:n,notice:r}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px",padding:"12px 14px",borderRadius:"10px",backgroundColor:s?"#e8f6fc":"#f9fafb",border:`1px solid ${s?"#7ECCEE":"#e5e7eb"}`,transition:"background-color 0.15s, border-color 0.15s"},children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"10px",cursor:"pointer",fontFamily:"'Montserrat', sans-serif",fontSize:"13px",fontWeight:500,color:"#56585A"},children:[e.jsx("input",{type:"checkbox",checked:s,onChange:a=>n(a.target.checked),style:{width:"16px",height:"16px",accentColor:"#7ECCEE",cursor:"pointer"}}),e.jsx("span",{children:t})]}),r&&e.jsx("p",{style:{margin:0,paddingLeft:"26px",fontSize:"11px",color:"#3a8ba8",fontFamily:"'Montserrat', sans-serif"},children:r})]})}function wx(t){const s=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${s}-${n}-${r}`}const Kc="https://us-central1-bucky-app-355a3.cloudfunctions.net";function Qc(){var J,H,Z;const{teamMember:t,source:s}=zl(),[n]=Zo(),r=t||"general",a=n.get("embed")==="true",o=s||n.get("source")||null,[i,d]=l.useState("select-type"),[m,p]=l.useState(null),[c,u]=l.useState(!0),[x,h]=l.useState(null),[b,f]=l.useState(null),[g,y]=l.useState(null),[j,v]=l.useState(()=>Intl.DateTimeFormat().resolvedOptions().timeZone),T=r==="general",[k,w]=l.useState(T?"ai":"calendar"),I={name:n.get("name")||void 0,email:n.get("email")||void 0,companyUrl:n.get("company")||void 0,topic:n.get("topic")||void 0};I.name||I.email;const[A,E]=l.useState(I),[C,N]=l.useState(null),[S,O]=l.useState(!1),[R,z]=l.useState(null),[D,L]=l.useState(null),[$,q]=l.useState(!1),P=(m==null?void 0:m.pairableWith)||null,U=$&&P?P:null;l.useEffect(()=>{fetch("https://geo.sunbowl.ca/json").then(Q=>Q.json()).then(Q=>{Q.timezone&&v(Q.timezone)}).catch(()=>{})},[]);const V=l.useCallback(async()=>{var Q,K,X,se;u(!0),h(null);try{const pe=await fetch(`${Kc}/getBookingConfig?slug=${encodeURIComponent(r)}`);if(!pe.ok)throw pe.status===404?new Error("This booking link is not available."):new Error("Failed to load booking page.");const me=await pe.json(),Ne={slug:me.slug||r,branding:{companyName:((Q=me.branding)==null?void 0:Q.companyName)||"Sunbowl",companyLogoUrl:(K=me.branding)==null?void 0:K.companyLogoUrl,tagline:(X=me.branding)==null?void 0:X.tagline,accentColor:(se=me.branding)==null?void 0:se.accentColor},teamMember:me.teamMember?{name:me.teamMember.name,title:me.teamMember.title,photoUrl:me.teamMember.photoUrl,slug:me.teamMember.slug||r}:null,meetingTypes:(me.meetingTypes||[]).map(ae=>({id:ae.id,name:ae.name,durationMinutes:ae.durationMinutes,description:ae.description})),pairableWith:me.pairableWith||null,pairLabel:me.pairLabel||null};p(Ne);const at=Ne.meetingTypes.find(ae=>ae.isDefault)||Ne.meetingTypes[0];at&&(f(at),d("select-time"))}catch(pe){console.error("Error fetching booking config:",pe),h(pe.message||"Something went wrong. Please try again later.")}finally{u(!1)}},[r]);l.useEffect(()=>{V()},[V]),l.useEffect(()=>{if(T){L(null);return}const Q=new Date;Q.setHours(0,0,0,0);const K=new Date(Q);K.setDate(K.getDate()+6);const X=fetch(`${Kc}/getAvailableSlots`,{method:"POST",headers:{"Content-Type":"application/json"}
385,body:JSON.stringify({slug:r,startDate:wx(Q),endDate:wx(K)})}).then(se=>{if(!se.ok)throw new Error("Failed to load available times");return se.json()}).then(se=>({slots:se.slots||{},blockedDays:se.blockedDays||[]}));X.catch(()=>{}),L(X)},[r,T]);const M=Q=>{f(Q),y(null),d("select-time")},F=Q=>{y(Q),d("intake")},W=()=>{d("select-time")},_=Q=>{y(Q),!b&&m&&m.meetingTypes.length>0&&f(m.meetingTypes[0]),d("intake")},G=Q=>{if(y({start:Q.slot.start,end:Q.slot.end,preference:Q.slot.preference||"standard",teamMemberSlug:Q.slot.teamMemberSlug}),Q.meetingTypeId&&m){const K=m.meetingTypes.find(X=>X.id===Q.meetingTypeId);K&&f(K)}!b&&m&&m.meetingTypes.length>0&&f(m.meetingTypes[0]),E({name:Q.name,email:Q.email,companyUrl:Q.companyUrl,topic:Q.topic}),d("intake")},B=async Q=>{if(!(!g||!b)){O(!0);try{const K=await fetch(`${Kc}/createBooking`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:r,meetingTypeId:b.id,startTime:g.start,endTime:g.end,bookerTimezone:j,name:Q.name,email:Q.email,companyUrl:Q.companyUrl||void 0,topic:Q.topic||void 0,slotPreference:g.preference,routedFrom:g.teamMemberSlug,aiConversation:C||void 0,bookingSource:o||void 0,withTeamMember:U||void 0})});if(!K.ok){const se=await K.json().catch(()=>({}));throw new Error(se.error||"Failed to create booking. Please try again.")}const X=await K.json();z(X),d("confirmation")}catch(K){console.error("Error creating booking:",K),alert(K.message||"Something went wrong. Please try again.")}finally{O(!1)}}},Y=()=>{y(null),z(null),E({}),d("select-time")};return x?e.jsx(yx,{branding:null,teamMember:null,isEmbed:a,isLoading:!1,children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-red-100",children:e.jsx("svg",{className:"h-7 w-7 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4.5c-.77-.833-2.694-.833-3.464 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z"})})}),e.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:"Booking Unavailable"}),e.jsx("p",{className:"mt-2 max-w-sm text-sm text-gray-500",children:x}),e.jsx("button",{type:"button",onClick:V,className:"mt-4 text-sm font-medium text-blue-600 hover:text-blue-700",children:"Try again"})]})}):e.jsx(yx,{branding:(m==null?void 0:m.branding)||null,teamMember:(m==null?void 0:m.teamMember)||null,isEmbed:a,isLoading:c,children:c?e.jsx(yR,{}):e.jsxs(e.Fragment,{children:[i==="select-type"&&m&&e.jsx(VI,{meetingTypes:m.meetingTypes,onSelect:M}),i==="select-time"&&b&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:"text-lg font-bold",style:{color:"#56585A",fontFamily:"'Montserrat', sans-serif"},children:"Book a Meeting"}),e.jsx("p",{className:"mt-0.5 text-sm font-light",style:{color:"#56585Aaa",fontFamily:"'Montserrat', sans-serif"},children:k==="ai"?"Chat with us to find the perfect time.":"Select a date and time that works for you."})]}),e.jsx(pR,{mode:k,onModeChange:w,calendarEnabled:!T,aiEnabled:!0,children:k==="calendar"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[(m==null?void 0:m.pairableWith)&&(m==null?void 0:m.pairLabel)&&e.jsx(bR,{label:m.pairLabel,checked:$,onChange:q}),e.jsx(oR,{slug:r,meetingTypeId:b.id,durationMinutes:b.durationMinutes,bookerTimezone:j,onTimezoneChange:v,onSlotSelect:F,initialSlotsPromise:D,withTeamMember:U})]}):e.jsx(gR,{slug:r,teamMemberName:((J=m==null?void 0:m.teamMember)==null?void 0:J.name)||"our team",isGeneral:T,onSlotSelect:_,onReadyToBook:G,onConversationUpdate:N})})]}),i==="intake"&&g&&b&&e.jsx(dR,{selectedSlot:g,meetingType:b,teamMemberName:((H=m==null?void 0:m.teamMember)==null?void 0:H.name)||null,bookerTimezone:j,onSubmit:B,onBack:W,isSubmitting:S,initialData:A}),i==="confirmation"&&R&&b&&e.jsx(mR,{bookingResult:R,meetingType:b,teamMemberName:((Z=m==null?void 0:m.teamMember)==null?void 0:Z.name)||null,bookerTimezone:j,onBookAnother:Y})]})})}function yR(){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(tn,{className:"h-6 w-48"}),e.jsx(tn,{className:"h-4 w-64"})]}),e.jsx("div",{className:"space-y-3",children:[1,2].map(t=>
385e.jsxs("div",{className:"flex items-center gap-4 rounded-xl border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(tn,{className:"h-4 w-32"}),e.jsx(tn,{className:"h-3 w-48"}),e.jsx(tn,{className:"h-3 w-20"})]}),e.jsx(tn,{className:"h-5 w-5 rounded"})]},t))})]})}function jR({...t}){return e.jsx(vj,{"data-slot":"accordion",...t})}function vR({className:t,...s}){return e.jsx(wj,{"data-slot":"accordion-item",className:$e("border-b last:border-b-0",t),...s})}function wR({className:t,children:s,...n}){return e.jsx(Nj,{className:"flex",children:e.jsxs(kj,{"data-slot":"accordion-trigger",className:$e("focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",t),...n,children:[s,e.jsx(Ot,{className:"text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200"})]})})}function NR({className:t,children:s,...n}){return e.jsx(Sj,{"data-slot":"accordion-content",className:"data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm",...n,children:e.jsx("div",{className:$e("pt-0 pb-4",t),children:s})})}const Nx=25;function kR(t){const s=sr(t);return s?s.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",year:"numeric"}):"Invalid Date"}function kx(t){const s=sr(t);return s?s.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}):"Invalid Time"}function SR(t){return t?e.jsxs(Wt,{variant:"secondary",className:"gap-1 bg-amber-100 text-amber-800 border-amber-200",children:[e.jsx(hN,{className:"h-3 w-3"}),t]}):null}function CR(t){switch(t){case"ai-routed":return e.jsxs(Wt,{variant:"secondary",className:"gap-1 bg-purple-100 text-purple-700 border-purple-200",children:[e.jsx(Fl,{className:"h-3 w-3"}),"AI Routed"]});case"direct":default:return e.jsxs(Wt,{variant:"secondary",className:"gap-1 bg-blue-100 text-blue-700 border-blue-200",children:[e.jsx(Ss,{className:"h-3 w-3"}),"Direct"]})}}function TR(t){switch(t){case"confirmed":return e.jsx(Wt,{className:"bg-green-600",children:"Confirmed"});case"cancelled":return e.jsx(Wt,{variant:"destructive",children:"Cancelled"});case"completed":return e.jsx(Wt,{variant:"secondary",className:"bg-gray-100 text-gray-600 border-gray-200",children:"Completed"});default:return e.jsx(Wt,{variant:"outline",children:t})}}function AR({authToken:t,onBack:s,onLogoClick:n}){const[r,a]=l.useState([]),[o,i]=l.useState({}),[d,m]=l.useState(!0),[p,c]=l.useState(!1),[u,x]=l.useState(!1),[h,b]=l.useState(null),[f,g]=l.useState("upcoming"),y=l.useRef(null),[j,v]=l.useState([]),[T,k]=l.useState([]),[w,I]=l.useState(!1),[A,E]=l.useState(null),[C,N]=l.useState(null),S=l.useCallback(async R=>{if(f!=="settings"){R?(m(!0),b(null),y.current=null):c(!0);try{const z=ja.fromDate(new Date),D=f==="upcoming"?[Ve("startTime",">=",z),Nt("startTime","asc")]:[Ve("startTime","<",z),Nt("startTime","desc")];!R&&y.current&&D.push(K0(y.current)),D.push(Tt(Nx));const L=await Ze(Ge(Re(ge,"bookings"),...D)),$=L.docs.map(q=>({id:q.id,...q.data()}));y.current=L.docs[L.docs.length-1]??y.current,x(L.size===Nx),a(q=>R?$:[...q,...$])}catch(z){console.error("Error fetching bookings:",z),R&&b("Failed to load bookings. Please try again.")}finally{m(!1),c(!1)}}},[f]);l.useEffect(()=>{S(!0)},[S]),l.useEffect(()=>{const R=Array.from(new Set(r.map(D=>D.contactId).filter(D=>!!D&&!(D in o))));if(R.length===0)return;let z=!1;return(async()=>{const D=await Promise.all(R.map(async L=>{try{const $=await ps(ut(ge,"contacts",L));if(!$.exists())return[L,{icpFitScore:null,jobTitle:null,seniority:null}];const q=$.data();return[L,{icpFitScore:typeof q.icpFitScore=="number"?q.icpFitScore:null,jobTitle:q.jobTitle??null,seniority:q.seniority??null}]}catch{return[L,{icpFitScore:null,jobTitle:null,seniority:null}]}}));z||i(L=>{const $={...L};for(const[q,P]of D)$[q]=P;return $})})(),()=>{z=!0}},[r,o]),l.useEffect(()=>{if(f!=="settings")return;I(!0);const R=Ze(Ge(Re(ge,"bookingLinks"),Ve("isRoutingLink","==",!1))).then(D=>{const L=D.docs.map($=>({slug:$.id,...$.data()}));v(L)}),z=Ze(Ge(Re(ge,"outreachSequences"),Ve("status","in",["active","draft"]))).then(D=>{const L=D.docs.map($=>({id:$.id,name:$.data().name||$.id,status:$.data().status||"draft"}));k(L.sort(($,q)=>$.name.localeCompare(q.name)))});Promise.all([R,z]).catch(D=>console.error("Error loading settings:",D)).finally(()=>I(!1))},[f]);const O=async(R,z)=>{E(R);try{await er(ut(ge,"bookingLinks",R),z),v(D=>D.map(L=>L.slug===R?{...L,...z}:L)),N(R),setTimeout(()=>N(null),2e3)}catch(D){console.error("Error saving settings:",D)}finally{E(null)}};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:n}),e.jsxs("div",{className:"mx-auto max-w-2xl px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("button",{onClick:s,className:"mb-4 flex items-center gap-2 text-muted-foreground transition-colors hover:text-foreground",children:[e.jsx(dt,{className:"h-5 w-5"}),e.jsx("span",{children:"Back to Admin"})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Bookings"}),e.jsx("p",{className:"text-muted-foreground",children:"View and manage scheduled meetings"})]}),e.jsxs("div",{className:"mb-4 flex gap-2",children:[e.jsx(ke,{variant:f==="upcoming"?"default":"outline",size:"sm",onClick:()=>g("upcoming"),children:"Upcoming"}),e.jsx(ke,{variant:f==="past"?"default":"outline",size:"sm",onClick:()=>g("past"),children:"Past"}),e.jsxs(ke,{variant:f==="settings"?"default":"outline",size:"sm",onClick:()=>g("settings"),children:[e.jsx(vu,{className:"h-4 w-4 mr-1"}),"Settings"]})]}),f==="settings"&&e.jsx(DR,{bookingLinks:j,sequences:T,isLoading:w,savingSlug:A,savedSlug:C,onSave:O}),f!=="settings"&&h&&e.jsx("div",{className:"mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700",children:h}),f!=="settings"&&d&&e.jsx("div",{className:"space-y-4",children:[1,2,3].map(R=>e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(tn,{className:"h-5 w-48"}),e.jsx(tn,{className:"h-4 w-32"})]})}),e.jsx(vt,{children:e.jsx(tn,{className:"h-4 w-64"})})]},R))}),f!=="settings"&&!d&&r.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-gray-100",children:e.jsx(Ss,{className:"h-7 w-7 text-gray-400"})}),e.jsxs("h3",{className:"text-lg font-medium text-gray-900",children:["No ",f," bookings"]}),e.jsx("p",{className:"mt-1 text-sm text-gray-500",children:f==="upcoming"?"No upcoming meetings scheduled.":"No past meetings found."})]}),f!=="settings"&&!d&&r.length>0&&e.jsxs("div",{className:"space-y-4",children:[r.map(R=>e.jsx(IR,{booking:R,isUpcoming:f==="upcoming",authToken:t,contactSummary:R.c
385ontactId?o[R.contactId]:void 0},R.id)),u&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(ke,{variant:"outline",size:"sm",onClick:()=>S(!1),disabled:p,children:p?"Loadingâ¦":"Load more"})})]})]})]})}const Sx="https://us-central1-bucky-app-355a3.cloudfunctions.net";function ER({score:t}){if(t==null)return null;let s="bg-red-100",n="text-red-700",r="border-red-200";return t>=80?(s="bg-green-100",n="text-green-700",r="border-green-200"):t>=50&&(s="bg-yellow-100",n="text-yellow-700",r="border-yellow-200"),e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-semibold ${s} ${n} ${r}`,title:"ICP Fit Score (0-100, higher is better)",children:["ICP ",t]})}function IR({booking:t,isUpcoming:s,authToken:n,contactSummary:r}){var c;const[a,o]=l.useState(null),[i,d]=l.useState(!1),m=async u=>{if(n){d(!0);try{if(!(await fetch(`${Sx}/deleteBooking`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({bookingId:t.id,action:u})})).ok)throw new Error("Failed");o(null)}catch(x){console.error("Error:",x),alert("Failed to process. Please try again.")}finally{d(!1)}}},p=async()=>{if(n){d(!0);try{if(!(await fetch(`${Sx}/deleteBooking`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({bookingId:t.id,action:"cancel"})})).ok)throw new Error("Failed to cancel");o(null);const x=t.teamMemberSlug||t.bookingLinkSlug||"jody",h=new URLSearchParams;t.bookerName&&h.set("name",t.bookerName),t.bookerEmail&&h.set("email",t.bookerEmail),t.bookerCompanyUrl&&h.set("company",t.bookerCompanyUrl),t.bookerTopic&&h.set("topic",t.bookerTopic),window.open(`/book/${x}?${h.toString()}`,"_blank")}catch(u){console.error("Error:",u),alert("Failed to cancel the existing booking. Please try again.")}finally{d(!1)}}};return e.jsxs(jt,{className:"overflow-hidden",children:[e.jsx(fs,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(vs,{className:"text-base font-semibold",children:t.bookerName}),e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Tn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:t.bookerEmail})]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[TR(t.status),CR(t.source),SR(t.bookingSource),e.jsx(ER,{score:(r==null?void 0:r.icpFitScore)??((c=t.preMeetingBrief)==null?void 0:c.icpFitScore)??null})]})]})}),e.jsxs(vt,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-gray-700",children:[e.jsx(Ss,{className:"h-4 w-4 text-gray-400"}),e.jsx("span",{children:kR(t.startTime)})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-gray-700",children:[e.jsx(ms,{className:"h-4 w-4 text-gray-400"}),e.jsxs("span",{children:[kx(t.startTime)," - ",kx(t.endTime)]}),e.jsx("span",{className:"text-gray-400",children:"·"}),e.jsxs("span",{className:"text-gray-500",children:[t.durationMinutes," min"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-gray-600",children:[e.jsx(mn,{className:"h-4 w-4 text-gray-400"}),e.jsx("span",{children:t.meetingTypeName}),t.teamMemberName&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-gray-300",children:"|"}),e.jsx(ei,{className:"h-4 w-4 text-gray-400"}),e.jsx("span",{children:t.teamMemberName})]})]}),t.bookerCompanyUrl&&e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-gray-600",children:[e.jsx(ag,{className:"h-4 w-4 text-gray-400"}),e.jsx("a",{href:t.bookerCompanyUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:t.bookerCompanyUrl.replace(/^https?:\/\//,"")})]}),t.bookerTopic&&e.jsx("p",{className:"rounded-lg bg-gray-50 px-3 py-2 text-sm text-gray-700",children:t.bookerTopic}),t.preMeetingBrief&&e.jsx(jR,{type:"single",collapsible:!0,children:e.jsxs(vR,{value:"brief",className:"rounded-lg border border-blue-200 bg-blue-50/50",children:[e.jsx(wR,{className:"group rounded-lg px-3 py-2.5 text-sm font-medium text-blue-700 hover:bg-blue-50 hover:no-underline data-[state=open]:bg-blue-50",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{children:"Pre-Meeting Brief"}),e.jsx("span",{className:"hidden rounded-full bg-blue-100 px-2 py-0.5 text-[10px] font-semibold text-blue-700 sm:inline",children:"AI"})]})}),e.jsxs(NR,{className:"space-y-3 px-3 pb-3 text-sm",children:[t.preMeetingBrief.contactSummary&&e.jsxs("div",{children:[e.jsx("h4",{className:"mb-1 font-medium text-gray-800",children:"Contact Summary"}),e.jsx("p",{className:"text-gray-600",children:t.preMeetingBrief.contactSummary})]}),t.preMeetingBrief.companyInfo&&e.jsxs("div",{children:[e.jsx("h4",{className:"mb-1 font-medium text-gray-800",children:"Company Info"}),e.jsx("p",{className:"text-gray-600",children:t.preMeetingBrief.companyInfo})]}),t.preMeetingBrief.suggestedTalkingPoints&&t.preMeetingBrief.suggestedTalkingPoints.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"mb-1 font-medium text-gray-800",children:"Talking Points"}),e.jsx("ul",{className:"list-inside list-disc space-y-1 text-gray-600",children:t.preMeetingBrief.suggestedTalkingPoints.map((u,x)=>e.jsx("li",{children:u},x))})]}),t.preMeetingBrief.previousInteractions&&e.jsxs("div",{children:[e.jsx("h4",{className:"mb-1 font-medium text-gray-800",children:"Previous Interactions"}),e.jsx("p",{className:"text-gray-600",children:t.preMeetingBrief.previousInteractions})]})]})]})}),e.jsx("div",{className:"border-t border-gray-100 pt-3 mt-3",children:a?e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm text-gray-500",children:a==="delete"?"Delete this booking permanently?":a==="reschedule"?"Cancel this booking and open a new one?":"Cancel this booking and notify attendees?"}),e.jsx(ke,{size:"sm",variant:"destructive",onClick:()=>a==="reschedule"?p():m(a),disabled:i,children:i?"Processing...":a==="reschedule"?"Yes, Reschedule":"C
385onfirm"}),e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>o(null),disabled:i,children:"No"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[s&&t.status==="confirmed"&&e.jsxs(ke,{size:"sm",variant:"outline",onClick:()=>o("reschedule"),className:"text-blue-600 border-blue-200 hover:bg-blue-50",children:[e.jsx(Ss,{className:"h-3.5 w-3.5 mr-1"}),"Reschedule"]}),s&&t.status==="confirmed"?e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>o("cancel"),className:"text-red-600 border-red-200 hover:bg-red-50",children:"Cancel"}):e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>o("delete"),className:"text-red-600 border-red-200 hover:bg-red-50",children:"Delete"})]})})]})]})}const ki=["monday","tuesday","wednesday","thursday","friday"],RR={monday:"Monday",tuesday:"Tuesday",wednesday:"Wednesday",thursday:"Thursday",friday:"Friday"};function DR({bookingLinks:t,sequences:s,isLoading:n,savingSlug:r,savedSlug:a,onSave:o}){return n?e.jsx("div",{className:"space-y-4",children:[1,2].map(i=>e.jsx(jt,{children:e.jsx(vt,{className:"p-6",children:e.jsx(tn,{className:"h-32 w-full"})})},i))}):e.jsx("div",{className:"space-y-6",children:t.map(i=>e.jsx(MR,{link:i,sequences:s,isSaving:r===i.slug,isSaved:a===i.slug,onSave:d=>o(i.slug,d)},i.slug))})}function MR({link:t,sequences:s,isSaving:n,isSaved:r,onSave:a}){var I,A,E,C,N;const[o,i]=l.useState(t.bufferMinutes),[d,m]=l.useState(t.preferences.idealBookingWindow.minDaysAhead),[p,c]=l.useState(t.preferences.idealBookingWindow.maxDaysAhead),[u,x]=l.useState(((I=t.preferences.preferredTimeRanges[0])==null?void 0:I.start)||"08:00"),[h,b]=l.useState(((A=t.preferences.preferredTimeRanges[0])==null?void 0:A.end)||"12:00"),[f]=l.useState(((E=t.preferences.preferredTimeRanges[0])==null?void 0:E.label)||"Preferred"),[g,y]=l.useState(Object.fromEntries(ki.map(S=>[S,t.preferences.deprioritizedDays.some(O=>O.day===S)]))),[j,v]=l.useState(t.postBookingSequenceId||""),T=o!==t.bufferMinutes||d!==t.preferences.idealBookingWindow.minDaysAhead||p!==t.preferences.idealBookingWindow.maxDaysAhead||u!==(((C=t.preferences.preferredTimeRanges[0])==null?void 0:C.start)||"08:00")||h!==(((N=t.preferences.preferredTimeRanges[0])==null?void 0:N.end)||"12:00")||j!==(t.postBookingSequenceId||"")||JSON.stringify(g)!==JSON.stringify(Object.fromEntries(ki.map(S=>[S,t.preferences.deprioritizedDays.some(O=>O.day===S)]))),k=()=>{const S=ki.filter(O=>g[O]).map(O=>({day:O,reason:"Deprioritized in booking settings"}));a({bufferMinutes:o,preferences:{...t.preferences,preferredTimeRanges:[{start:u,end:h,label:f}],deprioritizedDays:S,idealBookingWindow:{minDaysAhead:d,maxDaysAhead:p}},postBookingSequenceId:j||null})},w={border:"1px solid #d1d5db",borderRadius:"6px",padding:"6px 10px",fontSize:"14px",width:"80px",outline:"none"};return e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsxs(vs,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ei,{className:"h-5 w-5 text-muted-foreground"}),t.teamMemberName]}),e.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:["/book/",t.slug]})]})}),e.jsxs(vt,{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Meeting Buffer"}),e.jsx("p",{className:"text-xs text-gray-400 mb-2",children:"Minutes of padding on each side of a booking to prevent back-to-back meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",min:0,max:60,step:5,value:o,onChange:S=>i(parseInt(S.target.value)||0),style:w}),e.jsx("span",{className:"text-sm text-gray-500",children:"minutes"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Booking Window"}),e.jsx("p",{className:"text-xs text-gray-400 mb-2",children:"How far ahead people can book"}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm text-gray-500",children:"From"}),e.jsx("input",{type:"number",min:0,max:p,value:d,onChange:S=>m(parseInt(S.target.value)||0),style:w}),e.jsx("span",{className:"text-sm text-gray-500",children:"to"}),e.jsx("input",{type:"number",min:d,max:60,value:p,onChange:S=>c(parseInt(S.target.value)||14),style:w}),e.jsx("span",{className:"text-sm text-gray-500",children:"days ahead"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Preferred Time Range"}),e.jsx("p",{className:"text-xs text-gray-400 mb-2",children:"Time slots in this range are highlighted as recommended"}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("input",{type:"time",value:u,onChange:S=>x(S.target.value),style:{...w,width:"120px"}}),e.jsx("span",{className:"text-sm text-gray-500",children:"to"}),e.jsx("input",{type:"time",value:h,onChange:S=>b(S.target.value),style:{...w,width:"120px"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Deprioritized Days"}),e.jsx("p",{className:"text-xs text-gray-400 mb-2",children:"Slots on these days will be dimmed (still bookable but not recommended)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:ki.map(S=>e.jsx("button",{type:"button",onClick:()=>y(O=>({...O,[S]:!O[S]})),className:"rounded-md border px-3 py-1.5 text-sm transition-colors",style:{backgroundColor:g[S]?"#fee2e2":"white",borderColor:g[S]?"#fca5a5":"#d1d5db",color:g[S]?"#991b1b":"#56585A"},children:RR[S]},S))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Post-Booking Sequence"}),e.jsx("p",{className:"text-xs text-gray-400 mb-2",children:"Auto-enroll the booker into a sequence after a confirmed booking. Skipped if the contact is already in another active sequence."}),e.jsxs("select",{value:j,onChange:S=>v(S.target.value),style:{...w,width:"100%",maxWidth:"360px",fontFamily:"inherit"},children:[e.jsx("option",{value:"",children:"None â no sequence"}),s.map(S=>e.jsxs("option",{value:S.id,children:[S.name,S.status!=="active"?` (${S.status})`:""]},S.id))]}),j&&e.jsxs("div",{className:"mt-3 rounded-md border border-blue-100 bg-blue-50 p-3 text-xs text-gray-700",style:{fontFamily:"'Montserrat', sans-serif"},children:[e.jsx("p",{className:"mb-1 font-medium text-gray-800",children:"Available variables in your sequence templates:"}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-3 gap-y-0.5 font-mono text-[11px] text-gray-600",children:[e.jsx("span",{children:"{{bookerName}}"}),e.jsx("span",{children:"{{bookerFirstName}}"}),e.jsx("span",{children:"{{bookingDate}}"}),e.jsx("span",{children:"{{bookingTime}}"}),e.jsx("span",{children:"{{bookingDateTime}}"}),e.jsx("span",{children:"{{bookingTopic}}"}),e.jsx("span",{children:"{{bookingMeetLink}}"}),e.jsx("span",{children:"{{bookingCalendarLink}}"}),e.jsx("span",{children:"{{bookingMeetingTypeName}}"}),e.jsx("span",{children:"{{teamMemberName}}"})]}),e.jsxs("p",{className:"mt-2 text-gray-500",children:["Standard contact merge fields (","{{firstName}}",", ","{{companyName}}",", etc.) also work."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-2",children:[e.jsxs(ke,{size:"sm",onClick:k,disabled:!T||n,children:[e.jsx(ml,{className:"h-4 w-4 mr-1"}),n?"Saving...":"Save Settings"]}),r&&e.jsx("span",{className:"text-sm text-green-600",children:"Saved!"})]})]})]})}function PR(t,s={}){const{autoLoad:n=!0}=s,[r,a]=l.useState([]),[o,i]=l.useState(0),[d,m]=l.useState(!0),[p,c]=l.useState(!1),[u,x]=l.useState(!1),[h,b]=l.useState(!1),[f,g]=l.useState(null),[y,j]=l.useState(!navigator.onLine),[v,T]=l.useState(0),[k,w]=l.useState(!1),[I,A]=l.useState(null),[E,C]=l.useState(0),N=l.useRef(!0);l.useEffect(()=>{bn.setAuthToken(t)},[t]),l.useEffect(()=>{const G=()=>j(!1),B=()=>j(!0);return window.addEventListener("online",G),window.addEventListener("offline",B),()=>{window.removeEventListener("online",G),window.removeEventListener("offline",B)}},[]),l.useEffect(()=>{const G=async()=>{try{const Y=await wm.getPendingCount();N.current&&T(Y)}catch(Y){console.error("Failed to update pending count:",Y)}};G();const B=wm.addListener(G);return()=>{B()}},[]),l.useEffect(()=>()=>{N.current=!1},[]);const S=l.useCallback(async(G=!0)=>
385{if(!t){a([]),m(!1);return}try{m(!0),g(null);const B=await bn.getAdminTicketsForReview({useCache:G});N.current&&(a((B==null?void 0:B.tickets)||[]),w((B==null?void 0:B.hasMore)||!1),A((B==null?void 0:B.nextCursor)||null),C((B==null?void 0:B.pendingJobReports)||0),i(0))}catch(B){console.error("[useAdminQAReview] Error fetching tickets:",B),N.current&&(g(B.message||"Failed to fetch tickets for review"),a([]))}finally{N.current&&m(!1)}},[t]);l.useEffect(()=>{n&&S()},[S,n]);const O=r[o]||null,R=l.useCallback(()=>{i(G=>Math.min(G+1,r.length-1))},[r.length]),z=l.useCallback(()=>{i(G=>Math.max(G-1,0))},[]),D=l.useCallback(G=>{G>=0&&G<r.length&&i(G)},[r.length]),L=l.useCallback(async(G,B)=>{try{x(!0),g(null),await bn.approveTicket(G,B),N.current&&(a(Y=>Y.filter(J=>J.id!==G)),i(Y=>Math.max(0,Math.min(Y,r.length-2))))}catch(Y){throw console.error("[useAdminQAReview] Error approving ticket:",Y),N.current&&g(Y.message||"Failed to approve ticket"),Y}finally{N.current&&x(!1)}},[o,r.length]),$=l.useCallback(async(G,B,Y="minor")=>{try{x(!0),g(null),await bn.requestChanges(G,B,Y),N.current&&(a(J=>J.filter(H=>H.id!==G)),i(J=>Math.max(0,Math.min(J,r.length-2))))}catch(J){throw console.error("[useAdminQAReview] Error requesting changes:",J),N.current&&g(J.message||"Failed to request changes"),J}finally{N.current&&x(!1)}},[o,r.length]),q=l.useCallback(async G=>{try{x(!0),g(null),await bn.submitFeedback(G)}catch(B){throw console.error("[useAdminQAReview] Error submitting feedback:",B),N.current&&g(B.message||"Failed to submit feedback"),B}finally{N.current&&x(!1)}},[]),P=l.useCallback(async(G,B,Y)=>{const J=await bn.addQaReviewNote(G,B,Y);N.current&&a(H=>H.map(Z=>Z.id===G?{...Z,qaReviewNotes:[...Z.qaReviewNotes||[],J]}:Z))},[]),U=l.useCallback(async(G,B,Y)=>{const J=await bn.updateQaReviewNote(G,B,Y);N.current&&a(H=>H.map(Z=>Z.id===G?{...Z,qaReviewNotes:(Z.qaReviewNotes||[]).map(Q=>Q.id===B?J:Q)}:Z))},[]),V=l.useCallback(async(G,B)=>{await bn.deleteQaReviewNote(G,B),N.current&&a(Y=>Y.map(J=>J.id===G?{...J,qaReviewNotes:(J.qaReviewNotes||[]).filter(H=>H.id!==B)}:J))},[]),M=l.useCallback(async()=>{try{b(!0),g(null),await S(!1)}finally{N.current&&b(!1)}},[S]),F=l.useCallback((G,B)=>{N.current&&a(Y=>Y.map(J=>J.id===G?{...J,...B}:J))},[]),W=l.useCallback(async(G,B)=>{try{await bn.saveAlignmentOffset(G,B),F(G,{savedAlignmentOffset:B})}catch(Y){throw console.error("[useAdminQAReview] Error saving alignment offset:",Y),Y}},[F]),_=l.useCallback(async G=>{try{await bn.clearAlignmentOffset(G),N.current&&a(B=>B.map(Y=>Y.id===G?{...Y,savedAlignmentOffset:void 0}:Y))}catch(B){throw console.error("[useAdminQAReview] Error clearing alignment offset:",B),B}},[]);return{tickets:r,currentTicket:O,currentIndex:o,totalTickets:r.length,loading:d,loadingImages:p,submitting:u,refreshing:h,error:f,isOffline:y,pendingActions:v,pendingJobReports:E,approveTicket:L,requestChanges:$,submitFeedback:q,addNote:P,updateNote:U,deleteNote:V,nextTicket:R,previousTicket:z,goToTicket:D,refresh:M,saveAlignmentOffset:W,clearAlignmentOffset:_}}const Es={root:{display:"flex",flexDirection:"column",height:"100vh",backgroundColor:"#f9fafb"},header:{display:"flex",alignItems:"center",justifyContent:"space-between",backgroundColor:"#fff",borderBottom:"1px solid #e5e7eb",padding:"12px 16px",flexShrink:0},body:{display:"flex",flex:1,minHeight:0},list:{width:"288px",flexShrink:0,borderRight:"1px solid #e5e7eb",backgroundColor:"#fff",overflowY:"auto"},detail:{flex:1,minWidth:0,overflowY:"auto"},detailInner:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px"},card:{backgroundColor:"#fff",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"16px"},actionBar:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:"12px",backgroundColor:"#fff",borderTop:"1px solid #e5e7eb",padding:"12px 16px",flexShrink:0},clamp2:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",overflowWrap:"anywhere"}};
385function eo(t){return t.reviewType?t.reviewType==="visual":!!(t.beforeImageUrl&&(t.afterImageUrl||t.needsPreviewThemeId))}function LR(t){var d,m;if(!t.pageUrl)return;const s=t.pageUrl.includes("?")?"&":"?",n=t.previewThemeId?`${t.pageUrl}${s}preview_theme_id=${t.previewThemeId}&pb=0`:`${t.pageUrl}${s}pb=0`,r=((d=t.viewport)==null?void 0:d.width)||1280,a=((m=t.viewport)==null?void 0:m.height)||800,o=(window.screen.width-r)/2,i=(window.screen.height-a)/2;window.open(n,"PagePreview",`width=${r},height=${a},left=${o},top=${i},toolbar=no,menubar=no,location=yes,status=yes,scrollbars=yes,resizable=yes`)}function zR(t){const s=new Date(t).getTime();if(Number.isNaN(s))return"";const n=Date.now()-s,r=Math.round(n/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const a=Math.round(r/60);if(a<24)return`${a}h ago`;const o=Math.round(a/24);return o<7?`${o}d ago`:new Date(t).toLocaleDateString()}const OR={h2:({children:t})=>e.jsx("h2",{style:{fontSize:"15px",fontWeight:700,color:"#111827",marginTop:"16px",marginBottom:"8px",borderBottom:"1px solid #e5e7eb",paddingBottom:"4px"},children:t}),blockquote:({children:t})=>e.jsx("blockquote",{style:{borderLeft:"4px solid #fbbf24",backgroundColor:"#fffbeb",padding:"8px 12px",margin:"8px 0",color:"#374151",borderRadius:"0 6px 6px 0"},children:t}),a:({href:t,children:s})=>e.jsx("a",{href:t,style:{color:"#2563eb"},target:"_blank",rel:"noopener noreferrer",children:s}),strong:({children:t})=>e.jsx("strong",{style:{fontWeight:600,color:"#111827"},children:t}),hr:()=>e.jsx("hr",{style:{margin:"16px 0",borderColor:"#d1d5db"}}),p:({children:t})=>e.jsx("p",{style:{margin:"6px 0",color:"#374151",fontSize:"14px"},children:t}),li:({children:t})=>e.jsx("li",{style:{color:"#374151",fontSize:"14px"},children:t}),code:({children:t})=>e.jsx("code",{style:{backgroundColor:"#f3f4f6",padding:"1px 4px",borderRadius:"4px",fontSize:"12px"},children:t})};function Cx({authToken:t,userEmail:s,onBack:n}){const[r,a]=l.useState(!1),[o,i]=l.useState(!1),[d,m]=l.useState(null),[p,c]=l.useState(""),[u,x]=l.useState(!1),[h,b]=l.useState(null),[f,g]=l.useState(""),[y,j]=l.useState(!1),[v,T]=l.useState(null),{tickets:k,currentTicket:w,currentIndex:I,totalTickets:A,loading:E,submitting:C,refreshing:N,isOffline:S,pendingJobReports:O=0,approveTicket:R,requestChanges:z,addNote:D,updateNote:L,deleteNote:$,goToTicket:q,refresh:P,saveAlignmentOffset:U,clearAlignmentOffset:V}=PR(t),M=l.useCallback(()=>{w&&(m(null),i(!0))},[w]),F=l.useCallback(async()=>{if(w){i(!1);try{m(null),await R(w.id,{reviewerEmail:s||void 0,reviewerName:(s==null?void 0:s.split("@")[0])||"Admin"})}catch(K){m(K.message||"Failed to approve ticket")}}},[w,R,s]),W=l.useCallback(async K=>{if(w)try{m(null),await z(w.id,K.feedback,K.severity),a(!1)}catch(X){throw m(X.message||"Failed to submit feedback"),X}},[w,z]),_=l.useCallback(async()=>{if(!w)return;const K=p.trim();if(K){x(!0);try{m(null),await D(w.id,K,{email:s,name:s==null?void 0:s.split("@")[0]}),c("")}catch(X){m(X.message||"Failed to add note")}finally{x(!1)}}},[w,p,D,s]),G=l.useCallback((K,X)=>{b(K),g(X)},[]),B=l.useCallback(async()=>{if(!(!w||!h||!f.trim())){j(!0);try{m(null),await L(w.id,h,f.trim()),b(null),g("")}catch(K){m(K.message||"Failed to update note")}finally{j(!1)}}},[w,h,f,L]),Y=l.useCallback(async K=>{if(w)try{m(null),await $(w.id,K)}catch(X){m(X.message||"Failed to delete note")}},[w,$]),J=l.useCallback(K=>{m(`Image error: ${K}`)},[]);if(E)return e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",padding:"16px"},children:[e.jsx("div",{className:"animate-spin",style:{width:"48px",height:"48px",border:"3px solid #e5e7eb",borderBottomColor:"#2563eb",borderRadius:"50%",marginBottom:"16px"}}),e.jsx("p",{style:{color:"#4b5563"},children:"Loading all pending QA tickets..."})]});if(!E&&k.length===0)return e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",padding:"16px"},children:[e.jsx("div",{style:{fontSize:"60px",marginBottom:"16px"},children:"ð"}),e.jsx("h2",{style:{fontSize:"24px",fontWeight:700,color:"#1f2937",marginBottom:"8px"},children:"All Clear!"}),e.jsx("p",{style:{color:"#4b5563",textAlign:"center",marginBottom:"24px"},children:"There are no tickets waiting for QA review."}),O>0&&e.jsxs("p",{style:{color:"#6b7280",fontSize:"14px",textAlign:"center",marginTop:"-12px",marginBottom:"24px"},children:[O," ",O===1?"ticket is":"tickets are"," waiting on job-report approval and will appear here once approved."]}),e.jsx("button",{onClick:P,disabled:N||S,style:{padding:"12px 24px",borderRadius:"8px",border:"none",backgroundColor:"#2563eb",color:"#fff",cursor:"pointer"},children:N?"Checking...":"Refresh"}),n&&e.jsx("button",{onClick:n,style:{marginTop:"16px",color:"#2563eb",background:"none",border:"none",cursor:"pointer"},children:"Go Back"})]});const H=(w==null?void 0:w.qaReviewNotes)||[],Z=w!=null&&w.videoReviewUrl?uf(w.videoReviewUrl):null,Q=K=>({fontSize:"10px",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",padding:"2px 6px",borderRadius:"4px",flexShrink:0,whiteSpace:"nowrap",backgroundColor:K?"#dbeafe":"#fef3c7",color:K?"#1d4ed8":"#b45309"});return e.jsx(pv,{ticketId:w==null?void 0:w.id,children:e.jsxs("div",{style:Es.root,children:[e.jsxs("header",{style:Es.header,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[n&&e.jsx("button",{onClick:n,style:{padding:"8px",background:"none",border:"none",cursor:"pointer",borderRadius:"999px"},children:e.jsx("svg",{width:"22",height:"22",fill:"none",viewBox:"0 0 24 24",stroke:"#4b5563",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("h1",{style:{fontSize:"18px",fontWeight:600,color:"#111827",margin:0},children:"Admin QA Review"}),e.jsxs("span",{style:{fontSize:"13px",color:"#6b7280",backgroundColor:"#f3f4f6",padding:"2px 8px",borderRadius:"999px"},children:[A," in review"]}),O>0&&e.jsxs("span",{title:"In Review tickets held back until their job report is approved in the Job Reports screen",style:{fontSize:"13px",color:"#92400e",backgroundColor:"#fef3c7",padding:"2px 8px",borderRadius:"999px"},children:[O," awaiting job-report approval"]})]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[S&&e.jsx("span",{style:{padding:"4px 8px",backgroundColor:"#fef9c3",color:"#854d0e",borderRadius:"999px",fontSize:"13px"},children:"Offline"}),e.jsxs("button",{onClick:P,disabled:N||S,style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 12px",borderRadius:"8px",border:"none",fontSize:"13px",fontWeight:500,backgroundColor:"#2563eb",color:"#fff",cursor:N||S?"not-allowed":"pointer",opacity:N||S?.6:1},children:[e.jsx("svg",{className:N?"animate-spin":"",width:"16",height:"16",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),N?"Loading...":"Refresh"]})]})]}),e.jsx(hs,{children:d&&e.jsx(st.div,{initial:{opacity:0,height:0}
385,animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},style:{backgroundColor:"#fef2f2",borderBottom:"1px solid #fecaca",padding:"12px 16px",flexShrink:0},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsx("span",{style:{fontSize:"13px",color:"#b91c1c"},children:d}),e.jsx("button",{onClick:()=>m(null),style:{color:"#b91c1c",background:"none",border:"none",cursor:"pointer"},children:"â"})]})})}),e.jsxs("div",{style:Es.body,children:[e.jsx("aside",{style:Es.list,children:k.map((K,X)=>{var Ne;const se=eo(K),pe=((Ne=K.qaReviewNotes)==null?void 0:Ne.length)||0,me=X===I;return e.jsxs("button",{onClick:()=>q(X),style:{display:"block",width:"100%",textAlign:"left",cursor:"pointer",padding:"12px 16px",border:"none",borderBottom:"1px solid #f3f4f6",borderLeft:me?"4px solid #3b82f6":"4px solid transparent",backgroundColor:me?"#eff6ff":"transparent"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginBottom:"4px"},children:[e.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:"#6b7280"},children:K.notionId}),e.jsx("span",{style:Q(se),children:se?"Visual":"Context"})]}),e.jsx("p",{style:{fontSize:"14px",fontWeight:500,color:"#111827",margin:0,...Es.clamp2},children:K.title}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginTop:"4px"},children:[e.jsx("span",{style:{fontSize:"12px",color:"#6b7280",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:K.clientName}),pe>0&&e.jsxs("span",{style:{fontSize:"11px",color:"#9ca3af",display:"flex",alignItems:"center",gap:"2px",flexShrink:0},children:[e.jsx("svg",{width:"12",height:"12",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})}),pe]})]})]},K.id)})}),e.jsx("main",{style:Es.detail,children:w?e.jsxs("div",{style:Es.detailInner,children:[e.jsxs("div",{style:Es.card,children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[e.jsxs("div",{children:[e.jsx("h2",{style:{fontSize:"18px",fontWeight:600,color:"#111827",margin:0},children:w.title}),e.jsxs("p",{style:{fontSize:"13px",color:"#6b7280",margin:"2px 0 0"},children:[w.notionId," ","â¢"," ",w.clientName]})]}),e.jsx("span",{style:{...Q(eo(w)),fontSize:"11px",padding:"4px 8px"},children:eo(w)?"Visual QA":"Context QA"})]}),w.qaRequirements&&e.jsxs("div",{style:{marginTop:"12px",borderRadius:"8px",border:"1px solid #a7f3d0",backgroundColor:"#ecfdf5",padding:"12px"},children:[e.jsx("p",{style:{fontSize:"11px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.04em",color:"#047857",margin:"0 0 8px"},children:"ð¯ Client expectations (from intake)"}),[{label:"Expectations",value:w.qaRequirements.expectations},{label:"Expecting to see at review",value:w.qaRequirements.expectedDeliverable},{label:"Keep an eye out for",value:w.qaRequirements.watchOut}].map(K=>e.jsxs("div",{style:{marginBottom:"8px"},children:[e.jsx("p",{style:{fontSize:"11px",fontWeight:500,color:"#065f46",margin:0},children:K.label}),e.jsx("p",{style:{fontSize:"14px",color:"#1f2937",margin:"1px 0 0",whiteSpace:"pre-wrap"},children:K.value||"â"})]},K.label)),w.qaRequirements.submittedBy&&e.jsxs("p",{style:{fontSize:"11px",color:"#047857",marginTop:"4px"},children:["Submitted by ",w.qaRequirements.submittedBy]})]})]}),w.description&&e.jsxs("div",{style:Es.card,children:[e.jsx("p",{style:{fontSize:"11px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.04em",color:"#6b7280",margin:"0 0 8px"},children:"Ticket details"}),e.jsx("div",{style:{backgroundColor:"#f9fafb",borderRadius:"8px",border:"1px solid #e5e7eb",padding:"12px",maxHeight:"320px",overflowY:"auto"},children:e.jsx(Ta,{components:OR,children:w.description})})]}),eo(w)&&w.videoReviewUrl&&e.jsxs("div",{style:{...Es.card,display:"flex",flexDirection:"column",gap:"12px"},children:[e.jsx("p",{style:{fontSize:"11px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.04em",color:"#6b7280",margin:0},children:"Walkthrough video"}),Z?e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:"56.25%"},children:e.jsx("iframe",{src:Z,title:"Walkthrough video",style:{position:"absolute",inset:0,width:"100%",height:"100%",borderRadius:"8px",border:"1px solid #e5e7eb"},allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}):ll(w.videoReviewUrl)?e.jsx(Co,{src:w.videoReviewUrl,videoStyle:{border:"1px solid #e5e7eb"}}):e.jsx("a",{href:w.videoReviewUrl,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",fontSize:"14px"},children:"â¶ Watch walkthrough video"})]}),eo(w)?e.jsx("div",{style:{...Es.card,padding:0,overflow:"hidden"},children:e.jsx(Pl,{beforeImageUrl:w.beforeImageUrl,afterImageUrl:w.afterImageUrl,ticketId:w.id,savedAlignmentOffset:w.savedAlignmentOffset,onSaveAlignmentOffset:U,onClearAlignmentOffset:V,onError:J})}):e.jsxs("div",{style:{...Es.card,display:"flex",flexDirection:"column",gap:"12px"},children:[e.jsx("p",{style:{fontSize:"11px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.04em",color:"#6b7280",margin:0},children:"Review"}),Z?e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:"56.25%"},children:e.jsx("iframe",{src:Z,title:"Walkthrough video",style:{position:"absolute",inset:0,width:"100%",height:"100%",borderRadius:"8px",border:"1px solid #e5e7eb"},allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}):w.videoReviewUrl&&ll(w.videoReviewUrl)?e.jsx(Co,{src:w.videoReviewUrl,videoStyle:{border:"1px solid #e5e7eb"}}):w.videoReviewUrl?e.jsx("a",{href:w.videoReviewUrl,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",fontSize:"14px"},children:"â¶ Watch walkthrough video"}):null,w.pageUrl?e.jsxs("button",{onClick:()=>LR(w),style:{display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 16px",borderRadius:"8px",border:"none",backgroundColor:"#111827",color:"#fff",fontSize:"14px",fontWeight:500,cursor:"pointer",alignSelf:"flex-start"},children:[e.jsx("svg",{width:"16",height:"16",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),"Open live page"]}):null,!Z&&!w.videoReviewUrl&&!w.pageUrl&&e.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:0},children:"No screenshots or video for this ticket â review against the ticket details above."})]}),e.jsxs("div",{style:Es.card,children:[e.jsx("p",{style:{fontSize:"11px",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.04em",color:"#6b7280",margin:"0 0 2px"},children:"ð Internal notes (staff only)"}),e.jsx("p",{style:{fontSize:"11px",color:"#9ca3af",margin:"0 0 12px"},children:"Not sent to the customer. Ticket stays in review."}),H.length>0?e.jsx("ul",{style:{listStyle:"none",padding:0,margin:"0 0 12px",display:"flex",flexDirection:"column",gap:"8px"},children:H.map(K=>{const X=!!s&&(K.authorEmail||"").toLowerCase()===s.toLowerCase(),se=h===K.id;return e.jsx("li",{style:{backgroundColor:"#f9fafb",border:"1px solid #e5e7eb",borderRadius:"8px",padding:"12px"},children:se?e.jsxs(e.Fragment,{children:[e.jsx("textarea",{value:f,onChange:pe=>g(pe.target.value),rows:2,autoFocus:!0,style:{width:"100%",boxSizing:"border-box",fontSize:"14px",borderRadius:"6px",border:"1px solid #d1d5db",padding:"8px",resize:"vertical"}}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"8px",marginTop:"6px"},children:[e.jsx("button",{onClick:()=>{b(null),g("")},disabled:y,style:{padding:"6px 12px",borderRadius:"6px",border:"1px solid #d1d5db",backgroundColor:"#fff",color:"#374151",fontSize:"13px",cursor:"pointer"},children:"Cancel"}),e.jsx("button",{onClick:B,disabled:y||!f.trim(),style:{padding:"6px 12px",borderRadius:"6px",border:"none",backgroundColor:"#2563eb",color:"#fff",fontSize:"13px",cursor:y||!f.trim()?"not-allowed":"pointer",opacity:y||!f.trim()?.5:1},children:y?"Savingâ¦":"Save"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{fontSize:"14px",color:"#1f2937",margin:0,whiteSpace:"pre-wrap"},children:K.text}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",marginTop:"4px"},children:[e.jsxs("p",{style:{fontSize:"11px",color:"#9ca3af",margin:0},children:[K.authorName||K.authorEmail||"Staff"," · ",zR(K.createdAt),K.editedAt?" · edited":""]}),X&&e.jsxs("div",{style:{display:"flex",gap:"8px",flexShrink:0},children:[e.jsx("button",{onClick:()=>G(K.id,K.text),style:{fontSize:"12px",color:"#2563eb",background:"none",border:"none",cursor:"pointer",padding:0},children:"Edit"}),e.jsx("button",{onClick:()=>T(K.id),style:{fontSize:"12px",color:"#dc2626",background:"none",border:"none",cursor:"pointer",padding:0},children:"Delete"})]})]})]})},K.id)})}):e.jsx("p",{style:{fontSize:"14px",color:"#9ca3af",margin:"0 0 12px"},children:"No notes yet."}),e.jsx("textarea",{value:p,onChange:K=>c(K.target.value),placeholder:"Add an internal noteâ¦",rows:2,style:{width:"100%",boxSizing:"border-box",fontSize:"14px",borderRadius:"8px",border:"1px solid #d1d5db",padding:"8px",resize:"vertical"}}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"8px"},children:e.jsx("button",{onClick:_,disabled:u||!p.trim(),style:{padding:"8px 16px",borderRadius:"8px",border:"none",fontSize:"14px",fontWeight:500,backgroundColor:"#f3f4f6",color:"#374151",cursor:u||!p.trim()?"not-allowed":"pointer",opacity:u||!p.trim()?.5:1},children:u?"Addingâ¦":"Add note"})})]})]}):e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#6b7280"},children:"Select a ticket to review"})})]}),w&&!r&&e.jsxs("div",{style:Es.actionBar,children:[e.jsx("button",{onClick:()=>a(!0),disabled:C,style:{padding:"10px 20px",borderRadius:"8px",fontSize:"14px",fontWeight:600,border:"1px solid #fecaca",color:"#dc2626",backgroundColor:"#fff",cursor:C?"not-allowed":"pointer",opacity:C?.5:1},children:"Request changes"}),e.jsx("button",{onClick:M,disabled:C,style:{padding:"10px 20px",borderRadius:"8px",fontSize:"14px",fontWeight:600,border:"none",color:"#fff",backgroundColor:"#16a34a",cursor:C?"not-allowed":"pointer",opacity:C?.5:1},children:"Send for client review"})]}),e.jsx(hs,{children:r&&w&&e.jsx(st.div,{initial:{opacity:0}
385,animate:{opacity:1},exit:{opacity:0},style:{position:"fixed",inset:0,backgroundColor:"rgba(0,0,0,0.5)",zIndex:50,display:"flex",alignItems:"center",justifyContent:"center",padding:"16px"},onClick:K=>{K.target===K.currentTarget&&a(!1)},children:e.jsx(st.div,{initial:{y:40,opacity:0},animate:{y:0,opacity:1},exit:{y:40,opacity:0},transition:{type:"spring",damping:25,stiffness:300},style:{width:"100%",maxWidth:"512px",maxHeight:"90vh",overflow:"auto"},children:e.jsx(xv,{ticketId:w.id,onSubmit:W,onCancel:()=>a(!1),isSubmitting:C})})})}),o&&w&&e.jsx(ey,{ticketId:w.id,ticketTitle:w.title,ticketNumber:w.notionId,clientName:w.clientName,onSent:F,onClose:()=>i(!1)}),e.jsx(Kl,{open:v!==null,onOpenChange:K=>{K||T(null)},children:e.jsxs(Ql,{children:[e.jsxs(Tu,{children:[e.jsx(Eu,{children:"Delete this note?"}),e.jsx(Iu,{children:"This cannot be undone."})]}),e.jsxs(Au,{children:[e.jsx(Du,{children:"Cancel"}),e.jsx(Ru,{style:{backgroundColor:"#dc2626",color:"#fff"},onClick:()=>{v&&Y(v),T(null)},children:"Delete"})]})]})})]})})}function $R({onBack:t,onCaptureStore:s,onSEOReview:n}){return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsxs("div",{className:"bg-card border-b border-border px-4 py-3 flex items-center gap-3",children:[t&&e.jsx(st.button,{onClick:t,className:"p-2 -ml-2 hover:bg-accent rounded-lg transition-colors",whileTap:{scale:.95},children:e.jsx(dt,{className:"w-5 h-5 text-foreground"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"SEO Management"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Capture and review SEO content"})]})]}),e.jsx("div",{className:"max-w-md mx-auto px-4 pt-6",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs(st.button,{onClick:s,className:"w-full bg-card border border-border rounded-lg p-4 flex items-center gap-3 hover:bg-accent transition-colors",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},whileTap:{scale:.98},children:[e.jsx("div",{className:"flex-shrink-0 bg-primary/10 rounded-lg flex items-center justify-center",style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)"},children:e.jsx(Nu,{className:"text-primary",style:{width:"24px",height:"24px"}})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Capture New Store"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Import SEO data from a Shopify store"})]})]}),e.jsxs(st.button,{onClick:n,className:"w-full bg-card border border-border rounded-lg p-4 flex items-center gap-3 hover:bg-accent transition-colors",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},whileTap:{scale:.98},children:[e.jsx("div",{className:"flex-shrink-0 bg-primary/10 rounded-lg flex items-center justify-center",style:{width:"48px",height:"48px",borderRadius:"var(--radius-sm)"},children:e.jsx(Pt,{className:"text-primary",style:{width:"24px",height:"24px"}})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"SEO Review"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Review AI-generated SEO suggestions"})]})]})]})})]})}const Ar="https://us-central1-bucky-app-355a3.cloudfunctions.net",Tx="cache:seo_review:items",Jc="cache:seo_review:shops";class BR{constructor(){dm(this,"authToken",null)}setAuthToken(s){this.authToken=s}async captureSEOData(s){if(!this.authToken)throw new Error("No auth token available");const n=new AbortController,r=setTimeout(()=>n.abort(),12e4);try{const a=await fetch(`${Ar}/seoCaptureSEOData`,{method:"POST",headers:as(this.authToken),body:JSON.stringify(s),signal:n.signal});if(clearTimeout(r),!a.ok){const i=await a.json().catch(()=>({}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();return await this.invalidateCache(),o}catch(a){throw clearTimeout(r),a.name==="AbortError"?new Error("Request timed out. Capture may still be processing."):a}}async processWithAI(s){if(!this.authToken)throw new Error("No auth token available");const n=new AbortController,r=setTimeout(()=>n.abort(),3e5);try{const a=await fetch(`${Ar}/seoProcessWithAI`,{method:"POST",headers:as(this.authToken),body:JSON.stringify(s),signal:n.signal});if(clearTimeout(r),!a.ok){const i=await a.json().catch(()=>({}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();return await this.invalidateCache(),o}catch(a){throw clearTimeout(r),a.name==="AbortError"?new Error("Request timed out. AI processing may still be running."):a}}async getReviewItems(s){const{useCache:n=!0,...r}=s||{},a=`${Tx}:${JSON.stringify(r)}`;if(n&&!r.offset){const d=await qn.get(a);
385if(d)return console.log("[SEOReviewService] Returning cached items"),d}if(!this.authToken)throw new Error("No auth token available");const o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const d=await fetch(`${Ar}/seoGetReviewItems`,{method:"POST",headers:as(this.authToken),body:JSON.stringify(r),signal:o.signal});if(clearTimeout(i),!d.ok){const p=await d.json().catch(()=>({}));throw new Error(p.error||`HTTP ${d.status}`)}const m=await d.json();return r.offset||await qn.set(a,m,cl.FIVE_MINUTES),m}catch(d){throw clearTimeout(i),d.name==="AbortError"?new Error("Request timed out. Please try again."):d}}async updateReviewStatus(s){if(!this.authToken)throw new Error("No auth token available");const n=new AbortController,r=setTimeout(()=>n.abort(),3e4);try{const a=await fetch(`${Ar}/seoUpdateReviewStatus`,{method:"POST",headers:as(this.authToken),body:JSON.stringify(s),signal:n.signal});if(clearTimeout(r),!a.ok){const i=await a.json().catch(()=>({}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();return await this.invalidateCache(),o}catch(a){throw clearTimeout(r),a.name==="AbortError"?new Error("Request timed out. Please try again."):a}}async approveItem(s,n,r){return this.updateReviewStatus({itemId:s,action:"approve",reviewerEmail:n,editedProductTitle:r==null?void 0:r.productTitle,editedProductDescription:r==null?void 0:r.productDescription,editedPageTitle:r==null?void 0:r.pageTitle,editedMetaDescription:r==null?void 0:r.metaDescription,editedImageAltText:r==null?void 0:r.imageAltText})}async ignoreItem(s,n){return this.updateReviewStatus({itemId:s,action:"ignore",reviewerEmail:n})}async skipItem(s,n){return this.updateReviewStatus({itemId:s,action:"skip",reviewerEmail:n})}async pushToShopify(s){if(!this.authToken)throw new Error("No auth token available");const n=new AbortController,r=setTimeout(()=>n.abort(),12e4);try{const a=await fetch(`${Ar}/seoPushToShopify`,{method:"POST",headers:as(this.authToken),body:JSON.stringify(s),signal:n.signal});if(clearTimeout(r),!a.ok){const i=await a.json().catch(()=>({}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();return await this.invalidateCache(),o}catch(a){throw clearTimeout(r),a.name==="AbortError"?new Error("Request timed out. Push may still be processing."):a}}async getShops(s=!0){if(s)try{const a=await qn.get(Jc);if(a)return console.log("[SEOReviewService] Returning cached shops"),a}catch(a){console.error("Failed to retrieve cached shops:",a)}if(!this.authToken)throw new Error("No auth token available");const n=new AbortController,r=setTimeout(()=>n.abort(),3e4);try{const a=await fetch(`${Ar}/seoGetShops`,{method:"POST",headers:as(this.authToken),body:JSON.stringify({}),signal:n.signal});if(clearTimeout(r),!a.ok){const i=await a.json().catch(()=>({}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();try{await qn.set(Jc,o,cl.FIFTEEN_MINUTES)}catch(i){console.error("Failed to cache shops:",i)}return o}catch(a){throw clearTimeout(r),a.name==="AbortError"?new Error("Request timed out. Please try again."):a}}async triggerAutomation(s){if(!this.authToken)throw new Error("No auth token available");const n=new AbortController,r=setTimeout(()=>n.abort(),54e4);try{const a=await fetch(`${Ar}/seoTriggerAutomation`,{method:"POST",headers:as(this.authToken),body:JSON.stringify(s||{}),signal:n.signal});if(clearTimeout(r),!a.ok){const i=await a.json().catch(()=>({}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();return await this.invalidateCache(),o}catch(a){throw clearTimeout(r),a.name==="AbortError"?new Error("Request timed out. Automation may still be running."):a}}async invalidateCache(){try{await qn.remove(Tx),await qn.remove(Jc),console.log("[SEOReviewService] Cache invalidated")}catch(s){throw console.error("[SEOReviewService] Failed to invalidate cache",s),s}}}const _s=new BR,FR="https://us-central1-bucky-app-355a3.cloudfunctions.net/createTicket";function _R({authToken:t,onBack:s}){var v;const[n,r]=l.useState([]),[a,o]=l.useState(!0),[i,d]=l.useState(""),[m,p]=l.useState(""),[c,u]=l.useState(!0),[x,h]=l.useState({status:"idle",message:""}),{projects:b,loading:f,error:g}=nv(i);l.useEffect(()=>{t&&_s.setAuthToken(t)},[t]),l.useEffect(()=>{async function T(){try{o(!0);const{stores:k}=await re("listInstalledStores"),w=(k||[]).map(I=>({shop:I.shop,shopName:I.shopName,installedAt:I.installedAt?new Date(I.installedAt):new Date}));r(w)}catch(k){console.error("Error fetching stores:",k)}finally{o(!1)}}T()},[]),l.useEffect(()=>{p("")},[i]),l.useEffect(()=>{b.length>0&&!m&&p(b[0].id)},[b,m]);const y=async()=>{var T,k;if(!(!i||!t)){if(c&&!m){h({status:"error",message:"Please select a project to create a ticket"});return}try{if(c&&m){h({status:"capturing",message:"Creating ticket..."});const A=b.find(R=>R.id===m),E=(A==null?void 0:A.clientName)||"Unknown Client",C=new Date;C.setDate(C.getDate()+7);const N=C.toISOString().split("T")[0],S=await fetch(FR,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}
385,body:JSON.stringify({projectId:m,ticketName:`SEO capture for ${E}`,ticketDescription:`Initial URL optimization and capture of ${i}`,ticketStatus:"In Queue",dueDate:N})});if(!S.ok){const R=await S.text();throw console.error("Failed to create ticket:",S.status,R),new Error(`Failed to create ticket: ${R}`)}const O=await S.json();console.log("Created ticket:",O.ticketId)}h({status:"capturing",message:"Capturing SEO data from Shopify..."});const w=await _s.captureSEOData({shop:i,resourceTypes:["product","collection","page"],forceRefresh:!1});if(!w.success)throw new Error(((T=w.errors)==null?void 0:T[0])||"Capture failed");h({status:"processing",message:"Processing items with AI...",itemsCaptured:w.itemsCaptured||0});const I=await _s.processWithAI({shop:i});if(!I.success)throw new Error(((k=I.errors)==null?void 0:k[0])||"AI processing failed");h({status:"success",message:"Capture complete!",itemsCaptured:w.itemsCaptured||0,itemsProcessed:I.itemsProcessed||0})}catch(w){console.error("Capture error:",w),h({status:"error",message:w instanceof Error?w.message:"An error occurred"})}}},j=()=>{h({status:"idle",message:""})};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsxs("div",{className:"bg-card border-b border-border px-4 py-3 flex items-center gap-3",children:[s&&e.jsx(st.button,{onClick:s,className:"p-2 -ml-2 hover:bg-accent rounded-lg transition-colors",whileTap:{scale:.95},children:e.jsx(dt,{className:"w-5 h-5 text-foreground"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Capture New Store"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Import SEO data from Shopify"})]})]}),e.jsxs("div",{className:"max-w-md mx-auto px-4 pt-6",children:[e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Select Store"}),a?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground py-2",children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{children:"Loading stores..."})]}):n.length===0?e.jsx("div",{className:"text-muted-foreground py-2",children:"No Sunbowl stores found. Install the Sunbowl app on a store first."}):e.jsxs("select",{value:i,onChange:T=>d(T.target.value),disabled:x.status==="capturing"||x.status==="processing",className:"w-full bg-background border border-border rounded-lg px-3 py-2 text-foreground focus:outline-none focus:ring-2 focus:ring-primary",children:[e.jsx("option",{value:"",children:"Choose a store..."}),n.map(T=>e.jsxs("option",{value:T.shop,children:[T.shopName," (",T.shop,")"]},T.shop))]})]}),i&&e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mb-4",children:[e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer mb-4",children:[e.jsx("input",{type:"checkbox",checked:c,onChange:T=>u(T.target.checked),disabled:x.status==="capturing"||x.status==="processing",className:"w-5 h-5 rounded border-border text-primary focus:ring-primary"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Create ticket"})]})]}),c&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Select Project"}),f?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground py-2",children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{children:"Loading projects..."})]}):g?e.jsx("div",{className:"text-sm text-red-500 py-2",children:g}):b.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-2",children:"No projects found for this store. Make sure the store is linked to a client."}):e.jsxs("select",{value:m,onChange:T=>p(T.target.value),disabled:x.status==="capturing"||x.status==="processing",className:"w-full bg-background border border-border rounded-lg px-3 py-2 text-foreground focus:outline-none focus:ring-2 focus:ring-primary",children:[e.jsx("option",{value:"",children:"Choose a project..."}),b.map(T=>e.jsxs("option",{value:T.id,children:[T.name," (",T.clientName,")"]},T.id))]}),m&&b.length>0&&e.jsxs("div",{className:"mt-3 p-3 bg-background rounded-lg border border-border",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Ticket will be created as:"}),e.jsxs("p",{className:"text-sm font-medium text-foreground",children:["SEO capture for ",((v=b.find(T=>T.id===m))==null?void 0:v.clientName)||"Unknown"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Status: In Queue | Due: 7 days"})]})]})]}),x.status==="idle"&&e.jsxs(st.button,{onClick:y,disabled:!i||!t,className:"w-full bg-primary text-primary-foreground rounded-lg p-4 flex items-center justify-center gap-2 font-medium disabled:opacity-50 disabled:cursor-not-allowed",whileTap:{scale:.98},children:[e.jsx(Nu,{className:"w-5 h-5"}),"Capture SEO Data"]}),x.status!=="idle"&&e.jsxs("div",{className:"bg-card border border-border rounded-lg p-6",children:[x.status==="capturing"&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(fe,{className:"w-8 h-8 text-blue-600 animate-spin"})}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Capturing Data"}),e.jsx("p",{className:"text-muted-foreground",children:x.message})]}),x.status==="processing"&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(ws,{className:"w-8 h-8 text-purple-600 animate-pulse"})}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Processing with AI"}),e.jsx("p",{className:"text-muted-foreground",children:x.message}),x.itemsCaptured!==void 0&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:[x.itemsCaptured," items captured"]})]}),x.status==="success"&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(fu,{className:"w-8 h-8 text-green-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Capture Complete!"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:x.message}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center mb-4",children:[e.jsxs("div",{className:"bg-background rounded-lg p-3",children:[e.jsx("div",{className:"text-2xl font-bold text-foreground",children:x.itemsCaptured||0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Items Captured"})]}),e.jsxs("div",{className:"bg-background rounded-lg p-3",children:[e.jsx("div",{className:"text-2xl font-bold text-foreground",children:x.itemsProcessed||0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"AI Processed"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(st.button,{onClick:j,className:"flex-1 bg-secondary text-secondary-foreground rounded-lg py-2 px-4 font-medium",whileTap:{scale:.98},children:"Capture Another"}),e.jsx(st.button,{onClick:s,className:"flex-1 bg-primary text-primary-foreground rounded-lg py-2 px-4 font-medium",whileTap:{scale:.98},children:"Go to Review"})]})]}),x.status==="error"&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(gs,{className:"w-8 h-8 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Capture Failed"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:x.message}),e.jsxs(st.button,{onClick:j,className:"bg-primary text-primary-foreground rounded-lg py-2 px-4 font-medium flex items-center gap-2 mx-auto",whileTap:{scale:.98},children:[e.jsx(yt,{className:"w-4 h-4"}),"Try Again"]})]})]}),e.jsxs("div",{className:"mt-6 text-sm text-muted-foreground",children:[e.jsx("p",{className:"mb-2",children:e.jsx("strong",{children:"What this does:"})}),e.jsxs("ul",{className:"list-disc list-inside space-y-1",children:[e.jsx("li",{children:"Fetches products, collections, and pages from Shopify"}),e.jsx("li",{children:"Processes each item with AI for SEO suggestions"}),e.jsx("li",{children:"Items appear in SEO Review for approval"})]})]})]})]})}function WR(t,s,n,r){const a=t.length,o=s.length,i=(n==null?void 0:n.length)??0,d=(r==null?void 0:r.length)??0;return{productTitle:{length:i,isOptimal:i>=50&&i<=70,isTooLong:i>200,isTooShort:i<20&&i>0},productDescription:{length:d,isOptimal:d>=150&&d<=300,isTooLong:d>1e3,isTooShort:d<100&&d>0},pageTitle:{length:a,isOptimal:a>=50&&a<=60,isTooLong:a>70,isTooShort:a<30},metaDescription:{length:o,isOptimal:o>=150&&o<=155,isTooLong:o>160,isTooShort:o<120}}}function UR(t){return{product:"Product",collection:"Collection",page:"Page"}[t]}function HR(t,s,n={}){const{shop:r,status:a,resourceType:o,autoLoad:i=!0}=n,[d,m]=l.useState([]),[p,c]=l.useState(0),[u,x]=l.useState([]),[h,b]=l.useState(r||null),[f,g]=l.useState(a||["pending_review"]),[y,j]=l.useState(o||null),[v,T]=l.useState(!0),[k,w]=l.useState(!1),[I,A]=l.useState(!1),[E,C]=l.useState(!1),[N,S]=l.useState(!1),[O,R]=l.useState(!1),[z,D]=l.useState(null),L=l.useRef(!0);l.useEffect(()=>{_s.setAuthToken(t)},[t]),l.useEffect(()=>()=>{L.current=!1},[]);
385const $=d[p]||null,q=l.useMemo(()=>{const Q={pendingReview:0,approved:0,rejected:0,pushed:0},K={pendingReview:0,approved:0,rejected:0,pushed:0};for(const X of d)X.status==="pending_review"&&K.pendingReview++,X.status==="approved"&&K.approved++,X.status==="rejected"&&K.rejected++,X.status==="pushed"&&K.pushed++;if(h){const X=u.find(se=>se.shop===h);if(X)return Q.pushed=X.counts.pushed,Q.approved=Math.max(X.counts.approved,K.approved),Q.rejected=Math.max(X.counts.rejected,K.rejected),Q.pendingReview=K.pendingReview,Q}return K},[d,u,h]),P=l.useCallback(async(Q=!0)=>{if(!t){m([]),T(!1);return}try{T(!0),D(null);const K=await _s.getReviewItems({shop:h||void 0,status:f||void 0,useCache:Q});L.current&&(m(K.items),c(0))}catch(K){console.error("[useSEOReview] Error fetching items:",K),L.current&&(D(K.message||"Failed to fetch SEO items"),m([]))}finally{L.current&&T(!1)}},[t,h,f]),U=l.useCallback(async(Q=!0)=>{if(!t){x([]);return}try{const K=await _s.getShops(Q);L.current&&x(K.shops)}catch(K){console.error("[useSEOReview] Error fetching shops:",K)}},[t]);l.useEffect(()=>{i&&(P(),U())},[P,U,i]),l.useEffect(()=>{i&&t&&P(!1)},[h,f]);const V=l.useCallback(()=>{c(Q=>Math.min(Q+1,d.length-1))},[d.length]),M=l.useCallback(()=>{c(Q=>Math.max(Q-1,0))},[]),F=l.useCallback(Q=>{Q>=0&&Q<d.length&&c(Q)},[d.length]),W=l.useCallback(async Q=>{if(!$||!s)throw new Error("No current item or user email");try{C(!0),D(null);const K=await _s.approveItem($.id,s,Q);L.current&&(m(X=>X.map(se=>se.id===$.id?{...K.item,status:"approved"}:se)),p<d.length-1&&c(X=>X+1))}catch(K){throw console.error("[useSEOReview] Error approving item:",K),L.current&&D(K.message||"Failed to approve item"),K}finally{L.current&&C(!1)}},[$,s,p,d.length]),_=l.useCallback(async()=>{if(!$||!s)throw new Error("No current item or user email");try{C(!0),D(null);const Q=await _s.ignoreItem($.id,s);L.current&&(m(K=>K.filter(X=>X.id!==$.id)),p>=d.length-1&&c(Math.max(0,p-1)))}catch(Q){throw console.error("[useSEOReview] Error ignoring item:",Q),L.current&&D(Q.message||"Failed to ignore item"),Q}finally{L.current&&C(!1)}},[$,s,p,d.length]),G=l.useCallback(async()=>{if(!$||!s)throw new Error("No current item or user email");try{C(!0),D(null),await _s.skipItem($.id,s),L.current&&p<d.length-1&&c(Q=>Q+1)}catch(Q){throw console.error("[useSEOReview] Error skipping item:",Q),L.current&&D(Q.message||"Failed to skip item"),Q}finally{L.current&&C(!1)}},[$,s,p,d.length]),B=l.useCallback(async(Q,K=!1)=>{try{w(!0),D(null);const X=await _s.captureSEOData({shop:Q,forceRefresh:K});L.current&&(console.log(`[useSEOReview] Captured ${X.itemsCaptured} items`),await Promise.all([P(!1),U(!1)]))}catch(X){throw console.error("[useSEOReview] Error capturing SEO data:",X),L.current&&D(X.message||"Failed to capture SEO data"),X}finally{L.current&&w(!1)}},[P,U]),Y=l.useCallback(async(Q,K,X)=>{try{A(!0),D(null);const se=await _s.processWithAI({shop:Q,itemIds:K,keywords:X});L.current&&(console.log(`[useSEOReview] Processed ${se.itemsProcessed} items with AI`),await P(!1))}catch(se){throw console.error("[useSEOReview] Error processing with AI:",se),L.current&&D(se.message||"Failed to process with AI"),se}finally{L.current&&A(!1)}},[P]),J=l.useCallback(async(Q,K)=>{try{if(!Q)throw new Error("Target shop is required");S(!0),D(null);const X=await _s.pushToShopify({shop:Q,itemIds:K});L.current&&(console.log(`[useSEOReview] Pushed ${X.itemsPushed} items to Shopify`),X.errors&&X.errors.length>0&&console.warn("[useSEOReview] Push errors:",X.errors),await Promise.all([P(!1).catch(se=>{console.error("[useSEOReview] Error fetching items:",se)}),U(!1).catch(se=>{console.error("[useSEOReview] Error fetching shops:",se)})]))}catch(X){throw console.error("[useSEOReview] Error pushing to Shopify:",X),L.current&&D(X.message||"Failed to push to Shopify"),X}finally{L.current&&S(!1)}},[P,U]),H=l.useCallback(async Q=>{try{A(!0),D(null);const K=await _s.triggerAutomation({shop:Q});return L.current&&(console.log(`[useSEOReview] Automation completed: ${K.itemsProcessedWithAI} items processed`),K.errors&&K.errors.length>0&&console.warn("[useSEOReview] Automation errors:",K.errors),await Promise.all([P(!1),U(!1)])),{itemsProcessed:K.itemsProcessedWithAI}}catch(K){throw console.error("[useSEOReview] Error triggering automation:",K),L.current&&D(K.message||"Failed to trigger automation"),K}finally{L.current&&A(!1)}},[P,U]),Z=l.useCallback(async()=>{try{R(!0),D(null),await Promise.all([P(!1),U(!1)])}finally{L.current&&R(!1)}},[P,U]);return{items:d,currentItem:$,currentIndex:p,totalItems:d.length,shops:u,selectedShop:h,selectedStatus:f,selectedResourceType:y,loading:v,capturing:k,processing:I,submitting:E,pushing:N,refreshing:O,error:z,stats:q,setSelectedShop:b,setSelectedStatus:g,setSelectedResourceType:j,approveItem:W,ignoreItem:_,ski
385pItem:G,captureSEOData:B,processWithAI:Y,pushToShopify:J,triggerAutomation:H,nextItem:V,previousItem:M,goToItem:F,refresh:Z,fetchShops:U}}function qR({imageUrl:t,altText:s,onClose:n}){return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm p-8",onClick:n,children:[e.jsx("button",{onClick:n,className:"fixed top-4 right-4 z-50 w-10 h-10 flex items-center justify-center bg-white hover:bg-gray-100 text-gray-800 rounded-full shadow-lg transition-colors","aria-label":"Close image",children:e.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),e.jsxs("div",{className:"flex flex-col items-center p-5",onClick:r=>r.stopPropagation(),children:[e.jsx("img",{src:t,alt:s,style:{maxWidth:"calc(100vw - 5rem)",maxHeight:"calc(100vh - 12rem)"},className:"object-contain rounded-lg shadow-2xl"}),s&&e.jsx("div",{className:"mt-4 p-3 bg-white/90 backdrop-blur rounded-lg",style:{maxWidth:"calc(100vw - 6rem)"},children:e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Alt text:"})," ",s]})})]})]})}function to({current:t,optimal:s,max:n}){let r="text-green-600";return(t<s.min||t>s.max)&&(r="text-yellow-600"),(t>n||t<30)&&(r="text-red-600"),e.jsxs("span",{className:`text-xs ${r}`,children:[t,"/",s.max," chars"]})}function Ax(t){return t?t.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim():""}function VR(t,s,n){const r=t.replace(".myshopify.com",""),a=n.split("/").pop()||"",i={product:"products",collection:"collections",page:"pages"}[s]||"products";return`https://admin.shopify.com/store/${r}/${i}/${a}`}function YR({item:t,editedProductTitle:s,editedProductDescription:n,editedPageTitle:r,editedMetaDescription:a,editedImageAltText:o,onEditProductTitle:i,onEditProductDescription:d,onEditPageTitle:m,onEditMetaDescription:p,onEditImageAltText:c,productTitleEnabled:u=!0,productDescriptionEnabled:x=!0,pageTitleEnabled:h=!0,metaDescriptionEnabled:b=!0,imageAltTextEnabled:f=!0,onToggleProductTitle:g,onToggleProductDescription:y,onTogglePageTitle:j,onToggleMetaDescription:v,onToggleImageAltText:T}){const[k,w]=l.useState(!1),I=t.aiSuggestion,A=s??(I==null?void 0:I.productTitle)??t.original.title??"",E=n??(I==null?void 0:I.productDescription)??Ax(t.original.description)??"",C=r??(I==null?void 0:I.pageTitle)??t.original.pageTitle??"",N=a??(I==null?void 0:I.metaDescription)??t.original.metaDescription??"",S=o??(I==null?void 0:I.imageAltText)??t.original.imageAltText??"",O=t.original.imageUrl&&t.resourceType!=="page";return WR(C,N,A,E),e.jsxs("div",{className:"bg-white rounded-lg shadow-sm overflow-hidden",children:[e.jsx("div",{className:"bg-gray-50 px-4 py-3 border-b border-gray-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:t.original.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-xs px-2 py-0.5 bg-gray-200 text-gray-600 rounded-full",children:UR(t.resourceType)}),e.jsxs("a",{href:VR(t.shop,t.resourceType,t.resourceId),target:"_blank",rel:"noopener noreferrer",className:"text-xs text-blue-600 hover:text-blue-800 hover:underline flex items-center gap-1",title:"Open in Shopify Admin",children:["/",t.resourceHandle,e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})]})]}),I&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:` 386 px-3 py-1 rounded-full text-sm font-medium 387 ${I.seoScore>=80?"bg-green-100 text-green-700":I.seoScore>=60?"bg-yellow-100 text-yellow-700":"bg-red-100 text-red-700"} 388 `,children:["Score: ",I.seoScore]})})]})}),e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:`mb-6 ${u?"":"opacity-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[g&&e.jsx("button",{type:"button",onClick:g,className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${u?"bg-green-500 border-green-500 text-white":"bg-white border-gray-300 hover:border-gray-400"}`,title:u?"Click to exclude from update":"Click to include in update",children:u&&e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsxs("label",{className:"text-sm font-medium text-gray-700",children:[t.resourceType==="product"?"Product Title":t.resourceType==="collection"?"Collection Title":"Page Title",e.jsx("span",{className:"text-gray-400 font-normal ml-1",children:"(Display Name)"})]})]}),e.jsx(to,{current:A.length,optimal:{min:50,max:70},max:200})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-gray-500 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-gray-400 rounded-full"}),"Original"]}),e.jsx("div",{className:"p-3 bg-muted rounded border border-border text-sm text-muted-foreground min-h-[60
388px]",children:t.original.title||e.jsx("span",{className:"text-muted-foreground italic",children:"Not set"})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-green-600 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),"AI Suggestion"]}),e.jsx("textarea",{value:A,onChange:R=>i(R.target.value),className:"w-full p-3 rounded border border-gray-300 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none bg-green-50",rows:2,placeholder:"Enter title..."})]})]})]}),e.jsxs("div",{className:`mb-6 ${x?"":"opacity-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y&&e.jsx("button",{type:"button",onClick:y,className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${x?"bg-green-500 border-green-500 text-white":"bg-white border-gray-300 hover:border-gray-400"}`,title:x?"Click to exclude from update":"Click to include in update",children:x&&e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsxs("label",{className:"text-sm font-medium text-gray-700",children:[t.resourceType==="product"?"Product Description":t.resourceType==="collection"?"Collection Description":"Page Content",e.jsx("span",{className:"text-gray-400 font-normal ml-1",children:"(Body)"})]})]}),e.jsx(to,{current:E.length,optimal:{min:150,max:300},max:1e3})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-gray-500 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-gray-400 rounded-full"}),"Original"]}),e.jsx("div",{className:"p-3 bg-muted rounded border border-border text-sm text-muted-foreground min-h-[100px] max-h-[150px] overflow-y-auto",children:Ax(t.original.description)||e.jsx("span",{className:"text-muted-foreground italic",children:"Not set"})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-green-600 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),"AI Suggestion"]}),e.jsx("textarea",{value:E,onChange:R=>d(R.target.value),className:"w-full p-3 rounded border border-gray-300 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none bg-green-50",rows:4,placeholder:"Enter description..."})]})]})]}),e.jsx("div",{className:"border-t border-gray-200 my-6 pt-6",children:e.jsx("div",{className:"text-xs font-medium text-gray-500 uppercase tracking-wider mb-4",children:"SEO Meta Fields (Search Results)"})}),e.jsxs("div",{className:`mb-6 ${h?"":"opacity-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j&&e.jsx("button",{type:"button",onClick:j,className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${h?"bg-green-500 border-green-500 text-white":"bg-white border-gray-300 hover:border-gray-400"}`,title:h?"Click to exclude from update":"Click to include in update",children:h&&e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsxs("label",{className:"text-sm font-medium text-gray-700",children:["Page Title ",e.jsx("span",{className:"text-gray-400 font-normal",children:"(Meta Title)"})]})]}),e.jsx(to,{current:C.length,optimal:{min:50,max:60},max:70})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-gray-500 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-gray-400 rounded-full"}),"Original"]}),e.jsx("div",{className:"p-3 bg-muted rounded border border-border text-sm text-muted-foreground min-h-[60px]",children:t.original.pageTitle||e.jsx("span",{className:"text-muted-foreground italic",children:"Not set"})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-green-600 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),"AI Suggestion"]}),e.jsx("textarea",{value:C,onChange:R=>m(R.target.value),className:"w-full p-3 rounded border border-gray-300 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none bg-green-50",rows:2,placeholder:"Enter page title..."})]})]})]}
388),e.jsxs("div",{className:`mb-6 ${b?"":"opacity-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v&&e.jsx("button",{type:"button",onClick:v,className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${b?"bg-green-500 border-green-500 text-white":"bg-white border-gray-300 hover:border-gray-400"}`,title:b?"Click to exclude from update":"Click to include in update",children:b&&e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Meta Description"})]}),e.jsx(to,{current:N.length,optimal:{min:150,max:155},max:160})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-gray-500 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-gray-400 rounded-full"}),"Original"]}),e.jsx("div",{className:"p-3 bg-muted rounded border border-border text-sm text-muted-foreground min-h-[80px]",children:t.original.metaDescription||e.jsx("span",{className:"text-muted-foreground italic",children:"Not set"})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-green-600 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),"AI Suggestion"]}),e.jsx("textarea",{value:N,onChange:R=>p(R.target.value),className:"w-full p-3 rounded border border-gray-300 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none bg-green-50",rows:3,placeholder:"Enter meta description..."})]})]})]}),O&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-gray-200 my-6 pt-6",children:e.jsx("div",{className:"text-xs font-medium text-gray-500 uppercase tracking-wider mb-4",children:"Image Accessibility"})}
388),e.jsxs("div",{className:`mb-6 ${f?"":"opacity-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T&&e.jsx("button",{type:"button",onClick:T,className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${f?"bg-green-500 border-green-500 text-white":"bg-white border-gray-300 hover:border-gray-400"}`,title:f?"Click to exclude from update":"Click to include in update",children:f&&e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsxs("label",{className:"text-sm font-medium text-gray-700",children:["Image ALT Text ",e.jsx("span",{className:"text-gray-400 font-normal",children:"(Accessibility)"})]})]}),e.jsx(to,{current:S.length,optimal:{min:80,max:125},max:150})]}),t.original.imageUrl&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("button",{type:"button",onClick:()=>w(!0),className:"group relative cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 rounded","aria-label":"Click to view full image",children:[e.jsx("img",{src:t.original.imageUrl,alt:t.original.imageAltText||"Product image",className:"w-24 h-24 object-cover rounded border border-gray-200 group-hover:border-blue-400 transition-colors"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 rounded transition-colors flex items-center justify-center",children:e.jsx("svg",{className:"w-6 h-6 text-white opacity-0 group-hover:opacity-100 transition-opacity drop-shadow-lg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})})})]}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Click to enlarge"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-gray-500 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-gray-400 rounded-full"}),"Original"]}),e.jsx("div",{className:"p-3 bg-muted rounded border border-border text-sm text-muted-foreground min-h-[60px]",children:t.original.imageAltText||e.jsx("span",{className:"text-muted-foreground italic",children:"Not set"})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-green-600 mb-1 flex items-center gap-1",children:[e.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),"AI Suggestion"]}),e.jsx("textarea",{value:S,onChange:R=>c(R.target.value),className:"w-full p-3 rounded border border-gray-300 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none bg-green-50",rows:2,placeholder:"Enter image ALT text..."})]})]})]})]}),(I==null?void 0:I.reasoning)&&e.jsx("div",{className:"bg-blue-50 rounded-lg p-3 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("svg",{className:"w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-blue-700 mb-1",children:"AI Reasoning"}),e.jsx("p",{className:"text-sm text-blue-800",children:I.reasoning})]})]})})]}),k&&t.original.imageUrl&&e.jsx(qR,{imageUrl:t.original.imageUrl,altText:t.original.imageAltText||"Product image",onClose:()=>w(!1)})]})}function GR({onApprove:t,onIgnore:s,onSkip:n,disabled:r,loading:a,hasEdits:o=!1}){return e.jsxs("div",{className:"flex items-center justify-between p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{onClick:n,disabled:r,className:"px-4 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Skip"})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:s,disabled:r,className:"px-4 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 border border-gray-200 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"})}),"Ignore"]}),e.jsx("button",{onClick:t,disabled:r,className:"px-6 py-2 text-sm font-medium text-white bg-green-500 hover:bg-green-600 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),o?"Approve with Edits":"Approve"]})})]})]})}function Ex({shops:t,selectedShop:s,onSelectShop:n,loading:r=!1,stats:a}){return r?e.jsxs("div",{className:"flex items-center gap-2 text-gray-500",children:[e.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Loading shops..."]}):t.length===0?e.jsx("div",{className:"text-gray-500 text-sm",children:"No shops with SEO data. Capture data from a shop first."}):e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("label",{htmlFor:"shop-select",className:"text-sm font-medium text-gray-700",children:"Shop:"}),e.jsxs("select",{id:"shop-select",value:s||"",onChange:o=>n(o.target.value||null),className:"px-3 py-2 border border-gray-300 rounded-lg bg-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500",children:[e.jsx("option",{value:"",children:"All Shops"}),t.map(o=>e.jsxs("option",{value:o.shop,children:[o.shop," (",o.counts.pending_review," pending)"]},o.shop))]}),s&&e.jsx("div",{className:"flex items-center gap-4 text-xs",children:(()=>{const o=t.find(p=>p.shop===s);if(!o)return null;const i=(a==null?void 0:a.pendingReview)??o.counts.pending_review,d=(a==null?void 0:a.approved)??o.counts.approved,m=(a==null?void 0:a.pushed)??o.counts.pushed;return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-gray-500",children:["Total: ",e.jsx("span",{className:"font-medium",children:o.counts.total})]}),e.jsxs("span",{className:"text-yellow-600",children:["Pending: ",e.jsx("span",{className:"font-medium",children:i})]}),e.jsxs("span",{className:"text-green-600",children:["Approved: ",e.jsx("span",{className:"font-medium",children:d})]}),e.jsxs("span",{className:"text-purple-600",children:["Pushed: ",e.jsx("span",{className:"font-medium",children:m})]})]})})()})]})}function KR(){var j;const[t,s]=l.useState([]),[n,r]=l.useState(null),[a,o]=l.useState(!1),[i,d]=l.useState(!1),[m,p]=l.useState(null),[c,u]=l.useState(null),[x,h]=l.useState(null),b=typeof window<"u"&&!!((j=window.electron)!=null&&j.chatgpt);l.useEffect(()=>{if(!b)return;const v=window.electron.chatgpt.onKeywordsExtracted(I=>{s(I.keywords),r(I.question),u(I.conversationId),h(I.timestamp),p(`Found ${I.keywords.length} keywords`)}),T=window.electron.chatgpt.onWindowOpened(I=>{p(I.message),o(!0)}),k=window.electron.chatgpt.onSearchStarted(()=>{d(!0),p("ChatGPT is searching...")}),w=window.electron.chatgpt.onSearchComplete(I=>{d(!1),r(I.question),p(`Search complete - ${I.keywords.length} keywords captured`)});return window.electron.chatgpt.isWindowOpen().then(I=>{o(I.isOpen)}),()=>{v(),T(),k(),w()}},[b]);const f=l.useCallback(async()=>
388{if(!b){p("This feature requires the Electron desktop app");return}try{await window.electron.chatgpt.openWindow(),o(!0),p("Opening ChatGPT window...")}catch{p("Failed to open ChatGPT window")}},[b]),g=l.useCallback(async()=>{if(b)try{await window.electron.chatgpt.closeWindow(),o(!1),d(!1),p(null)}catch{p("Failed to close ChatGPT window")}},[b]),y=l.useCallback(()=>{s([]),r(null),u(null),h(null),p(null)},[]);return{keywords:t,question:n,isWindowOpen:a,isSearching:i,isSupported:b,statusMessage:m,conversationId:c,lastUpdated:x,openChatGPTWindow:f,closeChatGPTWindow:g,clearResults:y}}function Ix({onKeywordsExtracted:t,onApplyKeywords:s,className:n="",shopDomain:r}){const{keywords:a,question:o,isWindowOpen:i,isSearching:d,isSupported:m,statusMessage:p,lastUpdated:c,conversationId:u,openChatGPTWindow:x,closeChatGPTWindow:h,clearResults:b}=KR(),[f,g]=l.useState([]),[y,j]=l.useState(!1),[v,T]=l.useState(!1),[k,w]=l.useState(null),[I,A]=l.useState(!1),[E,C]=l.useState(!1),[N,S]=l.useState(new Set);l.useEffect(()=>{t&&a.length>0&&t(a)},[a,t]);const O=l.useCallback(async()=>{T(!0);try{const P=await re("getChatGPTKeywords",{shopDomain:r,limit:20});P.success&&P.results&&g(P.results)}catch(P){console.error("Failed to load saved results:",P)}finally{T(!1)}},[r]);l.useEffect(()=>{I&&f.length===0&&O()},[I,O,f.length]);const R=l.useCallback(async()=>{if(a.length>0)try{await navigator.clipboard.writeText(a.join(` 389`)),C(!0),setTimeout(()=>C(!1),2e3)}catch(P){console.error("Failed to copy keywords:",P)}},[a]),z=l.useCallback(async()=>{if(!o||a.length===0){w("No keywords to save");return}j(!0),w(null);try{const P=await re("saveChatGPTKeywords",{question:o,keywords:a,conversationId:u,shopDomain:r});P.success?(O(),b()):w(P.error||"Failed to save")}catch(P){w("Failed to save keywords"),console.error(P)}finally{j(!1)}},[o,a,u,r,O,b]),D=l.useCallback(async P=>{try{await re("deleteChatGPTKeywords",{id:P}),g(U=>U.filter(V=>V.id!==P)),S(U=>{if(U.has(P)){const V=new Set(U);return V.delete(P),V}return U})}catch(U){console.error("Failed to delete:",U)}},[]),L=l.useCallback(P=>{S(U=>{const V=new Set(U);return V.has(P)?V.delete(P):V.add(P),V})},[]),$=l.useCallback(()=>{const P=new Set;return f.forEach(U=>{var V;N.has(U.id)&&((V=U.keywords)==null||V.forEach(M=>P.add(M)))}),Array.from(P)},[f,N]),q=l.useCallback(()=>{const P=$();P.length>0&&s&&(s(P),S(new Set))},[$,s]);return m?e.jsxs("div",{className:`bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden ${n}`,children:[e.jsx("div",{className:"px-5 py-4 bg-gradient-to-r from-emerald-50 to-teal-50 border-b border-gray-100",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center shadow-lg shadow-emerald-200",children:e.jsx("svg",{className:"w-6 h-6 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:"ChatGPT Keyword Research"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Discover AI search queries for your brand"})]})]})}),e.jsx("div",{className:"p-5",children:e.jsx("button",{type:"button",onClick:i?h:x,className:`w-full py-4 px-6 rounded-xl font-semibold text-base transition-all flex items-center justify-center gap-3 ${i?"bg-gray-100 text-gray-700 hover:bg-gray-200 border-2 border-gray-200":"bg-gradient-to-r from-emerald-500 to-teal-500 text-white hover:from-emerald-600 hover:to-teal-600 shadow-lg shadow-emerald-200"}`,children:i?e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),"Close ChatGPT Window"]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),"New Search"]})})}),e.jsx(hs,{children:p&&e.jsx(st.div,{initial:{opacity:0,height:0}
389,animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:`mx-5 mb-4 px-4 py-3 rounded-lg ${d?"bg-amber-50 border border-amber-200":"bg-emerald-50 border border-emerald-200"}`,children:e.jsxs("div",{className:`flex items-center gap-2 ${d?"text-amber-700":"text-emerald-700"}`,children:[d&&e.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),!d&&a.length>0&&e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),e.jsx("span",{className:"text-sm font-medium",children:p})]})})}),e.jsx(hs,{children:i&&a.length===0&&e.jsx(st.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"px-5 pb-5",children:e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-100",children:[e.jsxs("h4",{className:"font-semibold text-blue-800 mb-2 flex items-center gap-2",children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),"How it works"]}),e.jsxs("ol",{className:"text-sm text-blue-700 space-y-2",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold",children:"1."}),e.jsx("span",{children:"In the ChatGPT window, ask about a brand or product"})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold",children:"2."}),e.jsx("span",{children:'Example: "Tell me about Nike running shoes"'})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold",children:"3."}),e.jsx("span",{children:"Keywords will appear here automatically when ChatGPT searches"})]})]})]})})}),e.jsx(hs,{children:a.length>0&&e.jsxs(st.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:"px-5 pb-5",children:[o&&e.jsxs("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Your question:"}),e.jsx("p",{className:"text-sm font-medium text-gray-800",children:o})]}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Keywords Found"}),e.jsx("span",{className:"px-2 py-0.5 bg-emerald-100 text-emerald-700 text-xs font-bold rounded-full",children:a.length})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:R,className:"px-3 py-1.5 text-xs font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-lg flex items-center gap-1.5 transition-colors",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})}),"Copy"]}),e.jsxs("button",{type:"button",onClick:b,className:"px-3 py-1.5 text-xs font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-lg flex items-center gap-1.5 transition-colors",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),"Clear"]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-4",children:a.map((P,U)=>e.jsx(st.span,{initial:{opacity:0,scale:.8}
389,animate:{opacity:1,scale:1},transition:{delay:U*.03},className:"px-3 py-1.5 bg-gradient-to-r from-emerald-50 to-teal-50 border border-emerald-200 text-emerald-800 text-sm rounded-lg font-medium",children:P},P))}),e.jsx("button",{type:"button",onClick:z,disabled:y||!o,className:"w-full py-3 px-4 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-lg font-semibold text-sm hover:from-blue-600 hover:to-indigo-600 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 shadow-lg shadow-blue-200",children:y?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"})}),"Save Keywords"]})}),k&&e.jsx("p",{className:"text-red-500 text-xs mt-2 text-center",children:k}),c&&e.jsxs("div",{className:"mt-4 pt-3 border-t border-gray-100 text-xs text-gray-500 text-center",children:["Last updated: ",new Date(c).toLocaleTimeString()]})]})}),e.jsxs("div",{className:"border-t border-gray-100",children:[e.jsxs("button",{type:"button",onClick:()=>A(!I),className:"w-full px-5 py-3 flex items-center justify-between text-sm font-medium text-gray-600 hover:bg-gray-50 transition-colors",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4"})}),"Saved Searches",f.length>0&&e.jsx("span",{className:"bg-gray-200 text-gray-600 px-1.5 py-0.5 rounded text-xs",children:f.length})]}),e.jsx("svg",{className:`w-4 h-4 transition-transform ${I?"rotate-180":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),e.jsx(hs,{children:I&&e.jsx(st.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:e.jsx("div",{className:"px-5 pb-5",children:v?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-emerald-500 border-t-transparent rounded-full"})}):f.length===0?e.jsx("div",{className:"text-center py-6 text-gray-500 text-sm",children:"No saved searches yet"}):e.jsxs("div",{className:"space-y-3",children:[N.size>0&&s&&e.jsxs("button",{type:"button",onClick:q,className:"w-full py-3 px-4 bg-gradient-to-r from-purple-500 to-indigo-500 text-white rounded-lg font-semibold text-sm hover:from-purple-600 hover:to-indigo-600 transition-all flex items-center justify-center gap-2 shadow-lg shadow-purple-200",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})}),"Apply ",$().length," Keywords to AI"]}),f.map(P=>e.jsx("div",{className:`rounded-lg p-3 border transition-colors cursor-pointer ${N.has(P.id)?"bg-purple-50 border-purple-200":"bg-gray-50 border-gray-100 hover:border-gray-200"}`,onClick:()=>L(P.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"pt-0.5",children:e.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${N.has(P.id)?"bg-purple-500 border-purple-500":"bg-white border-gray-300"}`,children:N.has(P.id)&&e.jsx("svg",{className:"w-3 h-3 text-white",f
389ill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium text-gray-900 text-sm",children:P.question}),e.jsxs("p",{className:"text-xs text-gray-500 mt-0.5",children:[new Date(P.createdAt).toLocaleDateString()," · ",P.keywords.length," keywords"]})]}),e.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),D(P.id)},className:"text-gray-400 hover:text-red-500 p-1",children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[P.keywords.slice(0,5).map(U=>e.jsx("span",{className:"px-2 py-0.5 bg-white border border-gray-200 text-gray-600 text-xs rounded",children:U},U)),P.keywords.length>5&&e.jsxs("span",{className:"px-2 py-0.5 text-gray-400 text-xs",children:["+",P.keywords.length-5," more"]})]})]})]})},P.id))]})})})})]}),e.jsx(hs,{children:E&&e.jsx(st.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},className:"fixed bottom-4 right-4 bg-gray-900 text-white px-4 py-2 rounded-lg text-sm shadow-lg",children:"Copied to clipboard!"})})]}):e.jsx("div",{className:`bg-gray-50 rounded-xl border border-gray-200 p-5 ${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gradient-to-br from-gray-200 to-gray-300 flex items-center justify-center",children:e.jsx("svg",{className:"w-6 h-6 text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-800",children:"ChatGPT Keyword Research"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Available in the Bucky desktop app"})]})]})})}function QR({authToken:t,userEmail:s,onBack:n}){const[r,a]=l.useState(),[o,i]=l.useState(),[d,m]=l.useState(),[p,c]=l.useState(),[u,x]=l.useState(),[h,b]=l.useState(null),[f,g]=l.useState(!1),[y,j]=l.useState([]),[v,T]=l.useState(""),[k,w]=l.useState(!0),[I,A]=l.useState(!0),[E,C]=l.useState(!0),[N,S]=l.useState(!0),[O,R]=l.useState(!0),{items:z,currentIndex:D,shops:L,selectedShop:$,selectedResourceType:q,loading:P,submitting:U,refreshing:V,pushing:M,processing:F,stats:W,setSelectedShop:_,setSelectedResourceType:G,selectedStatus:B,setSelectedStatus:Y,approveItem:J,ignoreItem:H,skipItem:Z,pushToShopify:Q,triggerAutomation:K,processWithAI:X,nextItem:se,previousItem:pe,goToItem:me,refresh:Ne}=HR(t,s),at=l.useMemo(()=>{let Te=z;if(q&&(Te=Te.filter(He=>He.resourceType===q)),v.trim()){const He=v.toLowerCase().trim();Te=Te.filter(Oe=>{var je,qe;const Je=((je=Oe.original.title)==null?void 0:je.toLowerCase())||"",de=((qe=Oe.resourceHandle)==null?void 0:qe.toLowerCase())||"";return Je.includes(He)||de.includes(He)})}return Te},[z,q,v]),ae=at[D]||null,xe=at.length,ze=l.useCallback(()=>{const He=Date.now()+3e3,Oe=(de,je)=>Math.random()*(je-de)+de,Je=()=>{const de=He-Date.now();if(de<=0)return;const je=50*(de/3e3);va({particleCount:je,startVelocity:30,spread:60,origin:{x:Oe(.1,.3),y:Math.random()-.2},colors:["#22c55e","#3b82f6","#f59e0b","#ec4899","#8b5cf6"]}),va({particleCount:je,startVelocity:30,spread:60,origin:{x:Oe(.7,.9),y:Math.random()-.2},colors:["#22c55e","#3b82f6","#f59e0b","#ec4899","#8b5cf6"]}),setTimeout(Je,250)};Je(),g(!0)},[]),Le=ae,ht=xe;ee.useEffect(()=>{me(0)},[v,q,B]),ee.useEffect(()=>{Le!=null&&Le.aiSuggestion?(a(Le.aiSuggestion.productTitle),i(Le.aiSuggestion.productDescription),m(Le.aiSuggestion.pageTitle),c(Le.aiSuggestion.metaDescription),x(Le.aiSuggestion.imageAltText??void 0)):(a(void 0),i(void 0),m(void 0),c(void 0),x(void 0))},[Le==null?void 0:Le.id]);const ue=l.useCallback(async()=>
389{if(!Le)return;const Te=D===ht-1;try{b(null);const He={};k&&r&&(He.productTitle=r),I&&o&&(He.productDescription=o),E&&d&&(He.pageTitle=d),N&&p&&(He.metaDescription=p),O&&u&&(He.imageAltText=u);const Oe=Object.keys(He).length>0;await J(Oe?He:void 0),Te&&ze()}catch(He){b(He.message||"Failed to approve item")}},[Le,J,r,o,d,p,u,k,I,E,N,O,D,ht,ze]),we=l.useCallback(async()=>{try{b(null),await H()}catch(Te){b(Te.message||"Failed to ignore item")}},[H]),Be=l.useCallback(async()=>{try{b(null),await Z()}catch(Te){b(Te.message||"Failed to skip item")}},[Z]),Ye=l.useCallback(async()=>{if(!$){b("Please select a shop first");return}try{b(null),await Q($)}catch(Te){b(Te.message||"Failed to push to Shopify")}},[$,Q]),rt=l.useCallback(async()=>{var Te;try{b(null);const He=$||(Le==null?void 0:Le.shop)||((Te=z[0])==null?void 0:Te.shop);if(!He)throw new Error("No shop available for processing");if(y.length>0)console.log(`Processing ${He} with ${y.length} keywords:`,y),await X(He,void 0,y),j([]);else{const Oe=await K(He);if(!Oe)throw new Error("Failed to trigger automation");console.log(`Automation processed ${Oe.itemsProcessed} items`)}}catch(He){console.error("Error in handleTriggerAutomation:",He),b(He.message||"Failed to run AI processing")}},[$,Le,z,K,X,y]),te=l.useCallback(Te=>{j(Te),console.log(`Queued ${Te.length} keywords for AI processing`)},[]),ve=Le!=null&&Le.aiSuggestion?r!==Le.aiSuggestion.productTitle||o!==Le.aiSuggestion.productDescription||d!==Le.aiSuggestion.pageTitle||p!==Le.aiSuggestion.metaDescription||u!==(Le.aiSuggestion.imageAltText??void 0):!!(r||o||d||p||u);if(P)return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-screen p-4",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading SEO items for review..."})]});const Ae=B&&JSON.stringify(B)===JSON.stringify(["pending_review"]),ie=(v||q)&&at.length===0&&z.length>0;return!P&&z.length===0&&!ie?e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-screen p-4",children:[e.jsx("div",{className:"text-6xl mb-4",children:"ð"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-800 mb-2",children:"All Caught Up!"}),e.jsx("p",{className:"text-gray-600 text-center mb-6",children:$?`No SEO items found for ${$}`:"No SEO items found"}),e.jsx("div",{className:"mb-6",children:e.jsx(Ex,{shops:L,selectedShop:$,onSelectShop:_,stats:W})}),e.jsx("div",{className:"w-full max-w-xl mb-6",children:e.jsx(Ix,{onApplyKeywords:te})}),y.length>0&&e.jsx("div",{className:"w-full max-w-xl mb-4 px-4 py-3 bg-purple-50 border border-purple-200 rounded-lg",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-purple-700",children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})}),e.jsxs("span",{className:"font-medium",children:[y.length," keywords queued for AI"]})]}),e.jsx("button",{onClick:()=>j([]),className:"text-purple-500 hover:text-purple-700",children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:Ne,disabled:V,className:"px-6 py-3 rounded-lg transition-colors flex items-center gap-2 bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[V&&e.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),V?"Checking...":"Check for New Items"]}),W.approved>0&&$&&e.jsx("button",{onClick:Ye,disabled:M,className:"px-6 py-3 rounded-lg transition-colors flex items-center gap-2 bg-purple-600 text-white hover:bg-purple-700 disabled:opacity-50",children:M?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"})}),"Push ",W.approved," Approved to Shopify"]})})]}),e.jsx("button",{onClick:rt,disabled:F,className:`px-6 py-3 rounded-lg transition-colors flex items-center gap-2 text-white disabled:opacity-50 ${y.length>0?"bg-purple-500 hover:bg-purple-600":"bg-green-500 hover:bg-green-600"}`,children:F?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),y.length>0?"Processing with Keywords...":"Running AI Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:y.length>0?e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"}):e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})}),y.length>0?`Run AI with ${y.length} Keywords`:"Run AI Processing"]})}),e.jsx("p",{className:"text-sm text-gray-500",children:y.length>0?"Selected keywords will be incorporated into AI suggestions":"Process captured items with AI to generate SEO suggestions"})]}),n&&e.jsx("button",{onClick:n,className:"mt-4 text-blue-600 hover:text-blue-800",children:"Go Back"})]}):e.jsxs("div",{className:"flex flex-col min-h-screen bg-gray-50",children:[e.jsxs("header",{className:"bg-white border-b border-gray-200 px-4 py-3 sticky top-0 z-10",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[n&&e.jsx("button",{onClick:n,className:"p-2 hover:bg-gray-100 rounded-full transition-colors",children:e.jsx("svg",{className:"w-6 h-6 text-gray-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),e.jsx("h1",{className:"text-lg font-semibold text-gray-900",children:"SEO Review"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[W.approved>0&&$&&e.jsx("button",{onClick:Ye,disabled:M,className:"px-3 py-1.5 text-sm font-medium text-white bg-purple-600 hover:bg-purple-700 rounded-lg transition-colors disabled:opacity-50 flex items-center gap-1.5",children:M?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"})}),"Push ",W.approved]})}),e.jsxs("button",{onClick:Ne,disabled:V,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium transition-colors bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[e.jsx("svg",{className:V?"w-4 h-4 animate-spin":"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),V?"Loading...":"Refresh"]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(Ex,{shops:L,selectedShop:$,onSelectShop:_,stats:W}),e.jsx("div",{className:"hidden sm:block h-6 w-px bg-gray-200"}),e.jsx("div",{className:"flex items-center gap-1 bg-gray-100 rounded-lg p-1",children:[{value:null,label:"All"},{value:"product",label:"Products"},{value:"collection",label:"Collections"},{value:"page",label:"Pages"}].map(Te=>e.jsx("button",{onClick:()=>G(Te.value),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${q===Te.value?"bg-white text-gray-900 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:Te.label},Te.label))}),e.jsx("div",{className:"hidden sm:block h-6 w-px bg-gray-200"}),e.jsx("div",{className:"flex items-center gap-1 bg-gray-100 rounded-lg p-1",children:[{value:["pending_review"],label:"Pending"},{value:null,label:"All"},{value:["approved","pushed"],label:"Approved"}].map(Te=>{const He=B===Te.value||B&&Te.value&&JSON.stringify(B)===JSON.stringify(Te.value);return e.jsx("button",{onClick:()=>Y(Te.value),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${He?"bg-white text-gray-900 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:Te.label},Te.label)})}),e.jsx("div",{className:"hidden sm:block h-6 w-px bg-gray-200"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-xs",children:[e.jsx(Pt,{className:"absolute top-[50%] translate-y-[-50%] w-4 h-4 text-gray-400",style:{left:"0.625rem"}}),e.jsx("input",{type:"text",placeholder:"Search by title or URL...",value:v,onCh
389ange:Te=>T(Te.target.value),className:"w-full pr-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500",style:{paddingLeft:"1.75rem"}}),v&&e.jsx("button",{onClick:()=>T(""),className:"absolute right-2 top-[50%] translate-y-[-50%] p-1 text-gray-400 hover:text-gray-600",children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),v&&e.jsxs("span",{className:"text-xs text-gray-500",children:[xe," of ",z.length," items"]})]})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx(Ix,{onApplyKeywords:te}),y.length>0&&e.jsx("div",{className:"mt-3 px-4 py-3 bg-purple-50 border border-purple-200 rounded-lg",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-purple-700",children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})}),e.jsxs("span",{className:"font-medium",children:[y.length," keywords queued for next AI processing"]})]}),e.jsx("button",{onClick:()=>j([]),className:"text-purple-500 hover:text-purple-700",children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})})]}),y.length>0&&e.jsx("div",{className:"bg-white border-b border-gray-200 px-4 py-3",children:e.jsx("button",{onClick:rt,disabled:F,className:"w-full py-3 px-4 bg-gradient-to-r from-purple-500 to-indigo-500 text-white rounded-lg font-semibold text-sm hover:from-purple-600 hover:to-indigo-600 transition-all disabled:opacity-50 flex items-center justify-center gap-2 shadow-lg shadow-purple-200",children:F?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-5 h-5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Reprocessing with Keywords..."]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})}),"Reprocess with ",y.length," Keywords"]})})}),e.jsx(hs,{children:h&&e.jsx(st.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"bg-red-50 border-b border-red-200 px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-red-700",children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),e.jsx("span",{className:"text-sm",children:h})]}),e.jsx("button",{onClick:()=>b(null),className:"text-red-700 hover:text-red-900",children:e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})})}),ie&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4",children:[e.jsx(Pt,{className:"w-12 h-12 text-gray-300 mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No matching items"}),e.jsx("p",{className:"text-gray-500 text-center mb-4",children:v&&q?`No ${q}s match "${v}"`:v?`No items match "${v}"`:`No ${q}s found`}),e.jsxs("div",{className:"flex gap-3",children:[v&&e.jsx("button",{onClick:()=>T(""),className:"text-blue-600 hover:text-blue-800 text-sm font-medium",children:"Clear search"}),q&&e.jsx("button",{onClick:()=>G(null),className:"text-blue-600 hover:text-blue-800 text-sm font-medium",children:"Show all types"})]})]}),e.jsx("main",{className:"flex-1 overflow-auto",children:Le&&!f&&!ie&&e.jsxs("div",{className:"p-4",children:[!Ae&&e.jsx("div",{className:"mb-3",children:e.jsx("span",{className:`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${Le.status==="pending_review"?"bg-yellow-100 text-yellow-800":Le.status==="approved"?"bg-green-100 text-green-800":Le.status==="pushed"?"bg-purple-100 text-purple-800":Le.status==="captured"?"bg-blue-100 text-blue-800":Le.status==="ai_processed"?"bg-indigo-100 text-indigo-800":Le.status==="ignored"?"bg-gray-100 text-gray-600":Le.status==="rejected"?"bg-red-100 text-red-800":"bg-gray-100 text-gray-600"}`,children:Le.status==="pending_review"?"Pending Review":Le.status==="ai_processed"?"AI Processed":Le.status.charAt(0).toUpperCase()+Le.status.slice(1)})}),e.jsx(YR,{item:Le,editedProductTitle:r,editedProductDescription:o,editedPageTitle:d,editedMetaDescription:p,editedImageAltText:u,onEditProductTitle:a,onEditProductDescription:i,onEditPageTitle:m,onEditMetaDescription:c,onEditImageAltText:x,productTitleEnabled:k,productDescriptionEnabled:I,pageTitleEnabled:E,metaDescriptionEnabled:N,imageAltTextEnabled:O,onToggleProductTitle:()=>w(Te=>!Te),onToggleProductDescription:()=>A(Te=>!Te),onTogglePageTitle:()=>C(Te=>!Te),onToggleMetaDescription:()=>S(Te=>!Te),onToggleImageAltText:()=>R(Te=>!Te)})]})}),Le&&!f&&!ie&&e.jsx("div",{className:"bg-white border-t border-gray-200",children:e.jsx(GR,{onApprove:ue,onIgnore:we,onSkip:Be,disabled:U,loading:U,hasEdits:ve})}),e.jsx(hs,{children:f&&e.jsx(st.div,{initial:{opacity:0}
389,animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4",onClick:()=>g(!1),children:e.jsxs(st.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.8,opacity:0},className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md w-full text-center",onClick:Te=>Te.stopPropagation(),children:[e.jsx("div",{className:"text-7xl mb-4 animate-bounce",children:"ð"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"All Done!"}),e.jsxs("p",{className:"text-gray-600 mb-6",children:["You've reviewed all ",ht," SEO item",ht!==1?"s":""," in this batch. Great job!"]}),W.approved>0&&e.jsx("div",{className:"bg-green-50 rounded-lg p-4 mb-6",children:e.jsxs("div",{className:"flex items-center justify-center gap-2 text-green-700",children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),e.jsxs("span",{className:"font-medium",children:[W.approved," items approved"]})]})}),e.jsxs("div",{className:"flex flex-col gap-3",children:[W.approved>0&&$&&e.jsx("button",{onClick:()=>{g(!1),Ye()},className:"w-full py-3 px-4 bg-purple-600 text-white rounded-lg font-medium hover:bg-purple-700 transition-colors",children:"Push to Shopify"}),e.jsx("button",{onClick:()=>{g(!1),Ne()},className:"w-full py-3 px-4 bg-primary text-primary-foreground rounded-lg font-medium hover:bg-primary/90 transition-colors",children:"Load New Batch"}),e.jsx("button",{onClick:()=>g(!1),className:"w-full py-3 px-4 text-gray-600 hover:bg-gray-100 rounded-lg font-medium transition-colors",children:"Stay Here"})]})]})})}),ht>1&&!f&&!ie&&e.jsxs("div",{className:"fixed bottom-24 left-0 right-0 flex justify-between px-4 pointer-events-none",children:[e.jsx("button",{onClick:pe,disabled:D===0,className:` 390 p-3 bg-white rounded-full shadow-lg pointer-events-auto transition-opacity 391 ${D===0?"opacity-50":"hover:bg-gray-50"} 392 `,children:e.jsx("svg",{className:"w-6 h-6 text-gray-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),e.jsx("button",{onClick:se,disabled:D===ht-1,className:` 393 p-3 bg-white rounded-full shadow-lg pointer-events-auto transition-opacity 394 ${D===ht-1?"opacity-50":"hover:bg-gray-50"} 395 `,children:e.jsx("svg",{className:"w-6 h-6 text-gray-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]})}const JR=["Ongoing Support","Recurring","Standard","Marketing"];function ZR({onBack:t,onLogoClick:s,prefillClientName:n}){const[r,a]=l.useState(""),[o,i]=l.useState(null),[d,m]=l.useState(n||""),[p,c]=l.useState(!1),[u,x]=l.useState(""),[h,b]=l.useState(""),[f,g]=l.useState(""),[y,j]=l.useState("Development"),[v,T]=l.useState(null),[k,w]=l.useState(""),[I,A]=l.useState(!1),[E,C]=l.useState(""),[N,S]=l.useState(""),[O,R]=l.useState(""),[z,D]=l.useState([]),[L,$]=l.useState([]),[q,P]=l.useState(!0),[U,V]=l.useState(!0),[M,F]=l.useState(!1),[W,_]=l.useState(!1),[G,B]=l.useState(null),[Y,J]=l.useState(null);l.useEffect(()=>{const K=Ge(Re(ge,"clients"),Nt("name","asc"));return qt(K,se=>{D(se.docs.map(pe=>{const me=pe.data();return{id:pe.id,name:me.name,slackChannel:me.slackChannel||null}})),P(!1)},se=>{console.error("Failed to load clients:",se),P(!1)})},[]),l.useEffect(()=>{const K=Ge(Re(ge,"shopifyStores"),Nt("name","asc"));return qt(K,se=>{$(se.docs.map(pe=>{const me=pe.data();return{id:pe.id,name:me.name,url:me.myshopifyUrl||me.onlineStoreUrl||null,clientId:me.clientId||null}})),V(!1)},se=>{console.error("Failed to load stores:",se),F(!0),V(!1)})},[]);const H=l.useMemo(()=>{const K=z.filter(se=>typeof se.name=="string"&&se.name.length>0);if(!d.trim())return K;const X=d.toLowerCase();return K.filter(se=>se.name.toLowerCase().includes(X)||typeof se.slackChannel=="string"&&se.slackChannel.toLowerCase().includes(X))},[z,d]);l.useEffect(()=>{T(null),w("")},[o]);const Z=l.useMemo(()=>
395{if(!o)return[];let K=L.filter(se=>se.clientId===o.id&&typeof se.name=="string"&&se.name.length>0);if(!k.trim())return K;const X=k.toLowerCase();return K.filter(se=>se.name.toLowerCase().includes(X)||typeof se.url=="string"&&se.url.toLowerCase().includes(X))},[L,k,o]),Q=async K=>{if(K.preventDefault(),B(null),J(null),!r.trim()||!o){B("Project Name and Client are required");return}if(!E.trim()||!N.trim()||!O.trim()){B("All success/failure fields are required");return}_(!0);try{const X=ut(ge,"counters","projects"),pe=`PROJ-${await Dl(ge,async at=>{const ae=await at.get(X),ze=(ae.exists()?ae.data().lastNumber:0)+1;return at.set(X,{lastNumber:ze},{merge:!0}),ze})}`,me=[`### What does failure look like? 396${E.trim()}`,`### What does success look like? 397${N.trim()}`,`### How will we know when we have succeeded? 398${O.trim()}`].join(` 399 400`),Ne=await Ma(Re(ge,"clientProjects"),{notionPageId:"",displayId:pe,name:r.trim(),status:"In Progress",subStatus:"Ready",projectType:u||null,clientId:o.id,clientName:o.name,department:y,estTimeInMins:0,timelineStart:h?new Date(h):null,timelineEnd:null,launchDate:f?new Date(f):null,priority:null,hubspotDealId:null,qaReviewUrl:null,shopifyStoreId:(v==null?void 0:v.id)||null,content:me,createdAt:ss(),updatedAt:ss()});J({message:`Project ${pe} created successfully!`}),a(""),i(null),m(""),x(""),b(""),g(""),T(null),w(""),C(""),S(""),R("")}catch(X){B(X.message||"Failed to create project")}finally{_(!1)}};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx(st.button,{onClick:t,className:"p-2 rounded-lg hover:bg-accent transition-colors",whileTap:{scale:.95},children:e.jsx(dt,{className:"w-5 h-5 text-foreground"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Create Project"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add a new client project"})]})]}),Y&&e.jsx(st.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"mb-4 p-4 bg-green-500/10 border border-green-500/20 rounded-lg",children:e.jsx("p",{className:"text-green-500 font-medium",children:Y.message})}),G&&e.jsx(st.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"mb-4 p-4 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-destructive",children:G})}),e.jsxs("form",{onSubmit:Q,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-foreground mb-1",children:["Project Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("input",{type:"text",value:r,onChange:K=>a(K.target.value),placeholder:"e.g., Website Redesign 2025",className:"w-full px-3 py-2 bg-card border border-border rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary",disabled:W})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("label",{className:"block text-sm font-medium text-foreground mb-1",children:["Client ",e.jsx("span",{className:"text-destructive",children:"*"})]}),o?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-card border border-border rounded-lg",children:[e.jsx("span",{className:"flex-1 text-foreground",children:o.name}),o.slackChannel&&e.jsx("span",{className:"text-xs text-muted-foreground",children:o.slackChannel}),e.jsx("button",{type:"button",onClick:()=>{i(null),m("")},className:"p-1 hover:bg-accent rounded",children:e.jsx(mt,{className:"w-4 h-4 text-muted-foreground"})})]}):e.jsxs("div",{className:"flex items-center bg-card border border-border rounded-lg focus-within:ring-2 focus-within:ring-primary",children:[e.jsx(Pt,{className:"ml-3 w-4 h-4 text-muted-foreground flex-shrink-0"}),e.jsx("input",{type:"text",value:d,onChange:K=>{m(K.target.value),c(!0)},onFocus:()=>c(!0),placeholder:q?"Loading clients...":"Search clients...",className:"w-full pl-2 pr-3 py-2 bg-transparent text-foreground placeholder:text-muted-foreground focus:outline-none",disabled:W||q})]}),p&&!o&&H.length>0&&e.jsx("div",{className:"absolute z-10 w-full mt-1 bg-card border border-border rounded-lg shadow-lg max-h-48 overflow-y-auto",children:H.map(K=>e.jsxs("button",{type:"button",onClick:()=>{i(K),m(K.name),c(!1)},className:"w-full px-3 py-2 text-left hover:bg-accent flex items-center justify-between",children:[e.jsx("span",{className:"text-foreground",children:K.name}),K.slackChannel&&e.jsx("span",{className:"text-xs text-muted-foreground",children:K.slackChannel})]},K.id))})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("label",{className:"block text-sm font-medium text-foreground mb-1",children:["Shopify Store ",e.jsx("span",{className:"text-xs text-muted-foreground",children:"(optional)"})]}),M?e.jsx("div",{className:"px-3 py-2 bg-card border border-border rounded-lg text-muted-foreground text-sm",children:"Stores unavailable - you can add this later"}):o?v?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-card border border-border rounded-lg",children:[e.jsx("span",{className:"flex-1 text-foreground",children:v.name}),v.url&&e.jsx("span",{className:"text-xs text-muted-foreground truncate max-w-[150px]",children:v.url}),e.jsx("button",{type:"button",onClick:()=>{T(null),w("")},className:"p-1 hover:bg-accent rounded",children:e.jsx(mt,{className:"w-4 h-4 text-muted-foreground"})})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:k,onChange:K=>{w(K.target.value),A(!0)},onFocus:()=>A(!0),placeholder:U?"Loading stores...":`Search ${o.name}'s stores...`,className:"w-full pl-9 pr-3 py-2 bg-card border border-border rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary",disabled:W||U})]}):e.jsx("div",{className:"px-3 py-2 bg-card border border-border rounded-lg text-muted-foreground text-sm",children:"Select a client first to see their stores"}),I&&!v&&!M&&o&&Z.length>0&&e.jsx("div",{className:"absolute z-10 w-full mt-1 bg-card border border-border rounded-lg shadow-lg max-h-48 overflow-y-auto",children:Z.map(K=>e.jsxs("button",{type:"button",onClick:()=>{T(K),w(K.name),A(!1)},className:"w-full px-3 py-2 text-left hover:bg-accent flex items-center justify-between",children:[e.jsx("span",{className:"text-foreground",children:K.name}),K.url&&e.jsx("span",{className:"text-xs text-muted-foreground truncate max-w-[150px]",children:K.url})]},K.id))}),!M&&o&&Z.length===0&&!U&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["No stores found for ",o.name," - you can add this later"]}),!M&&o&&Z.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[Z.length," store",Z.length!==1?"s":""," for ",o.name]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-foreground mb-1",children:"Project Type"}),e.jsxs("select",{value:u,onChange:K=>x(K.target.value),className:"w-full px-3 py-2 bg-card border border-border rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-primary",disabled:W,children:[e.jsx("option",{value:"",children:"Select type..."}),JR.map(K=>e.jsx("option",{value:K,children:K},K))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-foreground mb-1",children:"Start Date"}),e.jsx("input",{type:"date",value:h,onChange:K=>b(K.target.value),className:"w-full px-3 py-2 bg-card border border-border rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-primary",disabled:W})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-foreground mb-1",children:"Launch Date"}),e.jsx("input",{type:"date",value:f,onChange:K=>g(K.target.value),className:"w-full px-3 py-2 bg-card border border-border rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-primary",disabled:W})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Department"}),e.jsx("div",{className:"flex rounded-lg border border-border overflow-hidden",children:Io.map(K=>e.jsx("button",{type:"button",onClick:()=>j(K),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${y===K?"bg-primary text-primary-foreground":"bg-card text-muted-foreground hover:bg-accent"}`,disabled:W,children:K},K))})]}),e.jsxs("div",{className:"space-y-4 pt-4 border-t border-border",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Project Goals"}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-foreground mb-1",children:["What does failure look like? ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("textarea",{value:E,onChange:K=>C(K.target.value),placeholder:"Describe what would constitute failure for this project...",rows:3,className:"w-full px-3 py-2 bg-card border border-border rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary resize-none",disabled:W})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-foreground mb-1",children:["What does success look like? ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("textarea",{value:N,onChange:K=>S(K.target.value),placeholder:"Describe what successful completion looks like...",rows:3,className:"w-full px-3 py-2 bg-card border border-border rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary resize-none",disabled:W})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-foreground mb-1",children:["How will we know
400when we have succeeded? ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx("textarea",{value:O,onChange:K=>R(K.target.value),placeholder:"Define measurable criteria for success...",rows:3,className:"w-full px-3 py-2 bg-card border border-border rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary resize-none",disabled:W})]})]}),e.jsx(st.button,{type:"submit",disabled:W||!r.trim()||!o||!E.trim()||!N.trim()||!O.trim(),className:"w-full mt-6 px-4 py-3 bg-primary text-primary-foreground rounded-lg font-medium flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",whileTap:{scale:.98},children:W?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-5 h-5 animate-spin"}),"Creating Project..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ng,{className:"w-5 h-5"}),"Create Project"]})})]}),(p||I)&&e.jsx("div",{className:"fixed inset-0 z-0",onClick:()=>{c(!1),A(!1)}})]})]})}function nn({...t}){return e.jsx(Cj,{"data-slot":"select",...t})}function rn({...t}){return e.jsx(Ej,{"data-slot":"select-value",...t})}function an({className:t,size:s="default",children:n,...r}){return e.jsxs(Tj,{"data-slot":"select-trigger","data-size":s,className:$e("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-full items-center justify-between gap-2 rounded-md border bg-input-background px-3 py-2 text-sm whitespace-nowrap transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r,children:[n,e.jsx(Aj,{asChild:!0,children:e.jsx(Ot,{className:"size-4 opacity-50"})})]})}function on({className:t,children:s,position:n="popper",...r}){return e.jsx(Ij,{children:e.jsxs(Rj,{"data-slot":"select-content",className:$e("bg-white dark:bg-gray-800 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,...r,children:[e.jsx(XR,{}),e.jsx(Dj,{className:$e("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:s}),e.jsx(eD,{})]})})}function cs({className:t,children:s,...n}){return e.jsxs(Mj,{"data-slot":"select-item",className:$e("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-4 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...n,children:[e.jsx("span",{className:"absolute right-4 flex size-3.5 items-center justify-center",children:e.jsx(Pj,{children:e.jsx(kt,{className:"size-4"})})}),e.jsx(Lj,{children:s})]})}function XR({className:t,...s}){return e.jsx(zj,{"data-slot":"select-scroll-up-button",className:$e("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(hr,{className:"size-4"})})}function eD({className:t,...s}){return e.jsx(Oj,{"data-slot":"select-scroll-down-button",className:$e("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Ot,{className:"size-4"})})}const tD=8,sD=4,nD=8,Rx={high:3,medium:2,low:1},rD=new Set(["Backlog","In Progress"]),aD=new Set(["Complete"]),oD=new Set(["Deferred"]),iD=new Set(["Archived"]),lD=new Set(["AI Review"]);function fy(t){const s={total:t.length,pending:0,approved:0,completed:0,deferred:0,archived:0,other:0};for(const n of t)lD.has(n.currentStatus)?s.pending++:rD.has(n.currentStatus)?s.approved++:aD.has(n.currentStatus)?s.completed++:oD.has(n.currentStatus)?s.deferred++:iD.has(n.currentStatus)?s.archived++:s.other++;return s}async function Dx(t){var p;const s=Re(ge,`clarity_insights/${t}/weekly`),n=Ge(s,Nt("weekStart","desc"),Tt(tD)),r=await Ze(n);if(r.empty)return[];const a=r.docs.map(c=>c.data()),o=new Set;for(const c of a)for(const u of((p=c.aiAnalysis)==null?void 0:p.recommendations)??[]){const x=u.ticketId??u.notionPageId;x&&o.add(x)}const i=Array.from(o),d=await Promise.all(i.map(async c=>{const u=await ps(ut(ge,"tickets",c));if(!u.exists())return[c,{status:"Missing",displayId:void 0}];const x=u.data();return[c,{status:x.status??"Unknown",displayId:x.displayId}]})),m=new Map(d);return a.map(c=>{var h,b,f;const u=((h=c.aiAnalysis)==null?void 0:h.recommendations)??[],x=[];for(const g of u){const y=g.ticketId??g.notionPageId;if(!y)continue;const j=m.get(y)??{status:"Missing",displayId:void 0};
400x.push({ticketId:y,title:g.title,description:g.description,priority:g.priority,estimatedCredits:g.estimatedCredits,estimatedCreditsMin:g.estimatedCreditsMin,estimatedCreditsMax:g.estimatedCreditsMax,behaviorEvidence:g.behaviorEvidence??[],suggestedFix:g.suggestedFix,affectedFiles:g.affectedFiles??[],affectedPages:g.affectedPages??[],currentStatus:j.status,ticketDisplayId:j.displayId})}return{weekStart:c.weekStart,weekEnd:c.weekEnd,gateOutcome:c.gateOutcome,reason:c.reason,aggregate:c.aggregate,summary:((b=c.aiAnalysis)==null?void 0:b.summary)??"",weekImpact:((f=c.aiAnalysis)==null?void 0:f.weekImpact)??[],tickets:x,ticketCounts:fy(x)}})}function Mx(t){return t.behaviorEvidence.reduce((s,n)=>s+(typeof n.value=="number"?n.value:0),0)}function cD(t){const s=t.slice(0,sD),n=[];for(const r of s)for(const a of r.tickets)a.currentStatus==="AI Review"&&n.push({...a,weekStart:r.weekStart,weekEnd:r.weekEnd});return n.sort((r,a)=>{const o=Rx[a.priority]-Rx[r.priority];if(o!==0)return o;const i=Mx(a)-Mx(r);return i!==0?i:a.weekStart.localeCompare(r.weekStart)}),n.slice(0,nD)}function dD(){const[t,s]=l.useState([]),[n,r]=l.useState(null),[a,o]=l.useState([]),[i,d]=l.useState(!0),[m,p]=l.useState(null),[c,u]=l.useState(null);l.useEffect(()=>{(async()=>{try{const T=Re(ge,"clarity_clients"),k=Ge(T,Ve("active","==",!0)),I=(await Ze(k)).docs.map(A=>{var C,N,S,O,R,z;const E=A.data();return{id:A.id,name:E.name,domain:E.domain,active:E.active,lastSyncAt:((N=(C=E.lastSyncAt)==null?void 0:C.toDate)==null?void 0:N.call(C))||null,lastSyncStatus:E.lastSyncStatus||null,lastGenerationAt:((O=(S=E.lastGenerationAt)==null?void 0:S.toDate)==null?void 0:O.call(S))||null,lastSkipReason:E.lastSkipReason||null,lastSkipAt:((z=(R=E.lastSkipAt)==null?void 0:R.toDate)==null?void 0:z.call(R))||null}});s(I),I.length>0&&!n&&r(I[0].id)}catch(T){console.error("Error fetching clients:",T),p("Failed to load clients")}})()},[n]),l.useEffect(()=>{if(!n){o([]),d(!1);return}d(!0),(async()=>{try{const T=await Dx(n);o(T),p(null)}catch(T){console.error("Error fetching runs:",T),p("Failed to load run history")}finally{d(!1)}})()},[n]);const x=l.useCallback((v,T)=>{o(k=>k.map(w=>{if(!w.tickets.some(A=>A.ticketId===v))return w;const I=w.tickets.map(A=>A.ticketId===v?{...A,currentStatus:T}:A);return{...w,tickets:I,ticketCounts:fy(I)}}))},[]),h=l.useCallback(async v=>{try{u(v),await re("updateClarityTicketStatus",{ticketId:v,status:"Backlog"}),x(v,"Backlog")}catch(T){throw console.error("Error approving recommendation:",T),T}finally{u(null)}},[x]),b=l.useCallback(async v=>{try{u(v),await re("updateClarityTicketStatus",{ticketId:v,status:"Deferred"}),x(v,"Deferred")}catch(T){throw console.error("Error deferring recommendation:",T),T}finally{u(null)}},[x]),f=l.useCallback(async()=>{if(n){d(!0);try{const v=await Dx(n);o(v),p(null)}catch(v){console.error("Error refreshing:",v),p("Failed to refresh")}finally{d(!1)}}},[n]),g=t.find(v=>v.id===n)||null,y=a[0]??null,j=l.useMemo(()=>cD(a),[a]);return{clients:t,selectedClient:g,selectedClientId:n,setSelectedClientId:r,loading:i,error:m,actionLoading:c,runHistory:a,latestRun:y,topProposals:j,approveRecommendation:h,deferRecommendation:b,refresh:f}}const uD=8,mD={high:"bg-red-100 text-red-800",medium:"bg-yellow-100 text-yellow-800",low:"bg-green-100 text-green-800"},pD=()=>{const{clients:t,selectedClient:s,selectedClientId:n,setSelectedClientId:r,loading:a,error:o,actionLoading:i,runHistory:d,latestRun:m,topProposals:p,approveRecommendation:c,deferRecommendation:u,refresh:x}=dD(),h=s!=null&&s.lastSkipReason&&s.lastSkipAt&&s.lastSkipReason!=="insufficient_data"&&Date.now()-s.lastSkipAt.getTime()<uD*24*60*60*1e3?{reason:s.lastSkipReason,when:s.lastSkipAt}:null;return a&&d.length===0?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(fe,{className:"h-8 w-8 animate-spin text-gray-400"})}):e.jsxs("div",{className:"p-4 max-w-4xl mx-auto space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{className:"h-6 w-6 text-purple-500"}),e.jsx("h1",{className:"text-2xl font-bold",children:"AI Insights"})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(ke,{variant:"outline",size:"sm",onClick:x,disabled:a,children:[e.jsx(yt,{className:`h-4 w-4 mr-1 ${a?"animate-spin":""}`}),"Refresh"]})})]}),t.length>1&&e.jsxs(nn,{value:n||"",onValueChange:r,children:[e.jsx(an,{className:"w-full",children:e.jsx(rn,{placeholder:"Select client"})}),e.jsx(on,{children:t.map(b=>e.jsxs(cs,{value:b.id,children:[b.name," (",b.domain,")"]},b.id))})]}),o&&e.jsx(jt,{className:"border-red-200 bg-red-50",children:e.jsx(vt,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-2 text-red-600",children:[e.jsx(Dt,{className:"h-5 w-5"}),e.jsx("span",{children:o})]})})}),h&&e.jsx(xD,{skip:h}),!a&&d.length===0&&e.jsx(jt,{children:e.jsxs(vt,{className:"p-8 text-center",children:[e.jsx(Fr,{className:"h-12 w-12 mx-auto text-gray-300 mb-4"}),e.jsx("h2",{className:"text-lg font-semibold text-gray-600",children:"No weekly runs yet"}),e.jsx("p",{className:"text-gray-400 mt-2",children:"Recommendations are generated Mondays at 6am PST. Daily metrics are still being collected in the background."})]})}),d.length>0&&e.jsx(hD,{proposals:p,actionLoading:i,onApprove:c,onDefer:u}),m&&e.jsx(fD,{run:m,clientName:s==null?void 0:s.name}),d.length>0&&e.jsx(gD,{runs:d,actionLoading:i,onApprove:c,onDefer:u})]})},xD=({skip:t})=>
400{const s=t.reason==="backlog"?"This Monday's run was paused â too many open AI tickets. Triage existing recommendations to unblock the next batch.":"This Monday's run was skipped â generation cadence not yet reached. The next batch will land on the configured schedule.";return e.jsx(jt,{className:"border-amber-200 bg-amber-50",children:e.jsx(vt,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Dt,{className:"h-5 w-5 text-amber-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-amber-900",children:s}),e.jsxs("div",{className:"text-xs text-amber-700 mt-1",children:["Logged ",t.when.toLocaleString()]})]})]})})})},hD=({proposals:t,actionLoading:s,onApprove:n,onDefer:r})=>e.jsxs(jt,{className:"border-purple-200",children:[e.jsx(fs,{children:e.jsxs(vs,{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5 text-purple-500"}),"Top Proposals",e.jsx(Wt,{className:"ml-2",children:t.length}),e.jsx("span",{className:"text-xs font-normal text-gray-500 ml-2",children:"ranked across recent runs · pitch these first"})]})}),e.jsx(vt,{children:t.length===0?e.jsx("p",{className:"text-gray-500 text-center py-6",children:"No pending proposals. New recommendations land Mondays at 6am PST."}):e.jsx("div",{className:"space-y-3",children:t.map(a=>e.jsx(gy,{proposal:a,isLoading:s===a.ticketId,onApprove:()=>n(a.ticketId),onDefer:()=>r(a.ticketId),showWeekTag:!0},a.ticketId))})})]}),fD=({run:t,clientName:s})=>e.jsxs(e.Fragment,{children:[e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(vs,{children:s??"Latest Run"}),e.jsxs(Wt,{variant:"outline",children:[t.aggregate.weekEnd," â ",t.weekStart]})]})}),e.jsx(vt,{children:t.gateOutcome==="insufficient-data"?e.jsxs("div",{className:"flex items-start gap-2 text-amber-700",children:[e.jsx(Dt,{className:"h-5 w-5 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Latest run had insufficient data to generate recommendations"}),t.reason&&e.jsx("div",{className:"text-sm text-gray-500 mt-1",children:t.reason})]})]}):e.jsx("p",{className:"text-gray-600",children:t.summary})})]}),e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsxs(vs,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5"}),"7-Day Totals",e.jsxs(Wt,{variant:"secondary",className:"ml-2",children:[t.aggregate.daysWithData," of ",t.aggregate.daysScanned," days"]})]})}),e.jsx(vt,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ci,{label:"Sessions",value:t.aggregate.totals.sessions,series:t.aggregate.perDayTrend.sessions,color:"#2563eb"}),e.jsx(Ci,{label:"Rage Clicks",value:t.aggregate.totals.rageClicks,series:t.aggregate.perDayTrend.rageClicks,color:"#dc2626"}),e.jsx(Ci,{label:"Dead Clicks",value:t.aggregate.totals.deadClicks,series:t.aggregate.perDayTrend.deadClicks,color:"#dc2626"}),e.jsx(Ci,{label:"JS Errors",value:t.aggregate.totals.jsErrors,series:t.aggregate.perDayTrend.jsErrors,color:"#dc2626"})]})})]}),t.aggregate.perPage.length>0&&e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsxs(vs,{className:"flex items-center gap-2",children:[e.jsx(Xo,{className:"h-5 w-5"}),"Top Problem Pages"]})}),e.jsx(vt,{children:e.jsx(ND,{pages:t.aggregate.perPage.slice(0,8),newPages:t.aggregate.newProblemPages})})]}),t.weekImpact.length>0&&e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsxs(vs,{className:"flex items-center gap-2",children:[e.jsx(Ow,{className:"h-5 w-5"}),"Code Changes Impact"]})}),e.jsx(vt,{children:e.jsx("div",{className:"space-y-3",children:t.weekImpact.map((n,r)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-gray-50 rounded-lg",children:[e.jsx("div",{className:`mt-0.5 ${n.improved?"text-green-500":"text-yellow-500"}`,children:n.improved?e.jsx(kt,{className:"h-5 w-5"}):e.jsx(Dt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:n.changeDescription}),e.jsx("div",{className:"text-sm text-gray-500",children:n.metrics})]})]},r))})})]})]}),gD=({runs:t,actionLoading:s,onApprove:n,onDefer:r})=>e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsxs(vs,{className:"flex items-center gap-2",children:[e.jsx(og,{className:"h-5 w-5"}),"Run History",e.jsx(Wt,{variant:"secondary",className:"ml-2",children:t.length})]})}),e.jsx(vt,{children:e.jsx("div",{className:"space-y-2",children:t.map((a,o)=>e.jsx(bD,{run:a,defaultExpanded:o===0,actionLoading:s,onApprove:n,onDefer:r},a.weekStart))})})]}),bD=({run:t,defaultExpanded:s,actionLoading:n,onApprove:r,onDefer:a})=>{const[o,i]=l.useState(s);return e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>i(!o),className:"w-full p-3 bg-white hover:bg-gray-50 transition-colors flex items-center gap-3 text-left",children:[o?e.jsx(Ot,{className:"h-4 w-4 flex-shrink-0 text-gray-400"}):e.jsx(Rt,{className:"h-4 w-4 flex-shrink-0 text-gray-400"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-medium text-sm",children:["Week of ",t.aggregate.weekEnd," â ",t.weekStart]}),e.jsx(yD,{run:t})]}),t.gateOutcome==="generated"&&t.tickets.length>0&&e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:e.jsx(jD,{counts:t.ticketCounts})}),t.gateOutcome==="insufficient-data"&&t.reason&&e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:t.reason})]})]}),o&&e.jsxs("div",{className:"border-t bg-gray-50 p-4 space-y-4",children:[t.gateOutcome==="generated"&&e.jsxs(e.Fragment,{children:[t.summary&&e.jsx("div",{className:"text-sm text-gray-700",children:t.summary}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 text-sm",children:[e.jsx(Si,{label:"Sessions",value:t.aggregate.totals.sessions}),e.jsx(Si,{label:"Rage",value:t.aggregate.totals.rageClicks}),e.jsx(Si,{label:"Dead",value:t.aggregate.totals.deadClicks}),e.jsx(Si,{label:"JS Err",value:t.aggregate.totals.jsErrors})]}),t.tickets.length>0?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-xs font-medium text-gray-500 uppercase",children:["Tickets created (",t.tickets.length,")"]}),t.tickets.map(d=>e.jsx(gy,{proposal:d,isLoading:n===d.ticketId,onApprove:()=>r(d.ticketId),onDefer:()=>a(d.ticketId),compact:!0},d.ticketId))]}):e.jsx("div",{className:"text-sm text-gray-500",children:"No tickets generated this run."})]}),t.gateOutcome==="insufficient-data"&&e.jsxs("div",{className:"text-sm text-gray-600",children:["Run produced no tickets â data thresholds were not met.",t.reason&&e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:t.reason})]})]})]})},yD=({run:t})=>t.gateOutcome==="insufficient-data"?e.jsx(Wt,{variant:"outline",className:"text-amber-700 border-amber-300",children:"Insufficient data"}):e.jsxs(Wt,{variant:"outline",className:"text-purple-700 border-purple-300",children:["Generated ",t.ticketCounts.total]}),jD=({counts:t})=>{const s=[];return t.pending&&s.push(`${t.pending}
400 pending`),t.approved&&s.push(`${t.approved} approved`),t.completed&&s.push(`${t.completed} done`),t.deferred&&s.push(`${t.deferred} deferred`),t.archived&&s.push(`${t.archived} archived`),t.other&&s.push(`${t.other} other`),e.jsx(e.Fragment,{children:s.join(" · ")||"no tickets"})},Si=({label:t,value:s})=>e.jsxs("div",{className:"bg-white rounded p-2 text-center",children:[e.jsx("div",{className:"font-bold",children:s.toLocaleString()}),e.jsx("div",{className:"text-xs text-gray-500",children:t})]}),gy=({proposal:t,isLoading:s,onApprove:n,onDefer:r,showWeekTag:a,compact:o})=>{const i=t.estimatedCreditsMin&&t.estimatedCreditsMax?`${t.estimatedCreditsMin}â${t.estimatedCreditsMax} credits`:t.estimatedCredits?`${t.estimatedCredits} credits`:null,d=t.currentStatus==="AI Review",m=a&&"weekStart"in t?t.weekStart:null;return e.jsxs("div",{className:"border-l-4 border-purple-500 bg-white rounded-lg p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx(Wt,{className:mD[t.priority],children:t.priority.toUpperCase()}),i&&e.jsx(Wt,{variant:"secondary",children:i}),e.jsx(vD,{status:t.currentStatus}),t.ticketDisplayId&&e.jsx("span",{className:"text-xs text-gray-400 font-mono",children:t.ticketDisplayId}),m&&e.jsxs("span",{className:"text-xs text-gray-400 ml-auto",children:["from week of ",m]})]}),e.jsx("h3",{className:o?"font-medium mb-1":"font-semibold text-lg mb-2",children:t.title}),e.jsx("p",{className:`text-gray-600 ${o?"text-sm mb-2":"mb-3"}`,children:t.description}),t.behaviorEvidence.length>0&&e.jsxs("div",{className:"bg-gray-50 rounded p-2 mb-2 text-sm",children:[e.jsx("span",{className:"font-medium text-gray-700",children:"Evidence: "}),t.behaviorEvidence.map((p,c)=>e.jsxs("span",{className:"text-gray-600 mr-3 inline-flex items-center gap-1",children:[p.metric,": ",e.jsx("strong",{children:p.value}),p.trend==="up"&&e.jsx(Bl,{className:"h-3 w-3 text-red-500"}),p.trend==="down"&&e.jsx($l,{className:"h-3 w-3 text-green-500"})]},c))]}),!o&&t.affectedPages.length>0&&e.jsxs("div",{className:"text-sm text-gray-500 mb-3",children:[e.jsx("strong",{children:"Pages:"})," ",t.affectedPages.join(", ")]}),o&&t.affectedPages.length>0&&e.jsx("div",{className:"text-xs text-gray-500 mb-2",children:t.affectedPages.join(", ")}),d&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ke,{onClick:n,disabled:s,size:o?"sm":"default",className:"flex-1",children:[s?e.jsx(fe,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(kt,{className:"h-4 w-4 mr-1"}),"Send for Approval"]}),e.jsxs(ke,{variant:"outline",onClick:r,disabled:s,size:o?"sm":"default",className:"flex-1",children:[s?e.jsx(fe,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(mt,{className:"h-4 w-4 mr-1"}),"Defer"]})]})]})},vD=({status:t})=>{const s=t==="AI Review"?"bg-purple-100 text-purple-800":t==="Backlog"||t==="In Progress"?"bg-blue-100 text-blue-800":t==="Complete"?"bg-green-100 text-green-800":t==="Deferred"?"bg-yellow-100 text-yellow-800":t==="Archived"?"bg-gray-200 text-gray-600":t==="Missing"?"bg-red-100 text-red-700":"bg-gray-100 text-gray-700";return e.jsx(Wt,{className:s,children:t})},wD=({values:t,color:s,width:n=80,height:r=24})=>{if(!t||t.length===0)return null;const a=Math.max(...t,1),o=Math.min(...t,0),i=a-o||1,d=t.length>1?n/(t.length-1):0,m=t.map((p,c)=>{const u=c*d,x=r-(p-o)/i*r;return`${u.toFixed(1)},${x.toFixed(1)}`}).join(" ");return e.jsx("svg",{width:n,height:r,viewBox:`0 0 ${n} ${r}`,className:"mt-1 mx-auto block","aria-hidden":"true",children:e.jsx("polyline",{fill:"none",stroke:s,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",points:m})})},Ci=({label:t,value:s,series:n,color:r="#6b7280"})=>e.jsxs("div",{className:"text-center p-3 bg-gray-50 rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold",children:s.toLocaleString()}),e.jsx("div",{className:"text-sm text-gray-500",children:t}),n&&n.length>0&&e.jsx(wD,{values:n,color:r})]}),ND=({pages:t,newPages:s})=>{const n=new Set(s);return e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-2 font-medium text-gray-500 border-b pb-2 mb-2",children:[e.jsx("div",{className:"col-span-7",children:"Page"}),e.jsx("div",{className:"col-span-1 text-right",children:"Rage"}),e.jsx("div",{className:"col-span-1 text-right",children:"Dead"}),e.jsx("div",{className:"col-span-1 text-right",children:"JS"}),e.jsx("div",{className:"col-span-2 text-right",children:"Trend"})]}),t.map(r=>e.jsxs("div",{className:"grid grid-cols-12 gap-2 py-2 border-b last:border-0 items-center",children:[e.jsxs("div",{className:"col-span-7 truncate flex items-center gap-2",children:[e.jsx("span",{className:"truncate",title:r.url,children:r.url}),n.has(r.url)&&e.jsx(Wt,{variant:"outline",className:"border-purple-300 text-purple-600 text-xs",children:"NEW"})]}),e.jsx("div",{className:"col-span-1 text-right",children:r.rageClicks||"â"}),e.jsx("div",{className:"col-span-1 text-right",children:r.deadClicks||"â"}),e.jsx("div",{className:"col-span-1 text-right",children:r.jsErrors||"â"}),e.jsx("div",{className:"col-span-2 text-right",children:e.jsx(kD,{trend:r.trend})})]},r.url))]})},kD=({trend:t})=>t==="up"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-red-600",children:[e.jsx(Bl,{className:"h-3 w-3"})," up"]}):t==="down"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-green-600",children:[e.jsx($l,{className:"h-3 w-3"})," down"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-gray-500",children:[e.jsx(Wl,{className:"h-3 w-3"})," flat"]});function SD(t,s){const n=[],r=new Date(t+"T00:00:00"),a=new Date(s+"T00:00:00");for(;r<=a;)n.push(r.toISOString().split("T")[0]),r.setDate(r.getDate()+1);return n}function CD(t){const s=new Set;for(const n of t)for(const r of SD(n.startDate,n.endDate))s.add(r);return Array.from(s).sort()}function TD({onBack:t,onLogoClick:s}){const[n,r]=l.useState([]),[a,o]=l.useState(!0),[i,d]=l.useState(!1),[m,p]=l.useState(""),[c,u]=l.useState(""),[x,h]=l.useState(""),[b,f]=l.useState(""),[g,y]=l.useState([]);l.useEffect(()=>{const A=localStorage.getItem("capacityCalendar.departmentsList");if(A)try{y(JSON.parse(A))}catch{}j()},[]);async function j(){try{const A=ut(ge,"teamSettings","capacity"),E=await ps(A);if(E.exists()){const C=E.data();r(C.vacationDays||[])}}catch(A){console.error("Failed to load vacation days:",A)}finally{o(!1)}}async function v(A){d(!0);try{const E=CD(A),C=ut(ge,"teamSettings","capacity");await qr(C,{vacationDays:A,blackoutDates:E},{merge:!0}),r(A)}catch(E){console.error("Failed to save vacation days:",E)}finally{d(!1)}}function T(){if(!m.trim()||!x)return;const A={id:crypto.randomUUID(),personName:m.trim(),department:c,startDate:x,endDate:b||x,createdAt:new Date().toISOString()},E=[...n,A];v(E),p(""),u(""),h(""),f("")}function k(A){const E=n.filter(C=>C.id!==A);v(E)}function w(A,E){const C=new Date(A+"T00:00:00"),N=new Date(E+"T00:00:00"),S=O=>O.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return A===E?S(C):`${S(C)} â ${S(N)}`}const I=[...n].sort((A,E)=>A.startDate.localeCompare(E.startDate));return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs(st.button,{onClick:t,className:"flex items-center gap-2 text-muted-foreground hover:text-foreground mb-4 transition-colors",whileTap:{scale:.95},children:[e.jsx(dt,{style:{width:"20px",height:"20px"}}),e.jsx("span",{children:"Back to Admin"})]}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground mb-2 flex items-center gap-2",children:[e.jsx(pg,{style:{width:"28px",height:"28px"}}),"Vacation & Travel Days"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage team vacation & blackout dates"})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mb-6",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},children:[e.jsx("h3",{className:"font-semibold text-foreground mb-3",children:"Add Vacation"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm text-muted-foreground mb-1",children:"Person Name"}),e.jsx("input",{type:"text",value:m,onChange:A=>p(A.target.value),placeholder:"e.g. Jody",className:"w-full bg-background border border-border rounded-md px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary",style:{borderRadius:"var(--radius-sm)"}})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm text-muted-foreground mb-1",children:"Department"}),e.jsxs("select",{value:c,onChange:A=>u(A.target.value),className:"w-full bg-background border border-border rounded-md px-3 py-2 text-foreground focus:outline-none focus:ring-2 focus:ring-primary",style:{borderRadius:"var(--radius-sm)"},children:[e.jsx("option",{value:"",children:"All Departments"}),g.map(A=>e.jsx("option",{value:A,children:A},A))]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm text-muted-foreground mb-1",children:"Start Date"}),e.jsx("input",{type:"date",value:x,onChange:A=>h(A.target.value),className:"w-full bg-background border border-border rounded-md px-3 py-2 text-foreground focus:outline-none focus:ring-2 focus:ring-primary",style:{borderRadius:"var(--radius-sm)"}})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm text-muted-foreground mb-1",children:"End Date"}),e.jsx("input",{type:"date",value:b,onChange:A=>f(A.target.value),min:x,placeholder:x,className:"w-full bg-background border border-border rounded-md px-3 py-2 text-foreground focus:outline-none focus:ring-2 focus:ring-primary",style:{borderRadius:"var(--radius-sm)"}})]})]}),e.jsxs(st.button,{onClick:T,disabled:!m.trim()||!x||i,className:"w-full bg-primary text-primary-foreground rounded-md px-4 py-2 font-medium flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-primary/90 transition-colors",style:{borderRadius:"var(--radius-sm)"},whileTap:{scale:.98},children:[i?e.jsx(fe,{className:"animate-spin",style:{width:"18px",height:"18px"}}):e.jsx(Ut,{style:{width:"18px",height:"18px"}}),"Add Vacation"]})]})]}),a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(fe,{className:"animate-spin text-muted-foreground",style:{width:"32px",height:"32px"}})}):I.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No vacation days scheduled"}):e.jsx("div",{className:"space-y-2",children:I.map(A=>e.jsxs("div",{className:"bg-card border border-border rounded-lg p-3 flex items-center justify-between",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-foreground",children:A.personName}),e.jsx("div",{className:"text-sm text-muted-foreground",children:w(A.startDate,A.endDate)}),A.department&&e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:A.department})]}),e.jsx(st.button,{onClick:()=>k(A.id),disabled:i,className:"flex-shrink-0 text-destructive hover:text-destructive/80 p-1 disabled:opacity-50 transition-colors",whileTap:{scale:.9},children:e.jsx(zs,{style:{width:"18px",height:"18px"}})})]},A.id))})]})]})}const Px={position:"absolute",left:12,top:"50%",transform:"translateY(-50%)",width:16,height:16,pointerEvents:"none"},Lx={paddingLeft:36,paddingRight:16},zx={maxHeight:240,overflowY:"auto",borderRadius:12};function AD({onBack:t,onLogoClick:s}){const n=Qo(),{token:r}=pt(),[a,o]=l.useState([]),[i,d]=l.useState(!0),[m,p]=l.useState(null),[c,u]=l.useState(""),[x,h]=l.useState(!1),[b,f]=l.useState([]),[g,y]=l.useState(!1),[j,v]=l.useState(null),[T,k]=l.useState(""),[w,I]=l.useState(!1);l.useEffect(()=>{(async()=>{try{const S=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getNotionClients");if(!S.ok)throw new Error(`HTTP error! Status: ${S.status}`);const O=await S.json();O.success&&o(O.clients)}catch(S){console.error("Failed to fetch clients:",S)}finally{d(!1)}})()},[]),l.useEffect(()=>{if(!m){f([]),v(null),k("");return}(async()=>{y(!0);try{if(!m.name)throw new Error("Selected client name is missing");const S=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getProjectsByClients",{method:"POST",headers:as(r),body:JSON.stringify({clientNames:[m.name]})});if(!S.ok)throw new Error(`HTTP error! Status: ${S.status}`);const O=await S.json();f(O.projects||[])}catch(S){console.error("Failed to fetch projects:",S)}finally{y(!1)}})()},[m,r]);const A=l.useMemo(()=>{const N=a.filter(O=>typeof O.name=="string"&&O.name.length>0);if(!c.trim())return N;const S=c.toLowerCase();return N.filter(O=>O.name.toLowerCase().includes(S))},[a,c]),E=l.useMemo(()=>{const N=b.filter(O=>typeof O.name=="string"&&O.name.length>0);if(!T.trim())return N;const S=T.toLowerCase();return N.filter(O=>O.name.toLowerCase().includes(S))},[b,T]),C=()=>{j&&n(`/project-presentation/${j.id}`)};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("button",{onClick:t,className:"flex items-center gap-2 text-muted-foreground hover:text-foreground mb-6 transition-colors",children:[e.jsx(dt,{style:{width:"20px",height:"20px"}}),e.jsx("span",{children:"Back to Admin"})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-foreground mb-2",style:{fontSize:24,fontWeight:700},children:"Project Presentation"}),e.jsx("p",{className:"text-muted-foreground",children:"Select a client and project to present tickets"})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("label",{className:"block text-sm font-semibold text-foreground mb-2",children:"Client"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"text-muted-foreground",style:Px}),e.jsx("input",{type:"text",placeholder:i?"Loading clients...":"Search clients...",value:c,onChange:N=>{u(N.target.value),h(!0),m&&N.target.value!==m.name&&(p(null),v(null),k(""))},onFocus:()=>h(!0),className:"w-full py-3 bg-card border border-border rounded-xl text-foreground placeholder:text-muted-foreground",style:Lx,disabled:i})]}),x&&A.length>0&&!m&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-card border border-border shadow-lg",style:zx,
400children:A.map(N=>e.jsx("button",{onClick:()=>{p(N),u(N.name),h(!1)},className:"w-full text-left px-4 py-3 hover:bg-accent transition-colors",children:e.jsx("div",{className:"font-medium text-foreground",children:N.name})},N.id))})]})]}),m&&e.jsxs("div",{className:"mb-6",children:[e.jsx("label",{className:"block text-sm font-semibold text-foreground mb-2",children:"Project"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Pt,{className:"text-muted-foreground",style:Px}),e.jsx("input",{type:"text",placeholder:g?"Loading projects...":"Search projects...",value:T,onChange:N=>{k(N.target.value),I(!0),j&&N.target.value!==j.name&&v(null)},onFocus:()=>I(!0),className:"w-full py-3 bg-card border border-border rounded-xl text-foreground placeholder:text-muted-foreground",style:Lx,disabled:g})]}),w&&E.length>0&&!j&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-card border border-border shadow-lg",style:zx,children:E.map(N=>e.jsx("button",{onClick:()=>{v(N),k(N.name),I(!1)},className:"w-full text-left px-4 py-3 hover:bg-accent transition-colors",children:e.jsx("div",{className:"font-medium text-foreground",children:N.name})},N.id))})]})]}),e.jsx("button",{onClick:C,disabled:!j,className:`w-full py-4 rounded-xl font-semibold text-lg transition-all ${j?"bg-primary text-primary-foreground hover:bg-primary/90 shadow-md":"bg-muted text-muted-foreground cursor-not-allowed"}`,children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(hg,{style:{width:"20px",height:"20px"}}),"Open Presentation"]})})]})]})}const Ox={"Quick Fix":{bg:"bg-green-50",border:"border-green-200",text:"text-green-700",badge:"bg-green-100 text-green-800"},"Small Task":{bg:"bg-yellow-50",border:"border-yellow-200",text:"text-yellow-700",badge:"bg-yellow-100 text-yellow-800"},"Medium Task":{bg:"bg-orange-50",border:"border-orange-200",text:"text-orange-700",badge:"bg-orange-100 text-orange-800"},"Large Task":{bg:"bg-red-50",border:"border-red-200",text:"text-red-700",badge:"bg-red-100 text-red-800"}},ED={Backlog:"bg-gray-100 text-gray-600","To Do":"bg-blue-100 text-blue-700","In Progress":"bg-yellow-100 text-yellow-700","In Review":"bg-purple-100 text-purple-700","Client Approval":"bg-cyan-100 text-cyan-700",Complete:"bg-green-100 text-green-700",Done:"bg-green-100 text-green-700"},ID=({title:t,description:s,tickets:n,ticketCount:r,totalCredits:a,color:o,onNext:i,onBack:d,nextLabel:m})=>{const[p,c]=ee.useState(new Set),u=Ox[t]||Ox["Quick Fix"],x=h=>{c(b=>{const f=new Set(b);return f.has(h)?f.delete(h):f.add(h),f})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8 mt-12",children:[e.jsx("div",{className:`inline-block px-4 py-1.5 rounded-full text-sm font-semibold mb-4 ${u.badge}`,children:t}),e.jsx("h1",{className:"mb-2 text-foreground",style:{fontSize:"24px",fontWeight:700},children:t}),e.jsx("p",{className:"text-muted-foreground mb-4",children:s}),e.jsxs("div",{className:"flex justify-center gap-4",children:[e.jsxs("div",{className:"w-24 h-24 bg-card border border-border rounded-xl p-3 flex flex-col items-center justify-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"TICKETS"}),e.jsx("div",{className:"text-2xl font-bold text-foreground",children:r})]}),e.jsxs("div",{className:"w-24 h-24 bg-card border border-border rounded-xl p-3 flex flex-col items-center justify-center",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"CREDITS"}),e.jsx("div",{className:"text-2xl font-bold text-primary",children:a})]})]})]}),e.jsx("div",{className:"space-y-3",children:n.map((h,b)=>{const f=p.has(b),g=ED[h.status]||"bg-gray-100 text-gray-600";return e.jsxs("div",{onClick:()=>x(b),className:`bg-card border rounded-2xl p-4 cursor-pointer transition-all duration-300 ${f?`${u.border} shadow-lg scale-[1.02]`:"border-border hover:border-primary/30 hover:shadow-sm"}`,style:{transform:f?"scale(1.02)":"scale(1)",transition:"all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.ticketNumber&&e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:h.ticketNumber}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${g}`,children:Wr(h.status)})]}),e.jsx("h3",{className:"font-semibold text-foreground",children:h.name})]}),e.jsxs("div",{className:"text-right flex-shrink-0",children:[e.jsx("div",{className:"text-lg font-bold text-primary",children:h.maxCredits||0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"credits"})]})]}),f&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-border",children:[h.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground mb-3 [&_h1]:text-base [&_h1]:font-bold [&_h1]:text-foreground [&_h1]:mt-3 [&_h1]:mb-1 [&_h2]:text-sm [&_h2]:font-bold [&_h2]:text-foreground [&_h2]:mt-3 [&_h2]:mb-1 [&_h3]:text-sm [&_h3]:font-semibold [&_h3]:text-foreground [&_h3]:mt-2 [&_h3]:mb-1 [&_p]:my-1 [&_ul]:my-1 [&_ol]:my-1 [&_li]:my-0.5 [&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:pl-3 [&_blockquote]:italic [&_code]:bg-muted [&_code]:px-1 [&_code]:rounded [&_a]:text-primary [&_a]:underline",children:e.jsx(Ta,{children:h.description})}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[h.dueDate&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Due: "}),e.jsx("span",{className:"text-foreground",children:new Date(h.dueDate).toLocaleDateString()})]}),h.rushOrder&&e.jsx("div",{children:e.jsx("span",{className:"inline-block px-2 py-0.5 bg-red-100 text-red-700 rounded-full text-xs font-semibold",children:"RUSH ORDER"})})]})]})]}
400,h.id)})}),e.jsx("div",{className:"h-24"}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4 shadow-lg z-20",children:e.jsxs("div",{className:"max-w-4xl mx-auto flex gap-4",children:[d&&e.jsx("button",{onClick:d,className:"flex-1 bg-card border-2 border-border text-foreground px-6 py-3 rounded-xl font-semibold hover:bg-muted transition-colors shadow-sm",children:"â Back"}),e.jsx("button",{onClick:i,className:"flex-1 bg-primary text-primary-foreground px-6 py-3 rounded-xl font-semibold hover:bg-primary/90 transition-colors shadow-md",children:m})]})})]})},$x="https://us-central1-bucky-app-355a3.cloudfunctions.net",RD=({projectId:t,clientId:s,categories:n,selectedRecs:r,setSelectedRecs:a,totals:o,onBack:i,paymentPlan:d,setPaymentPlan:m,paymentCaptured:p,setPaymentCaptured:c,creditPriceCents:u,currency:x="usd"})=>{const[h,b]=l.useState(!1),f=o.deferred===0&&o.selected>0,g=async()=>{if(!d||p||h)return;if(!t||!s){ce.error("Missing project or client info â refresh and try again.");return}if(o.selected<1){ce.error("Select at least one ticket to continue.");return}b(!0);const T=new URLSearchParams(window.location.search).get("token"),k=T?`&token=${encodeURIComponent(T)}`:"",w=`${window.location.origin}/project-presentation/${t}`,I=`${w}?payment=success&sessionId={CHECKOUT_SESSION_ID}${k}`,A=`${w}?payment=cancelled${k}`;try{if(d==="upfront"){const E=await fetch(`${$x}/createCreditPurchaseSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:s,projectId:t,quantity:o.selected,forceCheckout:!0,applyUpfrontDiscount:f,successUrl:I,cancelUrl:A})}),C=await E.json();if(!E.ok)throw new Error((C==null?void 0:C.error)||"Failed to start checkout");if(C.checkoutUrl)window.location.href=C.checkoutUrl;else throw new Error("Stripe did not return a checkout URL")}else{const C=Math.max(1,Math.ceil(o.selected/10)),N=await fetch(`${$x}/createCreditSubscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:s,projectId:t,creditsPerMonth:10,monthsLimit:C,successUrl:I,cancelUrl:A})}),S=await N.json();if(!N.ok)throw new Error((S==null?void 0:S.error)||"Failed to start subscription");if(S.checkoutUrl)window.location.href=S.checkoutUrl;else throw new Error("Stripe did not return a checkout URL")}}catch(E){ce.error(E.message||"Payment failed to start"),b(!1)}},y=(v,T)=>{const k=T.map((A,E)=>`${v}-${E}`),w=k.every(A=>r[A]),I={...r};k.forEach(A=>{I[A]=!w}),a(I)},j=v=>{a({...r,[v]:!r[v]})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8 mt-12",children:[e.jsx("h1",{className:"mb-2 text-foreground",style:{fontSize:"24px",fontWeight:700},children:"Let's Build Your Plan"}),e.jsx("p",{className:"text-muted-foreground",children:"Everything will be addressed eventually. Let's prioritize what to tackle first."})]}),n.map(v=>v.tickets.length>0&&e.jsx(ho,{title:v.title.toUpperCase(),category:v.key,recommendations:v.tickets,selectedRecs:r,onToggleCategory:y,onToggleRecommendation:j},v.key)),e.jsxs("div",{className:"bg-card border-2 border-primary rounded-2xl p-6 text-center shadow-sm",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-1 uppercase tracking-wide",children:"SELECTED WORK"}),e.jsxs("div",{className:"text-4xl font-bold text-primary mb-1",children:[o.selected," credits"]}),o.deferred>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["(",o.deferred," credits deferred)"]})]}),e.jsx(my,{selectedCredits:o.selected,paymentPlan:d,setPaymentPlan:m,onCapturePayment:g,loading:h,paymentCaptured:p,setPaymentCaptured:c,creditPriceCents:u,currency:x,allItemsSelected:f}),e.jsx("div",{className:"h-24"}),e.jsx("div",{className:"fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4 shadow-lg z-20 print:hidden",children:e.jsx("div",{className:"max-w-4xl mx-auto",children:e.jsx("button",{onClick:i,className:"w-full bg-card border-2 border-border text-foreground px-6 py-3 rounded-xl font-semibold hover:bg-muted transition-colors shadow-sm",children:"â Back"})})})]})},DD=["Quick Fix","Small Task","Medium Task","Large Task"],MD={"Quick Fix":"Small adju
400stments and quick wins that can be completed rapidly.","Small Task":"Focused tasks requiring moderate effort and planning.","Medium Task":"Substantial work items that require significant development time.","Large Task":"Major initiatives requiring extensive planning and development."};function Bx(t){return!t||t<=4?"Quick Fix":t<=12?"Small Task":t<=30?"Medium Task":"Large Task"}const PD={usd:"$",cad:"CA$",eur:"â¬"};function LD(t,s){return`${PD[s.toLowerCase()]||"$"}${t.toLocaleString()}`}const zD=()=>{const{projectId:t}=zl(),[s,n]=Zo(),{token:r}=pt(),[a,o]=l.useState([]),[i,d]=l.useState(!0),[m,p]=l.useState(null),[c,u]=l.useState(1),[x,h]=l.useState({}),[b,f]=l.useState(!1),[g,y]=l.useState(null),[j,v]=l.useState(!1),[T,k]=l.useState(null),[w,I]=l.useState("usd"),[A,E]=l.useState(null),C=s.get("token"),N=!!C;l.useEffect(()=>{if(!t)return;if(!N&&!r){d(!1),p("This presentation link is missing access credentials. Please open the most recent email or sign in to view it.");return}(async()=>{try{d(!0),p(null);let W=[],_=null,G=!0;for(;G;){const H={projectId:t,pageSize:100};_&&(H.startCursor=_),N&&(H.token=C);const Z=N?"https://us-central1-bucky-app-355a3.cloudfunctions.net/getPublicProjectPresentation":"https://us-central1-bucky-app-355a3.cloudfunctions.net/getTicketsByProject",Q=N?{"Content-Type":"application/json"}:as(r),K=await fetch(Z,{method:"POST",headers:Q,body:JSON.stringify(H)});if(!K.ok)throw K.status===401&&N?new Error("This presentation link is invalid or has expired. Please request a new link."):new Error(`Failed: ${K.status}`);const X=await K.json();W=[...W,...(X==null?void 0:X.tickets)||[]],G=(X==null?void 0:X.hasMore)||!1,_=(X==null?void 0:X.nextCursor)||null,(X==null?void 0:X.creditPriceCents)!=null&&T===null&&k(X.creditPriceCents),X!=null&&X.currency&&I(String(X.currency).toLowerCase()),X!=null&&X.clientId&&!A&&E(X.clientId)}const B=["Deferred","Complete"];W=W.filter(H=>!B.includes(H.status)),o(W);const Y={};W.forEach(H=>{const Z=H.ticketComplexity||Bx(H.maxCredits);Y[Z]||(Y[Z]=[]),Y[Z].push(H)});const J={};Object.entries(Y).forEach(([H,Z])=>{const Q=H.toLowerCase().replace(/\s+/g,"-");Z.forEach((K,X)=>{J[`${Q}-${X}`]=!0})}),h(J)}catch(W){p(W.message||"Failed to load tickets")}finally{d(!1)}})()},[t,r,N,C]),l.useEffect(()=>{const F=s.get("payment");if(!F)return;F==="success"?(v(!0),ce.success("Payment received â generating your project.")):F==="cancelled"&&ce.info("Payment cancelled. Choose a plan to try again.");const W=new URLSearchParams(s);W.delete("payment"),W.delete("sessionId"),n(W,{replace:!0})},[]);const S=DD.map(F=>{const W=a.filter(_=>(_.ticketComplexity||Bx(_.maxCredits))===F).sort((_,G)=>{const B=parseInt((_.ticketNumber||"").replace(/\D/g,""),10)||0,Y=parseInt((G.ticketNumber||"").replace(/\D/g,""),10)||0;return B-Y});return{key:F.toLowerCase().replace(/\s+/g,"-"),title:F,description:MD[F],tickets:W}}).filter(F=>F.tickets.length>0),O=[...S.map(F=>F.title),"Price"],R=O.length;l.useEffect(()=>{if(R===0||c===R)return;(j||s.get("step")==="price")&&u(R)},[j,R]);const z=()=>{c<R&&(u(c+1),window.scrollTo(0,0))},D=()=>{c>1&&(u(c-1),window.scrollTo(0,0))},L=F=>{u(F),window.scrollTo(0,0)},$=()=>{let F=0,W=0;return S.forEach(_=>{_.tickets.forEach((G,B)=>{const Y=`${_.key}-${B}`,J=G.maxCredits||0;x[Y]?F+=J:W+=J})}),{selected:F,deferred:W}},q=()=>{window.print()},P=async()=>{if(!t){ce.error("Project ID is missing.");return}const F=window.prompt("Recipient email address:");if(!F)return;const W=window.prompt("Recipient name:","")||void 0;if(S.length===0){ce.error("No groups available to send in the email.");return}const _=$(),G=S.map(B=>({title:B.title,tickets:B.tickets.map((Y,J)=>({name:Y.name,credits:Y.maxCredits||0,selected:!!x[`${B.key}-${J}`]})).filter(Y=>Y.selected)})).filter(B=>B.tickets.length>0);f(!0);try{await re("sendProjectPresentationEmail",{projectId:t,recipientEmail:F,recipientName:W,ticketGroups:G,selectedCredits:_.selected,deferredCredits:_.deferred,creditPriceCents:T,currency:w}),ce.success(`Email sent to ${F}`)}catch(B){ce.error(B.message||"Failed to send email")}finally{f(!1)}};if(i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-16 w-16 border-b-4 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading presentation..."})]})});if(m)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center max-w-md mx-auto px-4",children:[e.jsx("h2",{className:"text-2xl font-bold mb-2 text-foreground",children:"Unable to Load Presentation"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:m})]})});if(a.length===0)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center max-w-md mx-auto px-4",children:[e.jsx("h2",{className:"text-2xl font-bold mb-2 text-foreground",children:"No Tickets Found"}),e.jsx("p",{className:"text-muted-foreground",children:"This project doesn't have any tickets yet."})]})});const U=$(),V=c===R,M=V?null:S[c-1];return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(Oa,{position:"top-right",richColors:!0}),e.jsx("div",{className:"bg-card border-b border-border sticky top-0 z-10 shadow-sm overflow-hidden print:static print:shadow-none",children:e.jsxs("div",{className:"max-w-4xl mx-auto px-4",children:[e.jsx("div",{style:{transform:V?"translateY(-100%)":"translateY(0)",transition:"transform 0.5s ease-in-out",opacity:V?0:1,height:V?0:"auto"},children:e.jsxs("div",{className:"py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Project Presentation"}),e.jsxs("div",{className:"flex items-center gap-2 print:hidden",children:[r&&e.jsxs("button",{onClick:P,disabled:b,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium transition-colors text-white disabled:opacity-50",style:{backgroundColor:"#22c55e"},title:"Send via email",children:[e.jsx(Tn,{size:16}),b?"Sending...":"Email"]}),e.jsxs("button",{onClick:q,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/90 transition-colors",title:"Print / Save as PDF",children:[e.jsx(fg,{size:16}),"Print"]})]})]}),e.jsx(uy,{currentStep:c,totalSteps:R,onStepClick:L,stepLabels:O})]})}),V&&e.jsxs("div",{style:{animation:"slideDown 0.5s ease-in-out"},className:"py-2 text-center",children:[e.jsx("div",{className:"text-muted-foreground mb-1 uppercase tracking-wide",style:{fontSize:"24px",fontWeight:"bold"},children:"ESTIMATED PRICE"}),e.jsxs("div",{className:"mb-0.5",style:{color:"#16a34a",fontWeight:"bold",fontSize:"48px"}
400,children:[LD(U.selected*((T??(w==="cad"?2e4:15e3))/100),w),e.jsx("span",{style:{fontSize:"24px",marginLeft:"8px"},children:w.toUpperCase()})]}),e.jsxs("div",{className:"text-sm text-primary font-semibold",children:[U.selected," credits"]})]})]})}),e.jsx("style",{children:` 401 @keyframes slideDown { 402 from { transform: translateY(-20px); opacity: 0; } 403 to { transform: translateY(0); opacity: 1; } 404 } 405 @media print { 406 .print\\:hidden { display: none !important; } 407 .print\\:static { position: static !important; } 408 .print\\:shadow-none { box-shadow: none !important; } 409 body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } 410 } 411 `}),e.jsxs("div",{className:"max-w-4xl mx-auto px-4 pb-8",children:[!V&&M&&e.jsx(ID,{title:M.title,description:M.description,tickets:M.tickets,ticketCount:M.tickets.length,totalCredits:M.tickets.reduce((F,W)=>F+(W.maxCredits||0),0),color:M.key,onNext:z,onBack:c>1?D:void 0,nextLabel:c<R-1?`Next: ${O[c]} â`:"Next: Pricing â"}),V&&e.jsx(RD,{projectId:t,clientId:A,categories:S.map(F=>({key:F.key,title:F.title,tickets:F.tickets.map(W=>({title:W.name,maxCredits:W.maxCredits||0}))})),selectedRecs:x,setSelectedRecs:h,totals:U,onBack:D,paymentPlan:g,setPaymentPlan:y,paymentCaptured:j,setPaymentCaptured:v,creditPriceCents:T,currency:w})]})]})},OD=["qa_needs_auth","qa_blocked","qa_needs_local","qa_failed"];function $D(){const[t,s]=l.useState([]),[n,r]=l.useState(!0),a=l.useRef(!0);return l.useEffect(()=>()=>{a.current=!1},[]),l.useEffect(()=>{const o=Ge(Re(ge,"aiRuns"),Nt("createdAt","desc"),Tt(100));return qt(o,d=>{if(!a.current)return;const m=d.docs.filter(p=>p.data().kind!=="answer").map(p=>({id:p.id,...p.data()}));s(m),r(!1)},d=>{console.error("[useAiRuns] Snapshot error:",d),a.current&&r(!1)})},[]),{runs:t,loading:n}}const by={pending:"bg-gray-100 text-gray-700",claimed:"bg-gray-100 text-gray-700",running:"bg-gray-100 text-gray-700",pr_open:"bg-green-100 text-green-600",blocked:"bg-amber-100 text-amber-700",failed:"bg-red-100 text-red-700",mixed:"bg-blue-100 text-blue-600",qa_claimed:"bg-violet-100 text-violet-600",qa_running:"bg-violet-100 text-violet-600",qa_fixing:"bg-violet-100 text-violet-600",qa_recording:"bg-violet-100 text-violet-600",qa_merging:"bg-violet-100 text-violet-600",qa_passed:"bg-emerald-100 text-emerald-700",qa_failed:"bg-red-100 text-red-700",qa_skipped:"bg-gray-100 text-gray-700",qa_blocked:"bg-amber-100 text-amber-700",qa_needs_auth:"bg-amber-100 text-amber-700",qa_needs_local:"bg-amber-100 text-amber-700"},yy={pending:"Pending",claimed:"Claimed",running:"Running",pr_open:"PR Open",blocked:"Blocked",failed:"Failed",mixed:"Mixed",qa_claimed:"QA Claimed",qa_running:"QA Running",qa_fixing:"QA Fixing",qa_recording:"QA Recording",qa_merging:"QA Merging",qa_passed:"QA Passed",qa_failed:"QA Failed",qa_skipped:"QA Skipped",qa_blocked:"QA Blocked",qa_needs_auth:"QA Needs Store Password",qa_needs_local:"QA Needs Local"},Fx=["running","claimed","pending","qa_running","qa_fixing","qa_recording","qa_merging","qa_claimed","pr_open","qa_needs_auth","qa_blocked","qa_needs_local","blocked","failed","qa_failed","mixed","qa_passed","qa_skipped"],BD=["qa_claimed","qa_running","qa_fixing","qa_recording","qa_merging"],FD=["qa_needs_auth","qa_blocked","qa_needs_local"];function _D(t){const s=sr(t);return s?s.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):""}function WD(t){const[s,n]=l.useState({}),r=t.join("|");l.useEffect(()=>{const o=r?r.split("|"):[];if(o.length===0)return;let i=!1;return re("getStorefrontPasswords",{projectIds:o}).then(d=>{i||n(m=>({...m,...d.passwords}))}).catch(d=>console.error("[useProjectPasswords] getStorefrontPasswords failed:",d)),()=>{i=!0}},[r]);const a=l.useCallback((o,i)=>{n(d=>({...d,[o]:i}))},[]);return{passwords:s,onSaved:a}}function UD({projectId:t,saved:s,onSaved:n}){const[r,a]=l.useState(s||""),[o,i]=l.useState(!1),[d,m]=l.useState(!1),[p,c]=l.useState(null);l.useEffect(()=>{a(h=>h===""||h===s?s||"":h)},[s]);const u=r!==(s||""),x=async()=>{m(!0),c(null);try{const h=r.trim()||null;await re("updateStorefrontPassword",{projectId:t,password:h}),n(t,h)}catch(h){c((h==null?void 0:h.message)||"Save failed")}finally{m(!1)}};return e.jsxs("div",{className:"mt-3",children:[e.jsxs("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:["Storefront password",e.jsx("span",{style:{fontWeight:400},children:" · used by QA to get past the store's password page"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:o?"text":"password",value:r,onChange:h=>a(h.target.value),onKeyDown:h=>{h.key==="Enter"&&u&&!d&&x()},placeholder:s?"":"Not set â QA will park on the password page",autoComplete:"off",spellCheck:!1,className:"flex-1 min-w-0 px-2 py-1 text-sm border border-border rounded bg-background text-foreground font-mono"}),e.jsx("button",{type:"button",onClick:()=>i(h=>!h),className:"px-2 py-1 text-xs rounded hover:bg-muted text-muted-foreground",title:o?"Hide":"Show",children:o?"Hide":"Show"}),e.jsx("button",{type:"button",onClick:()=>void x(),disabled:!u||d,className:"px-3 py-1 text-xs font-medium rounded bg-primary text-primary-foreground disabled:opacity-40",children:d?"Savingâ¦":"Save"})]}),p&&e.jsx("p",{className:"mt-1 text-xs text-red-600",children:p})]})}async function HD(t){await er(ut(ge,"aiRuns",t.id),{status:"pr_open",qaClaimedBy:null,qaHeartbeatAt:null,qaLeaseExpiresAt:null,qaActivity:null,qaError:null,log:mf(`[dashboard] retry QA requested from AI Runs (was ${t.status})`),updatedAt:ss()})}function qD({run:t,highlighted:s,storefrontPassword:n,onPasswordSaved:r}){const a=t.status==="blocked"||t.status==="failed",o=FD.includes(t.status),i=BD.includes(t.status),d=OD.includes(t.status),m=t.repoType==="theme"&&!!t.projectId,[p,c]=l.useState(!1),[u,x]=l.useState(null),h=async()=>{c(!0),x(null);try{await HD(t)}catch(b){x((b==null?void 0:b.message)||"Retry failed")}finally{c(!1)}};return e.jsxs("div",{className:`bg-card border rounded-lg p-4 ${s?"border-primary ring-1 ring-primary":"border-border"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:t.projectName}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[t.githubRepo,t.baseBranch?` · ${t.baseBranch}`:"",t.shopifyStore?` · ${t.shopifyStore}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[t.isRush&&e.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-700",children:"Rush"}),e.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${by[t.status]||"bg-gray-100 text-gray-700"}`,children:yy[t.status]||t.status})]})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[t.trigger&&e.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-muted text-muted-foreground",children:t.trigger==="rush"?"rush":"gate"}),(t.ticketDisplayIds||[]).map(b=>e.jsx("span",{className:"px-2 py-0.5 rounded text-xs font-mono bg-muted text-foreground",children:b},b)),typeof t.qaCycles=="number"&&t.qaCycles>0&&e.jsxs("span",{className:"px-2 py-0.5 rounded text-xs bg-muted text-muted-foreground",children:["QA cycle ",t.qaCycles]})]}),t.summary&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:t.summary}),i&&t.qaActivity&&e.jsxs("p",{className:"mt-2 text-sm text-violet-600 truncate",title:t.qaActivity,children:[t.qaClaimedBy?`${t.qaClaimedBy}: `:"",t.qaActivity]}),t.prUrl&&e.jsxs("a",{href:t.prUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-block mt-2 text-sm text-primary hover:underline",children:[t.prNumber?`PR #${t.prNumber}`:"View PR"," â"]}),a&&(t.error||t.resumeDocPath)&&e.jsxs("div",{className:"mt-3 p-3 bg-red-50 border border-red-200 rounded text-sm text-red-700 space-y-1",children:[t.error&&e.jsxs("p",{children:[t.errorClass?e.jsxs("strong",{children:[t.errorClass,": "]}):null,t.error]}),t.resumeDocPath&&e.jsxs("p",{className:"font-mono text-xs text-red-600 break-all",children:["Resume: ",t.resumeDocPath]})]}),(o||t.status==="qa_failed")&&t.qaError&&e.jsx("div",{className:"mt-3 p-3 bg-amber-100 border border-amber-300 rounded text-sm text-amber-800",children:t.status==="qa_needs_auth"&&!n?"QA hit the storefront password page and no password is saved for this project. Enter it below, then retry.":t.qaError}),m&&e.jsx(UD,{projectId:t.projectId,saved:n,onSaved:r}),d&&e.jsxs("div",{className:"mt-3 flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:()=>void h(),disabled:p,className:"px-3 py-1 text-sm font-medium rounded bg-primary text-primary-foreground disabled:opacity-40",children:p?"Re-queuingâ¦":"Retry QA"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sends the run back to PR Open for bucky-qa to claim again."}),u&&e.jsx("span",{className:"text-xs text-red-600",children:u})]}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:_D(t.createdAt)})]})}function VD({onBack:t,onLogoClick:s,initialRunId:n}){const{runs:r,loading:a}=$D(),o=l.useMemo(()=>Array.from(new Set(r.filter(c=>c.repoType==="theme"&&c.projectId).map(c=>c.projectId))).sort(),[r]),{passwords:i,onSaved:d}=WD(o);if(a)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(Xe,{onLogoClick:s||(()=>{})}),e.jsxs("div",{className:"flex flex-col items-center justify-center p-8",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading runs..."})]})]});const m=new Map;for(const c of r){const u=m.get(c.status)||[];u.push(c),m.set(c.status,u)}const p=[...Fx.filter(c=>m.has(c)),...Array.from(m.keys()).filter(c=>!Fx.includes(c))];return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s||(()=>{})}),e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[t&&e.jsx("button",{onClick:t,className:"p-2 hover:bg-muted rounded-full transition-colors",children:e.jsx("svg",{className:"w-5 h-5 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),e.jsx("h1",{className:"text-xl font-bold text-foreground",children:"AI Runs"})]}),r.length===0?e.jsx("div",{className:"text-center py-12",children:e.jsx("p",{className:"text-muted-foreground",children:"No pipeline runs yet."})}):e.jsx("div",{className:"space-y-6",children:p.map(c=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${by[c]||"bg-gray-100 text-gray-700"}`,children:yy[c]||c}),e.jsx("span",{className:"text-xs text-muted-foreground",children:(m.get(c)||[]).length})]}),e.jsx("div",{className:"space-y-2",children:(m.get(c)||[]).map(u=>e.jsx(qD,{run:u,highlighted:!!n&&u.id===n,storefrontPassword:u.projectId?i[u.projectId]??null:null,onPasswordSaved:d},u.id))})]},c))})]})]})}function jy(){const[t,s]=l.useState([]),[n,r]=l.useState(!0),[a,o]=l.useState(null),[i,d]=l.useState(!1),m=l.useRef(!0);l.useEffect(()=>()=>{m.current=!1},[]);const p=l.useCallback(async()=>{r(!0),o(null);try{const h=await re("manageShopRepos",{action:"list"});m.current&&s(h.shops||[])}catch(h){const b=h.message||"Failed to load shops";m.current&&o(b)}finally{m.current&&r(!1)}},[]),c=l.useCallback(async(h,b,f,g)=>{d(!0),o(null);try{await re("manageShopRepos",{action:"upsert",domain:h,repoType:b,repo:f,branch:g}),await p()}catch(y){const j=y.message||"Failed to save repo";throw m.current&&o(j),y}finally{m.current&&d(!1)}},[p]),u=l.useCallback(async(h,b)=>{d(!0),o(null);try{await re("manageShopRepos",{action:"delete",domain:h,docId:b}),await p()}catch(f){const g=f.message||"Failed to delete repo";throw m.current&&o(g),f}finally{m.current&&d(!1)}},[p]),x=l.useCallback(async h=>{d(!0),o(null);try{await re("manageShopRepos",{action:"deleteShop",domain:h}),await p()}catch(b){const f=b.message||"Failed to remove shop";throw m.current&&o(f),b}finally{m.current&&d(!1)}},[p]);return l.useEffect(()=>{p()},[p]),{shops:t,loading:n,error:a,saving:i,loadShops:p,upsertRepo:c,deleteRepo:u,deleteShop:x}}const YD=["theme","app","hydrogen","other"],_x={domain:"",repoType:"theme",repo:"",branch:"main"};function GD({onBack:t,onLogoClick:s}){const{shops:n,loading:r,error:a,saving:o,upsertRepo:i,deleteRepo:d,deleteShop:m}=jy(),[p,c]=l.useState(!1),[u,x]=l.useState(_x),[h,b]=l.useState(null),[f,g]=l.useState(null),y=()=>{x(_x),b(null),c(!0)},j=(w,I)=>{x({domain:w.domain,repoType:I.type,repo:I.repo,branch:I.branch}),b(`${w.domain}::${I.docId}`),c(!0)},v=async w=>{if(w.preventDefault(),!(!u.domain||!u.repoType||!u.repo||!u.branch))try{await i(u.domain,u.repoType,u.repo,u.branch),c(!1),b(null)}catch{}},T=async(w,I)=>{try{await d(w,I),g(null)}catch{}},k=async w=>{try{await m(w),g(null)}catch{}};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-2xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Shop Repos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage GitHub repos for each shop"})]}),e.jsxs("button",{onClick:y,className:"flex items-center gap-1.5 bg-primary text-primary-foreground px-3 py-2 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity",children:[e.jsx(Ut,{style:{width:"16px",height:"16px"}}),"Add Repo"]})]}),a&&e.jsx("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-3 mb-4 text-sm text-destructive",children:a}),p&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:()=>{c(!1),b(null)},children:e.jsxs("div",{className:"bg-card border border-border rounded-lg p-5 w-full max-w-md mx-4 shadow-lg",onClick:w=>w.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold text-foreground text-lg",children:h?"Edit Repo":"Add Repo"}),e.jsx("button",{onClick:()=>{c(!1),b(null)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(mt,{style:{width:"18px",height:"18px"}})})]}),e.jsxs("form",{onSubmit:v,className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"Shop Domain"}),e.jsx("input",{type:"text",value:u.domain,onChange:w=>x({...u,domain:w.target.value}),placeholder:"store.myshopify.com",disabled:!!h,className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground disabled:opacity-50"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"Repo Type"}
411),e.jsx("select",{value:u.repoType,onChange:w=>x({...u,repoType:w.target.value}),disabled:!!h,className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground disabled:opacity-50",children:YD.map(w=>e.jsx("option",{value:w,children:w},w))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"GitHub Repo"}),e.jsx("input",{type:"text",value:u.repo,onChange:w=>x({...u,repo:w.target.value}),placeholder:"org/repo-name",className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"Branch"}),e.jsx("input",{type:"text",value:u.branch,onChange:w=>x({...u,branch:w.target.value}),placeholder:"main",className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground"})]}),e.jsxs("button",{type:"submit",disabled:o||!u.domain||!u.repo||!u.branch,className:"w-full flex items-center justify-center gap-2 bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity disabled:opacity-50",children:[o?e.jsx(fe,{style:{width:"16px",height:"16px"},className:"animate-spin"}):e.jsx(kt,{style:{width:"16px",height:"16px"}}),h?"Update":"Add"," Repo"]})]})]})}),r&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{style:{width:"24px",height:"24px"},className:"animate-spin text-muted-foreground"})}),!r&&n.length===0&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No shops found. Add a repo to get started."}),e.jsx("div",{className:"space-y-4",children:n.map(w=>e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("h3",{className:"font-semibold text-foreground text-sm flex-1 truncate",children:w.domain}),f===`shop::${w.domain}`?e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-destructive",children:["Remove ",w.domain," and all its repo config?"]}),e.jsx("button",{onClick:()=>k(w.domain),disabled:o,className:"p-1 text-destructive hover:text-destructive/80 transition-colors",title:"Confirm remove shop",children:e.jsx(kt,{style:{width:"14px",height:"14px"}})}),e.jsx("button",{onClick:()=>g(null),className:"p-1 text-muted-foreground hover:text-foreground transition-colors",title:"Cancel",children:e.jsx(mt,{style:{width:"14px",height:"14px"}})})]}):e.jsx("button",{onClick:()=>g(`shop::${w.domain}`),className:"p-1 text-muted-foreground hover:text-destructive transition-colors flex-shrink-0",title:"Remove shop",children:e.jsx(zs,{style:{width:"14px",height:"14px"}})})]}),w.repos.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No repos configured"}):e.jsx("div",{className:"space-y-2",children:w.repos.map(I=>{const A=`${w.domain}::${I.docId}`;return e.jsxs("div",{className:"flex items-center gap-3 bg-background rounded-md px-3 py-2",children:[e.jsx(rg,{style:{width:"14px",height:"14px"},className:"text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"inline-block bg-primary/10 text-primary text-xs font-medium px-2 py-0.5 rounded",children:I.type}),e.jsx("span",{className:"text-sm text-foreground flex-1 truncate",children:I.repo}),e.jsx("span",{className:"text-xs text-muted-foreground",children:I.branch}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("button",{onClick:()=>j(w,I),className:"p-1 text-muted-foreground hover:text-foreground transition-colors",children:e.jsx(Na,{style:{width:"14px",height:"14px"}})}),f===A?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>T(w.domain,I.docId),disabled:o,className:"p-1 text-destructive hover:text-destructive/80 transition-colors",title:"Confirm delete",children:e.jsx(kt,{style:{width:"14px",height:"14px"}})}),e.jsx("button",{onClick:()=>g(null),className:"p-1 text-muted-foreground hover:text-foreground transition-colors",title:"Cancel",children:e.jsx(mt,{style:{width:"14px",height:"14px"}})})]}):e.jsx("button",{onClick:()=>g(A),className:"p-1 text-muted-foreground hover:text-destructive transition-colors",children:e.jsx(zs,{style:{width:"14px",height:"14px"}})})]})]},A)})})]},w.domain))})]})]})}function KD(){const[t,s]=l.useState([]),[n,r]=l.useState(null),[a,o]=l.useState(!1),[i,d]=l.useState(!1),[m,p]=l.useState(!1),[c,u]=l.useState(null),[x,h]=l.useState(null),[b,f]=l.useState(null),[g,y]=l.useState(!1),[j,v]=l.useState(!1),T=l.useCallback(async C=>{o(!0),u(null),s([]);try{const N=await re("themeDeploy",{action:"listBranches",repo:C});return s(N.branches||[]),N.branches||[]}catch(N){return u(N.message||"Failed to list branches"),[]}finally{o(!1)}},[]),k=l.useCallback(async(C,N,S)=>{d(!0),u(null),r(null);try{const O=await re("themeDeploy",{action:"compare",repo:C,base:N,head:S});return r(O),O}catch(O){return u(O.message||"Failed to compare branches"),null}finally{d(!1)}},[]),w=l.useCallback(async(C,N,S,O)=>{p(!0),u(null),h(null);try{const R=await re("themeDeploy",{action:"merge",repo:C,source:N,target:S,shopDomain:O});return h(R),R}catch(R){return u(R.message||"Failed to merge branches"),null}finally{p(!1)}},[]),I=l.useCallback(async(C,N,S)=>{y(!0),u(null),f(null);try{const O=await re("themeDeploy",{action:"getConflicts",repo:C,source:N,target:S});return f(O),O}catch(O){return u(O.message||"Failed to detect conflicts"),null}finally{y(!1)}},[]),A=l.useCallback(async(C,N,S,O,R)=>{v(!0),u(null),h(null);try{const z=await re("themeDeploy",{action:"resolveConflicts",repo:C,source:N,target:S,resolutions:O,shopDomain:R});return h(z),f(null),z}catch(z){return u(z.message||"Failed to resolve conflicts"),null}finally{v(!1)}},[]),E=l.useCallback(()=>{r(null),h(null),f(null),u(null)},[]);
411return{branches:t,comparison:n,conflicts:b,loading:a,comparing:i,merging:m,loadingConflicts:g,resolving:j,error:c,mergeResult:x,listBranches:T,compareBranches:k,mergeBranches:w,getConflicts:I,resolveConflicts:A,clearComparison:E}}function QD({onBack:t,onLogoClick:s}){const{shops:n,loading:r}=jy(),{branches:a,comparison:o,conflicts:i,loading:d,comparing:m,merging:p,loadingConflicts:c,resolving:u,error:x,mergeResult:h,listBranches:b,compareBranches:f,mergeBranches:g,getConflicts:y,resolveConflicts:j,clearComparison:v}=KD(),[T,k]=l.useState(null),[w,I]=l.useState(""),[A,E]=l.useState(""),[C,N]=l.useState(""),[S,O]=l.useState(!1),[R,z]=l.useState({}),[D,L]=l.useState(!1);l.useEffect(()=>{w&&(b(w),E(""),N(""),v())},[w,b,v]);const $=U=>{k(U),I(""),E(""),N(""),v();const V=U.repos.find(M=>M.type==="theme");V&&I(V.repo)},q=()=>{w&&A&&C&&f(w,C,A)},P=()=>{w&&A&&C&&(g(w,A,C,T==null?void 0:T.domain),O(!1))};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-3xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Theme Deploy"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Merge branches across client stores"})]})]}),x&&e.jsx("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-3 mb-4 text-sm text-destructive",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Dt,{style:{width:"16px",height:"16px",marginTop:"1px",flexShrink:0}}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{children:x}),(x.toLowerCase().includes("conflict")||x.toLowerCase().includes("merge conflict"))&&w&&A&&C&&!D&&e.jsx("button",{onClick:()=>{L(!0),z({}),y(w,A,C)},disabled:c,className:"mt-2 px-3 py-1.5 bg-purple-600 text-white text-xs rounded-md hover:bg-purple-700 disabled:opacity-50 inline-flex items-center gap-1.5",children:c?e.jsxs(e.Fragment,{children:[e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"})," Detecting conflicts..."]}):"Resolve Conflicts"})]})]})}),(h==null?void 0:h.success)&&e.jsxs("div",{className:"bg-green-500/10 border border-green-500/20 rounded-lg p-3 mb-4 text-sm text-green-700 flex items-start gap-2",children:[e.jsx(Ns,{style:{width:"16px",height:"16px",marginTop:"1px",flexShrink:0}}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:h.message}),h.url&&e.jsx("a",{href:h.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-xs",children:"View on GitHub"})]})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mb-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"Store"}),e.jsxs("div",{className:"relative",children:[e.jsxs("select",{value:(T==null?void 0:T.domain)||"",onChange:U=>{const V=n.find(M=>M.domain===U.target.value);V&&$(V)},disabled:r,className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground appearance-none pr-8",children:[e.jsx("option",{value:"",children:"Select a store..."}),n.filter(U=>U.repos.length>0).map(U=>e.jsx("option",{value:U.domain,children:U.domain},U.domain))]}),e.jsx(Ot,{style:{width:"14px",height:"14px"},className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none"})]})]}),T&&T.repos.length>1&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"Repository"}),e.jsxs("div",{className:"relative",children:[e.jsxs("select",{value:w,onChange:U=>I(U.target.value),className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground appearance-none pr-8",children:[e.jsx("option",{value:"",children:"Select a repo..."}),T.repos.map(U=>e.jsxs("option",{value:U.repo,children:[U.repo," (",U.type,")"]},U.type))]}),e.jsx(Ot,{style:{width:"14px",height:"14px"},className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none"})]})]}),w&&e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"Source (from)"}),e.jsxs("div",{className:"relative",children:[e.jsxs("select",{value:A,onChange:U=>{E(U.target.value),v()},disabled:d,className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground appearance-none pr-8",children:[e.jsx("option",{value:"",children:"Select branch..."}),a.filter(U=>U.name!==C).map(U=>e.jsx("option",{value:U.name,children:U.name},U.name))]}),e.jsx(Ot,{style:{width:"14px",height:"14px"},className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none"})]})]}),e.jsx(Ef,{style:{width:"20px",height:"20px",marginBottom:"10px"},className:"text-muted-foreground flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"Target (into)"}),e.jsxs("div",{className:"relative",children:[e.jsxs("select",{value:C,onChange:U=>{N(U.target.value),v()},disabled:d,className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground appearance-none pr-8",children:[e.jsx("option",{value:"",children:"Select branch..."}),a.filter(U=>U.name!==A).map(U=>e.jsx("option",{value:U.name,children:U.name},U.name))]}),e.jsx(Ot,{style:{width:"14px",height:"14px"},className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none"})]})]}),e.jsxs("button",{onClick:q,disabled:!A||!C||m,className:"flex items-center gap-1.5 bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity disabled:opacity-50 flex-shrink-0",children:[m?e.jsx(fe,{style:{width:"16px",height:"16px"},className:"animate-spin"}):e.jsx(Gw,{style:{width:"16px",height:"16px"}}),"Compare"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"}),"Loading branches..."]})]}),o&&e.jsx(JD,{comparison:o}),o&&o.status!=="identical"&&o.totalCommits>0&&!(h!=null&&h.success)&&e.jsx("div",{className:"bg-card border border-border rounded-lg p-4 mt-4",children:S?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-amber-700 bg-amber-50 rounded-lg p-3",children:[e.jsx(Dt,{style:{width:"16px",height:"16px",marginTop:"1px",flexShrink:0}}),e.jsxs("span",{children:["This will merge ",e.jsxs("strong",{children:[o.totalCommits," commits"]})," and"," ",e.jsxs("strong",{children:[o.files.length," file changes"]})," from ",e.jsx("strong",{children:A})," into"," ",e.jsx("strong",{children:C}),". This cannot be easily undone."]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>O(!1),className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium border border-border text-foreground hover:bg-muted transition-colors",children:"Cancel"}),e.jsxs("button",{onClick:P,disabled:p,className:"flex-1 flex items-center justify-center gap-2 bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-green-700 transition-colors disabled:opacity-50",children:[p?e.jsx(fe,{style:{width:"16px",height:"16px"},className:"animate-spin"}):e.jsx(Or,{style:{width:"16px",height:"16px"}}),p?"Merging...":"Confirm Merge"]})]})]}):e.jsxs("button",{onClick:()=>O(!0),className:"w-full flex items-center justify-center gap-2 bg-green-600 text-white px-4 py-3 rounded-lg text-sm font-semibold hover:bg-green-700 transition-colors",children:[e.jsx(Or,{style:{width:"18px",height:"18px"}}),"Merge ",A," into ",C]})}),D&&i&&i.conflicts.length>0&&e.jsxs("div",{className:"bg-card border border-purple-200 rounded-lg overflow-hidden mt-4",children:[e.jsxs("div",{className:"px-4 py-3 bg-purple-50 border-b border-purple-200",children:[e.jsxs("h3",{className:"text-sm font-semibold text-purple-900",children:[i.conflicts.length," file",i.conflicts.length>
4111?"s":""," need",i.conflicts.length===1?"s":""," your attention"]}),i.nonConflictingFiles>0&&e.jsxs("p",{className:"text-xs text-purple-600 mt-0.5",children:[i.nonConflictingFiles," other file",i.nonConflictingFiles>1?"s":""," will merge automatically"]})]}),e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsx("button",{onClick:()=>{const U={};i.conflicts.forEach(V=>{U[V.filename]="source"}),z(U)},className:"px-3 py-1.5 text-xs border border-purple-300 text-purple-700 rounded-md hover:bg-purple-50",children:"Keep all staging"}),e.jsx("button",{onClick:()=>{const U={};i.conflicts.forEach(V=>{U[V.filename]="target"}),z(U)},className:"px-3 py-1.5 text-xs border border-purple-300 text-purple-700 rounded-md hover:bg-purple-50",children:"Keep all production"})]}),i.conflicts.map(U=>e.jsxs("div",{className:"border border-border rounded-lg p-3",children:[e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:U.description}),e.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:U.filename})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-sm",children:[e.jsx("input",{type:"radio",name:`resolve-${U.filename}`,checked:R[U.filename]==="source",onChange:()=>z(V=>({...V,[U.filename]:"source"})),className:"accent-purple-600"}),e.jsxs("span",{children:["Keep staging ",e.jsx("span",{className:"text-muted-foreground",children:"(your changes)"})]})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-sm",children:[e.jsx("input",{type:"radio",name:`resolve-${U.filename}`,checked:R[U.filename]==="target",onChange:()=>z(V=>({...V,[U.filename]:"target"})),className:"accent-purple-600"}),e.jsxs("span",{children:["Keep production ",e.jsx("span",{className:"text-muted-foreground",children:"(live site)"})]})]})]})]},U.filename)),e.jsx("button",{onClick:()=>{const U=i.conflicts.map(V=>({filename:V.filename,keep:R[V.filename]||"source"}));j(w,A,C,U,T==null?void 0:T.domain),L(!1)},disabled:u||Object.keys(R).length<i.conflicts.length,className:"w-full flex items-center justify-center gap-2 bg-purple-600 text-white px-4 py-3 rounded-lg text-sm font-semibold hover:bg-purple-700 transition-colors disabled:opacity-50",children:u?e.jsxs(e.Fragment,{children:[e.jsx(fe,{style:{width:16,height:16},className:"animate-spin"})," Resolving & Merging..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{style:{width:16,height:16}})," Apply & Merge"]})}),Object.keys(R).length<i.conflicts.length&&e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Choose a version for each file above to continue"})]})]}),D&&c&&e.jsxs("div",{className:"bg-card border border-border rounded-lg p-8 mt-4 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(fe,{style:{width:16,height:16},className:"animate-spin"}),"Detecting conflicting files..."]}),D&&i&&i.conflicts.length===0&&e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mt-4 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(wa,{style:{width:16,height:16}}),"No conflicting files detected. Try merging again."]}),o&&o.status==="identical"&&e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mt-4 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(wa,{style:{width:"16px",height:"16px"}}),"Branches are identical. Nothing to merge."]})]})]})}function JD({comparison:t}){const s=n=>{switch(n){case"added":return e.jsx(Ww,{style:{width:"14px",height:"14px"},className:"text-green-600"});case"removed":return e.jsx(Uw,{style:{width:"14px",height:"14px"},className:"text-red-600"});default:return e.jsx(_w,{style:{width:"14px",height:"14px"},className:"text-amber-600"})}};return e.jsxs("div",{className:"bg-card border border-border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-muted/50 border-b border-border flex items-center gap-4 text-sm",children:[e.jsxs("span",{className:"font-medium text-foreground",children:[t.totalCommits," commits"]}),e.jsxs("span",{className:"text-muted-foreground",children:[t.files.length," files changed"]}),e.jsxs("span",{className:"text-green-600",children:["+",t.files.reduce((n,r)=>n+r.additions,0)]}),e.jsxs("span",{className:"text-red-600",children:["-",t.files.reduce((n,r)=>n+r.deletions,0)]})]}),t.files.length>0&&e.jsx("div",{className:"max-h-64 overflow-y-auto",children:t.files.map(n=>e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 text-sm border-b border-border last:border-0 hover:bg-muted/30",children:[s(n.status),e.jsx("span",{className:"text-foreground flex-1 truncate font-mono text-xs",children:n.filename}),e.jsxs("span",{className:"text-green-600 text-xs",children:["+",n.additions]}),e.jsxs("span",{className:"text-red-600 text-xs",children:["-",n.deleti
411ons]})]},n.filename))}),t.commits.length>0&&e.jsxs("div",{className:"border-t border-border",children:[e.jsx("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground bg-muted/30",children:"Recent commits"}),e.jsx("div",{className:"max-h-48 overflow-y-auto",children:t.commits.map(n=>e.jsxs("div",{className:"flex items-center gap-2 px-4 py-1.5 text-xs border-b border-border last:border-0",children:[e.jsx("code",{className:"text-primary font-mono",children:n.sha}),e.jsx("span",{className:"text-foreground flex-1 truncate",children:n.message}),e.jsx("span",{className:"text-muted-foreground flex-shrink-0",children:n.author})]},n.sha))})]})]})}function Wx(t){if(!t)return"never";const s=Date.now()-t,n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Ux({status:t}){if(!t)return e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not yet synced"});const n={synced:{label:"Synced",fg:"#15803d",bg:"rgba(134,217,168,0.25)",Icon:Ns},"up-to-date":{label:"Up to date",fg:"#15803d",bg:"rgba(134,217,168,0.25)",Icon:Ns},conflict:{label:"Conflict",fg:"#b91c1c",bg:"rgba(239,68,68,0.15)",Icon:Dt},error:{label:"Error",fg:"#b91c1c",bg:"rgba(239,68,68,0.15)",Icon:vN}}[t]||{label:t,fg:"var(--muted-foreground)",bg:"var(--muted)",Icon:ms},{Icon:r}=n;return e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full text-xs font-medium",style:{padding:"2px 8px",color:n.fg,background:n.bg},children:[e.jsx(r,{style:{width:12,height:12}}),n.label]})}function ZD({onBack:t,onLogoClick:s}){const[n,r]=l.useState([]),[a,o]=l.useState(!0),[i,d]=l.useState({}),[m,p]=l.useState({}),c=l.useCallback(async()=>{o(!0);try{const b=await re("manageThemeSync",{action:"list"});r((b==null?void 0:b.shops)||[])}catch(b){ce.error("Failed to load theme sync",{description:b==null?void 0:b.message})}finally{o(!1)}},[]);l.useEffect(()=>{c()},[c]);const u=(b,f)=>d(g=>({...g,[b]:f})),x=async b=>{const f=!b.enabled;u(b.shopDomain,!0);const g=ce.loading(f?"Enabling syncâ¦":"Disabling syncâ¦");try{await re("manageThemeSync",{action:f?"enable":"disable",shopDomain:b.shopDomain}),ce.success(f?"Sync enabled & webhook installed":"Sync disabled",{id:g}),await c()}catch(y){ce.error("Action failed",{id:g,description:y==null?void 0:y.message})}finally{u(b.shopDomain,!1)}},h=async b=>{u(b.shopDomain,!0);const f=ce.loading(`Syncing ${b.mainBranch} â ${b.stagingBranch}â¦`);try{const g=await re("manageThemeSync",{action:"syncNow",shopDomain:b.shopDomain});(g==null?void 0:g.status)==="conflict"?ce.warning("Merge conflict â staging left untouched",{id:f,description:g==null?void 0:g.message}):(g==null?void 0:g.status)==="error"?ce.error("Sync failed",{id:f,description:(g==null?void 0:g.message)||(g==null?void 0:g.error)}):ce.success((g==null?void 0:g.message)||"Synced",{id:f}),await c()}catch(g){ce.error("Sync failed",{id:f,description:g==null?void 0:g.message})}finally{u(b.shopDomain,!1)}};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-3xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Theme Sync"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Keep staging current with main (one-way)"})]}),e.jsx("button",{onClick:c,disabled:a,className:"text-muted-foreground hover:text-foreground disabled:opacity-50",title:"Refresh",children:e.jsx(yt,{style:{width:18,height:18},className:a?"animate-spin":""})})]}),e.jsxs("div",{className:"bg-muted border border-border rounded-lg p-3 mb-4 text-sm text-muted-foreground",children:["When Shopify pushes a change to ",e.jsx("strong",{children:"main"}),", enabled stores merge it into"," ",e.jsx("strong",{children:"staging"})," automatically. Staging keeps its own un-launched work; sync only ever flows main â staging."]}),a?e.jsx("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:e.jsx(fe,{style:{width:24,height:24},className:"animate-spin"})}):n.length===0?e.jsxs("div",{className:"text-center py-16 text-muted-foreground text-sm",children:["No stores with both a ",e.jsx("strong",{children:"main"})," and ",e.jsx("strong",{children:"staging"})," theme repo.",e.jsx("br",{}),"Add theme repos in Shop Repos first."]}):e.jsx("div",{className:"space-y-3",children:n.map(b=>{const f=!!i[b.shopDomain],g=!!m[b.shopDomain],y=b.lastSyncStatus==="conflict"||b.lastSyncStatus==="error";return e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",style:{borderRadius:"var(--radius-md)",...y?{borderColor:"#fca5a5"}:{}},children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground truncate",children:b.shopDomain.replace(".myshopify.com","")}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:b.repo}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-mono",children:b.mainBranch}),e.jsx(Or,{style:{width:12,height:12}}),e.jsx("span",{className:"font-mono",children:b.stagingBranch})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("span",{className:"text-xs font-medium",style:{color:b.enabled?"#15803d":"var(--muted-foreground)"},children:b.enabled?"Auto-sync on":"Auto-sync off"}),e.jsx("button",{onClick:()=>x(b),disabled:f,role:"switch","aria-checked":b.enabled,title:b.enabled?"Disable auto-sync":"Enable auto-sync",style:{position:"relative",flexShrink:0,width:44,height:24,borderRadius:999,border:"none",padding:0,cursor:f?"default":"pointer",opacity:f?.5:1,background:b.enabled?"#16a34a":"rgba(120,120,120,0.35)",transition:"background 0.18s ease"},children:e.jsx("span",{style:{position:"absolute",top:3,left:b.enabled?23:3,width:18,height:18,borderRadius:"50%",background:"#fff",boxShadow:"0 1px 2px rgba(0,0,0,0.25)",transition:"left 0.18s ease"}})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 pt-3 border-t border-border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ux,{status:b.lastSyncStatus}),b.lastSyncAt&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Wx(b.lastSyncAt)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>h(b),disabled:f,className:"px-3 py-1.5 bg-primary text-primary-foreground text-xs rounded-md hover:opacity-90 disabled:opacity-50 inline-flex items-center gap-1.5",children:[f?e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}):e.jsx(yt,{style:{width:12,height:12}}),"Sync now"]}),b.events.length>0&&e.jsx("button",{onClick:()=>p(j=>({...j,[b.shopDomain]:!g})),className:"text-muted-foreground hover:text-foreground",title:"Recent syncs",children:g?e.jsx(hr,{style:{width:16,height:16}}):e.jsx(Ot,{style:{width:16,height:16}})})]})]}),g&&b.events.length>0&&e.jsx("div",{className:"mt-3 space-y-1.5",children:b.events.map((j,v)=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsx(Ux,{status:j.status}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-muted-foreground truncate",children:j.message}
411),e.jsxs("p",{className:"text-muted-foreground/70",children:[j.trigger,j.pusher?` · ${j.pusher}`:""," · ",Wx(j.createdAt)]})]})]},v))})]},b.shopDomain)})})]})]})}const Hx=[{value:"approve_all",label:"Approve all (customer reviews)"},{value:"apply_with_revert",label:"Apply with revert"},{value:"auto_approve",label:"Auto-approve & apply"}],XD=[{value:"seo_only",label:"SEO fields only"},{value:"full",label:"Full (title, description & SEO)"}],vy="https://us-central1-bucky-app-355a3.cloudfunctions.net";async function wy(){var s;const t=await((s=Lr.currentUser)==null?void 0:s.getIdToken());if(!t)throw new Error("No auth token available");return t}async function eM(t){const s=await wy(),n=new AbortController,r=setTimeout(()=>n.abort(),12e4);try{const a=await fetch(`${vy}/seoRunAutoApply`,{method:"POST",headers:as(s),body:JSON.stringify({shop:t}),signal:n.signal});if(clearTimeout(r),!a.ok){const o=await a.json().catch(()=>({}));throw new Error(o.error||`HTTP ${a.status}`)}return await a.json()}catch(a){throw clearTimeout(r),a.name==="AbortError"?new Error("Request timed out. Auto-apply may still be running."):a}}async function tM(t,s,n){const r=await wy(),a=new AbortController,o=setTimeout(()=>a.abort(),6e4);try{const i=await fetch(`${vy}/seoRevertChange`,{method:"POST",headers:as(r),body:JSON.stringify({shop:t,approvalId:s,...n?{force:!0}:{}}),signal:a.signal});clearTimeout(o);const d=await i.json().catch(()=>({}));if(!i.ok&&d.success===void 0)throw new Error(d.error||`HTTP ${i.status}`);return d}catch(i){throw clearTimeout(o),i.name==="AbortError"?new Error("Request timed out. Please try again."):i}}const Ti="_global",so="_digest",sM=[{key:"pageTitle",label:"Page title"},{key:"metaDescription",label:"Meta description"},{key:"imageAltText",label:"Image alt"}],nM=[{key:"productTitle",label:"Product title"},{key:"description",label:"Description"}];function no(t){if(!t)return"never";const s=new Date(t).getTime();if(Number.isNaN(s))return"never";const n=Date.now()-s,r=Math.floor(n/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const a=Math.floor(r/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}const ro={border:"1px solid var(--border)",background:"var(--background)",color:"var(--foreground)",borderRadius:"var(--radius-md, 6px)",padding:"4px 8px",fontSize:12};function rM({onBack:t,onLogoClick:s}){const[n,r]=l.useState([]),[a,o]=l.useState(null),[i,d]=l.useState(!0),[m,p]=l.useState({}),[c,u]=l.useState({}),[x,h]=l.useState({}),[b,f]=l.useState({}),[g,y]=l.useState({}),[j,v]=l.useState({}),[T,k]=l.useState(!1),[w,I]=l.useState(null),[A,E]=l.useState({}),[C,N]=l.useState({}),[S,O]=l.useState({}),[R,z]=l.useState({}),D=l.useCallback(async()=>{d(!0);try{const Q=await re("manageSeoAutomation",{action:"list"});r((Q==null?void 0:Q.shops)||[]),o((Q==null?void 0:Q.global)||null)}catch(Q){ce.error("Failed to load SEO automation",{description:Q==null?void 0:Q.message})}finally{d(!1)}},[]);l.useEffect(()=>{D()},[D]);const L=(Q,K)=>p(X=>({...X,[Q]:K})),$=async()=>{if(!a)return;const Q=!a.killSwitch;k(!1),L(Ti,!0);const K=ce.loading(Q?"Pausing all auto-applyâ¦":"Resuming auto-applyâ¦");try{await re("manageSeoAutomation",{action:"setKillSwitch",on:Q}),ce.success(Q?"Auto-apply paused (all shops)":"Auto-apply resumed",{id:K}),await D()}catch(X){ce.error("Action failed",{id:K,description:X==null?void 0:X.message})}finally{L(Ti,!1)}},q=async()=>{const Q=(w??"").split(",").map(X=>X.trim()).filter(Boolean);L(so,!0);const K=ce.loading("Saving digest recipientsâ¦");try{const X=await re("manageSeoAutomation",{action:"setDigestRecipients",recipients:Q});o((X==null?void 0:X.global)||null),I(null),ce.success("Digest recipients saved",{id:K})}catch(X){ce.error("Action failed",{id:K,description:X==null?void 0:X.message})}finally{L(so,!1)}},P=async(Q,K)=>{L(Q,!0);const X=ce.loading("Updating modeâ¦");try{await re("manageSeoAutomation",{action:"setMode",shop:Q,mode:K}),ce.success("Mode updated",{id:X}),await D()}catch(se){ce.error("Action failed",{id:X,description:se==null?void 0:se.message})}finally{L(Q,!1)}},U=async(Q,K)=>{L(Q,!0);const X=ce.loading("Updating scopeâ¦");try{await re("manageSeoAutomation",{action:"setScope",shop:Q,applyScope:K}),ce.success("Scope updated",{id:X}),await D()}catch(se){ce.error("Action failed",{id:X,description:se==null?void 0:se.message})}finally{L(Q,!1)}},V=async(Q,K)=>{L(Q,!0);const X=ce.loading(K?"Enablingâ¦":"Disablingâ¦");try{await re("manageSeoAutomation",{action:"setEnabled",shop:Q,enabled:K}),ce.success(K?"Enabled":"Disabled",{id:X});try{await D()}catch(se){ce.error("Failed to reload data",{id:X,description:se==null?void 0:se.message})}}catch(se){ce.error("Action failed",{id:X,description:se==null?void 0:se.message})}finally{L(Q,!1)}},M=async Q=>{const K=(g[Q]??"").split(",").map(se=>
411se.trim()).filter(Boolean);L(Q,!0);const X=ce.loading("Saving recipientsâ¦");try{await re("manageSeoAutomation",{action:"setRecipients",shop:Q,recipients:K}),ce.success("Recipients saved",{id:X}),y(se=>{const pe={...se};return delete pe[Q],pe});try{await D()}catch(se){ce.error("Failed to reload data",{id:X,description:se==null?void 0:se.message})}}catch(se){ce.error("Action failed",{id:X,description:se==null?void 0:se.message})}finally{L(Q,!1)}},F=async Q=>{const K=j[Q]||"approve_all";L(Q,!0);const X=ce.loading("Enrollingâ¦");try{await re("manageSeoAutomation",{action:"enroll",shop:Q,mode:K,applyScope:"seo_only"}),ce.success("Shop enrolled",{id:X}),await D()}catch(se){ce.error("Enroll failed",{id:X,description:se==null?void 0:se.message})}finally{L(Q,!1)}},W=async Q=>{const K=!!c[Q];if(u(X=>({...X,[Q]:!K})),!(K||x[Q])){f(X=>({...X,[Q]:!0}));try{const X=await re("manageSeoAutomation",{action:"listEvents",shop:Q});h(se=>({...se,[Q]:(X==null?void 0:X.events)||[]}))}catch(X){ce.error("Failed to load events",{description:X==null?void 0:X.message})}finally{f(X=>({...X,[Q]:!1}))}}},_=async Q=>{L(Q,!0);const K=ce.loading("Running auto-applyâ¦");try{const{result:X}=await eM(Q);X.skippedReason?ce.warning(`Skipped: ${X.skippedReason}`,{id:K}):ce.success(`${X.applied.length} applied, ${X.pendingCreated} pending, ${X.skipped} skipped`,{id:K}),await D(),A[Q]&&await G(Q)}catch(X){ce.error("Run failed",{id:K,description:X==null?void 0:X.message})}finally{L(Q,!1)}},G=async Q=>{O(K=>({...K,[Q]:!0}));try{const K=await re("manageSeoAutomation",{action:"listApplied",shop:Q});N(X=>({...X,[Q]:(K==null?void 0:K.applied)||[]}))}catch(K){ce.error("Failed to load applied changes",{description:K==null?void 0:K.message})}finally{O(K=>({...K,[Q]:!1}))}},B=async Q=>{const K=!!A[Q];E(X=>({...X,[Q]:!K})),!(K||C[Q])&&await G(Q)},Y=async(Q,K,X)=>{L(K,!0);const se=ce.loading("Reverting changeâ¦");try{const pe=await tM(Q,K,X);pe.success?(z(me=>{const{[K]:Ne,...at}=me;return at}),ce.success("Change reverted",{id:se}),await G(Q)):pe.drifted?(ce.dismiss(se),z(me=>({...me,[K]:pe.driftedFields||[]}))):ce.error("Revert failed",{id:se,description:pe.error})}catch(pe){ce.error("Revert failed",{id:se,description:pe==null?void 0:pe.message})}finally{L(K,!1)}},J=Q=>Q.replace(".myshopify.com",""),H=!!(a!=null&&a.killSwitch),Z=w??((a==null?void 0:a.digestRecipients)||[]).join(", ");return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-3xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"SEO Automation"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Auto-apply AI SEO fixes per shop"})]}),e.jsx("button",{onClick:D,disabled:i,className:"text-muted-foreground hover:text-foreground disabled:opacity-50",title:"Refresh",children:e.jsx(yt,{style:{width:18,height:18},className:i?"animate-spin":""})})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mb-4",style:H?{borderColor:"#fca5a5"}:{},children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(yg,{style:{width:20,height:20,flexShrink:0,color:H?"#b91c1c":"var(--muted-foreground)"}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:"Global kill switch"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pauses every shop's auto-apply at once. Per-shop settings are preserved."})]}),T?e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:H?"Resume auto-apply?":"Pause all shops?"}),e.jsx("button",{onClick:$,className:"px-3 py-1.5 text-xs rounded-md hover:opacity-90 inline-flex items-center gap-1.5",style:{color:"#fff",background:H?"#16a34a":"#b91c1c"},children:"Confirm"}),e.jsx("button",{onClick:()=>k(!1),className:"px-3 py-1.5 bg-muted text-foreground text-xs rounded-md hover:opacity-90",children:"Cancel"})]}):e.jsxs("button",{onClick:()=>k(!0),disabled:i||!a||!!m[Ti],className:"px-3 py-1.5 text-xs rounded-md hover:opacity-90 disabled:opacity-50 inline-flex items-center gap-1.5 flex-shrink-0",style:{color:"#fff",background:H?"#16a34a":"#b91c1c"},children:[m[Ti]?e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}):H?e.jsx(In,{style:{width:12,height:12}}):e.jsx(aN,{style:{width:12,height:12}}),H?"Resume":"Pause all"]})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-border",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Digest recipients (comma-separated) â internal auto-apply digest"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"text",value:Z,disabled:i||!a||!!m[so],placeholder:"[email protected], [email protected]",onChange:Q=>I(Q.target.value),className:"flex-1 min-w-0",style:ro}),e.jsxs("button",{onClick:q,disabled:!a||!!m[so]||w===null,className:"px-3 py-1.5 bg-primary text-primary-foreground text-xs rounded-md hover:opacity-90 disabled:opacity-50 inline-flex items-center gap-1.5 flex-shrink-0",children:[m[so]?e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}):null,"Save"]})]})]})]}),H&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 text-sm flex items-center gap-2",style:{borderColor:"#fca5a5",background:"rgba(239,68,68,0.10)",color:"#b91c1c"},children:[e.jsx(Dt,{style:{width:16,height:16,flexShrink:0}}),e.jsxs("span",{children:[e.jsx("strong",{children:"AUTO-APPLY PAUSED (all shops)."})," No SEO changes will be pushed until resumed."]})]}),i?e.jsx("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:e.jsx(fe,{style:{width:24,height:24},className:"animate-spin"})}):n.length===0?e.jsx("div",{className:"text-center py-16 text-muted-foreground text-sm",children:"No installed shops found."}):e.jsx("div",{className:"space-y-3",children:n.map(Q=>{const K=!!m[Q.shop],X=!!c[Q.shop],se=Q.config,pe=g[Q.shop]??((se==null?void 0:se.notifyRecipients)||[]).join(", ");return e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground truncate",children:J(Q.shop)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Q.shop})]}),Q.enrolled?e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("span",{className:"text-xs font-medium",style:{color:se!=null&&se.enabled?"#15803d":"var(--muted-foreground)"},children:se!=null&&se.enabled?"Enabled":"Disabled"}),e.jsx("button",{onClick:()=>V(Q.shop,!(se!=null&&se.enabled)),disabled:K,role:"switch","aria-checked":!!(se!=null&&se.enabled),title:se!=null&&se.enabled?"Disable":"Enable",style:{position:"relative",flexShrink:0,width:44,height:24,borderRadius:999,border:"none",padding:0,cursor:K?"default":"pointer",opacity:K?.5:1,background:se!=null&&se.enabled?"#16a34a":"rgba(120,120,120,0.35)",transition:"background 0.18s ease"},children:e.jsx("span",{style:{position:"absolute",top:3,left:se!=null&&se.enabled?23:3,width:18,height:18,borderRadius:"50%",background:"#fff",boxShadow:"0 1px 2px rgba(0,0,0,0.25)",transition:"left 0.18s ease"}})})]}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground flex-shrink-0",children:"Not enrolled"})]}),Q.enrolled&&se?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Mode"}),e.jsx("select",{value:se.mode,disabled:K,onChange:me=>P(Q.shop,me.target.value),className:"w-full",style:{...ro,marginTop:2},children:Hx.map(me=>e.jsx("option",{value:me.value,children:me.label},me.value))})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Scope"}),e.jsx("select",{value:se.applyScope,disabled:K,onChange:me=>U(Q.shop,me.target.value),className:"w-full",style:{...ro,marginTop:2},children:XD.map(me=>e.jsx("option",{value:me.value,children:me.label},me.value))})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Digest recipients (comma-separated)"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"text",value:pe,disabled:K,placeholder:"[email protected], [email protected]",onChange:me=>y(Ne=>({...Ne,[Q.shop]:me.target.value})),className:"flex-1 min-w-0",style:ro}),e.jsx("button",{onClick:()=>M(Q.shop),disabled:K||g[Q.shop]===void 0,className:"px-3 py-1.5 bg-primary text-primary-foreground text-xs rounded-md hover:opacity-90 disabled:opacity-50 inline-flex items-center gap-1.5",children:"Save"})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 pt-3 border-t border-border",children:[e.jsx("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:se.lastRunAt?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Ns,{style:{width:12,height:12}}),"Last run ",no(se.lastRunAt),se.lastRunStats?` · ${se.lastRunStats.applied} applied, ${se.lastRunStats.pendingCreated} pending`:""]}):e.jsx("span",{children:"No runs yet"})}),e.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0",children:[e.jsxs("button",{onClick:()=>_(Q.shop),disabled:K||!se.enabled||H,title:H?"Auto-apply is globally paused":"Run auto-apply now",className:"px-3 py-1.5 bg-primary text-primary-foreground text-xs rounded-md hover:opacity-90 disabled:opacity-50 inline-flex items-center gap-1.5",children:[K?e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}):e.jsx(In,{style:{width:12,height:12}}),"Run now"]}),e.jsxs("button",{onClick:()=>B(Q.shop),className:"text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs",title:"Ap
411plied changes",children:[e.jsx(Zi,{style:{width:14,height:14}}),"Applied",A[Q.shop]?e.jsx(hr,{style:{width:16,height:16}}):e.jsx(Ot,{style:{width:16,height:16}})]}),e.jsxs("button",{onClick:()=>W(Q.shop),className:"text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs",title:"Recent events",children:["History",X?e.jsx(hr,{style:{width:16,height:16}}):e.jsx(Ot,{style:{width:16,height:16}})]})]})]}),X&&e.jsx("div",{className:"mt-3 space-y-1.5",children:b[Q.shop]?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}),"Loading eventsâ¦"]}):(x[Q.shop]||[]).length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No events yet."}):(x[Q.shop]||[]).map((me,Ne)=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsx("span",{className:"font-mono text-muted-foreground flex-shrink-0",children:me.kind}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-muted-foreground truncate",children:me.detail}),e.jsxs("p",{className:"text-muted-foreground/70",children:[me.actor," · ",no(me.createdAt)]})]})]},Ne))}),A[Q.shop]&&e.jsx("div",{className:"mt-3 space-y-2",children:S[Q.shop]?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}),"Loading applied changesâ¦"]}):(C[Q.shop]||[]).length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No applied changes yet."}):(C[Q.shop]||[]).map(me=>{const Ne=!!m[me.id],at=R[me.id],ae=[...sM,...me.applyScope==="full"?nM:[]].filter(xe=>me.before[xe.key]!==me.after[xe.key]);return e.jsxs("div",{className:"border border-border rounded-md p-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-foreground truncate",children:me.title}),e.jsxs("p",{className:"text-muted-foreground/70",style:{fontSize:11},children:[me.resourceType,me.appliedAt?` · applied ${no(me.appliedAt)}`:""]})]}),me.status==="reverted"?e.jsxs("span",{className:"text-xs font-medium flex-shrink-0",style:{color:"var(--muted-foreground)"},title:(me.revertedBy?`by ${me.revertedBy}`:"")+(me.revertedAt?` · ${no(me.revertedAt)}`:""),children:["Reverted",me.revertedAt?` · ${no(me.revertedAt)}`:""]}):e.jsxs("button",{onClick:()=>Y(Q.shop,me.id),disabled:Ne,className:"px-3 py-1 bg-muted text-foreground text-xs rounded-md hover:opacity-90 disabled:opacity-50 inline-flex items-center gap-1.5 flex-shrink-0",title:"Revert this change",children:[Ne?e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}):e.jsx(jg,{style:{width:12,height:12}}),"Revert"]})]}),ae.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:ae.map(xe=>e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:xe.label}),e.jsx("div",{style:{marginTop:2,textDecoration:"line-through",color:"var(--muted-foreground)",wordBreak:"break-word"},children:me.before[xe.key]||e.jsx("em",{children:"(empty)"})}),e.jsx("div",{className:"text-foreground",style:{marginTop:2,wordBreak:"break-word"},children:me.after[xe.key]||e.jsx("em",{children:"(empty)"})})]},String(xe.key)))}),at&&e.jsxs("div",{className:"mt-2 border rounded-md p-2 text-xs",style:{borderColor:"#fca5a5",background:"rgba(239,68,68,0.10)",color:"#b91c1c"},children:[e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(Dt,{style:{width:14,height:14,flexShrink:0,marginTop:1}}),e.jsxs("span",{children:["Live values changed:"," ",e.jsx("strong",{children:at.length?at.join(", "):"unknown fields"}),". Revert anyway?"]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs("button",{onClick:()=>Y(Q.shop,me.id,!0),disabled:Ne,className:"px-3 py-1 text-xs rounded-md hover:opacity-90 disabled:opacity-50 inline-flex items-center gap-1.5",style:{color:"#fff",background:"#b91c1c"},children:[Ne?e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}):null,"Revert anyway"]}),e.jsx("button",{onClick:()=>z(xe=>{const ze={...xe};return delete ze[me.id],ze}),className:"px-3 py-1 bg-muted text-foreground text-xs rounded-md hover:opacity-90",children:"Cancel"})]})]})]},me.id)})})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-3 pt-3 border-t border-border",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Enroll mode"}),e.jsx("select",{value:j[Q.shop]||"approve_all",disabled:K,onChange:me=>v(Ne=>({...Ne,[Q.shop]:me.target.value})),className:"w-full",style:{...ro,marginTop:2},children:Hx.map(me=>e.jsx("option",{value:me.value,children:me.label},me.value))})]}),e.jsxs("button",{onClick:()=>F(Q.shop),disabled:K,className:"px-3 py-1.5 bg-primary text-primary-foreground text-xs rounded-md hover:opacity-90 disabled:opacity-50 inline-flex items-center gap-1.5 flex-shrink-0",style:{alignSelf:"flex-end"},children:[K?e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}):null,"Enroll"]})]})]},Q.shop)})})]})]})}const aM=["Tickets","Messages","System"];function oM({onBack:t,onLogoClick:s}){const{token:n}=pt(),[r,a]=l.useState([]),[o,i]=l.useState(!0),[d,m]=l.useState(null);l.useEffect(()=>{let c=!1;return re("getNotificationSettings",{}).then(u=>{c||a(Array.isArray(u==null?void 0:u.globalDisabledTypes)?u.globalDisabledTypes:[])}).catch(u=>{c||ce.error("Failed to load notification settings",{description:u==null?void 0:u.message})}).finally(()=>{c||i(!1)}),()=>{c=!0}},[n]);const p=l.useCallback(async(c,u)=>{const x=u?r.filter(b=>b!==c):Array.from(new Set([...r,c])),h=r;a(x),m(c);try{const b=await re("setGlobalNotificationConfig",{disabledTypes:x},n??void 0);Array.isArray(b==null?void 0:b.disabledTypes)&&a(b.disabledTypes)}catch(b){a(h),ce.error("Could not save setting",{description:b==null?void 0:b.message})}finally{m(null)}},[r,n]);return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-2xl mx-auto pb-24",children:[e.jsx(Xe,{title:"Notifications",showTitle:!0,onLogoClick:s}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsxs("div",{className:"px-4 pt-4",children:[e.jsxs("button",{onClick:t,className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors mb-4",children:[e.jsx(dt,{style:{width:16,height:16}}),"Back"]}),e.jsx("p",{className:"text-muted-foreground text-sm mb-6",children:"Turn a notification type off to silence it for the whole team â in-app, push and email. Individuals can still mute their own notifications under Settings."}),o?e.jsxs("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:[e.jsx(fe,{className:"w-5 h-5 animate-spin mr-2"}),"Loadingâ¦"]}):aM.map(c=>{const u=_2.filter(x=>x.category===c);return u.length===0?null:e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-muted-foreground uppercase tracking-wide mb-3 px-1 text-sm",children:c}),e.jsx("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm",children:u.map((x,h)=>{const b=!r.includes(x.type);return e.jsxs("div",{className:`p-4 flex items-center justify-between gap-3 ${h<u.length-1?"border-b border-border":""}`,children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center flex-shrink-0",children:e.jsx(Dn,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-foreground",children:x.label}),e.jsx("p",{className:"text-muted-foreground text-sm",children:x.description})]})]}),e.jsx(Ca,{checked:b,disabled:d===x.type,onCheckedChange:f=>p(x.type,f)})]},x.type)})})]},c)})]})})]})}function iM({onCallerIdChange:t}={}){const{user:s}=pt(),n=ti(),[r,a]=l.useState("loading"),[o,i]=l.useState(null),[d,m]=l.useState(""),[p,c]=l.useState(null),[u,x]=l.useState(null),[h,b]=l.useState(!1),f=l.useCallback(async()=>{var j;if(s!=null&&s.uid)try{const v=await ps(ut(ge,"staffDirectory",s.uid)),T=v.exists()?(j=v.data())==null?void 0:j.voice:null;T!=null&&T.callerId&&(T!=null&&T.verifiedAt)?(i(T.callerId),t==null||t(T.callerId),a("verified")):(t==null||t(null),a("unverified"))}catch(v){console.error("[voice] loading dialer config failed:",v),a("unverified")}},[s==null?void 0:s.uid,t]);l.useEffect(()=>{f()},[f]);const g=async()=>{const j=si(d);if(!j){ce.error("Enter a valid phone number, including area code.");return}b(!0);try{const v=await re("startCallerIdVerification",{phoneNumber:j});if(v!=null&&v.alreadyVerified){i(v.phoneNumber??j),t==null||t(v.phoneNumber??j),a("verified"),ce.success("That number was already verified â you can call now.");return}c((v==null?void 0:v.validationCode)??null),x((v==null?void 0:v.phoneNumber)??j),a("awaiting-code")}catch(v){console.error("[voice] starting verification failed:",v),ce.error((v==null?void 0:v.message)||"Could not start verification")}finally{b(!1)}},y=async()=>{b(!0);try{const j=await re("checkCallerIdVerification");j!=null&&j.verified?(i(j.phoneNumber),t==null||t(j.phoneNumber),c(null),x(null),a("verified"),ce.success("Your number is verified â you can place calls now.")):ce.error("Twilio hasn't confirmed that number yet. Finish the call and try again.")}catch(j){console.error("[voice] confirming verification failed:",j),ce.error((j==null?void 0:j.message)||"Could not confirm verification")}finally{b(!1)}};return n?e.jsxs("div",{className:"mt-6 px-4",children:[e.jsx("h3",{className:"text-muted-foreground uppercase tracking-wide mb-3 px-1",children:"Dialer"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-3 px-1",children:"Verify your mobile once, then you can call clients from any phone number in Bucky. Clients see the number you verify here, and calls are logged against the ticket and client automatically."}),e.jsxs("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"w-10 h-10 bg-primary/20 rounded-xl flex items-center justify-center flex-shrink-0",children:r==="verified"?e.jsx(Ns,{className:"w-5 h-5 text-primary"}):e.jsx(En,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-foreground",children:"Your caller ID"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:r==="verified"?`Verified â ${cn(o)}`:"Not set up yet"})]})]}),r==="loading"&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"}),"Loadingâ¦"]}),r==="unverified"&&e.jsxs("div",{children:[e.jsx("input",{type:"tel",value:d,onChange:j=>m(j.target.value),placeholder:"(604) 555-1234",className:"w-full rounded-xl border border-border bg-background p-2 text-sm text-foreground mb-2"}),e.jsx("button",{onClick:g,disabled:h,className:"w-full px-3 py-2 rounded-xl text-sm bg-primary text-primary-foreground disabled:opacity-50 transition-opacity",children:h?"Calling youâ¦":"Verify my number"})]}),r==="awaiting-code"&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-muted-foreground text-sm mb-2",children:["We're calling ",cn(u),". Answer it and key in this code:"]}),e.jsx("p",{className:"text-foreground text-center py-3 mb-2 bg-muted rounded-xl",style:{letterSpacing:"0.25em"},children:p??"â¢â¢â¢â¢â¢â¢"}),e.jsx("button",{onClick:y,disabled:h,className:"w-full px-3 py-2 rounded-xl text-sm bg-primary text-primary-foreground disabled:opacity-50 transition-opacity mb-2",children:h?"Checkingâ¦":"I've entered the code"}),e.jsx("button",{onClick:()=>{a("unverified"),c(null),x(null)},className:"w-full px-3 py-2 rounded-xl text-sm text-muted-foreground hover:bg-muted transition-colors",children:"Start over"})]}),r==="verified"&&e.jsx("button",{onClick:()=>{m(""),a("unverified")},className:"w-full px-3 py-2 rounded-xl text-sm text-muted-foreground hover:bg-muted transition-colors",children:"Use a different number"})]})]}):null}function lM({callerId:t}){const s=Vl(),n=Zu(),[r,a]=l.useState(""),[o,i]=l.useState(!0);if(!s)return null;const d=si(r),m=s.phase!=="idle",p=r.trim().length>0,c=n?"Bucky Live is using the microphone â end the meeting to place a call":m?"You are already on a call":p?d?null:"That doesn't look like a valid number":"Enter a number to call",u=()=>
411{c||!d||(s.startCall({to:d,displayName:cn(d),logCall:o}),a(""),i(!0))};return e.jsxs("div",{className:"mt-6 px-4",children:[e.jsx("h3",{className:"text-muted-foreground uppercase tracking-wide mb-3 px-1",children:"Make a call"}),e.jsxs("div",{className:"bg-card rounded-2xl overflow-hidden shadow-sm p-4",children:[e.jsx("input",{type:"tel",value:r,onChange:x=>a(x.target.value),onKeyDown:x=>{x.key==="Enter"&&u()},placeholder:"(604) 555-1234",className:"w-full rounded-xl border border-border bg-background p-2 text-sm text-foreground mb-2"}),e.jsxs("button",{onClick:u,disabled:!!c,title:c??`Call ${cn(d)}`,className:"w-full flex items-center justify-center gap-2 px-3 py-2 rounded-xl text-sm bg-primary text-primary-foreground disabled:opacity-50 transition-opacity",children:[e.jsx(En,{className:"w-4 h-4"}),d?`Call ${cn(d)}`:"Call"]}),e.jsxs("label",{className:"flex items-center gap-2 mt-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:x=>i(x.target.checked)}),e.jsx("span",{className:"text-foreground text-sm",children:"Record and summarise this call"})]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-2",children:c&&p?c:o?t?`They'll see ${cn(t)}, and hear a short notice that the call is recorded.`:"Verify your number above before calling.":"This call won't be recorded â no history, no duration, no recap."})]})]})}function cM({onBack:t,onLogoClick:s}){const[n,r]=l.useState(null),a=l.useCallback(i=>r(i),[]),{user:o}=pt();return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-2xl mx-auto pb-24",children:[e.jsx(Xe,{title:"Dialer",showTitle:!0,onLogoClick:s}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"px-4 pt-4",children:[e.jsxs("button",{onClick:t,className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors mb-4",children:[e.jsx(dt,{style:{width:16,height:16}}),"Back"]}),e.jsx("p",{className:"text-muted-foreground text-sm mb-2",children:"Set up click-to-call. Verify your own mobile once and you can call clients from any phone number in Bucky â they see your number, and every call is logged against the ticket and client."})]}),e.jsx(iM,{onCallerIdChange:a}),n&&e.jsx(lM,{callerId:n}),(o==null?void 0:o.uid)&&e.jsx("div",{className:"px-4",children:e.jsx(Xu,{createdBy:o.uid,title:"Your recent calls",max:10})})]})]})}const dM="America/Vancouver";function uM(t,s=dM){const n=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),r=a=>{var o;return((o=n.find(i=>i.type===a))==null?void 0:o.value)??""};return`${r("year")}-${r("month")}-${r("day")}`}function us(t,s){const n=new Date(`${t}T00:00:00Z`);return n.setUTCDate(n.getUTCDate()+s),n.toISOString().slice(0,10)}function jl(t,s){const[n,r,a]=t.split("-").map(Number),o=new Date(Date.UTC(n,r-1+s,1)),i=new Date(Date.UTC(o.getUTCFullYear(),o.getUTCMonth()+1,0)).getUTCDate();return o.setUTCDate(Math.min(a,i)),o.toISOString().slice(0,10)}function mM(t,s){return Math.round((new Date(`${s}T00:00:00Z`).getTime()-new Date(`${t}T00:00:00Z`).getTime())/864e5)}function pM(t){const s=new Date(`${t}T00:00:00Z`).getUTCDay();return us(t,-(s===0?6:s-1))}function xM(t){return`${t.slice(0,7)}-01`}function hM(t){const[s,n]=t.split("-").map(Number);return new Date(Date.UTC(s,n,0)).toISOString().slice(0,10)}function ln(t){return new Date(`${t}T12:00:00Z`).toLocaleDateString("en-CA",{month:"short",day:"numeric",timeZone:"UTC"})}function fM(t){return new Date(`${t}T12:00:00Z`).toLocaleDateString("en-CA",{month:"long",year:"numeric",timeZone:"UTC"})}function gM(t){return new Date(`${t}T12:00:00Z`).toLocaleDateString("en-CA",{weekday:"short",timeZone:"UTC"})}function Po(t,s,n){var o;const r=s.toUpperCase();if(r==="CAD")return Math.round(t);const a=(o=n==null?void 0:n.rates)==null?void 0:o[r];return!a||!Number.isFinite(a)?null:Math.round(t*a+Number.EPSILON)}function xs(t,s,n={}){const r=s.toUpperCase(),o={CAD:"CA$",USD:"US$",EUR:"â¬",GBP:"£"}[r]??`${r}
411 `,i=Math.abs(t)/100,d=n.compact&&Number.isInteger(i),m=i.toLocaleString("en-CA",{minimumFractionDigits:d?0:2,maximumFractionDigits:d?0:2});return`${t<0?"-":""}${o}${m}`}function Zc(t,s,n){const r=xs(t,s,{compact:!0});return s.toUpperCase()==="CAD"||n==null?r:`${r} â ${xs(n,"CAD",{compact:!0})}`}function bM(t,s,n,r){const a=Math.max(1,n||1)*r;switch(s){case"day":return us(t,a);case"week":return us(t,7*a);case"year":return jl(t,12*a);default:return jl(t,a)}}function yM(t,s,n,r){const a=[];for(const o of t){if(o.status==="canceled"){o.canceledAt&&o.canceledAt>=s&&o.canceledAt<=n&&a.push({docId:o.id,doc:o,date:o.canceledAt,amount:0,currency:o.currency,amountCad:0,projected:!1,ended:!0});continue}if(o.status==="paused"||!o.nextCharge)continue;const i=(o.status==="cancel_scheduled"||o.status==="scheduled")&&o.cancelAt?o.cancelAt:null,d=o.nextCharge.date;for(let m=0;m<400;m++){const p=bM(d,o.interval,o.intervalCount,m);if(p>n||i&&p>=i)break;if(p>=s){const c=m===0,u=c?o.nextCharge.total:o.listAmount,x=c?o.nextChargeCad??Po(u,o.currency,r):Po(u,o.currency,r);a.push({docId:o.id,doc:o,date:p,amount:u,currency:c?o.nextCharge.currency:o.currency,amountCad:x,projected:!c})}}i&&i>=s&&i<=n&&a.push({docId:o.id,doc:o,date:i,amount:0,currency:o.currency,amountCad:0,projected:!1,ended:!0})}return a.sort((o,i)=>o.date===i.date?(i.amountCad??0)-(o.amountCad??0):o.date<i.date?-1:1)}const jM={scheduled:{bg:"rgba(59,130,246,0.12)",fg:"#1d4ed8",border:"rgba(59,130,246,0.5)"},active:{bg:"rgba(16,185,129,0.12)",fg:"#047857",border:"rgba(16,185,129,0.5)"},cancel_scheduled:{bg:"rgba(245,158,11,0.14)",fg:"#b45309",border:"rgba(245,158,11,0.6)"},past_due:{bg:"rgba(239,68,68,0.12)",fg:"#b91c1c",border:"rgba(239,68,68,0.6)"},canceled:{bg:"rgba(107,114,128,0.12)",fg:"#4b5563",border:"rgba(107,114,128,0.5)"},paused:{bg:"rgba(107,114,128,0.12)",fg:"#4b5563",border:"rgba(107,114,128,0.5)"}};function vM({c:t,selected:s,onSelect:n}){const r=jM[t.ended?"canceled":t.doc.status],a=t.doc.provider==="stripe"?"S":"R",o=t.ended?`${t.doc.customerName} · ended`:`${t.doc.customerName} · ${xs(t.amount,t.currency,{compact:!0})}`,i=!t.ended&&t.currency.toUpperCase()!=="CAD"&&t.amountCad!=null?`â ${xs(t.amountCad,"CAD",{compact:!0})}`:null;return e.jsxs("button",{type:"button",onClick:()=>n(t.docId),title:`${t.doc.customerName} â ${t.doc.productLabel}${t.projected?" (projected)":""}`,style:{display:"block",width:"100%",textAlign:"left",borderRadius:6,padding:"2px 6px",fontSize:11,lineHeight:"14px",marginBottom:3,cursor:"pointer",background:t.projected?"transparent":r.bg,color:r.fg,border:`1px ${t.projected?"dashed":"solid"} ${r.border}`,outline:s?`2px solid ${r.fg}`:"none"},children:[e.jsx("span",{style:{fontWeight:600,marginRight:4,opacity:.7},children:a}),e.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",display:"inline-block",maxWidth:"100%",verticalAlign:"bottom"},children:o}),i&&e.jsx("div",{style:{opacity:.75,fontSize:10},children:i})]})}function wM({docs:t,fx:s,month:n,today:r,onMonthChange:a,onSelect:o,selectedId:i,dateShift:d,totalLabel:m="this month"}){const p=xM(n),c=hM(n),u=new Date(`${p}T00:00:00Z`).getUTCDay(),x=us(p,-((u+6)%7)),h=new Date(`${c}T00:00:00Z`).getUTCDay(),b=us(c,(7-h)%7),f=l.useMemo(()=>{const j=new Map,v=d?us(x,-14):x;for(const T of yM(t,v,b,s)){const k=d&&!T.ended?{...T,date:d(T.date,T.doc)}:T;if(k.date<x||k.date>b)continue;const w=j.get(k.date)||[];w.push(k),j.set(k.date,w)}return j},[t,s,x,b,d]),g=[];for(let j=x;j<=b;j=us(j,1))g.push(j);const y=Array.from(f.entries()).filter(([j])=>j>=p&&j<=c).reduce((j,[,v])=>j+v.reduce((T,k)=>T+(k.ended?0:k.amountCad??0),0),0);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("button",{type:"button",onClick:()=>a(jl(p,-1)),className:"p-1 rounded hover:bg-muted","aria-label":"Previous month",children:e.jsx(fr,{style:{width:18,height:18}})}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:fM(p)}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["â ",xs(y,"CAD",{compact:!0})," ",m," · dashed = projected"]})]}),e.jsx("button",{type:"button",onClick:()=>a(jl(p,1)),className:"p-1 rounded hover:bg-muted","aria-label":"Next month",children:e.jsx(Rt,{style:{width:18,height:18}})})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, minmax(0, 1fr))",gap:4},children:[["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(j=>e.jsx("div",{className:"text-xs text-muted-foreground text-center py-1",children:j},j)),g.map(j=>{const v=j>=p&&j<=c,T=f.get(j)||[],k=T.reduce((I,A)=>I+(A.ended?0:A.amountCad??0),0),w=j===r;return e.jsxs("div",{style:{minHeight:84,borderRadius:8,padding:4,border:`1px solid ${w?"var(--primary, #2563eb)":"var(--border, #e5e7eb)"}`,opacity:v?1:.45,background:"var(--card, transparent)"},children:[e.jsxs("div",{className:"flex items-center justify-between",style:{fontSize:11,marginBottom:2},children:[e.jsx("span",{style:{fontWeight:w?700:500},children:Number(j.slice(8,10))}),k>0&&e.jsx("span",{className:"text-muted-foreground",children:xs(k,"CAD",{compact:!0})})]}),T.map((I,A)=>e.jsx(vM,{c:I,selected:i===I.docId,onSelect:o},`${I.docId}-${A}`))]},j)})]})]})}const Ny={stripeDelayDays:5,stripeInterval:"daily",stripeWeeklyAnchor:null,stripeMonthlyAnchor:null,shopifyDelayBusinessDays:2,source:"default"},NM=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function nm(t){return new Date(`${t}T00:00:00Z`).getUTCDay()}function qx(t){const s=nm(t);return s===6?us(t,2):s===0?us(t,1):t}
411function kM(t,s){let n=t,r=s;for(;r>0;){n=us(n,1);const a=nm(n);a!==0&&a!==6&&r--}return n}function SM(t,s,n=Ny){if(s==="recharge")return kM(t,n.shopifyDelayBusinessDays);const r=us(t,n.stripeDelayDays);if(n.stripeInterval==="weekly"&&n.stripeWeeklyAnchor){const a=NM.indexOf(n.stripeWeeklyAnchor.toLowerCase());if(a>=0){let o=r;for(;nm(o)!==a;)o=us(o,1);return o}}if(n.stripeInterval==="monthly"&&n.stripeMonthlyAnchor){let a=r;for(let o=0;o<40;o++){if(Number(a.slice(8,10))===n.stripeMonthlyAnchor)return qx(a);a=us(a,1)}}return qx(r)}function CM(t){return`${t.stripeInterval==="weekly"&&t.stripeWeeklyAnchor?`Stripe: ${t.stripeDelayDays}-day hold, paid out ${t.stripeWeeklyAnchor}s`:t.stripeInterval==="monthly"&&t.stripeMonthlyAnchor?`Stripe: ${t.stripeDelayDays}-day hold, paid out on the ${t.stripeMonthlyAnchor}th`:`Stripe: ${t.stripeDelayDays}-day hold, next business day`} · Shopify Payments: ${t.shopifyDelayBusinessDays} business days${t.source==="default"?" (assumed)":""}`}function TM(t,s,n){const r=us(s,6),a=Array.from({length:7},(m,p)=>({date:us(s,p),charges:[],totalCad:0})),o={};let i=0,d=0;for(const m of t){const p=m.nextCharge;if(!p||m.status==="canceled"||m.status==="paused"||p.date<s||p.date>r)continue;const c=m.nextChargeCad??Po(p.total,p.currency,n),u=p.currency.toUpperCase();a.find(x=>x.date===p.date).charges.push({docId:m.id,doc:m,date:p.date,amount:p.total,currency:u,amountCad:c}),c!=null&&(i+=c),o[u]=(o[u]||0)+p.total,d++}for(const m of a)m.charges.sort((p,c)=>(c.amountCad??0)-(p.amountCad??0)),m.totalCad=m.charges.reduce((p,c)=>p+(c.amountCad??0),0);return{weekStart:s,weekEnd:r,days:a,totalsByCurrency:o,totalCad:i,count:d}}function Vx(t,s,n,r){const a={};let o=0,i=0;for(const d of t){const m=d.nextCharge;if(!m||d.status==="canceled"||d.status==="paused"||m.date<s||m.date>n)continue;const p=m.currency.toUpperCase();a[p]=(a[p]||0)+m.total,o+=d.nextChargeCad??Po(m.total,m.currency,r)??0,i++}return{byCurrency:a,cad:o,count:i}}const Ai={scheduled:{label:"Scheduled",className:"bg-blue-500/10 text-blue-700 border-blue-500/40"},active:{label:"Active",className:"bg-emerald-600/10 text-emerald-700 border-emerald-600/30"},cancel_scheduled:{label:"Ending",className:"bg-amber-500/10 text-amber-700 border-amber-500/40"},past_due:{label:"Past due",className:"bg-red-500/10 text-red-700 border-red-500/40"},canceled:{label:"Cancelled",className:"bg-muted text-muted-foreground"},paused:{label:"Paused",className:"bg-muted text-muted-foreground"}};function Yx(t){const s=t.intervalCount;return t.interval==="week"&&s===4?"every 4 weeks":s===1?t.interval==="day"?"daily":t.interval==="week"?"weekly":t.interval==="month"?"monthly":"yearly":`every ${s} ${t.interval}s`}function nl(t,s){const n=t.paymentMethod;if(!n&&t.paymentMethodUnknown)return{text:"unknown (lookup failed)",bad:!1};if(!n)return{text:t.collectionMethod==="send_invoice"?"send invoice":"none",bad:t.collectionMethod!=="send_invoice"};const r=n.expMonth&&n.expYear?`${String(n.expMonth).padStart(2,"0")}/${String(n.expYear).slice(2)}`:"";let a=!1;if(s&&n.expMonth&&n.expYear){const[o,i]=s.split("-").map(Number);a=n.expYear<o||n.expYear===o&&n.expMonth<i}return{text:`${n.brand||"card"} ····${n.last4||"????"}${r?` ${r}`:""}`,bad:a}}function AM(t,s){if(t.status==="past_due")return!0;const n=t.openInvoice;return(n==null?void 0:n.collectionMethod)==="send_invoice"&&n.dueDate&&n.dueDate<s||t.nextCharge&&nl(t,t.nextCharge.date).bad?!0:!t.paymentMethod&&!t.paymentMethodUnknown&&t.collectionMethod==="charge_automatically"&&!!t.nextCharge&&mM(s,t.nextCharge.date)<=14}function EM({onBack:t,onLogoClick:s,focusId:n}){var _,G;const{user:r}=pt(),[a,o]=l.useState([]),[i,d]=l.useState(null),[m,p]=l.useState(null),[c,u]=l.useState(!1),[x,h]=l.useState(!1),[b,f]=l.useState(!1),[g,y]=l.useState("all"),[j,v]=l.useState(n??null),T=l.useMemo(()=>uM(new Date),[]),[k,w]=l.useState("charges"),[I,A]=l.useState(T);l.useEffect(()=>{const B=qt(Re(ge,"billingSubscriptions"),H=>{o(H.docs.map(Z=>Z.data())),u(!0)},H=>ce.error("Could not load subscriptions",{description:H.message})),Y=qt(ut(ge,"fxRates","latest"),H=>d(H.data()||null)),J=qt(ut(ge,"billingSubscriptionSync","latest"),H=>p(H.data()||null));return()=>{B(),Y(),J()}},[]),l.useEffect(()=>{n&&v(n)},[n]);const E=i!=null&&i.rates?{rates:i.rates,asOf:i.asOf}:null,C=l.useMemo(()=>
411a.filter(B=>B.status!=="canceled"),[a]),N=(m==null?void 0:m.payouts)??Ny,S=l.useCallback((B,Y)=>SM(B,Y.provider,N),[N]),O=l.useMemo(()=>k==="charges"?a:a.map(B=>B.nextCharge?{...B,nextCharge:{...B.nextCharge,date:S(B.nextCharge.date,B)}}:B),[a,k,S]),R=l.useMemo(()=>TM(O,pM(T),E),[O,T,E]),z=l.useMemo(()=>Vx(O,T,us(T,6),E),[O,T,E]),D=l.useMemo(()=>Vx(O,T,us(T,29),E),[O,T,E]),L=k==="charges"?"charge":"deposit",$=l.useMemo(()=>C.filter(B=>AM(B,T)),[C,T]),q=l.useMemo(()=>$.reduce((B,Y)=>B+(Y.openInvoice?Po(Y.openInvoice.amountDue,Y.openInvoice.currency,E)??0:Y.nextChargeCad??0),0),[$,E]),P=l.useMemo(()=>a.filter(B=>B.status==="cancel_scheduled"||B.status==="canceled"&&!!B.canceledAt&&B.canceledAt>=us(T,-30)),[a,T]),U=l.useMemo(()=>{let B=a.slice();return g==="stripe"?B=B.filter(Y=>Y.provider==="stripe"&&Y.status!=="canceled"):g==="recharge"?B=B.filter(Y=>Y.provider==="recharge"&&Y.status!=="canceled"):g==="problems"?B=$:g==="ending"?B=P:g==="yearly"?B=B.filter(Y=>Y.interval==="year"&&Y.status!=="canceled"):B=B.filter(Y=>Y.status!=="canceled"),B.sort((Y,J)=>{var Q,K;const H=((Q=Y.nextCharge)==null?void 0:Q.date)||"9999",Z=((K=J.nextCharge)==null?void 0:K.date)||"9999";return H===Z?(J.nextChargeCad??0)-(Y.nextChargeCad??0):H<Z?-1:1})},[a,g,$,P]),V=a.find(B=>B.id===j)||null,M=async()=>{var B,Y,J,H,Z,Q;h(!0);try{const K=await re("refreshBillingSubscriptions",{},void 0,{timeoutMs:3e5}),X=[((B=K==null?void 0:K.stripe)==null?void 0:B.error)&&`Stripe: ${K.stripe.error}`,((Y=K==null?void 0:K.recharge)==null?void 0:Y.error)&&`Recharge: ${K.recharge.error}`].filter(Boolean);ce[X.length?"warning":"success"](`Synced ${((J=K==null?void 0:K.stripe)==null?void 0:J.count)??0} Stripe + ${((H=K==null?void 0:K.recharge)==null?void 0:H.count)??0} Recharge subscriptions`,{description:X.length?X.join(" · "):`${((Z=K==null?void 0:K.alerts)==null?void 0:Z.length)??0} alert(s) raised · FX as of ${((Q=K==null?void 0:K.fx)==null?void 0:Q.asOf)||"n/a"}`})}catch(K){ce.error("Refresh failed",{description:K==null?void 0:K.message})}finally{h(!1)}},F=async()=>{var B,Y;f(!0);try{const J=await re("previewWeeklySubscriptionSummary",{},void 0,{timeoutMs:12e4});ce.success(`Preview sent to ${(r==null?void 0:r.email)||"you"}`,{description:`${(B=J==null?void 0:J.summary)==null?void 0:B.label}: â ${xs(((Y=J==null?void 0:J.summary)==null?void 0:Y.totalCad)??0,"CAD")}`})}catch(J){ce.error("Preview failed",{description:J==null?void 0:J.message})}finally{f(!1)}},W=B=>Object.entries(B).map(([Y,J])=>xs(J,Y,{compact:!0})).join(" + ")||"â";return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-5xl mx-auto pb-24",children:[e.jsx(Xe,{title:"Subscriptions",showTitle:!0,onLogoClick:s}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 gap-2 flex-wrap",children:[e.jsxs("button",{onClick:t,className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(dt,{style:{width:16,height:16}})," Back"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:F,disabled:b,className:"inline-flex items-center gap-1 text-sm px-3 py-1.5 rounded-md border hover:bg-muted disabled:opacity-50",children:[e.jsx(Tn,{style:{width:14,height:14}})," Email me this week"]}),e.jsxs("button",{onClick:M,disabled:x,className:"inline-flex items-center gap-1 text-sm px-3 py-1.5 rounded-md bg-primary text-primary-foreground hover:opacity-90 disabled:opacity-50",children:[e.jsx(yt,{style:{width:14,height:14},className:x?"animate-spin":""})," ",x?"Syncingâ¦":"Refresh from providers"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-3 flex-wrap",children:[e.jsxs("div",{className:"inline-flex rounded-md border overflow-hidden text-sm",children:[e.jsxs("button",{type:"button",onClick:()=>w("charges"),style:{padding:"6px 12px"},className:`inline-flex items-center gap-1 ${k==="charges"?"bg-primary text-primary-foreground":"hover:bg-muted"}`,children:[e.jsx(If,{style:{width:14,height:14}})," Charges"]}),e.jsxs("button",{type:"button",onClick:()=>w("deposits"),style:{padding:"6px 12px"},className:`inline-flex items-center gap-1 ${k==="deposits"?"bg-primary text-primary-foreground":"hover:bg-muted"}`,children:[e.jsx(Jw,{style:{width:14,height:14}})," Deposits"]})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k==="charges"?"When customers are billed.":`When the money lands. ${CM(N)}. Gross amounts, before processor fees.`})]}),e.jsxs("div",{className:"grid gap-3 mb-4",style:{gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))"},children:[e.jsx(jt,{children:e.jsxs(vt,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Next 7 days"}),e.jsxs("div",{className:"text-2xl font-semibold",children:["â ",xs(z.cad,"CAD",{compact:!0})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[W(z.byCurrency)," · ",z.count," ",L,z.count===1?"":"s"]})]})}),e.jsx(jt,{children:e.jsxs(vt,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Next 30 days"}),e.jsxs("div",{className:"text-2xl font-semibold",children:["â ",xs(D.cad,"CAD",{compact:!0})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[W(D.byCurrency)," · ",D.count," ",L,D.count===1?"":"s"]})]})}),e.jsx(jt,{children:e.jsxs(vt,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Past due / at risk"}),e.jsx("div",{className:`text-2xl font-semibold ${$.length?"text-red-700":""}`,children:$.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:$.length?`â ${xs(q,"CAD",{compact:!0})} outstanding`:"nothing outstanding"})]})}),e.jsx(jt,{children:e.jsxs(vt,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Ending"}),e.jsx("div",{className:`text-2xl font-semibold ${P.length?"text-amber-700":""}`,children:P.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"cancel scheduled or cancelled in 30 days"})]})})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mb-4 flex flex-wrap gap-x-3 gap-y-1",children:[e.jsxs("span",{children:["FX: ",E?`USD ${E.rates.USD??"â"}${E.rates.EUR?`, EUR ${E.rates.EUR}`:""} · Bank of Canada ${E.asOf}`:"no rate loaded"]}),(i==null?void 0:i.stale)&&e.jsx(Wt,{variant:"outline",className:"bg-amber-500/10 text-amber-700 border-amber-500/40",children:"rate fetch failed â carried forward"}),m&&e.jsxs("span",{children:["· synced ",new Date(m.ranAt).toLocaleStr
411ing("en-CA",{timeZone:"America/Vancouver",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),m.stripe.error?` · Stripe: ${m.stripe.error}`:"",m.recharge.error?` · Recharge: ${m.recharge.error}`:""]}),c&&a.length===0&&e.jsx("span",{children:"· no data yet â hit Refresh"})]}),e.jsx(jt,{className:"mb-4",children:e.jsxs(vt,{className:"p-4",children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-2",children:[e.jsxs("div",{className:"font-semibold",children:[k==="charges"?"This week":"Deposits this week"," · ",ln(R.weekStart)," â ",ln(R.weekEnd)]}),e.jsxs("div",{className:"text-sm",children:["â ",xs(R.totalCad,"CAD",{compact:!0})," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",W(R.totalsByCurrency),")"]})]})]}),R.count===0?e.jsxs("div",{className:"text-sm text-muted-foreground",children:["No ",L,"s expected this week."]}):e.jsx("div",{className:"text-sm",children:R.days.filter(B=>B.charges.length).map(B=>e.jsxs("div",{className:"flex gap-3 py-1 border-b last:border-b-0",style:{borderColor:"var(--border, #e5e7eb)"},children:[e.jsxs("div",{className:"w-16 shrink-0 text-muted-foreground",children:[gM(B.date)," ",Number(B.date.slice(8))]}),e.jsx("div",{className:"flex-1",children:B.charges.map(Y=>e.jsxs("button",{type:"button",onClick:()=>v(Y.docId),className:"block text-left w-full hover:underline",children:[e.jsx("span",{className:"text-muted-foreground mr-1",children:Y.doc.provider==="stripe"?"S":"R"}),e.jsx("span",{className:"font-medium",children:Y.doc.customerName})," ",e.jsxs("span",{className:"text-muted-foreground",children:["â ",Y.doc.productLabel]})]},Y.docId))}),e.jsx("div",{className:"text-right whitespace-nowrap",children:B.charges.map(Y=>e.jsx("div",{children:Zc(Y.amount,Y.currency,Y.amountCad)},Y.docId))})]},B.date))})]})}),e.jsx(jt,{className:"mb-4",children:e.jsx(vt,{className:"p-4",children:e.jsx(wM,{docs:a,fx:E,month:I,today:T,onMonthChange:A,onSelect:v,selectedId:j,dateShift:k==="deposits"?S:void 0,totalLabel:k==="deposits"?"landing this month":"this month"})})}),V&&e.jsx(jt,{className:"mb-4",style:{borderColor:"var(--primary, #2563eb)"},children:e.jsxs(vt,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-lg",children:[V.customerName," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",V.productLabel]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[V.customerEmail," · ",V.provider==="stripe"?"Stripe":"Recharge"," ",V.providerId,V.clientId?` · client ${V.clientId}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{variant:"outline",className:Ai[V.status].className,children:Ai[V.status].label}),e.jsxs("a",{href:V.providerUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm underline",children:[e.jsx(Da,{style:{width:14,height:14}})," Open in ",V.provider==="stripe"?"Stripe":"Recharge"]}),e.jsx("button",{onClick:()=>v(null),className:"text-sm text-muted-foreground hover:text-foreground",children:"Close"})]})]}),e.jsxs("div",{className:"grid gap-x-6 gap-y-1 mt-3 text-sm",style:{gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))"},children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Plan:"})," ",Zc(V.listAmount,V.currency,V.listAmountCad)," ",Yx(V)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Next charge:"})," ",V.nextCharge?`${ln(V.nextCharge.date)} · ${Zc(V.nextCharge.total,V.nextCharge.currency,V.nextChargeCad)}${V.nextCharge.tax?` (incl. ${xs(V.nextCharge.tax,V.nextCharge.currency)} tax)`:""}`:"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Last paid:"})," ",V.lastPaid?`${ln(V.lastPaid.date)} · ${xs(V.lastPaid.amount,V.lastPaid.currency)}`:"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Card:"})," ",e.jsx("span",{className:nl(V,((_=V.nextCharge)==null?void 0:_.date)||null).bad?"text-red-700":"",children:nl(V,((G=V.nextCharge)==null?void 0:G.date)||null).text})," · ",V.collectionMethod==="send_invoice"?"send invoice":"auto-charge"]}),V.status==="scheduled"&&V.nextCharge&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Starts:"})," ",ln(V.nextCharge.date)," (scheduled, no subscription yet)"]}),V.cancelAt&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Ends:"})," ",ln(V.cancelAt)]}),V.canceledAt&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Cancelled:"})," ",ln(V.canceledAt)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Period:"})," ",V.currentPeriodStart||"â"," â ",V.currentPeriodEnd||"â"]}
411),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Synced:"})," ",new Date(V.syncedAt).toLocaleString("en-CA",{timeZone:"America/Vancouver"}),V.fxAsOf?` · FX ${V.fxAsOf}`:""]})]}),V.openInvoice&&e.jsxs("div",{className:"mt-3 p-3 rounded-md text-sm",style:{background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.4)"},children:[e.jsxs("div",{className:"font-medium text-red-700",children:["Open ",V.provider==="stripe"?"invoice":"charge"," ",V.openInvoice.number||V.openInvoice.id,": ",xs(V.openInvoice.amountDue,V.openInvoice.currency)]}),e.jsxs("div",{className:"text-muted-foreground",children:[V.openInvoice.dueDate?`Due ${ln(V.openInvoice.dueDate)} · `:"",V.openInvoice.collectionMethod==="send_invoice"?"send-invoice (no automatic retry)":`${V.openInvoice.attemptCount} attempt(s)`,V.openInvoice.retryDate?` · retry ${ln(V.openInvoice.retryDate)}`:"",V.openInvoice.lastError?` · ${V.openInvoice.lastError}`:""]}),V.openInvoice.hostedUrl&&e.jsx("a",{href:V.openInvoice.hostedUrl,target:"_blank",rel:"noreferrer",className:"underline",children:"Hosted invoice link"})]}),Object.keys(V.alerts||{}).length>0&&e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Alerts sent: ",Object.entries(V.alerts).map(([B,Y])=>`${B} (${Y})`).join(" · ")]})]})}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mb-2 text-sm",children:["all","stripe","recharge","problems","ending","yearly"].map(B=>e.jsx("button",{type:"button",onClick:()=>y(B),style:{padding:"4px 12px"},className:`rounded-full border ${g===B?"bg-primary text-primary-foreground border-primary":"hover:bg-muted"}`,children:B==="all"?"All":B==="stripe"?"Stripe":B==="recharge"?"Recharge":B==="problems"?`Problems (${$.length})`:B==="ending"?`Ending (${P.length})`:"Yearly"},B))}),e.jsx(jt,{children:e.jsx(vt,{className:"p-0",children:e.jsx("div",{style:{overflowX:"auto"},children:e.jsxs("table",{className:"w-full text-sm",style:{borderCollapse:"collapse"},children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-muted-foreground",style:{borderBottom:"1px solid var(--border, #e5e7eb)"},children:[e.jsx("th",{className:"p-2",children:"Via"}),e.jsx("th",{className:"p-2",children:"Customer"}),e.jsx("th",{className:"p-2",children:"Product"}),e.jsx("th",{className:"p-2 text-right",children:"Amount"}),e.jsx("th",{className:"p-2 text-right",children:"CAD"}),e.jsx("th",{className:"p-2",children:"Next charge"}),e.jsx("th",{className:"p-2",children:"Status"}),e.jsx("th",{className:"p-2",children:"Card"})]})}),e.jsxs("tbody",{children:[U.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"p-4 text-center text-muted-foreground",children:c?"Nothing matches.":"Loadingâ¦"})}),U.map(B=>{var H;const Y=nl(B,((H=B.nextCharge)==null?void 0:H.date)||null),J=B.nextCharge?B.nextChargeCad:B.listAmountCad;return e.jsxs("tr",{onClick:()=>v(B.id),className:"cursor-pointer hover:bg-muted/50",style:{borderBottom:"1px solid var(--border, #e5e7eb)",background:j===B.id?"var(--muted, rgba(0,0,0,0.04))":void 0},children:[e.jsx("td",{className:"p-2 text-muted-foreground",children:B.provider==="stripe"?"Stripe":"Recharge"}),e.jsx("td",{className:"p-2 font-medium whitespace-nowrap",children:B.customerName}),e.jsxs("td",{className:"p-2",children:[B.productLabel,e.jsx("div",{className:"text-xs text-muted-foreground",children:Yx(B)})]}),e.jsx("td",{className:"p-2 text-right whitespace-nowrap",children:xs(B.nextCharge?B.nextCharge.total:B.listAmount,B.nextCharge?B.nextCharge.currency:B.currency,{compact:!0})}),e.jsx("td",{className:"p-2 text-right whitespace-nowrap text-muted-foreground",children:J==null?"n/a":xs(J,"CAD",{compact:!0})}),e.jsx("td",{className:"p-2 whitespace-nowrap",children:B.nextCharge?ln(B.nextCharge.date):B.cancelAt?`ends ${ln(B.cancelAt)}`:"â"}),e.jsx("td",{className:"p-2",children:e.jsx(Wt,{variant:"outline",className:Ai[B.status].className,children:Ai[B.status].label})}),e.jsx("td",{className:`p-2 whitespace-nowrap ${Y.bad?"text-red-700":"text-muted-foreground"}`,children:Y.text})]},B.id)})]})]})})})})]})]})}function IM({onBack:t,onLogoClick:s}){const[n,r]=l.useState(null),[a,o]=l.useState(null),[i,d]=l.useState(!1),m=l.useCallback(async()=>{o(null);try{r(await re("manageFunctionWarming",{action:"status"}))}catch(u){o(u.message)}},[]);l.useEffect(()=>{m()},[m]);const p=async u=>
411{if(!i){d(!0),o(null);try{r(await re("manageFunctionWarming",{action:"setEnabled",enabled:u}))}catch(x){o(x.message)}finally{d(!1)}}},c=n==null?void 0:n.lastRun;return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-2xl mx-auto pb-24",children:[e.jsx(Xe,{title:"Server Warming",showTitle:!0,onLogoClick:s}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 pt-4",children:[e.jsxs("button",{onClick:t,className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors mb-4",children:[e.jsx(dt,{style:{width:16,height:16}}),"Back"]}),e.jsx("div",{className:"rounded-xl border border-border bg-card p-4 mb-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-orange-500/10 flex items-center justify-center",children:e.jsx(sg,{className:"w-5 h-5 text-orange-500"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-foreground",children:"Keep functions warm"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:n?`Pings ${n.functionCount} functions every 10 min, 5amâ8pm PT`:"Loadingâ¦"})]})]}),e.jsx(Ca,{checked:!!(n!=null&&n.enabled),disabled:i||!n,onCheckedChange:p})]})}),e.jsxs("div",{className:"rounded-xl border border-amber-300/60 bg-amber-500/10 p-4 mb-4 text-sm text-foreground",children:[e.jsx("strong",{children:"Deploying?"})," Turn warming OFF first â warm instances hold the regional CPU quota that deploys need for their health checks. Instances drain about 15 minutes after the last ping; turn it back ON when the deploy is done."]}),a&&e.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 mb-4 text-sm text-destructive",children:a}),c&&e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"font-semibold text-foreground",children:"Last sweep"}),e.jsxs("button",{onClick:m,className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(yt,{style:{width:14,height:14}}),"Refresh"]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground space-y-1",children:[e.jsx("div",{children:c.at?new Date(c.at).toLocaleString():"â"}),e.jsxs("div",{children:[c.pinged??0," pinged · ",c.coldCount??0," were cold ·"," ",Math.round((c.durationMs??0)/1e3),"s sweep"]}),c.coldNames.length>0&&e.jsxs("div",{className:"break-words",children:["Cold: ",c.coldNames.join(", ")]}),c.unreachable.length>0&&e.jsxs("div",{className:"break-words text-destructive",children:["Unreachable: ",c.unreachable.join(", ")]})]})]})]})]})}const RM="node scripts/mockups/publish.cjs <payload-folder>";function Gx({text:t,label:s}){const[n,r]=l.useState(!1),a=async()=>{try{await navigator.clipboard.writeText(t),r(!0),setTimeout(()=>r(!1),1500)}catch{}};return e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",title:t,children:[n?e.jsx(kt,{style:{width:14,height:14}}):e.jsx(Hr,{style:{width:14,height:14}}),n?"Copied":s]})}function Kx({text:t}){return e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-muted text-muted-foreground",children:t})}function DM({onBack:t,onLogoClick:s}){const[n,r]=l.useState(null),[a,o]=l.useState(null),[i,d]=l.useState(""),m=l.useCallback(async()=>{o(null);try{const c=await re("listMockups",{});r(c.mockups)}catch(c){o(c.message)}},[]);l.useEffect(()=>{m()},[m]);const p=l.useMemo(()=>{const c=i.trim().toLowerCase(),u=new Map;for(const x of n??[]){const h=`${x.companyName} ${x.title} ${x.slug} ${x.versionLabel??""}`.toLowerCase();if(c&&!h.includes(c))continue;const b=u.get(x.companySlug)??[];b.push(x),u.set(x.companySlug,b)}return[...u.values()]},[n,i]);return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-2xl mx-auto pb-24",children:[e.jsx(Xe,{title:"Client Mockups",showTitle:!0,onLogoClick:s}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("button",{onClick:t,className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(dt,{style:{width:16,height:16}}),"Back"]}),e.jsxs("button",{onClick:m,className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(yt,{style:{width:14,height:14}}),"Refresh"]})]}),e.jsxs("div",{className:"relative mb-4",children:[e.jsx(Pt,{className:"absolute text-muted-foreground",style:{width:16,height:16,left:12,top:10}}),e.jsx(it,{value:i,onChange:c=>d(c.target.value),placeholder:"Search customer or mockup",style:{paddingLeft:36}})]}),a&&e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/10 p-4 mb-4 text-sm text-destructive",children:a}),!n&&!a&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loadingâ¦"}),n&&n.length===0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground",children:["No mockups published yet. Publish one from the Bucky repo with"," ",e.jsx("code",{className:"font-mono text-foreground",children:RM}),"."]}),n&&n.length>0&&p.length===0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["No mockups match â",i,"â."]}),p.map(c=>{const u=c[0],x=c.some(h=>h.published&&h.listed);return e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-violet-600/10 flex items-center justify-center",children:e.jsx(dg,{className:"w-5 h-5 text-violet-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-foreground",children:u.companyName}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[c.length," mockup",c.length===1?"":"s"]})]})]}),x&&e.jsx(Gx,{text:u.companyUrl,label:"Customer page"})]}),e.jsx("div",{className:"space-y-3",children:c.map(h=>e.jsxs("div",{className:"border-t border-border",style:{paddingTop:12},children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:h.title}),!h.published&&e.jsx(Kx,{text:"Unpublished"}),h.published&&!h.listed&&e.jsx(Kx,{text:"Unlisted"})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:[h.versionLabel,h.publishedAt?new Date(h.publishedAt).toLocaleDateString():null,h.versionCount>1?`v${h.currentVersion} of ${h.versionCount}
411`:null].filter(Boolean).join(" · ")}),e.jsx("div",{className:"text-xs text-muted-foreground break-words mb-2",children:h.url}),e.jsx("div",{className:"flex items-center gap-4 flex-wrap",children:h.published?e.jsxs(e.Fragment,{children:[e.jsx(Gx,{text:h.url,label:"Copy link"}),e.jsxs("a",{href:h.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(Da,{style:{width:14,height:14}}),"Open"]}),h.attachments.map(b=>e.jsxs("a",{href:b.url,className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(Mn,{style:{width:14,height:14}}),b.label]},b.url))]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Link is off. Re-publish to bring it back."})})]},h.slug))})]},u.companySlug)})]})]})}function nc({className:t,...s}){return e.jsx($j,{"data-slot":"tabs",className:$e("flex flex-col gap-2",t),...s})}function rc({className:t,...s}){return e.jsx(Bj,{"data-slot":"tabs-list",className:$e("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function Hs({className:t,...s}){return e.jsx(Fj,{"data-slot":"tabs-trigger",className:$e("data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function qs({className:t,...s}){return e.jsx(_j,{"data-slot":"tabs-content",className:$e("flex-1 outline-none",t),...s})}function MM(){const[t,s]=l.useState({clients:null,error:null});return l.useEffect(()=>qt(Re(ge,"ledgerClients"),n=>s({clients:n.docs.map(r=>({...r.data(),id:r.id})),error:null}),n=>s({clients:null,error:n.message})),[]),t}const Ei={strategy:"ledgerStrategy",holds:"ledgerHolds",changes:"ledgerChanges",assets:"ledgerAssets",decisions:"ledgerDecisions",recommendations:"ledgerRecommendations",waitingOn:"ledgerWaitingOn"},Qx={strategy:[],holds:[],changes:[],assets:[],decisions:[],recommendations:[],waitingOn:[]};function PM(t){const[s,n]=l.useState(Qx),[r,a]=l.useState(new Set),[o,i]=l.useState(null);return l.useEffect(()=>{if(n(Qx),a(new Set),i(null),!t)return;const d=Object.keys(Ei).map(m=>qt(Ge(Re(ge,Ei[m]),Ve("client_id","==",t)),p=>{const c=p.docs.map(u=>({...u.data(),id:u.id}));n(u=>({...u,[m]:c})),a(u=>new Set(u).add(m))},p=>i(`${Ei[m]}: ${p.message}`)));return()=>d.forEach(m=>m())},[t]),{data:s,loading:!!t&&r.size<Object.keys(Ei).length&&!o,error:o}}const LM="https://us-central1-bucky-app-355a3.cloudfunctions.net/ledgerApi",ac=["google","meta","klaviyo","amazon","merchant_center","seo","ga4","thoughtmetric","recharge","bucky"],zM=["google","meta"],ky=["budget","bid","bid_strategy","keyword","negative","targeting","launch","pause","tracking","feed","creative","structure"],rm=["account","campaign","ad_group","ad"],OM=["pending","kept","reversed","extended","superseded"],$M=["pending","extended"],Sy=["live","paused","draft","removed"],Cy=["brand","non_brand","shopping","pmax","local","conquesting","prospecting","retargeting","demand_gen","video","display","other"],BM=["open","decided","resolved"],FM={clients:"clients",strategy:"strategy",holds:"holds",changes:"changes",assets:"assets",decisions:"decisions",recommendations:"recommendations",weeklyMetrics:"weekly_metrics",waitingOn:"waiting_on"},Ty=t=>FM[t]??t;class rl extends Error{constructor(s,n,r,a){super(r),this.status=s,this.code=n,this.details=a,this.name="LedgerApiError"}get conflicts(){var n;const s=(n=this.details)==null?void 0:n.conflicts;return this.code==="guard_blocked"&&Array.isArray(s)?s:[]}}async function xn(t,s,n){const r=Lr.currentUser;if(!r)throw new rl(401,"unauthenticated","Sign in again to edit the ledger");const a=await r.getIdToken();let o;try{o=await fetch(`${LM}${s}`,{method:t,headers:{Authorization:`Bearer ${a}`,...n!==void 0?{"Content-Type":"application/json"}:{}},body:n!==void 0?JSON.stringify(n):void 0})}catch(d){throw new rl(0,"network",`Couldn't reach the ledger: ${d.message}`)}let i=null;try{i=await o.json()}catch{}if(!o.ok||!(i!=null&&i.ok)){const d=i==null?void 0:i.error;throw new rl(o.status,(d==null?void 0:d.code)??"http_error",(d==null?void 0:d.message)??`Ledger request failed (${o.status})`,d==null?void 0:d.details)}return i.data}const _M=()=>xn("GET","/google-ads/status"),WM=()=>xn("POST","/google-ads/connect"),UM=t=>xn("POST","/changes",t),HM=t=>xn("POST","/holds",t),qM=t=>xn("POST","/assets",t),VM=(t,s)=>kr("assets",t,{role:s}),YM=(t,s,n)=>xn("POST",`/strategy/${encodeURIComponent(t)}/notes`,n?{text:s,date:n}:{text:s}),GM=t=>xn("POST","/waiting_on",t),kr=(t,s,n)=>xn("PATCH",`/${Ty(t)}/${encodeURIComponent(s)}`,n),KM=(t,s)=>{const n={outcome:s.outcome};return s.outcome_note&&(n.outcome_note=s.outcome_note),s.client_note&&(n.client_note=s.client_note),s.outcome==="extended"&&s.review_date&&(n.review_date=s.review_date),kr("changes",t,n)},QM=(t,s)=>kr("holds",t,{status:"extended",end_date:s}),JM=t=>kr("holds",t,{status:"ended"}),ZM=t=>xn("POST",`/waiting_on/${encodeURIComponent(t)}/chase`,{}),XM=(t,s,n)=>xn("POST",`/${Ty(t)}/${encodeURIComponent(s)}/verify`,{note:(n==null?void 0:n.trim())||null}),eP=t=>
411xn("GET","/verification-queue"),Ea=()=>new Intl.DateTimeFormat("en-CA",{timeZone:"America/Vancouver",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),Ys=t=>(t??"").replace(/_/g," "),tP=t=>[t.name,t.external_id?`#${t.external_id}`:null].filter(Boolean).join(" ")||`${t.platform} ${Ys(t.level)}`,Wa=(t,s)=>t!=null&&t.length?t.map(tP).join("; "):s??"",oc=t=>(s,n)=>String(n[t]??"").localeCompare(String(s[t]??"")),sP={neutral:"bg-muted text-muted-foreground",warn:"bg-amber-100 text-amber-800",danger:"bg-destructive/10 text-destructive",ok:"bg-emerald-100 text-emerald-700",info:"bg-sky-100 text-sky-700"};function os({children:t,tone:s="neutral",title:n}){return e.jsx("span",{className:`text-xs px-2 rounded-full whitespace-nowrap ${sP[s]}`,style:{paddingTop:2,paddingBottom:2},title:n,children:t})}const Lo=t=>{switch(t){case"active":case"live":case"open":case"pending":return"info";case"extended":case"scheduled":case"paused":case"parked":case"draft":return"warn";case"kept":case"decided":case"resolved":case"done":case"answered":return"ok";case"reversed":case"removed":return"danger";default:return"neutral"}};function Ua({row:t}){return t.needs_verification?e.jsx(os,{tone:"warn",title:t.verification_note??void 0,children:"Needs verification"}):null}const nP=t=>{const s=new Map(t.filter(n=>n.external_id&&n.role).map(n=>[`${n.platform}:${n.external_id}`,n.role]));return n=>n.external_id?s.get(`${n.platform}:${n.external_id}`):null};function Ay({targets:t,roleOf:s}){if(!s||!(t!=null&&t.length))return null;const n=[...new Set(t.map(s).filter(r=>!!r))];return e.jsx(e.Fragment,{children:n.map(r=>e.jsx(os,{tone:"info",children:Ys(r)},r))})}function Ps({title:t,action:s,children:n}){return e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-3",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:t}),s]}),n]})}function sn({children:t}){return e.jsx("div",{className:"text-sm text-muted-foreground",children:t})}function Ln({children:t,first:s}){return e.jsx("div",{className:s?"":"border-t border-border",style:{paddingTop:s?0:12,paddingBottom:12},children:t})}function Kt({label:t,value:s}){return s==null||s===""?null:e.jsxs("div",{className:"text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:[t,": "]}),e.jsx("span",{className:"text-foreground whitespace-pre-wrap",children:s})]})}function wt({label:t,hint:s,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:t}),n,s&&e.jsx("span",{className:"text-xs text-muted-foreground",children:s})]})}const Ey={height:36,borderRadius:6,border:"1px solid var(--border)",background:"var(--background)",padding:"0 8px",fontSize:14,color:"inherit"};function Ls({value:t,options:s,onChange:n,labels:r,allowEmpty:a,ariaLabel:o}){return e.jsxs("select",{value:t,"aria-label":o,onChange:i=>n(i.target.value),className:"w-full",style:Ey,children:[a!==void 0&&e.jsx("option",{value:"",children:a}),s.map(i=>e.jsx("option",{value:i,children:(r==null?void 0:r[i])??Ys(i)},i))]})}function ko({children:t}){return e.jsx("div",{className:"grid gap-3",style:{gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))"},children:t})}const rP={hold:"Hold",open_change:"Open change",asset:"Asset",target:"Target",supersedes:"Override"};function aP({conflicts:t}){return t.length?e.jsxs("div",{className:"rounded-lg border border-destructive/20 bg-destructive/10 p-3 text-sm text-destructive",role:"alert",children:[e.jsxs("div",{className:"flex items-center gap-2 font-semibold mb-2",children:[e.jsx(Dt,{style:{width:16,height:16}}),"Blocked by the ledger guard"]}),e.jsx("ul",{className:"space-y-2",children:t.map((s,n)=>e.jsxs("li",{"data-testid":"guard-conflict",children:[e.jsx("span",{className:"font-medium",children:rP[s.check]??s.check}),s.target?e.jsxs("span",{className:"font-mono",children:[" ",s.target]}):null,": ",s.message,(s.hold_id||s.change_id)&&e.jsxs("span",{className:"text-xs font-mono",children:[" (",s.hold_id?`hold ${s.hold_id}`:`change ${s.change_id}`,")"]})]},n))})]}):null}function zo({message:t}){return t?e.jsx("div",{className:"rounded-lg border border-destructive/20 bg-destructive/10 p-3 text-sm text-destructive",role:"alert",children:t}):null}function Qs(){const[t,s]=l.useState(!1),[n,r]=l.useState(null),[a,o]=l.useState([]),i=l.useCallback(()=>{r(null),o([])},[]),d=l.useCallback(async(m,p,c)=>{s(!0),r(null),o([]);const u=ce.loading(`${m}â¦`);try{const x=await p();return ce.success(typeof c=="function"?c(x):c??`${m}: done`,{id:u}),x}catch(x){const h=x,b=x instanceof rl?x.conflicts:[];o(b),r(b.length?null:h.message),ce.error(b.length?`${h.message} â see the dialog for why`:h.message,{id:u});return}finally{s(!1)}},[]);return{busy:t,error:n,conflicts:a,reset:i,run:d}}function Sr({open:t,onOpenChange:s,title:n,description:r,submitLabel:a,action:o,onSubmit:i,children:d,wide:m}){const p=c=>{c||o.reset(),s(c)};return e.jsx(br,{open:t,onOpenChange:p,children:e.jsxs(yr,{style:{maxWidth:m?720:520,maxHeight:"85vh",overflowY:"auto"},children:[e.jsxs(jr,{children:[e.jsx(vr,{children:n}),r&&e.jsx(wr,{children:r})]}),e.jsxs("form",{className:"space-y-4",onSubmit:c=>{c.preventDefault(),o.busy||i()},children:[d,e.jsx(aP,{conflicts:o.conflicts}),e.jsx(zo,{message:o.error}),e.jsxs(Gr,{children:[e.jsx(ke,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsx(ke,{type:"submit",disabled:o.busy,children:o.busy?"Savingâ¦":a})]})]})]})})}const ls=t=>t.trim()||void 0,am=(t,s)=>({platform:t,level:s,external_id:"",name:""}),Iy=t=>t.map(s=>{var n,r;return{...s,external_id:((n=s.external_id)==null?void 0:n.trim())||null,name:((r=s.name)==null?void 0:r.trim())||null}}).filter(s=>s.external_id||s.name);function Ry({targets:t,onChange:s,defaultPlatform:n,defaultLevel:r}){const a=(o,i)=>s(t.map((d,m)=>m===o?{...d,...i}:d));return e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Targets"}),t.map((o,i)=>e.jsxs("div",{className:"rounded-lg border border-border p-2",children:[e.jsxs("div",{className:"grid gap-2",style:{gridTemplateColumns:"repeat(auto-fit, minmax(120px, 1fr))"},children:[e.jsx(Ls,{ariaLabel:"Target platform",value:o.platform,options:ac,onChange:d=>
411a(i,{platform:d})}),e.jsx(Ls,{ariaLabel:"Target level",value:o.level,options:rm,onChange:d=>a(i,{level:d})}),e.jsx(it,{"aria-label":"External ID",placeholder:zM.includes(o.platform)?"External ID (required)":"External ID",value:o.external_id??"",onChange:d=>a(i,{external_id:d.target.value})}),e.jsx(it,{"aria-label":"Target name",placeholder:"Name",value:o.name??"",onChange:d=>a(i,{name:d.target.value})})]}),t.length>1&&e.jsxs("button",{type:"button",onClick:()=>s(t.filter((d,m)=>m!==i)),className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground mt-2",children:[e.jsx(mt,{style:{width:12,height:12}})," Remove"]})]},i)),e.jsxs("button",{type:"button",onClick:()=>s([...t,am(n,r)]),className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground w-fit",children:[e.jsx(Ut,{style:{width:14,height:14}})," Add target"]})]})}const ui=t=>$M.includes(t.outcome),Dy=(t,s=Ea())=>ui(t)&&(!!t.overdue||!!t.review_date&&t.review_date<s);function My({change:t,onRecordOutcome:s,compact:n,roleOf:r}){const a=ui(t);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:Ys(t.change_type)}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[t.platform," · ",t.date_made]}),e.jsx(os,{tone:Lo(t.outcome),children:t.outcome}),e.jsx(Ay,{targets:t.targets,roleOf:r}),Dy(t)&&e.jsx(os,{tone:"danger",children:"Overdue review"}),t.conflict&&e.jsx(os,{tone:"danger",title:t.conflict_note??void 0,children:"Conflict"}),e.jsx(Ua,{row:t}),a&&s&&e.jsx(ke,{size:"sm",variant:"outline",style:{marginLeft:"auto"},onClick:()=>s(t),children:"Record outcome"})]}),e.jsx("div",{className:"text-sm text-foreground mt-1 break-words",children:Wa(t.targets,t.campaign)}),(t.before||t.after)&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[t.before||"â"," â ",t.after||"â"]}),e.jsx(Kt,{label:"Review",value:a?t.review_date:null}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(Kt,{label:"Why",value:t.why}),e.jsx(Kt,{label:"Expected",value:t.expected_effect}),e.jsx(Kt,{label:"Client note",value:t.client_note}),e.jsx(Kt,{label:"Outcome note",value:t.outcome_note}),e.jsx(Kt,{label:"Conflict",value:t.conflict_note}),e.jsx(Kt,{label:"Made by",value:t.made_by})]})]})}const Jx=()=>({platform:"google",level:"campaign",change_type:"",targets:[am("google","campaign")],date_made:Ea(),before:"",after:"",why:"",client_note:"",expected_effect:"",review_date:"",supersedes_change_id:"",supersede_reason:"",underspend_evidence:""});function oP({open:t,onOpenChange:s,client:n,openChanges:r}){const[a,o]=l.useState(Jx),i=Qs(),d=c=>o(u=>({...u,...c})),m=c=>{c||o(Jx()),s(c)},p=async()=>{if(!a.change_type){ce.error("Pick a change type");return}const c=Iy(a.targets);await i.run("Logging change",()=>UM({client_id:n.id,platform:a.platform,level:a.level,targets:c,change_type:a.change_type,date_made:ls(a.date_made),before:ls(a.before),after:ls(a.after),why:ls(a.why),client_note:ls(a.client_note),expected_effect:ls(a.expected_effect),review_date:ls(a.review_date),supersedes_change_id:ls(a.supersedes_change_id),supersede_reason:a.supersedes_change_id?ls(a.supersede_reason):void 0,underspend_evidence:a.change_type==="budget"?ls(a.underspend_evidence):void 0}),x=>["Change logged",x.hold_id?"learning hold opened":null,x.assets_created.length?`${x.assets_created.length} asset(s) registered`:null].filter(Boolean).join(" · "))&&m(!1)};return e.jsxs(Sr,{open:t,onOpenChange:m,title:`Log change â ${n.name}`,description:"Checked against holds, open changes and the asset registry before it is written.",submitLabel:"Log change",action:i,onSubmit:p,wide:!0,children:[e.jsxs(ko,{children:[e.jsx(wt,{label:"Platform",children:e.jsx(Ls,{value:a.platform,options:ac,onChange:c=>d({platform:c,targets:a.targets.map(u=>({...u,platform:c}))})})}),e.jsx(wt,{label:"Level",children:e.jsx(Ls,{value:a.level,options:rm,onChange:c=>d({level:c,targets:a.targets.map(u=>({...u,level:c}))})})}),e.jsx(wt,{label:"Change type",children:e.jsx(Ls,{ariaLabel:"Change type",value:a.change_type,options:ky,allowEmpty:"Chooseâ¦",onChange:c=>d({change_type:c})})}),e.jsx(wt,{label:"Date made",children:e.jsx(it,{type:"date",value:a.date_made,onCh
411ange:c=>d({date_made:c.target.value})})})]}),e.jsx(Ry,{targets:a.targets,onChange:c=>d({targets:c}),defaultPlatform:a.platform,defaultLevel:a.level}),e.jsxs(ko,{children:[e.jsx(wt,{label:"Before",children:e.jsx(it,{value:a.before,onChange:c=>d({before:c.target.value})})}),e.jsx(wt,{label:"After",children:e.jsx(it,{value:a.after,onChange:c=>d({after:c.target.value})})})]}),e.jsx(wt,{label:"Why",children:e.jsx(ds,{rows:2,value:a.why,onChange:c=>d({why:c.target.value})})}),e.jsx(wt,{label:"Expected effect",children:e.jsx(ds,{rows:2,value:a.expected_effect,onChange:c=>d({expected_effect:c.target.value})})}),e.jsx(wt,{label:"Client note",hint:"Client-facing wording, if this goes in an update.",children:e.jsx(ds,{rows:2,value:a.client_note,onChange:c=>d({client_note:c.target.value})})}),e.jsxs(ko,{children:[e.jsx(wt,{label:"Review date",hint:"Blank = 14 days after the date made.",children:e.jsx(it,{type:"date",value:a.review_date,onChange:c=>d({review_date:c.target.value})})}),e.jsx(wt,{label:"Overrides open change",hint:"Only when you mean to supersede a change still in review.",children:e.jsxs("select",{value:a.supersedes_change_id,onChange:c=>d({supersedes_change_id:c.target.value}),className:"w-full",style:Ey,children:[e.jsx("option",{value:"",children:"None"}),r.map(c=>e.jsxs("option",{value:c.id,children:[c.date_made," ",Ys(c.change_type)," â ",Wa(c.targets,c.campaign).slice(0,60)]},c.id))]})})]}),a.supersedes_change_id&&e.jsx(wt,{label:"Supersede reason (required)",children:e.jsx(ds,{rows:2,value:a.supersede_reason,onChange:c=>d({supersede_reason:c.target.value})})}),a.change_type==="budget"&&e.jsx(wt,{label:"Underspend evidence",hint:"Lets a budget increase through a learning hold when the campaign is underspending.",children:e.jsx(ds,{rows:2,value:a.underspend_evidence,onChange:c=>d({underspend_evidence:c.target.value})})})]})}const iP=OM.filter(t=>t!=="pending"&&t!=="superseded");function Py({change:t,onClose:s}){const[n,r]=l.useState("kept"),[a,o]=l.useState(""),[i,d]=l.useState(""),[m,p]=l.useState(""),c=Qs(),u=()=>{r("kept"),o(""),d(""),p(""),s()},x=async()=>{if(!t)return;await c.run("Recording outcome",()=>KM(t.id,{outcome:n,outcome_note:ls(a),client_note:ls(i),review_date:n==="extended"?ls(m):void 0}))&&u()};return e.jsxs(Sr,{open:!!t,onOpenChange:h=>{h||u()},title:"Record outcome",description:t?`${Ys(t.change_type)} on ${Wa(t.targets,t.campaign)} (${t.date_made})`:void 0,submitLabel:"Save outcome",action:c,onSubmit:x,children:[e.jsx(wt,{label:"Outcome",children:e.jsx(Ls,{ariaLabel:"Outcome",value:n,options:iP,onChange:r})}),n==="extended"&&e.jsx(wt,{label:"New review date",hint:"Required to extend the review window.",children:e.jsx(it,{type:"date",value:m,onChange:h=>p(h.target.value),required:!0})}),e.jsx(wt,{label:"Outcome note",children:e.jsx(ds,{rows:3,value:a,onChange:h=>o(h.target.value)})}),e.jsx(wt,{label:"Client note",hint:"Optional client-facing wording.",children:e.jsx(ds,{rows:2,value:i,onChange:h=>d(h.target.value)})})]})}function lP({client:t,changes:s}){const[n,r]=l.useState(!1),[a,o]=l.useState(null),i=l.useMemo(()=>[...s].sort(oc("date_made")),[s]),d=l.useMemo(()=>i.filter(ui),[i]);return e.jsxs(e.Fragment,{children:[e.jsxs(Ps,{title:`Changes (${s.length})`,action:e.jsxs(ke,{size:"sm",onClick:()=>r(!0),children:[e.jsx(Ut,{})," Log change"]}),children:[i.length===0&&e.jsxs(sn,{children:["No changes logged for ",t.name," yet."]}),i.map((m,p)=>e.jsx(Ln,{first:p===0,children:e.jsx(My,{change:m,onRecordOutcome:o})},m.id))]}),e.jsx(oP,{open:n,onOpenChange:r,client:t,openChanges:d}),e.jsx(Py,{change:a,onClose:()=>o(null)})]})}const Oo=t=>t.status!=="ended";function Yd({hold:t,onExtend:s,onEnd:n,roleOf:r}){var o;const a=Oo(t);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:Wa(t.targets,t.campaign)||`${t.platform} ${Ys(t.level)}`}),e.jsx(os,{tone:Lo(t.status),children:t.status}),e.jsx(Ay,{targets:t.targets,roleOf:r}),e.jsx(Ua,{row:t}),a&&(s||n)&&e.jsxs("span",{className:"flex items-center gap-2",style:{marginLeft:"auto"},children:[s&&e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>s(t),children:"Extend"}),n&&e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>n(t),children:"End"})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[t.platform," · ",Ys(t.level)," · ",t.start_date," â ",t.end_date]}),e.jsx(Kt,{label:"Reason",value:t.reason}),e.jsx(Kt,{label:"Permitted",value:(o=t.permitted_edits)!=null&&o.length?t.permitted_edits.map(Ys).join(", "):"nothing"}),e.jsx(Kt,{label:"Harry's wording",value:t.permitted_edits_text}),t.allow_budget_increase_if_underspending&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Budget increase allowed with underspend evidence."})]})}const Zx=()=>({platform:"google",level:"campaign",targets:[am("google","campaign")],start_date:Ea(),end_date:"",reason:"",permitted_edits:["negative"],allow_budget_increase_if_underspending:!1});function cP({open:t,onOpenChange:s,client:n}){const[r,a]=l.useState(Zx),o=Qs(),i=c=>a(u=>({...u,...c})),d=c=>{c||a(Zx()),s(c)},m=c=>i({permitted_edits:r.permitted_edits.includes(c)?r.permitted_edits.filter(u=>u!==c):[...r.permitted_edits,c]}),p=async()=>
411{if(!r.end_date||!r.reason.trim()){ce.error("A hold needs an end date and a reason");return}await o.run("Creating hold",()=>HM({client_id:n.id,platform:r.platform,level:r.level,targets:Iy(r.targets),start_date:ls(r.start_date),end_date:r.end_date,reason:r.reason.trim(),permitted_edits:r.permitted_edits,allow_budget_increase_if_underspending:r.allow_budget_increase_if_underspending}),"Hold created")&&d(!1)};return e.jsxs(Sr,{open:t,onOpenChange:d,title:`New hold â ${n.name}`,submitLabel:"Create hold",action:o,onSubmit:p,wide:!0,children:[e.jsxs(ko,{children:[e.jsx(wt,{label:"Platform",children:e.jsx(Ls,{value:r.platform,options:ac,onChange:c=>i({platform:c,targets:r.targets.map(u=>({...u,platform:c}))})})}),e.jsx(wt,{label:"Level",hint:"An account hold covers every campaign on the platform.",children:e.jsx(Ls,{value:r.level,options:rm,onChange:c=>i({level:c,targets:r.targets.map(u=>({...u,level:c}))})})}),e.jsx(wt,{label:"Start date",children:e.jsx(it,{type:"date",value:r.start_date,onChange:c=>i({start_date:c.target.value})})}),e.jsx(wt,{label:"End date",children:e.jsx(it,{type:"date",value:r.end_date,onChange:c=>i({end_date:c.target.value}),required:!0})})]}),e.jsx(Ry,{targets:r.targets,onChange:c=>i({targets:c}),defaultPlatform:r.platform,defaultLevel:r.level}),e.jsx(wt,{label:"Reason",children:e.jsx(ds,{rows:2,value:r.reason,onChange:c=>i({reason:c.target.value}),required:!0})}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Permitted edits during the hold"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:ky.map(c=>e.jsxs("label",{className:"inline-flex items-center gap-1 text-sm",children:[e.jsx("input",{type:"checkbox",checked:r.permitted_edits.includes(c),onChange:()=>m(c)}),Ys(c)]},c))})]}),e.jsxs("label",{className:"inline-flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:r.allow_budget_increase_if_underspending,onChange:c=>i({allow_budget_increase_if_underspending:c.target.checked})}),"Allow a budget increase when the campaign is underspending"]})]})}function dP({hold:t,onClose:s}){const[n,r]=l.useState(""),a=Qs(),o=()=>{r(""),s()},i=async()=>{if(!t)return;if(!n){ce.error("Extending a hold needs a new end date");return}await a.run("Extending hold",()=>QM(t.id,n),"Hold extended")&&o()};return e.jsx(Sr,{open:!!t,onOpenChange:d=>{d||o()},title:"Extend hold",description:t?`${Wa(t.targets,t.campaign)} â currently ends ${t.end_date}`:void 0,submitLabel:"Extend",action:a,onSubmit:i,children:e.jsx(wt,{label:"New end date",children:e.jsx(it,{type:"date",value:n,min:t==null?void 0:t.end_date,onChange:d=>r(d.target.value),required:!0})})})}function uP({client:t,holds:s}){const[n,r]=l.useState(!1),[a,o]=l.useState(null),i=Qs(),[d,m]=l.useMemo(()=>{const c=[...s].sort(oc("end_date"));return[c.filter(Oo),c.filter(u=>!Oo(u))]},[s]),p=c=>{window.confirm(`End the hold on ${Wa(c.targets,c.campaign)}?`)&&i.run("Ending hold",()=>JM(c.id),"Hold ended")};return e.jsxs(e.Fragment,{children:[e.jsxs(Ps,{title:`Holds in place (${d.length})`,action:e.jsxs(ke,{size:"sm",onClick:()=>r(!0),children:[e.jsx(Ut,{})," New hold"]}),children:[d.length===0&&e.jsx(sn,{children:"No holds in place."}),d.map((c,u)=>e.jsx(Ln,{first:u===0,children:e.jsx(Yd,{hold:c,onExtend:o,onEnd:p})},c.id))]}),m.length>0&&e.jsx(Ps,{title:`Ended (${m.length})`,children:m.map((c,u)=>e.jsx(Ln,{first:u===0,children:e.jsx(Yd,{hold:c})},c.id))}),e.jsx(cP,{open:n,onOpenChange:r,client:t}),e.jsx(dP,{hold:a,onClose:()=>o(null)})]})}function mP({strategy:t,open:s,onOpenChange:n}){const[r,a]=l.useState(""),[o,i]=l.useState(Ea()),d=Qs(),m=c=>{c||(a(""),i(Ea())),n(c)},p=async()=>{if(!r.trim()){ce.error("Write the note first");return}await d.run("Adding note",()=>YM(t.id,r.trim(),o||void 0),"Note added")&&m(!1)};return e.jsxs(Sr,{open:s,onOpenChange:m,title:"Add strategy note",description:"Settled context for this month's strategy. Notes can't be edited or deleted once added.",submitLabel:"Add note",action:d,onSubmit:p,children:[e.jsx(wt,{label:"Note",children:e.jsx(ds,{"aria-label":"Note",rows:3,value:r,onChange:c=>a(c.target.value),required:!0})}),e.jsx(wt,{label:"Date",children:e.jsx(it,{type:"date",value:o,onChange:c=>i(c.target.value)})})]})}function pP({client:t,strategy:s,holds:n,changes:r,assets:a=[]}){const[o,i]=l.useState(null),[d,m]=l.useState(!1),p=l.useMemo(()=>nP(a),[a]),c=l.useMemo(()=>s.filter(b=>b.status==="active").sort(oc("period_start"))[0]??null,[s]),u=l.useMemo(()=>n.filter(Oo).sort((b,f)=>b.end_date.localeCompare(f.end_date)),[n]),x=l.useMemo(()=>r.filter(ui).sort((b,f)=>String(b.review_date).localeCompare(String(f.review_date))),[r]),h=l.useMemo(()=>[...(c==null?void 0:c.notes)??[]].sort((b,f)=>String(f.date??"").localeCompare(String(b.date??""))),[c]);return e.jsxs(e.Fragment,{children:[e.jsxs(Ps,{title:"Strategy",children:[!c&&e.jsxs(sn,{children:["No active strategy for ",t.name,"."]}),c&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.p
411hase&&e.jsx(os,{tone:"info",children:c.phase}),c.period_start&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[c.period_start," â ",c.period_end]}),e.jsx(Ua,{row:c})]}),e.jsx("div",{className:"font-medium text-foreground",children:c.month_objective}),e.jsx(Kt,{label:"Success metric",value:c.success_metric}),e.jsx(Kt,{label:"Plan",value:c.plan_summary}),e.jsx(Kt,{label:"KPI",value:[t.primary_kpi,t.kpi_note].filter(Boolean).join(" â ")}),e.jsx(Kt,{label:"Monthly spend cap",value:typeof t.monthly_spend_cap=="number"?`$${t.monthly_spend_cap.toLocaleString()}${t.currency?` ${t.currency}`:""}`:null}),e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-sm font-medium text-foreground mb-1",children:"Notes"}),h.length===0&&e.jsx(sn,{children:"No notes yet."}),h.length>0&&e.jsx("ul",{className:"space-y-1",children:h.map((b,f)=>e.jsxs("li",{className:"text-sm text-foreground",children:[b.date&&e.jsxs("span",{className:"text-muted-foreground",children:[b.date," · "]}),e.jsx("span",{className:"whitespace-pre-wrap",children:b.text}),b.source&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[" (",b.source,")"]})]},f))}),e.jsxs(ke,{size:"sm",variant:"outline",className:"mt-2",onClick:()=>m(!0),children:[e.jsx(Ut,{})," Add note"]})]})]})]}),c&&e.jsx(mP,{strategy:c,open:d,onOpenChange:m}),e.jsxs(Ps,{title:`Holds in place (${u.length})`,children:[u.length===0&&e.jsx(sn,{children:"No holds in place."}),u.map((b,f)=>e.jsx(Ln,{first:f===0,children:e.jsx(Yd,{hold:b,roleOf:p})},b.id))]}),e.jsxs(Ps,{title:`Open changes (${x.length})`,children:[x.length===0&&e.jsx(sn,{children:"No changes in their review window."}),x.map((b,f)=>e.jsx(Ln,{first:f===0,children:e.jsx(My,{change:b,onRecordOutcome:i,compact:!0,roleOf:p})},b.id))]}),e.jsx(Py,{change:o,onClose:()=>i(null)})]})}function xP({open:t,onOpenChange:s,client:n}){const r={platform:"google",asset_type:"campaign",name:"",external_id:"",status:"live",role:"",details:""},[a,o]=l.useState(r),i=Qs(),d=c=>o(u=>({...u,...c})),m=c=>{c||o(r),s(c)},p=async()=>{if(!a.name.trim()||!a.asset_type.trim()){ce.error("An asset needs a type and a name");return}await i.run("Registering asset",()=>qM({client_id:n.id,platform:a.platform,asset_type:a.asset_type.trim(),name:a.name.trim(),external_id:ls(a.external_id),status:a.status,role:a.role||void 0,details:ls(a.details)}),"Asset registered")&&m(!1)};return e.jsxs(Sr,{open:t,onOpenChange:m,title:`Register asset â ${n.name}`,submitLabel:"Register",action:i,onSubmit:p,children:[e.jsxs(ko,{children:[e.jsx(wt,{label:"Platform",children:e.jsx(Ls,{value:a.platform,options:ac,onChange:c=>d({platform:c})})}),e.jsx(wt,{label:"Type",hint:"campaign, ad_account, conversion_action, flowâ¦",children:e.jsx(it,{value:a.asset_type,onChange:c=>d({asset_type:c.target.value})})}),e.jsx(wt,{label:"Name",children:e.jsx(it,{value:a.name,onChange:c=>d({name:c.target.value}),required:!0})}),e.jsx(wt,{label:"External ID",children:e.jsx(it,{value:a.external_id,onChange:c=>d({external_id:c.target.value})})}),e.jsx(wt,{label:"Status",children:e.jsx(Ls,{value:a.status,options:Sy,onChange:c=>d({status:c})})}),e.jsx(wt,{label:"Role",hint:"What the campaign is for.",children:e.jsx(Ls,{ariaLabel:"Role",value:a.role,options:Cy,allowEmpty:"None",onChange:c=>d({role:c})})})]}),e.jsx(wt,{label:"Details",children:e.jsx(ds,{rows:2,value:a.details,onChange:c=>d({details:c.target.value})})})]})}function hP({client:t,assets:s}){const[n,r]=l.useState(!1),a=Qs(),o=l.useMemo(()=>{const m=new Map;for(const p of s)m.set(p.platform,[...m.get(p.platform)??[],p]);return[...m.entries()].sort(([p],[c])=>p.localeCompare(c)).map(([p,c])=>({platform:p,list:c.sort((u,x)=>String(u.asset_type).localeCompare(String(x.asset_type))||String(u.name).localeCompare(String(x.name)))}))},[s]),i=(m,p)=>a.run("Setting role",()=>VM(m.id,p),`${m.name}: ${Ys(p)}`),d=(m,p)=>a.run("Updating asset",()=>kr("assets",m.id,{status:p}),`${m.name} is now ${p}`);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs(ke,{size:"sm",onClick:()=>r(!0),children:[e.jsx(Ut,{})," Register asset"]})}),o.length===0&&e.jsx(Ps,{title:"Assets",children:e.jsxs(sn,{children:["No assets registered for ",t.name,"."]})}),o.map(({platform:m,list:p})=>e.jsx(Ps,{title:`${m} (${p.length})`,children:p.map((c,u)=>
411e.jsxs(Ln,{first:u===0,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:c.asset_type}),c.external_id&&e.jsxs("span",{className:"text-xs font-mono text-muted-foreground",children:["#",c.external_id]}),c.role&&e.jsx(os,{tone:"info",children:Ys(c.role)}),e.jsx(Ua,{row:c}),e.jsxs("span",{className:"flex items-center gap-2",style:{marginLeft:"auto"},children:[e.jsx("span",{style:{width:140},children:e.jsx(Ls,{ariaLabel:`Role of ${c.name}`,value:c.role??"",options:Cy,allowEmpty:"Set roleâ¦",onChange:x=>{x&&i(c,x)}})}),e.jsx("span",{style:{width:120},children:e.jsx(Ls,{ariaLabel:`Status of ${c.name}`,value:c.status,options:Sy,onChange:x=>d(c,x)})})]})]}),e.jsx(Kt,{label:"Details",value:c.details}),e.jsx(Kt,{label:"Verified",value:c.verified_at})]},c.id))},m)),e.jsx(xP,{open:n,onOpenChange:r,client:t})]})}const Xx={high:0,medium:1,low:2};function fP({decision:t,onClose:s}){const[n,r]=l.useState(""),[a,o]=l.useState("decided"),i=Qs(),[d,m]=l.useState(null);t&&d!==t.id&&(m(t.id),r(t.decision??""),o(t.status==="open"?"decided":t.status));const p=()=>{m(null),s()},c=async()=>{if(!t)return;const u={status:a};n.trim()&&(u.decision=n.trim()),a!=="open"&&!t.decided_at&&(u.decided_at=Ea()),await i.run("Saving decision",()=>kr("decisions",t.id,u),"Decision saved")&&p()};return e.jsxs(Sr,{open:!!t,onOpenChange:u=>{u||p()},title:"Record decision",description:t==null?void 0:t.finding,submitLabel:"Save",action:i,onSubmit:c,children:[e.jsx(wt,{label:"Decision",children:e.jsx(ds,{rows:3,value:n,onChange:u=>r(u.target.value)})}),e.jsx(wt,{label:"Status",children:e.jsx(Ls,{ariaLabel:"Decision status",value:a,options:BM,onChange:o})})]})}function gP({decisions:t,recommendations:s}){const[n,r]=l.useState(null),a=Qs(),o=l.useMemo(()=>t.filter(c=>c.status==="open").sort((c,u)=>(Xx[c.priority]??3)-(Xx[u.priority]??3)),[t]),i=l.useMemo(()=>t.filter(c=>c.status==="decided"),[t]),d=l.useMemo(()=>s.filter(c=>c.status==="open"||c.status==="parked").sort(oc("week_start")),[s]),m=(c,u)=>a.run("Updating recommendation",()=>kr("recommendations",c.id,{status:u}),`Recommendation ${u}`),p=(c,u)=>e.jsxs(Ln,{first:u===0,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.finding}),e.jsx(os,{tone:c.priority==="high"?"danger":c.priority==="medium"?"warn":"neutral",children:c.priority}),e.jsx(os,{tone:Lo(c.status),children:c.status}),e.jsx(Ua,{row:c}),e.jsx(ke,{size:"sm",variant:"outline",style:{marginLeft:"auto"},onClick:()=>r(c),children:c.status==="open"?"Decide":"Update"})]}),e.jsx(Kt,{label:"Evidence",value:c.evidence}),e.jsx(Kt,{label:"Decision needed",value:c.decision_needed}),e.jsx(Kt,{label:"Decision",value:c.decision})]},c.id);return e.jsxs(e.Fragment,{children:[e.jsxs(Ps,{title:`Open decisions (${o.length})`,children:[o.length===0&&e.jsx(sn,{children:"Nothing waiting on a decision."}),o.map(p)]}),i.length>0&&e.jsx(Ps,{title:`Decided, not yet resolved (${i.length})`,children:i.map(p)}),e.jsxs(Ps,{title:`Open recommendations (${d.length})`,children:[d.length===0&&e.jsx(sn,{children:"No open recommendations."}),d.map((c,u)=>e.jsxs(Ln,{first:u===0,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:c.rec_id}),e.jsx(os,{children:c.type}),e.jsx(os,{tone:Lo(c.status),children:c.status}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["week of ",c.week_start]}),e.jsxs("span",{className:"flex items-center gap-2",style:{marginLeft:"auto"},children:[e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>m(c,"done"),children:"Done"}),c.status!=="parked"&&e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>m(c,"parked"),children:"Park"}),c.status==="parked"&&e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>m(c,"open"),children:"Reopen"}),e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>m(c,"dismissed"),children:"Dismiss"})]})]}),e.jsx("div",{className:"text-sm text-foreground mt-1 whitespace-pre-wrap",children:c.text}),e.jsx(Kt,{label:"Campaign",value:c.campaign}),e.jsx(Kt,{label:"Note",value:c.note})]},c.id))]}),e.jsx(fP,{decision:n,onClose:()=>r(null)})]})}const eh=2;function bP({open:t,onOpenChange:s,client:n}){const r={ask:"",asked_of:"",blocks:""},[a,o]=l.useState(r),i=Qs(),d=p=>{p||o(r),s(p)},m=async()=>
411{if(!a.ask.trim()){ce.error("What are we asking for?");return}await i.run("Adding ask",()=>GM({client_id:n.id,ask:a.ask.trim(),asked_of:ls(a.asked_of),blocks:ls(a.blocks)}),"Ask added")&&d(!1)};return e.jsxs(Sr,{open:t,onOpenChange:d,title:`New ask â ${n.name}`,submitLabel:"Add ask",action:i,onSubmit:m,children:[e.jsx(wt,{label:"Ask",children:e.jsx(ds,{rows:2,value:a.ask,onChange:p=>o({...a,ask:p.target.value}),required:!0})}),e.jsx(wt,{label:"Asked of",children:e.jsx(it,{value:a.asked_of,onChange:p=>o({...a,asked_of:p.target.value})})}),e.jsx(wt,{label:"Blocks",hint:"What can't move until this is answered.",children:e.jsx(it,{value:a.blocks,onChange:p=>o({...a,blocks:p.target.value})})})]})}function yP({client:t,asks:s}){const[n,r]=l.useState(!1),a=Qs(),[o,i]=l.useMemo(()=>{const c=[...s].sort((u,x)=>String(u.first_asked??"").localeCompare(String(x.first_asked??"")));return[c.filter(u=>u.status==="open"),c.filter(u=>u.status!=="open")]},[s]),d=c=>a.run("Chasing",()=>ZM(c.id),u=>u.status==="parked"?`Chased (${u.chase_count}) â parked after ${eh} chases`:`Chased (${u.chase_count??(c.chase_count??0)+1})`),m=c=>a.run("Marking answered",()=>kr("waiting_on",c.id,{status:"answered"}),"Marked answered"),p=(c,u)=>e.jsxs(Ln,{first:u===0,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.ask}),e.jsx(os,{tone:Lo(c.status),children:c.status}),e.jsxs(os,{tone:(c.chase_count??0)>=eh?"danger":"neutral",children:["chased ",c.chase_count??0,"Ã"]}),e.jsx(Ua,{row:c}),e.jsxs("span",{className:"flex items-center gap-2",style:{marginLeft:"auto"},children:[c.status==="open"&&e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>d(c),children:"Chase"}),c.status!=="answered"&&e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>m(c),children:"Answered"})]})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:[c.asked_of?`asked of ${c.asked_of}`:null,c.first_asked?`since ${c.first_asked}`:null].filter(Boolean).join(" · ")}),e.jsx(Kt,{label:"Blocks",value:c.blocks})]},c.id);return e.jsxs(e.Fragment,{children:[e.jsxs(Ps,{title:`Waiting on (${o.length})`,action:e.jsxs(ke,{size:"sm",onClick:()=>r(!0),children:[e.jsx(Ut,{})," New ask"]}),children:[o.length===0&&e.jsxs(sn,{children:["Nothing outstanding with ",t.name,"."]}),o.map(p)]}),i.length>0&&e.jsx(Ps,{title:`Parked & answered (${i.length})`,children:i.map(p)}),e.jsx(bP,{open:n,onOpenChange:r,client:t})]})}const jP={clients:"Client",strategy:"Strategy",holds:"Hold",changes:"Change",assets:"Asset",decisions:"Decision",recommendations:"Recommendation",weeklyMetrics:"Weekly metrics",waitingOn:"Ask"},$s=t=>typeof t=="string"&&t.trim()?t:null;function vP(t){switch(t.entity){case"clients":return $s(t.name)??t.id;case"strategy":return $s(t.month_objective)??$s(t.phase)??t.id;case"holds":return[$s(t.campaign),$s(t.reason)].filter(Boolean).join(" â ")||t.id;case"changes":return[Ys($s(t.change_type)),$s(t.campaign),$s(t.date_made)].filter(Boolean).join(" · ")||t.id;case"assets":return[$s(t.name),$s(t.asset_type)].filter(Boolean).join(" · ")||t.id;case"decisions":return $s(t.finding)??t.id;case"waitingOn":return $s(t.ask)??t.id;default:return $s(t.text)??t.id}}function wP({clients:t,clientFilter:s}){const[n,r]=l.useState(null),[a,o]=l.useState(null),[i,d]=l.useState(!1),[m,p]=l.useState({}),c=Qs(),u=l.useMemo(()=>new Map(t.map(f=>[f.id,f.name])),[t]),x=l.useCallback(async()=>{o(null);try{r(await eP())}catch(f){o(f.message)}},[]);l.useEffect(()=>{x()},[x]);const h=l.useMemo(()=>(n??[]).filter(f=>!i||!s||(f.entity==="clients"?f.id:f.client_id)===s).sort((f,g)=>String(u.get(String(f.client_id??f.id))??"").localeCompare(String(u.get(String(g.client_id??g.id))??""))||f.entity.localeCompare(g.entity)),[n,i,s,u]),b=async f=>{const g=`${f.entity}/${f.id}`;await c.run("Marking verified",()=>XM(f.entity,f.id,m[g]),"Verified")&&r(j=>(j??[]).filter(v=>!(v.entity===f.entity&&v.id===f.id)))};return e.jsxs(Ps,{title:`Needs verification${n?` (${h.length})`:""}`,action:e.jsxs("span",{className:"flex items-center gap-3",children:[s&&e.jsxs("label",{className:"inline-flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:i,onChange:f=>d(f.target.checked)}),"This client only"]}),e.jsxs("button",{onClick:x,className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(yt,{style:{width:14,height:14}})," Refresh"]})]}),children:[e.jsx(zo,{message:a}),e.jsx(zo,{message:c.error}),!n&&!a&&e.jsx(sn,{children:"Loadingâ¦"}),n&&h.length===0&&e.jsx(sn,{children:"Nothing waiting on verification."}),h.map((f,g)=>{const y=`${f.entity}/${f.id}`,j=f.entity==="clients"?f.id:String(f.client_id??"");return e.jsxs(Ln,{first:g===0,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(os,{tone:"info",children:jP[f.entity]??f.entity}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:u.get(j)??j}),f.legacy_id&&e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:f.legacy_id})]}),e.jsx("div",{className:"text-sm text-foreground mt-1 break-words",children:vP(f)}),e.jsx(Kt,{label:"Check",value:f.verification_note}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(it,{"aria-label":"Verification note",placeholder:"Note (optional) â what you checked",value:m[y]??"",onChange:v=>p(T=>({...T,[y]:v.target.value}))}),e.jsx(ke,{size:"sm",disabled:c.busy,onClick:()=>b(f),children:"Mark verified"})]})]},y)})]})}const NP=t=>t?new Date(t).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):"";function kP(){const[t,s]=l.useState(null),[n,r]=l.useState(null),[a,o]=l.useState(!1),i=l.useCallback(async()=>{try{s(await _M()),r(null)}catch(m){r(m.message)}},[]);l.useEffect(()=>(i(),window.addEventListener("focus",i),()=>window.removeEventListener("focus",i)),[i]);const d=async()=>{const m=window.open("about:blank","_blank");o(!0);try{const{url:p,expected_account:c}=await WM();m?m.location.href=p:window.location.assign(p),ce.info("Allow Google Ads access",{description:`Sign in with a Sunbowl account that's invited to the clients' Google Ads (e.g. ${c})`})}catch(p){m==null||m.close(),ce.error("Could not start the Google Ads connection",{description:p.message})}finally{o(!1)}};return e.jsxs("div",{className:"rounded-xl border border-border bg-card p-3 mb-4 flex items-center justify-between gap-2 flex-wrap","data-testid":"gads-connect",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Google Ads API"}),t!=null&&t.connected?e.jsxs(e.Fragment,{children:[e.jsx(os,{tone:"ok",children:"connected"}),e.jsxs("span",{className:"text-muted-foreground",children:["as ",t.account,t.connected_at?` · ${NP(t.connected_at)}`:""]})]}):t?e.jsxs(e.Fragment,{children:[e.jsx(os,{tone:"warn",children:"not connected"}),e.jsx("span",{className:"text-muted-foreground",children:"Needed for Bucky to run the Monday pull itself"})]}
411):n?e.jsx("span",{className:"text-destructive",children:n}):e.jsx("span",{className:"text-muted-foreground",children:"Checkingâ¦"})]}),e.jsx("button",{onClick:d,disabled:a,className:"rounded-md border border-border px-3 py-1 text-sm hover:bg-muted transition-colors",children:a?"Openingâ¦":t!=null&&t.connected?"Reconnect":"Connect Google Ads"})]})}const th={yes:0,paused:1},SP=t=>t.filter(s=>s.active!=="no").sort((s,n)=>(th[s.active]??2)-(th[n.active]??2)||String(s.name).localeCompare(String(n.name)));function CP({clients:t,selected:s,onSelect:n}){return e.jsx("div",{className:"flex flex-wrap gap-2 mb-4",role:"listbox","aria-label":"Client",children:t.map(r=>{const a=r.id===s;return e.jsx("button",{role:"option","aria-selected":a,"data-client-id":r.id,onClick:()=>n(r.id),title:r.active==="paused"?`${r.name} (paused)`:r.name,className:`text-sm px-3 py-1 rounded-full border transition-colors ${a?"bg-primary text-primary-foreground border-transparent":"border-border bg-card text-foreground"}`,style:{opacity:r.active==="paused"&&!a?.55:1},children:r.name},r.id)})})}function TP({onBack:t,onLogoClick:s}){const{clients:n,error:r}=MM(),a=l.useMemo(()=>SP(n??[]),[n]),[o,i]=l.useState(null),[d,m]=l.useState("overview");l.useEffect(()=>{!o&&a.length&&i(a[0].id)},[o,a]);const p=a.find(f=>f.id===o)??null,{data:c,loading:u,error:x}=PM((p==null?void 0:p.id)??null),h=l.useMemo(()=>({overdue:c.changes.filter(f=>Dy(f)).length,openChanges:c.changes.filter(ui).length,holds:c.holds.filter(Oo).length,decisions:c.decisions.filter(f=>f.status==="open").length+c.recommendations.filter(f=>f.status==="open"||f.status==="parked").length,asks:c.waitingOn.filter(f=>f.status==="open").length}),[c]),b=f=>f?e.jsx("span",{className:"text-xs text-muted-foreground",children:f}):null;return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-5xl mx-auto pb-24",children:[e.jsx(Xe,{title:"Client Ledger",showTitle:!0,onLogoClick:s}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("button",{onClick:t,className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(dt,{style:{width:16,height:16}}),"Back"]}),p&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[p.tier&&e.jsx("span",{children:p.tier}),p.active==="paused"&&e.jsx(os,{tone:"warn",children:"paused"}),h.overdue>0&&e.jsxs(os,{tone:"danger",children:[h.overdue," overdue review",h.overdue===1?"":"s"]})]})]}),e.jsx(kP,{}),e.jsx(zo,{message:r}),!n&&!r&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loadingâ¦"}),n&&a.length===0&&e.jsx("div",{className:"rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground",children:"No ledger clients yet. They arrive through the ledger import."}),a.length>0&&e.jsx(CP,{clients:a,selected:o,onSelect:i}),p&&e.jsxs(nc,{value:d,onValueChange:m,children:[e.jsx("div",{className:"overflow-x-auto mb-2",children:e.jsxs(rc,{children:[e.jsx(Hs,{value:"overview",children:"Overview"}),e.jsxs(Hs,{value:"changes",children:["Changes ",b(h.openChanges)]}),e.jsxs(Hs,{value:"holds",children:["Holds ",b(h.holds)]}),e.jsx(Hs,{value:"assets",children:"Assets"}),e.jsxs(Hs,{value:"decisions",children:["Decisions & Recs ",b(h.decisions)]}),e.jsxs(Hs,{value:"asks",children:["Asks ",b(h.asks)]}),e.jsx(Hs,{value:"verify",children:"Verify"})]})}),e.jsx(zo,{message:x}),u&&d!=="verify"&&e.jsxs("div",{className:"text-sm text-muted-foreground mb-2",children:["Loading ",p.name,"â¦"]}),e.jsx(qs,{value:"overview",children:e.jsx(pP,{client:p,strategy:c.strategy,holds:c.holds,changes:c.changes,assets:c.assets})}),e.jsx(qs,{value:"changes",children:e.jsx(lP,{client:p,changes:c.changes})}),e.jsx(qs,{value:"holds",children:e.jsx(uP,{client:p,holds:c.holds})}),e.jsx(qs,{value:"assets",children:e.jsx(hP,{client:p,assets:c.assets})}),e.jsx(qs,{value:"decisions",children:e.jsx(gP,{decisions:c.decisions,recommendations:c.recommendations})}),e.jsx(qs,{value:"asks",children:e.jsx(yP,{client:p,asks:c.waitingOn})}),e.jsx(qs,{value:"verify",children:e.jsx(wP,{clients:n??[],clientFilter:p.id})})]})]})]})}function AP(){const[t,s]=l.useState([]),[n,r]=l.useState({}),[a,o]=l.useState(!0),[i,d]=l.useState(null),[m,p]=l.useState(!1),c=l.useRef(!0);l.useEffect(()=>()=>{c.current=!1},[]);const u=l.useCallback(async()=>{o(!0),d(null);try{const g=((await re("manageShopRepos",{action:"list"})).shops||[]).filter(E=>E.repos.some(C=>C.type==="theme")).map(E=>E.domain),{firestoreQuery:y}=await Gs(async()=>{const{firestoreQuery:E}=await import("./firebaseHelper-CezmP0DK.js").then(C=>C.p);return{firestoreQuery:E}},__vite__mapDeps([1,2,3])),{where:j}=await Gs(async()=>{const{where:E}=await import("./vendor-firebase-Cr-z2ntb.js").then(C=>C.R);return{where:E}},[]),v=await y("clientProjects",[j("status","not-in",["Complete","Archived","Cancelled"])]),T=await y("shopifyStores",[]),k=new Map;for(const E of T)if(E.myshopifyUrl){const C=E.myshopifyUrl.replace(/^https?:\/\//,"").replace(/\/+$/,"");k.set(E.id,C)}const w=v.filter(E=>E.shopifyStoreId).map(E=>({id:E.id,name:E.name||E.displayId||E.id,status:E.status||"Unknown",shopifyStoreId:E.shopifyStoreId,shopifyThemeId:E.shopifyThemeId||null,storeDomain:k.get(E.shopifyStoreId)||void 0})).filter(E=>E.storeDomain&&g.includes(E.storeDomain));c.current&&s(w);const I=[...new Set(w.map(E=>
411E.storeDomain).filter(Boolean))],A={};await Promise.all(I.map(async E=>{try{const C=await re("listShopThemes",{shopDomain:E});A[E]=C.themes||[]}catch(C){console.warn(`Failed to load themes for ${E}:`,C),A[E]=[]}})),c.current&&r(A)}catch(b){const f=b.message||"Failed to load theme data";c.current&&d(f)}finally{c.current&&o(!1)}},[]),x=l.useCallback(async b=>{try{const f=await re("listShopThemes",{shopDomain:b});c.current&&r(g=>({...g,[b]:f.themes||[]}))}catch(f){console.warn(`Failed to load themes for ${b}:`,f)}},[]),h=l.useCallback(async(b,f)=>{p(!0),d(null);try{await re("updateProjectThemeId",{projectId:b,shopifyThemeId:f}),c.current&&s(g=>g.map(y=>y.id===b?{...y,shopifyThemeId:f}:y))}catch(g){const y=g.message||"Failed to update theme ID";throw c.current&&d(y),g}finally{c.current&&p(!1)}},[]);return l.useEffect(()=>{u()},[u]),{projects:t,themes:n,loading:a,error:i,saving:m,loadData:u,loadThemesForShop:x,updateThemeId:h}}function EP({onBack:t,onLogoClick:s}){const{projects:n,themes:r,loading:a,error:o,saving:i,loadData:d,updateThemeId:m}=AP(),[p,c]=l.useState({}),u=async(h,b)=>{const f=b===""?null:b;try{await m(h,f),c(g=>({...g,[h]:{type:"success",text:"Saved"}})),setTimeout(()=>{c(g=>{const y={...g};return delete y[h],y})},2e3)}catch{c(g=>({...g,[h]:{type:"error",text:"Failed"}}))}},x=n.reduce((h,b)=>{const f=b.storeDomain||"Unknown Store";return h[f]||(h[f]=[]),h[f].push(b),h},{});return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-2xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Theme Management"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Assign Shopify preview themes to projects"})]}),e.jsxs("button",{onClick:d,disabled:a,className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground px-3 py-2 rounded-lg text-sm transition-colors",children:[e.jsx(yt,{style:{width:"16px",height:"16px"},className:a?"animate-spin":""}),"Refresh"]})]}),o&&e.jsx("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-3 mb-4 text-sm text-destructive",children:o}),a&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{style:{width:"24px",height:"24px"},className:"animate-spin text-muted-foreground"})}),!a&&n.length===0&&e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(mg,{style:{width:"48px",height:"48px",margin:"0 auto 12px"},className:"opacity-30"}),e.jsx("p",{className:"text-sm",children:"No active projects with configured shop repos found."}),e.jsx("p",{className:"text-xs mt-1",children:"Add theme repos in Shop Repos first."})]}),!a&&Object.entries(x).map(([h,b])=>{const f=r[h]||[];return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:h}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[f.length," theme",f.length!==1?"s":""," available"]})]}),e.jsx("div",{className:"bg-card border border-border rounded-lg overflow-hidden",children:b.map((g,y)=>{var T;const j=p[g.id],v=g.shopifyThemeId?(T=f.find(k=>String(k.id)===g.shopifyThemeId))==null?void 0:T.name:null;return e.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 ${y<b.length-1?"border-b border-border":""}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:g.name}),e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded",style:{backgroundColor:g.status==="In Progress"?"var(--color-primary-light, #dbeafe)":"var(--color-muted, #f3f4f6)",color:g.status==="In Progress"?"var(--color-primary, #1e40af)":"var(--color-muted-foreground, #6b7280)"},children:g.status})]}),v&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Current: ",v]})]}),e.jsxs("select",{value:g.shopifyThemeId||"",disabled:i,onChange:k=>u(g.id,k.target.value),className:"bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground min-w-[180px] disabled:opacity-50",children:[e.jsx("option",{value:"",children:"â None â"}),f.map(k=>
411e.jsxs("option",{value:String(k.id),children:[k.name," (",k.id,")"]},k.id)),g.shopifyThemeId&&!f.find(k=>String(k.id)===g.shopifyThemeId)&&e.jsxs("option",{value:g.shopifyThemeId,children:["ID: ",g.shopifyThemeId," (not in store)"]})]}),e.jsxs("div",{style:{width:60,textAlign:"center"},children:[i&&e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin text-muted-foreground inline-block"}),j&&e.jsxs("span",{className:"text-xs font-medium",style:{color:j.type==="success"?"var(--color-success, #16a34a)":"var(--color-destructive, #ef4444)"},children:[j.type==="success"&&e.jsx(kt,{style:{width:"12px",height:"12px",display:"inline",marginRight:2}}),j.text]})]})]},g.id)})})]},h)})]})]})}function IP(){const[t,s]=l.useState([]),[n,r]=l.useState(!0),[a,o]=l.useState(null),[i,d]=l.useState(null),m=l.useRef(!0);l.useEffect(()=>()=>{m.current=!1},[]);const p=l.useCallback(async()=>{r(!0),o(null);try{const x=await re("auditClientSetup",{});m.current&&s(x.clients||[])}catch(x){m.current&&o((x==null?void 0:x.message)||"Failed to load audit")}finally{m.current&&r(!1)}},[]),c=l.useCallback(async x=>{var h;try{const f=(h=(await re("auditClientSetup",{clientId:x})).clients)==null?void 0:h[0];f&&m.current&&s(g=>g.map(y=>y.clientId===x?f:y))}catch{}},[]),u=l.useCallback(async(x,h,b)=>{d(`${x}:${h}`);try{const g=(await re("applyClientSetupFix",{clientId:x,checkId:h,overrides:b})).report;return m.current&&s(y=>y.map(j=>j.clientId===x?g:j)),g}finally{m.current&&d(null)}},[]);return l.useEffect(()=>{p()},[p]),{reports:t,loading:n,error:a,fixing:i,loadData:p,auditOne:c,fixGap:u}}const RP={shopify:"Shopify delivery",slack:"Slack + credits",contacts:"Contacts / CRM",dmarc:"Email / DMARC",chat:"Chat / Communications Hub"};function Ly({repo:t,branch:s,onChange:n,repoOnly:r}){const[a,o]=l.useState([]),[i,d]=l.useState([]),[m,p]=l.useState(!0),[c,u]=l.useState(!1),[x,h]=l.useState(null);l.useEffect(()=>{let f=!0;return(async()=>{p(!0),h(null);try{const y=((await re("listGithubRepos",{})).repos||[]).slice().sort((j,v)=>j.fullName.localeCompare(v.fullName,void 0,{sensitivity:"base"}));f&&o(y)}catch(g){f&&h((g==null?void 0:g.message)||"Failed to load repos")}finally{f&&p(!1)}})(),()=>{f=!1}},[]),l.useEffect(()=>{if(r||!t){d([]);return}let f=!0;return(async()=>{u(!0);try{const g=await re("listRepoBranches",{repo:t});f&&d(g.branches||[])}catch{f&&d([])}finally{f&&u(!1)}})(),()=>{f=!1}},[t]);const b=f=>{if(r){n({repo:f,branch:""});return}const g=a.find(y=>y.fullName===f);n({repo:f,branch:(g==null?void 0:g.defaultBranch)||"main"})};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"GitHub theme repo"}),m?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-1.5",children:[e.jsx(fe,{className:"w-3.5 h-3.5 animate-spin"})," Loading reposâ¦"]}):e.jsxs("select",{value:t,onChange:f=>b(f.target.value),className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground",children:[e.jsx("option",{value:"",children:"â Select repo â"}),a.map(f=>e.jsx("option",{value:f.fullName,children:f.fullName},f.fullName))]})]}),r?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Registers both ",e.jsx("span",{className:"font-mono",children:"main"})," + ",e.jsx("span",{className:"font-mono",children:"staging"})," theme repos."]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"Branch"}),e.jsxs("select",{value:s,disabled:!t||c,onChange:f=>n({repo:t,branch:f.target.value}),className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground disabled:opacity-50",children:[c&&e.jsx("option",{children:"Loadingâ¦"}),!c&&i.length===0&&e.jsx("option",{value:s,children:s||"â"}),!c&&i.map(f=>e.jsx("option",{value:f,children:f},f))]})]}),x&&e.jsx("p",{className:"text-xs text-destructive",children:x})]})}const $o="sunbowl",vl="lane:",Xc=t=>String(t).replace(vl,"");function DP({lane:t,depth:s,open:n,hasKids:r,selected:a,draggable:o,droppable:i,onToggle:d,onSelect:m}){const p=`${vl}${t.id}`,c=iu({id:p,disabled:!o,data:{laneId:t.id}}),u=ou({id:p,disabled:!i,data:{laneId:t.id}}),x=b=>{c.setNodeRef(b),u.setNodeRef(b)},h=u.isOver&&i;return e.jsxs("div",{ref:x,"data-testid":`lane-row-${t.id}`,"data-over":h?"true":void 0,className:`w-full text-left rounded-md ${a?"bg-primary/10 text-foreground":"text-foreground hover:bg-muted"} ${h?"ring-2 ring-primary":""}`,style:{display:"flex",alignItems:"center",gap:6,padding:"6px 8px",paddingLeft:8+s*16,fontSize:14,opacity:c.isDragging?.4:1,cursor:m?"pointer":"default"},onClick:m,role:m?"button":void 0,children:[e.jsx("span",{onClick:b=>{b.stopPropagation(),d()},"aria-label":n?"Collapse":"Expand",style:{width:16,display:"inline-flex",opacity:r?1:.25},children:n?e.jsx(Ot,{size:14}):e.jsx(Rt,{size:14})}),e.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",o
411pacity:t.archived?.55:1},children:t.name}),e.jsxs("span",{className:"text-muted-foreground",style:{fontSize:11},children:["#",t.handle]}),o&&e.jsx("span",{...c.listeners,...c.attributes,"aria-label":`Drag ${t.name}`,className:"text-muted-foreground",style:{cursor:"grab",display:"inline-flex",touchAction:"none"},onClick:b=>b.stopPropagation(),children:e.jsx(Yr,{size:14})})]})}function zy({accounts:t,selectedId:s,onSelect:n,filter:r,initiallyExpanded:a=[$o],hideArchived:o,disabledDropIds:i,dnd:d,header:m,emptyText:p="No lanes yet.",maxHeight:c}){const[u,x]=l.useState(()=>new Set(a)),[h,b]=l.useState(null),f=l.useMemo(()=>o?t.filter(S=>!S.archived):t,[t,o]),g=l.useMemo(()=>new Map(f.map(S=>[S.id,S])),[f]),y=l.useMemo(()=>{const S=new Map;for(const O of f)S.set(O.parentId,[...S.get(O.parentId)??[],O]);for(const O of S.values())O.sort((R,z)=>R.name.localeCompare(z.name));return S},[f]),j=l.useMemo(()=>f.filter(S=>!S.parentId||!g.has(S.parentId)),[f,g]),v=l.useMemo(()=>{const S=(r??"").trim().toLowerCase();return S?new Set(f.filter(O=>O.name.toLowerCase().includes(S)||O.handle.includes(S)).map(O=>O.id)):null},[f,r]),T=S=>!!(v!=null&&v.has(S.id))||(y.get(S.id)??[]).some(T),k=S=>x(O=>{const R=new Set(O);return R.has(S)?R.delete(S):R.add(S),R}),w=(S,O)=>{const R=y.get(S.id)??[],z=u.has(S.id)||!!v;if(v&&!v.has(S.id)&&!R.some(L=>T(L)))return null;const D=!!d&&!S.archived&&!(i!=null&&i.has(S.id))&&!((d==null?void 0:d.mode)==="move"&&h&&(S.id===h||S.path.includes(h)));return e.jsxs("div",{children:[e.jsx(DP,{lane:S,depth:O,open:z,hasKids:R.length>0,selected:s===S.id,draggable:(d==null?void 0:d.mode)==="move"&&!!S.parentId&&!S.archived,droppable:D,onToggle:()=>k(S.id),onSelect:n?()=>n(S.id):void 0}),z&&R.map(L=>w(L,O+1))]},S.id)},I=j.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",style:{padding:8},children:p}):j.map(S=>w(S,0)),A=Ho(Rn(Yo,{activationConstraint:{distance:5}}),Rn(Vo));if(!d)return e.jsxs("div",{style:{maxHeight:c,overflow:c?"auto":void 0},children:[m,I]});const E=S=>b(String(S.active.id).startsWith(vl)?Xc(S.active.id):String(S.active.id)),C=S=>{var z;if(b(null),!S.over)return;const O=Xc(S.over.id),R=String(S.active.id).startsWith(vl)?Xc(S.active.id):String(S.active.id);d.mode==="move"&&(R===O||(z=g.get(O))!=null&&z.path.includes(R))||d.onDrop(R,O)},N=h?g.get(h):null;return e.jsxs(qo,{sensors:A,onDragStart:E,onDragEnd:C,onDragCancel:()=>b(null),children:[e.jsxs("div",{style:{maxHeight:c,overflow:c?"auto":void 0},children:[m,I]}),e.jsx(Mf,{dropAnimation:null,children:N?e.jsxs("div",{className:"bg-card border border-border rounded-md shadow-md text-foreground",style:{padding:"4px 10px",fontSize:13},children:[N.name," ",e.jsxs("span",{className:"text-muted-foreground",children:["#",N.handle]})]}):null})]})}const MP="new-client";function PP({label:t}){const s=iu({id:MP});return e.jsxs("div",{ref:s.setNodeRef,...s.listeners,...s.attributes,"data-testid":"lane-placement-chip",className:"bg-primary text-primary-foreground rounded-md",style:{display:"inline-flex",alignItems:"center",gap:6,padding:"6px 10px",fontSize:13,fontWeight:600,cursor:"grab",touchAction:"none",opacity:s.isDragging?.4:1,marginBottom:8},children:[e.jsx(Yr,{size:14}),t||"New client"]})}function Oy({newLabel:t,value:s,onChange:n,excludeIds:r}){var h;const a=El(!0),[o,i]=l.useState(""),d=((h=a.access)==null?void 0:h.accounts)??[],m=l.useMemo(()=>new Map(d.map(b=>[b.id,b])),[d]),p=s||$o,c=m.get(p),u=l.useMemo(()=>new Set(r??[]),[r]),x=c?[...c.path.map(b=>{var f;return((f=m.get(b))==null?void 0:f.name)??b}),c.name].join(" ⺠"):p;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag the client onto the lane it belongs under â an agency like Harper + Scott â or leave it on Sunbowl to keep it top-level."}),e.jsx("input",{value:o,onChange:b=>i(b.target.value),placeholder:"Find a laneâ¦","aria-label":"Find a lane",className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground"}),e.jsx("div",{className:"bg-background border border-border rounded-md",style:{padding:6},children:a.loading?e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2",style:{padding:8},children:[e.jsx(fe,{size:14,className:"animate-spin"})," Loading the account treeâ¦"]}):a.error?e.jsx("p",{className:"text-xs text-destructive",style:{padding:8},children:a.error}):e.jsx(zy,{accounts:d,hideArchived:!0,filter:o,selectedId:p,onSelect:n,disabledDropIds:u,maxHeight:"40vh",dnd:{mode:"place",onDrop:(b,f)=>{u.has(f)||n(f)}},header:e.jsx(PP,{label:t})})}),e.jsxs("p",{className:"text-xs text-foreground","data-testid":"lane-placement-summary",children:["Will sit under ",e.jsx("span",{className:"font-medium",children:x}),p===$o?" (top-level)":""]})]})}function ed(t){return String(t||"").trim().replace(/^#/,"").toLowerCase().replace(/&/g," and ").replace(/[^a-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}function LP({onLogoClick:t,onClose:s,onDone:n}){const[r,a]=l.useState(""),[o,i]=l.useState(""),[d,m]=l.useState("main"),[p,c]=l.useState(null),[u,x]=l.useState(!1),[h,b]=l.useState(""),[f,g]=l.useState(""),[y,j]=l.useState(""),[v,T]=l.useState(!0),[k,w]=l.useState($o),[I,A]=l.useState(""),[E,C]=l.useState(""),[N,S]=l.useState(""),[O,R
411]=l.useState(""),[z,D]=l.useState(""),[L,$]=l.useState(!1),[q,P]=l.useState(null),[U,V]=l.useState(null),M=async()=>{if(r.trim()){x(!0),P(null);try{const W=await re("previewClientOnboard",{shopUrl:r.trim(),repo:o.trim()||void 0,branch:d.trim()||"main"});c(W),W.shopify.found&&(!h&&W.shopify.name&&b(W.shopify.name),!f&&W.shopify.name&&g(ed(W.shopify.name)),!I&&W.shopify.emailDomain&&A(W.shopify.emailDomain))}catch(W){P((W==null?void 0:W.message)||"Derive failed")}finally{x(!1)}}},F=async()=>{if(P(null),!h.trim()){P("Company name is required");return}if(!r.trim()){P("Shopify URL is required");return}$(!0);try{const W=await re("onboardClient",{companyName:h.trim(),myshopifyUrl:r.trim(),storeName:(p==null?void 0:p.shopify.name)||h.trim(),onlineStoreUrl:p==null?void 0:p.shopify.onlineStoreUrl,slackChannelName:f.trim()||void 0,slackChannelId:y.trim()||void 0,createSlackChannel:v,laneParentId:k,emailDomain:I.trim()||void 0,repo:o.trim()||void 0,branch:d.trim()||"main",contact:E.trim()?{email:E.trim(),firstName:N.trim(),lastName:O.trim()}:void 0,createProjectName:z.trim()||void 0});V({report:W.report,warnings:W.warnings||[]})}catch(W){P((W==null?void 0:W.message)||"Onboard failed")}finally{$(!1)}};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:t}),e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:s,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"New Client"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Onboard from a Shopify URL + repo"})]})]}),U?e.jsx(OP,{result:U,onDone:n}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs(Ii,{title:"1 · Source",children:[e.jsx(Wn,{label:"Shopify URL",value:r,onChange:a,placeholder:"store.myshopify.com"}),e.jsx(Ly,{repoOnly:!0,repo:o,branch:d,onChange:({repo:W,branch:_})=>{i(W),m(_)}}),e.jsxs("button",{onClick:M,disabled:u||!r.trim(),className:"flex items-center gap-1.5 text-sm font-medium bg-primary/10 text-primary px-3 py-2 rounded-md hover:bg-primary/20 disabled:opacity-50",children:[u?e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"}):e.jsx(ws,{style:{width:"14px",height:"14px"}}),"Derive details"]}),p&&e.jsx(zP,{preview:p})]}),e.jsxs(Ii,{title:"2 · Details",children:[e.jsx(Wn,{label:"Company name *",value:h,onChange:b,placeholder:"Acme Co"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Wn,{label:"Slack channel",value:f,onChange:g,placeholder:"acme-co"}),e.jsx(Wn,{label:"Channel ID (optional)",value:y,onChange:j,placeholder:"auto-detect"})]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm text-foreground",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:W=>T(W.target.checked),className:"mt-0.5"}),e.jsxs("span",{children:["Create ",e.jsxs("span",{className:"font-mono",children:["#",ed(f||h)||"channel"]})," in Slack if it doesn't exist, and invite all active staff"]})]}),e.jsx(Wn,{label:"Email domain",value:I,onChange:A,placeholder:"acme.com"})]}),e.jsx(Ii,{title:"3 · Chat lane",children:e.jsx(Oy,{newLabel:h||ed(f)||"New client",value:k,onChange:w})}),e.jsxs(Ii,{title:"4 · Optional",children:[e.jsx(Wn,{label:"Primary contact email",value:E,onChange:C,placeholder:"[email protected]"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Wn,{label:"First name",value:N,onChange:S,placeholder:"Jane"}),e.jsx(Wn,{label:"Last name",value:O,onChange:R,placeholder:"Doe"})]}),e.jsx(Wn,{label:"First project name",value:z,onChange:D,placeholder:"e.g. Revamp site"})]}),q&&e.jsx("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-3 text-sm text-destructive",children:q}),e.jsxs("button",{onClick:F,disabled:L,className:"w-full flex items-center justify-center gap-2 bg-primary text-primary-foreground px-4 py-2.5 rounded-lg text-sm font-medium hover:opacity-90 disabled:opacity-50",children:[L&&e.jsx(fe,{style:{width:"16px",height:"16px"},className:"animate-spin"}),"Create client"]})]})]})]})}function Ii({title:t,children:s}){return e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 space-y-3",children:[e.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:t}),s]})}function Wn({label:t,value:s,onChange:n,placeholder:r,type:a}){return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:t}),e.jsx("input",{type:a==="number"?"number":"text",value:s,placeholder:r,onChange:o=>n(o.target.value),className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground"})]})}function zP({preview:t}){var s;return e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1 border-t border-border pt-2 mt-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[t.shopify.found?e.jsx(kt,{style:{width:"12px",height:"12px",color:"#15803d"}}
411):e.jsx(Dt,{style:{width:"12px",height:"12px",color:"#b45309"}}),"Shopify: ",t.shopify.found?`${t.shopify.name||t.domain}${t.shopify.currency?` · ${t.shopify.currency.toUpperCase()}`:""}`:"no installed-app session (enter details manually)"]}),t.github&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[t.github.found?e.jsx(kt,{style:{width:"12px",height:"12px",color:"#15803d"}}):e.jsx(Dt,{style:{width:"12px",height:"12px",color:"#b45309"}}),"GitHub: ",t.github.found?`${((s=t.github.branches)==null?void 0:s.length)||0} branch(es)${t.github.isTheme?" · theme detected":""}`:"repo not found / not set"]})]})}function OP({result:t,onDone:s}){const{report:n,warnings:r}=t;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 text-center",children:[e.jsx(Ns,{style:{width:"40px",height:"40px",margin:"0 auto 8px",color:"#15803d"}}),e.jsxs("h2",{className:"font-semibold text-foreground",children:[n.companyName||n.name," created"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Setup score ",n.score,"% · ",n.errorGaps," gap(s), ",n.warnGaps," warning(s) remaining"]})]}),n.checks.filter(a=>a.status==="fail").length>0&&e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",children:[e.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2",children:"Remaining gaps"}),e.jsx("div",{className:"space-y-1.5",children:n.checks.filter(a=>a.status==="fail").map(a=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Dt,{style:{width:"14px",height:"14px",marginTop:2,color:a.severity==="error"?"#b91c1c":"#b45309"},className:"flex-shrink-0"}),e.jsxs("span",{className:"text-foreground",children:[a.label,e.jsxs("span",{className:"text-muted-foreground",children:[" â ",a.detail]})]})]},a.id))})]}),r.length>0&&e.jsx("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-3 text-xs text-destructive",children:r.map((a,o)=>e.jsx("div",{children:a},o))}),e.jsx("button",{onClick:s,className:"w-full bg-primary text-primary-foreground px-4 py-2.5 rounded-lg text-sm font-medium hover:opacity-90",children:"Done â view audit"})]})}const $P=["shopify","slack","chat","contacts","dmarc"];function BP({onBack:t,onLogoClick:s}){const{reports:n,loading:r,error:a,fixing:o,loadData:i,auditOne:d,fixGap:m}=IP(),[p,c]=l.useState(null),[u,x]=l.useState(new Set),h=j=>{const v=p!==j;c(v?j:null),v&&!u.has(j)&&(x(T=>new Set(T).add(j)),d(j))},[b,f]=l.useState(null),[g,y]=l.useState(!1);return g?e.jsx(LP,{onLogoClick:s,onClose:()=>y(!1),onDone:()=>{y(!1),i()}}):e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-2xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Client Setup"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Audit configuration gaps & onboard new clients"})]}),e.jsxs("button",{onClick:()=>y(!0),className:"flex items-center gap-1.5 bg-primary text-primary-foreground px-3 py-2 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity",children:[e.jsx(vg,{style:{width:"16px",height:"16px"}}),"New Client"]}),e.jsxs("button",{onClick:i,disabled:r,className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground px-3 py-2 rounded-lg text-sm transition-colors",children:[e.jsx(yt,{style:{width:"16px",height:"16px"},className:r?"animate-spin":""}),"Refresh"]})]}),a&&e.jsx("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-3 mb-4 text-sm text-destructive",children:a}),r&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{style:{width:"24px",height:"24px"},className:"animate-spin text-muted-foreground"})}),!r&&n.map(j=>e.jsx(FP,{report:j,expanded:p===j.clientId,onToggle:()=>h(j.clientId),fixing:o,onFix:v=>f({report:j,check:v})},j.clientId)),!r&&n.length===0&&!a&&e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:"No clients found."})]}),b&&e.jsx(UP,{report:b.report,check:b.check,busy:o===`${b.report.clientId}:${b.check.id}`,onClose:()=>f(null),onSubmit:async j=>{await m(b.report.clientId,b.check.id,j),f(null)}})]})}function FP({report:t,expanded:s,onToggle:n,fixing:r,onFix:a}){const o=t.errorGaps===0&&t.warnGaps===0,i=t.errorGaps>0?"#b91c1c":t.warnGaps>0?"#b45309":"#15803d";return e.jsxs("div",{className:"bg-card border border-border rounded-lg mb-3 overflow-hidden",children:[e.jsxs("button",{onClick:n,className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-muted/40 transition-colors",children:[s?e.jsx(Ot,{style:{width:"16px",height:"16px"},className:"text-muted-foreground flex-shrink-0"}):e.jsx(Rt,{style:{width:"16px",height:"16px"},className:"text-muted-foreground flex-shrink-0"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:t.companyName||t.name}),t.displayId&&e.jsx("span",{className:"text-xs text-muted-foreground",children:t.displayId})]})}),o?e.jsxs("span",{className:"flex items-center gap-1 text-xs font-medium",style:{color:i},children:[e.jsx(kt,{style:{width:"14px",height:"14px"}})," All good"]}):e.jsxs("span",{className:"text-xs font-medium",style:{color:i},children:[t.errorGaps>0&&`${t.errorGaps} gap${t.errorGaps!==1?"s":""}`,t.errorGaps>0&&t.warnGaps>0&&", ",t.warnGaps>0&&`${t.warnGaps} warn`]}),e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",style:{width:34,textAlign:"right"},children:[t.score,"%"]})]}),s&&e.jsx("div",{className:"border-t border-border px-4 py-3 space-y-4",children:$P.map(d=>{const m=t.checks.filter(p=>p.dimension===d);return m.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1.5",children:RP[d]}),e.jsx("div",{className:"space-y-1.5",children:m.map(p=>e.jsx(WP,{check:p,busy:r===`${t.clientId}:${p.id}`,onFix:()=>a(p)},p.id))})]},d)})})]})}function _P(t){switch(t.status){case"ok":return{icon:e.jsx(kt,{style:{width:"14px",height:"14px",color:"#15803d"}}
411),title:"Passing"};case"na":return{icon:e.jsx(su,{style:{width:"14px",height:"14px"},className:"text-muted-foreground"}),title:"Not applicable â doesn't apply to this client"};default:return t.severity==="error"?{icon:e.jsx(mt,{style:{width:"14px",height:"14px",color:"#b91c1c"}}),title:"Needs attention"}:{icon:e.jsx(Dt,{style:{width:"14px",height:"14px",color:"#b45309"}}),title:"Warning"}}}function WP({check:t,busy:s,onFix:n}){const[r,a]=l.useState(!1),{icon:o,title:i}=_P(t);return e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"flex-shrink-0 mt-0.5",title:i,children:o}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm text-foreground",children:t.label}),t.status==="fail"&&t.detail&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:t.detail}),r&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 break-words",style:{fontFamily:"var(--font-mono, ui-monospace, monospace)"},children:t.value||"â"})]}),t.value!==void 0&&e.jsx("button",{onClick:()=>a(d=>!d),title:"Quick view current value","aria-label":"Quick view current value",className:`flex-shrink-0 p-1 rounded-md transition-colors ${r?"text-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(So,{style:{width:"14px",height:"14px"}})}),t.status==="fail"&&t.fixable&&e.jsxs("button",{onClick:n,disabled:s,className:"flex-shrink-0 flex items-center gap-1 text-xs font-medium bg-primary/10 text-primary px-2 py-1 rounded-md hover:bg-primary/20 transition-colors disabled:opacity-50",children:[s?e.jsx(fe,{style:{width:"12px",height:"12px"},className:"animate-spin"}):e.jsx(jN,{style:{width:"12px",height:"12px"}}),"Fix"]})]})}function UP({report:t,check:s,busy:n,onClose:r,onSubmit:a}){const o=s.requiresInput||[],[i,d]=l.useState(()=>Object.fromEntries(o.map(b=>[b.name,b.default||""]))),m=s.targets||[],[p,c]=l.useState(m[0]||""),[u,x]=l.useState(null),h=async()=>{x(null);const b={};for(const f of o){const g=(i[f.name]||"").trim();g&&(b[f.name]=f.type==="number"?Number(g):g)}s.id==="shopify.themeRepo"&&p&&(b.domain=p);try{await a(b)}catch(f){x((f==null?void 0:f.message)||"Fix failed")}};return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50 px-4",onClick:r,children:e.jsxs("div",{className:`bg-card border border-border rounded-lg w-full ${s.id==="chat.lane"?"max-w-md":"max-w-sm"} p-4`,onClick:b=>b.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:s.label}),e.jsx("button",{onClick:r,className:"text-muted-foreground hover:text-foreground",children:e.jsx(mt,{style:{width:"16px",height:"16px"}})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:t.companyName||t.name}),o.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Apply the automatic fix for this gap?"}),s.id==="shopify.themeRepo"?e.jsxs("div",{className:"space-y-3",children:[m.length>1&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"Store"}),e.jsx("select",{value:p,onChange:b=>c(b.target.value),className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground",children:m.map(b=>e.jsx("option",{value:b,children:b},b))}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[m.length," stores need repos â each is set up separately with its own repo."]})]}),m.length===1&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Store: ",e.jsx("span",{className:"font-mono",children:p})]}),e.jsx(Ly,{repoOnly:!0,repo:i.repo||"",branch:i.branch||"",onChange:({repo:b,branch:f})=>d(g=>({...g,repo:b,branch:f}))})]}):s.id==="chat.lane"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"Lane handle"}),e.jsx("input",{type:"text",value:i.handle??"",placeholder:"acme-co (blank = from the Slack channel or company name)",onChange:b=>d(f=>({...f,handle:b.target.value})),className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground"})]}),e.jsx(Oy,{newLabel:t.companyName||t.name,value:i.parentId||$o,onChange:b=>d(f=>({...f,parentId:b}))})]}):e.jsx("div",{className:"space-y-3",children:o.map(b=>b.type==="boolean"?e.jsxs("label",{className:"flex items-start gap-2 text-sm text-foreground",children:[e.jsx("input",{type:"checkbox",checked:(i[b.n
411ame]??b.default??"false")==="true",onChange:f=>d(g=>({...g,[b.name]:f.target.checked?"true":"false"})),className:"mt-0.5"}),e.jsx("span",{children:b.label})]},b.name):e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:b.label}),e.jsx("input",{type:b.type==="number"?"number":"text",value:i[b.name]??"",placeholder:b.placeholder,onChange:f=>d(g=>({...g,[b.name]:f.target.value})),className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground"})]},b.name))}),s.id==="slack.projectMapping"&&e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Leave blank to auto-detect the channel ID from Slack."}),u&&e.jsx("p",{className:"text-xs text-destructive mt-3",children:u}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx("button",{onClick:r,className:"flex-1 px-3 py-2 rounded-md text-sm border border-border text-muted-foreground hover:text-foreground",children:"Cancel"}),e.jsxs("button",{onClick:h,disabled:n,className:"flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium bg-primary text-primary-foreground hover:opacity-90 disabled:opacity-50",children:[n&&e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"}),"Apply Fix"]})]})]})})}function HP(){const[t,s]=l.useState(null),[n,r]=l.useState([]),[a,o]=l.useState([]),[i,d]=l.useState(!0),[m,p]=l.useState(null),[c,u]=l.useState(!1),[x,h]=l.useState(!1),[b,f]=l.useState(!1),g=l.useRef(!0);l.useEffect(()=>()=>{g.current=!1},[]);const y=l.useCallback(async()=>{try{const D=await re("listPromoCampaigns",{});g.current&&r(D.campaigns||[])}catch{}},[]),j=l.useCallback(async()=>{try{const D=await re("listPromoOptIns",{});g.current&&o(D.optIns||[])}catch{}},[]),v=l.useCallback(async()=>{d(!0),p(null);try{const[D]=await Promise.all([re("getPromoConfig",{}),y(),j()]);g.current&&s(D)}catch(D){g.current&&p((D==null?void 0:D.message)||"Failed to load promo config")}finally{g.current&&d(!1)}},[y,j]),T=l.useCallback(async()=>{u(!0),p(null);try{await re("setPromoCaptureOwner",{}),await v()}catch(D){throw g.current&&p((D==null?void 0:D.message)||"Could not set capture inbox"),D}finally{g.current&&u(!1)}},[v]),k=l.useCallback(async D=>{u(!0);try{await re("upsertPromoCaptureMapping",D),await v()}finally{g.current&&u(!1)}},[v]),w=l.useCallback(async(D,L)=>{u(!0);try{await re("setPromoMappingStage",{tag:D,lifecycleStage:L}),await v()}finally{g.current&&u(!1)}},[v]),I=l.useCallback(async(D,L)=>{u(!0);try{await re("setPromoMappingLiveList",{tag:D,liveList:L}),await v()}finally{g.current&&u(!1)}},[v]),A=l.useCallback(async(D,L=!1)=>{u(!0);try{await re("deletePromoCaptureMapping",{tag:D,hard:L}),await v()}finally{g.current&&u(!1)}},[v]),E=l.useCallback(async()=>{h(!0),p(null);try{const D=await re("adminTriggerPromoIngest",{});return await Promise.all([y(),j()]),(D==null?void 0:D.summary)??null}catch(D){return g.current&&p((D==null?void 0:D.message)||"Ingest failed"),null}finally{g.current&&h(!1)}},[y,j]),C=l.useCallback(async D=>{f(!0),p(null);try{const L=await re("adminTriggerPromoCadenceCheck",D?{tag:D}:{});return await v(),(L==null?void 0:L.summary)??null}catch(L){return g.current&&p((L==null?void 0:L.message)||"Cadence check failed"),null}finally{g.current&&f(!1)}},[v]),N=l.useCallback(async(D,L)=>{u(!0),p(null);try{await re("setPromoCadenceTarget",{tag:D,targetGapDays:L}),await v()}catch($){g.current&&p(($==null?void 0:$.message)||"Could not save target")}finally{g.current&&u(!1)}},[v]),S=l.useCallback(async D=>{u(!0),p(null);try{await re("setPromoAlertRecipients",{recipientEmails:D}),await v()}catch(L){g.current&&p((L==null?void 0:L.message)||"Could not save recipients")}finally{g.current&&u(!1)}},[v]),O=l.useCallback(async D=>{try{await re("markPromoOutreachHandled",{tag:D})}catch(L){g.current&&p((L==null?void 0:L.message)||"Could not mark handled")}},[]),R=l.useCallback(async D=>{try{await re("markPromoOptInConfirmed",{id:D}),await j()}catch(L){g.current&&p((L==null?void 0:L.message)||"Failed to confirm opt-in")}},[j,p]),z=l.useCallback(async D=>{try{await re("dismissPromoOptIn",{id:D}),await j()}catch(L){g.current&&p((L==null?void 0:L.message)||"Failed to dismiss opt-in")}},[j,p]);return l.useEffect(()=>
411{v()},[v]),{config:t,campaigns:n,optIns:a,loading:i,error:m,busy:c,ingesting:x,checkingCadence:b,loadData:v,setOwner:T,upsertMapping:k,setMappingStage:w,setMappingLiveList:I,removeMapping:A,runIngest:E,runCadenceCheck:C,setCadenceTarget:N,setAlertRecipients:S,markOutreachHandled:O,confirmOptIn:R,dismissOptIn:z}}const Ds={good:{bg:"rgba(21,128,61,0.12)",fg:"#15803d"},warn:{bg:"rgba(217,119,6,0.14)",fg:"#b45309"},bad:{bg:"rgba(225,29,72,0.12)",fg:"#be123c"},muted:{bg:"rgba(120,120,120,0.12)",fg:"#71717a"}};function fo(t){return t?t.status==="quiet"||t.status==="lapsed"?"quiet":t.status==="slowing"?"slowing":"on_track":"never"}const xa={quiet:{label:"Quiet",tone:"bad",rank:0,blurb:"Two cycles late. Reach out."},slowing:{label:"Slowing",tone:"warn",rank:1,blurb:"One cycle late."},never:{label:"Never captured",tone:"muted",rank:2,blurb:"Nothing has ever arrived at this address."},on_track:{label:"On track",tone:"good",rank:3,blurb:"Sending within their rhythm."}};function wl({tone:t,children:s,title:n}){return e.jsx("span",{title:n,style:{backgroundColor:Ds[t].bg,color:Ds[t].fg},className:"promo-pill inline-flex items-center gap-1 px-1.5 py-0.5 rounded flex-shrink-0 whitespace-nowrap",children:s})}function qP(t){return t==="pass"?"good":t==="warn"?"warn":t==="fail"?"bad":"muted"}function Ri({label:t,status:s,title:n}){const r=qP(s),a=s==="pass"?kt:s==="warn"?Dt:s==="fail"?mt:Wl,o=s==="pass"?"ok":s==="warn"?"check":s==="fail"?"issue":"n/a";return e.jsxs("div",{className:"flex flex-col items-start",style:{minWidth:64},title:n,children:[e.jsx("span",{className:"promo-label",children:t}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium",style:{color:Ds[r].fg},children:[e.jsx(a,{style:{width:"12px",height:"12px"}}),o]})]})}function Nl(t){switch(t){case"pass":return{label:"pass",style:{backgroundColor:Ds.good.bg,color:Ds.good.fg}};case"warn":return{label:"warn",style:{backgroundColor:Ds.warn.bg,color:Ds.warn.fg}};case"fail":return{label:"fail",style:{backgroundColor:Ds.bad.bg,color:Ds.bad.fg}};default:return{label:"pending",style:{backgroundColor:Ds.muted.bg,color:Ds.muted.fg}}}}function om({kind:t,countsForCadence:s}){if(!t)return null;const n=t==="marketing"?"good":t==="test"?"muted":"warn",r=s===!1?"Not a marketing send; does not count toward cadence":"Marketing send; counts toward cadence";return e.jsx(wl,{tone:n,title:r,children:t})}function td(t){if(!t)return"";const s=Math.floor((Date.now()-t)/864e5);return s<=0?"today":s===1?"yesterday":`${s}d ago`}function Gd(t){return t?new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"}):""}function sd(t){if(!t)return null;if(typeof t=="number")return t;const s=t;if(typeof s.toMillis=="function")return s.toMillis();const n=s._seconds??s.seconds;return typeof n=="number"?n*1e3:null}function VP({mapping:t}){const s=t.klaviyo;if(!s)return e.jsxs("div",{className:"flex flex-col items-start",style:{minWidth:92},title:"No Klaviyo key stored for this client's store",children:[e.jsx("span",{className:"promo-label",children:"Klaviyo"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"not linked"})]});if(s.error)return e.jsxs("div",{className:"flex flex-col items-start",style:{minWidth:92},title:s.error,children:[e.jsx("span",{className:"promo-label",children:"Klaviyo"}),e.jsx("span",{className:"text-xs",style:{color:"#be123c"},children:"error"})]});const n=s.missingFrom.length,r=s.autoAdded.length,a=n>0?s.subscribeError?`missing from ${n}, key read-only`:`missing from ${n}`:s.profileId?"in audience":"no profile yet",o=n>0?"#b45309":s.profileId?"#15803d":"#71717a";return e.jsxs("div",{className:"flex flex-col items-start",style:{minWidth:92},title:`${s.accountName?`Klaviyo account: ${s.accountName}. `:""}${s.sendCount30d} Klaviyo send${s.sendCount30d===1?"":"s"} in 30 days${r?`; auto-subscribed to ${r} list${r===1?"":"s"}`:""}`,children:[e.jsx("span",{className:"promo-label",children:"Klaviyo"}),e.jsx("span",{className:"text-xs font-medium",style:{color:o},children:a})]})}function YP(t){var T,k,w,I;const{mapping:s,campaigns:n}=t,r=fo(s.cadence),a=xa[r],o=s.cadence,i=sd(o==null?void 0:o.lastSendAt),[d,m]=l.useState(!1),[p,c]=l.useState(s.targetGapDays?String(s.targetGapDays):""),[u,x]=l.useState(!1),[h,b]=l.useState(!1),f=async()=>{try{await navigator.clipboard.writeText(s.captureAddress),m(!0),setTimeout(()=>m(!1),1500)}catch{}},g=async()=>{const A=p.trim()===""?null:Number(p);if(!(A!==null&&(!Number.isFinite(A)||A<1||A>120))){x(!0);try{await t.onSetTarget(A)}finally{x(!1)}}},y=o!=null&&o.expectedGapDays?`every ~${o.expectedGapDays}d`:o?"one send day":"",j=n.filter(A=>A.countsForCadence!==!1),v=n.length-j.length;return e.jsxs("div",{className:`bg-card border border-border rounded-lg mb-2 ${s.active?"":"promo-dim"}`,children:[e.jsxs("button",{onClick:t.onToggle,className:"w-full text-left px-4 py-3 flex items-center gap-4 promo-row rounded-lg",children:[t.open?e.jsx(Ot,{style:{width:"14px",height:"14px"},className:"text-muted-foreground flex-shrink-0"}):e.jsx(Rt,{style:{width:"14px",height:"14px"},className:"text-muted-foreground flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",style:{flex:"1 1 240px"},children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(wl,{tone:a.tone,title:a.blurb,children:a.label}),e.jsx("span",{className:"text-sm font-semibold text-foreground truncate",children:s.clientName})]}),e.jsxs("p",{className:"promo-tiny text-muted-foreground font-mono truncate",children:[s.captureAddress,s.lifecycleStage==="managed"?" · managed":"",s.active?"":" · inactive"]})]}),e.jsxs("div",{className:"flex flex-col items-start",style:{minWidth:118},children:[e.jsx("span",{className:"promo-label",children:"Last send"}),i?e.jsxs("span",{className:"text-xs text-foreground promo-tabular",title:(o==null?void 0:o.source)==="klaviyo"?"From Klaviyo's send log":"From the capture inbox",children:[Gd(i)," ",e.jsxs("span",{className:"text-muted-foreground",children:["· ",td(i)]}),(o==null?void 0:o.source)==="klaviyo"&&e.jsx("span",{className:"promo-tiny text-muted-foreground",style:{marginLeft:6},title:"From Klaviyo's send log",children:"via Klaviyo"})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"none"})]}),e.jsxs("div",{className:"flex flex-col items-start",style:{minWidth:104},children:[e.jsx("span",{className:"promo-label",children:"Rhythm"}),e.jsxs("span",{className:"text-xs text-foreground promo-tabular",children:[y||e.jsx("span",{className:"text-muted-foreground",children:"n/a"}),s.targetGapDays?e.jsxs("span",{className:"text-muted-foreground",children:[" · target ",s.targetGapDays,"d"]}):null]})]}),e.jsx(Ri,{label:"Links",status:(T=s.health)==null?void 0:T.links,title:"Do the links resolve? Worst of the last 5 marketing sends"}),e.jsx(Ri,{label:"Promise",status:(k=s.health)==null?void 0:k.misleading,title:"Do links land exactly where their text promised? Worst of the last 5"}),e.jsx(Ri,{label:"Spam",status:(w=s.health)==null?void 0:w.spam,title:"Inbox placement across the last 5"}),e.jsx(Ri,{label:"Auth",status:(I=s.health)==null?void 0:I.auth,title:"SPF / DKIM / DMARC across the last 5"}),e.jsx(VP,{mapping:s})]}),t.open&&e.jsxs("div",{className:"border-t border-border px-4 py-3 space-y-4",children:[r!=="on_track"&&r!=="never"&&e.jsxs("div",{className:"rounded-md p-3",style:{backgroundColor:xa[r].tone==="bad"?"rgba(225,29,72,0.06)":"rgba(217,119,6,0.06)"},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[e.jsxs("h4",{className:"text-xs font-semibold text-foreground",children:["Talking points for ",s.clientName]}),e.jsx("button",{onClick:async()=>{await t.onMarkHandled(),b(!0)},disabled:h,className:"promo-tiny promo-ghost promo-link",title:"Record that someone reached out about this quiet spell",children:h?"Marked as reached out":"Mark reached out"})]}),s.talkingPoints&&s.talkingPoints.length>0?e.jsx("ul",{className:"space-y-1",children:s.talkingPoints.map((A,E)=>e.jsx("li",{className:"text-sm text-foreground",children:A},E))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Talking points appear after the next cadence check."}),e.jsxs("p",{className:"promo-tiny text-muted-foreground mt-2",children:[(o==null?void 0:o.daysSinceLast)!=null?`${o.daysSinceLast} days since the last send`:"",(o==null?void 0:o.slowingThresholdDays)!=null?` · slowing after ${o.slowingThresholdDays}d`:"",(o==null?void 0:o.thresholdDays)!=null?` · quiet after ${o.thresholdDays}d`:""]})]}),r==="never"&&e.jsxs("div",{className:"rounded-md p-3 text-sm text-muted-foreground promo-note",children:[n.length>0?e.jsxs(e.Fragment,{children:["Only non-marketing mail has arrived at ",e.jsx("span",{className:"font-mono",children:s.captureAddress})," (",n.length," ",n.length===1?"message":"messages",": invoices, tests or notices). The address is probably on the wrong list."]}):e.jsxs(e.Fragment,{children:["Nothing has ever arrived at ",e.jsx("span",{className:"font-mono",children:s.captureAddress}),"."]}
411),s.klaviyo?s.klaviyo.sendCount30d>0?` Klaviyo shows ${s.klaviyo.sendCount30d} send${s.klaviyo.sendCount30d===1?"":"s"} in the last 30 days, so the address is not in their audience.`:" Klaviyo shows no sends in the last 30 days either.":n.length>0?"":" Check the address is subscribed to their list."]}),s.klaviyo&&e.jsxs("div",{children:[e.jsx("h4",{className:"promo-label font-semibold mb-1",children:"Klaviyo audience"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Store ",e.jsx("span",{className:"font-mono",children:s.klaviyo.shop}),s.klaviyo.accountName?e.jsxs(e.Fragment,{children:[" · Klaviyo account ",e.jsx("strong",{children:s.klaviyo.accountName})]}):null," · ",s.klaviyo.sendCount30d," send",s.klaviyo.sendCount30d===1?"":"s"," in 30 days",s.klaviyo.profileId?" · tracking profile exists":" · tracking profile not created yet"," · checked ",td(sd(s.klaviyo.checkedAt))||"never"]}),s.klaviyo.missingFrom.length>0&&e.jsx("ul",{className:"mt-1 promo-stack",children:s.klaviyo.missingFrom.map(A=>{var E;return e.jsxs("li",{className:"text-xs flex items-center gap-1.5",style:{color:"#b45309"},children:[e.jsx(Dt,{style:{width:"12px",height:"12px"}}),"Not in ",A.kind," â",A.name||A.id,"â",A.kind==="segment"?" (segments are rule-based; ask the client to include the address)":(E=s.klaviyo)!=null&&E.subscribeError?"":" (will be auto-subscribed on the next check)"]},A.id)})}),s.klaviyo.autoAdded.length>0&&e.jsx("ul",{className:"mt-1 promo-stack",children:s.klaviyo.autoAdded.map(A=>e.jsxs("li",{className:"text-xs flex items-center gap-1.5",style:{color:"#15803d"},children:[e.jsx(kt,{style:{width:"12px",height:"12px"}}),"Auto-subscribed to â",A.name||A.id,"â ",td(sd(A.at))]},A.id))}),s.klaviyo.subscribeError&&e.jsx("p",{className:"text-xs mt-1",style:{color:"#b45309"},children:s.klaviyo.subscribeError}),s.klaviyo.error&&e.jsx("p",{className:"text-xs mt-1",style:{color:"#be123c"},children:s.klaviyo.error})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"promo-label font-semibold mb-1",children:["Campaigns · ",j.length,v>0&&e.jsxs("span",{className:"font-normal",style:{textTransform:"none",letterSpacing:0},children:[" (+",v," not marketing)"]})]}),n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No captures yet."}):e.jsx("div",{className:"promo-stack",children:n.slice(0,12).map(A=>{const E=Nl(A.verdict);return e.jsxs("button",{onClick:()=>t.onOpenCampaign(A.id),className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded-md promo-row",children:[e.jsx("span",{className:"text-xs text-muted-foreground promo-tabular flex-shrink-0",style:{width:52},children:Gd(A.receivedAt)}),e.jsx("span",{className:`text-sm truncate flex-1 ${A.countsForCadence===!1?"text-muted-foreground":"text-foreground"}`,children:A.subject||"(no subject)"}),e.jsx(om,{kind:A.kind,countsForCadence:A.countsForCadence}),A.landedInSpam&&e.jsx(wl,{tone:"bad",title:"Landed in the Spam folder",children:"spam"}),e.jsx("span",{style:E.style,className:"promo-pill px-1.5 py-0.5 rounded flex-shrink-0",children:E.label})]},A.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 border-t border-border",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:["Target",e.jsx("input",{type:"number",min:1,max:120,value:p,placeholder:"learned",onChange:A=>c(A.target.value),onBlur:()=>{(s.targetGapDays?String(s.targetGapDays):"")!==p.trim()&&g()},onKeyDown:A=>{A.key==="Enter"&&A.target.blur()},className:"bg-background border border-border rounded-md px-2 py-1 text-xs text-foreground",style:{width:72},title:"We'd like a campaign at least every N days. Blank = learned rhythm only."}),"days ",u&&e.jsx(fe,{style:{width:"12px",height:"12px"},className:"animate-spin"})]}),e.jsxs("button",{onClick:t.onCheckNow,disabled:t.checking,className:"flex items-center gap-1 text-xs promo-ghost px-2 py-1 rounded-md border border-border",title:"Re-check cadence and Klaviyo for this client now",children:[t.checking?e.jsx(fe,{style:{width:"12px",height:"12px"},className:"animate-spin"}):e.jsx(ug,{style:{width:"12px",height:"12px"}}),"Check now"]}),e.jsxs("button",{onClick:f,className:"flex items-center gap-1 text-xs promo-ghost px-2 py-1 rounded-md border border-border",title:`Copy ${s.captureAddress}`,children:[d?e.jsx(kt,{style:{width:"12px",height:"12px",color:"#15803d"}}
411):e.jsx(Hr,{style:{width:"12px",height:"12px"}}),d?"Copied":"Copy address"]}),e.jsx("button",{onClick:t.onToggleLiveList,disabled:t.busy,className:"flex items-center gap-1 text-xs promo-ghost px-2 py-1 rounded-md border border-border",title:s.liveList?"Live list: real sends. Click to mark as a test list.":"Test list. Click to mark as a live list.",children:s.liveList?"live list":"test list"}),e.jsxs("button",{onClick:t.onToggleStage,disabled:t.busy,className:"flex items-center gap-1 text-xs promo-ghost px-2 py-1 rounded-md border border-border",title:s.lifecycleStage==="managed"?"We run this list (pre-send gate). Click to switch to monitoring.":"Client runs the campaigns. Click to switch to managed.",children:[s.lifecycleStage==="managed"?e.jsx(su,{style:{width:"12px",height:"12px"}}):e.jsx(Ew,{style:{width:"12px",height:"12px"}}),s.lifecycleStage==="managed"?"managed":"monitoring"]}),e.jsxs("a",{href:`https://mail.google.com/mail/u/0/#search/to%3A${encodeURIComponent(s.captureAddress)}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-xs promo-ghost px-2 py-1 rounded-md border border-border",title:"Open the capture mailbox search for this address",children:[e.jsx(Da,{style:{width:"12px",height:"12px"}})," mailbox"]}),e.jsxs("button",{onClick:t.onRemove,disabled:t.busy,className:"promo-push promo-ghost promo-danger flex items-center gap-1 text-xs px-2 py-1 rounded-md",title:"Deactivate this tag",children:[e.jsx(zs,{style:{width:"12px",height:"12px"}})," remove"]})]})]})]})}function GP({config:t,busy:s,onSetOwner:n,onSetRecipients:r,onAddTag:a}){const[o,i]=l.useState(null),[d,m]=l.useState(((t==null?void 0:t.alertRecipients)||[]).join(", ")),[p,c]=l.useState(!1),u=async()=>{i(null);try{await n()}catch(h){i((h==null?void 0:h.message)||"Could not set capture inbox")}},x=async()=>{const h=d.split(/[,\s]+/).map(b=>b.trim()).filter(Boolean);await r(h),c(!0),setTimeout(()=>c(!1),1500)};return e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mb-5 grid gap-4",style:{gridTemplateColumns:"repeat(auto-fit, minmax(260px, 1fr))"},children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ju,{style:{width:"16px",height:"16px"},className:"text-muted-foreground"}),e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:"Capture inbox"})]}),t!=null&&t.owner?e.jsxs("div",{className:"flex items-center gap-2 text-sm flex-wrap",children:[e.jsx(kt,{style:{width:"14px",height:"14px",color:"#15803d"}}),e.jsx("span",{className:"text-foreground font-mono text-xs",children:t.owner.gmailAddress}),e.jsx("button",{onClick:u,disabled:s,className:"text-xs promo-ghost promo-link",children:"Re-point to current login"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["No capture inbox set. Sign in ",e.jsx("strong",{children:"as the capture mailbox"}),t!=null&&t.captureDomain?e.jsxs(e.Fragment,{children:[" (on ",e.jsxs("span",{className:"font-mono",children:["@",t.captureDomain]}),")"]}):null,", connect its Gmail, then click below."]}),e.jsxs("button",{onClick:u,disabled:s,className:"flex items-center gap-1.5 bg-primary text-primary-foreground px-3 py-2 rounded-lg text-sm font-medium promo-ghost",children:[s&&e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"}),"Use this mailbox as the capture inbox"]})]}),o&&e.jsxs("p",{className:"flex items-start gap-1.5 text-xs text-destructive mt-2",children:[e.jsx(Dt,{style:{width:"13px",height:"13px"},className:"mt-0.5 flex-shrink-0"}),o]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Dn,{style:{width:"16px",height:"16px"},className:"text-muted-foreground"}),e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:"Who gets the âgone quietâ alert"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:d,onChange:h=>m(h.target.value),placeholder:"[email protected], [email protected]",className:"flex-1 bg-background border border-border rounded-md px-2 py-1.5 text-xs text-foreground font-mono"}),e.jsx("button",{onClick:x,disabled:s,className:"text-xs px-2 py-1.5 rounded-md border border-border text-foreground promo-row",children:p?"Saved":"Save"})]}),e.jsx("p",{className:"promo-tiny text-muted-foreground mt-1",children:"One bell per quiet spell, plus a talking-points card on the client row.
411Comma separated."})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ut,{style:{width:"16px",height:"16px"},className:"text-muted-foreground"}),e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:"Monitor another client"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Creates a tag address to subscribe to their list. If their store has a Klaviyo key, the address is added to their lists automatically."}),e.jsxs("button",{onClick:a,className:"flex items-center gap-1.5 bg-primary text-primary-foreground px-3 py-2 rounded-lg text-sm font-medium promo-row",children:[e.jsx(Ut,{style:{width:"16px",height:"16px"}}),"Add client tag"]})]})]})}function KP({optIn:t,onConfirm:s,onDismiss:n}){const[r,a]=l.useState(!1),o=t.confirmUrl||t.candidateUrls[0]||null,i=async()=>{o&&window.open(o,"_blank","noopener,noreferrer"),a(!0);try{await s()}finally{a(!1)}};return e.jsxs("div",{className:"bg-card border border-border rounded-lg mb-2 px-3 py-2.5 flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-foreground truncate",children:t.clientName}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[t.subject||"(no subject)",t.esp?` · ${t.esp}`:""]}),e.jsx("p",{className:"text-[11px] text-muted-foreground font-mono truncate",children:t.captureAddress})]}),e.jsxs("button",{onClick:i,disabled:r||!o,title:o?"Open the confirm link and mark confirmed":"No confirm link found â open the email manually",style:{backgroundColor:"#d97706",padding:"6px 12px"},className:"flex-shrink-0 flex items-center gap-1.5 text-xs font-medium text-white rounded-md hover:opacity-90 transition-opacity disabled:opacity-50",children:[r?e.jsx(fe,{style:{width:"13px",height:"13px"},className:"animate-spin"}):e.jsx(Da,{style:{width:"13px",height:"13px"}}),"Confirm"]}),e.jsx("button",{onClick:n,disabled:r,title:"Dismiss",className:"flex-shrink-0 p-1.5 rounded-md text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",children:e.jsx(mt,{style:{width:"15px",height:"15px"}})})]})}function nd(t){return(t||"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")}function QP({busy:t,existingTags:s,onClose:n,onSubmit:r}){const[a,o]=l.useState([]),[i,d]=l.useState(!0),[m,p]=l.useState(""),[c,u]=l.useState(""),[x,h]=l.useState(""),[b,f]=l.useState(!1),[g,y]=l.useState("monitoring"),[j,v]=l.useState(!0),[T,k]=l.useState(null);l.useEffect(()=>{let A=!0;return(async()=>{try{const C=((await re("auditClientSetup",{})).clients||[]).map(N=>({clientId:N.clientId,label:N.companyName||N.name||N.clientId}));A&&o(C)}catch(E){A&&k((E==null?void 0:E.message)||"Could not load clients")}finally{A&&d(!1)}})(),()=>{A=!1}},[]);const w=A=>{p(A);const E=a.find(N=>N.clientId===A),C=(E==null?void 0:E.label)||"";u(C),b||h(nd(C))},I=async()=>{k(null);const A=nd(x);if(!m){k("Pick a client");return}if(!A){k("Enter a tag");return}if(s.has(A)){k(`Tag "${A}" is already in use`);return}try{await r({tag:A,clientId:m,clientName:c,lifecycleStage:g,liveList:j})}catch(E){k((E==null?void 0:E.message)||"Could not save")}};return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50 px-4",onClick:n,children:e.jsxs("div",{className:"bg-card border border-border rounded-lg w-full max-w-sm p-4",onClick:A=>A.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:"Add client tag"}),e.jsx("button",{onClick:n,className:"text-muted-foreground hover:text-foreground",children:e.jsx(mt,{style:{width:"16px",height:"16px"}})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"Client"}),e.jsxs("select",{value:m,onChange:A=>w(A.target.value),disabled:i,className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground",children:[e.jsx("option",{value:"",children:i?"Loading clientsâ¦"
411:"Select a clientâ¦"}),a.map(A=>e.jsx("option",{value:A.clientId,children:A.label},A.clientId))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"Capture tag"}),e.jsx("input",{type:"text",value:x,placeholder:"acme",onChange:A=>{h(A.target.value),f(!0)},className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground font-mono"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Subscribe ",e.jsxs("span",{className:"font-mono",children:[nd(x)||"tag","@campaigns.sunbowl.ca"]})," to their list."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"Lifecycle"}),e.jsxs("select",{value:g,onChange:A=>y(A.target.value),className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground",children:[e.jsx("option",{value:"monitoring",children:"Monitoring â client runs the campaigns"}),e.jsx("option",{value:"managed",children:"Managed â we run them (pre-send gate)"})]})]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm text-foreground",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:A=>v(A.target.checked),className:"mt-0.5"}),e.jsxs("span",{children:["Live list",e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Real sends â minimize link fetching so we don't inflate the client's click stats."})]})]})]}),T&&e.jsx("p",{className:"text-xs text-destructive mt-3",children:T}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx("button",{onClick:n,className:"flex-1 px-3 py-2 rounded-md text-sm border border-border text-muted-foreground hover:text-foreground",children:"Cancel"}),e.jsxs("button",{onClick:I,disabled:t,className:"flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium bg-primary text-primary-foreground hover:opacity-90 disabled:opacity-50",children:[t&&e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"}),"Add tag"]})]})]})})}function JP(t){switch(t){case"pass":return e.jsx(kt,{style:{width:"15px",height:"15px",color:"#15803d"}});case"warn":return e.jsx(Dt,{style:{width:"15px",height:"15px",color:"#b45309"}});case"fail":return e.jsx(mt,{style:{width:"15px",height:"15px",color:"#b91c1c"}});default:return e.jsx(su,{style:{width:"15px",height:"15px"},className:"text-muted-foreground"})}}function ZP({id:t,onClose:s,onReanalyzed:n}){const[r,a]=l.useState(null),[o,i]=l.useState(!0),[d,m]=l.useState(!1),[p,c]=l.useState(null),[u,x]=l.useState(!0),[h,b]=l.useState(null),f=l.useRef(null),g=l.useRef([]),y=l.useRef(null),j=async()=>{i(!0);try{const E=await re("getPromoCampaign",{id:t});a(E.campaign)}finally{i(!1)}},v=async()=>{x(!0);try{const E=await re("getPromoCampaignHtml",{id:t});c((E==null?void 0:E.html)??null)}catch{c(null)}finally{x(!1)}};l.useEffect(()=>{j(),v()},[t]);const T=async()=>{m(!0);try{await re("reanalyzePromoCampaign",{id:t}),await j(),n()}finally{m(!1)}},k=()=>{var S;const E=(S=f.current)==null?void 0:S.contentDocument;if(!E||!r){g.current=[];return}const C=Array.from(E.querySelectorAll("a[href]")),N=new Set;g.current=r.links.map(O=>{const R=(O.rawHref||"").trim();if(!R)return null;for(let z=0;z<C.length;z++)if(!N.has(z)&&(C[z].getAttribute("href")||"").trim()===R)return N.add(z),C[z];return null})};l.useEffect(()=>{k()},[p,r]);const w=(E,C)=>{const N=g.current[E];N&&(C?(N.style.outline="2px solid #2563eb",N.style.outlineOffset="2px",N.style.backgroundColor="rgba(37,99,235,0.18)",N.scrollIntoView({block:"center",behavior:"smooth"})):(N.style.outline="",N.style.outlineOffset="",N.style.backgroundColor=""))},I=E=>{const C=y.current;C!==null&&C!==E&&w(C,!1),E!==null&&w(E,!0),y.current=E,b(E)},A=Nl(r?r.verdict:"pending");return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50 px-4",onClick:s,children:e.jsxs("div",{className:"bg-card border border-border rounded-lg w-full flex flex-col",style:{maxWidth:"1120px",maxHeight:"88vh"},onClick:E=>E.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 p-4 border-b border-border",children:[e.jsx("h3",{className:"font-semibold text-foreground flex-1 min-w-0",children:(r==null?void 0:r.subject)||"Campaign"}),e.jsx("span",{style:A.style,className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded flex-shrink-0",children:A.label}),e.jsx("button",{onClick:s,className:"text-muted-foreground hover:text-foreground flex-shrink-0",children:e.jsx(mt,{style:{width:"16px",height:"16px"}})})]}),o||!r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{style:{width:"22px",height:"22px"},className:"animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"flex flex-wrap",style:{flex:1,minHeight:0},children:[e.jsxs("div",{className:"p-4",style:{flex:"1 1 360px",overflowY:"auto",maxHeight:"100%"},children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-3 flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{children:[r.clientName,r.esp?` · ${r.esp}`:""," · ",r.mode,r.liveList?" · live list":""]}),e.jsx(om,{kind:r.kind,countsForCadence:r.countsForCadence})]}),e.jsxs("div",{className:"space-y-2 mb-4",children:[r.checks.map(E=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"flex-shrink-0 mt-0.5",children:JP(E.status)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm text-foreground",children:E.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:E.detail})]})]},E.id)),r.checks.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Not analyzed yet."})]}),r.links.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsxs("h4",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1.5",children:["Links · ",r.links.length,e.jsx("span",{className:"ml-1 font-normal normal-case tracking-normal",children:"â hover to find in email"})]}),e.jsx("div",{className:"space-y-1",onMouseLeave:()=>I(null),children:r.links.map((E,C)=>e.jsx(XP,{link:E,active:h===C,locatable:!!g.current[C],onHover:()=>I(C)},C))})]}),e.jsxs("button",{onClick:T,disabled:d,className:"w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium border border-border text-foreground hover:bg-muted/40 disabled:opacity-50",children:[d?e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"}):e.jsx(yt,{style:{width:"14px",height:"14px"}}),"Re-run checks"]})]}),e.jsxs("div",{className:"border-t md:border-t-0 border-l border-border",style:{flex:"2
4111 460px",minHeight:"460px",display:"flex",flexDirection:"column"},children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-border text-xs text-muted-foreground",children:[e.jsx(Tn,{style:{width:"13px",height:"13px"}}),"Email preview"]}),e.jsx("div",{style:{flex:1,minHeight:0,position:"relative",background:"#fff"},children:u?e.jsx("div",{className:"flex items-center justify-center",style:{height:"100%"},children:e.jsx(fe,{style:{width:"20px",height:"20px"},className:"animate-spin text-muted-foreground"})}):p?e.jsx("iframe",{ref:f,title:"Email preview",sandbox:"allow-same-origin",srcDoc:p,onLoad:k,style:{width:"100%",height:"100%",border:"none"}}):e.jsx("div",{className:"flex items-center justify-center text-sm text-muted-foreground",style:{height:"100%"},children:"No HTML captured for this campaign."})})]})]})]})})}function XP({link:t,active:s,locatable:n,onHover:r}){const a=t.httpStatus==null?"#a1a1aa":t.httpStatus===429?"#b45309":t.httpStatus>=400?"#b91c1c":"#15803d",o=t.intent,i=t.resolvedUrl||t.rawHref,d=/^https?:/i.test(i);return e.jsxs("div",{className:"flex items-center gap-2 text-xs rounded px-1 -mx-1",style:{cursor:n?"pointer":"default",backgroundColor:s?"rgba(37,99,235,0.10)":"transparent"},onMouseEnter:r,children:[e.jsx("span",{className:"text-foreground truncate",style:{maxWidth:"40%"},children:t.anchorText||"(no text)"}),d?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",onClick:m=>{t.kind==="unsubscribe"&&!window.confirm("This is the UNSUBSCRIBE link â opening it may remove the capture address from the client's list. Open anyway?")&&m.preventDefault()},title:`Open in a new tab: ${i}`,className:"font-mono truncate flex-1",style:{color:t.kind==="unsubscribe"?"#b91c1c":"#2563eb",textDecoration:"underline"},children:i}):e.jsx("span",{className:"text-muted-foreground font-mono truncate flex-1",children:i}),t.kind==="unsubscribe"&&e.jsx("span",{className:"text-[10px] text-muted-foreground flex-shrink-0",children:"unsub"}),t.pageTitle&&e.jsxs("span",{className:"text-[10px] text-muted-foreground truncate flex-shrink-0",style:{maxWidth:"22%"},title:`Destination page: ${t.pageTitle}`,children:["â ",t.pageTitle]}),o&&e.jsx("span",{className:"text-[10px] flex-shrink-0 font-medium",title:o.reason,style:{color:o.verdict==="mismatch"?"#b91c1c":o.verdict==="partial"?"#b45309":o.verdict==="exact"||o.verdict==="match"?"#15803d":"#a1a1aa"},children:o.verdict==="match"?"exact":o.verdict}),t.fetched?e.jsx("span",{className:"font-mono flex-shrink-0",style:{color:a},children:t.httpStatus??"ERR"}):e.jsx("span",{className:"text-[10px] text-muted-foreground flex-shrink-0",children:"â"})]})}const e8=["quiet","slowing","never","on_track"];function t8({onBack:t,onLogoClick:s}){const{config:n,campaigns:r,optIns:a,loading:o,error:i,busy:d,ingesting:m,checkingCadence:p,loadData:c,setOwner:u,upsertMapping:x,setMappingStage:h,setMappingLiveList:b,removeMapping:f,runIngest:g,runCadenceCheck:y,setCadenceTarget:j,setAlertRecipients:v,markOutreachHandled:T,confirmOptIn:k,dismissOptIn:w}=HP(),[I,A]=l.useState(!1),[E,C]=l.useState(!1),[N,S]=l.useState(null),[O,R]=l.useState(null),[z,D]=l.useState(null),[L,$]=l.useState(null),[q,P]=l.useState(null),[U,V]=l.useState(!1),M=(n==null?void 0:n.mappings)||[],F=l.useMemo(()=>[...M].sort((H,Z)=>{var X,se;const Q=xa[fo(H.cadence)].rank,K=xa[fo(Z.cadence)].rank;return Q!==K?Q-K:(((X=Z.cadence)==null?void 0:X.daysSinceLast)??0)-(((se=H.cadence)==null?void 0:se.daysSinceLast)??0)}),[M]),W=l.useMemo(()=>{const H={quiet:0,slowing:0,never:0,on_track:0};for(const Z of M)Z.active&&H[fo(Z.cadence)]++;return H},[M]),_=l.useMemo(()=>{const H=new Map;for(const Z of r){const Q=H.get(Z.clientId)||[];Q.push(Z),H.set(Z.clientId,Q)}return H},[r]),G=L?F.filter(H=>fo(H.cadence)===L):F,B=!o&&!!n&&!n.owner,Y=async()=>{S(null);const H=await g();H&&S(`Ingest: ${H.stored} stored, ${H.processed} scanned`+(H.skippedNoMapping?`, ${H.skippedNoMapping} unmapped`:"")+(H.errors?`, ${H.errors} errors`:""))},J=async H=>{S(null),H&&P(H);try{const Z=await y(H);Z&&S(`${H?`${H}: `:""}${Z.checked} checked · ${Z.onTrack} on track · ${Z.slowing} slowing · ${Z.quiet} quiet`+(Z.klaviyoChecked?` · Klaviyo checked for ${Z.klaviyoChecked}`:"")+(Z.klaviyoAutoAdded?` · auto-subscribed to ${Z.klaviyoAutoAdded} list${Z.klaviyoAutoAdded===1?"":"s"}
411`:"")+(Z.newlyQuiet.length?` · newly quiet: ${Z.newlyQuiet.join(", ")}`:"")+(Z.recovered.length?` · back on track: ${Z.recovered.join(", ")}`:"")+(Z.errors?` · ${Z.errors} errors`:""))}finally{P(null)}};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-5 flex-wrap",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Promo Email Review"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Who is still sending, whether their links keep their promise, and where they land."})]}),e.jsxs("button",{onClick:()=>J(),disabled:p,title:"Re-check every client's rhythm and Klaviyo audience now (runs daily at 9am)",className:"flex items-center gap-1.5 promo-ghost px-3 py-2 rounded-lg text-sm",children:[p&&!q?e.jsx(fe,{style:{width:"16px",height:"16px"},className:"animate-spin"}):e.jsx(ug,{style:{width:"16px",height:"16px"}}),"Check cadence"]}),e.jsxs("button",{onClick:Y,disabled:m||!(n!=null&&n.owner),title:n!=null&&n.owner?"Pull new campaigns from the capture inbox now":"Set the capture inbox first",className:"flex items-center gap-1.5 promo-ghost px-3 py-2 rounded-lg text-sm",children:[m?e.jsx(fe,{style:{width:"16px",height:"16px"},className:"animate-spin"}):e.jsx(In,{style:{width:"16px",height:"16px"}}),"Run ingest"]}),e.jsxs("button",{onClick:()=>A(H=>!H),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm ${I||B?"text-foreground":"promo-ghost"}`,title:"Capture inbox, alert recipients, add a client",children:[e.jsx(bg,{style:{width:"16px",height:"16px"}}),"Setup"]}),e.jsxs("button",{onClick:c,disabled:o,className:"flex items-center gap-1.5 promo-ghost px-3 py-2 rounded-lg text-sm",children:[e.jsx(yt,{style:{width:"16px",height:"16px"},className:o?"animate-spin":""}),"Refresh"]})]}),N&&e.jsx("div",{className:"promo-note border border-border rounded-lg p-2.5 mb-4 text-xs text-muted-foreground",children:N}),i&&e.jsx("div",{className:"promo-error border rounded-lg p-3 mb-4 text-sm text-destructive",children:i}),(I||B)&&e.jsx(GP,{config:n,busy:d,onSetOwner:u,onSetRecipients:v,onAddTag:()=>C(!0)}),!o&&a.length>0&&e.jsxs("div",{className:"border rounded-lg p-4 mb-5",style:{backgroundColor:"rgba(245,158,11,0.06)",borderColor:"rgba(245,158,11,0.35)"},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(eN,{style:{width:"16px",height:"16px",color:"#d97706"}}),e.jsxs("h2",{className:"text-sm font-semibold text-foreground",children:["Confirm subscriptions",e.jsxs("span",{className:"text-muted-foreground font-normal",children:[" · ",a.length]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"These lists need a double opt-in. Click to confirm, then the client's campaigns will flow in."}),a.map(H=>e.jsx(KP,{optIn:H,onConfirm:()=>k(H.id),onDismiss:()=>w(H.id)},H.id))]}),!o&&M.length>0&&e.jsx("div",{className:"grid gap-2 mb-4",style:{gridTemplateColumns:"repeat(4, minmax(0, 1fr))"},children:e8.map(H=>{const Z=xa[H],Q=L===H;return e.jsxs("button",{onClick:()=>$(Q?null:H),className:"text-left rounded-lg border px-3 py-2 transition-colors",style:{borderColor:Q?Ds[Z.tone].fg:"var(--border)",backgroundColor:W[H]>0?Ds[Z.tone].bg:"var(--card)"},title:Z.blurb,children:[e.jsx("div",{className:"promo-num",style:{color:W[H]>0?Ds[Z.tone].fg:"var(--foreground)"},children:W[H]}),e.jsx("div",{className:"promo-label",children:Z.label})]},H)})}),o&&e.jsx("div",{className:"space-y-2",children:[0,1,2,3].map(H=>e.jsx("div",{className:"promo-skeleton border border-border rounded-lg",style:{height:58}},H))}),!o&&M.length===0&&e.jsx("div",{className:"text-center py-6 text-muted-foreground text-sm",children:"No clients monitored yet. Open Setup and add a client tag."}),!o&&G.map(H=>e.jsx(YP,{mapping:H,campaigns:_.get(H.clientId)||[],open:z===H.tag,busy:d,checking:q===H.tag,onToggle:()=>D(z===H.tag?null:H.tag),onOpenCampaign:Z=>R(Z),onCheckNow:()=>J(H.tag),onSetTarget:Z=>j(H.tag,Z),onToggleStage:()=>h(H.tag,H.lifecycleStage==="managed"?"monitoring":"managed"),onToggleLiveList:()=>b(H.tag,!H.liveList),onRemove:()=>f(H.tag,!1),onMarkHandled:()=>T(H.tag)},H.tag)),!o&&L&&G.length===0&&e.jsxs("div",{className:"text-center py-6 text-muted-foreground text-sm",children:["No clients are ",xa[L].label.toLowerCase(),"."]}),!o&&r.length>0&&e.jsxs("div",{className:"mt-6",children:[e.jsxs("button",{onClick:()=>V(H=>!H),className:"flex items-center gap-1.5 text-sm font-semibold text-foreground mb-2",children:[U?e.jsx(Ot,{style:{width:"14px",height:"14px"}}):e.jsx(Rt,{style:{width:"14px",height:"14px"}}),"All recent captures",e.jsxs("span",{className:"text-muted-foreground font-normal",children:[" · ",r.length]})]}),U&&r.map(H=>{const Z=Nl(H.verdict);return e.jsxs("button",{onClick:()=>R(H.id),className:"w-full text-left bg-card border border-border rounded-lg mb-2 px-3 py-2 flex items-center gap-3 promo-row",children:[e.jsx("span",{className:"text-xs text-muted-foreground promo-tabular flex-shrink-0",style:{width:52},children:Gd(H.receivedAt)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm text-foreground truncate block",children:H.subject||"(no subject)"}),e.jsxs("span",{className:"text-xs text-muted-foreground truncate block",children:[H.clientName,H.esp?` · ${H.esp}`:""]})]}),e.jsx(om,{kind:H.kind,countsForCadence:H.countsForCadence}),H.landedInSpam&&e.jsx(wl,{tone:"bad",children:"spam"}),e.jsx("span",{style:Z.style,className:"promo-pill px-1.5 py-0.5 rounded flex-shrink-0",children:Z.label})]},H.id)})]})]}),O&&e.jsx(ZP,{id:O,onClose:()=>R(null),onReanalyzed:()=>c()}),E&&e.jsx(QP,{busy:d,existingTags:new Set(M.map(H=>H.tag)),onClose:()=>C(!1),onSubmit:async H=>{await x(H),C(!1)}})]})}function Vn(t,s){return`${t}_${s}`}function s8(){const[t,s]=l.useState([]),[n,r]=l.useState(null),[a,o]=l.useState(!0),[i,d]=l.useState(null),[m,p]=l.useState(null),c=l.useRef(!0),u=l.useRef(null);l.useEffect(()=>()=>{c.current=!1},[]);const x=l.useCallback(async(v,T)=>{T!=null&&T.silent||o(!0),d(null);try{const k=v??u.current??void 0,w=await re("listReportRecommendations",{sendMonth:k});c.current&&(u.current=(w==null?void 0:w.sendMonth)??k??null,r(u.current),s((w==null?void 0:w.items)||[]))}catch(k){c.current&&d((k==null?void 0:k.message)||"Failed to load recommendations")}finally{c.current&&!(T!=null&&T.silent)&&o(!1)}},[]),h=l.useCallback(async(v,T,k)=>{p(v),d(null);try{const w=await T();return await x(void 0,{silent:!0}),w}catch(w){throw c.current&&d((w==null?void 0:w.message)||k),w}finally{c.current&&p(null)}},[x]),b=l.useCallback(async v=>{await h(Vn(v.shop,v.sendMonth),()=>re("updateReportRecommendation",v),"Could not save summary")}
411,[h]),f=l.useCallback(async v=>h(Vn(v.shop,v.sendMonth),()=>re("approveReportRecommendation",v),"Could not approve"),[h]),g=l.useCallback(async v=>{await h(Vn(v.shop,v.sendMonth),()=>re("rejectReportRecommendation",v),"Could not reject")},[h]),y=l.useCallback(async v=>{await h(Vn(v.shop,v.sendMonth),()=>re("regenerateReportRecommendation",v),"Could not regenerate")},[h]),j=l.useCallback(async v=>{const T=v.sendMonth??u.current??void 0;await h(Vn(v.shop,T??""),()=>re("generateShopRecommendation",{shop:v.shop,sendMonth:T}),"Could not generate recommendation")},[h]);return l.useEffect(()=>{x()},[x]),{items:t,sendMonth:n,loading:a,error:i,busyId:m,loadData:x,updateText:b,approve:f,reject:g,regenerate:y,generateForShop:j}}function n8(t,s,n=0){const[r,a]=l.useState(null),[o,i]=l.useState(null),[d,m]=l.useState(null),[p,c]=l.useState(!1),[u,x]=l.useState(null),[h,b]=l.useState(0),f=l.useRef(!0),g=l.useRef(0);l.useEffect(()=>()=>{f.current=!1},[]),l.useEffect(()=>{if(!t||!s){a(null),i(null);return}const j=++g.current;c(!0),x(null),re("getReportRecommendationPreview",{shop:t,sendMonth:s}).then(v=>{!f.current||j!==g.current||(a((v==null?void 0:v.html)??null),i((v==null?void 0:v.reason)??null),m((v==null?void 0:v.sourceType)??null))}).catch(v=>{!f.current||j!==g.current||(a(null),x((v==null?void 0:v.message)||"Could not load the report preview"))}).finally(()=>{f.current&&j===g.current&&c(!1)})},[t,s,n,h]);const y=l.useCallback(()=>b(j=>j+1),[]);return{html:r,reason:o,sourceType:d,loading:p,error:u,reload:y}}const r8=232,a8=460;function sh(t,s){const[n,r]=t.split("-").map(o=>parseInt(o,10)),a=new Date(Date.UTC(n,r-1+s,1));return`${a.getUTCFullYear()}-${String(a.getUTCMonth()+1).padStart(2,"0")}`}function o8(t){const s=t.split("-");if(s.length!==2)return t;const n=parseInt(s[0],10),r=parseInt(s[1],10);if(isNaN(n)||isNaN(r)||r<1||r>12)return t;try{return new Date(Date.UTC(n,r-1,1)).toLocaleDateString(void 0,{month:"long",year:"numeric",timeZone:"UTC"})}catch{return t}}function i8({onBack:t,onLogoClick:s}){const{items:n,sendMonth:r,loading:a,error:o,busyId:i,loadData:d,updateText:m,approve:p,reject:c,regenerate:u,generateForShop:x}=s8(),[h,b]=l.useState(null),[f,g]=l.useState(0);l.useEffect(()=>{if(n.length===0){b(null);return}b(w=>w&&n.some(I=>I.shop===w)?w:n[0].shop)},[n]);const y=l.useMemo(()=>n.find(w=>w.shop===h)??null,[n,h]),j=n8((y==null?void 0:y.shop)??null,(y==null?void 0:y.sendMonth)??null,f),v=async()=>{const w=window.prompt("Generate a draft for which shop domain? (e.g. acme.mysh
411opify.com)");w&&await x({shop:w.trim()})},T=l.useCallback(()=>g(w=>w+1),[]),k=n.filter(w=>w.status==="draft").length;return e.jsxs("div",{className:"bg-background",style:{height:"100dvh",display:"flex",flexDirection:"column"},children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"border-b border-border",style:{display:"flex",alignItems:"center",gap:"12px",padding:"12px 20px",flexShrink:0},children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("h1",{className:"text-lg font-bold text-foreground",children:"Report Recommendations"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:k>0?`${k} awaiting approval`:"Nothing awaiting approval"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginLeft:"16px"},children:[e.jsx("button",{onClick:()=>r&&d(sh(r,-1)),disabled:a||!r,title:"Previous month",className:"text-muted-foreground hover:text-foreground disabled:opacity-40",style:{fontSize:"20px",lineHeight:1,padding:"0 6px"},children:"â¹"}),e.jsx("span",{className:"text-sm font-semibold text-foreground",style:{minWidth:"130px",textAlign:"center"},children:r?o8(r):"â"}),e.jsx("button",{onClick:()=>r&&d(sh(r,1)),disabled:a||!r,title:"Next month",className:"text-muted-foreground hover:text-foreground disabled:opacity-40",style:{fontSize:"20px",lineHeight:1,padding:"0 6px"},children:"âº"})]}),e.jsx("div",{style:{flex:1}}),e.jsxs("button",{onClick:v,className:"flex items-center gap-1.5 bg-primary text-primary-foreground px-3 py-2 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity",children:[e.jsx(Ut,{style:{width:"16px",height:"16px"}}),"Generate for shopâ¦"]}),e.jsxs("button",{onClick:()=>d(),disabled:a,className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground px-3 py-2 rounded-lg text-sm transition-colors disabled:opacity-40",children:[e.jsx(yt,{style:{width:"16px",height:"16px"},className:a?"animate-spin":""}),"Refresh"]})]}),o&&e.jsx("div",{className:"bg-destructive/10 border-b border-destructive/20 text-sm text-destructive",style:{padding:"10px 20px",flexShrink:0},children:o}),e.jsxs("div",{style:{flex:1,minHeight:0,display:"flex"},children:[e.jsxs("aside",{className:"border-r border-border",style:{width:`${r8}px`,flexShrink:0,overflowY:"auto"},children:[a&&n.length===0&&e.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"32px 0"},children:e.jsx(fe,{style:{width:"20px",height:"20px"},className:"animate-spin text-muted-foreground"})}),n.map(w=>e.jsx(c8,{item:w,active:w.shop===h,busy:i===Vn(w.shop,w.sendMonth),onSelect:()=>b(w.shop)},Vn(w.shop,w.sendMonth))),!a&&n.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",style:{padding:"20px 14px",lineHeight:1.6},children:"No drafts yet â they generate 3 days before month-end."})]}),e.jsx("section",{className:"border-r border-border",style:{width:`${a8}px`,flexShrink:0,overflowY:"auto",padding:"18px"},children:y?e.jsx(d8,{item:y,busy:i===Vn(y.shop,y.sendMonth),onSave:async w=>{await m({shop:y.shop,sendMonth:y.sendMonth,summaryText:w}),T()},onApprove:async()=>{await p({shop:y.shop,sendMonth:y.sendMonth}),T()},onReject:async()=>{await c({shop:y.shop,sendMonth:y.sendMonth}),T()},onRegenerate:async()=>{await u({shop:y.shop,sendMonth:y.sendMonth}),T()}},Vn(y.shop,y.sendMonth)):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pick a shop to review its recommendation."})}),e.jsxs("section",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column"},children:[e.jsxs("div",{className:"border-b border-border",style:{display:"flex",alignItems:"center",gap:"10px",padding:"8px 14px",flexShrink:0},children:[e.jsx("span",{className:"text-xs font-semibold text-foreground",children:"Report preview"}),j.sourceType&&j.html&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:j.sourceType==="preview"?"from the month-end preview run":`from the ${j.sourceType} run`}),e.jsx("div",{style:{flex:1}}),j.loading&&e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin text-muted-foreground"}
411),e.jsx("button",{onClick:j.reload,disabled:j.loading||!y,className:"text-xs text-muted-foreground hover:text-foreground disabled:opacity-40",children:"Refresh"})]}),e.jsx("div",{style:{flex:1,minHeight:0,background:"#f5f5f5"},children:j.html?e.jsx("iframe",{title:"Monthly report preview",srcDoc:j.html,sandbox:"",style:{width:"100%",height:"100%",border:"none",display:"block"}}):e.jsx("div",{style:{padding:"28px 22px"},children:e.jsx("p",{className:"text-sm text-muted-foreground",style:{lineHeight:1.6},children:j.error||j.reason||(j.loading?"Loading the reportâ¦":"No report to preview.")})})})]})]})]})}function $y(t){switch(t){case"approved":return{label:"Approved",cls:"bg-emerald-600/10 text-emerald-700"};case"rejected":return{label:"Rejected",cls:"bg-rose-600/10 text-rose-700"};default:return{label:"Draft",cls:"bg-amber-600/10 text-amber-700"}}}function l8(t){const{audio:s,status:n}=t;return s.status==="error"?{label:"audio error",cls:"bg-rose-600/10 text-rose-700"}:s.status==="ready"?n!=="approved"?{label:"audio stale",cls:"bg-amber-600/10 text-amber-700"}:{label:"audio ready",cls:"bg-emerald-600/10 text-emerald-700"}:{label:"no audio",cls:"bg-muted text-muted-foreground"}}function c8({item:t,active:s,busy:n,onSelect:r}){const a=$y(t.status),o=t.status==="approved"?"#059669":t.status==="rejected"?"#e11d48":"#d97706";return e.jsxs("button",{onClick:r,className:"border-b border-border hover:bg-muted/40 transition-colors",style:{width:"100%",textAlign:"left",padding:"10px 12px",display:"flex",alignItems:"center",gap:"8px",background:s?"var(--muted)":"transparent",borderLeft:s?"3px solid var(--primary)":"3px solid transparent"},children:[e.jsx("span",{style:{width:"7px",height:"7px",borderRadius:"50%",background:o,flexShrink:0},title:a.label}),e.jsx("span",{className:"text-sm text-foreground truncate",style:{flex:1,minWidth:0},children:t.shopName||t.shop.replace(".myshopify.com","")}),n&&e.jsx(fe,{style:{width:"13px",height:"13px"},className:"animate-spin text-muted-foreground"})]})}function d8({item:t,busy:s,onSave:n,onApprove:r,onReject:a,onRegenerate:o}){const[i,d]=l.useState(t.summaryText),[m,p]=l.useState(null);l.useEffect(()=>{d(t.summaryText)},[t.summaryText]);const c=i.trim()!==t.summaryText.trim(),u=$y(t.status),x=l8(t),h=t.status==="approved"&&t.audio.status==="error",b=i.trim()?i.trim().split(/\s+/).length:0,f=async()=>{window.confirm("Regenerate this summary from scratch? Your edits and any approval will be discarded.")&&await o()};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground truncate flex-1",children:t.shopName||t.shop}),e.jsx("span",{className:`text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded flex-shrink-0 ${u.cls}`,children:u.label}),e.jsx("span",{className:`text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded flex-shrink-0 ${x.cls}`,children:x.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mb-3",children:t.shop}),e.jsx("textarea",{value:i,onChange:g=>d(g.target.value),disabled:s,className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground",style:{minHeight:"260px",resize:"vertical",lineHeight:1.6}}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 mb-3",children:[e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[b," words · ",i.length," chars"]}),e.jsxs("button",{onClick:()=>n(i),disabled:s||!c,className:"ml-auto flex items-center gap-1.5 bg-primary text-primary-foreground px-3 py-1.5 rounded-md text-sm font-medium hover:opacity-90 transition-opacity disabled:opacity-50",children:[s?e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"}):e.jsx(kt,{style:{width:"14px",height:"14px"}}),"Save"]})]}),c&&e.jsx("p",{className:"text-[11px] text-muted-foreground mb-3",children:"Unsaved edits â the preview still shows the saved text."}),t.audio.status==="ready"&&t.audio.publicUrl&&e.jsxs("div",{className:"mb-3",children:[e.jsx("audio",{controls:!0,src:t.audio.publicUrl,className:"w-full mb-2",style:{height:"36px"}}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("a",{href:t.audio.publicUrl,target:"_blank",rel:"noreferrer",className:"text-xs text-primary",style:{textDecoration:"underline"},children:"Open audio â"}),e.jsx("button",{type:"button",onClick:()=>{var y;const g=t.audio.publicUrl;g&&((y=navigator.clipboard)==null||y.writeText(g),p("link"),setTimeout(()=>p(null),1500))},className:"text-xs text-muted-foreground hover:text-foreground",children:m==="link"?"Copied!":"Copy link"}),e.jsx("button",{type:"button",onClick:()=>{var y;const g=t.audio.publicUrl;g&&((y=navigator.clipboard)==null||y.writeText(`For a laugh, try the experimental AI audio podcast of this report (presented by Sunbowl's AI assistant on Jody's behalf): 412${g}`),p("blurb"),setTimeout(()=>p(null),1500))},className:"text-xs text-muted-foreground hover:text-foreground",title:"Copies the framing text + link, ready to paste into a manual email",children:m==="blurb"?"Copied!":"Copy blurb"})]})]}),t.audio.status==="error"&&t.audio.error&&e.jsxs("p",{className:"text-xs text-destructive mb-3",children:["Audio: ",t.audio.error]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:r,disabled:s,className:"flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium text-white hover:opacity-90 transition-opacity disabled:opacity-50",style:{backgroundColor:"#059669"},children:s?e.jsxs(e.Fragment,{children:[e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"})," Generating audioâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{style:{width:"14px",height:"14px"}})," Approve"]})}),e.jsxs("button",{onClick:a,disabled:s,className:"flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium border border-border text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50",children:[e.jsx(mt,{style:{width:"14px",height:"14px"}}),"Reject"]}),e.jsxs("button",{onClick:f,disabled:s,className:"flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium border border-border text-foreground hover:bg-muted/40 transition-colors disabled:opacity-50",children:[e.jsx(yt,{style:{width:"14px",height:"14px"}}),"Regenerate"]}),h&&e.jsxs("button",{onClick:r,disabled:s,className:"flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium border border-border text-foreground hover:bg-muted/40 transition-colors disabled:opacity-50",children:[e.jsx(gg,{style:{width:"14px",height:"14px"}}),"Retry audio"]})]})]})}function u8(){const[t,s]=l.useState([]),[n,r]=l.useState(!0),[a,o]=l.useState(null),[i,d]=l.useState(null),m=l.useRef(!0);l.useEffect(()=>()=>{m.current=!1},[]);const p=l.useCallback(async()=>{r(!0),o(null);try{const j=await re("listTicketJobReports",{});m.current&&s((j==null?void 0:j.items)||[])}catch(j){m.current&&o((j==null?void 0:j.message)||"Failed to load job reports")}finally{m.current&&r(!1)}},[]),c=l.useCallback(async(j,v,T)=>{d(j),o(null);try{const k=await v();return await p(),k}catch(k){return m.current&&o((k==null?void 0:k.message)||T),null}finally{m.current&&d(null)}}
412,[p]),u=l.useCallback(async(j,v)=>{await c(j,()=>re("updateTicketJobReport",{ticketId:j,transcript:v}),"Could not save transcript")},[c]),x=l.useCallback(async(j,v)=>{await c(j,()=>re("updateJobReportTicketFields",{ticketId:j,...v}),"Could not save ticket fields")},[c]),h=l.useCallback(async j=>{await c(j,()=>re("regenerateTicketJobReportTranscript",{ticketId:j}),"Could not regenerate transcript")},[c]),b=l.useCallback(async j=>{await c(j,()=>re("regenerateTicketJobReportMedia",{ticketId:j}),"Could not regenerate media")},[c]),f=l.useCallback(async j=>c(j,()=>re("approveTicketJobReport",{ticketId:j}),"Could not approve"),[c]),g=l.useCallback(async j=>{await c(j,()=>re("rejectTicketJobReport",{ticketId:j}),"Could not reject")},[c]),y=l.useCallback(async(j,v)=>{const T=v?/\.(mp4|webm|mov)(\?|$)/i.test(v):!1;await c(j,()=>re("runTicketJobReport",v?{ticketId:j,...T?{videoUrl:v}:{gifUrl:v}}:{ticketId:j}),"Could not run the job report pipeline")},[c]);return l.useEffect(()=>{p()},[p]),{items:t,loading:n,error:a,busyId:i,loadData:p,saveTranscript:u,saveTicketFields:x,regenerateTranscript:h,regenerateMedia:b,approve:f,reject:g,runForTicket:y}}function m8({onBack:t,onLogoClick:s}){const{items:n,loading:r,error:a,busyId:o,loadData:i,saveTranscript:d,saveTicketFields:m,regenerateTranscript:p,regenerateMedia:c,approve:u,reject:x,runForTicket:h}=u8(),b=async()=>{const f=window.prompt("Run the job report pipeline for which ticket? (TICK-#### or Firestore doc id)");if(!f)return;const g=window.prompt("Capture URL â walkthrough .mp4/.webm or .gif (leave empty to use the ticketâs agentQa media):")||void 0;await h(f.trim(),(g==null?void 0:g.trim())||void 0)};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-3xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:"20px",height:"20px"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Job Reports"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Review AI job videos before human QA"})]}),e.jsxs("button",{onClick:b,className:"flex items-center gap-1.5 bg-primary text-primary-foreground px-3 py-2 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity",children:[e.jsx(In,{style:{width:"16px",height:"16px"}}),"Run for ticketâ¦"]}),e.jsxs("button",{onClick:()=>i(),disabled:r,className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground px-3 py-2 rounded-lg text-sm transition-colors disabled:opacity-40",children:[e.jsx(yt,{style:{width:"16px",height:"16px"},className:r?"animate-spin":""}),"Refresh"]})]}),a&&e.jsx("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-3 mb-4 text-sm text-destructive",children:a}),r&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{style:{width:"24px",height:"24px"},className:"animate-spin text-muted-foreground"})}),!r&&n.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(gu,{style:{width:"32px",height:"32px"},className:"mx-auto mb-3 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No job reports waiting â they appear automatically when Bucky QA passes a ticket."})]}),!r&&n.map(f=>e.jsx(h8,{item:f,busy:o===f.ticketId,onSave:g=>d(f.ticketId,g),onSaveTicketFields:g=>m(f.ticketId,g),onApprove:()=>u(f.ticketId),onReject:()=>x(f.ticketId),onRegenerateTranscript:()=>p(f.ticketId),onRegenerateMedia:()=>c(f.ticketId)},f.ticketId))]})]})}function p8(t){switch(t.status){case"generating":return{label:"Generatingâ¦",cls:"bg-sky-600/10 text-sky-700"};case"approved":return{label:"Approved",cls:"bg-emerald-600/10 text-emerald-700"};case"rejected":return{label:"Rejected",cls:"bg-rose-600/10 text-rose-700"};case"error":return{label:"Error",cls:"bg-rose-600/10 text-rose-700"};default:return{label:"Draft",cls:"bg-amber-600/10 text-amber-700"}}}function Un(t){return t==null?"":String(t)}function x8(t){return t.trim()?t.trim().split(/\s+/).length:0}function h8({item:t,busy:s,onSave:n,onSaveTicketFields:r,onApprove:a,onReject:o,onRegenerateTranscript:i,onRegenerateMedia:d}){var S,O,R,z,D,L,$,q,P,U,V;const[m,p]=l.useState(t.transcript),[c,u]=l.useState(!1),[x,h]=l.useState(!1),[b,f]=l.useState(Un((S=t.ticketFields)==null?void 0:S.shopifyThemeId)),[g,y]=l.useState(Un((O=t.ticketFields)==null?void 0:O.pageUrl)),[j,v]=l.useState(Un((R=t.t
412icketFields)==null?void 0:R.videoReviewUrl));l.useEffect(()=>{p(t.transcript)},[t.transcript]),l.useEffect(()=>{var M,F,W;f(Un((M=t.ticketFields)==null?void 0:M.shopifyThemeId)),y(Un((F=t.ticketFields)==null?void 0:F.pageUrl)),v(Un((W=t.ticketFields)==null?void 0:W.videoReviewUrl))},[(z=t.ticketFields)==null?void 0:z.shopifyThemeId,(D=t.ticketFields)==null?void 0:D.pageUrl,(L=t.ticketFields)==null?void 0:L.videoReviewUrl]);const T=b.trim()!==Un(($=t.ticketFields)==null?void 0:$.shopifyThemeId)||g.trim()!==Un((q=t.ticketFields)==null?void 0:q.pageUrl)||j.trim()!==Un((P=t.ticketFields)==null?void 0:P.videoReviewUrl),k=m.trim()!==t.transcript.trim(),w=p8(t),I=x8(m),A=t.video.status==="ready"&&(t.video.textHash!==t.currentTextHash||t.video.sourceUrl!==(t.videoUrl??t.gifUrl)||k),E=t.status==="generating",C=async()=>{window.confirm("Regenerate the transcript from scratch? Your edits will be discarded.")&&await i()},N=async()=>{const M=A||t.video.status!=="ready"?` 413 414The video will be regenerated for the current transcript first.`:"";window.confirm(`Approve this job report? The ticket moves to human QA with the video attached.${M}`)&&await a()};return e.jsxs("div",{className:"bg-card border border-border rounded-lg mb-3 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"text-sm font-semibold text-foreground truncate flex-1",children:[t.ticketDisplayId," â ",t.ticketName]}),t.qaAttempt>0&&e.jsxs("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded flex-shrink-0 bg-muted text-muted-foreground",children:["QA attempt ",t.qaAttempt]}),e.jsx("span",{className:`text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded flex-shrink-0 ${w.cls}`,children:w.label})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[t.clientName||"Unknown client",t.projectName?` · ${t.projectName}`:"",t.aiPrUrl&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("a",{href:t.aiPrUrl,target:"_blank",rel:"noreferrer",className:"text-primary",style:{textDecoration:"underline"},children:"PR â"})]})]}),t.status==="error"&&t.error&&e.jsxs("p",{className:"text-xs text-destructive mb-3",children:["Pipeline: ",t.error]}),e.jsxs("button",{onClick:()=>u(M=>!M),className:"flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground mb-2",children:[c?e.jsx(Ot,{style:{width:"14px",height:"14px"}}):e.jsx(Rt,{style:{width:"14px",height:"14px"}}),"Original request & QA notes"]}),c&&e.jsxs("div",{className:"bg-muted/30 border border-border rounded-md p-3 mb-3 text-xs text-foreground whitespace-pre-wrap",style:{maxHeight:"220px",overflowY:"auto"},children:[t.originalRequest||"(no request text)",t.qaNotes&&e.jsxs(e.Fragment,{children:[` 415 416`,e.jsx("span",{className:"font-semibold",children:"QA notes:"}),` 417`,t.qaNotes]})]}),e.jsxs("button",{onClick:()=>h(M=>!M),className:"flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground mb-2",children:[x?e.jsx(Ot,{style:{width:"14px",height:"14px"}}):e.jsx(Rt,{style:{width:"14px",height:"14px"}}),"Ticket settings â theme, page & Loom",T&&e.jsx("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-amber-600/10 text-amber-700 ml-1",children:"unsaved"})]}),x&&e.jsxs("div",{className:"bg-muted/30 border border-border rounded-md p-3 mb-3",children:[e.jsxs("div",{className:"grid gap-2",style:{gridTemplateColumns:"1fr 2fr"},children:[e.jsx("label",{className:"text-xs text-muted-foreground self-center",children:"Theme preview ID"}),e.jsx("input",{value:b,onChange:M=>f(M.target.value),disabled:s,placeholder:"e.g. 156879421629",className:"bg-background border border-border rounded-md px-2 py-1 text-xs text-foreground"}),e.jsx("label",{className:"text-xs text-muted-foreground self-center",children:"Page URL"}),e.jsx("input",{value:g,onChange:M=>y(M.target.value),disabled:s,placeholder:"https://store.com/page-being-changed",className:"bg-background border border-border rounded-md px-2 py-1 text-xs text-foreground"}),e.jsx("label",{className:"text-xs text-muted-foreground self-center",children:"Loom video (fallback)"}),e.jsx("input",{value:j,onChange:M=>v(M.target.value),disabled:s,placeholder:"https://www.loom.com/share/â¦
417(used when no MP4)",className:"bg-background border border-border rounded-md px-2 py-1 text-xs text-foreground"})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsxs("button",{onClick:()=>r({shopifyThemeId:b.trim()||null,pageUrl:g.trim()||null,videoReviewUrl:j.trim()||null}),disabled:s||!T,className:"flex items-center gap-1.5 bg-primary text-primary-foreground px-3 py-1.5 rounded-md text-xs font-medium hover:opacity-90 transition-opacity disabled:opacity-50",children:[s?e.jsx(fe,{style:{width:"12px",height:"12px"},className:"animate-spin"}):e.jsx(kt,{style:{width:"12px",height:"12px"}}),"Save ticket settings"]})})]}),t.video.status==="ready"&&t.video.publicUrl?e.jsxs("div",{className:"mb-3",children:[e.jsx(Co,{src:t.video.publicUrl,captionsUrl:t.video.captionsUrl,videoStyle:{maxHeight:"360px"}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[A&&e.jsx("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-amber-600/10 text-amber-700",children:"Video out of date â approve will rebuild it"}),t.video.durationSec!=null&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[t.video.durationSec,"s"]}),t.audio.quietWindows&&e.jsx("span",{className:"text-[11px] text-muted-foreground",title:"Stretches with no narration longer than 2.6s â Bucky floats on screen during these so the video never looks stalled",children:t.audio.quietWindows.length?`${t.audio.quietWindows.length} quiet stretch${t.audio.quietWindows.length===1?"":"es"} · longest ${Math.max(...t.audio.quietWindows.map(M=>M.end-M.start)).toFixed(1)}s · Bucky on screen`:"No quiet stretches over 2.6s"}),e.jsx("a",{href:t.video.publicUrl,target:"_blank",rel:"noreferrer",className:"text-xs text-primary ml-auto",style:{textDecoration:"underline"},children:"Open video â"})]})]}):E?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-3",children:[e.jsx(fe,{style:{width:"16px",height:"16px"},className:"animate-spin"}),"Generating transcript, audio and videoâ¦"]}):e.jsxs("div",{className:"mb-3",children:[t.videoUrl?e.jsx("video",{src:t.videoUrl,controls:!0,muted:!0,playsInline:!0,className:"w-full rounded-md border border-border mb-2",style:{maxHeight:"240px",objectFit:"contain",backgroundColor:"#000"}}):t.gifUrl?e.jsx("img",{src:t.gifUrl,alt:"QA capture",className:"w-full rounded-md border border-border mb-2",style:{maxHeight:"240px",objectFit:"contain",backgroundColor:"#000"}}):null,t.video.error&&e.jsxs("p",{className:"text-xs text-destructive",children:["Video: ",t.video.error]}),t.audio.error&&e.jsxs("p",{className:"text-xs text-destructive",children:["Audio: ",t.audio.error]})]}),t.audio.status==="ready"&&t.audio.publicUrl&&e.jsx("audio",{controls:!0,src:t.audio.publicUrl,className:"w-full mb-3",style:{height:"32px"}}),(U=t.qa)!=null&&U.beforeImageUrl&&t.qa.afterImageUrl?e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Before / after (drag to compare)"}),e.jsx("div",{className:"rounded-md border border-border overflow-hidden",children:e.jsx(Pl,{beforeImageUrl:t.qa.beforeImageUrl,afterImageUrl:t.qa.afterImageUrl,ticketId:t.ticketId,savedAlignmentOffset:t.qa.savedAlignmentOffset,readOnly:!0})})]}):(V=t.qa)!=null&&V.beforeImageUrl?e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Before (no after screenshot yet)"}),e.jsx("a",{href:t.qa.beforeImageUrl,target:"_blank",rel:"noreferrer",children:e.jsx("img",{src:t.qa.beforeImageUrl,alt:"Before",className:"w-full rounded-md border border-border",style:{maxHeight:"240px",objectFit:"contain",objectPosition:"top",backgroundColor:"#fff"}})})]}):null,e.jsx("textarea",{value:m,onChange:M=>p(M.target.value),disabled:s||E,className:"w-full bg-background border border-border rounded-md px-2 py-1.5 text-sm text-foreground",style:{minHeight:"110px",resize:"vertical",lineHeight:1.5}}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 mb-3",children:[e.jsxs("span",{className:`text-[11px] ${I>=60&&I<=120?"text-muted-foreground":"text-amber-700"}`,children:[I," words (target 60â120)"]}),e.jsxs("button",{onClick:()=>n(m),disabled:s||E||!k,className:"ml-auto flex items-center gap-1.5 bg-primary text-primary-foreground px-3 py-1.5 rounded-md text-sm font-medium hover:opacity-90 transition-opacity disabled:opacity-50",children:[s?e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"}):e.jsx(kt,{style:{width:"14px",height:"14px"}}),"Save"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("button",{onClick:N,disabled:s||E||t.status==="error",className:"flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium text-white hover:opacity-90 transition-opacity disabled:opacity-50",style:{backgroundColor:"#059669"},children:s?e.jsxs(e.Fragment,{children:[e.jsx(fe,{style:{width:"14px",height:"14px"},className:"animate-spin"})," Workingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{style:{width:"14px",height:"14px"}})," Approve â human QA"]})}),e.jsxs("button",{onClick:o,disabled:s||E,className:"flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium border border-border text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50",children:[e.jsx(mt,{style:{width:"14px",height:"14px"}}),"Reject"]}),e.jsxs("button",{onClick:C,disabled:s||E,className:"flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium border border-border text-foreground hover:bg-muted/40 transition-colors disabled:opacity-50",children:[e.jsx(yt,{style:{width:"14px",height:"14px"}}),"Regenerate transcript"]}),e.jsxs("button",{onClick:d,disabled:s||E,className:"flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium border border-border text-foreground hover:bg-muted/40 transition-colors disabled:opacity-50",children:[e.jsx(gu,{style:{width:"14px",height:"14px"}}),"Regenerate media"]})]})]})}const nh="https://us-central1-bucky-app-355a3.cloudfunctions.net",f8=[{key:"story",label:"Tell the story",hint:'Record it (or upload a voice memo) answering the questions below out loud, in order. Hit the scenes as moments, not summaries: where were you, what did you see, what did you assume, what did you check and find "green", the moment it clicked, what it cost, what still makes you wince, what you did the same day.'},{key:"takeaway",label:"The turn â write the ending first",hint:"What is the one sentence the whole episode exists to earn? The line the viewer walks away repeating."},{key:"withheld",label:"The withheld",hint:"Which 2â3 facts do we deliberately NOT reveal early, and where does each one pay off? One per line: fact â payoff."},{key:"prerequisites",label:"The prerequisites",hint:"What must the viewer understand before the twist can land? Planted early and casually, without telegraphing it."},{key:"notes",label:"Research notes",hint:"Everything else: the pace map (SLOW moments to live inside, FAST ones to compress to a sentence), the scenes list, evidence with sources (dates and PRs only â never intent), redaction, title candidates."},{key:"title",label:"Title â the research decides it",hint:"Leave it undecided until the story is told. Candidates go in the notes; the winner goes here."}],g8=t=>{var n,r;const s=a=>!!(a&&a.trim());return[{key:"title",label:"Title decided",done:s(t.title)&&t.title!==t.id},{key:"story",label:"Story recorded",done:!!((n=t.researchAudio)!=null&&n.storagePath)},{key:"transcript",label:"Transcribed",done:s((r=t.researchAudio)==null?void 0:r.transcript)},{key:"takeaway",label:"The turn",done:s(t.takeaway)},{key:"withheld",label:"Withheld",done:s(t.withheld)},{key:"prerequisites",label:"Prerequisites",done:s(t.prerequisites)}]},rh=20*1024*1024,ah=t=>t===null||!Number.isFinite(t)?"":`${Math.floor(t/60)}:${String(Math.round(t%60)).padStart(2,"0")}`,b8=()=>{if(!(typeof MediaRecorder>"u"))return["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;
417codecs=opus"].find(t=>MediaRecorder.isTypeSupported(t))},y8=t=>new Promise((s,n)=>{const r=new FileReader;r.onerror=()=>n(r.error??new Error("read failed")),r.onload=()=>{const a=String(r.result??"");s(a.slice(a.indexOf(",")+1))},r.readAsDataURL(t)}),oh={research:{bg:"rgba(109,40,217,0.12)",fg:"#6d28d9",label:"research"},production:{bg:"rgba(14,116,144,0.12)",fg:"#0e7490",label:"production"},pending_review:{bg:"rgba(161,98,7,0.12)",fg:"#a16207",label:"needs approval"},approved:{bg:"rgba(21,128,61,0.12)",fg:"#15803d",label:"approved"},rejected:{bg:"rgba(185,28,28,0.12)",fg:"#b91c1c",label:"rejected"}},ao=new Set(["research","production"]),ih=t=>t===null?"":t>1024*1024?`${(t/1024/1024).toFixed(1)} MB`:t>1024?`${Math.round(t/1024)} KB`:`${t} B`,lh={pending_review:{bg:"rgba(75,85,99,0.12)",fg:"#4b5563"},scheduled:{bg:"rgba(14,116,144,0.12)",fg:"#0e7490"},posting:{bg:"rgba(161,98,7,0.12)",fg:"#a16207"},posted:{bg:"rgba(21,128,61,0.12)",fg:"#15803d"},failed:{bg:"rgba(185,28,28,0.12)",fg:"#b91c1c"},canceled:{bg:"rgba(75,85,99,0.12)",fg:"#4b5563"}},j8={youtube:"YouTube",facebook:"Facebook",instagram:"Instagram",linkedin:"LinkedIn",tiktok:"TikTok"},v8=new Set(["pending_review","scheduled","failed","canceled"]),Di={backgroundColor:"var(--card)",border:"1px solid var(--border)",borderRadius:8,padding:16,marginBottom:12},zt=(t,s="var(--foreground)")=>({backgroundColor:t,color:s,border:"none",borderRadius:6,padding:"7px 14px",fontSize:13,cursor:"pointer"}),vn=(t,s)=>({backgroundColor:t,color:s,padding:"2px 8px",borderRadius:4,fontSize:12,fontWeight:600}),rs={width:"100%",padding:8,marginBottom:8,background:"var(--card)",color:"var(--foreground)",border:"1px solid var(--border)",borderRadius:4,fontSize:13},Xs={fontSize:11,color:"var(--muted-foreground)",display:"block",marginBottom:2},w8={display:"block",fontSize:13,fontWeight:600,marginTop:14,marginBottom:2},N8={fontSize:12,color:"var(--muted-foreground)",marginBottom:6,lineHeight:1.4},ch={padding:"10px 12px",borderLeft:"3px solid #6d28d9",background:"rgba(109,40,217,0.08)",borderRadius:4,fontSize:14,fontWeight:600,margin:"6px 0 10px"},aa=t=>t?t.toDate().toLocaleString(void 0,{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"â",k8=t=>{if(!t)return"";const s=t.toDate(),n=r=>String(r).padStart(2,"0");return`${s.getFullYear()}-${n(s.getMonth()+1)}-${n(s.getDate())}T${n(s.getHours())}:${n(s.getMinutes())}`},S8={title:"",description:"",tags:"",text:"",link:"",firstComment:"",thumbnailPath:"",captionsPath:"",scheduledAt:""};function C8({onBack:t,onLogoClick:s}){const[n,r]=l.useState([]),[a,o]=l.useState({}),[i,d]=l.useState({}),[m,p]=l.useState(new Set),[c,u]=l.useState(!0),[x,h]=l.useState(null),[b,f]=l.useState(null),[g,y]=l.useState(null),[j,v]=l.useState(S8),[T,k]=l.useState(null),[w,I]=l.useState(!1),[A,E]=l.useState(!1),[C,N]=l.useState({id:"",title:""}),[S,O]=l.useState(null),[R,z]=l.useState({title:"",takeaway:"",withheld:"",prerequisites:"",researchNotes:"",brief:"",expectedFiles:"",episodeUrl:""}),[D,L]=l.useState({}),[$,q]=l.useState({}),[P,U]=l.useState(null),V=l.useRef(null),M=l.useRef([]),F=l.useRef(null),W=l.useRef(null),_=l.useRef(0),G=l.useRef(null),B=l.useRef(null),Y=l.useCallback(async()=>{u(!0);try{const te=await Ze(Ge(Re(ge,"contentPacks"),Nt("updatedAt","desc"),Tt(50)));r(te.docs.map(ve=>({id:ve.id,...ve.data()})))}catch(te){f(`Load failed: ${te.message}`)}finally{u(!1)}},[]);l.useEffect(()=>{Y()},[Y]);const J=l.useCallback(async()=>{try{const te=await re("contentPlatformStatus",{});k(te.linkedin)}catch{}},[]);l.useEffect(()=>{J()},[J]),l.useEffect(()=>{const te=ve=>{var Ae,We;ve.origin===nh&&(((Ae=ve.data)==null?void 0:Ae.type)==="LINKEDIN_AUTH_SUCCESS"?(I(!1),f("LinkedIn connected. Essays post from this profile at their scheduled time."),J()):((We=ve.data)==null?void 0:We.type)==="LINKEDIN_AUTH_FAILED"&&(I(!1),f(`LinkedIn connect failed: ${ve.data.detail??"unknown error"}`)))};return window.addEventListener("message",te),()=>window.removeEventListener("message",te)},[J]);const H=async()=>{f(null),I(!0);try{const{getAuth:te}=await Gs(async()=>{const{getAuth:de}=await import("./vendor-firebase-Cr-z2ntb.js").then(je=>je.P);return{getAuth:de}},[]),ve=te().currentUser;if(!ve)throw new Error("Not signed in");const Ae=await ve.getIdToken(),We=await fetch(`${nh}/linkedinOAuthStart`,{headers:{Authorization:`Bearer ${Ae}`}});if(!We.ok)throw new Error(`linkedinOAuthStart â ${We.status}`);const{authUrl:ie}=await We.json(),Ue=600,Te=720,He=window.screenX+(window.outerWidth-Ue)/2,Oe=window.screenY+(window.outerHeight-Te)/2;window.open(ie,"linkedin-connect",`width=${Ue},height=${Te}
417,left=${He},top=${Oe}`)||(I(!1),f("Popup blocked â allow popups for this site and try again."))}catch(te){I(!1),f(te.message)}};l.useEffect(()=>{const te=n.filter(Ae=>{var We;return ao.has(Ae.status)&&((We=Ae.researchAudio)==null?void 0:We.storagePath)&&!D[Ae.researchAudio.storagePath]});if(te.length===0)return;let ve=!1;return(async()=>{try{const Ae=await re("contentGetMediaUrls",{packIds:te.map(ie=>ie.id)});if(ve)return;const We={};for(const ie of te){const Ue=Ae.urls[`pack:${ie.id}`];Ue&&ie.researchAudio&&(We[ie.researchAudio.storagePath]=Ue)}L(ie=>({...ie,...We}))}catch{}})(),()=>{ve=!0}},[n]),l.useEffect(()=>()=>{var te;(te=F.current)==null||te.getTracks().forEach(ve=>ve.stop()),W.current&&window.clearInterval(W.current)},[]);const Z=async te=>{const ve=te.filter(Ae=>Ae.payload.storagePath&&!i[Ae.id]);if(ve.length!==0)try{const Ae=await re("contentGetMediaUrls",{postIds:ve.map(We=>We.id)});d(We=>({...We,...Ae.urls}))}catch{}},Q=async te=>{try{const Ae=(await Ze(Ge(Re(ge,"contentQueue"),Ve("packId","==",te),Nt("scheduledAt","asc")))).docs.map(We=>({id:We.id,...We.data()}));o(We=>({...We,[te]:Ae})),Z(Ae)}catch(ve){f(`Posts load failed: ${ve.message}`)}},K=te=>{const ve=new Set(m);ve.has(te)?ve.delete(te):(ve.add(te),a[te]?Z(a[te]):Q(te)),p(ve)},X=async(te,ve)=>{if(ve==="approve"){const Ae=n.find(ie=>ie.id===te);if(!window.confirm(`Approve "${(Ae==null?void 0:Ae.title)??te}"? Every post in the pack goes out on its scheduled day with no further review.`))return}h(te),f(null);try{const Ae=await re("contentReviewPack",{packId:te,action:ve});f(ve==="approve"?`Approved â ${Ae.scheduled} posts scheduled. The sweep posts them when due.`:"Rejected. Fix and re-approve, or re-push the pack."),await Y(),a[te]&&await Q(te)}catch(Ae){f(Ae.message)}finally{h(null)}},se=te=>{y(te.id),v({title:te.payload.title??"",description:te.payload.description??"",tags:(te.payload.tags??[]).join(", "),text:te.payload.text??"",link:te.payload.link??"",firstComment:te.payload.firstComment??"",thumbnailPath:te.payload.thumbnailPath??"",captionsPath:te.payload.captionsPath??"",scheduledAt:k8(te.scheduledAt)})},pe=async te=>{h(te.id),f(null);try{const ve={postId:te.id,payload:{title:j.title,description:j.description,tags:j.tags.split(",").map(Ae=>Ae.trim()).filter(Boolean),text:j.text,link:j.link,firstComment:j.firstComment,...te.platform==="youtube"?{thumbnailPath:j.thumbnailPath,captionsPath:j.captionsPath}:{}}};j.scheduledAt&&(ve.scheduledAt=new Date(j.scheduledAt).toISOString()),await re("contentUpdatePost",ve),y(null),await Q(te.packId)}catch(ve){f(ve.message)}finally{h(null)}},me=async()=>{const te=C.id.trim(),ve=C.title.trim();if(!te){f("Pack id is required (e.g. ep-03).");return}h("new-pack"),f(null);try{await re("contentSavePackDraft",ve?{packId:te,title:ve}:{packId:te}),E(!1),N({id:"",title:""}),await Y(),O(te),z({title:ve,takeaway:"",withheld:"",prerequisites:"",researchNotes:"",brief:"",expectedFiles:"",episodeUrl:""})}catch(Ae){f(Ae.message)}finally{h(null)}},Ne=te=>{O(te.id),z({title:te.title===te.id?"":te.title,takeaway:te.takeaway??"",withheld:te.withheld??"",prerequisites:te.prerequisites??"",researchNotes:te.researchNotes??"",brief:te.brief??"",expectedFiles:(te.expectedFiles??[]).join(` 418`),episodeUrl:te.episodeUrl??""})},at=async(te,ve)=>{h(te.id),f(null);try{const Ae={packId:te.id,title:R.title,takeaway:R.takeaway,withheld:R.withheld,prerequisites:R.prerequisites,researchNotes:R.researchNotes,brief:R.brief,episodeUrl:R.episodeUrl,expectedFiles:R.expectedFiles.split(` 419`).map(We=>We.trim()).filter(Boolean)};ve&&(Ae.stage=ve),await re("contentSavePackDraft",Ae),O(null),await Y()}catch(Ae){f(Ae.message)}finally{h(null)}},ae=async(te,ve)=>{h(te.id),f(null);try{await re("contentSavePackDraft",{packId:te.id,stage:ve}),await Y()}catch(Ae){f(Ae.message)}finally{h(null)}},xe=async te=>{q(ve=>({...ve,[te]:"transcribing"})),f(null);try{const ve=await re("contentTranscribeResearchAudio",{packId:te},void 0,{timeoutMs:54e4});f(`Transcribed â ${ve.chars.toLocaleString()} characters. Now fill in the turn, the withheld facts and the prerequisites from it.`),await Y()}catch(ve){f(ve.message),await Y()}finally{q(ve=>{const Ae={...ve};return delete Ae[te],Ae})}},ze=async(te,ve,Ae,We)=>{if(ve.size===0){f("That recording is empty.");return}if(ve.size>rh){f(`Recording is ${(ve.size/1048576).toFixed(1)} MB â max ${rh/1048576} MB. Trim it or split the story.`);return}q(ie=>({...ie,[te]:"uploading"})),f(null);try{const ie=await y8(ve),Ue=await re("contentUploadResearchAudio",{packId:te,filename:Ae,contentType:ve.type||null,base64:ie,durationSeconds:We},void 0,{timeoutMs:3e5});Ue.url&&L(Te=>({...Te,[Ue.storagePath]:Ue.url})),await Y()}catch(ie){f(ie.message),q(Ue=>{const Te={...Ue};return delete Te[te],Te});return}await xe(te)},Le=async te=>{var ve;if(!P){if(!((ve=navigator.mediaDevices)!=null&&ve.getUserMedia)||typeof MediaRecorder>"u"){f("This browser cannot record â upload a voice memo instead.");return}f(null);try{const Ae=await navigator.mediaDevices.getUserMedia({audio:!0}),We=b8(),ie=new MediaRecorder(Ae,We?{mimeType:We}:void 0);M.current=[],F.current=Ae,V.current=ie,_.current=Date.now(),ie.ondataavailable=Ue=>{Ue.data.size>0&&M.current.push(Ue.data)},ie.onstop=()=>
419{Ae.getTracks().forEach(Je=>Je.stop()),F.current=null,W.current&&(window.clearInterval(W.current),W.current=null);const Ue=Math.round((Date.now()-_.current)/1e3);U(null);const Te=ie.mimeType||We||"audio/webm",He=new Blob(M.current,{type:Te});M.current=[];const Oe=Te.includes("mp4")?"m4a":Te.includes("ogg")?"ogg":"webm";ze(te,He,`story.${Oe}`,Ue)},ie.start(1e3),U({packId:te,seconds:0}),W.current=window.setInterval(()=>{U(Ue=>Ue&&{...Ue,seconds:Math.round((Date.now()-_.current)/1e3)})},500)}catch(Ae){f(`Microphone unavailable: ${Ae.message}`)}}},ht=()=>{const te=V.current;te&&te.state!=="inactive"&&te.stop(),V.current=null},ue=te=>{var ve;B.current=te,(ve=G.current)==null||ve.click()},we=te=>{var We;const ve=(We=te.target.files)==null?void 0:We[0],Ae=B.current;te.target.value="",!(!ve||!Ae)&&ze(Ae,ve,ve.name,null)},Be=async te=>{h(`scan-${te.id}`),f(null);try{const ve=await re("contentScanAssets",{packId:te.id});r(Ae=>Ae.map(We=>We.id===te.id?{...We,assetScan:{files:ve.files,scannedAt:ja.now()}}:We))}catch(ve){f(ve.message)}finally{h(null)}},Ye=async te=>{var Ae;const ve=[`# Production brief â ${te.title} (${te.id})`,te.episodeUrl?`Episode: ${te.episodeUrl}`:"","",te.brief??"","","## The story (research)",`Takeaway (the turn): ${te.takeaway??"(undecided)"}`,"","Withheld (fact â payoff):",te.withheld??"(none)","","Prerequisites:",te.prerequisites??"(none)","","## Deliverables (upload to gs://bucky-app-355a3.firebasestorage.app/content-media/"+te.id+"/)",...(te.expectedFiles??[]).map(We=>`- ${We}`),"","## Research notes",te.researchNotes??"(none)","","## Story transcript (build the script from this â Jody's words, his order)",((Ae=te.researchAudio)==null?void 0:Ae.transcript)??"(not recorded yet)","",`When assets are up, push posts with contentEnqueuePack (packId: ${te.id}).`].join(` 420`);try{await navigator.clipboard.writeText(ve),f("Brief copied â paste it to the CLI content agent.")}catch{f(ve)}},rt=async(te,ve)=>{h(te.id),f(null);try{await re("contentUpdatePost",{postId:te.id,action:ve}),await Q(te.packId)}catch(Ae){f(Ae.message)}finally{h(null)}};return e.jsxs("div",{style:{padding:24,color:"var(--foreground)",maxWidth:980,margin:"0 auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:4},children:[e.jsx("button",{onClick:t,style:zt("var(--muted)"),children:"â Back"}),e.jsx("h1",{style:{fontSize:20,margin:0,cursor:s?"pointer":"default"},onClick:s,children:"Content Queue"})]}),e.jsxs("p",{style:{color:"var(--muted-foreground)",fontSize:13,marginTop:4},children:["A pack moves research â production â approval. One approval per pack.",e.jsx("strong",{children:" Approving schedules every post in it"})," â review the media below, edit anything in place, then approve."]}),e.jsxs("div",{style:{...Di,display:"flex",gap:10,alignItems:"center",flexWrap:"wrap",fontSize:13},children:[e.jsx("span",{style:{color:"var(--muted-foreground)",fontSize:12},children:"Posting as:"}),e.jsx("span",{style:vn("rgba(21,128,61,0.12)","#15803d"),children:"YouTube · brand channel"}),e.jsx("span",{style:vn("rgba(21,128,61,0.12)","#15803d"),children:"Facebook + Instagram · Content Pipeline"}),T===null?e.jsx("span",{style:vn("rgba(75,85,99,0.12)","#6b7280"),children:"LinkedIn · checkingâ¦"}):T.connected?e.jsxs("span",{style:vn(T.expiringSoon?"rgba(161,98,7,0.12)":"rgba(21,128,61,0.12)",T.expiringSoon?"#a16207":"#15803d"),children:["LinkedIn · ",T.displayName||T.connectedBy,T.expiresAt&&` · expires ${new Date(T.expiresAt).toLocaleDateString()}`]}):e.jsx("span",{style:vn("rgba(185,28,28,0.12)","#b91c1c"),children:"LinkedIn · not connected"}),e.jsx("button",{onClick:H,disabled:w,style:zt("var(--muted)"),children:w?"Waiting for LinkedInâ¦":T!=null&&T.connected?"Reconnect LinkedIn":"Connect LinkedIn"}),e.jsx("span",{style:{color:"var(--muted-foreground)",fontSize:11},children:"Essays post from Jody's personal profile; member tokens last ~60 days."})]}),e.jsx("div",{style:{margin:"12px 0"},children:A?e.jsxs("div",{style:{...Di,display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[e.jsx("input",{placeholder:"pack id (e.g. ep-03)",value:C.id,onChange:te=>N({...C,id:te.target.value}),style:{...rs,width:180,marginBottom:0}}),e.jsx("input",{placeholder:"title (optional â the research decides it)",value:C.title,onChange:te=>N({...C,title:te.target.value}),style:{...rs,flex:1,minWidth:220,marginBottom:0}}),e.jsx("button",{onClick:me,disabled:x==="new-pack",style:zt("#16a34a","#fff"),children:"Create in research"}),e.jsx("button",{onClick:()=>E(!1),style:zt("var(--muted)"),children:"Cancel"})]}):e.jsx("button",{onClick:()=>E(!0),style:zt("var(--primary)"),children:"+ New pack"})}),b&&e.jsx("pre",{style:{...Di,whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:12,color:"#92400e"},children:b}),e.jsx("input",{ref:G,type:"file",accept:"audio/*,.m4a,.mp3,.wav,.webm,.ogg,.aac,.flac",onChange:we,style:{display:"none"}}),c&&e.jsx("p",{style:{color:"var(--muted-foreground)"},children:"Loadingâ¦"}),!c&&n.length===0&&e.jsx("p",{style:{color:"var(--muted-foreground)"},children:"No packs yet. Push one with contentEnqueuePack (content.sh pack push)."}),n.map(te=>{const ve=oh[te.status]??oh.pending_review,Ae=m.has(te.id),We=a[te.id]??[];return e.jsxs("div",{style:Di,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsx("span",{style:vn(ve.bg,ve.fg),children:ve.label}),e.jsx("strong",{children:te.title}),ao.has(te.status)&&te.title===te.id&&e.jsx("span",{style:vn("rgba(161,98,7,0.12)","#a16207"),children:"title undecided"}),e.jsxs("span",{style:{color:"var(--muted-foreground)",fontSize:13},children:[te.episode," · ",te.postCount," posts",te.postedCount>0&&` · ${te.postedCount} posted`,te.failedCount>0&&e.jsxs("span",{style:{color:"#b91c1c"},children:[" · ",te.failedCount," failed"]})]})]}),e.jsxs("div",{style:{fontSize:12,color:"var(--muted-foreground)",marginTop:6},children:["Day 0: ",aa(te.day0)," · pushed by ",te.createdBy,te.approvedBy&&` · approved by ${te.approvedBy}`,te.episodeUrl&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("a",{href:te.episodeUrl,target:"_blank",rel:"noreferrer",style:{color:"#0e7490"},children:"episode"})]})]}),te.notes&&e.jsx("div",{style:{fontSize:12,color:"var(--muted-foreground)",marginTop:4},children:te.notes}),te.rejectedReason&&e.jsxs("div",{style:{fontSize:12,color:"#b91c1c",marginTop:4},children:["Rejected: ",te.rejectedReason]}),ao.has(te.status)&&(()=>{var qe,he,lt,tt,Se,es;const ie=te.researchAudio??null,Ue=ie?D[ie.storagePath]:void 0,Te=$[te.id],He=(P==null?void 0:P.packId)===te.id,Oe=g8(te),Je=(_e,St)=>{const $t=f8.find(Ct=>Ct.key===St);return e.jsxs(e.Fragment,{children:[e.jsxs("label",{style:w8,children:[_e,". ",$t.label]}),e.jsx("div",{style:N8,children:$t.hint})]})},de=e.jsxs("div",{style:{padding:10,borderRadius:6,background:"var(--muted)",marginBottom:4},children:[ie?e.jsxs(e.Fragment,{children:[Ue?e.jsx("audio",{src:Ue,controls:!0,preload:"metadata",style:{width:"100%",maxWidth:520}}):e.jsx("div",{style:{fontSize:12,color:"var(--muted-foreground)"},children:"loading recordingâ¦"}),e.jsxs("div",{style:{fontSize:11,color:"var(--muted-foreground)",marginTop:4},children:[ie.durationSeconds?`${ah(ie.durationSeconds)} · `:"",ih(ie.bytes)," · ",ie.uploadedBy,ie.uploadedAt&&` · ${aa(ie.uploadedAt)}`,ie.transcribedAt&&` · transcribed ${aa(ie.transcribedAt)}`]}),ie.transcribeError&&!Te&&e.jsxs("div",{style:{fontSize:12,color:"#b91c1c",marginTop:4},children:["Transcription failed: ",ie.transcribeError]})]}):e.jsx("div",{style:{fontSize:12,color:"var(--muted-foreground)"},children:"No story recorded yet. Talk it through â a voice memo is fine."}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:8,flexWrap:"wrap",alignItems:"center"},children:[He?e.jsxs("button",{onClick:ht,style:zt("#b91c1c","#fff"),children:["â Stop (",ah(P.seconds),")"]}):e.jsx("button",{onClick:()=>Le(te.id),disabled:!!Te||!!P,style:zt("var(--primary)"),children:ie?"â Re-record":"â Record the story"}),e.jsx("button",{onClick:()=>ue(te.id),disabled:!!Te||!!P,style:zt("var(--card)"),children:"Upload audio"}),ie&&!ie.transcript&&!Te&&e.jsx("button",{onClick:()=>xe(te.id),style:zt("#0e7490","#fff"),children:ie.transcribeError?"Retry transcription":"Transcribe"}),(ie==null?void 0:ie.transcript)&&!Te&&e.jsx("button",{onClick:()=>xe(te.id),style:zt("var(--card)"),children:"Re-transcribe"}),Te&&e.jsx("span",{style:{fontSize:12,color:"var(--muted-foreground)"},children:Te==="uploading"?"Uploadingâ¦":"Transcribing with Gemini â a long story can take a minuteâ¦"})]}),(ie==null?void 0:ie.transcript)&&e.jsxs("details",{style:{marginTop:8},children:[e.jsxs("summary",{style:{cursor:"pointer",fontSize:12,color:"var(--muted-foreground)"}
420,children:["Transcript (",ie.transcript.length.toLocaleString()," chars) â the script is built from this"]}),e.jsx("pre",{style:{whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:12,margin:"6px 0 0",maxHeight:360,overflow:"auto",color:"var(--foreground)"},children:ie.transcript})]})]}),je=e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:10},children:Oe.map(_e=>e.jsxs("span",{style:vn(_e.done?"rgba(21,128,61,0.12)":"rgba(75,85,99,0.12)",_e.done?"#15803d":"#6b7280"),children:[_e.done?"â":"â"," ",_e.label]},_e.key))});return S===te.id?e.jsxs("div",{style:{marginTop:4},children:[je,e.jsxs("div",{style:{fontSize:12,color:"var(--muted-foreground)",marginTop:10},children:[e.jsx("strong",{children:"Research â the story interview."})," Answer in order. The script gets built from the transcript and these fields, so nothing here is optional for long."]}),Je(1,"story"),de,Je(2,"takeaway"),e.jsx("input",{value:R.takeaway,onChange:_e=>z({...R,takeaway:_e.target.value}),placeholder:"One sentence. e.g. âNobody decided who owned the number â and deciding ownership is the real work.â",style:rs}),Je(3,"withheld"),e.jsx("textarea",{value:R.withheld,rows:4,onChange:_e=>z({...R,withheld:_e.target.value}),placeholder:`that there were TWO writers â the debugging is told as a mystery first 421both systems were individually correct â the reveal: the architecture was the bug`,style:{...rs,fontFamily:"inherit"}}),Je(4,"prerequisites"),e.jsx("textarea",{value:R.prerequisites,rows:3,onChange:_e=>z({...R,prerequisites:_e.target.value}),placeholder:"What the credit balance IS (client money); that it's the number work stops on; that the two features were built at different times.",style:{...rs,fontFamily:"inherit"}}),Je(5,"notes"),e.jsx("textarea",{value:R.researchNotes,rows:8,onChange:_e=>z({...R,researchNotes:_e.target.value}),style:{...rs,fontFamily:"inherit"}}),Je(6,"title"),e.jsx("input",{value:R.title,onChange:_e=>z({...R,title:_e.target.value}),placeholder:"undecided â candidates in the notes, the winner here",style:rs}),e.jsxs("div",{style:{fontSize:12,color:"var(--muted-foreground)",marginTop:16,paddingTop:10,borderTop:"1px solid var(--border)"},children:[e.jsx("strong",{children:"Production"})," â what the CLI content agent works from once the story is set."]}),e.jsx("label",{style:Xs,children:"Production brief"}),e.jsx("textarea",{value:R.brief,rows:8,onChange:_e=>z({...R,brief:_e.target.value}),style:{...rs,fontFamily:"inherit"}}),e.jsxs("label",{style:Xs,children:["Expected files, one per line (relative to content-media/",te.id,"/)"]}),e.jsx("textarea",{value:R.expectedFiles,rows:4,onChange:_e=>z({...R,expectedFiles:_e.target.value}),style:{...rs,fontFamily:"ui-monospace, monospace"},placeholder:`cut1-admission.mp4 422cut2-thesis.mp4`}),e.jsx("label",{style:Xs,children:"Episode URL"}),e.jsx("input",{value:R.episodeUrl,onChange:_e=>z({...R,episodeUrl:_e.target.value}),style:rs}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:()=>at(te),disabled:x===te.id,style:zt("#16a34a","#fff"),children:"Save"}),te.status==="research"&&e.jsx("button",{onClick:()=>at(te,"production"),disabled:x===te.id,style:zt("#0e7490","#fff"),children:"Save & move to production"}),e.jsx("button",{onClick:()=>O(null),style:zt("var(--muted)"),children:"Cancel"})]})]}):e.jsxs("div",{style:{marginTop:4},children:[je,e.jsxs("div",{style:{marginTop:10},children:[te.takeaway?e.jsxs("div",{style:ch,children:[e.jsx("span",{style:{fontSize:10,fontWeight:700,letterSpacing:.5,color:"#6d28d9",display:"block",marginBottom:2},children:"THE TURN"}),te.takeaway]}):te.status==="research"&&e.jsx("div",{style:{...ch,fontWeight:400,color:"var(--muted-foreground)",fontSize:12},children:"The turn is undecided â what is the one sentence this episode exists to earn?"}),te.status==="research"&&de,(te.withheld||te.prerequisites)&&e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(260px, 1fr))",gap:10,margin:"10px 0"},children:[te.withheld&&e.jsxs("div",{style:{padding:10,borderRadius:6,border:"1px solid var(--border)"},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,letterSpacing:.5,color:"var(--muted-foreground)",marginBottom:4},children:"WITHHELD · fact â payoff"}),e.jsx("pre",{style:{whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:12,margin:0},children:te.withheld})]}),te.prerequisites&&e.jsxs("div",{style:{padding:10,borderRadius:6,border:"1px solid var(--border)"},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,letterSpacing:.5,color:"var(--muted-foreground)",marginBottom:4},children:"PREREQUISITES · plant early"}),e.jsx("pre",{style:{whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:12,margin:0},children:te.prerequisites})]})]}),te.status==="production"&&ie&&e.jsxs("details",{style:{marginBottom:8},children:[e.jsx("summary",{style:{cursor:"pointer",fontSize:12,color:"var(--muted-foreground)"},children:"The story (recording + transcript)"}),e.jsx("div",{style:{marginTop:6},children:de})]}),te.researchNotes&&e.jsxs("details",{open:te.status==="research",style:{marginBottom:8},children:[e.jsx("summary",{style:{cursor:"pointer",fontSize:12,color:"var(--muted-foreground)"},children:"Research notes (scenes, pace map, evidence)"}),e.jsx("pre",{style:{whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:12,margin:"6px 0 0",color:"var(--foreground)"},children:te.researchNotes})]}),te.brief&&e.jsxs("details",{open:te.status==="production",style:{marginBottom:8},children:[e.jsx("summary",{style:{cursor:"pointer",fontSize:12,color:"var(--muted-foreground)"},children:"Production brief"}),e.jsx("pre",{style:{whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:12,margin:"6px 0 0",color:"var(--foreground)"},children:te.brief})]}),((((qe=te.expectedFiles)==null?void 0:qe.length)??0)>0||(((lt=(he=te.assetScan)==null?void 0:he.files)==null?void 0:lt.length)??0)>0)&&e.jsxs("div",{style:{marginBottom:8,padding:10,borderRadius:6,background:"var(--muted)"},children:[e.jsxs("div",{style:{fontSize:12,fontWeight:600,marginBottom:6},children:["Deliverables checklist",((tt=te.assetScan)==null?void 0:tt.scannedAt)&&e.jsxs("span",{style:{fontWeight:400,color:"var(--muted-foreground)"},children:[" ","· scanned ",aa(te.assetScan.scannedAt)]})]}
422),(((Se=te.assetScan)==null?void 0:Se.files)??(te.expectedFiles??[]).map(_e=>({name:_e,present:!1,bytes:null,unexpected:!1}))).map(_e=>e.jsxs("div",{style:{fontSize:13,display:"flex",gap:8,alignItems:"center",padding:"2px 0"},children:[e.jsx("span",{style:{color:_e.present?"#15803d":"#b91c1c",fontWeight:700},children:_e.present?"â":"â"}),e.jsx("span",{style:{fontFamily:"ui-monospace, monospace",fontSize:12},children:_e.name}),e.jsx("span",{style:{color:"var(--muted-foreground)",fontSize:11},children:ih(_e.bytes)}),_e.unexpected&&e.jsx("span",{style:vn("rgba(161,98,7,0.12)","#a16207"),children:"not in checklist"})]},_e.name)),(((es=te.assetScan)==null?void 0:es.files)??[]).length>0&&te.assetScan.files.filter(_e=>!_e.unexpected).every(_e=>_e.present)&&e.jsx("div",{style:{fontSize:12,color:"#15803d",marginTop:6},children:"All deliverables present â ready for the pack push (contentEnqueuePack)."})]})]})]})})(),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:12,flexWrap:"wrap"},children:[ao.has(te.status)&&S!==te.id&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>Ne(te),disabled:x===te.id,style:zt("var(--muted)"),children:"Edit details"}),e.jsx("button",{onClick:()=>Be(te),disabled:x===`scan-${te.id}`,style:zt("var(--muted)"),children:x===`scan-${te.id}`?"Scanningâ¦":"Scan storage"}),te.brief&&e.jsx("button",{onClick:()=>Ye(te),style:zt("var(--muted)"),children:"Copy brief for CLI"}),te.status==="research"&&e.jsx("button",{onClick:()=>ae(te,"production"),disabled:x===te.id,style:zt("#0e7490","#fff"),children:"Move to production"}),te.status==="production"&&e.jsx("button",{onClick:()=>ae(te,"research"),disabled:x===te.id,style:zt("var(--muted)"),children:"Back to research"})]}),te.status==="pending_review"&&e.jsx("button",{onClick:()=>X(te.id,"approve"),disabled:x===te.id,style:zt("#16a34a","#fff"),children:"Approve pack"}),(te.status==="pending_review"||te.status==="approved")&&e.jsx("button",{onClick:()=>X(te.id,"reject"),disabled:x===te.id,style:zt("var(--destructive)","#fff"),children:te.status==="approved"?"Halt remaining posts":"Reject"}),te.status==="rejected"&&e.jsx("button",{onClick:()=>X(te.id,"approve"),disabled:x===te.id,style:zt("#16a34a","#fff"),children:"Re-approve"}),!ao.has(te.status)&&e.jsx("button",{onClick:()=>K(te.id),style:zt("var(--muted)"),children:Ae?"Hide posts":`Show posts (${te.postCount})`})]}),Ae&&We.map(ie=>{var Je,de,je,qe,he,lt;const Ue=lh[ie.status]??lh.pending_review,Te=g===ie.id,He=v8.has(ie.status),Oe=ie.payload.storagePath?i[ie.id]:void 0;return e.jsxs("div",{style:{marginTop:10,padding:12,borderRadius:6,background:"var(--muted)",fontSize:13},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[e.jsx("span",{style:vn(Ue.bg,Ue.fg),children:ie.status}),e.jsx("strong",{children:j8[ie.platform]??ie.platform}),e.jsxs("span",{style:{color:"var(--muted-foreground)",fontSize:12},children:[ie.kind," · day ",ie.dayOffset," · ",aa(ie.scheduledAt)]})]}),e.jsxs("div",{style:{display:"flex",gap:14,marginTop:10,flexWrap:"wrap"},children:[ie.payload.storagePath&&e.jsxs("div",{style:{flexShrink:0},children:[Oe?e.jsx("video",{src:Oe,controls:!0,preload:"metadata",style:{maxHeight:320,maxWidth:200,borderRadius:6,background:"#000"}}):e.jsx("div",{style:{height:320,width:180,borderRadius:6,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.25)",color:"var(--muted-foreground)",fontSize:12},children:"loading mediaâ¦"}),e.jsx("div",{style:{fontSize:11,color:"var(--muted-foreground)",marginTop:4,maxWidth:200,overflowWrap:"anywhere"},children:ie.payload.storagePath})]}),e.jsx("div",{style:{flex:1,minWidth:260},children:Te?e.jsxs(e.Fragment,{children:[e.jsx("label",{style:Xs,children:"Title"}),e.jsx("input",{value:j.title,onChange:tt=>v({...j,title:tt.target.value}),style:rs}),e.jsx("label",{style:Xs,children:"Description"}),e.jsx("textarea",{value:j.description,rows:5,onChange:tt=>v({...j,description:tt.target.value}),style:{...rs,fontFamily:"inherit"}}),(ie.kind==="text"||ie.kind==="link"||ie.kind==="story"||!!ie.payload.text)&&e.jsxs(e.Fragment,{children:[e.jsx("label",{style:Xs,children:"Post text"}),e.jsx("textarea",{value:j.text,rows:5,onChange:tt=>v({...j,text:tt.target.value}),style:{...rs,fontFamily:"inherit"}})]}),e.jsx("label",{style:Xs,children:"Tags (comma-separated)"}),e.jsx("input",{value:j.tags,onChange:tt=>v({...j,tags:tt.target.value}),style:rs}),e.jsx("label",{style:Xs,children:"Link"}),e.jsx("input",{value:j.link,onChange:tt=>v({...j,link:tt.target.value}),style:rs}),(ie.platform==="youtube"||ie.platform==="linkedin")&&e.jsxs(e.Fragment,{children:[e.jsx("label",{style:Xs,children:ie.platform==="youtube"?"First comment (posted as the channel once the video is public â pin it on the watch page)":"First c
422omment (links go here, not in the body; defaults to the link above)"}),e.jsx("textarea",{value:j.firstComment,rows:3,onChange:tt=>v({...j,firstComment:tt.target.value}),style:{...rs,fontFamily:"inherit"}})]}),ie.platform==="youtube"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{style:Xs,children:["Thumbnail path (jpg/png, relative to the bucket, e.g. content-media/",ie.packId,"/thumbnail.jpg)"]}),e.jsx("input",{value:j.thumbnailPath,onChange:tt=>v({...j,thumbnailPath:tt.target.value}),style:{...rs,fontFamily:"ui-monospace, monospace"}}),e.jsx("label",{style:Xs,children:"Captions path (srt/vtt)"}),e.jsx("input",{value:j.captionsPath,onChange:tt=>v({...j,captionsPath:tt.target.value}),style:{...rs,fontFamily:"ui-monospace, monospace"}})]}),e.jsx("label",{style:Xs,children:"Scheduled time (your timezone)"}),e.jsx("input",{type:"datetime-local",value:j.scheduledAt,onChange:tt=>v({...j,scheduledAt:tt.target.value}),style:rs}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:()=>pe(ie),disabled:x===ie.id,style:zt("#16a34a","#fff"),children:"Save"}),e.jsx("button",{onClick:()=>y(null),style:zt("var(--card)"),children:"Cancel"})]})]}):e.jsxs(e.Fragment,{children:[ie.payload.title&&e.jsx("div",{style:{fontWeight:600},children:ie.payload.title}),ie.payload.description&&e.jsx("pre",{style:{whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:12,color:"var(--muted-foreground)",margin:"6px 0 0",maxHeight:140,overflow:"auto"},children:ie.payload.description}),ie.payload.text&&e.jsx("pre",{style:{whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:12,color:"var(--muted-foreground)",margin:"6px 0 0",maxHeight:140,overflow:"auto"},children:ie.payload.text}),(((Je=ie.payload.tags)==null?void 0:Je.length)??0)>0&&e.jsxs("div",{style:{fontSize:12,color:"var(--muted-foreground)",marginTop:6},children:["tags: ",ie.payload.tags.join(", ")]}),ie.payload.link&&e.jsx("div",{style:{fontSize:12,marginTop:4},children:e.jsx("a",{href:ie.payload.link,target:"_blank",rel:"noreferrer",style:{color:"#0e7490"},children:ie.payload.link})}),ie.payload.firstComment&&e.jsxs("div",{style:{fontSize:12,color:"var(--muted-foreground)",marginTop:6},children:["first comment: ",ie.payload.firstComment,((de=ie.result)==null?void 0:de.firstCommentId)&&e.jsxs("span",{style:{color:"#15803d"},children:[" · posted",ie.platform==="youtube"?" â pin it on the watch page":""]}),!((je=ie.result)!=null&&je.firstCommentId)&&((qe=ie.followup)==null?void 0:qe.pending)&&e.jsx("span",{style:{color:"#a16207"},children:" · posts after the video goes public"})]}),(ie.payload.thumbnailPath||ie.payload.captionsPath)&&e.jsxs("div",{style:{fontSize:11,color:"var(--muted-foreground)",marginTop:4,fontFamily:"ui-monospace, monospace"},children:[ie.payload.thumbnailPath&&e.jsxs("div",{children:["thumbnail: ",ie.payload.thumbnailPath]}),ie.payload.captionsPath&&e.jsxs("div",{children:["captions: ",ie.payload.captionsPath]})]}),((he=ie.result)==null?void 0:he.url)&&e.jsxs("div",{style:{fontSize:12,marginTop:6},children:[e.jsx("a",{href:ie.result.url,target:"_blank",rel:"noreferrer",style:{color:"#0e7490"},children:ie.result.url}),ie.result.publishAt&&` · goes live ${aa(ie.result.publishAt)}`]}),((lt=ie.result)==null?void 0:lt.warning)&&e.jsxs("div",{style:{fontSize:12,color:"#a16207",marginTop:6},children:["â ",ie.result.warning]}),ie.lastError&&e.jsxs("div",{style:{fontSize:12,color:"#b91c1c",marginTop:6},children:[ie.attempts>0&&`attempt ${ie.attempts}: `,ie.lastError]}),He&&e.jsxs("div",{style:{display:"flex",gap:8,marginTop:10},children:[e.jsx("button",{onClick:()=>se(ie),disabled:x===ie.id,style:zt("var(--card)"),children:"Edit"}),ie.status!=="canceled"&&e.jsx("button",{onClick:()=>rt(ie,"cancel"),disabled:x===ie.id,style:zt("var(--card)","#b91c1c"),children:"Skip this post"}),(ie.status==="canceled"||ie.status==="failed")&&e.jsx("button",{onClick:()=>rt(ie,"restore"),disabled:x===ie.id,style:zt("var(--card)","#15803d"),children:ie.status==="failed"?"Retry":"Restore"})]})]})})]})]},ie.id)})]},te.id)})]})}function By(t){return t==null?"":typeof t=="string"?t.toLowerCase():typeof t=="number"||typeof t=="boolean"?String(t).toLowerCase():Array.isArray(t)?t.map(By).filter(
422Boolean).join(" "):""}function T8(t){return t.map(By).filter(Boolean).join(" ")}function A8(t){return t.toLowerCase().split(/\s+/).filter(Boolean)}function E8(t,s){return s.length===0?!0:s.every(n=>t.includes(n))}function Js(t,s){const n=A8(t);return n.length===0?()=>!0:r=>E8(T8(s(r)),n)}let oo=null;const I8=()=>(oo||(oo=Ze(Re(ge,"contacts")).then(t=>t.docs.map(s=>{const n=s.data();return{id:s.id,firstName:n.firstName||"",lastName:n.lastName||"",email:(n.email||"").toLowerCase().trim(),clientIds:n.clientIds||[],isPrimary:n.isPrimary===!0}}).filter(s=>s.email)),oo.catch(()=>{oo=null})),oo),rd=t=>`${t.firstName} ${t.lastName}`.trim(),kl=t=>t>=1e9?`${(t/1e9).toFixed(1)} GB`:t>=1e6?`${(t/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(t/1e3))} KB`,Sl=t=>t&&typeof t.toDate=="function"?t.toDate():null,R8={draft:"text-muted-foreground bg-muted",sent:"text-primary bg-primary/10",partial:"text-amber-600 bg-amber-600/10",complete:"text-green-600 bg-green-600/10",expired:"text-destructive bg-destructive/10"};function dh({status:t}){return e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${R8[t]||"text-muted-foreground bg-muted"}`,children:t})}function ic({text:t}){const[s,n]=l.useState(!1);return e.jsx("button",{type:"button",title:"Copy link",className:"text-muted-foreground hover:text-foreground",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{n(!0),setTimeout(()=>n(!1),1500)})},children:s?e.jsx(kt,{style:{width:16,height:16},className:"text-green-600"}):e.jsx(Hr,{style:{width:16,height:16}})})}function D8({onBack:t,onLogoClick:s}){const[n,r]=l.useState([]),[a,o]=l.useState(""),[i,d]=l.useState("requests"),[m,p]=l.useState(!1),[c,u]=l.useState(null),[x,h]=l.useState([]),[b,f]=l.useState([]),[g,y]=l.useState([]),[j,v]=l.useState([]),[T,k]=l.useState(null),[w,I]=l.useState({}),[A,E]=l.useState("");l.useEffect(()=>{(async()=>{try{const R=(await Ze(Ge(Re(ge,"clients"),Ve("lifecycleStage","==","active")))).docs.map(z=>({id:z.id,name:z.data().companyName||z.data().name||z.id})).sort((z,D)=>z.name.localeCompare(D.name));r(R),await C()}catch(O){u(String(O))}})()},[]);const C=l.useCallback(async()=>{const O=await Ze(Re(ge,"assetRequestTemplates"));f(O.docs.map(R=>({id:R.id,name:R.data().name||R.id,count:Array.isArray(R.data().lineItems)?R.data().lineItems.length:0})))},[]),N=l.useCallback(async()=>{if(a){p(!0),u(null);try{const[O,R,z]=await Promise.all([Ze(Ge(Re(ge,"clientProjects"),Ve("clientId","==",a))),Ze(Ge(Re(ge,"assetRequests"),Ve("clientId","==",a),Nt("createdAt","desc"),Tt(50))),Ze(Ge(Re(ge,"assets"),Ve("clientId","==",a),Nt("createdAt","desc"),Tt(100)))]);k(null),h(O.docs.map(D=>({id:D.id,name:D.data().name||D.id}))),y(R.docs.map(D=>{var $;const L=D.data();return{id:D.id,title:L.title,status:L.status,createdAt:Sl(L.createdAt),dueAt:Sl(L.dueAt),hoursToComplete:(($=L.metrics)==null?void 0:$.hoursToComplete)??null}})),v(z.docs.map(D=>{var $;const L=D.data();return{id:D.id,originalFilename:L.originalFilename,sizeBytes:L.sizeBytes||0,currentVersion:L.currentVersion||1,mimeType:L.mimeType||"",tags:L.tags||[],projectIds:L.projectIds||[],status:L.status||"active",hasThumb:!!L.thumbnailUrl,licenceRequired:!!(($=L.licence)!=null&&$.required)}}))}catch(O){u(String(O))}finally{p(!1)}}},[a]);l.useEffect(()=>{N()},[N]);const S=l.useCallback(async()=>{if(!a)return;const O=await re("intakeListUploadLinks",{clientId:a});k((O==null?void 0:O.links)||[])},[a]);return l.useEffect(()=>{i==="links"&&a&&T===null&&S().catch(O=>u(String(O)))},[i,a,T,S]),l.useEffect(()=>{if(i!=="assets"||!a)return;const O=`${a}:${j.map(z=>z.id).join(",")}`;if(A===O)return;const R=j.filter(z=>z.hasThumb).map(z=>z.id);if(E(O),!R.length){I({});return}re("intakeGetAssetThumbs",{assetIds:R}).then(z=>I((z==null?void 0:z.urls)||{})).catch(()=>{})},[i,a,j,A]),e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-2xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:20,height:20}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Asset Intake"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Requests, incoming assets & upload links"})]}),e.jsx("button",{onClick:N,disabled:m||!a,className:"text-muted-foreground hover:text-foreground p-2",title:"Refresh",children:e.jsx(yt,{style:{width:18,height:18},className:m?"animate-spin":""})})]}),e.jsxs("select",{value:a,onChange:O=>o(O.target.value),className:"bg-card border border-border text-foreground text-sm rounded-lg w-full mb-4",style:{padding:"10px 12px"},children:[e.jsx("option",{value:"",children:"Select a clientâ¦"}),n.map(O=>e.jsx("option",{value:O.id,children:O.name},O.id))]}),c&&e.jsx("p",{className:"text-sm text-destructive mb-3",children:c}),e.jsx("div",{className:"flex gap-1 mb-4 bg-muted rounded-lg p-1",children:["requests","assets","links","templates"].map(O=>e.jsx("button",{onClick:()=>d(O),className:`flex-1 text-sm rounded-md py-2 capitalize font-medium transition-colors ${i===O?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:O==="requests"&&a?`Requests (${g.length})`:O==="assets"&&a?`Assets (${j.length})`:O==="links"&&a?`Links${T?` (${T.length})`:""}`:O},O))}
422),i!=="templates"&&!a&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a client above to see their ",i,"."]}),i==="requests"&&a&&e.jsx(M8,{clientId:a,projects:x,templates:b,requests:g,assets:j,onChanged:N}),i==="assets"&&a&&e.jsx(O8,{clientId:a,assets:j,projects:x,thumbs:w,onChanged:N}),i==="links"&&a&&e.jsx(B8,{clientId:a,links:T,onChanged:S}),i==="templates"&&e.jsx(_8,{onChanged:C})]})]})}function M8({clientId:t,projects:s,templates:n,requests:r,assets:a,onChanged:o}){const[i,d]=l.useState(!1),[m,p]=l.useState(""),[c,u]=l.useState(""),[x,h]=l.useState(""),[b,f]=l.useState(!1),[g,y]=l.useState(null),j=async()=>{f(!0),y(null);try{await re("intakeCreateAssetRequest",{clientId:t,projectId:x,title:m,templateId:c||void 0}),d(!1),p(""),u(""),h(""),o()}catch(v){y(String(v.message||v))}finally{f(!1)}};return e.jsxs("div",{className:"space-y-3",children:[i?e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:"New asset request"}),e.jsx("button",{onClick:()=>d(!1),className:"text-muted-foreground",children:e.jsx(mt,{style:{width:16,height:16}})})]}),e.jsx("input",{value:m,onChange:v=>p(v.target.value),placeholder:"Request title (client-facing)",className:"bg-background border border-border text-foreground text-sm rounded-lg w-full",style:{padding:"8px 10px"}}),e.jsxs("select",{value:c,onChange:v=>u(v.target.value),className:"bg-background border border-border text-foreground text-sm rounded-lg w-full",style:{padding:"8px 10px"},children:[e.jsx("option",{value:"",children:"Checklist templateâ¦"}),n.map(v=>e.jsxs("option",{value:v.id,children:[v.name," (",v.count," items)"]},v.id))]}),e.jsxs("select",{value:x,onChange:v=>h(v.target.value),className:"bg-background border border-border text-foreground text-sm rounded-lg w-full",style:{padding:"8px 10px"},children:[e.jsx("option",{value:"",children:"Projectâ¦"}),s.map(v=>e.jsx("option",{value:v.id,children:v.name},v.id))]}),g&&e.jsx("p",{className:"text-sm text-destructive",children:g}),e.jsx("button",{onClick:j,disabled:b||!m.trim()||!x||!c,className:"bg-primary text-primary-foreground text-sm font-medium rounded-lg w-full py-2 disabled:opacity-50",children:b?e.jsx(fe,{className:"animate-spin inline",style:{width:16,height:16}}):"Create draft"})]}):e.jsxs("button",{onClick:()=>d(!0),className:"flex items-center gap-2 text-sm text-primary font-medium",children:[e.jsx(Ut,{style:{width:16,height:16}})," New asset request"]}),r.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No requests yet for this client."}),r.map(v=>e.jsx(P8,{request:v,clientId:t,assets:a,onChanged:o},v.id))]})}function P8({request:t,clientId:s,assets:n,onChanged:r}){const[a,o]=l.useState(!1),[i,d]=l.useState(null),[m,p]=l.useState(!1),[c,u]=l.useState(null),[x,h]=l.useState(null),[b,f]=l.useState(null),[g,y]=l.useState(null),[j,v]=l.useState(""),[T,k]=l.useState("idle"),w=l.useCallback(async()=>{const N=await Ze(Re(ge,"assetRequests",t.id,"lineItems"));d(N.docs.map(S=>({id:S.id,label:S.data().label,description:S.data().description||"",required:!!S.data().required,status:S.data().status,fulfilledByAssetIds:S.data().fulfilledByAssetIds||[]})))},[t.id]);l.useEffect(()=>{a&&w()},[a,w]),l.useEffect(()=>{!a||t.status==="draft"||g||re("intakeGetRequestLink",{requestId:t.id}).then(N=>y({url:(N==null?void 0:N.url)||null,recipientEmail:(N==null?void 0:N.recipientEmail)||null})).catch(()=>y({url:null,recipientEmail:null}))},[a,t.status,t.id,g]);const I=async()=>{k("sending"),h(null);try{await re("intakeEmailUploadLink",{requestId:t.id,email:j.trim()}),k("sent"),y(N=>N&&{...N,recipientEmail:j.trim().toLowerCase()}),setTimeout(()=>k("idle"),2500)}catch(N){k("idle"),h(String(N.message||N))}},A=async()=>{p(!0),h(null);try{const N=await re("intakeSendAssetRequest",{requestId:t.id});u(N.url),r()}catch(N){h(String(N.message||N))}finally{p(!1)}},E=async(N,S)=>{p(!0);try{const O=N.fulfilledByAssetIds.includes(S)?N.fulfilledByAssetIds.filter(R=>R!==S):[...N.fulfilledByAssetIds,S];await re("intakeAssignLineItem",{requestId:t.id,lineItemId:N.id,assetIds:O}),await w(),r()}catch(O){h(String(O.message||O))}finally{p(!1)}},C=async N=>{p(!0);try{await re("intakeAssignLineItem",{requestId:t.id,lineItemId:N.id,waive:!0}),await w(),r()}catch(S){h(String(S.message||S))}finally{p(!1)}};return e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4",children:[e.jsxs("button",{className:"w-full text-left",onClick:()=>o(!a),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ju,{className:"text-primary flex-shrink-0",style:{width:18,height:18}}),e.jsx("span",{className:"font-medium text-foreground flex-1",children:t.title}),e.jsx(dh,{status:t.status})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[t.createdAt?t.createdAt.toLocaleDateString():"",t.dueAt?` · due ${t.dueAt.toLocaleDateString()}`:"",t.hoursToComplete!=null?` · completed in ${t.hoursToComplete}h`:""]})]}),a&&e.jsxs("div",{className:"mt-3 space-y-2",children:[t.status==="draft"&&e.jsxs("button",{onClick:A,disabled:m,className:"flex items-center gap-2 bg-primary text-primary-foreground text-sm font-medium rounded-lg px-3 py-2 disabled:opacity-50",children:[e.jsx(An,{style:{width:14,height:14}}
422)," Send â create upload link"]}),(c||(g==null?void 0:g.url))&&e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-muted rounded-lg px-3 py-2",children:[e.jsx(lg,{className:"text-primary flex-shrink-0",style:{width:14,height:14}}),e.jsx("span",{className:"flex-1 truncate text-foreground",children:c||(g==null?void 0:g.url)}),e.jsx(ic,{text:c||(g==null?void 0:g.url)})]}),t.status!=="draft"&&e.jsxs("div",{className:"border border-border rounded-lg p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:["Send to customer",(g==null?void 0:g.recipientEmail)&&e.jsxs("span",{className:"font-normal",children:[" · last sent to ",g.recipientEmail]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(L8,{requestId:t.id,clientId:s,value:j,onChange:v}),e.jsxs("button",{onClick:I,disabled:T==="sending"||!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(j.trim()),className:"flex items-center gap-1.5 bg-primary text-primary-foreground text-sm font-medium rounded-lg px-3 disabled:opacity-50",children:[T==="sending"?e.jsx(fe,{className:"animate-spin",style:{width:14,height:14}}):T==="sent"?e.jsx(kt,{style:{width:14,height:14}}):e.jsx(An,{style:{width:14,height:14}}),T==="sent"?"Sent":"Email link"]})]})]}),x&&e.jsx("p",{className:"text-sm text-destructive",children:x}),!i&&e.jsx(fe,{className:"animate-spin text-muted-foreground",style:{width:16,height:16}}),i==null?void 0:i.map(N=>{const S=N.fulfilledByAssetIds.map(R=>{var z;return((z=n.find(D=>D.id===R))==null?void 0:z.originalFilename)||`${R.slice(0,6)}â¦`}),O=b===N.id;return e.jsxs("div",{className:"border border-border rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm text-foreground flex-1",children:[N.label,N.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),e.jsx(dh,{status:N.status==="pending"?"sent":N.status==="fulfilled"?"complete":"draft"}),N.status==="pending"&&e.jsx("button",{onClick:()=>C(N),disabled:m,title:"Waive",className:"text-muted-foreground hover:text-foreground",children:e.jsx(hu,{style:{width:14,height:14}})})]}),N.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:N.description}),S.length>0&&e.jsxs("p",{className:"text-xs mt-1.5",children:[e.jsx("span",{className:"text-green-600 font-medium",children:"Fulfilled by:"})," ",e.jsx("span",{className:"text-foreground",children:S.join(", ")})]}),e.jsx("button",{onClick:()=>f(O?null:N.id),className:"text-xs text-primary font-medium mt-2",children:O?"Close":N.fulfilledByAssetIds.length?"Change filesâ¦":"+ Assign files"}),O&&e.jsxs("div",{className:"mt-2 border border-border rounded-lg p-2 space-y-1 bg-background",style:{maxHeight:180,overflowY:"auto"},children:[n.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No uploads from this client yet â files appear here once they land."}),n.map(R=>e.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground py-0.5",children:[e.jsx("input",{type:"checkbox",checked:N.fulfilledByAssetIds.includes(R.id),onChange:()=>E(N,R.id),disabled:m}),e.jsx("span",{className:"truncate",children:R.originalFilename}),e.jsx("span",{className:"text-muted-foreground flex-shrink-0",children:kl(R.sizeBytes)})]},R.id))]})]},N.id)})]})]})}function L8({requestId:t,clientId:s,value:n,onChange:r}){const[a,o]=l.useState(null),[i,d]=l.useState(!1),[m,p]=l.useState(0),c=l.useRef(null),u=`contact-listbox-${t}`,x=n.trim(),h=l.useMemo(()=>{if(!a)return[];const j=k=>k.clientIds.includes(s),v=(k,w)=>rd(k).localeCompare(rd(w));if(x.length===0)return a.filter(j).sort((k,w)=>Number(w.isPrimary)-Number(k.isPrimary)||v(k,w));if(x.length<2)return[];const T=Js(x,k=>[k.firstName,k.lastName,k.email]);return a.filter(T).sort((k,w)=>Number(j(w))-Number(j(k))||Number(w.isPrimary)-Number(k.isPrimary)||v(k,w))},[a,x,s]),b=l.useMemo(()=>h.slice(0,6),[h]),f=i&&(a===null?x.length!==1:b.length>0),g=b.map(j=>j.id).join(",");l.useEffect(()=>{p(0)},[g]);const y=j=>{var v;r(j.email),d(!1),(v=c.current)==null||v.focus()};return e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{ref:c,value:n,onChange:j=>{r(j.target.value),d(!0)},onFocus:()=>{d(!0),I8().then(o).catch(()=>o([]))},onBlur:()=>d(!1),onKeyDown:j=>{if(j.key==="Escape"){d(!1);return}!f||b.length===0||(j.key==="ArrowDown"?(j.preventDefault(),p(v=>(v+1)%b.length)):j.key==="ArrowUp"?(j.preventDefault(),p(v=>(v-1+b.length)%b.length)):j.key==="Enter"&&(j.preventDefault(),y(b[m])))},placeholder:"[email protected]",type:"email",autoComplete:"off",role:"combobox","aria-expanded":f,"aria-autocomplete":"list","aria-controls":u,className:"bg-background border border-border text-foreground text-sm rounded-lg w-full",style:{padding:"7px 10px"}}),f&&e.jsx("div",{id:u,role:"listbox",className:"absolute left-0 right-0 z-10 bg-card border border-border rounded-lg overflow-hidden shadow-lg mt-1",style:{to
422p:"100%"},onMouseDown:j=>j.preventDefault(),children:a===null?e.jsx("div",{className:"text-xs text-muted-foreground px-3 py-2",children:"Loading contactsâ¦"}):b.map((j,v)=>e.jsxs("button",{type:"button",role:"option","aria-selected":v===m,onClick:()=>y(j),className:`w-full text-left px-3 py-2 flex items-center gap-2 hover:bg-muted ${v===m?"bg-muted":""}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-foreground truncate",children:rd(j)||j.email}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:j.email})]}),j.clientIds.includes(s)&&e.jsx("span",{className:"text-xs text-primary font-medium flex-shrink-0",children:"This client"})]},j.id))})]})}function z8({clientId:t,assets:s,onClose:n}){const[r,a]=l.useState(()=>new Set(s.map(v=>v.id))),[o,i]=l.useState(""),[d,m]=l.useState(""),[p,c]=l.useState("30"),[u,x]=l.useState(!1),[h,b]=l.useState(null),[f,g]=l.useState(null),y=v=>a(T=>{const k=new Set(T);return k.has(v)?k.delete(v):k.add(v),k}),j=async()=>{if(!(u||r.size===0)){x(!0),b(null);try{const v=p==="never"?null:Date.now()+Number(p)*24*60*60*1e3,T=await re("intakeCreateShareLink",{clientId:t,assetIds:[...r],title:o.trim()||void 0,message:d.trim()||void 0,expiresAtMs:v});g(T==null?void 0:T.url)}catch(v){b(String(v.message||v))}finally{x(!1)}}};return e.jsx("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.45)",zIndex:60,display:"flex",alignItems:"center",justifyContent:"center",padding:16},onClick:n,children:e.jsx("div",{className:"bg-card border border-border rounded-lg",style:{width:480,maxWidth:"100%",maxHeight:"85vh",overflowY:"auto",padding:16},onClick:v=>v.stopPropagation(),children:f?e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Share link ready"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Anyone with this link can download the ",r.size," selected file",r.size===1?"":"s"," â no login needed. Paste it into an email or Slack."]}),e.jsxs("div",{className:"flex items-center gap-2 bg-background border border-border rounded-lg",style:{padding:"8px 10px"},children:[e.jsx("span",{className:"text-sm text-foreground flex-1 truncate",children:f}),e.jsx(ic,{text:f})]}),e.jsx("button",{onClick:n,className:"text-sm text-primary font-medium",children:"Done"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Share files with a public link"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Title (shown on the page)"}),e.jsx("input",{value:o,onChange:v=>i(v.target.value),placeholder:"e.g. Homepage design assets",className:"bg-background border border-border text-foreground text-sm rounded-lg w-full",style:{padding:"8px 10px"}})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Note to the recipient (optional)"}),e.jsx("textarea",{value:d,onChange:v=>m(v.target.value),rows:2,className:"bg-background border border-border text-foreground text-sm rounded-lg w-full",style:{padding:"8px 10px",resize:"vertical"}})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Link expires"}),e.jsxs("select",{value:p,onChange:v=>c(v.target.value),className:"bg-background border border-border text-foreground text-sm rounded-lg",style:{padding:"8px 10px"},children:[e.jsx("option",{value:"7",children:"in 7 days"}),e.jsx("option",{value:"30",children:"in 30 days"}),e.jsx("option",{value:"never",children:"never (until revoked)"})]})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:["Files (",r.size," of ",s.length," selected)"]}),e.jsx("div",{className:"border border-border rounded-lg",style:{maxHeight:220,overflowY:"auto"},children:s.map(v=>e.jsxs("label",{className:"flex items-center gap-2 text-sm text-foreground hover:bg-accent/50 cursor-pointer",style:{padding:"6px 10px"},children:[e.jsx("input",{type:"checkbox",checked:r.has(v.id),onChange:()=>y(v.id)}),e.jsx("span",{className:"flex-1 truncate",children:v.originalFilename}),e.jsx("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:kl(v.sizeBytes)})]},v.id))})]}),h&&e.jsx("p",{className:"text-sm text-destructive",children:h}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:j,disabled:u||r.size===0,className:"flex items-center gap-1 text-sm text-primary font-medium",children:[u?e.jsx(fe,{className:"animate-spin",style:{width:14,height:14}}):e.jsx(wu,{style:{width:14,height:14}}),"Create link"]}),e.jsx("button",{onClick:n,className:"text-sm text-muted-foreground hover:text-foreground",children:"Cancel"})]})]})})})}function O8({clientId:t,assets:s,projects:n,thumbs:r,onChanged:a}){const[o,i]=l.useState(""),[d,m]=l.useState([]),[p,c]=l.useState(!1),[u,x]=l.useState(!1),[h,b]=l.useState(null),[f,g]=l.useState(!1),y=l.useMemo(()=>o?s.filter(k=>k.projectIds.includes(o)):s,[s,o]),j=l.useMemo(()=>y.filter(k=>k.status!=="archived"),[y]),v=async()=>
422{if(!(u||j.length===0)){x(!0),b(null);try{const k=await re("intakeZipAssets",{assetIds:j.map(w=>w.id)});k!=null&&k.url&&window.open(k.url,"_blank")}catch(k){b(String(k.message||k))}finally{x(!1)}}},T=async k=>{if(!(!k.length||p)){c(!0),m(k.map(w=>({name:w.name,state:{phase:"queued"}})));try{const{sessionId:w}=await re("intakeCreateStaffSession",{clientId:t}),I=k.map(C=>({file:C,relativePath:null})),E=(await Cv(w,I,3,(C,N)=>m(S=>S.map((O,R)=>R===C?{...O,state:N}:O)))).filter(C=>!!C);E.length&&await Tv(w,E),setTimeout(()=>{a(),m([])},4e3)}catch(w){m(I=>I.map(A=>({...A,state:{phase:"error",message:String(w.message||w)}})))}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-primary font-medium cursor-pointer",children:[e.jsx(Ut,{style:{width:16,height:16}})," Upload files for this client",e.jsx("input",{type:"file",multiple:!0,hidden:!0,disabled:p,onChange:k=>{T(Array.from(k.target.files||[])),k.target.value=""}})]}),d.length>0&&e.jsx("div",{className:"bg-card border border-border rounded-lg p-3 space-y-1",children:d.map((k,w)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-foreground",children:[e.jsx("span",{className:"flex-1 truncate",children:k.name}),e.jsxs("span",{className:"text-muted-foreground",children:[k.state.phase==="queued"&&"Waiting",k.state.phase==="hashing"&&"Preparing",k.state.phase==="uploading"&&`${Math.round(k.state.progress*100)}%`,k.state.phase==="done"&&"Processingâ¦",k.state.phase==="error"&&e.jsx("span",{className:"text-destructive",children:k.state.message})]})]},w))}),e.jsxs("div",{className:"flex items-center gap-2",children:[n.length>0&&e.jsxs("select",{value:o,onChange:k=>i(k.target.value),className:"bg-card border border-border text-foreground text-sm rounded-lg flex-1",style:{padding:"8px 10px"},children:[e.jsx("option",{value:"",children:"All projects"}),n.map(k=>e.jsx("option",{value:k.id,children:k.name},k.id))]}),j.length>0&&e.jsxs("button",{onClick:v,disabled:u,title:"Download everything listed as one zip",className:"flex items-center gap-1 text-xs text-primary font-medium whitespace-nowrap border border-border rounded-lg bg-card",style:{padding:"8px 10px"},children:[e.jsx(zr,{style:{width:14,height:14}}),u?"Zippingâ¦":`Download all (${j.length})`]}),j.length>0&&e.jsxs("button",{onClick:()=>g(!0),title:"Create a public download link for a customer",className:"flex items-center gap-1 text-xs text-primary font-medium whitespace-nowrap border border-border rounded-lg bg-card",style:{padding:"8px 10px"},children:[e.jsx(wu,{style:{width:14,height:14}})," Shareâ¦"]})]}),f&&e.jsx(z8,{clientId:t,assets:j,onClose:()=>g(!1)}),h&&e.jsx("p",{className:"text-sm text-destructive",children:h}),y.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No assets yet for this client."}),y.map(k=>e.jsx($8,{asset:k,thumbUrl:r[k.id]||null,projects:n,allAssets:s,onChanged:a},k.id))]})}function $8({asset:t,thumbUrl:s,projects:n,allAssets:r,onChanged:a}){const[o,i]=l.useState(!1),d=s,[m,p]=l.useState(!1),[c,u]=l.useState(null),[x,h]=l.useState(t.tags.join(", ")),[b,f]=l.useState(null),[g,y]=l.useState(null),[j,v]=l.useState(""),[T,k]=l.useState(""),w=async(C,N=!0)=>{p(!0),u(null);try{await C(),N&&a()}catch(S){u(String(S.message||S))}finally{p(!1)}},I=()=>Ze(Re(ge,"assets",t.id,"versions")).then(C=>f(C.docs.map(N=>({n:Number(N.id),sizeBytes:N.data().sizeBytes||0,uploadedAt:Sl(N.data().uploadedAt),superseded:!!N.data().supersededAt})).sort((N,S)=>S.n-N.n))),A=()=>Ze(Ge(Re(ge,"assets",t.id,"comments"),Nt("createdAt","asc"))).then(C=>y(C.docs.map(N=>{var S;return{id:N.id,body:N.data().body,authorUid:N.data().authorUid||null,uploaderName:((S=N.data().uploaderIdentity)==null?void 0:S.name)||null,createdAt:Sl(N.data().createdAt)}}))),E=()=>w(async()=>{const C=await re("intakeGetAssetUrl",{assetId:t.id,variant:"original",download:!0});C!=null&&C.url&&window.open(C.url,"_blank")},!1);return e.jsxs("div",{className:`bg-card border border-border rounded-lg p-3 ${t.status==="archived"?"opacity-60":""}`,children:[e.jsxs("button",{className:"w-full text-left flex items-center gap-3",onClick:()=>i(!o),children:[e.jsx("div",{className:"flex-shrink-0 bg-muted rounded-lg flex items-center justify-center overflow-hidden",style:{width:48,height:48},children:d?e.jsx("img",{src:d,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):e.jsx(ig,{className:"text-muted-foreground",style:{width:20,height:20}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:t.originalFilename}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[kl(t.sizeBytes)," · v",t.currentVersion,t.licenceRequired?" · licence":"",t.status==="archived"?" · archived":""]}),t.tags.length>0&&e.jsx("p",{className:"text-xs text-primary truncate",children:t.tags.map(C=>`#${C}`).join(" ")})]})]}),o&&e.jsxs("div",{className:"mt-3 space-y-3",children:[c&&e.jsx("p",{className:"text-sm text-destructive",children:c}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:E,disabled:m,title:"Download original",className:"flex items-center gap-1 text-xs text-primary font-medium",children:[e.jsx(zr,{style:{width:14,height:14}})," Original"]}),e.jsxs("button",{onClick:()=>w(()=>re("intakeArchiveAsset",{assetId:t.id,archived:t.status!=="archived"})),disabled:m,className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(Aw,{style:{width:14,height:14}})," ",t.status==="archived"?"Restore":"Archive"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Tags (comma-separated)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:x,onChange:C=>h(C.target.value),className:"bg-background border border-border text-foreground text-sm rounded-lg flex-1",style:{padding:"6px 10px"}}),e.jsx("button",{onClick:()=>w(()=>re("intakeUpdateAssetTags",{assetId:t.id,tags:x.split(",").map(C=>
422C.trim()).filter(Boolean)})),disabled:m,className:"text-xs text-primary font-medium",children:"Save"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Projects"}),n.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No projects for this client."}),n.map(C=>e.jsxs("label",{className:"flex items-center gap-2 text-xs text-foreground py-0.5",children:[e.jsx("input",{type:"checkbox",checked:t.projectIds.includes(C.id),disabled:m,onChange:()=>{const N=t.projectIds.includes(C.id)?t.projectIds.filter(S=>S!==C.id):[...t.projectIds,C.id];w(()=>re("intakeAssignAssetProjects",{assetId:t.id,projectIds:N}))}}),C.name]},C.id))]}),e.jsxs("details",{onToggle:C=>{C.target.open&&!b&&I()},children:[e.jsxs("summary",{className:"text-xs text-primary cursor-pointer flex items-center gap-1",children:[e.jsx(og,{style:{width:14,height:14}})," Versions"]}),e.jsxs("div",{className:"mt-2 space-y-1",children:[!b&&e.jsx(fe,{className:"animate-spin text-muted-foreground",style:{width:14,height:14}}),b==null?void 0:b.map(C=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-foreground",children:[e.jsxs("span",{className:C.superseded?"text-muted-foreground":"font-medium",children:["v",C.n," · ",kl(C.sizeBytes),C.uploadedAt?` · ${C.uploadedAt.toLocaleDateString()}`:"",C.superseded?" (superseded)":" (current)"]}),((b==null?void 0:b.length)||0)>1&&e.jsx("button",{onClick:()=>w(async()=>{await re("intakeSplitVersion",{assetId:t.id,version:C.n}),f(null)}),disabled:m,className:"text-primary",title:"Split into its own asset",children:"split"})]},C.n)),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("select",{value:T,onChange:C=>k(C.target.value),className:"bg-background border border-border text-foreground text-xs rounded-lg flex-1",style:{padding:"4px 8px"},children:[e.jsx("option",{value:"",children:"Merge this asset intoâ¦"}),r.filter(C=>C.id!==t.id&&C.status==="active").map(C=>e.jsxs("option",{value:C.id,children:[C.originalFilename," (v",C.currentVersion,")"]},C.id))]}),e.jsx("button",{onClick:()=>T&&w(()=>re("intakeMergeAssets",{sourceAssetId:t.id,targetAssetId:T})),disabled:m||!T,className:"text-xs text-primary font-medium",children:"Merge"})]})]})]}),e.jsxs("details",{onToggle:C=>{C.target.open&&!g&&A()},children:[e.jsxs("summary",{className:"text-xs text-primary cursor-pointer flex items-center gap-1",children:[e.jsx(mn,{style:{width:14,height:14}})," Comments"]}),e.jsxs("div",{className:"mt-2 space-y-2",children:[g==null?void 0:g.map(C=>e.jsxs("div",{className:"text-xs text-foreground bg-muted rounded-lg px-2 py-1.5",children:[e.jsx("p",{children:C.body}),e.jsxs("p",{className:"text-muted-foreground mt-0.5",children:[C.uploaderName?`${C.uploaderName} (uploader)`:"Staff",C.createdAt?` · ${C.createdAt.toLocaleDateString()}`:""]})]},C.id)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:j,onChange:C=>v(C.target.value),placeholder:"Add a commentâ¦",className:"bg-background border border-border text-foreground text-xs rounded-lg flex-1",style:{padding:"6px 10px"}}),e.jsx("button",{onClick:()=>j.trim()&&w(async()=>{await re("intakeAddAssetComment",{assetId:t.id,body:j.trim()}),v(""),y(null),await A()},!1),disabled:m||!j.trim(),className:"text-xs text-primary font-medium",children:"Post"})]})]})]})]})]})}function B8({clientId:t,links:s,onChanged:n}){const[r,a]=l.useState(!1),[o,i]=l.useState(null),d=async()=>{a(!0),i(null);try{await re("intakeCreateUploadLink",{clientId:t,type:"open"}),n()}catch(p){i(String(p.message||p))}finally{a(!1)}},m=async p=>{a(!0);try{await re("intakeRevokeUploadLink",{linkId:p}),n()}catch(c){i(String(c.message||c))}finally{a(!1)}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("button",{onClick:d,disabled:r,className:"flex items-center gap-2 text-sm text-primary font-medium",children:[e.jsx(Ut,{style:{width:16,height:16}})," New drop-box link (no checklist)"]}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),s===null&&e.jsx(fe,{className:"animate-spin text-muted-foreground",style:{width:16,height:16}}),(s==null?void 0:s.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No upload links for this client."}),s==null?void 0:s.map(p=>e.jsxs("div",{className:`bg-card border border-border rounded-lg p-3 ${p.revoked?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lg,{className:"text-primary flex-shrink-0",style:{width:16,height:16}}),e.jsx("span",{className:"text-sm text-foreground flex-1 truncate",children:p.url}),e.jsx(ic,{text:p.url}),!p.revoked&&e.jsx("button",{onClick:()=>m(p.linkId),disabled:r,title:"Revoke",className:"text-muted-foreground hover:text-destructive",children:e.jsx(hu,{style:{width:16,height:16}})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[p.type,p.boundEmail?` · ${p.boundEmail}`:"",p.requestTitle?` · for â${p.requestTitle}â`:p.requestId?" · request-linked":" · free-form drop-box",` · ${p.sessionCount} session${p.sessionCount===1?"":"s"}`,p.revoked?" · REVOKED":""]})]},p.linkId)),e.jsx(F8,{clientId:t})]})}function F8({clientId:t}){const[s,n]=l.useState(null),[r,a]=l.useState(!1),[o,i]=l.useState(null),d=l.useCallback(async()=>{try{const p=await re("intakeListShareLinks",{clientId:t});n((p==null?void 0:p.shares)||[])}catch(p){i(String(p.message||p)),n([])}},[t]);l.useEffect(()=>{n(null),d()},[d]);const m=async p=>{a(!0),i(null);try{await re("intakeRevokeShareLink",{shareId:p}),await d()}catch(c){i(String(c.message||c))}finally{a(!1)}};return e.jsxs("div",{className:"space-y-3",style:{marginTop:16},children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Share links (customer downloads)"}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),s===null&&e.jsx(fe,{className:"animate-spin text-muted-foreground",style:{width:16,height:16}}),(s==null?void 0:s.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No share links yet â create one from the Assets tab (Shareâ¦)."}),s==null?void 0:s.map(p=>e.jsxs("div",{className:`bg-card border border-border rounded-lg p-3 ${p.revoked?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wu,{className:"text-primary flex-shrink-0",style:{width:16,height:16}}),e.jsx("span",{className:"text-sm text-foreground flex-1 truncate",children:p.url}),e.jsx(ic,{text:p.url}),!p.revoked&&e.jsx("button",{onClick:()=>m(p.shareId),disabled:r,title:"Revoke",className:"text-muted-foreground hover:text-destructive",children:e.jsx(hu,{style:{width:16,height:16}})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[p.title?`â${p.title}â · `:"",p.fileCount," file",p.fileCount===1?"":"s",` · ${p.openCount} open${p.openCount===1?"":"s"}`,p.expiresAt?` · expires ${new Date(p.expiresAt).toLocaleDateString()}`:" · no expiry",p.revoked?" · REVOKED":""]})]},p.shareId))]})}const uh={label:"",description:"",required:!0,acceptedTypes:[],requiresLicence:!1};function _8({onChanged:t}){const[s,n]=l.useState(null),[r,a]=l.useState(null),[o,i]=l.useState(!1),[d,m]=l.useState(null),[p,
422c]=l.useState(!1),u=l.useCallback(async()=>{const f=await Ze(Re(ge,"assetRequestTemplates"));n(f.docs.map(g=>({id:g.id,name:g.data().name||g.id,description:g.data().description||"",lineItems:(g.data().lineItems||[]).map(y=>({label:y.label||"",description:y.description||"",required:y.required!==!1,acceptedTypes:y.acceptedTypes||[],requiresLicence:y.requiresLicence===!0}))})).sort((g,y)=>g.name.localeCompare(y.name)))},[]);l.useEffect(()=>{u()},[u]);const x=(f,g)=>{a(y=>y&&{...y,lineItems:y.lineItems.map((j,v)=>v===f?{...j,...g}:j)})},h=async()=>{if(!r)return;const f=r.lineItems.map(g=>({...g,label:g.label.trim()})).filter(g=>g.label);if(!r.name.trim()||f.length===0){m("A template needs a name and at least one line item.");return}i(!0),m(null);try{const g={name:r.name.trim(),description:r.description.trim(),lineItems:f,updatedAt:ss(),updatedBy:"admin-ui"};r.id?await qr(ut(ge,"assetRequestTemplates",r.id),g,{merge:!0}):await Ma(Re(ge,"assetRequestTemplates"),{...g,createdAt:ss()}),a(null),await u(),t()}catch(g){m(String(g.message||g))}finally{i(!1)}},b=async()=>{if(r!=null&&r.id){i(!0);try{await ru(ut(ge,"assetRequestTemplates",r.id)),a(null),c(!1),await u(),t()}finally{i(!1)}}};return r?e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:r.id?"Edit template":"New template"}),e.jsx("button",{onClick:()=>{a(null),c(!1)},className:"text-muted-foreground",children:e.jsx(mt,{style:{width:16,height:16}})})]}),e.jsx("input",{value:r.name,onChange:f=>a(g=>g&&{...g,name:f.target.value}),placeholder:"Template name",className:"bg-background border border-border text-foreground text-sm rounded-lg w-full",style:{padding:"8px 10px"}}),e.jsx("input",{value:r.description,onChange:f=>a(g=>g&&{...g,description:f.target.value}),placeholder:"One-line description",className:"bg-background border border-border text-foreground text-sm rounded-lg w-full",style:{padding:"8px 10px"}}),r.lineItems.map((f,g)=>e.jsxs("div",{className:"border border-border rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{value:f.label,onChange:y=>x(g,{label:y.target.value}),placeholder:"Item label (client-facing)",className:"bg-background border border-border text-foreground text-sm rounded-lg flex-1",style:{padding:"6px 10px"}}),e.jsx("button",{onClick:()=>a(y=>y&&{...y,lineItems:y.lineItems.filter((j,v)=>v!==g)}),className:"text-muted-foreground hover:text-destructive",title:"Remove item",children:e.jsx(mt,{style:{width:14,height:14}})})]}),e.jsx("input",{value:f.description,onChange:y=>x(g,{description:y.target.value}),placeholder:"Helper text shown under the item (optional)",className:"bg-background border border-border text-foreground text-xs rounded-lg w-full",style:{padding:"6px 10px"}}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("input",{value:f.acceptedTypes.join(", "),onChange:y=>x(g,{acceptedTypes:y.target.value.split(",").map(j=>j.trim().toLowerCase().replace(/^\./,"")).filter(Boolean)}),placeholder:"File types e.g. svg, ai, png",className:"bg-background border border-border text-foreground text-xs rounded-lg",style:{padding:"6px 10px",width:180}}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-foreground",children:[e.jsx("input",{type:"checkbox",checked:f.required,onChange:y=>x(g,{required:y.target.checked})}),"Required"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-foreground",children:[e.jsx("input",{type:"checkbox",checked:f.requiresLicence,onChange:y=>x(g,{requiresLicence:y.target.checked})}),"Licence details"]})]})]},g)),e.jsxs("button",{onClick:()=>a(f=>f&&{...f,lineItems:[...f.lineItems,{...uh}]}),className:"flex items-center gap-2 text-sm text-primary font-medium",children:[e.jsx(Ut,{style:{width:14,height:14}})," Add line item"]}),d&&e.jsx("p",{className:"text-sm text-destructive",children:d}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:h,disabled:o,className:"bg-primary text-primary-foreground text-sm font-medium rounded-lg px-4 py-2 disabled:opacity-50",children:o?e.jsx(fe,{className:"animate-spin inline",style:{width:14,height:14}}):"Save template"}),r.id&&e.jsx("button",{onClick:()=>p?b():c(!0),disabled:o,className:`text-sm ${p?"text-destructive font-semibold":"text-muted-foreground"}`,children:p?"Really delete? Click again":"Delete template"})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>a({id:"",name:"",description:"",lineItems:[{...uh}]}),className:"flex items-center gap-2 text-sm text-primary font-medium",children:[e.jsx(Ut,{style:{width:16,height:16}})," New template"]}),s===null&&e.jsx(fe,{className:"animate-spin text-muted-foreground",style:{width:16,height:16}}),(s==null?void 0:s.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No templates yet."}),s==null?void 0:s.map(f=>e.jsxs("button",{onClick:()=>{a({...f,lineItems:f.lineItems.map(g=>({...g}))}),c(!1)},className:"bg-card border border-border rounded-lg p-4 w-full text-left hover:bg-accent transition-colors",children:[e.jsx("p",{className:"font-medium text-foreground",children:f.name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[f.lineItems.length," item",f.lineItems.length===1?"":"s",f.description?` · ${f.description}`:""]})]},f.id))]})}function W8({onBack:t}){var M,F,W,_,G;const s=El(!0),n=((M=s.access)==null?void 0:M.accounts)??[],[r,a]=l.useState(null),[o,i]=l.useState(""),[d,m]=l.useState(null),[p,
422c]=l.useState(null),[u,x]=l.useState(!1),[h,b]=l.useState(""),[f,g]=l.useState([]),[y,j]=l.useState([]),[v,T]=l.useState(null),[k,w]=l.useState(null),[I,A]=l.useState(null),[E,C]=l.useState(null),[N,S]=l.useState(null);l.useEffect(()=>{A(null),S(null)},[r]);const O=async B=>{C("preflight"),S(null),w(null);try{A(await re("chatCutoverPreflight",{clientId:B},void 0,{timeoutMs:12e4}))}catch(Y){w(String(Y.message??Y))}finally{C(null)}},R=async(B,Y,J)=>{const H=Y==="bridge"?`Turn the Slack bridge on for ${(L==null?void 0:L.name)??B}? Their app goes native, and their Slack channel keeps working in both directions. This imports the Slack delta first.`:`Flip ${(L==null?void 0:L.name)??B} to native chat? This imports the Slack delta and posts the moved notice in their channels.`;if(window.confirm(H)){C("flip"),w(null);try{const Z=await re("chatCutoverFlip",{clientId:B,target:Y,force:J},void 0,{timeoutMs:54e4}),Q=Z.deltas.map(K=>`#${K.handle} +${K.imported} msgs/${K.files} files${K.error?` (${K.error})`:""}`).join(", ")||"none needed";S(Y==="bridge"?`Bridge on. Delta: ${Q}. Slack channels keep working â no moved notice posted.`:`Flipped. Delta: ${Q}. Notices: ${Z.notices.filter(K=>K.posted).length}/${Z.notices.length} posted.`),A(null),s.refresh()}catch(Z){w(String(Z.message??Z))}finally{C(null)}}},z=async(B,Y)=>{const J=Y==="bridge"?"Step this client back to bridge mode? Their app stays native and their Slack channel starts mirroring again.":"Revert this client to Slack? Nothing is deleted; their app goes back to the Slack-era chat.";if(window.confirm(J)){C("revert"),w(null);try{await re("chatCutoverRevert",{clientId:B,to:Y}),S(Y==="bridge"?"Back to bridge mode.":"Reverted to Slack."),A(null),s.refresh()}catch(H){w(String(H.message??H))}finally{C(null)}}},D=l.useMemo(()=>new Map(n.map(B=>[B.id,B])),[n]),L=r?D.get(r)??null:null,$=async(B,Y)=>{const J=D.get(B),H=D.get(Y);if(!(!J||!H||J.parentId===Y)&&window.confirm(`Move ${J.name} under ${H.name}? Everyone who manages ${H.name} will see it, and its own subtree moves with it.`)){T(B),w(null),m(null);try{await re("chatMoveAccount",{accountId:B,parentId:Y}),m(`${J.name} now sits under ${H.name}.`),await s.refresh()}catch(Z){w(String(Z.message??Z))}finally{T(null)}}},q=l.useCallback(async B=>{c(null);try{const Y=await re("chatListMembers",{accountId:B});c(Y.members),x(!!Y.canAdminister)}catch(Y){w(Y instanceof Error?Y.message:"Could not load members")}},[]),P=l.useCallback(async()=>{var B;if((B=s.access)!=null&&B.isAdmin)try{const Y=await re("chatListJoinRequests",{});j(Y.requests)}catch{}},[(F=s.access)==null?void 0:F.isAdmin]);l.useEffect(()=>{r&&q(r)},[r,q]),l.useEffect(()=>{P()},[P]),l.useEffect(()=>{if(h.trim().length<2){g([]);return}const B=setTimeout(async()=>{try{g((await re("chatSearchProfiles",{query:h,accountId:r??void 0})).profiles)}catch{g([])}},250);return()=>clearTimeout(B)},[h,r]);const U=async(B,Y,J)=>{if(r){T(B),w(null);try{await re("chatSetMembership",{accountId:r,profileId:B,role:Y,...J??{}}),await q(r),await P(),b("")}catch(H){w(H instanceof Error?H.message:"Change failed")}finally{T(null)}}},V=async(B,Y,J)=>{T(B);try{await re("chatDecideJoinRequest",{profileId:B,decision:Y,accountId:J,role:"member"}),await P(),J&&J===r&&await q(J)}catch(H){w(H instanceof Error?H.message:"Decision failed")}finally{T(null)}};return e.jsx("div",{className:"min-h-screen bg-background pb-24",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground","aria-label":"Back",children:e.jsx(dt,{size:20})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Chat Accounts"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"The account tree and who can see which lanes. Members see their node only; managers see everything beneath it."})]})]}),s.error&&e.jsx("p",{className:"text-sm text-destructive mb-3",children:s.error}),k&&e.jsx("p",{className:"text-sm text-destructive mb-3",children:k}),d&&e.jsx("p",{className:"text-sm text-foreground mb-3",children:d}),((W=s.access)==null?void 0:W.isAdmin)&&y.length>0&&e.jsxs("div",{className:"bg-card border border-border rounded-lg mb-4",style:{padding:12},children:[e.jsxs("div",{className:"font-medium text-foreground",style:{marginBottom:8},children:["Waiting to be placed (",y.length,")"]}),y.map(B=>e.jsxs("div",{className:"border-t border-border",style:{padding:"8px 0",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[e.jsxs("div",{style:{flex:1,minWidth:200},children:[e.jsx("div",{className:"text-foreground",style:{fontSize:14},children:B.fullName||B.email}),e.jsxs("div",{className:"text-muted-foreground",style:{fontSize:12},children:[B.email,B.shop?` · ${B.shop}`:""]})]}),B.suggested.map(Y=>e.jsxs("button",{disabled:v===B.profileId,onClick:()=>V(B.profileId,"approve",Y.id),className:"bg-primary text-primary-foreground rounded-md",style:{padding:"4px 10px",fontSize:13},children:["Add to ",Y.name]}
422,Y.id)),e.jsx("button",{disabled:v===B.profileId,onClick:()=>{a(r),b(B.email)},className:"border border-border text-foreground rounded-md",style:{padding:"4px 10px",fontSize:13},children:"Pick nodeâ¦"}),e.jsx("button",{disabled:v===B.profileId,onClick:()=>V(B.profileId,"dismiss"),className:"text-muted-foreground",style:{fontSize:13},children:"Dismiss"})]},B.profileId))]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(260px, 1fr) 2fr",gap:16},children:[e.jsxs("div",{className:"bg-card border border-border rounded-lg",style:{padding:8,maxHeight:"70vh",overflow:"auto"},children:[e.jsxs("div",{style:{position:"relative",marginBottom:8},children:[e.jsx(Pt,{size:14,className:"text-muted-foreground",style:{position:"absolute",left:10,top:11}}),e.jsx("input",{value:o,onChange:B=>i(B.target.value),placeholder:"Find an accountâ¦",className:"bg-background border border-border text-foreground rounded-md w-full",style:{padding:"8px 8px 8px 30px",fontSize:14}})]}),s.loading?e.jsx("p",{className:"text-sm text-muted-foreground",style:{padding:8},children:"Loading treeâ¦"}):e.jsx(zy,{accounts:n,selectedId:r,onSelect:a,filter:o,dnd:(_=s.access)!=null&&_.isAdmin?{mode:"move",onDrop:$}:void 0}),((G=s.access)==null?void 0:G.isAdmin)&&!s.loading&&e.jsx("p",{className:"text-muted-foreground",style:{fontSize:11,padding:"6px 8px 0"},children:"Drag a lane by its handle onto another lane to move it there."})]}),e.jsx("div",{className:"bg-card border border-border rounded-lg",style:{padding:16},children:L?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:12},children:[e.jsxs("div",{className:"text-lg font-semibold text-foreground",children:[L.name," ",e.jsxs("span",{className:"text-muted-foreground",style:{fontSize:13,fontWeight:400},children:["#",L.handle]})]}),e.jsxs("div",{className:"text-muted-foreground",style:{fontSize:12},children:[L.path.map(B=>{var Y;return((Y=D.get(B))==null?void 0:Y.name)??B}).join(" ⺠")||"root",L.archived?" · archived":""]})]}),u&&L.clientId&&e.jsxs("div",{className:"bg-background border border-border rounded-md",style:{padding:12,marginBottom:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[e.jsx(dN,{size:14,className:"text-muted-foreground"}),e.jsx("span",{className:"text-foreground",style:{fontSize:13,fontWeight:600},children:"Chat backend"}),e.jsx("span",{className:L.backend==="slack"?"bg-muted text-muted-foreground":"bg-primary text-primary-foreground",style:{padding:"1px 8px",borderRadius:999,fontSize:11,fontWeight:600},children:L.backend}),e.jsxs("span",{style:{marginLeft:"auto",display:"flex",gap:8},children:[L.backend!=="native"&&e.jsx("button",{disabled:E!==null,onClick:()=>O(L.clientId),className:"text-primary",style:{fontSize:12,fontWeight:600},children:E==="preflight"?"Checkingâ¦":"Run preflight"}),L.backend==="native"&&e.jsx("button",{disabled:E!==null,onClick:()=>z(L.clientId,"bridge"),className:"text-primary",style:{fontSize:12,fontWeight:600},children:E==="revert"?"Workingâ¦":"Back to bridge"}),L.backend!=="slack"&&e.jsx("button",{disabled:E!==null,onClick:()=>z(L.clientId,"slack"),className:"text-destructive",style:{fontSize:12,fontWeight:600},children:E==="revert"?"Revertingâ¦":"Revert to Slack"})]})]}),N&&e.jsx("div",{className:"text-foreground",style:{fontSize:12,marginBottom:6},children:N}),I&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,fontSize:12},children:[I.errors.map((B,Y)=>e.jsxs("div",{className:"text-destructive",children:["â ",B]},`e${Y}`)),I.warnings.map((B,Y)=>e.jsxs("div",{style:{color:"#f2994a"},children:["â ",B]},`w${Y}`)),I.conflicts.map((B,Y)=>e.jsxs("div",{className:"text-destructive",children:["â #",B.handle," also claimed by ",B.clientName]},`c${Y}`)),e.jsxs("div",{className:"text-muted-foreground",children:[I.lanes.length," lane(s) · Slack ",I.slackOk?"reachable":`unreachable (${I.slackError})`," · ",I.claimedProfiles," claimed client profile(s)"]}),e.jsxs("div",{className:"text-muted-foreground",children:["Last imported: ",I.lastImported.map(B=>`#${B.handle} ${B.at?new Date(B.at).toLocaleDateString():"never"}`).join(" · ")]}),I.delta.length>0&&e.jsxs("div",{className:"text-muted-foreground",children:["Waiting in Slack: ",I.delta.map(B=>`#${B.handle} ${B.error?"unknown":B.pending}${B.exceedsCap?" (over cap)":""}`).join(" · ")]}),e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",marginTop:4,flexWrap:"wrap"},children:[L.backend==="slack"&&e.jsx("button",{disabled:E!==null,onClick:()=>R(L.clientId,"bridge",!I.ok),className:"bg-primary text-primary-foreground",style:{padding:"6px 14px",borderRadius:6,fontSize:13,fontWeight:600,opacity:I.ok?1:.9},children:E==="flip"?"Workingâ¦":I.ok?"Turn on the bridge":"Bridge anyway (force)"}),e.jsx("button",{disabled:E!==null,onClick:()=>R(L.clientId,"native",!I.ok),className:L.backend==="slack"?"border border-border text-foreground":"bg-primary text-primary-foreground",style:{padding:"6px 14px",borderRadius:6,fontSize:13,fontWeight:600,opacity:I.ok?1:.9},children:E==="flip"?"Flippingâ¦":I.ok?"Flip to native":"Flip anyway (force)"}),e.jsx("span",{className:"text-muted-foreground",style:{fontSize:11},children:L.backend==="slack"?"Both import the Slack delta first. Bridge keeps the Slack channel working in both directions; native posts the moved notice and stops mirroring. Reversible either way.":"Imports the Slack delta (messages + files), posts the moved notice, then flips. Rever
422sible."})]})]})]}),u&&e.jsxs("div",{style:{position:"relative",marginBottom:12},children:[e.jsx(vg,{size:14,className:"text-muted-foreground",style:{position:"absolute",left:10,top:11}}),e.jsx("input",{value:h,onChange:B=>b(B.target.value),placeholder:"Add a person by name or emailâ¦",className:"bg-background border border-border text-foreground rounded-md w-full",style:{padding:"8px 8px 8px 30px",fontSize:14}}),f.length>0&&e.jsx("div",{className:"bg-card border border-border rounded-md",style:{position:"absolute",left:0,right:0,top:40,zIndex:5,maxHeight:240,overflow:"auto"},children:f.map(B=>e.jsxs("div",{className:"border-b border-border",style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px"},children:[e.jsxs("div",{style:{flex:1},children:[e.jsxs("div",{className:"text-foreground",style:{fontSize:14},children:[B.fullName||"(no name yet)"," ",B.isStaff&&e.jsx($m,{size:12,style:{display:"inline",verticalAlign:-2}})]}),e.jsxs("div",{className:"text-muted-foreground",style:{fontSize:12},children:[B.email,B.exists===!1?" · new to chat â added as soon as they sign in":B.claimed?"":" · not signed in yet"]})]}),e.jsx("button",{disabled:v===B.profileId,onClick:()=>U(B.profileId,"member",B.exists===!1?{email:B.email,fullName:B.fullName}:void 0),className:"border border-border text-foreground rounded-md",style:{padding:"3px 8px",fontSize:12},children:"Member"}),e.jsx("button",{disabled:v===B.profileId,onClick:()=>U(B.profileId,"manager",B.exists===!1?{email:B.email,fullName:B.fullName}:void 0),className:"bg-primary text-primary-foreground rounded-md",style:{padding:"3px 8px",fontSize:12},children:"Manager"})]},B.profileId))})]}),p===null?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading membersâ¦"}):p.length===0?e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx(Hl,{size:14,style:{display:"inline",verticalAlign:-2}})," Nobody is a member of this node yet."]}):p.map(B=>e.jsxs("div",{className:"border-t border-border",style:{display:"flex",alignItems:"center",gap:8,padding:"8px 0"},children:[e.jsxs("div",{style:{flex:1},children:[e.jsxs("div",{className:"text-foreground",style:{fontSize:14},children:[B.fullName||"(no name yet)"," ",B.isStaff&&e.jsx($m,{size:12,style:{display:"inline",verticalAlign:-2}})]}),e.jsxs("div",{className:"text-muted-foreground",style:{fontSize:12},children:[B.email,B.claimed?"":" · not signed in yet"]})]}),e.jsx("span",{className:`rounded-md ${B.role==="manager"?"bg-primary/10 text-foreground":"bg-muted text-muted-foreground"}`,style:{padding:"2px 8px",fontSize:12},children:B.role==="manager"?"manager · sees all below":"member · this node"}),u&&e.jsxs(e.Fragment,{children:[e.jsx("button",{disabled:v===B.profileId,onClick:()=>U(B.profileId,B.role==="manager"?"member":"manager"),className:"border border-border text-foreground rounded-md",style:{padding:"3px 8px",fontSize:12},children:B.role==="manager"?"Make member":"Make manager"}),e.jsx("button",{disabled:v===B.profileId,onClick:()=>U(B.profileId,null),className:"text-destructive","aria-label":"Remove",style:{padding:4},children:e.jsx(gN,{size:16})})]})]},B.profileId))]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select an account to see its members."})})]})]})})}function U8(){const[t,s]=l.useState(!1),[n,r]=l.useState(!0),[a,o]=l.useState(null),{user:i}=pt(),d=l.useRef(i);l.useEffect(()=>{d.current=i},[i]),l.useEffect(()=>{i?m():(s(!1),r(!1))},[i]),l.useEffect(()=>{if(new URLSearchParams(window.location.search).get("slack_auth")==="success"){const h=new URL(window.location.href);if(h.searchParams.delete("slack_auth"),window.history.replaceState({},"",h.toString()),window.opener){window.opener.postMessage({type:"SLACK_AUTH_SUCCESS"},window.location.origin),window.close();return}d.current&&m()}const x=h=>{var b;h.origin===window.location.origin&&((b=h.data)==null?void 0:b.type)==="SLACK_AUTH_SUCCESS"&&(console.log("Received Slack auth success message from popup"),d.current&&m())};return window.addEventListener("message",x),()=>window.removeEventListener("message",x)},[]);const m=async()=>{try{if(r(!0),!i){s(!1),r(!1);return}if(!i)throw new Error("User not authenticated");const u=await i.getIdToken(),x=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/checkSlackAuth",{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!x.ok)throw new Error("Failed to check Slack connection");const h=await x.json();s(h.connected)}catch(u){console.error("Failed to check Slack connection:",u),o(u.message),s(!1)}finally{r(!1)}};return{isConnected:t,loading:n,error:a,connectSlack:async()=>{try{if(o(null),!i)throw new Error("User not authenticated");const u=600,x=700,h=window.screen.width/2-u/2,b=window.screen.height/2-x/2,f=window.open("about:blank","Slack Authorization",`width=${u},height=${x},left=${h},top=${b}`);if(!f)throw new Error("Your browser blocked the Slack window. Allow pop-ups for this site, then try again.");const g=await i.getIdToken(),y=new AbortController,j=setTimeout(()=>y.abort(),2e4);let v;try{v=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/slackOAuthStart",{method:"GET",headers:{Authorization:`Bearer ${g}`},signal:y.signal})}catch(w){throw f.close(),new Error((w==null?void 0:w.name)==="AbortError"?"Slack sign-in timed out. Try again.":"Could not reach Slack sign-in. Try again.")}finally{clearTimeout(j)}if(!v.ok)throw f.close(),new Error("Failed to start Slack OAuth");const T=await v.json();f.location.href=T.authUrl;
422const k=setInterval(()=>{try{f!=null&&f.closed&&(clearInterval(k),setTimeout(()=>{m()},1e3))}catch{}},500)}catch(u){console.error("Failed to connect Slack:",u),o(u.message)}},sendMessage:async(u,x,h)=>{try{if(o(null),!i)throw new Error("User not authenticated");const b=await i.getIdToken(),f=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/sendSlackMessageAsUser",{method:"POST",headers:{Authorization:`Bearer ${b}`,"Content-Type":"application/json"},body:JSON.stringify({channelId:u,text:x,threadTs:h})});if(!f.ok){const y=await f.json();throw y.needsAuth?(s(!1),new Error("Slack not connected. Please connect your account.")):new Error(y.error||"Failed to send message")}return await f.json()}catch(b){throw console.error("Failed to send message:",b),o(b.message),b}}}}const H8=["routed","gathering","drafting","ready","blocked","awaiting_voice"],q8=["routed","gathering","drafting"],mh=t=>{const s=t;return s&&typeof s.toDate=="function"?s.toDate():t instanceof Date?t:null},Fy=t=>t==="T4"||t==="T5";function _y(t,s){var i;const n=Array.isArray(s.tiers)?s.tiers.map(String):[],a=n.some(Fy)?!("codeAnswer"in s)||s.codeAnswer===void 0?"pending":s.codeAnswer?"landed":"unavailable":"none",o=Array.isArray((i=s.lint)==null?void 0:i.failures)?s.lint.failures.map(d=>typeof d=="string"?{rule:d,excerpt:null}:{rule:String((d==null?void 0:d.rule)??"rule"),excerpt:(d==null?void 0:d.excerpt)!=null?String(d.excerpt):null}):[];return{id:t,accountId:String(s.accountId??""),clientId:s.clientId??null,status:s.status,shadow:s.shadow===!0,voiceUid:s.voiceUid??null,voiceName:s.voiceName??null,voiceOptions:Array.isArray(s.voiceOptions)?s.voiceOptions.filter(d=>d&&typeof d.uid=="string").map(d=>({uid:d.uid,name:String(d.name??d.uid),p:Number(d.p)||0})):[],tiers:n,reply:typeof s.reply=="string"?s.reply:"",reviewerNotes:Array.isArray(s.reviewerNotes)?s.reviewerNotes.map(String):[],claims:Array.isArray(s.claims)?s.claims.map(d=>({text:String((d==null?void 0:d.text)??""),sourceType:String((d==null?void 0:d.sourceType)??""),sourceId:String((d==null?void 0:d.sourceId)??"")})):[],confidence:typeof s.confidence=="number"?s.confidence:null,lint:s.lint?{ok:s.lint.ok!==!1,failures:o}:null,model:s.model??null,sensitive:s.sensitive===!0||s.sensitive===void 0&&s.jodyOnly===!0,urgencyScore:typeof s.urgencyScore=="number"?s.urgencyScore:0,codeAnswer:a,forMessageIds:Array.isArray(s.forMessageIds)?s.forMessageIds.map(String):[],aiRunId:s.aiRunId??null,upgradedFrom:s.upgradedFrom??null,createdAt:mh(s.createdAt)??new Date(0),readyAt:mh(s.readyAt)}}const V8=/@(howtoshopify\.com|sunbowl\.ca)$/i;function ph(t){return!!(t!=null&&t.email&&t.emailVerified&&V8.test(t.email))}function Y8(){const[t,s]=l.useState(()=>ph(Lr.currentUser)?{uid:Lr.currentUser.uid}:null);return l.useEffect(()=>Q0(Lr,n=>{s(r=>{const a=n&&ph(n)?n.uid:null;return((r==null?void 0:r.uid)??null)===a?r:a?{uid:a}:null})}),[]),t}const Wy="sunbowl.chat.replyDrafts.showShadow",ad="sb-reply-drafts-shadow";function xh(){try{return localStorage.getItem(Wy)==="1"}catch{return!1}}function G8(){const[t,s]=l.useState(xh);l.useEffect(()=>{const r=()=>s(xh());return window.addEventListener(ad,r),()=>window.removeEventListener(ad,r)},[]);const n=l.useCallback(r=>{try{localStorage.setItem(Wy,r?"1":"0")}catch{}s(r),window.dispatchEvent(new Event(ad))},[]);return[t,n]}function K8(t,s){const[n,r]=l.useState([]),[a,o]=l.useState(null);return l.useEffect(()=>{if(r([]),o(null),!s.enabled||!t)return;const d=Ge(Re(ge,"chatReplyDrafts"),Ve("accountId","==",t),Ve("status","in",H8),Nt("createdAt","desc"),Tt(10));return qt(d,m=>r(m.docs.map(p=>_y(p.id,p.data()))),m=>{console.error("[hub] reply draft listener",m),o(m.message)})},[t,s.enabled]),{draft:l.useMemo(()=>n.find(d=>s.showShadow||!d.shadow)??null,[n,s.showShadow]),error:a}}function Q8(t){const[s,n]=l.useState([]);return l.useEffect(()=>{if(n([]),!t.enabled)return;const r=Ge(Re(ge,"chatReplyDrafts"),Ve("status","==","ready"),Nt("createdAt","desc"),Tt(200));return qt(r,a=>n(a.docs.map(o=>_y(o.id,o.data()))),a=>console.error("[hub] ready drafts listener",a))},[t.enabled]),l.useMemo(()=>J8(s,t.showShadow),[s,t.showShadow])}function J8(t,s){const n=new Map;for(const r of t){if(r.status!=="ready"||r.shadow&&!s||!r.accountId)continue;const a=n.get(r.accountId);(!a||r.urgencyScore>a.urgencyScore)&&n.set(r.accountId,r)}return[...n.values()].sort((r,a)=>a.urgencyScore-r.urgencyScore||r.createdAt.getTime()-a.createdAt.getTime()).map(r=>r.accountId)}const hh="#b7791f",fh=t=>`${t.rule}${t.excerpt?`: â${t.excerpt}â`:""}`;function Z8(t,s=Date.now()){const n=Math.max(0,Math.round((s-t.getTime())/1e3));if(n<45)return"just now";const r=Math.round(n/60);if(r<60)return`${r}m ago`;const a=Math.round(r/60);return a<24?`${a}h ago`:`${Math.round(a/24)}d ago`}function X8(t){const s=[];for(const n of[...t].sort()){const r=Fy(n)?"code":n;s.includes(r)||s.push(r)}return s}function eL({draft:t,viewerUid:s,compact:n,onUse:r,onSettled:a,onOpenTicket:o,onShowMessage:i}){var V;
422const[d,m]=l.useState(null),[p,c]=l.useState(null),[u,x]=l.useState(!1),[h,b]=l.useState(!1),[f,g]=l.useState(""),[y,j]=l.useState(!0);l.useEffect(()=>{c(null),b(!1),g("")},[t.id]);const v=async(M,F={})=>{m(M),c(null);try{await re("chatReplyDraftAction",{draftId:t.id,action:M,...F}),(M==="dismiss"||M==="use")&&(a==null||a(t.id,M)),M==="regenerate"&&(b(!1),g(""))}catch(W){c(W instanceof Error?W.message:"That did not work")}finally{m(null)}},T=()=>{var F;const M=t.status==="blocked"?{title:"Fix before sending â the draft failed these checks:",lines:(((F=t.lint)==null?void 0:F.failures)??[]).map(fh)}:null;r(t.reply,t.forMessageIds[t.forMessageIds.length-1]??null,M),v("use")},k=q8.includes(t.status),w=t.status==="blocked",I=t.status==="awaiting_voice",A=!!s&&s!==t.voiceUid&&t.voiceOptions.some(M=>M.uid===s),E=X8(t.tiers),C=t.voiceOptions.some(M=>M.p>0),N=t.readyAt??t.createdAt,S={minHeight:n?40:30,padding:"0 12px",borderRadius:6,fontSize:12,fontWeight:600},O={padding:"1px 7px",borderRadius:999,fontSize:10,fontWeight:600,letterSpacing:".03em"},R=e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap",fontSize:12},children:[e.jsx("button",{onClick:()=>j(!y),"aria-expanded":y,"aria-label":y?"Collapse draft":"Expand draft",className:"text-muted-foreground",style:{display:"inline-flex",alignItems:"center"},children:y?e.jsx(Ot,{size:14}):e.jsx(Rt,{size:14})}),e.jsx(ws,{size:13,className:"text-primary"}),e.jsx("span",{className:"text-foreground",style:{fontWeight:700},children:I?"Draft â who should answer?":`Draft as ${t.voiceName??"Sunbowl"}`}),E.map(M=>e.jsx("span",{className:"bg-muted text-muted-foreground",style:O,children:M},M)),t.shadow&&e.jsx("span",{"data-testid":"shadow-badge",className:"text-muted-foreground",style:{...O,border:"1px dashed var(--sbc-border)"},children:"Shadow"}),e.jsx("span",{className:"text-muted-foreground",style:{marginLeft:"auto",fontSize:11},children:[t.model,Z8(N)].filter(Boolean).join(" · ")})]}),z=e.jsxs(e.Fragment,{children:[t.sensitive&&e.jsxs("div",{"data-testid":"sensitive-line",style:{display:"flex",alignItems:"center",gap:6,fontSize:12,color:hh,borderLeft:`3px solid ${hh}`,paddingLeft:8},children:[e.jsx(Dt,{size:12})," Sensitive topic â read before sending"]}),w&&e.jsxs("div",{"data-testid":"blocked-line",className:"text-destructive",style:{display:"flex",flexDirection:"column",gap:2,fontSize:12,borderLeft:"3px solid var(--sbc-destructive)",paddingLeft:8},children:[e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,fontWeight:600},children:[e.jsx(Dt,{size:12})," Failed the checks â edit before sending"]}),(((V=t.lint)==null?void 0:V.failures)??[]).map((M,F)=>e.jsx("span",{children:fh(M)},F))]})]}),D=k?e.jsxs("div",{"data-testid":"drafting",className:"text-muted-foreground",style:{fontSize:12,display:"flex",alignItems:"center",gap:6},children:[e.jsx(yt,{size:12,className:"sb-spin"})," Draftingâ¦"]}):I?e.jsxs("div",{"data-testid":"voice-picker",style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[e.jsx("span",{className:"text-muted-foreground",style:{fontSize:12},children:"Pick a voice:"}),[...t.voiceOptions].sort((M,F)=>F.p-M.p).map(M=>e.jsxs("button",{disabled:d!==null,onClick:()=>v("pick_voice",{voiceUid:M.uid}),className:"bg-card text-foreground border border-border",style:{...S,fontWeight:500},children:[M.name,C&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",Math.round(M.p*100),"%"]})]},M.uid)),t.voiceOptions.length===0&&e.jsx("span",{className:"text-muted-foreground",style:{fontSize:12},children:"No voices offered."})]}):e.jsx("div",{"data-testid":"draft-reply",className:"bg-card text-foreground border border-border",style:{padding:"8px 12px",borderRadius:10,fontSize:13,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere",maxHeight:n?140:180,overflowY:"auto"},children:t.reply?Ki(t.reply):e.jsx("span",{className:"text-muted-foreground",children:"No text."})}),L=t.codeAnswer==="pending"&&!I&&e.jsxs("div",{"data-testid":"code-coming",className:"text-muted-foreground",style:{fontSize:11,display:"flex",alignItems:"center",gap:5},children:[e.jsx(yt,{size:11,className:"sb-spin"})," Code answer coming â this draft updates when it lands"]}),$=!k&&e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[!I&&e.jsx("button",{disabled:d!==null||!t.reply,onClick:T,title:w?"Put this in the composer with the failed checks listed â edit, then Send":"Put this in the composer â you still press Send",className:"bg-primary text-primary-foreground",style:{...S,opacity:t.reply?1:.5},children:"Use"}),!I&&e.jsx("button",{disabled:d!==null,onClick:()=>b(!h),"aria-expanded":h,className:"bg-card text-foreground border border-border",style:S,children:"Regenerate"}),!I&&A&&e.jsx("button",{disabled:d!==null,onClick:()=>v("rewrite_voice",{voiceUid:s}
422),className:"bg-card text-foreground border border-border",style:S,children:"Rewrite in my voice"}),e.jsxs("button",{disabled:d!==null,onClick:()=>v("dismiss"),"aria-label":"Dismiss draft",className:"bg-card text-muted-foreground border border-border",style:{...S,display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(mt,{size:12})," Dismiss"]}),!I&&e.jsxs("button",{onClick:()=>x(!u),"aria-expanded":u,className:"text-muted-foreground",style:{marginLeft:"auto",fontSize:11,display:"inline-flex",alignItems:"center",gap:3},children:[u?e.jsx(Ot,{size:11}):e.jsx(Rt,{size:11})," Why this draft"]})]}),q=h&&e.jsxs("form",{onSubmit:M=>{M.preventDefault(),v("regenerate",f.trim()?{instruction:f.trim()}:{})},style:{display:"flex",gap:6},children:[e.jsx("input",{autoFocus:!0,value:f,onChange:M=>g(M.target.value),placeholder:"Optional: shorter, mention the invoiceâ¦","aria-label":"Regenerate instruction",className:"bg-muted text-foreground border border-border",style:{flex:1,minWidth:0,padding:"6px 10px",borderRadius:6,fontSize:12,minHeight:n?40:30}}),e.jsx("button",{type:"submit",disabled:d!==null,className:"bg-foreground text-background",style:S,children:d==="regenerate"?"Askingâ¦":"Go"})]}),P=M=>M.sourceType==="ticket"&&o?e.jsx("button",{onClick:()=>o(M.sourceId),className:"text-primary",style:{fontSize:11,textDecoration:"underline"},children:M.sourceId}):M.sourceType==="message"&&i?e.jsx("button",{onClick:()=>{i(M.sourceId)||c("That message is not loaded in the feed")},className:"text-primary",style:{fontSize:11,textDecoration:"underline"},children:"message"}):e.jsxs("span",{className:"text-muted-foreground",style:{fontSize:11},children:[M.sourceType,M.sourceId?` ${M.sourceId}`:""]}),U=u&&!k&&!I&&e.jsxs("div",{"data-testid":"why-panel",className:"bg-muted",style:{padding:"8px 10px",borderRadius:8,fontSize:12,lineHeight:1.45,display:"flex",flexDirection:"column",gap:6},children:[e.jsxs("div",{className:"text-muted-foreground",children:["Confidence ",t.confidence!=null?`${Math.round(t.confidence*100)}%`:"unknown"," · ","checks ",t.lint?t.lint.ok?"passed":`failed (${t.lint.failures.map(M=>M.rule).join(", ")})`:"not run",t.upgradedFrom?" · upgraded with the code answer":""]}),t.reviewerNotes.length>0&&e.jsx("ul",{style:{margin:0,paddingLeft:16},className:"text-foreground",children:t.reviewerNotes.map((M,F)=>e.jsx("li",{children:M},F))}),t.claims.length>0&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[e.jsx("span",{className:"text-muted-foreground",style:{fontSize:10,fontWeight:600,letterSpacing:".06em"},children:"CLAIMS"}),t.claims.map((M,F)=>e.jsxs("div",{className:"text-foreground",style:{display:"flex",gap:6,alignItems:"baseline"},children:[e.jsx("span",{style:{flex:1,minWidth:0},children:M.text}),P(M)]},F))]}),t.reviewerNotes.length===0&&t.claims.length===0&&e.jsx("span",{className:"text-muted-foreground",children:"No notes or claims on this draft."})]});return e.jsxs("div",{"data-testid":"reply-draft-card","data-status":t.status,className:"bg-background border-t border-border",style:{padding:n?"8px 12px":"10px 24px",display:"flex",flexDirection:"column",gap:8},children:[R,y&&e.jsxs(e.Fragment,{children:[z,D,L,$,q,p&&e.jsx("div",{className:"text-destructive",style:{fontSize:12},children:p}),U]})]})}function tL({accountId:t,showShadow:s,...n}){const{draft:r}=K8(t,{enabled:!0,showShadow:s}),[a,o]=l.useState(new Set);return!r||a.has(r.id)?null:e.jsx(eL,{...n,draft:r,onSettled:i=>o(d=>new Set(d).add(i))})}const sL=["Development","Marketing","QA","Administration"],gh=t=>t.toLocaleString([],{year:t.getFullYear()===new Date().getFullYear()?void 0:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});function nL({onBack:t,compact:s}){var gn,Zs,Yt,is;const n=El(!0),r=n.access,a=l.useMemo(()=>new Map(((r==null?void 0:r.accounts)??[]).map(ne=>[ne.id,ne])),[r]),o=U8(),[i,d]=l.useState(null),m=Y8(),p=!!m&&!n.impersonating,[c,u]=G8(),x=Q8({enabled:p,showShadow:c}),[h,b]=l.useState(!1),f=p&&h,[g,y]=l.useState(!!s);l.useEffect(()=>{if(s!==void 0){y(s);return}const ne=window.matchMedia("(max-width: 900px)"),Ce=()=>y(ne.matches);
422return Ce(),ne.addEventListener("change",Ce),()=>ne.removeEventListener("change",Ce)},[s]);const[j,v]=l.useState([]);l.useEffect(()=>{if(!(r!=null&&r.isAdmin))return;const ne=Ge(Re(ge,"chatTriage"),Ve("status","==","pending"),Nt("createdAt","desc"),Tt(100));return qt(ne,Ce=>v(Ce.docs.map(Qe=>{var ye,Me;const xt=Qe.data();return{id:Qe.id,messageId:xt.messageId,accountId:xt.accountId,clientId:xt.clientId??null,draft:xt.draft,status:xt.status,ticketId:xt.ticketId??null,createdAt:((Me=(ye=xt.createdAt)==null?void 0:ye.toDate)==null?void 0:Me.call(ye))??new Date}})),Ce=>console.error("[hub] triage listener",Ce))},[r==null?void 0:r.isAdmin]);const[T,k]=l.useState({}),w=l.useRef(new Set),[I,A]=l.useState(new Set);l.useEffect(()=>{for(const ne of new Set(j.map(Ce=>Ce.messageId).filter(Boolean)))w.current.has(ne)||(w.current.add(ne),ps(ut(ge,"chatMessages",ne)).then(Ce=>{const Qe=Ce.exists()?Ce.data():null;k(xt=>{var ye,Me;return{...xt,[ne]:Qe?{text:Qe.text??"",authorName:Qe.authorName??"",createdAt:((Me=(ye=Qe.createdAt)==null?void 0:ye.toDate)==null?void 0:Me.call(ye))??null,emailSubject:typeof Qe.emailSubject=="string"?Qe.emailSubject:null}:null}})}).catch(Ce=>{console.error("[hub] source message",Ce),w.current.delete(ne),k(Qe=>({...Qe,[ne]:null}))}))},[j]);const[E,C]=l.useState([]);l.useEffect(()=>{if(!(r!=null&&r.isAdmin))return;const ne=Ge(Re(ge,"clients"),Ve("lifecycleStage","==","active"));return qt(ne,Ce=>C(Ce.docs.map(Qe=>({id:Qe.id,name:Qe.data().name??Qe.id})).sort((Qe,xt)=>Qe.name.localeCompare(xt.name))),Ce=>console.error("[hub] clients listener",Ce))},[r==null?void 0:r.isAdmin]);const[N,S]=l.useState(""),[O,R]=l.useState([]),[z,D]=l.useState(null),[L,$]=l.useState(null),q=async ne=>{$(ne),Y(null);try{D((await re("chatGetTicket",{ticketId:ne})).ticket)}catch(Ce){Y(String(Ce.message??Ce))}finally{$(null)}};l.useEffect(()=>{if(N.trim().length<2){R([]);return}const ne=setTimeout(async()=>{try{R((await re("chatSearchTickets",{query:N})).tickets)}catch{R([])}},250);return()=>clearTimeout(ne)},[N]);const P=l.useRef(null),U=l.useCallback(ne=>{P.current=ne},[]),[V,M]=l.useState(null),[F,W]=l.useState(null),[_,G]=l.useState(null),[B,Y]=l.useState(null),[J,H]=l.useState(null),[Z,Q]=l.useState(""),[K,X]=l.useState(!1);l.useEffect(()=>{z&&(Q(z.promisedDate??""),!z.promisedDate&&["Awaiting Approval","Backlog","New","Scoping"].includes(z.status)&&re("getTicketCompletionEstimate",{ticketId:z.id}).then(ne=>{typeof(ne==null?void 0:ne.completionDate)=="string"&&Q(Ce=>Ce||ne.completionDate)}).catch(()=>{}))},[z==null?void 0:z.id,z==null?void 0:z.promisedDate,z==null?void 0:z.status]),l.useEffect(()=>{if(!J)return;const ne=setTimeout(()=>H(null),3e3);return()=>clearTimeout(ne)},[J]);const se=async(ne,Ce)=>{const Qe=P.current;if(Qe){G(Ce.id),Y(null);try{if(Ce.kind==="ticket"){if(ne.tags.some(xt=>xt.kind==="ticket"&&xt.id===Ce.id)){H(`Already on ${Ce.label}`);return}await Qe.retag(ne.id,[...ne.tags,{kind:"ticket",id:Ce.id,label:Ce.label,source:"staff"}]),H(`Added to ${Ce.label}`)}else await re("chatDraftTriage",{messageId:ne.id,title:Ce.label}),H("Drafted from this message")}catch(xt){Y(xt instanceof Error?xt.message:"Could not attach")}finally{G(null),M(null),W(null)}}},pe=async ne=>{d(ne.id),Y(null);try{await re("chatSlackResend",{messageId:ne.id}),H("Sent to Slack")}catch(Ce){Y(Ce instanceof Error?Ce.message:"Slack would not take it")}finally{d(null)}},me=async ne=>{G(ne.id),Y(null);try{await re("chatDraftTriage",{messageId:ne.id}),H("Drafted in triage")}catch(Ce){Y(Ce instanceof Error?Ce.message:"Could not draft")}finally{G(null)}},[Ne,at]=l.useState(null),[ae,xe]=l.useState({}),[ze,Le]=l.useState([]),[ht,ue]=l.useState([]);l.useEffect(()=>{Ne&&xe({name:Ne.draft.title,description:Ne.draft.description,clientId:Ne.clientId??"",projectId:Ne.draft.projectId??"",shopifyStoreId:"",status:"Backlog",department:"Development",ticketComplexity:"Medium Task",rushOrder:!1,pageUrl:"",dueDate:""})},[Ne]);const we=Ne?String(ae.clientId??""):"";l.useEffect(()=>{if(!Ne)return;if(!we){Le([]),ue([]);return}const ne=Ge(Re(ge,"clientProjects"),Ve("clientId","==",we),Tt(50)),Ce=Ge(Re(ge,"shopifyStores"),Ve("clientId","==",we),Tt(20)),Qe=qt(ne,ye=>Le(ye.docs.map(Me=>{const Pe=Me.data();return{id:Me.id,name:Pe.name??Me.id,shopifyStoreId:Pe.shopifyStoreId??null}}))),xt=qt(Ce,ye=>ue(ye.docs.map(Me=>{const Pe=Me.data();return{id:Me.id,label:Pe.myshopifyUrl||Pe.name||Me.id}})),ye=>console.error("[hub] stores listener",ye));return()=>{Qe(),xt()}},[Ne,we]);const[Be,Ye]=l.useState(null);l.useEffect(()=>{if(!Ne||!we||E.some(Ce=>Ce.id===we)){Ye(null);return}let ne=!1;return ps(ut(ge,"clients",we)).then(Ce=>{if(ne)return;const Qe=Ce.data();Ye(Ce.exists()?{id:Ce.id,name:(Qe==null?void 0:Qe.name)??Ce.id,lifecycleStage:(Qe==null?void 0:Qe.lifecycleStage)??null}:null)}
422).catch(Ce=>console.error("[hub] seeded client lookup",Ce)),()=>{ne=!0}},[Ne,we,E]);const rt=ne=>xe({...ae,clientId:ne,projectId:"",shopifyStoreId:""}),te=ne=>{const Ce=ze.find(xt=>xt.id===ne),Qe=String(ae.shopifyStoreId??"")||(Ce!=null&&Ce.shopifyStoreId&&ht.some(xt=>xt.id===Ce.shopifyStoreId)?Ce.shopifyStoreId:"");xe({...ae,projectId:ne,shopifyStoreId:Qe})},ve=async(ne,Ce,Qe)=>{G(ne.id),Y(null);try{const xt=await re("chatDecideTriage",{triageId:ne.id,decision:Ce,ticket:Qe}),ye=xt.attachmentsCopied?` with ${xt.attachmentsCopied} file${xt.attachmentsCopied===1?"":"s"} from the email`:"";H(Ce==="approve"?`Minted ${xt.displayId}${ye}`:"Discarded"),at(null)}catch(xt){Y(xt instanceof Error?xt.message:"Decision failed")}finally{G(null)}},[Ae,We]=l.useState("feed"),[ie,Ue]=l.useState(0),[Te,He]=l.useState(null),[Oe]=V0(n.profileId),Je=l.useMemo(()=>((r==null?void 0:r.accounts)??[]).filter(ne=>!ne.archived&&ne.clientActive!==!1&&(Oe||!ne.internalRoom)),[r,Oe]),de=l.useMemo(()=>Je.filter(ne=>ne.backend==="bridge"),[Je]),je=l.useMemo(()=>{if(!f)return[null,...Je.map(Ce=>Ce.id)];const ne=new Set(Je.map(Ce=>Ce.id));return[null,...x.filter(Ce=>ne.has(Ce))]},[Je,f,x]),qe=je[Math.min(ie,je.length-1)]??null,he=l.useRef(null),lt=ne=>{he.current=ne.touches[0].clientX},tt=ne=>{if(he.current===null)return;const Ce=ne.changedTouches[0].clientX-he.current;he.current=null,Ce<-50?Ue(Qe=>Math.min(je.length-1,Qe+1)):Ce>50&&Ue(Qe=>Math.max(0,Qe-1))};if(n.loading||!r)return e.jsx("div",{className:"sb-chat min-h-screen bg-background text-muted-foreground",style:{padding:24},children:n.error??"Loadingâ¦"});if(!r.isAdmin)return e.jsx("div",{className:"sb-chat min-h-screen bg-background text-muted-foreground",style:{padding:24},children:"The Communications Hub is for Sunbowl staff."});const Se=(ne,Ce,Qe,xt,ye)=>{const Me=Ce&&V&&F===ne,Pe=Ce&&V&&!Me;return e.jsxs("div",{onDragOver:Ce?Et=>{Et.preventDefault(),F!==ne&&W(ne)}:void 0,onDragLeave:Ce?Et=>{Et.currentTarget.contains(Et.relatedTarget)||F===ne&&W(null)}:void 0,onDrop:Ce?Et=>{Et.preventDefault(),xt()}:void 0,className:"bg-card",style:{position:"relative",padding:12,borderRadius:8,border:`${Me?2:1}px ${Pe?"dashed":"solid"} ${Me||Pe?"var(--sbc-primary)":"var(--sbc-border)"}`,background:Me?"#eaf6fc":void 0,boxShadow:Me?"0 6px 18px rgba(126,204,238,.45)":"none",transform:Me?"scale(1.02)":"none",transition:"transform .1s, box-shadow .1s"},children:[Me&&e.jsx("div",{className:"bg-primary text-primary-foreground",style:{position:"absolute",top:-10,right:10,padding:"2px 8px",borderRadius:999,fontSize:10,fontWeight:700,letterSpacing:".04em"},children:"DROP TO ATTACH"}),ye,e.jsx("span",{className:"sr-only",children:Qe})]},ne)},es=ne=>Se(`t:${ne.id}`,ne.status!=="Complete",ne.displayId,()=>V&&se(V,{kind:"ticket",id:ne.id,label:ne.displayId}),e.jsxs("div",{onClick:()=>{!V&&!Te&&q(ne.id)},style:{display:"flex",flexDirection:"column",gap:4,cursor:V||Te?void 0:"pointer",opacity:L===ne.id?.6:1},children:[e.jsxs("div",{className:"text-muted-foreground",style:{display:"flex",gap:6,fontSize:11,alignItems:"center"},children:[e.jsx("span",{className:"text-foreground",style:{fontWeight:600},children:ne.displayId}),e.jsx("span",{children:"·"}),e.jsx("span",{children:ne.clientName??ne.projectName??""}),e.jsx("span",{className:"bg-muted",style:{marginLeft:"auto",padding:"1px 7px",borderRadius:999},children:ne.status})]}),e.jsx("div",{className:"text-foreground",style:{fontSize:13,fontWeight:600,lineHeight:1.35},children:ne.name}),Te&&e.jsx("button",{onClick:()=>{se(Te,{kind:"ticket",id:ne.id,label:ne.displayId}),He(null)},className:"bg-primary text-primary-foreground",style:{marginTop:6,minHeight:40,borderRadius:6,fontSize:13,fontWeight:600},children:"Attach here"})]})),_e=(ne,Ce=!1)=>{const Qe=T[ne.messageId],xt=Ce||I.has(ne.id),ye=Qe===void 0?e.jsx("span",{children:"Loading original messageâ¦"}):Qe===null?e.jsx("span",{children:"Original message unavailable"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{style:{fontWeight:600,letterSpacing:".04em"},children:["FROM THE MESSAGE · @",Qe.authorName||"unknown",Qe.createdAt?` · ${gh(Qe.createdAt)}`:""]}),Qe.emailSubject&&e.jsx("span",{className:"text-foreground",style:{fontWeight:600},children:Qe.emailSubject}),Ce?e.jsx("div",{className:"text-foreground",style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:pm(Qe.text)}):e.jsx("span",{className:"text-foreground",style:{overflowWrap:"anywhere",display:xt?void 0:"-webkit-box",WebkitLineClamp:xt?void 0:3,WebkitBoxOrient:xt?void 0:"vertical",overflow:xt?void 0:"hidden"},children:Ki(Qe.text)})]}),Me={display:"flex",flexDirection:"column",gap:3,padding:"6px 10px",borderRadius:6,borderLeft:"3px solid var(--sbc-primary)",fontSize:11,lineHeight:1.45,textAlign:"left"};return Ce?e.jsx("div",{className:"bg-muted text-muted-foreground",style:{...Me,maxHeight:200,overflow:"auto"},children:ye}):e.jsx("button",{type:"button",disabled:!Qe,"aria-expanded":xt,title:Qe?xt?"Show less":"Show the whole message":void 0,onClick:()=>A(Pe=>{const Et=new Set(Pe);return Et.has(ne.id)?Et.delete(ne.id):Et.add(ne.id),Et}),className:"bg-muted text-muted-foreground",style:{...Me,width:"100%",cursor:Qe?"pointer":void 0},children:ye})},St=ne=>{const Ce=a.get(ne.accountId);return Se(`d:${ne.id}`,!0,ne.draft.title,()=>V&&se(V,{kind:"draft",id:ne.id,label:ne.draft.title}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{className:"text-muted-foreground",style:{display:"flex",gap:6,fontSize:11},children:[e.jsxs("span",{children:["#",(Ce==null?void 0:Ce.handle)??ne.accountId]}),e.jsx("span",{style:{marginLeft:"auto"}
422,title:ne.createdAt.toLocaleString(),children:gh(ne.createdAt)})]}),e.jsx("div",{className:"text-foreground",style:{fontSize:14,fontWeight:600,lineHeight:1.35},children:Ki(ne.draft.title)}),e.jsx("div",{className:"text-muted-foreground",style:{fontSize:12,lineHeight:1.45,display:"-webkit-box",WebkitLineClamp:3,WebkitBoxOrient:"vertical",overflow:"hidden"},children:Ki(ne.draft.description)}),_e(ne),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{disabled:_===ne.id,onClick:()=>at(ne),className:"bg-primary text-primary-foreground",style:{flex:1,minHeight:g?44:36,borderRadius:6,fontSize:13,fontWeight:600},children:"Mint ticketâ¦"}),e.jsx("button",{disabled:_===ne.id,onClick:()=>at(ne),className:"bg-card text-foreground border border-border",style:{minHeight:g?44:36,padding:"0 12px",borderRadius:6,fontSize:13},children:"Edit"}),e.jsx("button",{disabled:_===ne.id,onClick:()=>ve(ne,"dismiss"),className:"bg-card text-muted-foreground border border-border",style:{minHeight:g?44:36,padding:"0 12px",borderRadius:6,fontSize:13},children:"Discard"})]}),Te&&e.jsx("button",{onClick:()=>{se(Te,{kind:"draft",id:ne.id,label:ne.draft.title}),He(null)},className:"bg-card text-foreground border border-border",style:{minHeight:40,borderRadius:6,fontSize:13,fontWeight:600},children:"Attach here"})]}))},$t=(ne,Ce)=>e.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[e.jsx("span",{className:"text-muted-foreground",style:{fontSize:11,fontWeight:600,letterSpacing:".04em"},children:ne}),Ce]}),Ct="bg-card text-foreground border border-border rounded-md",ot={padding:"9px 10px",fontSize:13,minHeight:g?44:36},fn=Ne&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:g?12:16,overflow:"auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("button",{onClick:()=>at(null),"aria-label":"Back to triage",className:"text-foreground",style:{width:36,height:36},children:e.jsx(dt,{size:18})}),e.jsxs("div",{className:"text-foreground",style:{fontSize:14,fontWeight:700},children:["New ticket from #",(gn=a.get(Ne.accountId))==null?void 0:gn.handle]})]}),$t("NAME",e.jsx("input",{className:Ct,style:ot,value:String(ae.name??""),onChange:ne=>xe({...ae,name:ne.target.value})})),$t("CLIENT",e.jsxs("select",{className:Ct,style:ot,value:we,onChange:ne=>rt(ne.target.value),children:[e.jsx("option",{value:"",children:E.length?"Pick a clientâ¦":"Loading clientsâ¦"}),Be&&e.jsxs("option",{value:Be.id,children:[Be.name,Be.lifecycleStage?` (${Be.lifecycleStage})`:""]}),E.map(ne=>e.jsx("option",{value:ne.id,children:ne.name},ne.id))]})),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:10},children:[$t("PROJECT",e.jsxs("select",{className:Ct,style:ot,value:String(ae.projectId??""),onChange:ne=>te(ne.target.value),children:[e.jsx("option",{value:"",children:ze.length?"Pick a projectâ¦":we?"No projects for this client yet":"Pick a client first"}),ze.map(ne=>e.jsx("option",{value:ne.id,children:ne.name},ne.id))]})),$t("SHOPIFY STORE",e.jsxs("select",{className:Ct,style:ot,value:String(ae.shopifyStoreId??""),onChange:ne=>xe({...ae,shopifyStoreId:ne.target.value}),children:[e.jsx("option",{value:"",children:ht.length?"No store":we?"No stores for this client":"Pick a client first"}),ht.map(ne=>e.jsx("option",{value:ne.id,children:ne.label},ne.id))]})),$t("STATUS",e.jsx("select",{className:Ct,style:ot,value:String(ae.status??"Backlog"),onChange:ne=>xe({...ae,status:ne.target.value}),children:hl.map(ne=>e.jsx("option",{value:ne,children:Wr(ne)},ne))})),$t("DEPARTMENT",e.jsx("select",{className:Ct,style:ot,value:String(ae.department),onChange:ne=>xe({...ae,department:ne.target.value}),children:sL.map(ne=>e.jsx("option",{children:ne},ne))})),$t("COMPLEXITY",e.jsx("select",{className:Ct,style:ot,value:String(ae.ticketComplexity),onChange:ne=>xe({...ae,ticketComplexity:ne.target.value}),children:Fg.map(ne=>e.jsx("option",{value:ne,children:ne||"Not set"},ne))})),$t("DUE DATE",e.jsx("input",{type:"date",className:Ct,style:ot,value:String(ae.dueDate??""),onChange:ne=>xe({...ae,dueDate:ne.target.value})}))]}),$t("PAGE URL",e.jsx("input",{className:Ct,style:ot,placeholder:"https://â¦",value:String(ae.pageUrl??""),onChange:ne=>xe({...ae,pageUrl:ne.target.value})})),e.jsxs("label",{className:"text-foreground",style:{display:"flex",alignItems:"center",gap:8,fontSize:13,minHeight:36},children:[e.jsx("input",{type:"checkbox",checked:!!ae.rushOrder,onChange:ne=>xe({...ae,rushOrder:ne.target.checked})})," Rush order"]}),_e(Ne,!0),$t("DESCRIPTION",e.jsx("textarea",{rows:5,className:Ct,style:{...ot,fontFamily:"inherit",lineHeight:1.45},value:String(ae.description??""),onChange:ne=>xe({...ae,description:ne.target.value})})),e.jsxs("div",{className:"text-muted-foreground",style:{fontSize:11},children:["Linked to the message it came from · tagged #",(Zs=a.get(Ne.accountId))==null?void 0:Zs.handle,'. Approving posts "Sunbowl created TICK-#### from this" into the lane.']}),B&&e.jsx("div",{className:"text-destructive",style:{fontSize:12},children:B}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{disabled:_===Ne.id||!String(ae.projectId),onClick:()=>ve(Ne,"approve",{name:ae.name,description:ae.description,clientId:ae.clientId,projectId:ae.projectId,shopifyStoreId:ae.shopifyStoreId,status:ae.status,department:ae.department,ticketComplexity:ae.ticketComplexity,rushOrder:ae.rushOrder,pageUrl:ae.pageUrl,dueDate:ae.dueDate?new Date(String(ae.dueDate)).toISOString():""}),className:"bg-primary text-primary-foreground",style:{flex:1,minHeight:44,borderRadius:6,fontSize:14,fontWeight:600,opacity:String(ae.projectId)?1:.5},children:"Mint ticket"}),e.jsx("button",{onClick:()=>at(null),className:"bg-card text-foreground border border-border",style:{minHeight:44,padding:"0 16px",borderRadius:6,fontSize:14},children:"Cancel"})]})]}),Vt=(ne,Ce)=>e.jsxs("div",{style:{display:"flex",gap:8,fontSize:12,lineHeight:1.5},children:[e.jsx("span",{className:"text-muted-foreground",style:{width:84,flexShrink:0},children:ne}),e.jsx("span",{className:"text-foreground",style:{minWidth:0,overflowWrap:"anywhere"},children:Ce})]}),rr=async ne=>{if(z){X(!0);try{const Ce=await re("chatSetTicketSchedule",{ticketId:z.id,promisedDate:Z||null,queue:ne});D({...z,promisedDate:Ce.promisedDate??null,status:ne?"In Queue":z.status}),H(ne?`${z.displayId} approved and queued`:"Estimated completion saved")}catch(Ce){Y(String(Ce.message??Ce))}finally{X(!1)}}},Cr=z?["Awaiting Approval","Backlog","New","Scoping"].includes(z.status):!1,Qr=z&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:12,overflow:"auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("button",{onClick:()=>D(null),"aria-label":"Back to triage",className:"text-muted-foreground",style:{width:32,height:32,display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(dt,{size:16})}),e.jsx("div",{className:"text-foreground",style:{fontSize:14,fontWeight:700},children:z.displayId}),e.jsx("span",{className:"bg-muted text-muted-foreground",style:{marginLeft:"auto",padding:"1px 8px",borderRadius:999,fontSize:11},children:z.status})]}),e.jsx("div",{className:"text-foreground",style:{fontSize:15,fontWeight:600,lineHeight:1.35},children:z.name}),e.jsx("div",{className:"bg-card border border-border",style:{borderRadius:8,padding:"10px 12px",fontSize:13,lineHeight:1.5,whiteSpace:"pre-wrap"}
422,children:z.description?pm(z.description):e.jsx("span",{className:"text-muted-foreground",children:"No description."})}),e.jsxs("div",{className:"bg-card border border-border",style:{borderRadius:8,padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[z.clientName&&Vt("Client",z.clientName),z.projectName&&Vt("Project",z.projectName),z.department&&Vt("Department",z.department),z.ticketComplexity&&Vt("Complexity",z.ticketComplexity),z.creditsMin!=null&&Vt("Credits",z.creditsMin===z.creditsMax?String(z.creditsMin):`${z.creditsMin}â${z.creditsMax}`),z.rushOrder&&Vt("Rush",e.jsx("span",{className:"text-destructive",style:{fontWeight:600},children:"Rush order"})),z.pageUrl&&Vt("Page",e.jsx("a",{href:z.pageUrl,target:"_blank",rel:"noopener noreferrer",className:"text-primary",style:{overflowWrap:"anywhere"},children:z.pageUrl})),z.dueDate&&Vt("Due",new Date(z.dueDate).toLocaleDateString()),Vt("Est. completion",e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[e.jsx("input",{type:"date",value:Z,onChange:ne=>Q(ne.target.value),className:Ct,style:{...ot,width:150}}),!Cr&&Z!==(z.promisedDate??"")&&e.jsx("button",{onClick:()=>rr(!1),disabled:K,className:"bg-foreground text-background",style:{padding:"4px 10px",borderRadius:999,fontSize:11,fontWeight:600},children:"Save"}),Cr&&e.jsx("button",{onClick:()=>rr(!0),disabled:K||!Z,className:"bg-primary text-primary-foreground",style:{padding:"4px 10px",borderRadius:999,fontSize:11,fontWeight:600,opacity:Z?1:.5},title:"Approve by hand: sets the date and moves the ticket to In Queue",children:"Approve & queue"})]})),z.createdAt&&Vt("Created",new Date(z.createdAt).toLocaleString())]}),e.jsx("div",{className:"text-muted-foreground",style:{fontSize:11},children:"Drag a message onto its card in search results to add it to this ticket's context."})]}),le=Ne?fn:z?Qr:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:12,overflow:"auto"},children:[e.jsxs("div",{style:{position:"relative"},children:[e.jsx(Pt,{size:14,className:"text-muted-foreground",style:{position:"absolute",left:10,top:12}}),e.jsx("input",{value:N,onChange:ne=>S(ne.target.value),placeholder:"Search ticketsâ¦",className:Ct,style:{...ot,width:"100%",paddingLeft:30}})]}),V&&e.jsx("div",{className:"text-muted-foreground",style:{padding:"8px 10px",borderRadius:6,border:"1px dashed var(--sbc-primary)",fontSize:12,textAlign:"center"},children:"Drop on a ticket to add the message to its context"}),Te&&e.jsxs("div",{className:"bg-muted text-foreground",style:{padding:"8px 10px",borderRadius:6,fontSize:12},children:["Attach â",Te.text.slice(0,80),Te.text.length>80?"â¦":"","â â ",Te.authorName," ",e.jsx("button",{onClick:()=>He(null),className:"text-muted-foreground",style:{marginLeft:8},children:"cancel"})]}),O.map(es),e.jsxs("div",{className:"text-muted-foreground",style:{fontSize:11,fontWeight:600,letterSpacing:".06em",paddingTop:4},children:["DRAFTS · ",j.length]}),j.length===0&&e.jsx("div",{className:"text-muted-foreground",style:{fontSize:12},children:"Nothing waiting. Use âDraft ticketâ on a message to start one."}),j.map(St),B&&!Ne&&e.jsx("div",{className:"text-destructive",style:{fontSize:12},children:B}),e.jsx("div",{className:"bg-muted text-muted-foreground",style:{padding:"10px 12px",borderRadius:8,fontSize:12,lineHeight:1.45},children:"Approving posts a line into the client's lane so they watch the loop close. Nothing is created without a person pressing it."})]}),Ie=ne=>{var Ce,Qe;return e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[!ne.isStaff&&e.jsxs("button",{disabled:_===ne.id,onClick:()=>me(ne),className:"text-muted-foreground",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,minHeight:g?36:24},children:[e.jsx(_r,{size:12})," ",ne.isRequest?"Drafted in triage":"Draft ticket"]}),g&&e.jsx("button",{onClick:()=>{He(ne),We("triage")},"aria-label":"Add to a ticket",style:{width:44,height:44,borderRadius:22,fontSize:20},children:"ð¯"}),ne.retractedAt&&e.jsxs("span",{className:"text-destructive",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontWeight:600}
422,title:`Deleted in Slack ${ne.retractedAt.toLocaleString()}. Kept here so the conversation still makes sense.`,children:[e.jsx(Dt,{size:12})," Withdrawn in Slack"]}),!ne.retractedAt&&ne.editedAt&&e.jsx("span",{className:"text-muted-foreground",style:{fontSize:11},title:`Edited in Slack ${ne.editedAt.toLocaleString()}. Earlier versions are kept on the message.`,children:"Edited in Slack"}),((Ce=ne.slackRelay)==null?void 0:Ce.state)==="failed"&&e.jsxs("span",{className:"text-destructive",style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,fontWeight:600},title:ne.slackRelay.lastError??void 0,children:[e.jsx(Dt,{size:12})," Not delivered to Slack",e.jsxs("button",{disabled:i===ne.id,onClick:()=>pe(ne),className:"bg-destructive text-destructive-foreground",style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 9px",borderRadius:999,fontSize:11,fontWeight:600,minHeight:g?32:22,opacity:i===ne.id?.6:1},children:[e.jsx(yt,{size:11})," ",i===ne.id?"Sendingâ¦":"Resend"]})]}),((Qe=ne.slackRelay)==null?void 0:Qe.state)==="sent"&&ne.slackRelay.isTeaser&&e.jsxs("span",{className:"text-muted-foreground",title:"This client still reads in Slack. They got a link to Sunbowl Chat, not this message.",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11},children:[e.jsx(Uo,{size:11})," Teaser only in Slack"]})]})},Ke=g&&Ae==="feed"&&je.length>1&&e.jsxs("div",{className:"bg-card border-t border-border",style:{display:"flex",alignItems:"center",gap:6,padding:"4px 8px"},children:[e.jsx("button",{onClick:()=>Ue(ne=>Math.max(0,ne-1)),disabled:ie===0,"aria-label":"Previous lane",className:"text-foreground",style:{width:44,height:44,opacity:ie===0?.3:1},children:e.jsx(fr,{size:20})}),e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:4,minWidth:0},children:[e.jsx("div",{className:"text-foreground",style:{fontSize:14,fontWeight:700,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:qe?`#${(Yt=a.get(qe))==null?void 0:Yt.handle} · ${ie} of ${je.length-1}`:"All lanes"}),qe&&((is=a.get(qe))==null?void 0:is.backend)==="bridge"&&e.jsx("div",{className:"text-muted-foreground",style:{fontSize:11},children:"Reading in Slack â replies go out as you"}),e.jsxs("div",{style:{display:"flex",gap:5},children:[je.slice(0,12).map((ne,Ce)=>e.jsx("button",{onClick:()=>Ue(Ce),"aria-label":`Lane ${Ce}`,style:{width:Ce===ie?18:6,height:6,borderRadius:3,background:Ce===ie?"var(--sbc-primary)":"var(--sbc-border)",transition:"width .15s"}},Ce)),je.length>12&&e.jsx("span",{className:"text-muted-foreground",style:{fontSize:10},children:"â¦"})]})]}),e.jsx("button",{onClick:()=>Ue(ne=>Math.min(je.length-1,ne+1)),disabled:ie>=je.length-1,"aria-label":"Next lane",className:"text-foreground",style:{width:44,height:44,opacity:ie>=je.length-1?.3:1},children:e.jsx(Rt,{size:20})})]}),Fe=ne=>{/^TICK-/i.test(ne)?S(ne):q(ne),g&&We("triage")},Ht=p?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{b(!h),Ue(0)},"aria-pressed":h,title:h?"Show every lane":"Only lanes with a reply draft ready, most urgent first",className:"sb-rail-toggle",style:h?{color:"var(--sbc-foreground)",fontWeight:600}:void 0,children:["drafts ",x.length]}),e.jsxs("button",{onClick:()=>u(!c),"aria-pressed":c,title:c?"Hide shadow drafts (the pilot dry run)":"Show shadow drafts (the pilot dry run)",className:"sb-rail-toggle",style:c?{color:"var(--sbc-foreground)",fontWeight:600}:void 0,children:["shadow ",c?"on":"off"]})]}):void 0,At=e.jsx("div",{onTouchStart:g?lt:void 0,onTouchEnd:g?tt:void 0,style:{flex:1,minHeight:0,minWidth:0,display:"flex",flexDirection:"column"},children:e.jsx(Sd,{access:r,onConnectSlack:()=>{o.connectSlack()},profileId:n.profileId||"",compact:g,impersonating:n.impersonating,forcedLane:g?qe:null,hideLanes:!1,onDragMessage:g?void 0:M,onDragEnd:()=>{M(null),W(null)},renderMessageActions:Ie,defaultAnchorToLastInbound:!0,aboveComposer:Ke||void 0,onFeedReady:U,railOnly:f?x:null,railExtras:Ht,renderReplyDraft:p&&m?({accountId:ne,fillComposer:Ce,showMessage:Qe})=>e.jsx(tL,{accountId:ne,showShadow:c,viewerUid:m.uid,compact:g,onUse:Ce,onShowMessage:Qe,onOpenTicket:Fe}):void 0})});return e.jsxs("div",{className:"sb-chat bg-background sb-viewport-column",children:[e.jsx(Xe,{rightAction:J?e.jsx("div",{className:"bg-foreground text-background",style:{padding:"6px 12px",borderRadius:999,fontSize:12,whiteSpace:"nowrap"},children:J}):void 0}),!o.loading&&!o.isConnected&&de.length>0&&e.jsxs("div",{className:"bg-secondary border-b border-border",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px"},children:[e.jsx(Dt,{size:14,className:"text-destructive",style:{flexShrink:0}}),e.jsxs("div",{className:"text-foreground truncate",style:{flex:1,minWidth:0,fontSize:12},children:[e.jsx("strong",{children:"Connect Slack"})," to reply to ",de.length," ",de.length===1?"client":"clients"," still reading there â replies go out as you, not as a bot."]}),e.jsx("button",{onClick:()=>{o.connectSlack()},className:"bg-primary text-primary-foreground",style:{flexShrink:0,minHeight:28,padding:"0 12px",borderRadius:14,fontSize:12,fontWeight:600},children:"Connect"})]}),g&&e.jsx("div",{className:"bg-card border-b border-border",style:{display:"flex",gap:6,padding:"8px 12px"},children:["feed","triage"].map(ne=>e.jsxs("button",{onClick:()=>We(ne),className:Ae===ne?"bg-foreground text-background":"bg-card text-foreground border border-border",style:{flex:1,minHeight:44,borderRadius:22,fontSize:14,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:8},children:[ne==="feed"?"Feed":"Triage",ne==="triage"&&e.jsx("span",{className:"bg-secondary text-foreground",style:{minWidth:22,height:22,padding:"0 7px",borderRadius:11,fontSize:12,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:j.length})]},ne))}),g?Ae==="feed"?At:e.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:[Te&&e.jsxs("div",{className:"bg-muted text-foreground",style:{margin:12,padding:"8px 10px",borderRadius:6,fontSize:12,display:"flex",alignItems:"center",gap:8},children:[e.jsx(gr,{size:14})," Pick a ticket or draft to attach to ",e.jsx("button",{onClick:()=>He(null),style:{marginLeft:"auto"},children:e.jsx(mt,{size:14})})]}),le]}):e.jsxs("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"row"},children:[At,e.jsxs("aside",{className:"bg-card border-l border-border",style:{width:360,display:"flex",flexDirection:"column",flexShrink:0},children:[e.jsxs("div",{className:"border-b border-border",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 10px 16px"},children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-foreground",style:{fontSize:15,fontWeight:700},children:"Triage"}),e.jsx("div",{className:"text-muted-foreground",style:{fontSize:12},children:"Drafted tickets · you decide"})]}),e.jsx("span",{className:"bg-secondary text-foreground",style:{minWidth:24,height:24,padding:"0 8px",borderRadius:12,fontSize:12,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:j.length})]}),e.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",display:"flex",flexDirection:"column"},children:le})]})]})]})}function hn({title:t,count:s,loading:n,error:r,searchValue:a,onSearchChange:o,onBack:i,onLogoClick:d,tabs:m,activeTab:p,onTabChange:c,onCreate:u,children:x}){return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:d}),e.jsxs("div",{className:"max-w-4xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("button",{onClick:i,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:20,height:20}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground",children:t}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s," records"]})]}),u&&e.jsxs("button",{onClick:u,className:"bg-primary text-primary-foreground",style:{display:"flex",alignItems:"center",gap:4,padding:"6px 14px",borderRadius:8,fontSize:13,fontWeight:500},children:[e.jsx(Ut,{style:{width:16,height:16}})," New"]})]}),e.jsxs("div",{style:{position:"relative",marginBottom:16},children:[e.jsx(Pt,{className:"text-muted-foreground",style:{position:"absolute",left:12,top:"50%",transform:"translateY(-50%)",width:16,height:16,pointerEvents:"none"}}),e.jsx("input",{type:"text",placeholder:"Search...",value:a,onChange:h=>o(h.target.value),className:"bg-card border border-border text-foreground placeholder:text-muted-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary/30",style:{width:"100%",paddingLeft:36,paddingRight:16,paddingTop:8,paddingBottom:8,borderRadius:8}})]}),m&&c&&e.jsx("div",{className:"flex flex-wrap gap-1 mb-4",children:m.map(h=>e.jsxs("button",{onClick:()=>c(h.key),className:`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-colors ${p===h.key?"bg-primary text-primary-foreground":"bg-card text-muted-foreground hover:text-foreground border border-border"}`,children:[h.label,h.count!==void 0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",h.count,")"]})]},h.key))}),n?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(fe,{className:"animate-spin mr-2",style:{width:20,height:20}}),"Loading..."]}):r?e.jsx("div",{className:"bg-red-500/10 text-red-400 p-4 rounded-lg text-sm",children:r}):x]})]})}function nr({onDelete:t,label:s="Delete Record"}){const[n,r]=l.useState(!1),[a,o]=l.useState(!1);return n?e.jsxs("div",{className:"border-t border-border",style:{padding:"12px 0",marginTop:12,display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{className:"text-sm text-foreground",children:"Are you sure?"}),e.jsx("button",{onClick:async()=>{o(!0),await t(),o(!1),r(!1)},disabled:a,style:{padding:"6px 14px",borderRadius:8,fontSize:13,fontWeight:500,backgroundColor:"#ef4444",color:"white",opacity:a?.6:1},children:a?"Deleting...":"Yes, delete"}),e.jsx("button",{onClick:()=>r(!1),className:"text-muted-foreground text-sm hover:text-foreground",style:{padding:"6px 14px"},children:"Cancel"})]}):e.jsx("div",{className:"border-t border-border",style:{padding:"12px 0",marginTop:12},children:e.jsxs("button",{onClick:()=>r(!0),style:{display:"flex",alignItems:"center",gap:6,fontSize:13,color:"#ef4444"},children:[e.jsx(zs,{style:{width:14,height:14}})," ",s]})})}const rL=["monthly","weekly","quarterly"];function aL({onBack:t,onLogoClick:s}){const{rows:n,loading:r,error:a,updateRow:o,deleteRow:i}=Xt({collectionName:"recurringTemplates",orderByField:"updatedAt",orderDirection:"desc"}),{rows:d}
422=Xt({collectionName:"clients",orderByField:"name",orderDirection:"asc"}),m=l.useMemo(()=>d.map(Y=>({id:Y.id,label:Y.name})),[d]),{rows:p}=Xt({collectionName:"clientProjects",orderByField:"name",orderDirection:"asc"}),{rows:c}=Xt({collectionName:"shopifyStores",orderByField:"name",orderDirection:"asc"}),u=l.useMemo(()=>c.map(Y=>({id:Y.id,label:Y.myshopifyUrl||Y.name})),[c]),[x,h]=l.useState(""),[b,f]=l.useState("all"),[g,y]=l.useState(null),[j,v]=l.useState(null),[T,k]=l.useState(""),w=l.useRef(!1),[I,A]=l.useState(!1),[E,C]=l.useState(null),[N,S]=l.useState([]);l.useEffect(()=>{if(!g){S([]);return}const Y=Ge(Re(ge,"tickets"),Ve("recurringTemplateId","==",g.id),Nt("createdAt","desc"));return qt(Y,H=>{S(H.docs.map(Z=>({id:Z.id,...Z.data()})))})},[g==null?void 0:g.id]);const O=l.useMemo(()=>{let Y=n;return b==="active"?Y=Y.filter(J=>J.active):b==="paused"&&(Y=Y.filter(J=>!J.active)),Y=Y.filter(Js(x,J=>[J.name,J.clientName,J.projectName])),Y},[n,b,x]),R=l.useMemo(()=>({all:n.length,active:n.filter(Y=>Y.active).length,paused:n.filter(Y=>!Y.active).length}),[n]),z=[{key:"all",label:"All",count:R.all},{key:"active",label:"Active",count:R.active},{key:"paused",label:"Paused",count:R.paused}],D=(Y,J)=>{v(Y),k(J)},L=l.useCallback(async()=>{if(!g||!j)return;const J=["creditsMin","creditsMax","dayOfMonth"].includes(j)?T===""?null:Number(T):T;await o(g.id,{[j]:J}),y({...g,[j]:J}),v(null)},[g,j,T,o]),$=l.useCallback(async(Y,J)=>{g&&(await o(g.id,{[Y]:J}),y({...g,[Y]:J}))},[g,o]),q=l.useCallback(async Y=>{g&&(await o(g.id,{clientId:Y.id,clientName:Y.label,projectId:null,projectName:null}),y({...g,clientId:Y.id,clientName:Y.label,projectId:null,projectName:null}))},[g,o]),P=l.useMemo(()=>g!=null&&g.clientId?p.filter(Y=>Y.clientId===g.clientId).map(Y=>({id:Y.id,label:Y.name})):p.map(Y=>({id:Y.id,label:Y.name})),[p,g==null?void 0:g.clientId]),U=l.useCallback(async Y=>{g&&(await o(g.id,{projectId:Y.id,projectName:Y.label}),y({...g,projectId:Y.id,projectName:Y.label}))},[g,o]),V=l.useCallback(async Y=>{g&&(await o(g.id,{shopifyStoreId:Y.id}),y({...g,shopifyStoreId:Y.id}))},[g,o]),[M,F]=l.useState(null);l.useEffect(()=>{if(!M)return;const Y=n.find(J=>J.id===M);Y&&(y(Y),F(null))},[n,M]);const W=l.useCallback(async()=>{const Y=await Ma(Re(ge,"recurringTemplates"),{name:"New Template",projectId:null,projectName:null,clientId:null,clientName:null,shopifyStoreId:null,shopifyThemeId:null,pageUrl:null,content:null,creditsMin:null,creditsMax:null,rushOrder:!1,frequency:"monthly",dayOfMonth:1,active:!1,autoApprove:!1,lastGeneratedAt:null,lastGeneratedTicketId:null,createdAt:ss(),updatedAt:ss()});F(Y.id)},[]),{user:_}=pt(),G=l.useCallback(async()=>{var Y,J,H,Z,Q;if(g){if(!_){C("Authentication required");return}A(!0),C(null);try{const K=await _.getIdToken();if(!K)throw new Error("Failed to retrieve authentication token");const X=await fetch(`https://us-central1-bucky-app-355a3.cloudfunctions.net/triggerRecurringTickets?templateId=${g.id}`,{method:"POST",headers:{Authorization:`Bearer ${K}`}});if(!X.ok)throw new Error(`HTTP error! Status: ${X.status}`);const se=await X.json();se.success&&((Y=se.summary)==null?void 0:Y.ticketsCreated)>0?C(`Created ${((J=se.summary.results[0])==null?void 0:J.ticketDisplayId)||"ticket"}`):(Q=(Z=(H=se.summary)==null?void 0:H.results)==null?void 0:Z[0])!=null&&Q.error?C(`Error: ${se.summary.results[0].error}`):C(se.message||"No ticket generated")}catch(K){const X=K instanceof Error?K.message:"Failed to generate";C(X)}finally{A(!1)}}},[g,_]),B={editField:j,editValue:T,onEdit:D,onSave:L,onEditValueChange:k};return e.jsxs(hn,{title:"Recurring Templates",count:O.length,loading:r,error:a,onCreate:W,searchValue:x,onSearchChange:h,onBack:t,onLogoClick:s,tabs:z,activeTab:b,onTabChange:f,children:[e.jsxs("div",{className:"space-y-2",children:[O.map(Y=>e.jsx("button",{onClick:()=>{y(Y),C(null)},className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${Y.active?"bg-green-100 text-green-700":"bg-gray-100 text-gray-500"}`,children:Y.active?"Active":"Paused"}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-medium bg-blue-100 text-blue-700",children:Y.frequency}),Y.autoApprove&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-medium bg-purple-100 text-purple-700",children:"Auto-Approve"})]}),e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:Y.name}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[Y.clientName&&e.jsx("span",{children:Y.clientName}),Y.creditsMax!=null&&e.jsxs("span",{children:[Y.creditsMax," cr"]}),Y.lastGeneratedAt&&e.jsxs("span",{children:["Last: ",nt(Y.lastGeneratedAt)]})]})]})})},Y.id)),O.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No templates found"})]}),g&&e.jsxs(Cs,{title:g.name,onClose:()=>{y(null),v(null),C(null)},footer:e.jsx(nr,{onDelete:async()=>{await i(g.id),y(null)}}),children:[e.jsx(De,{title:"Details"}),e.jsx(oe,{label:"Name",value:g.name,field:"name",...B}),e.jsx(oe,{label:"Frequency",value:g.frequency,field:"frequency",...B,options:rL,onDirectSave:$}),e.jsx(oe,{label:"Day of Month",value:g.dayOfMonth!=null?String(g.dayOfMonth):"1",field:"dayOfMonth",...B,numeric:!0}),e.jsx(oe,{label:"Active",value:"",field:"active",...B,checkbox:!0,checked:g.active,onDirectSave:$}),e.jsx(oe,{label:"Auto-Approve",value:"",field:"autoApprove",...B,checkbox:!0,checked:g.autoApprove,onDirectSave:$}),e.jsx(oe,{label:"Rush Order",value:"",field:"rushOrder",...B,checkbox:!0,checked:g.rushOrder,onDirectSave:$}),e.jsx(De,{title:"Client & Project"}),e.jsx(oe,{label:"Client",value:g.clientName||"",field:"clientName",...B,lookupItems:m,onLookupSelect:q}),e.jsx(oe,{label:"Project",value:g.projectName||"",field:"projectName",...B,lookupItems:P,onLookupSelect:U}),e.jsx(oe,{label:"Shopify Store",value:g.shopifyStoreId||"",field:"shopifyStoreId",...B,lookupItems:u,onLookupSelect:V}),e.jsx(oe,{label:"Page URL",value:g.pageUrl||"",field:"pageUrl",...B}),e.jsx(oe,{label:"Shopify Theme ID",value:g.shopifyThemeId||"",field:"shopifyThemeId",...B}),e.jsx(De,{title:"Credits"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(oe,{label:"Credits Min",value:g.creditsMin!=null?String(g.creditsMin):"",field:"creditsMin",...B,numeric:!0}),e.jsx(oe,{label:"Credits Max",value:g.creditsMax!=null?String(g.creditsMax):"",field:"creditsMax",...B,numeric:!0})]}),e.jsx(De,{title:"Content"}),j==="content"?e.jsx("div",{children:e.jsx("textarea",{autoFocus:!0,value:T,onChange:Y=>k(Y.target.value),onKeyDown:Y=>{Y.key==="Escape"&&(w.current=!0,v(null))},onBlur:()=>{w.current||L(),w.current=!1},rows:8,className:"bg-background border border-primary text-sm text-foreground focus:outline-none",style:{width:"100%",padding:"8px 12px",borderRadius:8,resize:"vertical"}})}):e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Template Content (copied to generated tickets)"}),e.jsxs("button",{onClick:()=>D("content",g.content||""),className:"text-muted-foreground hover:text-foreground",style:{display:"flex",alignItems:"center",gap:4,fontSize:12},children:[e.jsx(Na,{style:{width:12,height:12}})," Edit"]})]}),e.jsx("div",{className:"bg-background border border-border text-sm text-foreground prose prose-sm dark:prose-invert max-w-none",style:{padding:12,borderRadius:8,maxHeight:200,overflowY:"auto"},children:g.content?e.jsx(Ta,{children:g.content}):e.jsx("span",{className:"text-muted-foreground italic",children:"No content"})})]}),e.jsx(De,{title:"Generate"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e.jsxs("button",{onClick:G,disabled:I,className:"bg-primary text-primary-foreground",style:{display:"flex",alignItems:"center",gap:6,padding:"8px 16px",borderRadius:8,fontSize:13,fontWeight:500,opacity:I?.5:1},children:[I?e.jsx(fe,{style:{width:14,height:14},className:"animate-spin"}):e.jsx(In,{style:{width:14,height:14}}),"Generate Now"]}),E&&e.jsx("span",{className:"text-sm text-muted-foreground",children:E})]}),N.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(De,{title:`Generated Tickets (${N.length})`}),e.jsx("div",{className:"space-y-1.5",style:{maxHeight:200,overflowY:"auto"},children:N.map(Y=>e.jsxs("div",{className:"flex items-center justify-between bg-background border border-border rounded-md px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:Y.displayId}),e.jsx("span",{className:"text-sm text-foreground truncate",children:Y.name})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600",children:Y.status}),e.jsx("span",{className:"text-xs text-muted-foreground",children:nt(Y.createdAt)})]})]},Y.id))})]}),e.jsx(De,{title:"Metadata"}),e.jsx(oe,{label:"Last Generated",value:nt(g.lastGeneratedAt),field:"",...B,readOnly:!0}),e.jsx(oe,{label:"Created",value:nt(g.createdAt),field:"",...B,readOnly:!0}),e.jsx(oe,{label:"Updated",value:nt(g.updatedAt),field:"",...B,readOnly:!0})]})]})}const od="https://us-central1-bucky-app-355a3.cloudfunctions.net",oL={chatting:"bg-blue-100 text-blue-700",quoted:"bg-amber-100 text-amber-700",purchased:"bg-green-100 text-green-700",stale:"bg-gray-100 text-gray-400"};function iL({onBack:t,onLogoClick:s}){var I,A,E;const[n,r]=l.useState([]),[a,o]=l.useState(!0),[i,d]=l.useState(""),[m,p]=l.useState("all"),[c,u]=l.useState(null),[x,h]=l.useState([]),[b,f]=l.useState(!1),[g,y]=l.useState(!1),j=l.useCallback(async()=>{o(!0);try{const C=await fetch(`${od}/listPublicChatLeads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({limit:100})});if(!C.ok)throw new Error("Network response was not ok");const N=await C.json();r(N.leads||[])}catch(C){console.error("Failed to fetch leads:",C)}finally{o(!1)}},[]);l.useEffect(()=>{j()},[j]);const v=async C=>{u(C),h([]),f(!0);try{const N=await fetch(`${od}/getPublicChatHistory`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:C.id})});if(!N.ok)throw new Error(`HTTP error! Status: ${N.status}`);const S=await N.json();Array.isArray(S.messages)?h(S.messages):console.error("Invalid messages format received:",S.messages)}catch(N){console.error("Failed to fetch chat history:",N)}finally{f(!1)}},T=async()=>
422{if(c){y(!0);try{const N=await(await fetch(`${od}/summarizePublicChat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:c.id})})).json();N.summary&&(u({...c,summary:N.summary}),r(S=>S.map(O=>O.id===c.id?{...O,summary:N.summary}:O)))}catch{}finally{y(!1)}}},k=n.filter(C=>{var N,S,O;if(m!=="all"&&C.status!==m)return!1;if(i){const R=i.toLowerCase();return((N=C.name)==null?void 0:N.toLowerCase().includes(R))||((S=C.email)==null?void 0:S.toLowerCase().includes(R))||((O=C.firstMessage)==null?void 0:O.toLowerCase().includes(R))}return!0}),w=[{key:"all",label:"All",count:n.length},{key:"chatting",label:"Chatting",count:n.filter(C=>C.status==="chatting").length},{key:"quoted",label:"Quoted",count:n.filter(C=>C.status==="quoted").length},{key:"purchased",label:"Purchased",count:n.filter(C=>C.status==="purchased").length}];return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:20,height:20}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Chat Leads"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[n.length," conversations"]})]}),e.jsx("button",{onClick:j,disabled:a,className:"text-muted-foreground hover:text-foreground p-2",children:e.jsx(yt,{style:{width:18,height:18},className:a?"animate-spin":""})})]}),e.jsxs("div",{style:{position:"relative",marginBottom:12},children:[e.jsx(Pt,{className:"text-muted-foreground",style:{position:"absolute",left:12,top:"50%",transform:"translateY(-50%)",width:16,height:16,pointerEvents:"none"}}),e.jsx("input",{type:"text",placeholder:"Search leads...",value:i,onChange:C=>d(C.target.value),className:"bg-card border border-border text-foreground placeholder:text-muted-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary/30",style:{width:"100%",paddingLeft:36,paddingRight:16,paddingTop:8,paddingBottom:8,borderRadius:8}})]}),e.jsx("div",{className:"flex flex-wrap gap-1 mb-4",children:w.map(C=>e.jsxs("button",{onClick:()=>p(C.key),className:`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-colors ${m===C.key?"bg-primary text-primary-foreground":"bg-card text-muted-foreground hover:text-foreground border border-border"}`,children:[C.label," ",e.jsxs("span",{className:"ml-1 opacity-70",children:["(",C.count,")"]})]},C.key))}),e.jsxs("div",{className:"flex gap-4",style:{minHeight:500},children:[e.jsx("div",{className:"w-1/3 space-y-2 overflow-y-auto",style:{maxHeight:"calc(100vh - 250px)"},children:a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(fe,{className:"animate-spin text-muted-foreground",style:{width:20,height:20}})}):k.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No leads found"}):k.map(C=>e.jsxs("button",{onClick:()=>v(C),className:`w-full bg-card border rounded-lg p-3 text-left hover:bg-accent transition-colors ${(c==null?void 0:c.id)===C.id?"border-primary bg-primary/5":"border-border"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${oL[C.status]||"bg-gray-100 text-gray-600"}`,children:C.status}),C.estimatedCredits&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[C.estimatedCredits," cr"]})]}),e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:C.name||"Anonymous"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:C.email||"No email"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:C.firstMessage})]},C.id))}),e.jsx("div",{className:"flex-1 bg-card border border-border rounded-lg overflow-hidden flex flex-col",children:c?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border bg-accent/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground",children:c.name||"Anonymous"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c.email||"No email"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.estimatedCost&&e.jsxs("span",{className:"text-sm font-semibold text-foreground",children:["$",c.estimatedCost]}),e.jsxs("button",{onClick:T,disabled:g,className:"flex items-center gap-1 px-2 py-1 text-xs bg-primary/10 text-primary rounded-md hover:bg-primary/20",children:[g?e.jsx(fe,{style:{width:12,height:12},className:"animate-spin"}):e.jsx(Mn,{style:{width:12,height:12}}),g?"Summarizing...":"Summarize"]})]})]}),c.summary&&e.jsxs("div",{className:"mt-3 p-3 bg-background border border-border rounded-lg text-xs space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Request:"})," ",c.summary.whatClientWants]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Effort:"}
422)," ",c.summary.effortClassification," (",(I=c.summary.estimatedCredits)==null?void 0:I.min,"â",(A=c.summary.estimatedCredits)==null?void 0:A.max," credits)"]}),((E=c.summary.technicalRequirements)==null?void 0:E.length)>0&&e.jsxs("p",{children:[e.jsx("strong",{children:"Technical:"})," ",c.summary.technicalRequirements.join(", ")]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Approach:"})," ",c.summary.recommendedApproach]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Sentiment:"})," ",c.summary.clientSentiment]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-3",children:b?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(fe,{className:"animate-spin text-muted-foreground",style:{width:20,height:20}})}):x.length===0?e.jsx("p",{className:"text-center text-muted-foreground text-sm py-8",children:"No messages"}):x.map((C,N)=>e.jsx("div",{className:`flex ${C.role==="user"?"justify-end":"justify-start"}`,children:e.jsx("div",{className:`max-w-[80%] px-3 py-2 rounded-xl text-sm ${C.role==="user"?"bg-primary text-primary-foreground rounded-br-sm":"bg-accent text-foreground rounded-bl-sm"}`,children:C.text})},N))})]}):e.jsx("div",{className:"flex items-center justify-center flex-1 text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(mn,{style:{width:32,height:32,margin:"0 auto 8px"}}),e.jsx("p",{className:"text-sm",children:"Select a lead to view the conversation"})]})})})]})]})]})}const lc=l.createContext(null);lc.displayName="PanelGroupContext";const Zt={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},im=10,$r=l.useLayoutEffect,bh=S0.useId,lL=typeof bh=="function"?bh:()=>null;let cL=0;function lm(t=null){const s=lL(),n=l.useRef(t||s||null);return n.current===null&&(n.current=""+cL++),t??n.current}function Uy({children:t,className:s="",collapsedSize:n,collapsible:r,defaultSize:a,forwardedRef:o,id:i,maxSize:d,minSize:m,onCollapse:p,onExpand:c,onResize:u,order:x,style:h,tagName:b="div",...f}){const g=l.useContext(lc);if(g===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:y,expandPanel:j,getPanelSize:v,getPanelStyle:T,groupId:k,isPanelCollapsed:w,reevaluatePanelConstraints:I,registerPanel:A,resizePanel:E,unregisterPanel:C}=g,N=lm(i),S=l.useRef({callbacks:{onCollapse:p,onExpand:c,onResize:u},constraints:{collapsedSize:n,collapsible:r,defaultSize:a,maxSize:d,minSize:m},id:N,idIsFromProps:i!==void 0,order:x});l.useRef({didLogMissingDefaultSizeWarning:!1}),$r(()=>{const{callbacks:R,constraints:z}=S.current,D={...z};S.current.id=N,S.current.idIsFromProps=i!==void 0,S.current.order=x,R.onCollapse=p,R.onExpand=c,R.onResize=u,z.collapsedSize=n,z.collapsible=r,z.defaultSize=a,z.maxSize=d,z.minSize=m,(D.collapsedSize!==z.collapsedSize||D.collapsible!==z.collapsible||D.maxSize!==z.maxSize||D.minSize!==z.minSize)&&I(S.current,D)}),$r(()=>{const R=S.current;return A(R),()=>{C(R)}},[x,N,A,C]),l.useImperativeHandle(o,()=>({collapse:()=>{y(S.current)},expand:R=>{j(S.current,R)},getId(){return N},getSize(){return v(S.current)},isCollapsed(){return w(S.current)},isExpanded(){return!w(S.current)},resize:R=>{E(S.current,R)}}),[y,j,v,w,N,E]);const O=T(S.current,a);return l.createElement(b,{...f,children:t,className:s,id:N,style:{...O,...h},[Zt.groupId]:k,[Zt.panel]:"",[Zt.panelCollapsible]:r||void 0,[Zt.panelId]:N,[Zt.panelSize]:parseFloat(""+O.flexGrow).toFixed(1)})}const Hy=l.forwardRef((t,s)=>l.createElement(Uy,{...t,forwardedRef:s}));Uy.displayName="Panel";Hy.displayName="forwardRef(Panel)";let Kd=null,al=-1,mr=null;function dL(t,s,n){const r=(s&Ky)!==0,a=(s&Qy)!==0,o=(s&Jy)!==0,i=(s&Zy)!==0;if(s){if(r)return o?"se-resize":i?"ne-resize":"e-resize";if(a)return o?"sw-resize":i?"nw-resize":"w-resize";if(o)return"s-resize";if(i)return"n-resize"}switch(t){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function uL(){mr!==null&&(document.head.removeChild(mr),Kd=null,mr=null,al=-1)}function id(t,s,n){var r,a;const o=dL(t,s);if(Kd!==o){if(Kd=o,mr===null&&(mr=document.createElement("style"),document.head.appendChild(mr)),al>=0){var i;(i=mr.sheet)===null||i===void 0||i.removeRule(al)}al=(r=(a=mr.sheet)===null||a===void 0?void 0:a.insertRule(`*{curs
422or: ${o} !important;}`))!==null&&r!==void 0?r:-1}}function qy(t){return t.type==="keydown"}function Vy(t){return t.type.startsWith("pointer")}function Yy(t){return t.type.startsWith("mouse")}function cc(t){if(Vy(t)){if(t.isPrimary)return{x:t.clientX,y:t.clientY}}else if(Yy(t))return{x:t.clientX,y:t.clientY};return{x:1/0,y:1/0}}function mL(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function pL(t,s,n){return t.x<s.x+s.width&&t.x+t.width>s.x&&t.y<s.y+s.height&&t.y+t.height>s.y}function xL(t,s){if(t===s)throw new Error("Cannot compare node with itself");const n={a:vh(t),b:vh(s)};let r;for(;n.a.at(-1)===n.b.at(-1);)t=n.a.pop(),s=n.b.pop(),r=t;bt(r,"Stacking order can only be calculated for elements with a common ancestor");const a={a:jh(yh(n.a)),b:jh(yh(n.b))};if(a.a===a.b){const o=r.childNodes,i={a:n.a.at(-1),b:n.b.at(-1)};let d=o.length;for(;d--;){const m=o[d];if(m===i.a)return 1;if(m===i.b)return-1}}return Math.sign(a.a-a.b)}const hL=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function fL(t){var s;const n=getComputedStyle((s=Gy(t))!==null&&s!==void 0?s:t).display;return n==="flex"||n==="inline-flex"}function gL(t){const s=getComputedStyle(t);return!!(s.position==="fixed"||s.zIndex!=="auto"&&(s.position!=="static"||fL(t))||+s.opacity<1||"transform"in s&&s.transform!=="none"||"webkitTransform"in s&&s.webkitTransform!=="none"||"mixBlendMode"in s&&s.mixBlendMode!=="normal"||"filter"in s&&s.filter!=="none"||"webkitFilter"in s&&s.webkitFilter!=="none"||"isolation"in s&&s.isolation==="isolate"||hL.test(s.willChange)||s.webkitOverflowScrolling==="touch")}function yh(t){let s=t.length;for(;s--;){const n=t[s];if(bt(n,"Missing node"),gL(n))return n}return null}function jh(t){return t&&Number(getComputedStyle(t).zIndex)||0}function vh(t){const s=[];for(;t;)s.push(t),t=Gy(t);return s}function Gy(t){const{parentNode:s}=t;return s&&s instanceof ShadowRoot?s.host:s}const Ky=1,Qy=2,Jy=4,Zy=8,bL=mL()==="coarse";let un=[],ya=!1,pr=new Map,dc=new Map;const Bo=new Set;function yL(t,s,n,r,a){var o;const{ownerDocument:i}=s,d={direction:n,element:s,hitAreaMargins:r,setResizeHandlerState:a},m=(o=pr.get(i))!==null&&o!==void 0?o:0;return pr.set(i,m+1),Bo.add(d),Cl(),function(){var c;dc.delete(t),Bo.delete(d);const u=(c=pr.get(i))!==null&&c!==void 0?c:1;if(pr.set(i,u-1),Cl(),u===1&&pr.delete(i),un.includes(d)){const x=un.indexOf(d);x>=0&&un.splice(x,1),uc(),a("up",!0,null)}}}function jL(t){const{target:s}=t,{x:n,y:r}=cc(t);ya=!0,cm({target:s,x:n,y:r}),Cl(),un.length>0&&(Tl("down",t),uc(),t.preventDefault(),Xy(s)||t.stopImmediatePropagation())}function ld(t){const{x:s,y:n}=cc(t);if(ya&&t.type!=="pointerleave"&&t.buttons===0&&(ya=!1,Tl("up",t)),!ya){const{target:r}=t;cm({target:r,x:s,y:n})}Tl("move",t),uc(),un.length>0&&t.preventDefault()}function cd(t){const{target:s}=t,{x:n,y:r}=cc(t);dc.clear(),ya=!1,un.length>0&&(t.preventDefault(),Xy(s)||t.stopImmediatePropagation()),Tl("up",t),cm({target:s,x:n,y:r}),uc(),Cl()}function Xy(t){let s=t;for(;s;){if(s.hasAttribute(Zt.resizeHandle))return!0;s=s.parentElement}return!1}function cm({target:t,x:s,y:n}){un.splice(0);let r=null;(t instanceof HTMLElement||t instanceof SVGElement)&&(r=t),Bo.forEach(a=>{const{element:o,hitAreaMargins:i}=a,d=o.getBoundingClientRect(),{bottom:m,left:p,right:c,top:u}=d,x=bL?i.coarse:i.fine;if(s>=p-x&&s<=c+x&&n>=u-x&&n<=m+x){if(r!==null&&document.contains(r)&&o!==r&&!o.contains(r)&&!r.contains(o)&&xL(r,o)>0){let b=r,f=!1;for(;b&&!b.contains(o);){if(pL(b.getBoundingClientRect(),d)){f=!0;break}b=b.parentElement}if(f)return}un.push(a)}})}function dd(t,s){dc.set(t,s)}function uc(){let t=!1,s=!1;un.forEach(r=>{const{direction:a}=r;a==="horizontal"?t=!0:s=!0});let n=0;dc.forEach(r=>{n|=r}),t&&s?id("intersection",n):t?id("horizontal",n):s?id("vertical",n):uL()}let ud;function Cl(){var t;(t=ud)===null||t===void 0||t.abort(),ud=new AbortController;const s={capture:!0,signal:ud.signal};Bo.size&&(ya?(un.length>0&&pr.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("contextmenu",cd,s),a.addEventListener("pointerleave",ld,s),a.addEventListener("pointermove",ld,s))}),pr.forEach((n,r)=>{const{body:a}=r;a.addEventListener("pointerup",cd,s),a.addEventListener("pointercancel",cd,s)})):pr.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("pointerdown",jL,s),a.addEventListener("pointermove",ld,s))}))}
422function Tl(t,s){Bo.forEach(n=>{const{setResizeHandlerState:r}=n,a=un.includes(n);r(t,a,s)})}function vL(){const[t,s]=l.useState(0);return l.useCallback(()=>s(n=>n+1),[])}function bt(t,s){if(!t)throw console.error(s),Error(s)}function Ur(t,s,n=im){return t.toFixed(n)===s.toFixed(n)?0:t>s?1:-1}function Yn(t,s,n=im){return Ur(t,s,n)===0}function Us(t,s,n){return Ur(t,s,n)===0}function wL(t,s,n){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r++){const a=t[r],o=s[r];if(!Us(a,o,n))return!1}return!0}function ha({panelConstraints:t,panelIndex:s,size:n}){const r=t[s];bt(r!=null,`Panel constraints not found for index ${s}`);let{collapsedSize:a=0,collapsible:o,maxSize:i=100,minSize:d=0}=r;if(Ur(n,d)<0)if(o){const m=(a+d)/2;Ur(n,m)<0?n=a:n=d}else n=d;return n=Math.min(i,n),n=parseFloat(n.toFixed(im)),n}function go({delta:t,initialLayout:s,panelConstraints:n,pivotIndices:r,prevLayout:a,trigger:o}){if(Us(t,0))return s;const i=[...s],[d,m]=r;bt(d!=null,"Invalid first pivot index"),bt(m!=null,"Invalid second pivot index");let p=0;if(o==="keyboard"){{const u=t<0?m:d,x=n[u];bt(x,`Panel constraints not found for index ${u}`);const{collapsedSize:h=0,collapsible:b,minSize:f=0}=x;if(b){const g=s[u];if(bt(g!=null,`Previous layout not found for panel index ${u}`),Us(g,h)){const y=f-g;Ur(y,Math.abs(t))>0&&(t=t<0?0-y:y)}}}{const u=t<0?d:m,x=n[u];bt(x,`No panel constraints found for index ${u}`);const{collapsedSize:h=0,collapsible:b,minSize:f=0}=x;if(b){const g=s[u];if(bt(g!=null,`Previous layout not found for panel index ${u}`),Us(g,f)){const y=g-h;Ur(y,Math.abs(t))>0&&(t=t<0?0-y:y)}}}}{const u=t<0?1:-1;let x=t<0?m:d,h=0;for(;;){const f=s[x];bt(f!=null,`Previous layout not found for panel index ${x}`);const y=ha({panelConstraints:n,panelIndex:x,size:100})-f;if(h+=y,x+=u,x<0||x>=n.length)break}const b=Math.min(Math.abs(t),Math.abs(h));t=t<0?0-b:b}{let x=t<0?d:m;for(;x>=0&&x<n.length;){const h=Math.abs(t)-Math.abs(p),b=s[x];bt(b!=null,`Previous layout not found for panel index ${x}`);const f=b-h,g=ha({panelConstraints:n,panelIndex:x,size:f});if(!Us(b,g)&&(p+=b-g,i[x]=g,p.toFixed(3).localeCompare(Math.abs(t).toFixed(3),void 0,{numeric:!0})>=0))break;t<0?x--:x++}}if(wL(a,i))return a;{const u=t<0?m:d,x=s[u];bt(x!=null,`Previous layout not found for panel index ${u}`);const h=x+p,b=ha({panelConstraints:n,panelIndex:u,size:h});if(i[u]=b,!Us(b,h)){let f=h-b,y=t<0?m:d;for(;y>=0&&y<n.length;){const j=i[y];bt(j!=null,`Previous layout not found for panel index ${y}`);const v=j+f,T=ha({panelConstraints:n,panelIndex:y,size:v});if(Us(j,T)||(f-=T-j,i[y]=T),Us(f,0))break;t>0?y--:y++}}}const c=i.reduce((u,x)=>x+u,0);return Us(c,100)?i:a}function NL({layout:t,panelsArray:s,pivotIndices:n}){let r=0,a=100,o=0,i=0;const d=n[0];bt(d!=null,"No pivot index found"),s.forEach((u,x)=>{const{constraints:h}=u,{maxSize:b=100,minSize:f=0}=h;x===d?(r=f,a=b):(o+=f,i+=b)});const m=Math.min(a,100-o),p=Math.max(r,100-i),c=t[d];return{valueMax:m,valueMin:p,valueNow:c}}function Fo(t,s=document){return Array.from(s.querySelectorAll(`[${Zt.resizeHandleId}][data-panel-group-id="${t}"]`))}function e0(t,s,n=document){const a=Fo(t,n).findIndex(o=>o.getAttribute(Zt.resizeHandleId)===s);return a??null}function t0(t,s,n){const r=e0(t,s,n);return r!=null?[r,r+1]:[-1,-1]}function kL(t){return t instanceof HTMLElement?!0:typeof t=="object"&&t!==null&&"tagName"in t&&"getAttribute"in t}function s0(t,s=document){if(kL(s)&&s.dataset.panelGroupId==t)return s;
422const n=s.querySelector(`[data-panel-group][data-panel-group-id="${t}"]`);return n||null}function mc(t,s=document){const n=s.querySelector(`[${Zt.resizeHandleId}="${t}"]`);return n||null}function SL(t,s,n,r=document){var a,o,i,d;const m=mc(s,r),p=Fo(t,r),c=m?p.indexOf(m):-1,u=(a=(o=n[c])===null||o===void 0?void 0:o.id)!==null&&a!==void 0?a:null,x=(i=(d=n[c+1])===null||d===void 0?void 0:d.id)!==null&&i!==void 0?i:null;return[u,x]}function CL({committedValuesRef:t,eagerValuesRef:s,groupId:n,layout:r,panelDataArray:a,panelGroupElement:o,setLayout:i}){l.useRef({didWarnAboutMissingResizeHandle:!1}),$r(()=>{if(!o)return;const d=Fo(n,o);for(let m=0;m<a.length-1;m++){const{valueMax:p,valueMin:c,valueNow:u}=NL({layout:r,panelsArray:a,pivotIndices:[m,m+1]}),x=d[m];if(x!=null){const h=a[m];bt(h,`No panel data found for index "${m}"`),x.setAttribute("aria-controls",h.id),x.setAttribute("aria-valuemax",""+Math.round(p)),x.setAttribute("aria-valuemin",""+Math.round(c)),x.setAttribute("aria-valuenow",u!=null?""+Math.round(u):"")}}return()=>{d.forEach((m,p)=>{m.removeAttribute("aria-controls"),m.removeAttribute("aria-valuemax"),m.removeAttribute("aria-valuemin"),m.removeAttribute("aria-valuenow")})}},[n,r,a,o]),l.useEffect(()=>{if(!o)return;const d=s.current;bt(d,"Eager values not found");const{panelDataArray:m}=d,p=s0(n,o);bt(p!=null,`No group found for id "${n}"`);const c=Fo(n,o);bt(c,`No resize handles found for group id "${n}"`);const u=c.map(x=>{const h=x.getAttribute(Zt.resizeHandleId);bt(h,"Resize handle element has no handle id attribute");const[b,f]=SL(n,h,m,o);if(b==null||f==null)return()=>{};const g=y=>{if(!y.defaultPrevented)switch(y.key){case"Enter":{y.preventDefault();const j=m.findIndex(v=>v.id===b);if(j>
422=0){const v=m[j];bt(v,`No panel data found for index ${j}`);const T=r[j],{collapsedSize:k=0,collapsible:w,minSize:I=0}=v.constraints;if(T!=null&&w){const A=go({delta:Us(T,k)?I-k:k-T,initialLayout:r,panelConstraints:m.map(E=>E.constraints),pivotIndices:t0(n,h,o),prevLayout:r,trigger:"keyboard"});r!==A&&i(A)}}break}}};return x.addEventListener("keydown",g),()=>{x.removeEventListener("keydown",g)}});return()=>{u.forEach(x=>x())}},[o,t,s,n,r,a,i])}function wh(t,s){if(t.length!==s.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==s[n])return!1;return!0}function n0(t,s){const n=t==="horizontal",{x:r,y:a}=cc(s);return n?r:a}function TL(t,s,n,r,a){const o=n==="horizontal",i=mc(s,a);bt(i,`No resize handle element found for id "${s}"`);const d=i.getAttribute(Zt.groupId);bt(d,"Resize handle element has no group id attribute");let{initialCursorPosition:m}=r;const p=n0(n,t),c=s0(d,a);bt(c,`No group element found for id "${d}"`);const u=c.getBoundingClientRect(),x=o?u.width:u.height;return(p-m)/x*100}function AL(t,s,n,r,a,o){if(qy(t)){const i=n==="horizontal";let d=0;t.shiftKey?d=100:a!=null?d=a:d=10;let m=0;switch(t.key){case"ArrowDown":m=i?0:d;break;case"ArrowLeft":m=i?-d:0;break;case"ArrowRight":m=i?d:0;break;case"ArrowUp":m=i?0:-d;break;case"End":m=100;break;case"Home":m=-100;break}return m}else return r==null?0:TL(t,s,n,r,o)}function EL({panelDataArray:t}){const s=Array(t.length),n=t.map(o=>o.constraints);let r=0,a=100;for(let o=0;o<t.length;o++){const i=n[o];bt(i,`Panel constraints not found for index ${o}`);const{defaultSize:d}=i;d!=null&&(r++,s[o]=d,a-=d)}for(let o=0;o<t.length;o++){const i=n[o];bt(i,`Panel constraints not found for index ${o}`);const{defaultSize:d}=i;if(d!=null)continue;const m=t.length-r,p=a/m;r++,s[o]=p,a-=p}return s}function oa(t,s,n){s.forEach((r,a)=>{const o=t[a];bt(o,`Panel data not found for index ${a}`);const{callbacks:i,constraints:d,id:m}=o,{collapsedSize:p=0,collapsible:c}=d,u=n[m];if(u==null||r!==u){n[m]=r;const{onCollapse:x,onExpand:h,onResize:b}=i;b&&b(r,u),c&&(x||h)&&(h&&(u==null||Yn(u,p))&&!Yn(r,p)&&h(),x&&(u==null||!Yn(u,p))&&Yn(r,p)&&x())}})}function Mi(t,s){if(t.length!==s.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!=s[n])return!1;return!0}function IL({defaultSize:t,dragState:s,layout:n,panelData:r,panelIndex:a,precision:o=3}){const i=n[a];let d;return i==null?d=t!=null?t.toFixed(o):"1":r.length===1?d="1":d=i.toFixed(o),{flexBasis:0,flexGrow:d,flexShrink:1,overflow:"hidden",pointerEvents:s!==null?"none":void 0}}function RL(t,s=10){let n=null;return(...a)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{t(...a)},s)}}function Nh(t){try{if(typeof localStorage<"u")t.getItem=s=>localStorage.getItem(s),t.setItem=(s,n)=>{localStorage.setItem(s,n)};else throw new Error("localStorage not supported in this environment")}catch(s){console.error(s),t.getItem=()=>null,t.setItem=()=>{}}}function r0(t){return`react-resizable-panels:${t}`}function a0(t){return t.map(s=>{const{constraints:n,id:r,idIsFromProps:a,order:o}=s;return a?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((s,n)=>s.localeCompare(n)).join(",")}function o0(t,s){try{const n=r0(t),r=s.getItem(n);if(r){const a=JSON.parse(r);if(typeof a=="object"&&a!=null)return a}}catch{}return null}function DL(t,s,n){var r,a;const o=(r=o0(t,n))!==null&&r!==void 0?r:{},i=a0(s);return(a=o[i])!==null&&a!==void 0?a:null}function ML(t,s,n,r,a){var o;const i=r0(t),d=a0(s),m=(o=o0(t,a))!==null&&o!==void 0?o:{};m[d]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{a.setItem(i,JSON.stringify(m))}catch(p){console.error(p)}}function kh({layout:t,panelConstraints:s}){const n=[...t],r=n.reduce((o,i)=>o+i,0);if(n.length!==s.length)throw Error(`Invalid ${s.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!Us(r,100)&&n.length>0)for(let o=0;o<s.length;o++){const i=n[o];bt(i!=null,`No layout data found for index ${o}`);const d=100/r*i;n[o]=d}let a=0;for(let o=0;o<s.length;o++){const i=n[o];bt(i!=null,`No layout data found for index ${o}`);const d=ha({panelConstraints:s,panelIndex:o,size:i});i!=d&&(a+=i-d,n[o]=d)}if(!Us(a,0))for(let o=0;o<s.length;o++){const i=n[o];bt(i!=null,`No layout data found for index ${o}`);const d=i+a,m=ha({panelConstraints:s,panelIndex:o,size:d});if(i!==m&&(a-=m-i,n[o]=m,Us(a,0)))break}return n}const PL=100,bo={getItem:t=>(Nh(bo),bo.getItem(t)),setItem:(t,s)=>{Nh(bo),bo.setItem(t,s)}},Sh={};function i0({autoSaveId:t=null,children:s,className:n="",direction:r,forwardedRef:a,id:o=null,onLayout:i=null,keyboardResizeBy:d=null,storage:m=bo,style:p,tagName:c="div",...u}){const x=lm(o),h=l.useRef(null),[b,f]=l.useState(null),[g,y]=l.useState([]),j=vL(),v=l.useRef({}),T=l.useRef(new Map),k=l.useRef(0),w=l.useRef({autoSaveId:t,direction:r,dragState:b,id:x,keyboardResizeBy:d,onLayout:i,storage:m}),I=l.useRef({layout:g,panelDataArray:[],panelDataArrayChanged:!1});l.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),l.useImperativeHandle(a,()=>({getId:()=>w.current.id,getLayout:()=>{const{layout:M}=I.current;return M},setLayout:M=>{const{onLayout:F}=w.current,{layout:W,panelDataArray:_}=I.current,G=kh({layout:M,panelConstraints:_.map(B=>B.constraints)});wh(W,G)||(y(G),I.current.layout=G,F&&F(G),oa(_,G,v.current))}}),[]),$r(()=>{w.current.autoSaveId=t,w.current.direction=r,w.current.dragState=b,w.current.id=x,w.current.onLayout=i,w.current.storage=m}),CL({committedValuesRef:w,eagerValuesRef:I,groupId:x,layout:g,panelDataArray:I.current.panelDataArray,setLayout:y,panelGroupElement:h.current}),l.useEffect(()=>{const{panelDataArray:M}=I.current;if(t){if(g.length===0||g.length!==M.length)return;let F=Sh[t];F==null&&(F=RL(ML,PL),Sh[t]=F);const W=[...M],_=new Map(T.current);F(t,W,_,g,m)}},[t,g,m]),l.useEffect(()=>{});const A=l.useCallback(M=>{const{onLayout:F}=w.current,{layout:W,panelDataArray:_}=I.current;if(M.constraints.collapsible){const G=_.map(H=>H.constraints),{collapsedSize:B=0,panelSize:Y,pivotIndices:J}=Er(_,M,W);
422if(bt(Y!=null,`Panel size not found for panel "${M.id}"`),!Yn(Y,B)){T.current.set(M.id,Y);const Z=pa(_,M)===_.length-1?Y-B:B-Y,Q=go({delta:Z,initialLayout:W,panelConstraints:G,pivotIndices:J,prevLayout:W,trigger:"imperative-api"});Mi(W,Q)||(y(Q),I.current.layout=Q,F&&F(Q),oa(_,Q,v.current))}}},[]),E=l.useCallback((M,F)=>{const{onLayout:W}=w.current,{layout:_,panelDataArray:G}=I.current;if(M.constraints.collapsible){const B=G.map(K=>K.constraints),{collapsedSize:Y=0,panelSize:J=0,minSize:H=0,pivotIndices:Z}=Er(G,M,_),Q=F??H;if(Yn(J,Y)){const K=T.current.get(M.id),X=K!=null&&K>=Q?K:Q,pe=pa(G,M)===G.length-1?J-X:X-J,me=go({delta:pe,initialLayout:_,panelConstraints:B,pivotIndices:Z,prevLayout:_,trigger:"imperative-api"});Mi(_,me)||(y(me),I.current.layout=me,W&&W(me),oa(G,me,v.current))}}},[]),C=l.useCallback(M=>{const{layout:F,panelDataArray:W}=I.current,{panelSize:_}=Er(W,M,F);return bt(_!=null,`Panel size not found for panel "${M.id}"`),_},[]),N=l.useCallback((M,F)=>{const{panelDataArray:W}=I.current,_=pa(W,M);return IL({defaultSize:F,dragState:b,layout:g,panelData:W,panelIndex:_})},[b,g]),S=l.useCallback(M=>{const{layout:F,panelDataArray:W}=I.current,{collapsedSize:_=0,collapsible:G,panelSize:B}=Er(W,M,F);return bt(B!=null,`Panel size not found for panel "${M.id}"`),G===!0&&Yn(B,_)},[]),O=l.useCallback(M=>{const{layout:F,panelDataArray:W}=I.current,{collapsedSize:_=0,collapsible:G,panelSize:B}=Er(W,M,F);return bt(B!=null,`Panel size not found for panel "${M.id}"`),!G||Ur(B,_)>0},[]),R=l.useCallback(M=>{const{panelDataArray:F}=I.current;F.push(M),F.sort((W,_)=>{const G=W.order,B=_.order;return G==null&&B==null?0:G==null?-1:B==null?1:G-B}),I.current.panelDataArrayChanged=!0,j()},[j]);$r(()=>{if(I.current.panelDataArrayChanged){I.current.panelDataArrayChanged=!1;const{autoSaveId:M,onLayout:F,storage:W}=w.current,{layout:_,panelDataArray:G}=I.current;let B=null;if(M){const J=DL(M,G,W);J&&(T.current=new Map(Object.entries(J.expandToSizes)),B=J.layout)}B==null&&(B=EL({panelDataArray:G}));const Y=kh({layout:B,panelConstraints:G.map(J=>J.constraints)});wh(_,Y)||(y(Y),I.current.layout=Y,F&&F(Y),oa(G,Y,v.current))}}),$r(()=>{const M=I.current;return()=>{M.layout=[]}},[]);const z=l.useCallback(M=>{let F=!1;const W=h.current;return W&&window.getComputedStyle(W,null).getPropertyValue("direction")==="rtl"&&(F=!0),function(G){G.preventDefault();const B=h.current;if(!B)return()=>null;const{direction:Y,dragState:J,id:H,keyboardResizeBy:Z,onLayout:Q}=w.current,{layout:K,panelDataArray:X}=I.current,{initialLayout:se}=J??{},pe=t0(H,M,B);let me=AL(G,M,Y,J,Z,B);const Ne=Y==="horizontal";Ne&&F&&(me=-me);const at=X.map(ze=>ze.constraints),ae=go({delta:me,initialLayout:se??K,panelConstraints:at,pivotIndices:pe,prevLayout:K,trigger:qy(G)?"keyboard":"mouse-or-touch"}),xe=!Mi(K,ae);(Vy(G)||Yy(G))&&k.current!=me&&(k.current=me,!xe&&me!==0?Ne?dd(M,me<0?Ky:Qy):dd(M,me<0?Jy:Zy):dd(M,0)),xe&&(y(ae),I.current.layout=ae,Q&&Q(ae),oa(X,ae,v.current))}},[]),D=l.useCallback((M,F)=>{const{onLayout:W}=w.current,{layout:_,panelDataArray:G}=I.current,B=G.map(K=>K.constraints),{panelSize:Y,pivotIndices:J}=Er(G,M,_);bt(Y!=null,`Panel size not found for panel "${M.id}"`);const Z=pa(G,M)===G.length-1?Y-F:F-Y,Q=go({delta:Z,initialLayout:_,panelConstraints:B,pivotIndices:J,prevLayout:_,trigger:"imperative-api"});Mi(_,Q)||(y(Q),I.current.layout=Q,W&&W(Q),oa(G,Q,v.current))},[]),L=l.useCallback((M,F)=>{const{layout:W,panelDataArray:_}=I.current,{collapsedSize:G=0,collapsible:B}=F,{collapsedSize:Y=0,collapsible:J,maxSize:H=100,minSize:Z=0}=M.constraints,{panelSize:Q}=Er(_,M,W);Q!=null&&(B&&J&&Yn(Q,G)?Yn(G,Y)||D(M,Y):Q<Z?D(M,Z):Q>H&&D(M,H))},[D]),$=l.useCallback((M,F)=>{const{direction:W}=w.current,{layout:_}=I.current;if(!h.current)return;const G=mc(M,h.current);bt(G,`Drag handle element not found for id "${M}"`);const B=n0(W,F);f({dragHandleId:M,dragHandleRect:G.getBoundingClientRect(),initialCursorPosition:B,initialLayout:_})},[]),q=l.useCallback(()=>{f(null)},[]),P=l.useCallback(M=>{const{panelDataArray:F}=I.current,W=pa(F,M);W>=0&&(F.splice(W,1),delete v.current[M.id],I.current.panelDataArrayChanged=!0,j())},[j]),U=l.useMemo(()=>({collapsePanel:A,direction:r,dragState:b,expandPanel:E,getPanelSize:C,getPanelStyle:N,groupId:x,isPanelCollapsed:S,isPanelExpanded:O,reevaluatePanelConstraints:L,registerPanel:R,registerResizeHandle:z,resizePanel:D,startDragging:$,stopDragging:q,unregisterPanel:P,panelGroupElement:h.current}
422),[A,b,r,E,C,N,x,S,O,L,R,z,D,$,q,P]),V={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return l.createElement(lc.Provider,{value:U},l.createElement(c,{...u,children:s,className:n,id:o,ref:h,style:{...V,...p},[Zt.group]:"",[Zt.groupDirection]:r,[Zt.groupId]:x}))}const l0=l.forwardRef((t,s)=>l.createElement(i0,{...t,forwardedRef:s}));i0.displayName="PanelGroup";l0.displayName="forwardRef(PanelGroup)";function pa(t,s){return t.findIndex(n=>n===s||n.id===s.id)}function Er(t,s,n){const r=pa(t,s),o=r===t.length-1?[r-1,r]:[r,r+1],i=n[r];return{...s.constraints,panelSize:i,pivotIndices:o}}function LL({disabled:t,handleId:s,resizeHandler:n,panelGroupElement:r}){l.useEffect(()=>{if(t||n==null||r==null)return;const a=mc(s,r);if(a==null)return;const o=i=>{if(!i.defaultPrevented)switch(i.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{i.preventDefault(),n(i);break}case"F6":{i.preventDefault();const d=a.getAttribute(Zt.groupId);bt(d,`No group element found for id "${d}"`);const m=Fo(d,r),p=e0(d,s,r);bt(p!==null,`No resize element found for id "${s}"`);const c=i.shiftKey?p>0?p-1:m.length-1:p+1<m.length?p+1:0;m[c].focus();break}}};return a.addEventListener("keydown",o),()=>{a.removeEventListener("keydown",o)}},[r,t,s,n])}function c0({children:t=null,className:s="",disabled:n=!1,hitAreaMargins:r,id:a,onBlur:o,onClick:i,onDragging:d,onFocus:m,onPointerDown:p,onPointerUp:c,style:u={},tabIndex:x=0,tagName:h="div",...b}){var f,g;const y=l.useRef(null),j=l.useRef({onClick:i,onDragging:d,onPointerDown:p,onPointerUp:c});l.useEffect(()=>{j.current.onClick=i,j.current.onDragging=d,j.current.onPointerDown=p,j.current.onPointerUp=c});const v=l.useContext(lc);if(v===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:T,groupId:k,registerResizeHandle:w,startDragging:I,stopDragging:A,panelGroupElement:E}=v,C=lm(a),[N,S]=l.useState("inactive"),[O,R]=l.useState(!1),[z,D]=l.useState(null),L=l.useRef({state:N});$r(()=>{L.current.state=N}),l.useEffect(()=>{if(n)D(null);else{const U=w(C);D(()=>U)}},[n,C,w]);const $=(f=r==null?void 0:r.coarse)!==null&&f!==void 0?f:15,q=(g=r==null?void 0:r.fine)!==null&&g!==void 0?g:5;l.useEffect(()=>{if(n||z==null)return;const U=y.current;bt(U,"Element ref not attached");let V=!1;return yL(C,U,T,{coarse:$,fine:q},(F,W,_)=>{if(!W){S("inactive");return}switch(F){case"down":{S("drag"),V=!1,bt(_,'Expected event to be defined for "down" action'),I(C,_);const{onDragging:G,onPointerDown:B}=j.current;G==null||G(!0),B==null||B();break}case"move":{const{state:G}=L.current;V=!0,G!=="drag"&&S("hover"),bt(_,'Expected event to be defined for "move" action'),z(_);break}case"up":{S("hover"),A();const{onClick:G,onDragging:B,onPointerUp:Y}=j.current;B==null||B(!1),Y==null||Y(),V||G==null||G();break}}})},[$,T,n,q,w,C,z,I,A]),LL({disabled:n,handleId:C,resizeHandler:z,panelGroupElement:E});const P={touchAction:"none",userSelect:"none"};return l.createElement(h,{...b,children:t,className:s,id:a,onBlur:()=>{R(!1),o==null||o()},onFocus:()=>{R(!0),m==null||m()},ref:y,role:"separator",style:{...P,...u},tabIndex:x,[Zt.groupDirection]:T,[Zt.groupId]:k,[Zt.resizeHandle]:"",[Zt.resizeHandleActive]:N==="drag"?"pointer":O?"keyboard":void 0,[Zt.resizeHandleEnabled]:!n,[Zt.resizeHandleId]:C,[Zt.resizeHandleState]:N})}c0.displayName="PanelResizeHandle";function zL({className:t,...s}){return e.jsx(l0,{"data-slot":"resizable-panel-group",className:$e("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",t),...s})}function Ch({...t}){return e.jsx(Hy,{"data-slot":"resizable-panel",...t})}function OL({withHandle:t,className:s,...n}){return e.jsx(c0,{"data-slot":"resizable-handle",className:$e("bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",s),...n,children:t&&e.jsx("div",{className:"bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border",children:e.jsx(Yr,{className:"size-2.5"})})})}function $L(){const[t,s]=l.useState([]),[n,r]=l.useState(!0),[a,o]=l.useState(null),{user:i}=pt(),d=l.useRef(!0);l.useEffect(()=>()=>{d.current=!1},[]),l.useEffect(()=>{const c=Ge(Re(ge,"duplicateDetectionResults"),Ve("reviewed","==",!1),Nt("detectedAt","desc"),Tt(50));return qt(c,x=>{if(!d.current)return;const h=x.docs.map(b=>({id:b.id,...b.data()}));s(h),r(!1)},x=>{console.error("[useUnresolvedDuplicates] Snapshot error:",x),d.current&&(o(x.message),r(!1))})},[]);const m=l.useCallback(async(c,u,x)=>{const h=ut(ge,"duplicateDetectionResults",c),b=t.find(v=>v.id===c),f=(b==null?void 0:b.resolvedGroupIndexes)??[],y=new Set(f).add(u).size>=x,j={resolvedGroupIndexes:mf(u)};y&&(j.reviewed=!0,j.reviewedAt=ss(),j.reviewedBy=(i==null?void 0:i.uid)||"unknown"),await er(h,j)},[t,i]),p=l.useCallback(async(c,u)=>{const x=[...c].sort(),h=x.join("_");
422await qr(ut(ge,"dismissedDuplicates",h),{ticketIds:x,dismissedAt:ss(),dismissedBy:(i==null?void 0:i.uid)||"unknown",...u?{sourceDocId:u}:{}},{merge:!0})},[i]);return{results:t,loading:n,error:a,markGroupResolved:m,recordDismissedDuplicate:p}}const BL=[{label:"Backlog",value:"Backlog"},{label:"Defer",value:"Deferred"},{label:"In Queue",value:"In Queue"},{label:"Complete",value:"Complete"}];function FL({groups:t,onMerge:s,onDismiss:n,onComplete:r,onMergeAll:a,onClose:o,merging:i}){const[d,m]=l.useState({}),[p,c]=l.useState(new Set),[u,x]=l.useState({}),[h,b]=l.useState({}),[f,g]=l.useState({}),[y,j]=l.useState(null),v=t.filter((S,O)=>!p.has(O)),T=S=>{c(O=>new Set(O).add(S)),n(t[S])},k=async S=>{try{const O=await ps(ut(ge,"tickets",S));return O.exists()?O.data().content??"":""}catch{return""}},w=async(S,O)=>{j(S);try{const R=await s(O,A(S,O));if(R){x(D=>({...D,[S]:R}));const z=await k(R.id);b(D=>({...D,[S]:z}))}}finally{j(null)}},I=async(S,O,R)=>{const z=u[S];if(z){g(D=>({...D,[S]:R}));try{await re("updateTicket",{ticketRefId:z.id,status:R}),c(D=>new Set(D).add(S)),r(O,{...z,status:R})}catch(D){console.error("[DuplicateReviewModal] Failed to set merged ticket status:",D),g(L=>{const $={...L};return delete $[S],$})}}},A=(S,O)=>d[S]??O.suggestedMergedTitle,E=S=>S>=.85?"bg-green-100 text-green-700":S>=.75?"bg-yellow-100 text-yellow-700":"bg-gray-100 text-gray-600",C=v.length===0?"No duplicates detected":`${v.length} group${v.length>1?"s":""} found`,N=e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{children:v.length>1&&e.jsx("button",{onClick:a,disabled:i,style:{padding:"6px 14px",fontSize:13,borderRadius:6,border:"none",cursor:"pointer",backgroundColor:"#7c3aed",color:"#fff",opacity:i?.5:1},children:i?"Merging...":`Merge All (${v.length})`})}),e.jsx("button",{onClick:o,style:{padding:"6px 14px",fontSize:13,borderRadius:6,border:"1px solid #e5e7eb",cursor:"pointer",backgroundColor:"#f9fafb",color:"#374151"},children:"Close"})]});return e.jsx(Cs,{title:"Duplicate Detection Results",subtitle:C,onClose:o,footer:N,children:v.length===0?e.jsx("div",{style:{textAlign:"center",padding:"32px 0",color:"#9ca3af"},children:e.jsx("p",{style:{fontSize:14},children:"No duplicate tickets detected in this project."})}):t.map((S,O)=>{if(p.has(O))return null;const R=u[O],z=f[O],D=y===O||i&&y===null&&!R;if(R){const L=z!==void 0,$=h[O],q=$===void 0;return e.jsxs("div",{style:{border:"1px solid #e5e7eb",borderRadius:8,padding:12,marginBottom:8,backgroundColor:"#f0fdf4"},children:[e.jsxs("p",{style:{fontSize:11,fontWeight:600,color:"#6b7280",textTransform:"uppercase",letterSpacing:.5,marginBottom:6},children:["Source Tickets (",S.tickets.length,")"]}),S.tickets.map(P=>e.jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:6,padding:8,marginBottom:6,opacity:.75},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:"monospace"},children:P.displayId}),e.jsx("span",{style:{fontSize:11,padding:"1px 6px",backgroundColor:"#f3f4f6",color:"#6b7280",borderRadius:4,fontWeight:500},children:P.status})]}),e.jsx("p",{style:{fontSize:13,fontWeight:500,color:"#111827",marginTop:2},children:P.name}),P.content&&e.jsx("p",{style:{fontSize:11,color:"#6b7280",marginTop:2,overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:P.content})]},P.id)),e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,marginTop:12,marginBottom:6},children:[e.jsx("span",{style:{fontSize:16,lineHeight:"20px",color:"#059669"},children:"â"}),e.jsxs("div",{style:{minWidth:0},children:[e.jsxs("p",{style:{fontSize:13,fontWeight:600,color:"#065f46"},children:["Merged into ",R.displayId]}),e.jsx("p",{style:{fontSize:12,color:"#047857",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:R.name})]})]}),e.jsx("div",{style:{backgroundColor:"#fff",border:"1px solid #d1fae5",borderRadius:6,padding:8,marginBottom:10,maxHeight:180,overflowY:"auto"},children:q?e.jsx("p",{style:{fontSize:11,color:"#6b7280",fontStyle:"italic"},children:"Loading merged content..."}):$?e.jsx("p",{style:{fontSize:12,color:"#374151",whiteSpace:"pre-wrap"},children:$}):e.jsx("p",{style:{fontSize:11,color:"#9ca3af",fontStyle:"italic"},children:"No content"})}),e.jsx("p",{style:{fontSize:11,fontWeight:600,color:"#6b7280",marginBottom:6},children:"Set status for the merged ticket"}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:6},children:BL.map(({label:P,value:U})=>{const V=z===U;return e.jsx("button",{onClick:()=>I(O,S,U),disabled:L,style:{padding:"8px 12px",fontSize:13,borderRadius:6,border:"1px solid #d1d5db",curs
422or:L?"not-allowed":"pointer",backgroundColor:"#fff",color:"#111827",opacity:L&&!V?.5:1,fontWeight:500},children:V?"Setting...":P},U)})})]},O)}return e.jsxs("div",{style:{border:"1px solid #e5e7eb",borderRadius:8,padding:12,marginBottom:8},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[e.jsxs("span",{className:E(S.confidence),style:{padding:"2px 8px",fontSize:12,fontWeight:500,borderRadius:4},children:[Math.round(S.confidence*100),"% match"]}),e.jsx("span",{style:{fontSize:12,color:"#6b7280"},children:S.reason})]}),S.tickets.map(L=>e.jsxs("div",{style:{backgroundColor:"#f9fafb",borderRadius:6,padding:8,marginBottom:6},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontSize:11,color:"#9ca3af",fontFamily:"monospace"},children:L.displayId}),e.jsx("span",{style:{fontSize:11,padding:"1px 6px",backgroundColor:"#f3f4f6",color:"#6b7280",borderRadius:4,fontWeight:500},children:L.status})]}),e.jsx("p",{style:{fontSize:13,fontWeight:500,color:"#111827",marginTop:2},children:L.name}),L.content&&e.jsx("p",{style:{fontSize:11,color:"#6b7280",marginTop:2,overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:L.content})]},L.id)),e.jsxs("div",{style:{marginTop:8,marginBottom:8},children:[e.jsx("label",{style:{fontSize:11,fontWeight:600,color:"#6b7280",display:"block",marginBottom:4},children:"Merged ticket title"}),e.jsx("input",{type:"text",value:A(O,S),onChange:L=>m($=>({...$,[O]:L.target.value})),style:{width:"100%",padding:"6px 10px",fontSize:13,border:"1px solid #d1d5db",borderRadius:6,outline:"none"}})]}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:()=>w(O,S),disabled:D||i,style:{padding:"5px 12px",fontSize:13,borderRadius:6,border:"none",cursor:"pointer",backgroundColor:"#7c3aed",color:"#fff",opacity:D||i?.5:1},children:D?"Merging...":"Merge"}),e.jsx("button",{onClick:()=>T(O),style:{padding:"5px 12px",fontSize:13,borderRadius:6,border:"1px solid #e5e7eb",cursor:"pointer",backgroundColor:"#f9fafb",color:"#374151"},children:"Dismiss"})]})]},O)})})}const md=768;function _L(){const[t,s]=l.useState(void 0);return l.useEffect(()=>{const n=window.matchMedia(`(max-width: ${md-1}px)`),r=()=>{s(window.innerWidth<md)};return n.addEventListener("change",r),s(window.innerWidth<md),()=>n.removeEventListener("change",r)},[]),!!t}const WL=[{label:"Backlog",value:"Backlog"},{label:"Defer",value:"Deferred"},{label:"In Queue",value:"In Queue"},{label:"Complete",value:"Complete"}];function d0(t){return t>=.85?"bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300":t>=.75?"bg-yellow-100 text-yellow-700 dark:bg-yellow-900 dark:text-yellow-300":"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300"}async function Th(t){return(await Promise.all(t.map(async n=>{try{const r=await ps(ut(ge,"tickets",n));if(!r.exists())return null;const a=r.data();return["Merged (Archived)","Archived","Cancelled"].includes(a.status)?null:{id:r.id,displayId:a.displayId||n,name:a.name||"",status:a.status||"Unknown",content:a.content||null,creditsMin:a.creditsMin??null,creditsMax:a.creditsMax??null,ticketComplexity:a.ticketComplexity??null}}catch{return null}}))).filter(Boolean)}function UL({ticket:t,onRemove:s,isPrimary:n}){const{attributes:r,listeners:a,setNodeRef:o,transform:i,transition:d,isDragging:m}=sc({id:t.id}),p={transform:i?`translate3d(${i.x}px, ${i.y}px, 0)`:void 0,transition:d,opacity:m?.5:1,zIndex:m?10:"auto"};return e.jsx("div",{ref:o,style:p,className:`bg-card border rounded-lg p-3 mb-2 group ${n?"border-primary ring-1 ring-primary/30":"border-border"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("button",{...r,...a,className:"mt-1 cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground shrink-0",title:"Drag to reorder · top ticket is primary",children:e.jsx(Yr,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:t.displayId}),e.jsx("span",{className:"text-xs px-1.5 py-0.5 bg-accent text-muted-foreground rounded font-medium",children:t.status}),n&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 bg-primary/10 text-primary rounded font-semibold",children:"Primary"})]}),e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:t.name}),t.content&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:t.content})]}),e.jsx("button",{onClick:s,className:"mt-1 p-1 rounded hover:bg-red-100 dark:hover:bg-red-900/30 text-muted-foreground hover:text-red-500 shrink-0",title:"Remove from merge",children:e.jsx(mt,{className:"w-4 h-4"})})]})})}
422function HL({candidates:t,mergedTitle:s,onTitleChange:n,confidence:r,aiSummary:a,generatingSummary:o,onGenerateSummary:i,onMerge:d,onDismiss:m,merging:p}){const c=t.length>=2&&s.trim().length>0,u=t.length>=2&&!o,x=t.filter(h=>h.content).map(h=>`[${h.displayId}] ${h.name}: 423${h.content}`).join(` 424 425--- 426 427`);return e.jsxs("div",{className:"h-full flex flex-col p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(So,{className:"w-5 h-5 text-primary"}),e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Merge Preview"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1.5 block",children:"Merged Ticket Title"}),e.jsx("input",{type:"text",value:s,onChange:h=>n(h.target.value),className:"w-full px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary"})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-4 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[t.length," ticket",t.length!==1?"s":""," to merge"]}),e.jsxs("span",{className:`px-1.5 py-0.5 rounded font-medium ${d0(r)}`,children:[Math.round(r*100),"% confidence"]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mb-4 min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Combined Content"}),e.jsxs("button",{onClick:i,disabled:!u,className:"text-xs px-2 py-1 rounded border border-border hover:bg-accent text-foreground font-medium disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1 transition-colors",title:"Generate an AI summary preview",children:[o?e.jsx(fe,{className:"w-3 h-3 animate-spin"}):e.jsx(ws,{className:"w-3 h-3"}),a?"Regenerate":"Generate"]})]}),e.jsx("div",{className:"bg-background border border-border rounded-lg p-3 text-sm max-h-96 overflow-y-auto",children:t.length===0?e.jsx("p",{className:"text-muted-foreground italic text-xs",children:"No candidates remaining"}):o?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"})," Generating summary..."]}):a?e.jsx("p",{className:"text-xs text-foreground whitespace-pre-wrap",children:a}):x?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:x}),e.jsx("p",{className:"text-[10px] text-muted-foreground italic mt-2",children:"Click Generate to preview the AI-summarized version that will be saved."})]}):e.jsx("p",{className:"text-muted-foreground italic text-xs",children:"No content to preview"})})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsxs("button",{onClick:d,disabled:!c||p,className:"flex-1 px-4 py-2.5 bg-primary hover:bg-primary/90 text-primary-foreground rounded-lg text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 transition-colors",children:[p?e.jsx(fe,{className:"w-4 h-4 animate-spin"}):e.jsx(tN,{className:"w-4 h-4"}),p?"Merging...":"Merge Tickets"]}),e.jsx("button",{onClick:m,className:"px-4 py-2.5 bg-card border border-border hover:bg-accent text-foreground rounded-lg text-sm font-medium transition-colors",children:"Dismiss"})]})]})}function qL({mergedTicket:t,mergedDetails:s,applyingStatus:n,onApplyStatus:r}){return e.jsxs("div",{className:"h-full flex flex-col p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Ns,{className:"w-5 h-5 text-green-600 dark:text-green-400"}),e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Merged Result"})]}),e.jsxs("div",{className:"mb-3 bg-background border border-border rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:t.displayId}),e.jsx("span",{className:"text-xs px-1.5 py-0.5 bg-accent text-muted-foreground rounded font-medium",children:(s==null?void 0:s.status)??t.status})]}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:(s==null?void 0:s.name)??t.n
427ame})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mb-4 min-h-0",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1.5 block",children:"Combined Content"}),e.jsx("div",{className:"bg-background border border-border rounded-lg p-3 text-sm max-h-72 overflow-y-auto",children:s?s.content?e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:s.content}):e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No content"}):e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"})," Loading merged content..."]})})]}),e.jsxs("div",{className:"shrink-0",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Set status for the merged ticket"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:WL.map(({label:a,value:o})=>{const i=n===o,d=n!==null;return e.jsxs("button",{onClick:()=>r(o),disabled:d,className:"px-3 py-2.5 bg-card border border-border hover:bg-accent text-foreground rounded-lg text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 transition-colors",children:[i?e.jsx(fe,{className:"w-4 h-4 animate-spin"}):e.jsx(kt,{className:"w-4 h-4"}),a]},o)})})]})]})}function VL({ticket:t}){return e.jsxs("div",{className:"bg-card border border-border rounded-lg p-3 mb-2 opacity-75",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:t.displayId}),e.jsx("span",{className:"text-xs px-1.5 py-0.5 bg-accent text-muted-foreground rounded font-medium",children:t.status})]}),e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:t.name}),t.content&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:t.content})]})}function YL({flatGroup:t,onMerge:s,onDismiss:n,onComplete:r,onPreviewSummary:a,merging:o}){const[i,d]=l.useState([]),[m,p]=l.useState(!0),[c,u]=l.useState(t.group.suggestedMergedTitle),[x,h]=l.useState(null),[b,f]=l.useState(null),[g,y]=l.useState(0),[j,v]=l.useState(null),[T,k]=l.useState(null),[w,I]=l.useState(!1),A=_L(),E=Ho(Rn(Yo,{activationConstraint:{distance:5}}),Rn(Vo,{coordinateGetter:sm}));l.useEffect(()=>{let $=!1;return p(!0),Th(t.group.ticketIds).then(q=>{$||(d(q),p(!1),q.length<2&&n(!0))}),()=>{$=!0}},[t.group.ticketIds]);const C=$=>{const{active:q,over:P}=$;!P||q.id===P.id||(d(U=>{const V=U.findIndex(F=>F.id===q.id),M=U.findIndex(F=>F.id===P.id);return ci(U,V,M)}),k(null))},N=$=>{d(q=>q.filter(P=>P.id!==$)),k(null)},S=async()=>{if(!(i.length<2)){I(!0);try{const $=await a(i.map(q=>q.id));$&&k($)}finally{I(!1)}}},O=async()=>{const $=await s(i.map(q=>q.id),t.projectId,c,t.group.confidence,t.group.reason);$&&(y(i.length),h($),Th([$.id]).then(q=>{q[0]?f(q[0]):f({id:$.id,displayId:$.displayId,name:$.name,status:$.status,content:null,creditsMin:null,creditsMax:null,ticketComplexity:null})}))},R=async $=>{if(x){v($);try{await re("updateTicket",{ticketRefId:x.id,status:$}),r({...x,status:$},g)}catch(q){console.error("[DuplicateMerge] Failed to set merged ticket status:",q),v(null)}}};if(m)return e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground border-t border-border",children:[e.jsx(fe,{className:"w-5 h-5 animate-spin mr-2"}),"Loading ticket details..."]});if(i.length<2&&!x)return e.jsxs("div",{className:"flex items-center justify-center gap-2 py-8 text-muted-foreground border-t border-border text-sm",children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"}),"Already resolved â clearing..."]});const z=x!==null,D=z?e.jsxs("div",{className:"h-full overflow-y-auto p-4",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3",children:["Source Tickets (",i.length,")"]}),i.map($=>e.jsx(VL,{ticket:$},$.id))]}):e.jsxs("div",{className:"h-full overflow-y-auto p-4",children:[e.jsxs("div",{className:"mb-3",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:["Candidates (",i.length,")"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:"Drag to reorder â top ticket becomes the primary."})]}),e.jsx(qo,{sensors:E,collisionDetection:cu,onDragEnd:C,children:e.jsx(tm,{items:i.map($=>
427$.id),strategy:em,children:i.map(($,q)=>e.jsx(UL,{ticket:$,onRemove:()=>N($.id),isPrimary:q===0},$.id))})})]}),L=z&&x?e.jsx(qL,{mergedTicket:x,mergedDetails:b,applyingStatus:j,onApplyStatus:R}):e.jsx(HL,{candidates:i,mergedTitle:c,onTitleChange:u,confidence:t.group.confidence,aiSummary:T,generatingSummary:w,onGenerateSummary:S,onMerge:O,onDismiss:n,merging:o});return A?e.jsxs("div",{className:"border-t border-border flex flex-col",children:[e.jsx("div",{className:"max-h-[50vh] overflow-y-auto",children:D}),e.jsx("div",{className:"border-t border-border",children:L})]}):e.jsx("div",{className:"h-[420px] border-t border-border",children:e.jsxs(zL,{direction:"horizontal",children:[e.jsx(Ch,{defaultSize:50,minSize:30,children:D}),e.jsx(OL,{withHandle:!0}),e.jsx(Ch,{defaultSize:50,minSize:30,children:L})]})})}function GL({flatGroup:t,isExpanded:s,onToggle:n,onMerge:r,onDismiss:a,onComplete:o,onPreviewSummary:i,merging:d}){const{group:m,projectName:p}=t,c=s?hr:Ot;return e.jsxs(st.div,{layout:!0,className:"bg-card border border-border rounded-lg overflow-hidden",initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},children:[e.jsxs("button",{onClick:n,className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-accent/50 transition-colors text-left",children:[e.jsx(c,{className:"w-4 h-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground truncate",children:p}),e.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium shrink-0 ${d0(m.confidence)}`,children:[Math.round(m.confidence*100),"%"]}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[m.ticketIds.length," tickets"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:m.suggestedMergedTitle})]})]}),e.jsx(hs,{children:s&&e.jsx(st.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},children:e.jsx(YL,{flatGroup:t,onMerge:r,onDismiss:a,onComplete:o,onPreviewSummary:i,merging:d})})})]})}function KL({token:t,onGroupsDetected:s,detecting:n,onDetect:r}){const[a,o]=l.useState(!1),[i,d]=l.useState([]),[m,p]=l.useState(!1),[c,u]=l.useState(null),[x,h]=l.useState(""),[b,f]=l.useState([]),[g,y]=l.useState(!1),[j,v]=l.useState(null),[T,k]=l.useState("");l.useEffect(()=>{!a||i.length>0||(p(!0),fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getNotionClients").then(E=>E.json()).then(E=>{E.success&&E.clients&&d(E.clients)}).catch(()=>{}).finally(()=>p(!1)))},[a,i.length]),l.useEffect(()=>{if(!c||!t){f([]);return}y(!0),fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/getProjectsByClients",{method:"POST",headers:as(t),body:JSON.stringify({clientNames:[c.name]})}).then(E=>E.json()).then(E=>f(E.projects||[])).catch(()=>{}).finally(()=>y(!1))},[c,t]);const w=async()=>{if(!j)return;const E=await r(j.id);E&&s(E.duplicateGroups,j.id)},I=i.filter(E=>E.name.toLowerCase().includes(x.toLowerCase())),A=b.filter(E=>E.name.toLowerCase().includes(T.toLowerCase()));return e.jsxs("div",{className:"bg-card border border-border rounded-lg mb-4",children:[e.jsxs("button",{onClick:()=>o(!a),className:"w-full flex items-center justify-between px-4 py-3 text-sm font-medium text-foreground hover:bg-accent/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{children:"Detect for Project"})]}),a?e.jsx(hr,{className:"w-4 h-4 text-muted-foreground"}):e.jsx(Ot,{className:"w-4 h-4 text-muted-foreground"})]}),a&&e.jsxs("div",{className:"px-4 pb-4 space-y-3 border-t border-border pt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"text",placeholder:m?"Loading...":"Search clients...",value:x,onChange:E=>h(E.target.value),className:"w-full px-3 py-2 text-sm bg-background border border-border rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-primary"}),x&&I.length>0&&e.jsx("div",{className:"absolute z-10 mt-1 w-full bg-card border border-border rounded-lg shadow-lg max-h-48 overflow-y-auto",children:I.map(E=>e.jsx("button",{onClick:()=>{u(E),h(E.name),v(null),k("")},className:"w-full text-left px-3 py-2 text-sm hover:bg-accent text-foreground",children:E.name},E.id))})]}),c&&e.jsx("div",{className:"relative",children:g?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm py-2",children:[e.jsx(fe,{className:"w-4 h-4 animate-spin"})," Loading..."]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",placeholder:"Search projects...",value:T,onChange:E=>k(E.target.value),className:"w-full px-3 py-2 text-sm bg-background border border-border rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-primary"}),T&&A.length>0&&e.jsx("div",{className:"absolute z-10 mt-1 w-full bg-card border border-border rounded-lg shadow-lg max-h-48 overflow-y-auto",children:A.map(E=>
427e.jsx("button",{onClick:()=>{v(E),k(E.name)},className:"w-full text-left px-3 py-2 text-sm hover:bg-accent text-foreground",children:E.name},E.id))})]})}),j&&e.jsxs("button",{onClick:w,disabled:n,className:"px-4 py-2 bg-primary hover:bg-primary/90 text-primary-foreground text-sm rounded-lg disabled:opacity-50 flex items-center gap-2 transition-colors",children:[n?e.jsx(fe,{className:"w-4 h-4 animate-spin"}):e.jsx(Pt,{className:"w-4 h-4"}),n?"Scanning...":"Detect Duplicates"]})]})]})}function QL({onBack:t,onLogoClick:s}){const{token:n}=pt(),{results:r,loading:a,markGroupResolved:o,recordDismissedDuplicate:i}=$L(),{detectDuplicates:d,mergeTickets:m,previewMergedContent:p,merging:c,detecting:u,error:x,clearError:h}=ty(),[b,f]=l.useState(null),[g,y]=l.useState(null),[j,v]=l.useState([]),[T,k]=l.useState(null),[w,I]=l.useState(!1),A=l.useMemo(()=>r.flatMap(q=>{const P=new Set(q.resolvedGroupIndexes??[]);return q.duplicateGroups.map((U,V)=>({key:`${q.id}-${V}`,docId:q.id,groupIndex:V,totalGroups:q.duplicateGroups.length,projectId:q.projectId,projectName:q.projectName,group:U})).filter(U=>!P.has(U.groupIndex))}),[r]),E=A.reduce((q,P)=>q+P.group.ticketIds.length,0),C=q=>{y(q),setTimeout(()=>y(null),4e3)},N=l.useCallback(async q=>{f(P=>P===q.key?null:P),await o(q.docId,q.groupIndex,q.totalGroups)},[o]),S=async(q,P,U,V,M)=>{h();const F=await m({ticketIds:q,projectId:P,mergedTitle:U,confidence:V,matchReason:M});return F?F.mergedTicket:null},O=async(q,P,U)=>{await N(q),C(`Merged ${U} tickets into ${P.displayId} · ${P.status}`)},R=async(q,P=!1)=>{P||await i(q.group.ticketIds,q.docId),await N(q),C(P?"Group resolved":"Group dismissed")},z=(q,P)=>{v(q),k(P),I(!0)},D=async(q,P)=>{if(!T)return null;const U=await m({ticketIds:q.ticketIds,projectId:T,mergedTitle:P,confidence:q.confidence,matchReason:q.reason});return U?U.mergedTicket:null},L=(q,P)=>{v(U=>U.filter(V=>V!==q)),C(`Merged into ${P.displayId} · ${P.status}`)},$=async()=>{if(T){for(const q of j)await m({ticketIds:q.ticketIds,projectId:T,mergedTitle:q.suggestedMergedTitle,confidence:q.confidence,matchReason:q.reason});v([]),C("All groups merged")}};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s,onBack:t}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Duplicate Merge"}),e.jsx("p",{className:"text-muted-foreground",children:"Review and merge duplicate tickets detected by the nightly scan"})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsxs("span",{className:"text-xs px-2.5 py-1 rounded-full bg-primary/10 text-primary font-medium",children:[A.length," pending group",A.length!==1?"s":""]}),e.jsxs("span",{className:"text-xs px-2.5 py-1 rounded-full bg-accent text-muted-foreground font-medium",children:[E," total candidates"]})]}),e.jsx(hs,{children:g&&e.jsxs(st.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"mb-4 p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg flex items-center gap-2 text-green-700 dark:text-green-300 text-sm",children:[e.jsx(Ns,{className:"w-4 h-4 shrink-0"}),g]})}),x&&e.jsxs("div",{className:"mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-center gap-2 text-red-700 dark:text-red-300 text-sm",children:[e.jsx(gs,{className:"w-4 h-4 shrink-0"}),x]}),e.jsx(KL,{token:n,onGroupsDetected:z,detecting:u,onDetect:d}),a?e.jsxs("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:[e.jsx(fe,{className:"w-5 h-5 animate-spin mr-2"}),"Loading pending duplicates..."]}):A.length===0?e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground text-sm",children:"No pending duplicate groups from the nightly scan."}),e.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:'Use "Detect for Project" above to scan manually.'})]}):e.jsx("div",{className:"space-y-3",children:e.jsx(hs,{children:A.map(q=>e.jsx(GL,{flatGroup:q,isExpanded:b===q.key,onToggle:()=>f(b===q.key?null:q.key),onMerge:S,onDismiss:P=>R(q,P),onComplete:(P,U)=>O(q,P,U),onPreviewSummary:p,merging:c},q.key))})})]}),w&&e.jsx(FL,{groups:j,onMerge:D,onDismiss:q=>i(q.ticketIds),onComplete:L,onMergeAll:$,onClose:()=>I(!1),merging:c})]})}const JL={"gemini-3.8-flash":{input:.75,output:3.75},"gemini-3.6-flash":{input:.75,output:3.75},"gemini-3.5-flash-lite":{input:.3,output:2.5},"gemini-3.1-flash-lite":{input:.02,output:.1},"gemini-3.1-pro-preview":{input:1.25,output:10},"gemini-2.5-flash":{input:.3,output:2.5},"gemini-2.5-pro":{input:1.25,output:10}};function Ah(t){return JL[t]||null}function ZL({onBack:t,onLogoClick:s}){const[n,r]=l.useState(""),[a,o]=l.useState(""),[i,d]=l.useState(!1),[m,p]=l.useState(null),[c,u]=l.useState(null),[x,h]=l.useState(null),[b,f]=l.useState(null),[g,y]=l.useState(null),[j,v]=l.useState(!0);l.useEffect(()=>{re("geminiModelCompare",{action:"getConfig"}).then(k=>{y(k),r(k.legacyModel),o(k.currentModel)}).catch(()=>{r("gemini-2.5-flash"),o("gemini-3.1-flash-lite")}).finally(()=>v(!1))},[]);const T=async()=>{d(!0),p(null),u(null);try{const k=await re("geminiModelCompare",{oldModel:n,newModel:a});u(k)}catch(k){p(k.message||"Failed to run comparison")}finally{d(!1)}};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-3xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:20,height:20}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Model Compare"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Compare Gemini model quality, speed, and output side-by-side"})]})]}),g&&!j&&e.jsxs("div",{className:"bg-green-500/10 border border-green-500/20 rounded-lg px-4 py-3 mb-4 flex items-center gap-3",children:[e.jsx(Ns,{style:{width:16,height:16},className:"text-green-600 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Current production model: "}),e.jsx("span",{className:"font-semibold text-foreground font-mono",children:g.currentModel}),e.jsx("span",{className:"text-muted-foreground ml-3",children:"Location: "}),e.jsx("span",{className:"font-mono text-foreground",children:g.location})]})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mb-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"Baseline Model"}),e.jsxs("select",{value:n,onChange:k=>r(k.target.value),className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground appearance-none",children:[e.jsx("option",{value:"",children:"Select model..."}),((g==null?void 0:g.availableModels)||[]).map(k=>
427e.jsxs("option",{value:k.id,children:[k.name," (",k.location,")"]},k.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-1",children:"Candidate Model"}),e.jsxs("select",{value:a,onChange:k=>o(k.target.value),className:"w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground appearance-none",children:[e.jsx("option",{value:"",children:"Select model..."}),((g==null?void 0:g.availableModels)||[]).map(k=>e.jsxs("option",{value:k.id,children:[k.name," (",k.location,")"]},k.id))]})]})]}),e.jsx("button",{onClick:T,disabled:i||!n||!a,className:"w-full flex items-center justify-center gap-2 bg-primary text-primary-foreground px-4 py-3 rounded-lg text-sm font-semibold hover:opacity-90 transition-opacity disabled:opacity-50",children:i?e.jsxs(e.Fragment,{children:[e.jsx(fe,{style:{width:16,height:16},className:"animate-spin"})," Running 6 tests (this takes ~60s)..."]}):e.jsxs(e.Fragment,{children:[e.jsx(In,{style:{width:16,height:16}})," Run Comparison"]})})]}),m&&e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-3 mb-4 text-sm text-destructive flex items-start gap-2",children:[e.jsx(gs,{style:{width:16,height:16,marginTop:1,flexShrink:0}}),m]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 mb-4",children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground mb-3",children:"Summary"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-center",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Tests Run"}),e.jsx("div",{className:"text-xl font-bold text-foreground",children:c.summary.testsRun})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Avg Latency"}),e.jsxs("div",{className:"text-sm font-mono",children:[e.jsx("span",{className:"text-muted-foreground",children:"old: "}),e.jsxs("span",{className:"font-bold",children:[c.summary.avgLatencyOldMs,"ms"]})]}),e.jsxs("div",{className:"text-sm font-mono",children:[e.jsx("span",{className:"text-muted-foreground",children:"new: "}),e.jsxs("span",{className:"font-bold",children:[c.summary.avgLatencyNewMs,"ms"]})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Speed"}),e.jsx("div",{className:"text-lg font-bold",style:{color:c.summary.speedDifference.includes("faster")?"#16a34a":"#dc2626"},children:c.summary.speedDifference})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:"Pricing (per 1M tokens)"}),(()=>{const k=Ah(c.summary.oldModel),w=Ah(c.summary.newModel);return e.jsxs("div",{className:"text-xs font-mono space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"old: "}),k?e.jsxs("span",{children:["$",k.input," in / $",k.output," out"]}):e.jsx("span",{className:"text-muted-foreground",children:"unknown"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"new: "}),w?e.jsxs("span",{style:{color:k&&w.input<k.input?"#16a34a":void 0},children:["$",w.input," in / $",w.output," out"]}):e.jsx("span",{className:"text-muted-foreground",children:"unknown"})]}),k&&w&&e.jsx("div",{className:"text-xs font-semibold",style:{color:w.input<k.input?"#16a34a":"#dc2626"},children:w.input<k.input?`${Math.round((1-w.input/k.input)*100)}% cheaper`:`${Math.round((w.input/k.input-1)*100)}% more expensive`})]})})()]})]})]}),e.jsx("div",{className:"space-y-3",children:c.results.map(k=>{const w=x===k.testName,I=k.oldModel.latencyMs<k.newModel.latencyMs,A=k.oldModel.latencyMs<0,E=k.newModel.latencyMs<0;return e.jsxs("div",{className:"bg-card border border-border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>h(w?null:k.testName),className:"w-full text-left px-4 py-3 flex items-center gap-3 hover:bg-muted/30 transition-colors",children:[A||E?e.jsx(gs,{style:{width:16,height:16},className:"text-destructive flex-shrink-0"}):e.jsx(Ns,{style:{width:16,height:16},className:"text-green-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-foreground",children:k.testName}),e.jsx("div",{className:"text-xs text-muted-foreground",children:k.description})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs font-mono flex-shrink-0",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ms,{style:{width:12,height:12}}),k.oldModel.latencyMs>0?`${k.oldModel.latencyMs}ms`:"ERR"]}),e.jsx(Ao,{style:{width:12,height:12},className:"text-muted-foreground"}),e.jsxs("span",{className:"flex items-center gap-1",style:{color:!I&&
427!E?"#16a34a":void 0},children:[e.jsx(ms,{style:{width:12,height:12}}),k.newModel.latencyMs>0?`${k.newModel.latencyMs}ms`:"ERR"]})]})]}),w&&e.jsxs("div",{className:"border-t border-border",children:[e.jsx("div",{className:"px-4 py-2 border-b border-border bg-muted/20",children:e.jsxs("button",{onClick:C=>{C.stopPropagation(),f({title:k.testName,prompt:k.prompt})},className:"text-xs text-primary hover:underline flex items-center gap-1.5",children:[e.jsx(Mn,{style:{width:12,height:12}}),"View prompt sent to model"]})}),e.jsxs("div",{className:"grid grid-cols-2 divide-x divide-border",children:[e.jsxs("div",{className:"p-3",style:{minWidth:0},children:[e.jsxs("div",{className:"text-xs font-semibold text-muted-foreground mb-2",children:[k.oldModel.model," (",k.oldModel.latencyMs,"ms)"]}),e.jsx("div",{className:"text-xs text-foreground bg-muted/30 rounded p-2 max-h-72 overflow-y-auto",style:{wordBreak:"break-word",overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:k.oldModel.response})]}),e.jsxs("div",{className:"p-3",style:{minWidth:0},children:[e.jsxs("div",{className:"text-xs font-semibold text-muted-foreground mb-2",children:[k.newModel.model," (",k.newModel.latencyMs,"ms)"]}),e.jsx("div",{className:"text-xs text-foreground bg-muted/30 rounded p-2 max-h-72 overflow-y-auto",style:{wordBreak:"break-word",overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:k.newModel.response})]})]})]})]},k.testName)})})]})]}),b&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.75)",padding:16},onClick:()=>f(null),children:e.jsxs("div",{className:"bg-card border border-border shadow-2xl flex flex-col",style:{maxHeight:"85vh",width:"100%",maxWidth:640,borderRadius:12,overflow:"hidden"},onClick:k=>k.stopPropagation(),children:[e.jsxs("div",{className:"bg-primary text-primary-foreground",style:{padding:"14px 20px",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs opacity-80",children:"Prompt for"}),e.jsx("div",{className:"font-semibold",children:b.title})]}),e.jsx("button",{onClick:()=>f(null),className:"text-primary-foreground/80 hover:text-primary-foreground",style:{padding:4},children:e.jsx(mt,{style:{width:20,height:20}})})]}),e.jsx("div",{style:{overflowY:"auto",flex:1,padding:"16px 20px"},children:e.jsx("div",{className:"text-sm text-foreground",style:{wordBreak:"break-word",overflowWrap:"anywhere",whiteSpace:"pre-wrap",lineHeight:1.6},children:b.prompt})}),e.jsx("div",{className:"border-t border-border",style:{padding:"10px 20px",flexShrink:0},children:e.jsx("button",{onClick:()=>f(null),className:"w-full text-sm font-medium text-foreground bg-muted hover:bg-muted/80 rounded-lg",style:{padding:"8px 16px"},children:"Close"})})]})})]})}function u0(){const[t,s]=l.useState([]),[n,r]=l.useState(!0),[a,o]=l.useState(null),i=l.useCallback(async()=>{r(!0),o(null);try{const m=ys(),c=(await Ze(Re(m,"benchmarks"))).docs.map(u=>({id:u.id,...u.data()}));s(c)}catch(m){o(m.message||"Failed to fetch benchmarks")}finally{r(!1)}},[]);l.useEffect(()=>{i()},[i]);const d=l.useCallback(m=>t.find(p=>p.verticalId===m)||null,[t]);return{benchmarks:t,loading:n,error:a,refetch:i,getBenchmarkById:d}}function m0(t){const[s,n]=l.useState([]),[r,a]=l.useState(!1),[o,i]=l.useState(null),d=l.useCallback(async()=>{if(!t){n([]);return}a(!0),i(null);try{const x=ys(),h=Ge(Re(x,"shopifyStores",t,"analyticsSnapshots"),Nt("period","desc")),f=(await Ze(h)).docs.map(g=>({id:g.id,...g.data()}));n(f)}catch(x){i(x.message||"Failed to fetch analytics")}finally{a(!1)}},[t]);l.useEffect(()=>{d()},[d]);const m=l.useCallback(x=>s.find(h=>h.period===x)||null,[s]),p=l.useCallback(async(x,h)=>{if(!t)throw new Error("No store selected");const b=await re("collectStoreAnalytics",{storeId:t,period:x,...h?{manual:h}:{}});return await d(),b},[t,d]),c=l.useCallback(async x=>{if(!t)throw new Error("No store selected");const h=await re("triggerAnalyticsCollection",{storeId:t,...x?{period:x}:{}});return await d(),h},[t,d]),u=l.useCallback(async(x=12)=>{if(!t)throw new Error("No store selected");const h=await re("backfillStoreAnalytics",{storeId:t,months:x});return await d(),h},[t,d]);return{snapshots:s,loading:r,error:o,refetch:d,getSnapshotByPeriod:m,collectData:p,autoCollect:c,backfill:u}}function XL(t){const[s,n]=l.useState([]),[r,a]=l.useState(!1),[o,i]=l.useState(null),d=l.useCallback(()=>
427{if(!t)return null;const h=ys();return Re(h,"shopifyStores",t,"storeEvents")},[t]),m=l.useCallback(async()=>{const h=d();if(!h){n([]);return}a(!0),i(null);try{const b=Ge(h,Nt("date","asc")),g=(await Ze(b)).docs.map(y=>({id:y.id,...y.data()}));n(g)}catch(b){i(b.message||"Failed to fetch events")}finally{a(!1)}},[d]);l.useEffect(()=>{m()},[m]);const p=l.useCallback(async h=>{const b=d();if(!b)throw new Error("No store selected");ys();const f=ut(b);return await qr(f,{eventId:f.id,date:h.date,eventType:h.eventType,title:h.title,description:h.description||null,impact:h.impact||"unknown",createdAt:ja.now(),createdBy:h.createdBy,source:"manual",hidden:!1}),await m(),f.id},[d,m]),c=l.useCallback(async(h,b)=>{if(!t)throw new Error("No store selected");const f=ys(),g=ut(f,"shopifyStores",t,"storeEvents",h);await er(g,b),await m()},[t,m]),u=l.useCallback(async(h,b)=>{await c(h,{hidden:b})},[c]),x=l.useCallback(async h=>{if(!t)throw new Error("No store selected");const b=ys(),f=ut(b,"shopifyStores",t,"storeEvents",h);await ru(f),await m()},[t,m]);return{events:s,loading:r,error:o,refetch:m,addEvent:p,updateEvent:c,toggleHidden:u,removeEvent:x}}function ez(t,s){const[n,r]=l.useState(null),[a,o]=l.useState(!1),[i,d]=l.useState(!1),[m,p]=l.useState(null),c=l.useCallback(async()=>{if(!t||!s){r(null);return}o(!0),p(null);try{const h=ys(),b=ut(h,"shopifyStores",t,"recommendations",s),f=await ps(b);f.exists()?r({id:f.id,...f.data()}):r(null)}catch(h){p(h.message||"Failed to fetch recommendations")}finally{o(!1)}},[t,s]);l.useEffect(()=>{c()},[c]);const u=l.useCallback(async()=>{if(!t||!s)throw new Error("No store or period selected");d(!0),p(null);try{await re("generateStoreRecommendations",{storeId:t,period:s}),await c()}catch(h){p(h.message||"Failed to generate recommendations")}finally{d(!1)}},[t,s,c]),x=l.useCallback(async(h,b,f)=>{if(!n||!t||!s)return;const g=ys(),y=ut(g,"shopifyStores",t,"recommendations",s),j=[...n[b]],v=j.findIndex(T=>T.id===h);v!==-1&&(j[v]={...j[v],dismissed:!j[v].dismissed,...f?{dismissedNote:f}:{}},await er(y,{[b]:j}),await c())},[n,t,s,c]);return{recommendations:n,loading:a,generating:i,error:m,refetch:c,generate:u,dismissRecommendation:x}}function tz(t,s){if(t===void 0||t===0)return"text-muted-foreground bg-muted";const n=t>0;return(s?!n:n)?"text-emerald-700 bg-emerald-50 dark:text-emerald-400 dark:bg-emerald-950":"text-red-700 bg-red-50 dark:text-red-400 dark:bg-red-950"}function sz(t){return t===void 0||t===0?"":t>0?"â²":"â¼"}function Gn({label:t,value:s,delta:n,deltaLabel:r,invertDelta:a,icon:o}){const i=tz(n,a),d=sz(n),m=n!==void 0&&n!==0?`${n>0?"+":""}${n.toFixed(1)}%`:null;return e.jsx(jt,{className:"min-w-[140px]",children:e.jsxs(vt,{className:"flex flex-col gap-1 p-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground text-sm",children:[o&&e.jsx("span",{className:"shrink-0",children:o}),e.jsx("span",{className:"truncate",children:t})]}),e.jsx("span",{className:"text-2xl font-semibold tracking-tight text-card-foreground",children:s}),m?e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs font-medium w-fit ${i}`,children:[d," ",m]}),r&&e.jsx("span",{className:"text-xs text-muted-foreground",children:r})]}):n===0?e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs font-medium w-fit ${i}`,children:"0.0%"}),r&&e.jsx("span",{className:"text-xs text-muted-foreground",children:r})]}):null]})})}function nz(t,s,n,r,a){return a?t<=s?{text:"text-green-600",bg:"bg-green-500",label:"BELOW LOW"}:t<=n?{text:"text-yellow-600",bg:"bg-yellow-500",label:"BELOW MEDIAN"}:t<=r?{text:"text-orange-600",bg:"bg-orange-500",label:"ABOVE MEDIAN"}:{text:"text-red-600",bg:"bg-red-500",label:"ABOVE HIGH"}:t>=r?{text:"text-green-600",bg:"bg-green-500",label:"ABOVE HIGH"}:t>=n?{text:"text-orange-600",bg:"bg-orange-500",label:"ABOVE MEDIAN"}:t>=s?{text:"text-yellow-600",bg:"bg-yellow-500",label:"BELOW MEDIAN"}:{text:"text-red-600",bg:"bg-red-500",label:"BELOW LOW"}}function Pi(t,s){return s==="$"?`$${t.toFixed(0)}`:`${t.toFixed(s==="%"?1:2)}${s??""}`}function Li(t,s,n){return n===s?50:Math.max(0,Math.min(100,(t-s)/(n-s)*100))}function zi({label:t,value:s,low:n,median:r,high:a,suffix:o,invertColors:i}){const d=(a-n)*.3,m=0,p=Math.max(a+d,s*1.1),c=Li(n,m,p),u=Li(r,m,p),x=Li(a,m,p),h=Li(s,m,p),b=Math.max(1.5,Math.min(98.5,h)),{text:f,bg:g,label:y}=nz(s,n,r,a,i),j=i?s<=n:s>=a;return e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-card-foreground",children:t}),e.jsx("span",{className:`text-sm font-semibold ${f}`,children:Pi(s,o)})]}),e.jsxs("div",{className:"relative h-3 w-full rounded-full bg-muted",children:[e.jsx("div",{className:"absolute top-0 bottom-0 rounded-full bg-muted-foreground
427/15",style:{left:`${c}%`,width:`${x-c}%`}}),e.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-muted-foreground/40",style:{left:`${c}%`}}),e.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-muted-foreground/60",style:{left:`${u}%`}}),e.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-muted-foreground/40",style:{left:`${x}%`}}),e.jsx("div",{className:`absolute top-1/2 z-10 -translate-y-1/2 -translate-x-1/2 h-5 w-5 rounded-full border-2 border-white shadow-md ${g}`,style:{left:`${b}%`}})]}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground",children:[e.jsxs("span",{children:["Low ",Pi(n,o)]}),e.jsxs("span",{children:["Median ",Pi(r,o)]}),e.jsxs("span",{children:["High ",Pi(a,o)]})]}),e.jsxs("div",{className:`flex items-center gap-1.5 text-xs font-medium ${f}`,children:[e.jsx("span",{className:`inline-block h-2 w-2 rounded-full ${g}`}),"Your store: ",y," ",j?"â":""]})]})}function p0({delayDuration:t=0,...s}){return e.jsx(Wj,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function rz({...t}){return e.jsx(p0,{children:e.jsx(Uj,{"data-slot":"tooltip",...t})})}function az({...t}){return e.jsx(Hj,{"data-slot":"tooltip-trigger",...t})}function oz({className:t,sideOffset:s=0,children:n,...r}){return e.jsx(qj,{children:e.jsxs(Vj,{"data-slot":"tooltip-content",sideOffset:s,className:$e("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...r,children:[n,e.jsx(Yj,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}const Ia={"theme-change":"Theme Change","app-change":"App Change","pricing-change":"Pricing Change",promotion:"Promotion","shipping-change":"Shipping Change","product-launch":"Product Launch","checkout-change":"Checkout Change","traffic-shift":"Traffic Shift","sunbowl-ticket":"Sunbowl Ticket","external-event":"External Event",other:"Other"},_o={"theme-change":"indigo","app-change":"purple","pricing-change":"amber",promotion:"orange","shipping-change":"sky","product-launch":"emerald","checkout-change":"teal","traffic-shift":"blue","sunbowl-ticket":"rose","external-event":"slate",other:"zinc"},Eh={indigo:"#6366f1",purple:"#a855f7",amber:"#f59e0b",orange:"#f97316",sky:"#0ea5e9",emerald:"#10b981",teal:"#14b8a6",blue:"#3b82f6",rose:"#f43f5e",slate:"#64748b",zinc:"#71717a"};function Ih(t){const s=_o[t]??"slate";return Eh[s]??Eh.slate}const Qd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function iz(t){const s=t.split("-");return parseInt(s[1],10)-1}function lz(t){const s=new Date(t+"T00:00:00"),n=s.getMonth(),r=s.getDate(),a=new Date(s.getFullYear(),n+1,0).getDate();return n+(r-1)/a}function cz(t,s){const n=Math.floor(Math.max(0,Math.min(t,11))),r=t-n,a=new Date(s,n+1,0).getDate(),o=Math.max(1,Math.min(a,Math.round(r*a)+1)),i=String(n+1).padStart(2,"0"),d=String(o).padStart(2,"0");return`${s}-${i}-${d}`}function dz({active:t,payload:s,year:n,benchmark:r}){if(!t||!(s!=null&&s.length))return null;const a=s[0];if(a.value==null||a.payload==null)return null;const o=Qd[a.payload.month]??"",i=a.value;return e.jsxs("div",{className:"rounded-lg border border-border/50 bg-background px-3 py-2 text-xs shadow-xl",children:[e.jsxs("p",{className:"font-medium",children:[o," ",n]}),e.jsxs("p",{className:"mt-1 tabular-nums",children:["Conversion Rate:"," ",e.jsxs("span",{className:"font-semibold",children:[i.toFixed(2),"%"]})]}),r&&e.jsxs("p",{className:"mt-0.5 text-muted-foreground tabular-nums",children:["Benchmark median: ",r.median.toFixed(2),"%"]})]})}function uz({viewBox:t,event:s,color:n,onClick:r}){const a=(t==null?void 0:t.x)??0;return e.jsx(p0,{children:e.jsxs(rz,{children:[e.jsx(az,{asChild:!0,children:e.jsx("circle",{cx:a,cy:8,r:6,fill:n,stroke:"white",strokeWidth:2,style:{cursor:r?"pointer":"default"},onClick:i=>{i.stopPropagation(),r==null||r()}})}),e.jsxs(oz,{children:[e.jsx("p",{className:"font-medium",children:s.title}),e.jsxs("p",{className:"text-xs opacity-80",children:[Ia[s.eventType]," · ",s.date]}),s.description&&e.jsx("p",{className:"mt-1 max-w-[200px] text-xs opacity-70",children:s.description})]})]})})}function mz({snapshots:t,events:s,benchmark:n,year:r,onEventClick:a,onGraphClick:o}){const i=l.useMemo(()=>{const c=new Map;for(const u of t){if(!u.period.startsWith(String(r)))continue;const x=iz(u.period);c.set(x,u.shopify.conversionRate)}return Qd.map((u,x)=>({month:x,cr:c.has(x)?c.get(x):void 0,label:u}))},[t,r]),d=l.useMemo(()=>s.filter(c=>!c.hidden&&c.date.startsWith(String(r))),[s,r]),m=l.useMemo(()=>{const c=[];for(const b of i)b.cr!=null&&c.push(b.cr);if(n&&c.push(n.low,n.high),c.length===0)return[0,5];const u=Math.min(...c),x=Math.max(...c),h=(x-u)*.2||.5;return[Math.max(0,Math.floor((u-h)*10)/10),Math.ceil((x+h)*10)/10]},[i,n]),p=l.useCallback((c,u)=>{if(!o||c.activeLabel==null)return;const x=parseFloat(c.activeLabel);if(isNaN(x))return;const h=cz(x,r);o(h)},[o,r]);return e.jsxs("div",{className:"w-full",children:[d.length>0&&e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground",children:[Array.from(new Map(d.map(c=>[c.eventType,c.eventType])).values()).map(c=>e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full",style:{backgroundColor:Ih(c)}}),Ia[c]]},c)),n&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-4 roun
427ded-sm bg-slate-300/40"}),"Benchmark range"]})]}),e.jsx(vf,{width:"100%",height:340,children:e.jsxs(Qj,{data:i,margin:{top:20,right:16,bottom:4,left:0},onClick:p,children:[e.jsx(wf,{strokeDasharray:"3 3",opacity:.3}),e.jsx(Nf,{dataKey:"month",type:"number",domain:[0,11],ticks:[0,1,2,3,4,5,6,7,8,9,10,11],tickFormatter:c=>Qd[c]??"",tick:{fontSize:12}}),e.jsx(kf,{domain:m,tickFormatter:c=>`${c.toFixed(1)}%`,tick:{fontSize:12},width:56}),n&&e.jsx(Jj,{y1:n.low,y2:n.high,fill:"#94a3b8",fillOpacity:.1,ifOverflow:"extendDomain"}),n&&e.jsx(fm,{y:n.median,stroke:"#94a3b8",strokeDasharray:"6 4",strokeWidth:1.5,label:{value:`Median ${n.median.toFixed(1)}%`,position:"insideTopRight",fontSize:11,fill:"#94a3b8"}}),d.map(c=>{const u=lz(c.date),x=Ih(c.eventType);return e.jsx(fm,{x:u,stroke:x,strokeDasharray:"4 3",strokeWidth:1.5,strokeOpacity:.7,label:e.jsx(uz,{event:c,color:x,onClick:a?()=>a(c.eventId):void 0})},c.eventId)}),e.jsx(Zj,{dataKey:"cr",type:"monotone",stroke:"#6366f1",strokeWidth:2.5,dot:{r:4,fill:"#6366f1",strokeWidth:2,stroke:"#fff"},activeDot:{r:6,fill:"#6366f1",strokeWidth:2,stroke:"#fff"},connectNulls:!1,isAnimationActive:!0,animationDuration:600}),e.jsx(Sf,{content:e.jsx(dz,{year:r,benchmark:n}),cursor:{stroke:"#6366f1",strokeOpacity:.2,strokeWidth:1}})]})})]})}const Rh={indigo:"bg-indigo-500",purple:"bg-purple-500",amber:"bg-amber-500",orange:"bg-orange-500",sky:"bg-sky-500",emerald:"bg-emerald-500",teal:"bg-teal-500",blue:"bg-blue-500",rose:"bg-rose-500",slate:"bg-slate-500",zinc:"bg-zinc-500"},Dh={indigo:"bg-indigo-50 text-indigo-700 dark:bg-indigo-950 dark:text-indigo-300",purple:"bg-purple-50 text-purple-700 dark:bg-purple-950 dark:text-purple-300",amber:"bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300",orange:"bg-orange-50 text-orange-700 dark:bg-orange-950 dar
427k:text-orange-300",sky:"bg-sky-50 text-sky-700 dark:bg-sky-950 dark:text-sky-300",emerald:"bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300",teal:"bg-teal-50 text-teal-700 dark:bg-teal-950 dark:text-teal-300",blue:"bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",rose:"bg-rose-50 text-rose-700 dark:bg-rose-950 dark:text-rose-300",slate:"bg-slate-50 text-slate-700 dark:bg-slate-950 dark:text-slate-300",zinc:"bg-zinc-50 text-zinc-700 dark:bg-zinc-950 dark:text-zinc-300"},Oi=["theme-change","app-change","pricing-change","promotion","shipping-change","product-launch","checkout-change","traffic-shift","sunbowl-ticket","external-event","other"];function pz(t){return new Date(t+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function xz({impact:t}){switch(t){case"positive":return e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-md bg-emerald-50 px-1.5 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-950 dark:text-emerald-400",children:[e.jsx(Bl,{className:"size-3"}),"Positive"]});case"negative":return e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-md bg-red-50 px-1.5 py-0.5 text-xs font-medium text-red-700 dark:bg-red-950 dark:text-red-400",children:[e.jsx($l,{className:"size-3"}),"Negative"]});case"neutral":return e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-md bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground",children:[e.jsx(Wl,{className:"size-3"}),"Neutral"]});case"unknown":return e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-md bg-slate-100 px-1.5 py-0.5 text-xs font-medium text-slate-500 dark:bg-slate-900 dark:text-slate-400",children:[e.jsx(nu,{className:"size-3"}),"Unknown"]});default:return null}}function hz({events:t,year:s,onEdit:n,onDelete:r,onToggleHidden:a,onAddNew:o}){const[i,d]=l.useState(new Set(Oi)),[m,p]=l.useState(!1),c=l.useMemo(()=>{const b=String(s);return t.filter(f=>f.date.startsWith(b)).filter(f=>i.has(f.eventType)).filter(f=>m||!f.hidden).sort((f,g)=>f.date.localeCompare(g.date))},[t,s,i,m]);function u(b){d(f=>{const g=new Set(f);return g.has(b)?g.delete(b):g.add(b),g})}const x=i.size===Oi.length;function h(){d(x?new Set:new Set(Oi))}return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button",onClick:h,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors ${x?"border-foreground
427/20 bg-foreground/5 text-foreground":"border-border bg-background text-muted-foreground hover:bg-accent"}`,children:x?"Clear all":"Select all"}),Oi.map(b=>{const f=_o[b],g=i.has(b);return e.jsxs("button",{type:"button",onClick:()=>u(b),className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors ${g?`${Dh[f]??""} border-transparent`:"border-border bg-background text-muted-foreground opacity-50 hover:opacity-75"}`,children:[e.jsx("span",{className:`inline-block size-2 rounded-full ${Rh[f]??"bg-slate-500"}`}),Ia[b]]},b)}),e.jsxs("button",{type:"button",onClick:()=>p(b=>!b),className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors ${m?"border-foreground/20 bg-foreground/5 text-foreground":"border-border bg-background text-muted-foreground hover:bg-accent"}`,children:[m?e.jsx(So,{className:"size-3"}):e.jsx(Lm,{className:"size-3"}),m?"Showing hidden":"Hidden events"]})]}),e.jsxs(ke,{size:"sm",onClick:o,children:[e.jsx(Ut,{className:"size-4"}),"Add Event"]})]}),e.jsx("div",{className:"max-h-[480px] overflow-y-auto rounded-md border",children:c.length===0?e.jsxs("div",{className:"flex items-center justify-center py-12 text-sm text-muted-foreground",children:["No events match the current filters for ",s,"."]}):e.jsx("ul",{className:"divide-y",children:c.map(b=>{const f=_o[b.eventType];return e.jsxs("li",{className:`flex items-center gap-3 px-4 py-3 ${b.hidden?"opacity-40":""}`,children:[e.jsx("span",{className:`shrink-0 size-2.5 rounded-full ${Rh[f]??"bg-slate-500"}`}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0.5 sm:flex-row sm:items-center sm:gap-2",children:[e.jsx(Wt,{variant:"secondary",className:`shrink-0 text-[10px] uppercase tracking-wider ${Dh[f]??""}`,children:Ia[b.eventType]}),e.jsx("span",{className:"truncate text-sm font-medium text-foreground",children:b.title})]}),e.jsx("span",{className:"hidden shrink-0 text-xs text-muted-foreground sm:inline",children:pz(b.date)}),e.jsx("div",{className:"hidden shrink-0 sm:block",children:e.jsx(xz,{impact:b.impact})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(ke,{variant:"ghost",size:"icon",className:"size-7",onClick:()=>a(b.id,!b.hidden),title:b.hidden?"Show event":"Hide event",children:b.hidden?e.jsx(Lm,{className:"size-3.5"}):e.jsx(So,{className:"size-3.5"})}),e.jsx(ke,{variant:"ghost",size:"icon",className:"size-7",onClick:()=>n(b),title:"Edit event",children:e.jsx(Na,{className:"size-3.5"})}),e.jsx(ke,{variant:"ghost",size:"icon",className:"size-7 text-destructive hover:text-destructive",onClick:()=>r(b.id),title:"Delete event",children:e.jsx(zs,{className:"size-3.5"})})]})]},b.id)})})})]})}const fz=Yl("inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 px-2 min-w-9",sm:"h-8 px-1.5 min-w-8",lg:"h-10 px-2.5 min-w-10"}},defaultVariants:{variant:"default",size:"default"}}),x0=l.createContext({size:"default",variant:"default"});function gz({className:t,variant:s,size:n,children:r,...a}){return e.jsx(Gj,{"data-slot":"toggle-group","data-variant":s,"data-size":n,className:$e("group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",t),...a,children:e.jsx(x0.Provider,{value:{variant:s,size:n},children:r})})}function $i({className:t,children:s,variant:n,size:r,...a}){const o=l.useContext(x0);return e.jsx(Kj,{"data-slot":"toggle-group-item","data-variant":
427o.variant||n,"data-size":o.size||r,className:$e(fz({variant:o.variant||n,size:o.size||r}),"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",t),...a,children:s})}const Mh={indigo:"bg-indigo-500",purple:"bg-purple-500",amber:"bg-amber-500",orange:"bg-orange-500",sky:"bg-sky-500",emerald:"bg-emerald-500",teal:"bg-teal-500",blue:"bg-blue-500",rose:"bg-rose-500",slate:"bg-slate-500",zinc:"bg-zinc-500"},bz=["theme-change","app-change","pricing-change","promotion","shipping-change","product-launch","checkout-change","traffic-shift","sunbowl-ticket","external-event","other"];function yz({open:t,onClose:s,onSave:n,initialData:r,initialDate:a}){const o=!!(r!=null&&r.id),[i,d]=l.useState(""),[m,p]=l.useState(""),[c,u]=l.useState(""),[x,h]=l.useState(""),[b,f]=l.useState("");l.useEffect(()=>{t&&(d((r==null?void 0:r.date)??a??""),p((r==null?void 0:r.eventType)??""),u((r==null?void 0:r.title)??""),h((r==null?void 0:r.description)??""),f((r==null?void 0:r.impact)??""))},[t,r,a]);const g=i!==""&&m!==""&&c.trim()!=="";function y(){g&&n({date:i,eventType:m,title:c.trim(),description:x.trim()||void 0,impact:b||void 0})}return e.jsx(br,{open:t,onOpenChange:j=>!j&&s(),children:e.jsxs(yr,{className:"sm:max-w-md",children:[e.jsxs(jr,{children:[e.jsx(vr,{children:o?"Edit Event":"Add Event"}),e.jsx(wr,{children:o?"Update the details of this store event.":"Log a store event that may affect conversion rates."})]}),e.jsxs("div",{className:"flex flex-col gap-4 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs(Jt,{htmlFor:"event-date",children:["Date ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(it,{id:"event-date",type:"date",value:i,onChange:j=>d(j.target.value),required:!0})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs(Jt,{htmlFor:"event-type",children:["Event Type ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(nn,{value:m,onValueChange:j=>p(j),children:[e.jsx(an,{id:"event-type",children:e.jsx(rn,{placeholder:"Select event type",children:m&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-block size-2.5 rounded-full ${Mh[_o[m]]??"bg-slate-500"}`}),Ia[m]]})})}),e.jsx(on,{children:bz.map(j=>{const v=_o[j];return e.jsx(cs,{value:j,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-block size-2.5 rounded-full ${Mh[v]??"bg-slate-500"}`}),Ia[j]]})},j)})})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs(Jt,{htmlFor:"event-title",children:["Title ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(it,{id:"event-title",type:"text",value:c,onChange:j=>u(j.target.value),maxLength:80,placeholder:"e.g. Switched to Dawn theme",required:!0}),e.jsxs("span",{className:"text-xs text-muted-foreground text-right",children:[c.length,"/80"]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(Jt,{htmlFor:"event-description",children:"Description"}),e.jsx(ds,{id:"event-description",value:x,onChange:j=>h(j.target.value),placeholder:"Optional details about the event...",rows:3})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(Jt,{children:"Impact"}),e.jsxs(gz,{type:"single",variant:"outline",size:"sm",value:b,onValueChange:j=>
427f(j),className:"w-full",children:[e.jsxs($i,{value:"positive","aria-label":"Positive",className:"flex-1 gap-1 data-[state=on]:bg-emerald-50 data-[state=on]:text-emerald-700 dark:data-[state=on]:bg-emerald-950 dark:data-[state=on]:text-emerald-400",children:[e.jsx(Bl,{className:"size-3.5"}),"Positive"]}),e.jsxs($i,{value:"negative","aria-label":"Negative",className:"flex-1 gap-1 data-[state=on]:bg-red-50 data-[state=on]:text-red-700 dark:data-[state=on]:bg-red-950 dark:data-[state=on]:text-red-400",children:[e.jsx($l,{className:"size-3.5"}),"Negative"]}),e.jsxs($i,{value:"neutral","aria-label":"Neutral",className:"flex-1 gap-1 data-[state=on]:bg-muted data-[state=on]:text-foreground",children:[e.jsx(Wl,{className:"size-3.5"}),"Neutral"]}),e.jsxs($i,{value:"unknown","aria-label":"Unknown",className:"flex-1 gap-1 data-[state=on]:bg-slate-100 data-[state=on]:text-slate-600 dark:data-[state=on]:bg-slate-900 dark:data-[state=on]:text-slate-400",children:[e.jsx(nu,{className:"size-3.5"}),"Unknown"]})]})]})]}),e.jsxs(Gr,{children:[e.jsx(ke,{variant:"outline",onClick:s,children:"Cancel"}),e.jsx(ke,{onClick:y,disabled:!g,children:o?"Save Changes":"Add Event"})]})]})})}function jz(t){const[s,n]=t.split("-");return new Date(Number(s),Number(n)-1).toLocaleDateString("en-US",{month:"long",year:"numeric"})}function Ph(t){if(t==="")return;const s=Number(t);return Number.isNaN(s)?void 0:s}function vz({open:t,onClose:s,onSave:n,period:r,existingData:a}){const[o,i]=l.useState(""),[d,m]=l.useState(""),[p,c]=l.useState(""),[u,x]=l.useState(""),[h,b]=l.useState(""),[f,g]=l.useState(""),[y,j]=l.useState(""),[v,T]=l.useState(""),[k,w]=l.useState(""),[I,A]=l.useState(!1);l.useEffect(()=>{var N,S,O,R,z,D,L,$,q;t&&(a?(i(((N=a.sessions)==null?void 0:N.toString())??""),m(((S=a.orders)==null?void 0:S.toString())??""),c(((O=a.conversionRate)==null?void 0:O.toString())??""),x(((R=a.addToCartRate)==null?void 0:R.toString())??""),b(((z=a.cartAbandonmentRate)==null?void 0:z.toString())??""),g(((D=a.aov)==null?void 0:D.toString())??""),j(((L=a.totalRevenue)==null?void 0:L.toString())??""),T((($=a.returningCustomerRate)==null?void 0:$.toString())??""),w(((q=a.notes)==null?void 0:q.toString())??""),A(!0)):(i(""),m(""),c(""),x(""),b(""),g(""),j(""),T(""),w(""),A(!1)))},[t,a]),l.useEffect(()=>{if(I)return;const N=Ph(o),S=Ph(d);N!==void 0&&N>0&&S!==void 0&&c((S/N*100).toFixed(2))},[o,d,I]);const E=l.useCallback(N=>{c(N.target.value),A(!0)},[]),C=l.useCallback(N=>{N.preventDefault(),n({sessions:Number(o),orders:Number(d),conversionRate:Number(p),addToCartRate:Number(u),cartAbandonmentRate:Number(h),aov:Number(f),totalRevenue:Number(y),returningCustomerRate:v!==""?Number(v):void 0,notes:k.trim()||void 0})},[o,d,p,u,h,f,y,v,k,n]);return e.jsx(br,{open:t,onOpenChange:N=>!N&&s(),children:e.jsxs(yr,{className:"sm:max-w-xl",children:[e.jsxs(jr,{children:[e.jsxs(vr,{children:["Manual Data Entry â ",jz(r)]}),e.jsx(wr,{children:"Enter analytics data for this period. Conversion rate is auto-calculated from sessions and orders but can be overridden."})]}),e.jsxs("form",{onSubmit:C,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Jt,{htmlFor:"me-sessions",children:"Sessions"}),e.jsx(it,{id:"me-sessions",type:"number",min:0,step:1,required:!0,placeholder:"e.g. 12400",value:o,onChange:N=>i(N.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Jt,{htmlFor:"me-orders",children:"Orders"}),e.jsx(it,{id:"me-orders",type:"number",min:0,step:1,required:!0,placeholder:"e.g. 186",value:d,onChange:N=>m(N.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Jt,{htmlFor:"me-cr",children:"Conversion Rate %"}),e.jsx(it,{id:"me-cr",type:"number",min:0,max:100,step:.01,required:!0,placeholder:"auto-calculated",value:p,onChange:E})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Jt,{htmlFor:"me-atcr",children:"Add to Cart Rate %"}),e.jsx(it,{id:"me-atcr",type:"number",min:0,max:100,step:.01,required:!0,placeholder:"e.g. 8.50",value:u,onChange:N=>x(N.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Jt,{htmlFor:"me-car",children:"Cart Abandonment Rate %"}
427),e.jsx(it,{id:"me-car",type:"number",min:0,max:100,step:.01,required:!0,placeholder:"e.g. 69.20",value:h,onChange:N=>b(N.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Jt,{htmlFor:"me-aov",children:"AOV $"}),e.jsx(it,{id:"me-aov",type:"number",min:0,step:.01,required:!0,placeholder:"e.g. 74.50",value:f,onChange:N=>g(N.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Jt,{htmlFor:"me-revenue",children:"Total Revenue $"}),e.jsx(it,{id:"me-revenue",type:"number",min:0,step:.01,required:!0,placeholder:"e.g. 13857.00",value:y,onChange:N=>j(N.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(Jt,{htmlFor:"me-rcr",children:["Returning Customer Rate %"," ",e.jsx("span",{className:"text-muted-foreground font-normal",children:"(optional)"})]}),e.jsx(it,{id:"me-rcr",type:"number",min:0,max:100,step:.01,placeholder:"e.g. 22.30",value:v,onChange:N=>T(N.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(Jt,{htmlFor:"me-notes",children:["Notes"," ",e.jsx("span",{className:"text-muted-foreground font-normal",children:"(optional)"})]}),e.jsx(ds,{id:"me-notes",rows:3,placeholder:"Any context about this period (promotions, site changes, etc.)",value:k,onChange:N=>w(N.target.value)})]}),e.jsxs(Gr,{children:[e.jsx(ke,{type:"button",variant:"outline",onClick:s,children:"Cancel"}),e.jsx(ke,{type:"submit",children:"Save"})]})]})]})})}const wz={conversionRate:"border-l-indigo-500",addToCartRate:"border-l-emerald-500",cartAbandonment:"border-l-amber-500",aov:"border-l-blue-500"},Nz={conversionRate:"bg-indigo-50 text-indigo-700 dark:bg-indigo-950 dark:text-indigo-300",addToCartRate:"bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300",cartAbandonment:"bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300",aov:"bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300"},kz={conversionRate:"Conversion Rate",addToCartRate:"Add-to-Cart",cartAbandonment:"Cart Abandonment",aov:"AOV"},Sz={low:"bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300",medium:"bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300",high:"bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-300"};function Cz(t){const s=sr(t);return s?s.toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0}):""}function Tz(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Lh({rec:t,type:s,onDismiss:n,dimmed:r}){return e.jsx(jt,{className:`border-l-4 ${wz[t.metric]} ${r?"opacity-50":""}`,children:e.jsxs(vt,{className:"flex flex-col gap-2 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Wt,{variant:"secondary",className:`text-[10px] uppercase tracking-wider ${Nz[t.metric]}`,children:kz[t.metric]}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:t.title})]}),!t.dismissed&&e.jsx(ke,{variant:"ghost",size:"icon",className:"size-7 shrink-0 text-muted-foreground hover:text-destructive",title:"Dismiss recommendation",onClick:()=>n(t.id,s),children:e.jsx(mt,{className:"size-3.5"})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsxs("span",{className:`inline-flex items-center rounded-md px-1.5 py-0.5 font-medium ${Sz[t.effort]}`,children:["Effort: ",Tz(t.effort)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Impact: ",t.expectedImpact]})]}),e.jsx("p",{className:"text-sm leading-relaxed text-muted-foreground",children:t.rationale}),t.dismissed&&t.dismissedNote&&e.jsxs("p",{className:"text-xs italic text-muted-foreground",children:["Dismissed: ",t.dismissedNote]})]})})}function zh({title:t,icon:s,items:n,type:r,onDismiss:a}){const[o,i]=l.useState(!1),d=l.useMemo(()=>n.filter(p=>!p.dismissed),[n]),m=l.useMemo(()=>n.filter(p=>p.dismissed),[n]);return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:t})]}),d.length===0&&m.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["No ",t.toLowerCase()," recommendations."]}),d.map(p=>e.jsx(Lh,{rec:p,type:r,onDismiss:a}
427,p.id)),m.length>0&&e.jsxs(hv,{open:o,onOpenChange:i,children:[e.jsx(fv,{asChild:!0,children:e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ot,{className:`size-3.5 transition-transform ${o?"rotate-180":""}`}),m.length," dismissed â"," ",o?"hide":"show"]})}),e.jsx(gv,{className:"flex flex-col gap-3 pt-2",children:m.map(p=>e.jsx(Lh,{rec:p,type:r,onDismiss:a,dimmed:!0},p.id))})]})]})}function Az({recommendations:t,loading:s,generating:n,onGenerate:r,onDismiss:a}){if(s)return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Recommendations"})}),e.jsx("div",{className:"flex items-center justify-center py-12 text-sm text-muted-foreground",children:"Loading recommendations..."})]});if(!t&&!n)return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Recommendations"})}),e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 rounded-md border border-dashed py-12",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recommendations yet."}),e.jsxs(ke,{size:"sm",onClick:r,children:[e.jsx(Ao,{className:"size-4"}),"Generate Recommendations"]})]})]});if(!t&&n)return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Recommendations"})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 py-12 text-sm text-muted-foreground",children:[e.jsx(yt,{className:"size-4 animate-spin"}),"Generating recommendations..."]})]});const{quickWins:o,strategic:i,generatedAt:d,generatedBy:m}=t;return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Recommendations"}),e.jsxs(ke,{variant:"outline",size:"sm",onClick:r,disabled:n,children:[e.jsx(yt,{className:`size-4 ${n?"animate-spin":""}`}),n?"Generating...":"Regenerate"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Generated: ",Cz(d),m&&e.jsxs("span",{className:"ml-1",children:["by ",m]})]})]}),e.jsx(zh,{title:"Quick Wins",icon:e.jsx(Ao,{className:"size-4 text-amber-500"}),items:o,type:"quickWins",onDismiss:a}),e.jsx(zh,{title:"Strategic",icon:e.jsx(gr,{className:"size-4 text-indigo-500"}),items:i,type:"strategic",onDismiss:a})]})}function Ez({className:t,...s}){return e.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:e.jsx("table",{"data-slot":"table",className:$e("w-full caption-bottom text-sm",t),...s})})}function Iz({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:$e("[&_tr]:border-b",t),...s})}function Rz({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:$e("[&_tr:last-child]:border-0",t),...s})}function Oh({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:$e("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function ia({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:$e("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function la({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:$e("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function Dz(t){return t===null?{label:"No Data",className:"bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400"}:t>=0?{label:"Good",className:"bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-400"}:{label:"Watch",className:"bg-amber-50 text-amber-700 dark:bg-amber-950 dar
427k:text-amber-400"}}function Mz(t){return t===null?"â":`${t.toFixed(1)}%`}function Pz(t){return t===null?"â":`${t>=0?"+":""}${t.toFixed(1)}%`}function Lz(t){return t===null?"â":`$${t.toFixed(0)}`}function pd(t,s,n){return t===null&&s===null?0:t===null?1:s===null?-1:n?t-s:s-t}function zz(t){return t===null?"no-data":t>=0?"good":"watch"}function Oz({stores:t,onStoreClick:s}){const[n,r]=l.useState("crVsMedian"),[a,o]=l.useState(!1),[i,d]=l.useState("all"),[m,p]=l.useState("all"),c=l.useMemo(()=>{const g=new Map;for(const y of t)y.vertical&&!g.has(y.vertical)&&g.set(y.vertical,y.verticalLabel);return Array.from(g.entries()).sort((y,j)=>y[1].localeCompare(j[1]))},[t]);function u(g){n===g?o(y=>!y):(r(g),o(g==="storeName"||g==="vertical"))}const x=l.useMemo(()=>t.filter(g=>!(i!=="all"&&zz(g.crVsMedian)!==i||m==="unassigned"&&g.vertical||m!=="all"&&m!=="unassigned"&&g.vertical!==m)),[t,i,m]),h=l.useMemo(()=>{const g=[...x];return g.sort((y,j)=>{switch(n){case"storeName":return a?y.storeName.localeCompare(j.storeName):j.storeName.localeCompare(y.storeName);case"vertical":return a?y.verticalLabel.localeCompare(j.verticalLabel):j.verticalLabel.localeCompare(y.verticalLabel);case"conversionRate":return pd(y.conversionRate,j.conversionRate,a);case"crVsMedian":return pd(y.crVsMedian,j.crVsMedian,a);case"aov":return pd(y.aov,j.aov,a);default:return 0}}),g},[x,n,a]);function b(g){return n!==g?"":a?" â²":" â¼"}const f=l.useMemo(()=>t.filter(g=>!g.vertical).length,[t]);return t.length===0?e.jsx("div",{className:"flex items-center justify-center rounded-md border py-12 text-sm text-muted-foreground",children:"No store analytics data available."}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(nn,{value:i,onValueChange:g=>d(g),children:[e.jsx(an,{className:"w-[150px]",children:e.jsx(rn,{placeholder:"Status"})}),e.jsxs(on,{children:[e.jsx(cs,{value:"all",children:"All Statuses"}),e.jsx(cs,{value:"good",children:"Good"}),e.jsx(cs,{value:"watch",children:"Watch"}),e.jsx(cs,{value:"no-data",children:"No Data"})]})]}),e.jsxs(nn,{value:m,onValueChange:g=>p(g),children:[e.jsx(an,{className:"w-[220px]",children:e.jsx(rn,{placeholder:"Vertical"})}),e.jsxs(on,{children:[e.jsx(cs,{value:"all",children:"All Verticals"}),e.jsxs(cs,{value:"unassigned",children:["Unassigned (",f,")"]}),c.map(([g,y])=>e.jsx(cs,{value:g,children:y},g))]})]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[h.length," of ",t.length," stores"]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ez,{children:[e.jsx(Iz,{children:e.jsxs(Oh,{children:[e.jsxs(ia,{className:"cursor-pointer select-none",onClick:()=>u("storeName"),children:["Store Name",b("storeName")]}),e.jsxs(ia,{className:"cursor-pointer select-none",onClick:()=>u("vertical"),children:["Vertical",b("vertical")]}),e.jsxs(ia,{className:"cursor-pointer select-none text-right",onClick:()=>u("conversionRate"),children:["Conv Rate",b("conversionRate")]}),e.jsxs(ia,{className:"cursor-pointer select-none text-right",onClick:()=>u("crVsMedian"),children:["vs Median",b("crVsMedian")]}),e.jsxs(ia,{className:"cursor-pointer select-none text-right",onClick:()=>u("aov"),children:["AOV",b("aov")]}),e.jsx(ia,{children:"Status"})]})}),e.jsx(Rz,{children:h.map(g=>{const y=Dz(g.crVsMedian);return e.jsxs(Oh,{className:"cursor-pointer",onClick:()=>s(g.storeId),children:[e.jsx(la,{className:"font-medium",children:g.storeName}),e.jsx(la,{className:"text-muted-foreground",children:g.verticalLabel}),e.jsx(la,{className:"text-right tabular-nums",children:Mz(g.conversionRate)}),e.jsx(la,{className:"text-right tabular-nums",children:e.jsx("span",{className:g.crVsMedian===null?"text-muted-foreground":g.crVsMedian>=0?"text-emerald-600 dark:text-emerald-400":"text-amber-600 dark:text-amber-400",children:Pz(g.crVsMedian)})}),e.jsx(la,{className:"text-right tabular-nums",children:Lz(g.aov)}),e.jsx(la,{children:e.jsx("span",{className:`inline-flex items-center rounded-md px-2 py-0.5 text-xs font-medium ${y.className}`,children:y.label})})]},g.storeId)})})]})})]})}function Bi(t){return{low:t.low.toString(),median:t.median.toString(),high:t.high.toString()}}function Fi(t){return{low:Number(t.low)||0,median:Number(t.median)||0,high:Number(t.high)||0}}function $z(t){return t.map(s=>({verticalId:s.verticalId,verticalLabel:s.verticalLabel,conversionRate:
427Bi(s.conversionRate),addToCartRate:Bi(s.addToCartRate),cartAbandonmentRate:Bi(s.cartAbandonmentRate),aov:Bi(s.aov)}))}const xd=[{key:"conversionRate",label:"Conv Rate %",step:"0.01"},{key:"addToCartRate",label:"ATC Rate %",step:"0.01"},{key:"cartAbandonmentRate",label:"Abandon %",step:"0.01"},{key:"aov",label:"AOV $",step:"0.01"}];function Bz({open:t,onClose:s,benchmarks:n,onSave:r}){const[a,o]=l.useState(""),[i,d]=l.useState([]);l.useEffect(()=>{if(!t)return;d($z(n));const u=n.length>0?n[0].dataAsOf:"";o(u)},[t,n]);const m=l.useCallback((u,x,h,b)=>{d(f=>{const g=[...f];return g[u]={...g[u],[x]:{...g[u][x],[h]:b}},g})},[]),p=l.useCallback(u=>{u.preventDefault();const x=i.map(h=>({verticalId:h.verticalId,conversionRate:Fi(h.conversionRate),addToCartRate:Fi(h.addToCartRate),cartAbandonmentRate:Fi(h.cartAbandonmentRate),aov:Fi(h.aov),dataAsOf:a}));r(x)},[i,a,r]),c=n.length>0?n[0].dataAsOf:"N/A";return e.jsx(br,{open:t,onOpenChange:u=>!u&&s(),children:e.jsxs(yr,{className:"sm:max-w-5xl max-h-[90vh] flex flex-col",children:[e.jsxs(jr,{children:[e.jsx(vr,{children:"Update Benchmark Data"}),e.jsxs(wr,{children:["Source: Dynamic Yield / Mastercard â Current: ",c]})]}),e.jsxs("form",{onSubmit:p,className:"flex flex-col gap-4 min-h-0",children:[e.jsxs("div",{className:"space-y-1.5 shrink-0",children:[e.jsx(Jt,{htmlFor:"bm-data-as-of",children:"Data As Of"}),e.jsx(it,{id:"bm-data-as-of",type:"text",required:!0,placeholder:"e.g. Q1 2025",value:a,onChange:u=>o(u.target.value),className:"max-w-xs"})]}),e.jsx(Pg,{className:"flex-1 min-h-0 max-h-[55vh] rounded-md border",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsxs("thead",{className:"bg-muted/50 sticky top-0 z-10",children:[e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"px-3 py-2 text-left font-medium text-foreground whitespace-nowrap min-w-[160px]",children:"Vertical"}),xd.map(u=>e.jsx("th",{colSpan:3,className:"px-2 py-2 text-center font-medium text-foreground border-l",children:u.label},u.key))]}),e.jsxs("tr",{className:"border-b bg-muted/30",children:[e.jsx("th",{}),xd.map(u=>e.jsxs(ee.Fragment,{children:[e.jsx("th",{className:"px-1 py-1 text-center text-xs font-normal text-muted-foreground border-l",children:"Low"}),e.jsx("th",{className:"px-1 py-1 text-center text-xs font-normal text-muted-foreground",children:"Med"}),e.jsx("th",{className:"px-1 py-1 text-center text-xs font-normal text-muted-foreground",children:"High"})]},`${u.key}-sub`))]})]}),e.jsx("tbody",{children:i.map((u,x)=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"px-3 py-2 font-medium text-foreground whitespace-nowrap",children:u.verticalLabel}),xd.map(h=>{const b=u[h.key];return e.jsxs(ee.Fragment,{children:[e.jsx("td",{className:"px-1 py-1 border-l",children:e.jsx(it,{type:"number",step:h.step,min:0,value:b.low,onChange:f=>m(x,h.key,"low",f.target.value),className:"h-8 w-20 text-center text-xs tabular-nums"})}),e.jsx("td",{className:"px-1 py-1",children:e.jsx(it,{type:"number",step:h.step,min:0,value:b.median,onChange:f=>m(x,h.key,"median",f.target.value),className:"h-8 w-20 text-center text-xs tabular-nums"})}),e.jsx("td",{className:"px-1 py-1",children:e.jsx(it,{type:"number",step:h.step,min:0,value:b.high,onChange:f=>m(x,h.key,"high",f.target.value),className:"h-8 w-20 text-center text-xs tabular-nums"})})]},h.key)})]},u.verticalId))})]})})}),e.jsxs(Gr,{className:"shrink-0",children:[e.jsx(ke,{type:"button",variant:"outline",onClick:s,children:"Cancel"}),e.jsx(ke,{type:"submit",children:"Save All"})]})]})]})})}function Fz(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function _i(t){const[s,n]=t.split("-").map(Number);return new Date(s,n-1).toLocaleDateString("en-US",{month:"long",year:"numeric"})}function _z({onBack:t,onLogoClick:s,initialShopDomain:n}){var We,ie,Ue,Te,He,Oe,Je;const{user:r}=pt(),[a,o]=l.useState([]),[i,d]=l.useState(!0);l.useEffect(()=>{(async()=>{const je=ys(),he=(await Ze(Re(je,"shopifyStores"))).docs.map(lt=>({id:lt.id,...lt.data()}));he.sort((lt,tt)=>(lt.name||"").localeCompare(tt.name||"")),o(he),d(!1)})()},[]);const[m,p]=l.useState(null),[c,u]=l.useState(""),[x,h]=l.useState(!1),b=l.useRef(null),f=l.useRef(null),[g,y]=l.useState(Fz()),[j,v]=l.useState(new Date().getFullYear()),T=l.useMemo(()=>a.find(de=>de.id===m)||null,[a,m]),k=l.useMemo(()=>
427{if(!c)return a;const de=c.toLowerCase();return a.filter(je=>[je.name,je.myshopifyUrl,je.id].some(qe=>qe==null?void 0:qe.toLowerCase().includes(de)))},[a,c]);l.useEffect(()=>{const de=je=>{f.current&&!f.current.contains(je.target)&&h(!1)};return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[]);const w=l.useRef(!1);l.useEffect(()=>{if(w.current||!n||a.length===0)return;const de=he=>(he||"").trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,""),je=de(n),qe=a.find(he=>de(he.myshopifyUrl)===je);qe&&(p(qe.id),w.current=!0)},[n,a]);const{benchmarks:I,refetch:A,getBenchmarkById:E}=u0(),{snapshots:C,collectData:N,autoCollect:S,backfill:O}=m0(m),{events:R,addEvent:z,updateEvent:D,toggleHidden:L,removeEvent:$}=XL(m),{recommendations:q,loading:P,generating:U,generate:V,dismissRecommendation:M}=ez(m,g),F=l.useMemo(()=>C.find(de=>de.period===g)||null,[C,g]),W=l.useMemo(()=>T!=null&&T.vertical?E(T.vertical):null,[T,E]),_=l.useMemo(()=>{const de=C.map(je=>je.period);return de.includes(g)||de.unshift(g),[...new Set(de)].sort().reverse()},[C,g]),[G,B]=l.useState(!1),[Y,J]=l.useState(!1),[H,Z]=l.useState(null),[Q,K]=l.useState(),[X,se]=l.useState(!1),[pe,me]=l.useState(!1),[Ne,at]=l.useState(!1),[ae,xe]=l.useState(!1),ze=l.useCallback(async()=>{var je,qe;if(!m||pe)return;me(!0);const de=ce.loading(`Collecting ${_i(g)}â¦`);try{const he=await S(g),lt=(he==null?void 0:he.succeeded)??0,tt=(he==null?void 0:he.failed)??0,Se=(qe=(je=he==null?void 0:he.results)==null?void 0:je.find(es=>es.status!=="success"))==null?void 0:qe.status;lt>0&&tt===0?ce.success(`Collected ${_i(g)}`,{id:de}):lt>0&&tt>0?ce.warning(`Collected with ${tt} failure(s)`,{id:de,description:Se}):ce.error("Collection failed",{id:de,description:Se||"No snapshots written"})}catch(he){ce.error("Collection failed",{id:de,description:(he==null?void 0:he.message)||String(he)})}finally{me(!1)}},[m,pe,S,g]),Le=l.useCallback(async()=>{if(!m||Ne)return;at(!0);const de=ce.loading("Backfilling 12 months⦠this can take a few minutes");try{const je=await O(12);if(!je)throw new Error("Backfill returned an unexpected result");const qe=(je==null?void 0:je.snapshotsCreated)??0,he=(je==null?void 0:je.snapshotsSkipped)??0,lt=(je==null?void 0:je.snapshotsFailed)??0;qe===0&<===0?ce.info(`Backfill complete â ${he} already existed, nothing new to add`,{id:de}):lt===0?ce.success(`Backfill complete â ${qe} new, ${he} skipped`,{id:de}):ce.warning(`Backfill finished with ${lt} failure(s)`,{id:de,description:`${qe} new, ${he} skipped, ${lt} failed`})}catch(je){ce.error("Backfill failed",{id:de,description:(je==null?void 0:je.message)||String(je)})}finally{at(!1)}},[m,Ne,O]),ht=l.useCallback(async de=>{if(ae)return;xe(!0);const je=ce.loading("Saving manual entryâ¦");try{await N(g,de),ce.success(`Saved ${_i(g)}`,{id:je}),B(!1)}catch(qe){ce.error("Save failed",{id:je,description:(qe==null?void 0:qe.message)||String(qe)})}finally{xe(!1)}},[N,g,ae]),ue=l.useCallback(async de=>{H?await D(H.id,de):await z({...de,createdBy:(r==null?void 0:r.uid)||"unknown"}),J(!1),Z(null)},[H,D,z,r]),we=l.useCallback(de=>{K(de),Z(null),J(!0)},[]),Be=l.useCallback(de=>{Z(de),K(void 0),J(!0)},[]),Ye=l.useCallback(async de=>{if(!m)return;const je=ys();await er(ut(je,"shopifyStores",m),{vertical:de}),o(qe=>qe.map(he=>he.id===m?{...he,vertical:de}:he))},[m]),rt=l.useCallback(async de=>{const je=ys(),qe=de.map(he=>qr(ut(je,"benchmarks",he.verticalId),{...he,updatedAt:ja.now(),source:"Dynamic Yield / Mastercard",sourceUrl:"https://marketing.dynamicyield.com/benchmarks/"},{merge:!0}));await Promise.all(qe),await A(),se(!1)},[A]),[te,ve]=l.useState([]);l.useEffect(()=>{const de=async()=>{var he,lt,tt;const je=ys(),qe=[];for(const Se of a){const es=Re(je,"shopifyStores",Se.id,"analyticsSnapshots"),_e=await Ze(es);let St=null;_e.docs.forEach(Ct=>{const ot=Ct.data();(!St||ot.period>St.period)&&(St=ot)});const $t=Se.vertical?E(Se.vertical):null;qe.push({storeId:Se.id,storeName:Se.name||Se.myshopifyUrl||Se.id,vertical:Se.vertical,verticalLabel:($t==null?void 0:$t.verticalLabel)||Se.vertical||"Unassigned",conversionRate:((he=St==null?void 0:St.shopify)==null?void 0:he.conversionRate)??null,crVsMedian:((lt=St==null?void 0:St.delta)==null?void 0:lt.conversionRateVsMedian)??null,aov:((tt=St==null?void 0:St.shopify)==null?void 0:tt.aov)??null})}ve(qe)};a.length>0&&de()},[a,E]);const Ae=F==null?void 0:F.shopify;return e.jsxs("div",{className:"min-h-screen bg-background flex flex-col max-w-6xl mx-auto pb-8",children:[e.jsx(Oa,{richColors:!0,position:"top-center",closeButton:!0}),e.jsxs("div",{className:"sticky top-0 z-10 border-b px-4 py-3 flex items-center gap-3",style:{backgroundColor:"var(--background)",backdropFilter:"blur(8px)"},children:[e.jsx(ke,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(dt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Conversion Rate Analytics"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Internal validation dashboard"})]}),e.jsxs(ke,{variant:"outline",size:"sm",onClick:()=>se(!0),children:[e.jsx(bg,{className:"h-4 w-4 mr-1"})," Benchmarks"]})]}),e.jsxs(nc,{defaultValue:"detail",className:"flex-1 px-4 pt-4",children:[e.jsxs(rc,{className:"mb-4 gap-1 rounded-lg p-1",style:{backgroundColor:"var(--muted)"},children:[e.jsxs(Hs,{value:"detail",className:"rounded-md px-3 py-1.5 text-sm font-medium data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=inactive]:text-gray-500",children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"})," Store Detail"]}),e.jsxs(Hs,{value:"all-stores",className:"rounded-md px-3 py-1.5 text-sm font-medium data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=inactive]:text-gray-500",children:[e.jsx(xN,{className:"h-4 w-4 mr-1"})," All Stores"]})]}),e.jsxs(qs,{value:"detail",className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap gap-3 items-end",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",ref:f,style:{position:"relative"},children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Store"}),e.jsxs("div",{className:"flex items-center border border-input rounded-md bg-input-background h-9 px-3 gap-2",children:[e.jsx(Pt,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("input",{ref:b,type:"text",className:"flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground",placeholder:m&&!x&&(((We=a.find(de=>de.id===m))==null?void 0:We.name)||((ie=a.find(de=>de.id===m))==null?void 0:ie.myshopifyUrl))||"Search stores...",value:c,onChange:de=>{u(de.target.value),h(!0)},onFocus:()=>{u(""),h(!0)}})]}),x&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-white dark:bg-gray-800 border rounded-md shadow-lg",style:{maxHeight:250,overflowY:"auto"},children:[k.length===0&&e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"No store found."}),k.map(de=>{const je=de.name||de.myshopifyUrl||de.id;return e.jsx("button",{className:`w-full text-left px-3 py-2 text-sm hover:bg-accent transition-colors ${m===de.id?"bg-accent font-medium":""}`,onClick:()=>{p(de.id),u(""),h(!1)},children:je},de.id)})]})]}),e.jsxs("div",{className:"w-[160px]",children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Period"}),e.jsxs(nn,{value:g,onValueChange:y,children:[e.jsx(an,{children:e.jsx(rn,{})}),e.jsx(on,{children:_.map(de=>e.jsxs(cs,{value:de,children:[_i(de),C.some(je=>
427je.period===de)?"":" (no data)"]},de))})]})]}),T&&e.jsxs("div",{className:"w-[200px]",children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Vertical"}),e.jsxs(nn,{value:T.vertical||"",onValueChange:Ye,children:[e.jsx(an,{children:e.jsx(rn,{placeholder:"Assign vertical..."})}),e.jsx(on,{children:I.map(de=>e.jsx(cs,{value:de.verticalId,children:de.verticalLabel},de.verticalId))})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{size:"sm",onClick:ze,disabled:!m||pe||Ne,children:pe?"Collectingâ¦":"Collect Data"}),e.jsx(ke,{size:"sm",variant:"outline",onClick:Le,disabled:!m||pe||Ne,children:Ne?"Backfillingâ¦":"Backfill 12mo"}),e.jsx(ke,{size:"sm",variant:"outline",onClick:()=>B(!0),disabled:!m,children:"Manual Entry"})]})]}),!m&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Select a store to view analytics."}),m&&e.jsxs(e.Fragment,{children:[Ae&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3",children:[e.jsx(Gn,{label:"Conv Rate",value:`${Ae.conversionRate}%`,delta:(Ue=F==null?void 0:F.delta)==null?void 0:Ue.conversionRateVsMedian,deltaLabel:"vs median"}),e.jsx(Gn,{label:"Add to Cart",value:`${Ae.addToCartRate}%`,delta:(Te=F==null?void 0:F.delta)==null?void 0:Te.addToCartVsMedian,deltaLabel:"vs median"}),e.jsx(Gn,{label:"Cart Abandon",value:`${Ae.cartAbandonmentRate}%`,invertDelta:!0}),e.jsx(Gn,{label:"AOV",value:`$${Ae.aov}`,delta:(He=F==null?void 0:F.delta)==null?void 0:He.aovVsMedian,deltaLabel:"vs median"}),e.jsx(Gn,{label:"Revenue",value:`$${((Oe=Ae.totalRevenue)==null?void 0:Oe.toLocaleString())||"0"}`})]}),Ae&&W&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Benchmark Comparison"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[W.verticalLabel," â ",W.source,", ",W.dataAsOf]})]})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsx(zi,{label:"Conversion Rate",value:Ae.conversionRate,low:W.conversionRate.low,median:W.conversionRate.median,high:W.conversionRate.high,suffix:"%"}),e.jsx(zi,{label:"Add to Cart Rate",value:Ae.addToCartRate,low:W.addToCartRate.low,median:W.addToCartRate.median,high:W.addToCartRate.high,suffix:"%"}),e.jsx(zi,{label:"Cart Abandonment",value:Ae.cartAbandonmentRate,low:W.cartAbandonmentRate.low,median:W.cartAbandonmentRate.median,high:W.cartAbandonmentRate.high,suffix:"%",invertColors:!0}),e.jsx(zi,{label:"Average Order Value",value:Ae.aov,low:W.aov.low,median:W.aov.median,high:W.aov.high,suffix:"$"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Timeline"}),e.jsxs(nn,{value:String(j),onValueChange:de=>v(Number(de)),children:[e.jsx(an,{className:"w-[100px] h-8",children:e.jsx(rn,{})}),e.jsx(on,{children:[new Date().getFullYear(),new Date().getFullYear()-1,new Date().getFullYear()-2].map(de=>e.jsx(cs,{value:String(de),children:de},de))})]})]}),e.jsx(mz,{snapshots:C,events:R,benchmark:(W==null?void 0:W.conversionRate)||null,year:j,onGraphClick:we,onEventClick:de=>{const je=R.find(qe=>qe.eventId===de||qe.id===de);je&&Be(je)}})]}),e.jsx(hz,{events:R,year:j,onEdit:Be,onDelete:$,onToggleHidden:L,onAddNew:()=>{Z(null),K(void 0),J(!0)}}),e.jsx(Az,{recommendations:q,loading:P,generating:U,onGenerate:V,onDismiss:M}),(F==null?void 0:F.notes)&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Admin Notes"}),e.jsx("p",{className:"text-sm",children:F.notes}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Collected: ",F.collectedBy," â ",(Je=F.collectedAt)!=null&&Je.seconds?new Date(F.collectedAt.seconds*1e3).toLocaleDateString():"Unknown"]})]})]})]}),e.jsx(qs,{value:"all-stores",children:e.jsx(Oz,{stores:te,onStoreClick:de=>{p(de);const je=document.querySelector('[data-value="detail"]');je==null||je.click()}})})]}),e.jsx(vz,{open:G,onClose:()=>B(!1),onSave:ht,period:g,existingData:F==null?void 0:F.shopify}),e.jsx(yz,{open:Y,onClose:()=>{J(!1),Z(null)},onSave:ue,initialData:H||void 0,initialDate:Q}),e.jsx(Bz,{open:X,onClose:()=>se(!1),benchmarks:I,onSave:rt})]})}function Wz(t){const n=[...t].sort((p,c)=>c.period.localeCompare(p.period)).slice(0,12);if(n.length===0)return{totalRevenue:0,avgSessions:0,avgCR:0,avgAOV:0,months:0};let r=0,a=0,o=0,i=0,d=0,m=0;for(const p of n){const c=p.shopify;c&&(r+=c.totalRevenue||0,a+=c.sessions||0,o+=c.orders||0,i+=c.conversionRate||0,d+=c.aov||0,m++)}return{totalRevenue:r,avgSessions:m>0?a/m:0,avgCR:m>0?i/m:0,avgAOV:m>0?d/m:0,months:m}}function hd(t,s,n,r,a,o,i,d){const m=[];let p=0;for(let c=0;c<=d;c++){const u=Math.pow(1+o/100,c),x=Math.pow(1+i/100,c),h=c===0?s:s+(a-s)*c/d,b=t*u,f=n*x,g=b*12*(h/100)*f,y=g-r;p+=c===0?0:y,m.push({year:c,label:c===0?"Current":`Year ${c}`,conversionRate:Math.round(h*100)/100,monthlySessions:Math.round(b),aov:Math.round(f*100)/100,annualRevenue:Math.round(g),additionalRevenue:c===0?0:Math.round(y),cumulativeAdditional:Math.round(p)})}return m}function Uz(t,s,n){return l.useMemo(()=>{var w,I;const r=Wz(t);if(r.months===0||r.avgCR===0)return{currentCR:0,currentAnnualRevenue:0,currentMonthlySessions:0,currentAOV:0,benchmarkMedianCR:((w=s==null?void 0:s.conversionRate)==null?void 0:w.median)??null,revenueAtMedian:null,revenueGap:null,
427scenarios:[],targetBreakdown:[],valuePerCRPoint:0,hasData:!1};const{totalRevenue:a,avgSessions:o,avgCR:i,avgAOV:d}=r,m=r.months<12?a/r.months*12:a,p=((I=s==null?void 0:s.conversionRate)==null?void 0:I.median)??null,c=p!==null?m*(p/i):null,u=c!==null?Math.round(c-m):null,x=m/i,{targetCR:h,annualTrafficGrowth:b,annualAOVGrowth:f,years:g}=n,y=hd(o,i,d,m,i,b,f,g),j=i+(h-i)/2,v=hd(o,i,d,m,j,b,f,g),T=hd(o,i,d,m,h,b,f,g),k=[{name:"Current Trajectory",data:y,color:"#94a3b8"},{name:"Conservative",data:v,color:"#f59e0b"},{name:"Target",data:T,color:"#10b981"}];return{currentCR:Math.round(i*100)/100,currentAnnualRevenue:Math.round(m),currentMonthlySessions:Math.round(o),currentAOV:Math.round(d*100)/100,benchmarkMedianCR:p,revenueAtMedian:c!==null?Math.round(c):null,revenueGap:u,scenarios:k,targetBreakdown:T,valuePerCRPoint:Math.round(x),hasData:!0}},[t,s,n])}function fd(t){return t>=1e6?`$${(t/1e6).toFixed(1)}M`:t>=1e3?`$${(t/1e3).toFixed(0)}K`:`$${t.toLocaleString()}`}function ca(t){return`$${t.toLocaleString()}`}function gd(t){return t?t.trim().toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,""):""}const Hz=` 428 .profit-range::-webkit-slider-thumb { 429 -webkit-appearance: none; 430 appearance: none; 431 width: 18px; 432 height: 18px; 433 border-radius: 50%; 434 background: #10b981; 435 border: 2px solid white; 436 box-shadow: 0 1px 3px rgba(0,0,0,0.2); 437 cursor: pointer; 438 margin-top: -5px; 439 } 440 .profit-range::-moz-range-thumb { 441 width: 18px; 442 height: 18px; 443 border-radius: 50%; 444 background: #10b981; 445 border: 2px solid white; 446 box-shadow: 0 1px 3px rgba(0,0,0,0.2); 447 cursor: pointer; 448 } 449 .profit-range::-webkit-slider-runnable-track { 450 height: 8px; 451 border-radius: 9999px; 452 } 453 .profit-range::-moz-range-track { 454 height: 8px; 455 border-radius: 9999px; 456 } 457`;function qz({onBack:t,onLogoClick:s,initialShopDomain:n,initialTrafficGrowthPct:r,onNavigateToMarketingResearch:a,onNavigateToConversionRate:o}){var P,U,V,M;const{user:i}=pt(),[d,m]=l.useState([]),[p,c]=l.useState(!0);l.useEffect(()=>{(async()=>{const W=ys(),G=(await Ze(Re(W,"shopifyStores"))).docs.map(B=>({id:B.id,...B.data()}));G.sort((B,Y)=>(B.name||"").localeCompare(Y.name||"")),m(G),c(!1)})()},[]);const[u,x]=l.useState(null),[h,b]=l.useState(""),[f,g]=l.useState(!1),y=l.useRef(null),j=l.useMemo(()=>d.find(F=>F.id===u)||null,[d,u]),v=l.useMemo(()=>{if(!h)return d;const F=h.toLowerCase();return d.filter(W=>[W.name,W.myshopifyUrl,W.id].some(_=>_==null?void 0:_.toLowerCase().includes(F)))},[d,h]);l.useEffect(()=>{const F=W=>{y.current&&!y.current.contains(W.target)&&g(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[]);const{getBenchmarkById:T}=u0(),{snapshots:k,loading:w}=m0(u),I=l.useMemo(()=>{if(!j)return null;const F=j.verticalOverride||j.vertical;return F?T(F):null},[j,T]),A=((P=I==null?void 0:I.conversionRate)==null?void 0:P.median)??3,[E,C]=l.useState(A),[N,S]=l.useState(0),[O,R]=l.useState(0);l.useEffect(()=>{var F;(F=I==null?void 0:I.conversionRate)!=null&&F.median&&C(I.conversionRate.median)},[I]);const z=l.useRef(!1);l.useEffect(()=>{if(z.current||!n||d.length===0)return;const F=gd(n),W=d.find(_=>gd(_.myshopifyUrl)===F);W&&(x(W.id),z.current=!0)},[n,d]);const D=l.useRef(!1);l.useEffect(()=>{D.current||typeof r!="number"||!Number.isFinite(r)||(S(r),D.current=!0)},[r]);const L=l.useMemo(()=>({targetCR:E,annualTrafficGrowth:N,annualAOVGrowth:O,years:5}),[E,N,O]),$=Uz(k,I,L),q=l.useMemo(()=>{if(!$.hasData||$.scenarios.length===0)return[];const F=$.scenarios[0].data.length,W=[];for(let _=0;_<F;_++){const G={label:$.scenarios[0].data[_].label};for(const B of $.scenarios)G[B.name]=B.data[_].annualRevenue;W.push(G)}return W},[$]);return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("style",{children:Hz}),e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"mx-auto max-w-5xl px-4 py-6",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-6",children:[e.jsx(ke,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(dt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Profit Projections"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Revenue impact of conversion rate improvements over 5 years"})]}),(j==null?void 0:j.myshopifyUrl)&&(()=>{const F=gd(j.myshopifyUrl);return F?e.jsxs("div",{className:"flex gap-2 mt-1",children:[o&&e.jsx(ke,{variant:"outline",size:"sm",onClick:()=>o(F),children:"Conversion Rate"}),a&&e.jsx(ke,{variant:"outline",size:"sm",onClick:()=>a(F),children:"Marketing Research"})]}):null})()]}),e.jsxs("div",{className:"mb-6 max-w-sm",ref:y,style:{position:"relative"},children:[e.jsxs("div",{className:"flex items-center border border-input rounded-md bg-input-background h-9 px-3 gap-2",children:[e.jsx(Pt,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("input",{type:"text",className:"flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground",placeholder:u&&!f?((U=d.find(F=>F.id===u))==null?void 0:U.name)||((V=d.find(F=>F.id===u))==null?void 0:V.myshopifyUrl)||"Search stores...":p?"Loading stores...":"Search stores...",value:h,onChange:F=>{b(F.target.value),g(!0)},onFocus:()=>{b(""),g(!0)}})]}),f&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full bg-white dark:bg-gray-800 border rounded-md shadow-lg",style:{maxHeight:250,overflowY:"auto"},children:[v.length===0&&e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"No store found."}),v.map(F=>{const W=F.name||F.myshopifyUrl||F.id;return e.jsx("button",{className:`w-full text-left px-3 py-2 text-sm hover:bg-accent transition-colors ${u===F.id?"bg-accent font-medium":""}`,onClick:()=>{x(F.id),b(""),g(!1)},children:W}
457,F.id)})]})]}),!u&&e.jsx(jt,{children:e.jsxs(vt,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium",children:"Select a store to view profit projections"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Choose a store with analytics data to model revenue growth scenarios"})]})}),u&&w&&e.jsx(jt,{children:e.jsx(vt,{className:"flex items-center justify-center py-16",children:e.jsx("p",{className:"text-muted-foreground",children:"Loading analytics data..."})})}),u&&!w&&!$.hasData&&e.jsx(jt,{children:e.jsxs(vt,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Dt,{className:"h-12 w-12 text-amber-500 mb-4"}),e.jsx("p",{className:"text-lg font-medium",children:"No analytics data available"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Collect analytics snapshots in the Conversion Analytics dashboard first"})]})}),u&&!w&&$.hasData&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Gn,{label:"Current CR",value:`${$.currentCR}%`,icon:e.jsx(gr,{className:"h-4 w-4"})}),e.jsx(Gn,{label:"Annual Revenue",value:fd($.currentAnnualRevenue),icon:e.jsx(yu,{className:"h-4 w-4"})}),e.jsx(Gn,{label:"Benchmark Median",value:$.benchmarkMedianCR!==null?`${$.benchmarkMedianCR}%`:"N/A",delta:$.benchmarkMedianCR!==null?Math.round(($.currentCR-$.benchmarkMedianCR)*100)/100:void 0,deltaLabel:"vs benchmark",icon:e.jsx(Fr,{className:"h-4 w-4"})}),e.jsx(Gn,{label:"Revenue Gap",value:$.revenueGap!==null?fd(Math.abs($.revenueGap)):"N/A",icon:e.jsx(Xo,{className:"h-4 w-4"})})]}),e.jsx(jt,{className:"border-emerald-200 bg-emerald-50/50 dark:border-emerald-900 dark:bg-emerald-950/30",children:e.jsx(vt,{className:"py-4",children:e.jsxs("p",{className:"text-sm text-emerald-800 dark:text-emerald-300",children:[e.jsx("strong",{children:"Each 1% point of conversion rate"})," is worth approximately"," ",e.jsx("strong",{children:ca($.valuePerCRPoint)})," in annual revenue for this store."]})})}),e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsx(vs,{className:"text-base",children:"Scenario Controls"})}),e.jsxs(vt,{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Target Conversion Rate"}),e.jsxs("span",{className:"text-sm font-semibold text-emerald-600",children:[E.toFixed(1),"%"]})]}),e.jsx("input",{type:"range",value:E*10,onChange:F=>C(Number(F.target.value)/10),min:Math.round($.currentCR*10),max:100,step:1,className:"profit-range w-full appearance-none cursor-pointer",style:{background:`linear-gradient(to right, #10b981 0%, #10b981 ${(E*10-Math.round($.currentCR*10))/(100-Math.round($.currentCR*10))*100}%, #e2e8f0 ${(E*10-Math.round($.currentCR*10))/(100-Math.round($.currentCR*10))*100}%, #e2e8f0 100%)`}}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{children:["Current: ",$.currentCR,"%"]}),$.benchmarkMedianCR!==null&&e.jsxs("span",{children:["Median: ",$.benchmarkMedianCR,"%"]}),e.jsx("span",{children:"10%"})]})]}),((M=I==null?void 0:I.conversionRate)==null?void 0:M.high)!=null&&E>I.conversionRate.high&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-2.5 dark:border-amber-800 dark:bg-amber-950/40",children:[e.jsx(Dt,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("p",{className:"text-sm text-amber-800 dark:text-amber-300",children:["Target (",E.toFixed(1),"%) exceeds the top industry benchmark (",I.conversionRate.high,"%). Achieving this would require exceptional optimization beyond typical results for this vertical."]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium block mb-1.5",children:"Annual Traffic Growth"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{type:"number",value:N,onChange:F=>S(Number(F.target.value)||0),min:-20,max:50,step:1,className:"w-20"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"%"})]}),e.jsxs("div",{className:"mt-2 space-y-0.5 text-xs text-muted-foreground",children:[e.jsxs("p",{children:["Now: ",e.jsx("span",{className:"font-medium text-foreground",children:$.currentMonthlySessions.toLocaleStr
457ing()})," sessions/mo"]}),$.targetBreakdown.length>0&&e.jsxs("p",{children:["Year 5: ",e.jsx("span",{className:"font-medium text-foreground",children:$.targetBreakdown[$.targetBreakdown.length-1].monthlySessions.toLocaleString()})," sessions/mo"]}),$.targetBreakdown.length>0&&e.jsxs("p",{children:["Year 5 annual: ",e.jsx("span",{className:"font-medium text-foreground",children:($.targetBreakdown[$.targetBreakdown.length-1].monthlySessions*12).toLocaleString()})," sessions"]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium block mb-1.5",children:"Annual AOV Growth"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{type:"number",value:O,onChange:F=>R(Number(F.target.value)||0),min:-20,max:50,step:1,className:"w-20"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"%"})]}),e.jsxs("div",{className:"mt-2 space-y-0.5 text-xs text-muted-foreground",children:[e.jsxs("p",{children:["Now: ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",$.currentAOV.toFixed(2)]})]}),$.targetBreakdown.length>0&&e.jsxs("p",{children:["Year 5: ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",$.targetBreakdown[$.targetBreakdown.length-1].aov.toFixed(2)]})]}),$.targetBreakdown.length>0&&(()=>{const F=$.targetBreakdown[$.targetBreakdown.length-1],W=F.monthlySessions*12*(F.conversionRate/100)*F.aov;return e.jsxs("p",{children:["Year 5 revenue: ",e.jsx("span",{className:"font-medium text-foreground",children:ca(Math.round(W))})]})})()]})]})]})]})]}),e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsx(vs,{className:"text-base",children:"5-Year Revenue Projection"})}),e.jsx(vt,{children:e.jsx("div",{children:e.jsx(vf,{width:"100%",height:350,children:e.jsxs(Xj,{data:q,margin:{top:10,right:10,left:10,bottom:0},children:[e.jsx(wf,{strokeDasharray:"3 3",className:"stroke-border"}),e.jsx(Nf,{dataKey:"label",tick:{fontSize:12},className:"fill-muted-foreground"}),e.jsx(kf,{tickFormatter:F=>fd(F),tick:{fontSize:12},className:"fill-muted-foreground",width:70}),e.jsx(Sf,{formatter:(F,W)=>[ca(F),W],labelStyle:{fontWeight:600},contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e2e8f0",borderRadius:"8px",fontSize:"13px",boxShadow:"0 4px 12px rgba(0,0,0,0.1)"}}),e.jsx(ev,{}),$.scenarios.map(F=>e.jsx(tv,{type:"monotone",dataKey:F.name,stroke:F.color,fill:F.color,fillOpacity:F.name==="Target"?.15:.05,strokeWidth:F.name==="Target"?2.5:1.5,dot:F.name==="Target"},F.name))]})})})})]}),e.jsxs(jt,{children:[e.jsx(fs,{children:e.jsx(vs,{className:"text-base",children:"Year-by-Year Breakdown (Target Scenario)"})}),e.jsx(vt,{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",children:[e.jsx("th",{className:"pb-2 pr-4 font-medium text-muted-foreground",children:"Year"}),e.jsx("th",{className:"pb-2 pr-4 font-medium text-muted-foreground text-right",children:"CR"}),e.jsx("th",{className:"pb-2 pr-4 font-medium text-muted-foreground text-right",children:"Monthly Sessions"}),e.jsx("th",{className:"pb-2 pr-4 font-medium text-muted-foreground text-right",children:"AOV"}),e.jsx("th",{className:"pb-2 pr-4 font-medium text-muted-foreground text-right",children:"Annual Revenue"}),e.jsx("th",{className:"pb-2 pr-4 font-medium text-muted-foreground text-right",children:"Additional Revenue"}),e.jsx("th",{className:"pb-2 font-medium text-muted-foreground text-right",children:"Cumulative Gain"})]})}),e.jsx("tbody",{children:$.targetBreakdown.map(F=>e.jsxs("tr",{className:"border-b last:border-b-0",children:[e.jsx("td",{className:"py-2.5 pr-4 font-medium",children:F.label}),e.jsxs("td",{className:"py-2.5 pr-4 text-right",children:[F.conversionRate,"%"]}),e.jsx("td",{className:"py-2.5 pr-4 text-right",children:F.monthlySessions.toLocaleString()}),e.jsxs("td",{className:"py-2.5 pr-4 text-right",children:["$",F.aov.toFixed(2)]}),e.jsx("td",{className:"py-2.5 pr-4 text-right font-medium",children:ca(F.annualRevenue)}),e.jsx("td",{className:`py-2.5 pr-4 text-right ${F.additionalRevenue>0?"text-emerald-600 font-medium":""}`,children:F.additionalRevenue>0?`+${ca(F.additionalRevenue)}`:"â"}
457),e.jsx("td",{className:`py-2.5 text-right ${F.cumulativeAdditional>0?"text-emerald-600 font-semibold":""}`,children:F.cumulativeAdditional>0?`+${ca(F.cumulativeAdditional)}`:"â"})]},F.year))})]})})]})]})]})]})}const Vz=(t,s)=>{if(!t||!s)return"â";const n=t.toDate(),r=s.toDate();return n.toDateString()===r.toDateString()?n.toLocaleDateString():`${n.toLocaleDateString()} â ${r.toLocaleDateString()}`},Yz=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;async function Gz(t){var r;const s=t.match(Yz);if(!s)return null;const n=`${s[4]}.${s[3]}.${s[2]}.${s[1]}.in-addr.arpa`;try{const a=await fetch(`https://dns.google/resolve?name=${n}&type=PTR`,{signal:AbortSignal.timeout(5e3)});if(!a.ok)return null;const i=(r=(await a.json()).Answer)==null?void 0:r.find(d=>d.type===12);return i?i.data.replace(/\.$/,""):null}catch{return null}}function Kz({domain:t,status:s,onClose:n}){var u,x;const[r,a]=l.useState([]),[o,i]=l.useState(!0),[d,m]=l.useState(null),[p,c]=l.useState({});return l.useEffect(()=>{let h=!1;return i(!0),sO(t).then(b=>{h||a(b)}).finally(()=>{h||i(!1)}),()=>{h=!0}},[t]),l.useEffect(()=>{var f;const h=((f=s==null?void 0:s.topFailingSources)==null?void 0:f.map(g=>g.sourceIp))??[];if(h.length===0)return;let b=!1;return Promise.all(h.map(async g=>[g,await Gz(g)])).then(g=>{b||c(y=>{const j={...y};for(const[v,T]of g)j[v]=T;return j})}),()=>{b=!0}},[s==null?void 0:s.topFailingSources]),e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.5)"},onClick:n,children:e.jsxs("div",{className:"bg-white rounded-lg w-full flex flex-col border border-border overflow-hidden",style:{maxWidth:"42rem",maxHeight:"85vh",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.35), 0 10px 20px -5px rgba(0, 0, 0, 0.15)"},onClick:h=>h.stopPropagation(),children:[e.jsxs("div",{className:"bg-white border-b border-border px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:(s==null?void 0:s.clientCompanyName)||"â"}),e.jsx("h2",{className:"font-mono text-lg",children:t})]}),e.jsx(ke,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(mt,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto flex-1",children:[e.jsxs("section",{children:[e.jsx("h3",{className:"text-xs uppercase tracking-wide text-muted-foreground mb-2",children:"Published _dmarc record"}),(u=s==null?void 0:s.published)!=null&&u.found?e.jsx("pre",{className:"text-xs bg-muted rounded p-3 whitespace-pre-wrap break-all font-mono",children:s.published.rawRecord}):e.jsx("div",{className:"text-sm text-red-700",children:"No record published"}),((x=s==null?void 0:s.published)==null?void 0:x.lastProbedAt)&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Last probed ",s.published.lastProbedAt.toDate().toLocaleString()]})]}),(s==null?void 0:s.topFailingSources)&&s.topFailingSources.length>0&&e.jsxs("section",{children:[e.jsx("h3",{className:"text-xs uppercase tracking-wide text-muted-foreground mb-2",children:"Top failing sources (7d)"}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs text-muted-foreground",children:e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("th",{className:"text-left font-medium py-1",children:"Source IP"}),e.jsx("th",{className:"text-left font-medium py-1",children:"Host (PTR)"}),e.jsx("th",{style:{textAlign:"right"},className:"font-medium py-1",children:"Failing"})]})}),e.jsx("tbody",{children:s.topFailingSources.map(h=>{const b=p[h.sourceIp];return e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("td",{className:"font-mono py-1",children:h.sourceIp}),e.jsx("td",{style:{wordBreak:"break-all"},className:"font-mono text-xs text-muted-foreground py-1",children:b===void 0?"â¦":b===null?"â":b}),e.jsxs("td",{style:{textAlign:"right"},className:"text-xs text-muted-foreground py-1 whitespace-nowrap",children:[h.messages.toLocaleString()," msgs · ",h.pctOfFails,"%"]})]},h.sourceIp)})})]})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-xs uppercase tracking-wide text-muted-foreground mb-2",children:"Recent reports"}),o?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"Loadingâ¦"}):r.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"No reports yet for this domain."}):e.jsx("div",{className:"space-y-2",children:r.map(h=>{const b=h.totals||{messages:0,passing:0},f=b.messages>0?Math.round(b.passing/b.messages*100):0,g=d===h.id;return e.jsxs("div",{className:"border border-border rounded",children:[e.jsxs("button",{onClick:()=>m(g?null:h.id),className:"w-full text-left px-3 py-2 flex items-center justify-between hover:bg-muted/40",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:h.orgName}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Vz(h.dateRangeBeginTs,h.dateRangeEndTs)})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-sm font-mono",children:[f,"%"]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[b.messages.toLocaleStr
457ing()," msgs"]})]})]}),g&&h.records&&h.records.length>0&&e.jsx("div",{className:"border-t border-border px-3 py-2 bg-muted/20",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-1 font-medium",children:"Source IP"}),e.jsx("th",{className:"text-left py-1 font-medium",children:"From"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Count"}),e.jsx("th",{className:"text-center py-1 font-medium",children:"DKIM"}),e.jsx("th",{className:"text-center py-1 font-medium",children:"SPF"})]})}),e.jsx("tbody",{children:h.records.map((y,j)=>e.jsxs("tr",{className:"border-t border-border",children:[e.jsx("td",{className:"py-1 font-mono",children:y.sourceIp}),e.jsx("td",{className:"py-1 font-mono",children:y.headerFrom}),e.jsx("td",{className:"py-1 text-right font-mono",children:y.count.toLocaleString()}),e.jsx("td",{className:`py-1 text-center ${y.dkimEval==="pass"?"text-emerald-700":"text-red-700"}`,children:y.dkimEval}),e.jsx("td",{className:`py-1 text-center ${y.spfEval==="pass"?"text-emerald-700":"text-red-700"}`,children:y.spfEval})]},`${y.sourceIp}-${j}`))})]})})]},h.id)})})]})]})]})})}const Jd="[email protected]",Wi=`mailto:${Jd}`,Qz=t=>{if(!t)return{mode:"fresh",value:`v=DMARC1; p=none; rua=${Wi}`};const s=t.split(";").map(r=>r.trim()).filter(Boolean),n=s.findIndex(r=>r.toLowerCase().startsWith("rua="));if(n===-1)s.push(`rua=${Wi}`);else{const a=s[n].slice(4).split(",").map(i=>i.trim()).filter(Boolean);a.some(i=>i.toLowerCase()===Wi.toLowerCase())||a.push(Wi),s[n]=`rua=${a.join(",")}`}return{mode:"append",value:s.join("; "),previous:t}},Jz=t=>t.messages===0?0:Math.round(t.passing/t.messages*100),Zz=t=>t?t==="reject"?{label:"p=reject",cls:"bg-emerald-100 text-emerald-800"}:t==="quarantine"?{label:"p=quarantine",cls:"bg-amber-100 text-amber-800"}:{label:"p=none",cls:"bg-slate-100 text-slate-700"}:{label:"no record",cls:"bg-red-100 text-red-700"},Xz=t=>t?t.toDate().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â";function eO({onBack:t,onLogoClick:s}){const{user:n,token:r}=pt(),[a,o]=l.useState([]),[i,d]=l.useState(!0),[m,p]=l.useState(!1),[c,u]=l.useState("overview"),[x,h]=l.useState(""),[b,f]=l.useState(null),[g,y]=l.useState(null),[j,v]=l.useState(null),[T,k]=l.useState(!1);l.useEffect(()=>{const N=ys();ps(ut(N,"dmarcConfig","owner")).then(S=>{if(S.exists()){const O=S.data();y({uid:O.uid,gmailAddress:O.gmailAddress})}})},[]);const w=l.useCallback(async()=>{const N=ys(),[S,O]=await Promise.all([Ze(Re(N,"dmarcDomainStatus")),Ze(Ge(Re(N,"clients"),Ve("lifecycleStage","==","active")))]),R=new Set(O.docs.map(D=>D.id)),z=S.docs.map(D=>({id:D.id,...D.data()})).filter(D=>D.clientId&&R.has(D.clientId));z.sort((D,L)=>{var P,U;const $=((P=D.totals7d)==null?void 0:P.failing)??0,q=((U=L.totals7d)==null?void 0:U.failing)??0;return $!==q?q-$:(D.clientCompanyName||D.domain).localeCompare(L.clientCompanyName||L.domain)}),o(z)},[]);l.useEffect(()=>{w().finally(()=>d(!1))},[w]);const I=l.useMemo(()=>{if(!x.trim())return a;const N=x.toLowerCase();return a.filter(S=>S.domain.toLowerCase().includes(N)||(S.clientCompanyName||"").toLowerCase().includes(N))},[a,x]),A=l.useMemo(()=>{var z;let N=0,S=0,O=0,R=0;for(const D of a)D.status==="enforcing"?S++:D.status==="monitoring"?N++:D.status==="not-monitored"&&O++,R+=((z=D.totals7d)==null?void 0:z.failing)??0;return{monitored:N,enforcing:S,notMonitored:O,totalFailing7d:R,totalDomains:a.length}},[a]),E=l.useCallback(async()=>{if(!r){ce.error("Not signed in");return}k(!0);try{const N=await fetch("https://us-central1-bucky-app-355a3.cloudfunctions.net/adminTriggerDmarcDigest?mode=preview",{headers:{Authorization:`Bearer ${r}`}}),S=await N.json();if(!N.ok)throw new Error((S==null?void 0:S.error)||`HTTP ${N.status}`);v({text:S.text,firedCount:S.firedCount??0,suppressedCount:S.suppressedCount??0,resolvedCount:S.resolvedCount??0})}catch(N){ce.error(N instanceof Error?N.message:"Preview failed")}finally{k(!1)}},[r]),C=l.useCallback(async N=>{if(!r){ce.error("Not signed in");return}p(!0);try{const S=await fetch(`https://us-central1-bucky-app-355a3.cloudfunctions.net/adminTriggerDmarcIngest?mode=${N}`,{headers:{Authorization:`Bearer ${r}`}}),O=await S.json();if(!S.ok)throw new Error((O==null?void 0:O.error)||`HTTP ${S.status}`);const R=O==null?void 0:O.ingest;R&&R.errors>0?ce.warning(`DMARC ${N}: ${R.stored} stored, ${R.errors} error${R.errors===1?"":"s"} â check function logs`):R?ce.success(`DMARC ${N}: ${R.stored} stored, ${R.skipped} skipped (${R.processed} message${R.processed===1?"":"s"})`):ce.success(`DMARC ${N} complete`),await w()}catch(S){ce.error(S instanceof Error?S.message:"DMARC refresh failed")}finally{p(!1)}},[r,w]);return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(Oa,{position:"top-right"}),e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 py-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6 flex-wrap gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ke,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(dt,{className:"w-4 h-4 mr-1"})," Back"]}),e.jsx("h1",{className:"text-2xl font-semibold",children:"DMARC Monitoring"})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(ke,{variant:"outline",size:"sm",onClick:()=>C("probe"),disabled:m,children:[e.jsx(yt,{className:`w-4 h-4 mr-1 ${m?"animate-spin":""}`}),"Probe DNS"]}),e.jsxs(ke,{variant:"outline",size:"sm",onClick:()=>C("ingest"),disabled:m,children:[e.jsx(yt,{className:`w-4 h-4 mr-1 ${m?"animate-spin":""}`}),"Ingest reports"]}),e.jsxs(ke,{variant:"outline",size:"sm",onClick:E,disabled:T,children:[e.jsx(Tn,{className:`w-4 h-4 mr-1 ${T?"animate-pulse":""}`}),"Preview digest"]})]})]}),!g&&e.jsxs("div",{className:"mb-4 rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-900",children:["DMARC owner config missing â ingest will fail. Restore the",e.jsx("code",{className:"font-mono mx-1",children:"dmarcConfig/owner"})," Firestore doc (uid of the Bucky user holding the Gmail OAuth grant for the mailbox receiving ",e.jsx("code",{className:"font-mono",children:"[email protected]"}),")."]}),g&&e.jsxs("div",{className:"mb-4 text-xs text-muted-foreground",children:["Ingest mailbox owner: ",e.jsx("span",{className:"font-mono",children:g.gmailAddress})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-6",children:[e.jsx(Ui,{icon:e.jsx(Xi,{className:"w-5 h-5 text-emerald-600"}),label:"Enforcing",value:A.enforcing,sub:`of ${A.totalDomains} domains`}),e.jsx(Ui,{icon:e.jsx(Xi,{className:"w-5 h-5 text-blue-600"}),label:"Monitoring",value:A.monitored,sub:"receiving reports"}),e.jsx(Ui,{icon:e.jsx(uN,{className:"w-5 h-5 text-red-600"}),label:"Not monitored",value:A.notMonitored,sub:"needs DNS rollout"}),e.jsx(Ui,{icon:e.jsx(Dt,{className:"w-5 h-5 text-amber-600"}
457),label:"Failing (7d)",value:A.totalFailing7d.toLocaleString(),sub:"messages without alignment"})]}),e.jsxs(nc,{value:c,onValueChange:N=>u(N),children:[e.jsxs(rc,{children:[e.jsx(Hs,{value:"overview",children:"Overview"}),e.jsxs(Hs,{value:"rollout",children:["Rollout worklist (",A.notMonitored,")"]})]}),e.jsxs(qs,{value:"overview",className:"mt-4",children:[e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Pt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(it,{value:x,onChange:N=>h(N.target.value),placeholder:"Filter by domain or client",className:"pl-9"})]}),i?e.jsx("div",{className:"text-sm text-muted-foreground py-12 text-center",children:"Loadingâ¦"}):I.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-12 text-center",children:"No domains yet â run the DNS probe to populate from shopifyStores."}):e.jsx("div",{className:"rounded-lg border border-border overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-medium",children:"Client / Domain"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium hidden sm:table-cell",children:"Policy"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium hidden lg:table-cell",children:"rua"}),e.jsx("th",{style:{textAlign:"right"},className:"px-3 py-2 font-medium",children:"7d pass rate"}),e.jsx("th",{style:{textAlign:"right"},className:"px-3 py-2 font-medium hidden md:table-cell",children:"7d msgs"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium hidden lg:table-cell",children:"Last report"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:I.map(N=>{var D,L,$,q,P;const S=Zz(((D=N.published)==null?void 0:D.p)??null),O=Jz(N.totals7d||{messages:0,passing:0}),R=(((L=N.totals7d)==null?void 0:L.messages)??0)>0,z=O>=95?"text-emerald-700":O>=80?"text-amber-700":"text-red-700";return e.jsxs("tr",{className:"border-t border-border hover:bg-muted/40",children:[e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:N.clientCompanyName||"â"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:N.domain})]}),e.jsx("td",{className:"px-3 py-2 hidden sm:table-cell",children:e.jsx("span",{className:`inline-block px-2 py-0.5 rounded text-xs font-medium ${S.cls}`,children:S.label})}),e.jsx("td",{className:"px-3 py-2 hidden lg:table-cell",children:($=N.published)!=null&&$.ruaIncludesOurs?e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-700 text-xs",children:[e.jsx(Xi,{className:"w-3 h-3"})," ours present"]}):(q=N.published)!=null&&q.found?e.jsxs("span",{className:"inline-flex items-center gap-1 text-amber-700 text-xs",children:[e.jsx(yg,{className:"w-3 h-3"})," not pointed at us"]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"no record"})}),e.jsx("td",{style:{textAlign:"right"},className:`px-3 py-2 font-mono ${R?z:"text-muted-foreground"}`,children:R?`${O}%`:"â"}),e.jsx("td",{style:{textAlign:"right"},className:"px-3 py-2 font-mono text-xs hidden md:table-cell",children:(((P=N.totals7d)==null?void 0:P.messages)??0).toLocaleString()}),e.jsx("td",{className:"px-3 py-2 text-xs text-muted-foreground hidden lg:table-cell",children:Xz(N.lastReportAt)}),e.jsx("td",{style:{textAlign:"right"},className:"px-3 py-2",children:e.jsx(ke,{variant:"ghost",size:"sm",onClick:()=>f(N.domain),children:"View"})})]},N.id)})})]})})]}),e.jsx(qs,{value:"rollout",className:"mt-4",children:e.jsx(tO,{rows:a})})]})]}),b&&e.jsx(Kz,{domain:b,status:a.find(N=>N.domain===b)||null,onClose:()=>f(null)}),j&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.5)"},onClick:()=>v(null),children:e.jsxs("div",{className:"bg-white rounded-lg max-w-3xl w-full flex flex-col border border-border",style:{maxHeight:"85vh",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.35), 0 10px 20px -5px rgba(0, 0, 0, 0.15)"},onClick:N=>N.stopPropagation(),children:[e.jsxs("div",{className:"border-b border-border px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold",children:"Digest preview"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[j.firedCount," would fire · ",j.suppressedCount," suppressed · ",j.resolvedCount," resolved"]})]}),e.jsx(ke,{variant:"ghost",size:"icon",onClick:()=>v(null),children:e.jsx(mt,{className:"w-4 h-4"})})]}),e.jsx("pre",{style:{fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.5,wordBreak:"break-word"},className:"overflow-auto p-4 whitespace-pre-wrap flex-1",children:j.text}),e.jsx("div",{className:"border-t border-border px-4 py-3 text-xs text-muted-foreground",children:"Preview only â no email sent. The scheduled job runs daily at 7am Toronto."})]})})]})}function Ui({icon:t,label:s,value:n,sub:r}){return e.jsxs("div",{className:"rounded-lg border border-border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[t,s]}),e.jsx("div",{className:"mt-1 text-2xl font-semibold",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground",children:r})]})}function tO({rows:t}){const s=l.useMemo(()=>t.filter(r=>{var a;return!((a=r.published)!=null&&a.ruaIncludesOurs)}),[t]),n=r=>{navigator.clipboard.writeText(r).then(()=>{ce.success("Copied")}).catch(a=>{console.error("Failed to copy text: ",a),ce.error("Failed to copy")})};return s.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground py-12 text-center",children:["Every watched domain has ",Jd," in
457its DMARC record. Nice."]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[s.length," domain",s.length===1?"":"s"," still need",s.length===1?"s":""," ",e.jsx("span",{className:"font-mono",children:Jd})," added to ",e.jsx("span",{className:"font-mono",children:"_dmarc"}),". Copy the suggested TXT value and publish it on each client's DNS host. The 24-hour DNS probe will re-validate automatically."]}),s.map(r=>{var i;const a=Qz((i=r.published)==null?void 0:i.rawRecord),o=a.mode==="append";return e.jsxs("div",{className:"rounded-lg border border-border bg-card p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:r.clientCompanyName||"â"}),e.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:["_dmarc.",r.domain]})]}),o?e.jsx("span",{className:"text-xs text-amber-700",children:"append to existing record"}):e.jsx("span",{className:"text-xs text-red-700",children:"publish new record"})]}),o&&e.jsxs("div",{className:"text-xs",children:[e.jsx("div",{className:"text-muted-foreground mb-0.5",children:"Current value:"}),e.jsx("code",{className:"block bg-muted/60 rounded px-2 py-1 break-all font-mono text-muted-foreground",children:a.previous})]}),e.jsxs("div",{className:"text-xs",children:[e.jsx("div",{className:"text-muted-foreground mb-0.5",children:o?"Replace with:":"Publish:"}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("code",{className:"flex-1 bg-muted rounded px-2 py-1.5 break-all font-mono",children:a.value}),e.jsxs(ke,{variant:"outline",size:"sm",onClick:()=>n(a.value),className:"flex-shrink-0",children:[e.jsx(Hr,{className:"w-3.5 h-3.5 mr-1"})," Copy"]})]})]})]},r.id)})]})}async function sO(t){const s=ys(),n=Ge(Re(s,"dmarcReports"),Ve("policyDomain","==",t),Nt("dateRangeEndTs","desc"),Tt(15));return(await Ze(n)).docs.map(a=>({id:a.id,...a.data()}))}const Hi="https://us-central1-bucky-app-355a3.cloudfunctions.net",nO=["category","comparison","problem","branded"],$h=[{code:"2840",label:"United States"},{code:"2124",label:"Canada"},{code:"2826",label:"United Kingdom"},{code:"2036",label:"Australia"},{code:"2554",label:"New Zealand"},{code:"2372",label:"Ireland"}],Bh={companyName:"",clientSlug:"",rootDomain:"",aliases:"",negativeAliases:"",locationCode:"2840",languageCode:"en",enabled:!0,activePromptSetVersion:"v1"};function rO(t){const s=t.map(r=>/^v(\d+)$/.exec(r)).filter(Boolean).map(r=>Number(r[1]));return`v${(s.length?Math.max(...s):0)+1}`}function aO({getToken:t,initialClientId:s,onChanged:n}){const r=l.useCallback(async()=>{const _=await t();return _?{Authorization:`Bearer ${_}`}:null},[t]),[a,o]=l.useState([]),[i,d]=l.useState(s||""),[m,p]=l.useState(""),[c,u]=l.useState(!1),x=l.useRef(null),[h,b]=l.useState(Bh),[f,g]=l.useState([]),[y,j]=l.useState(""),[v,T]=l.useState([]),[k,w]=l.useState("v1"),[I,A]=l.useState(!0),[E,C]=l.useState(""),[N,S]=l.useState(!1),[O,R]=l.useState(!1),[z,D]=l.useState(!1);l.useEffect(()=>{(async()=>{const _=await r();if(_)try{const B=await(await fetch(`${Hi}/listSaviClientRoster`,{headers:_})).json();o((B==null?void 0:B.clients)||[])}catch(G){ce.error(`Roster load failed: ${G}`)}})()},[r]);const L=a.find(_=>_.clientId===i)||null,$=l.useMemo(()=>{const _=m.trim().toLowerCase();return _?a.filter(G=>(G.companyName||"").toLowerCase().includes(_)||(G.name||"").toLowerCase().includes(_)):a},[a,m]);l.useEffect(()=>{if(!c)return;const _=G=>{x.current&&!x.current.contains(G.target)&&u(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[c]);const q=l.useCallback(async(_,G)=>{var Y,J,H;if(!_)return;const B=await r();if(B){S(!0);try{const Z=new URL(`${Hi}/getSaviClientConfig`);Z.searchParams.set("clientId",_),G&&Z.searchParams.set("version",G);const Q=await fetch(Z.toString(),{headers:B}),K=await Q.json();if(!Q.ok)throw new Error((K==null?void 0:K.error)||`HTTP ${Q.status}`);const X=a.find(pe=>pe.clientId===_),se=K.config;b(se?{companyName:se.companyName||"",clientSlug:se.clientSlug||"",rootDomain:se.rootDomain||"",aliases:(se.aliases||[]).join(` 458`),negativeAliases:(se.negativeAliases||[]).join(` 459`),locationCode:String(se.locationCode??2840),languageCode:se.languageCode||"en",enabled:!!se.enabled,activePromptSetVersion:se.activePromptSetVersion||"v1"}:{...Bh,companyName:(X==null?void 0:X.companyName)||(X==null?void 0:X.name)||"",rootDomain:((X==null?void 0:X.domains)||[]).find(pe=>!pe.includes("myshopify.com"))||((Y=X==null?void 0:X.domains)==null?void 0:Y[0])||"",aliases:X!=null&&X.companyName?X.companyName:""}),g(K.versions||[]),j(K.version||""),T((((J=K.promptSet)==null?void 0:J.prompts)||[]).map(pe=>({...pe}))),w((H=K.versions)!=null&&H.length?rO(K.versions):"v1")}catch(Z){ce.error(Z instanceof Error?Z.message:"Load failed")}finally{S(!1)}}},[r,a]);l.useEffect(()=>{i&&q(i)},[i,a.length]);const P=l.useCallback(async()=>
459{if(!i)return;if(!h.rootDomain.trim()){ce.error("Root domain is required");return}const _=await r();if(_){R(!0);try{const G=await fetch(`${Hi}/upsertSaviConfig`,{method:"POST",headers:{..._,"Content-Type":"application/json"},body:JSON.stringify({clientId:i,...h,locationCode:Number(h.locationCode)||2840})}),B=await G.json();if(!G.ok)throw new Error((B==null?void 0:B.error)||`HTTP ${G.status}`);ce.success("Config saved"),n==null||n()}catch(G){ce.error(G instanceof Error?G.message:"Save failed")}finally{R(!1)}}},[r,i,h,n]),U=l.useCallback(async()=>{if(!i)return;const _=v.filter(B=>B.prompt_text.trim());if(_.length===0){ce.error("Add at least one prompt");return}if(!k.trim()){ce.error("Version label required");return}const G=await r();if(G){D(!0);try{const B=await fetch(`${Hi}/saveSaviPromptSet`,{method:"POST",headers:{...G,"Content-Type":"application/json"},body:JSON.stringify({clientId:i,version:k.trim(),prompts:_,setActive:I,frozen:!0})}),Y=await B.json();if(!B.ok)throw new Error((Y==null?void 0:Y.error)||`HTTP ${B.status}`);ce.success(`Saved ${Y.promptCount} prompts as ${k}${I?" (now active)":""}`),await q(i,k.trim()),n==null||n()}catch(B){ce.error(B instanceof Error?B.message:"Save failed")}finally{D(!1)}}},[r,i,v,k,I,q,n]),V=(_,G,B)=>{T(Y=>Y.map((J,H)=>H===_?{...J,[G]:B}:J))},M=()=>{const _=`p${String(v.length+1).padStart(3,"0")}`;T(G=>[...G,{prompt_id:_,prompt_type:"category",prompt_text:""}])},F=_=>T(G=>G.filter((B,Y)=>Y!==_)),W=()=>{const _=E.split(` 460`).map(G=>G.trim()).filter(Boolean);_.length&&(T(G=>{const B=G.length,Y=_.map((J,H)=>({prompt_id:`p${String(B+H+1).padStart(3,"0")}`,prompt_type:"category",prompt_text:J.slice(0,500)}));return[...G,...Y]}),C(""))};return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(Jt,{className:"text-sm shrink-0",children:"Client"}),e.jsxs("div",{className:"relative w-80",ref:x,children:[L?e.jsxs("div",{className:"flex items-center justify-between bg-card border border-border rounded-lg px-3 py-2",children:[e.jsx("span",{className:"text-foreground",children:L.companyName||L.name}),e.jsx("button",{type:"button",onClick:()=>{d(""),p(""),u(!1)},className:"p-1 hover:bg-accent rounded",children:e.jsx(mt,{className:"w-4 h-4 text-muted-foreground"})})]}):e.jsxs("div",{className:"flex items-center bg-card border border-border rounded-lg focus-within:ring-2 focus-within:ring-primary",children:[e.jsx(Pt,{className:"ml-3 w-4 h-4 text-muted-foreground flex-shrink-0"}),e.jsx("input",{type:"text",value:m,onChange:_=>{p(_.target.value),u(!0)},onFocus:()=>u(!0),placeholder:a.length?"Search active clientsâ¦":"Loading clientsâ¦",className:"w-full pl-2 pr-3 py-2 bg-transparent text-foreground placeholder:text-muted-foreground focus:outline-none"})]}),c&&!L&&$.length>0&&e.jsx("div",{className:"absolute z-10 w-full mt-1 bg-card border border-border rounded-lg shadow-lg max-h-64 overflow-y-auto",children:$.map(_=>e.jsxs("button",{type:"button",onClick:()=>{d(_.clientId),p(""),u(!1)},className:"w-full px-3 py-2 text-left hover:bg-accent flex flex-col",children:[e.jsx("span",{className:"text-foreground text-sm truncate",children:_.companyName||_.name}),_.domains[0]&&e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:_.domains[0]})]},_.clientId))})]}),N&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Loadingâ¦"})]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"rounded-lg border border-border p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Client config"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ca,{checked:h.enabled,onCheckedChange:_=>b(G=>({...G,enabled:_}))}),e.jsx("span",{className:"text-sm",children:h.enabled?"Enabled (in monthly batch)":"Disabled"})]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsx(da,{label:"Company name",children:e.jsx(it,{value:h.companyName,onChange:_=>b(G=>({...G,companyName:_.target.value}))})}),e.jsx(da,{label:"Slug (report id)",children:e.jsx(it,{value:h.clientSlug,onChange:_=>b(G=>({...G,clientSlug:_.target.value})),placeholder:"auto from company name"})}),e.jsx(da,{label:"Root domain *",hint:"for citation matching, e.g. hillsdrygoods.com",children:e.jsx(it,{value:h.rootDomain,onChange:_=>b(G=>({...G,rootDomain:_.target.value}))})}),e.jsx(da,{label:"Location / Language",hint:"market for Google AI surfaces (C
460hatGPT & Gemini ignore it)",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(nn,{value:h.locationCode,onValueChange:_=>b(G=>({...G,locationCode:_})),children:[e.jsx(an,{className:"w-44",children:e.jsx(rn,{placeholder:"Country"})}),e.jsxs(on,{children:[$h.map(_=>e.jsx(cs,{value:_.code,children:_.label},_.code)),!$h.some(_=>_.code===h.locationCode)&&h.locationCode&&e.jsxs(cs,{value:h.locationCode,children:["Code ",h.locationCode]})]})]}),e.jsx(it,{className:"w-20",value:h.languageCode,onChange:_=>b(G=>({...G,languageCode:_.target.value}))})]})}),e.jsx(da,{label:"Brand aliases",hint:"one per line; matched case-insensitive, word-boundary",children:e.jsx(ds,{rows:3,value:h.aliases,onChange:_=>b(G=>({...G,aliases:_.target.value}))})}),e.jsx(da,{label:"Negative aliases",hint:"one per line; presence vetoes a mention (for common-word brands)",children:e.jsx(ds,{rows:3,value:h.negativeAliases,onChange:_=>b(G=>({...G,negativeAliases:_.target.value}))})})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3",children:[e.jsxs(ke,{onClick:P,disabled:O,children:[e.jsx(ml,{className:"w-4 h-4 mr-1"})," ",O?"Savingâ¦":"Save config"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Active prompt set: ",h.activePromptSetVersion]})]})]}),e.jsxs("section",{className:"rounded-lg border border-border p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Prompt set"}),f.length>0&&e.jsxs(nn,{value:y,onValueChange:_=>{j(_),q(i,_)},children:[e.jsx(an,{className:"w-28 h-8",children:e.jsx(rn,{placeholder:"version"})}),e.jsx(on,{children:f.map(_=>e.jsxs(cs,{value:_,children:[_,_===h.activePromptSetVersion?" â¢":""]},_))})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v.length," prompts"]})]}),e.jsxs(ke,{variant:"outline",size:"sm",onClick:M,children:[e.jsx(Ut,{className:"w-4 h-4 mr-1"})," Add prompt"]})]}),e.jsx("div",{className:"space-y-2",children:v.map((_,G)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground w-10 shrink-0",children:_.prompt_id}),e.jsxs(nn,{value:_.prompt_type,onValueChange:B=>V(G,"prompt_type",B),children:[e.jsx(an,{className:"w-32 h-9 shrink-0",children:e.jsx(rn,{})}),e.jsx(on,{children:nO.map(B=>e.jsx(cs,{value:B,children:B},B))})]}),e.jsx(it,{className:"flex-1",maxLength:500,value:_.prompt_text,onChange:B=>V(G,"prompt_text",B.target.value),placeholder:"buyer queryâ¦"}),e.jsx(ke,{variant:"ghost",size:"sm",onClick:()=>F(G),children:e.jsx(zs,{className:"w-4 h-4 text-muted-foreground"})})]},G))}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Jt,{className:"text-xs text-muted-foreground",children:"Bulk add (one prompt per line)"}),e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(ds,{rows:2,value:E,onChange:_=>C(_.target.value),placeholder:"paste prompts, one per line"}),e.jsxs(ke,{variant:"outline",onClick:W,className:"shrink-0",children:[e.jsx(pl,{className:"w-4 h-4 mr-1"})," Append"]})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-3 flex-wrap border-t border-border pt-4",children:[e.jsx(Jt,{className:"text-sm",children:"Save as version"}),e.jsx(it,{className:"w-24",value:k,onChange:_=>w(_.target.value)}),e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ca,{checked:I,onCheckedChange:A}),"Make active"]}),e.jsxs(ke,{onClick:U,disabled:z,children:[e.jsx(ml,{className:"w-4 h-4 mr-1"})," ",z?"Savingâ¦":"Save prompt set"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Bump the version (d
460on't overwrite) so trend lines stay honest."})]})]})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Select a client to configure its aliases and prompt set."})]})}function da({label:t,hint:s,children:n}){return e.jsxs("div",{children:[e.jsx(Jt,{className:"text-sm",children:t}),s&&e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:s}),e.jsx("div",{className:s?"":"mt-1",children:n})]})}const qi="https://us-central1-bucky-app-355a3.cloudfunctions.net",oO=["chatgpt","gemini","ai_overview","ai_mode"],iO={chatgpt:"ChatGPT",gemini:"Gemini",ai_overview:"Google AI Overview",ai_mode:"Google AI Mode"},lO={Low:"bg-red-100 text-red-700",Building:"bg-amber-100 text-amber-700",Strong:"bg-emerald-100 text-emerald-700",Leading:"bg-sky-100 text-sky-700"},cO={running:"bg-sky-100 text-sky-700",complete:"bg-emerald-100 text-emerald-700",complete_with_failures:"bg-amber-100 text-amber-700"},dO={running:"Running",complete:"Complete",complete_with_failures:"Complete with failures"},io=t=>`${Math.round(t*100)}%`;function uO({onBack:t,onLogoClick:s}){const{getToken:n}=pt(),r=l.useCallback(async()=>{const N=await n();return N?{Authorization:`Bearer ${N}`}:null},[n]),[a,o]=l.useState([]),[i,d]=l.useState(""),[m,p]=l.useState([]),[c,u]=l.useState(""),[x,h]=l.useState(null),[b,f]=l.useState(!1),[g,y]=l.useState(!1),[j,v]=l.useState(null),[T,k]=l.useState(!1),w=l.useCallback(async()=>{const N=await r();N&&fetch(`${qi}/listSaviClients`,{headers:N}).then(S=>S.json()).then(S=>{S!=null&&S.clients&&(o(S.clients),d(O=>{var R;return O||(((R=S.clients[0])==null?void 0:R.clientId)??"")})),v((S==null?void 0:S.latestBatch)??null)}).catch(S=>ce.error(`Failed to load clients: ${S}`))},[r]);l.useEffect(()=>{w()},[w]);const I=l.useCallback(async(N,S)=>{if(!N)return;const O=await r();if(O){f(!0);try{const R=new URL(`${qi}/getSaviRollup`);R.searchParams.set("clientId",N),S&&R.searchParams.set("month",S);const z=await fetch(R.toString(),{headers:O}),D=await z.json();if(!z.ok)throw new Error((D==null?void 0:D.error)||`HTTP ${z.status}`);p(D.months||[]),u(D.month||""),h(D.rollup||null)}catch(R){ce.error(R instanceof Error?R.message:"Failed to load rollup"),h(null)}finally{f(!1)}}},[r]);l.useEffect(()=>{i&&I(i)},[i,I]);const A=l.useCallback(async()=>{var S,O;if(!i)return;const N=await r();if(N){y(!0);try{const R=new URL(`${qi}/adminTriggerSaviRun`);R.searchParams.set("clientId",i),c&&R.searchParams.set("month",c);const z=await fetch(R.toString(),{method:"POST",headers:N}),D=await z.json();if(!z.ok)throw new Error((D==null?void 0:D.error)||`HTTP ${z.status}`);const L=D.summary;(S=L==null?void 0:L.errors)!=null&&S.length?ce.warning(`Run finished with ${L.errors.length} surface error(s)`):ce.success(`Run complete â SAVI ${((O=L==null?void 0:L.rollup)==null?void 0:O.SAVI)??"â"}`);try{await I(i,c)}catch($){ce.error($ instanceof Error?$.message:"Failed to load rollup data")}}catch(R){ce.error(R instanceof Error?R.message:"Run failed")}finally{y(!1)}}},[r,i,c,I]),E=l.useCallback(async()=>{const N=await r();if(N){k(!0);try{const S=new URL(`${qi}/adminTriggerSaviRun`);c&&S.searchParams.set("month",c);const O=await fetch(S.toString(),{method:"POST",headers:N}),R=await O.json();if(!O.ok)throw new Error((R==null?void 0:R.error)||`HTTP ${O.status}`);ce.success(`Queued ${R.enqueued} of ${R.total} clients (batch ${R.batchId})`),w()}catch(S){ce.error(S instanceof Error?S.message:"Dispatch failed")}finally{k(!1)}}},[r,c,w]),C=a.find(N=>N.clientId===i)||null;return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(Xe,{onLogoClick:s}),e.jsx(Oa,{position:"top-center",richColors:!0}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsxs(ke,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(dt,{className:"w-4 h-4 mr-1"})," Back"]}),e.jsx("h1",{className:"text-2xl font-semibold",children:"SAVI â AI Visibility Index"})]}),e.jsxs(nc,{defaultValue:"dashboard",children:[e.jsxs(rc,{className:"mb-6",children:[e.jsx(Hs,{value:"dashboard",children:"Dashboard"}),e.jsx(Hs,{value:"configure",children:"Configure"})]}),e.jsxs(qs,{value:"dashboard",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap items-center mb-6",children:[e.jsxs(nn,{value:i,onValueChange:d,children:[e.jsx(an,{className:"w-56",children:e.jsx(rn,{placeholder:"Select client"})}),e.jsx(on,{children:a.map(N=>e.jsxs(cs,{value:N.clientId,children:[N.companyName||N.clientSlug,N.enabled?"":" (disabled)"]},N.clientId))})]}),m.length>0&&e.jsxs(nn,{value:c,onValueChange:N=>I(i,N),children:[e.jsx(an,{className:"w-32",children:e.jsx(rn,{placeholder:"Month"})}),e.jsx(on,{children:m.map(N=>e.jsx(cs,{value:N,children:N},N))})]}),e.jsxs(ke,{variant:"outline",size:"sm",onClick:()=>I(i,c),disabled:b,children:[e.jsx(yt,{className:`w-4 h-4 mr-1 ${b?"animate-spin":""}`})," Refresh"]}),e.jsxs(ke,{size:"sm",onClick:A,disabled:g||!i,children:[e.jsx(In,{className:`w-4 h-4 mr-1 ${g?"animate-pulse":""}`}),g?"Runningâ¦":"Run now"]}),e.jsxs(ke,{variant:"outline",size:"sm",onClick:E,disabled:T,children:[e.jsx(Zw,{className:"w-4 h-4 mr-1"}),T?"Queuingâ¦":"Run all clients"]})]}),j&&e.jsxs("div",{className:"rounded-lg border border-border bg-card p-4 mb-6 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("span",{className:"font-medium",children:["Last batch · ",j.month]}),e.jsx(Wt,{className:cO[j.status],children:dO[j.status]}),e.jsxs("span",{className:"text-muted-foreground",children:[j.counts.done," done · ",j.counts.queued+j.counts.retrying," pending",j.counts.failed+j.counts.skipped>0?` · ${j.counts.failed+j.counts.skipped} failed/skipped`:""," ","of ",j.total," · ",j.trigger,j.requestedBy?` by ${j.requestedBy}`:""]}),e.jsxs(ke,{variant:"ghost",size:"sm",className:"ml-auto",onClick:w,children:[e.jsx(yt,{className:"w-3.5 h-3.5 mr-1"})," Refresh"]})]}),Object.entries(j.clients).filter(([,N])=>N.status==="failed"||N.status==="skipped"||N.status==="retrying").map(([N,S])=>e.jsxs("div",{className:"mt-2 text-xs text-amber-700 flex items-start gap-1",children:[e.jsx(Dt,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),e.jsxs("span",{children:[e.jsx("strong",{children:S.clientSlug||N})," ",S.status,S.attempts>1?` (attempt ${S.attempts})`:"",S.error?` â ${S.error}`:""]})]},N))]}),C&&e.jsxs("div",{className:"text-sm text-muted-foreground mb-4",children:[C.rootDomain," · prompt set ",C.activePromptSetVersion]}),b?e.jsx("div",{className:"text-sm text-muted-foreground py-12 text-center",children:"Loadingâ¦"}):x?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-lg border border-border bg-card p-6 mb-6 flex items-center gap-6 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-5xl font-semibold tabular-nums",children:x.SAVI}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["SAVI · ",x.month," · R=",x.R]})]}),e.jsx(Wt,{className:lO[x.band],children:x.band}),x.lowConfidence&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-700",children:[e.jsx(Dt,{className:"w-3.5 h-3.5"})," Low confidence (small sample)"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 mb-6",children:[e.jsx(Ir,{label:"Mention Rate",value:io(x.MR),sub:"brand named in answers"}),e.jsx(Ir,{label:"Citation Rate",value:io(x.CR),sub:"client site cited as source"}),e.jsx(Ir,{label:"Surface Coverage",value:io(x.SC),sub:"surfaces with a mention"})]}),e.jsx("div",{className:"rounded-lg border border-border overflow-x-auto mb-6",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-medium",children:"Surface"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium",children:"Mention rate"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium",children:"Citation rate"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium",children:"Answered cells"})]})}),e.jsx("tbody",{children:oO.map(N=>{const S=x.by_surface[N];return e.jsxs("tr",{className:"border-t border-border hover:bg-muted/40",children:[e.jsx("td",{className:"px-3 py-2 font-medium",children:iO[N]}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:S?io(S.mention_rate):"â"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:S?io(S.
460citation_rate):"â"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:S?S.answered_cells:0})]},N)})})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Ir,{label:"Mentions",value:String(x.counts.mentions)}),e.jsx(Ir,{label:"Citations",value:String(x.counts.citations)}),e.jsx(Ir,{label:"Cited pages",value:String(x.counts.cited_pages)}),e.jsx(Ir,{label:"Answered cells",value:`${x.counts.answered_cells}/${x.counts.total_cells}`})]})]}):e.jsxs("div",{className:"text-sm text-muted-foreground py-12 text-center",children:["No rollup yet for this client/month. Click ",e.jsx("strong",{children:"Run now"})," to generate one."]})]}),e.jsx(qs,{value:"configure",children:e.jsx(aO,{getToken:n,initialClientId:i,onChanged:()=>{w(),i&&I(i,c)}})})]})]})]})}function Ir({label:t,value:s,sub:n}){return e.jsxs("div",{className:"rounded-lg border border-border bg-card p-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:t}),e.jsx("div",{className:"text-2xl font-semibold tabular-nums mt-1",children:s}),n&&e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:n})]})}const mO=15;function pO(){const{active:t,since:s,suppressCount:n}=D0(),[r,a]=l.useState(()=>Date.now());if(l.useEffect(()=>{if(!t)return;const i=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(i)},[t]),!t||n>0)return null;const o=Math.max(0,mO-Math.floor((r-s)/1e3));return e.jsx("div",{className:"fixed z-[100] pointer-events-none",style:{bottom:16,left:16},children:e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border bg-card shadow-lg px-4 py-3 max-w-xs",children:[e.jsx("div",{className:"animate-spin shrink-0",style:{animationDuration:"2s"},children:e.jsx("img",{src:ks,alt:"",className:"w-6 h-6"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-foreground",children:"Waking up the minions"}),e.jsx("div",{className:"text-xs text-muted-foreground",style:{fontVariantNumeric:"tabular-nums"},children:o>0?`Warming a server â about ${o}sâ¦`:"Any second nowâ¦"})]})]})})}const xO=[{key:"tickets",title:"Tickets",desc:"All support tickets",icon:_r,handler:"onTickets"},{key:"projects",title:"Projects",desc:"Client projects",icon:Vw,handler:"onProjects"},{key:"clients",title:"Clients",desc:"Client accounts",icon:Hl,handler:"onClients"},{key:"contacts",title:"Contacts",desc:"People & CRM contacts",icon:$w,handler:"onContacts"},{key:"companies",title:"Companies",desc:"All companies & prospects",icon:eg,handler:"onCompanies"},{key:"sequences",title:"Sequences",desc:"Outreach sequences & campaigns",icon:An,handler:"onSequences"},{key:"deals",title:"Deals",desc:"Sales pipeline & deal tracking",icon:gr,handler:"onDeals"},{key:"stores",title:"Shopify Stores",desc:"Connected stores",icon:Nu,handler:"onStores"},{key:"meetings",title:"Meetings",desc:"Meeting notes & recordings",icon:Lw,handler:"onMeetings"},{key:"shopRepos",title:"Shop Repos",desc:"GitHub repos per shop",icon:rg,handler:"onShopRepos"},{key:"recurringTemplates",title:"Recurring Templates",desc:"Scheduled ticket generators",icon:yt,handler:"onRecurringTemplates"},{key:"projectMappings",title:"Project Mappings",desc:"Channel-to-credit linking",icon:cg,handler:"onProjectMappings"}];function hO({onBack:t,onLogoClick:s,onTickets:n,onProjects:r,onClients:a,onStores:o,onMeetings:i,onShopRepos:d,onRecurringTemplates:m,onProjectMappings:p,onContacts:c,onCompanies:u,onSequences:x,onDeals:h}){const b={onTickets:n,onProjects:r,onClients:a,onStores:o,onMeetings:i,onShopRepos:d,onRecurringTemplates:m,onProjectMappings:p,onContacts:c,onCompanies:u,onSequences:x,onDeals:h};return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-md mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:20,height:20}})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Databases"}),e.jsx("p",{className:"text-muted-foreground",children:"Browse and manage all data"})]})]}),e.jsx("div",{className:"space-y-3",children:xO.map(f=>{const g=f.icon;return e.jsxs("button",{onClick:b[f.handler],className:"w-full bg-card border border-border rounded-lg p-4 flex items-center gap-3 hover:bg-accent transition-colors active:scale-[0.98]",style:{borderRadius:"var(--radius-md)",borderWidth:"var(--border-width-default)"},children:[e.jsx("div",{className:"flex-shrink-0 bg-primary/10 rounded-lg flex items-center justify-center",style:{width:48,height:48,borderRadius:"var(--radius-sm)"},children:e.jsx(g,{className:"text-primary",style:{width:24,height:24}})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:f.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:f.desc})]})]},f.key)})})]})]})}const fO={Backlog:"bg-gray-100 text-gray-700","To Do":"bg-blue-100 text-blue-700","In Progress":"bg-purple-100 text-purple-700","In Review":"bg-
460amber-100 text-amber-700","Client Approval":"bg-cyan-100 text-cyan-700","Awaiting Approval":"bg-sky-100 text-sky-700","In Queue":"bg-indigo-100 text-indigo-700","Changes Requested":"bg-orange-100 text-orange-700",Parked:"bg-muted text-muted-foreground",Complete:"bg-green-100 text-green-700",Done:"bg-green-100 text-green-700",Deferred:"bg-yellow-100 text-yellow-700",Merge:"bg-teal-100 text-teal-700","Merged Away":"bg-slate-100 text-slate-600",Cancelled:"bg-gray-100 text-gray-400"};function gO({onBack:t,onLogoClick:s,initialTicketDisplayId:n}){const{rows:r,loading:a,error:o,updateRow:i,deleteRow:d}=Xt({collectionName:"tickets",orderByField:"updatedAt",orderDirection:"desc"}),[m,p]=l.useState(""),[c,u]=l.useState("all"),[x,h]=l.useState(null),b=l.useMemo(()=>{let N=r;return c!=="all"&&(N=N.filter(S=>S.status===c)),N=N.filter(Js(m,S=>[S.name,S.displayId,S.clientName,S.projectName])),N},[r,c,m]),f=l.useMemo(()=>{const N={all:r.length};for(const S of hl)N[S]=r.filter(O=>O.status===S).length;return N},[r]),g=[{key:"all",label:"All",count:f.all},...hl.map(N=>({key:N,label:Wr(N),count:f[N]||0}))],[y,j]=l.useState(null);l.useEffect(()=>{if(!y)return;const N=r.find(S=>S.id===y);N&&(h(N),j(null))},[r,y]);const[v,T]=l.useState(!1);l.useEffect(()=>{if(v||!n||r.length===0)return;const N=r.find(S=>S.displayId===n);N&&(h(N),u("all"),T(!0))},[r,n,v]);const k=l.useCallback(async()=>{const N=ut(ge,"counters","tickets"),S=await Dl(ge,async z=>{const D=await z.get(N),$=(D.exists()?D.data().lastNumber:0)+1;return z.set(N,{lastNumber:$},{merge:!0}),$}),O=`TICK-${S}`,R=await Ma(Re(ge,"tickets"),{name:"New Ticket",displayId:O,ticketNumber:S,status:"Backlog",projectId:null,projectName:null,clientId:null,clientName:null,shopifyStoreId:null,shopifyStoreUrl:null,creditsMin:null,creditsMax:null,pageUrl:null,shopifyThemeId:null,videoReviewUrl:null,internalTimeEstimate:null,internalTimeInMins:null,ticketComplexity:null,dueDate:null,rushOrder:!1,qaApproved:!1,content:null,notionPageId:"",createdAt:ss(),updatedAt:ss()});u("all"),j(R.id)},[]),w=l.useMemo(()=>x?b.findIndex(N=>N.id===x.id):-1,[b,x]),I=w>0,A=w>=0&&w<b.length-1,E=l.useCallback(()=>{I&&h(b[w-1])},[b,w,I]),C=l.useCallback(()=>{A&&h(b[w+1])},[b,w,A]);return e.jsxs(hn,{title:"Tickets",count:b.length,loading:a,error:o,onCreate:k,searchValue:m,onSearchChange:p,onBack:t,onLogoClick:s,tabs:g,activeTab:c,onTabChange:N=>u(N),children:[e.jsxs("div",{className:"space-y-2",children:[b.map(N=>{var S;return e.jsx("button",{onClick:()=>h(N),className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:N.displayId}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${fO[N.status]||"bg-gray-100 text-gray-600"}`,children:Wr(N.status)}),N.rushOrder&&e.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:4,backgroundColor:"#fee2e2",color:"#b91c1c",fontWeight:500},children:"Rush"}),((S=N.mergeInfo)==null?void 0:S.isMerged)&&e.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:4,backgroundColor:"#f3e8ff",color:"#7c3aed",fontWeight:500},children:"Merged"}),N.archivedByMerge&&e.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:4,backgroundColor:"#fef3c7",color:"#92400e",fontWeight:500},children:"Merged Away"})]}),e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:N.name}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[N.clientName&&e.jsx("span",{children:N.clientName}),N.projectName&&e.jsx("span",{children:N.projectName}),N.creditsMax!=null&&e.jsxs("span",{children:[N.creditsMax," cr"]})]})]}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:nt(N.updatedAt)})]})},N.id)}),b.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No tickets found"})]}),x&&e.jsx(sy,{ticket:x,rows:r,updateRow:i,deleteRow:d,onClose:()=>h(null),onSelect:h,onPrev:E,onNext:C,hasPrev:I,hasNext:A,positionLabel:w>=0?`${w+1}/${b.length}`:void 0})]})}const bO=["Backlog","In Progress","Complete","On Hold","Cancelled"],yO=["","Standard","Recurring","One-Time","Retainer","Ongoing Support","Marketing"],jO=["",...Io],vO=["","Ready","Blocked","Waiting on Client","In Review"],wO={Backlog:"bg-gray-100 text-gray-700","In Progress":"bg-purple-100 text-purple-700",Complete:"bg-green-100 text-green-700","On Hold":"bg-amber-100 text-amber-700",Cancelled:"bg-gray-100 text-gray-400"};function NO({onBack:t,onLogoClick:s,initialProjectId:n}){var F,W;const{rows:r,loading:a,error:o,updateRow:i,deleteRow:d}
460=Xt({collectionName:"clientProjects",orderByField:"updatedAt",orderDirection:"desc"}),{rows:m}=Xt({collectionName:"clients",orderByField:"name",orderDirection:"asc"}),p=l.useMemo(()=>m.map(_=>({id:_.id,label:_.name})),[m]),{rows:c}=Xt({collectionName:"shopifyStores",orderByField:"name",orderDirection:"asc"}),u=l.useMemo(()=>c.map(_=>({id:_.id,label:_.name||_.myshopifyUrl})),[c]),[x,h]=l.useState(""),[b,f]=l.useState("active"),[g,y]=l.useState(null),[j,v]=l.useState(null),[T,k]=l.useState(""),w=l.useCallback(async _=>{g&&(await i(g.id,{shopifyStoreId:_.id}),y({...g,shopifyStoreId:_.id}))},[g,i]),I=l.useCallback(async _=>{g&&(await i(g.id,{clientId:_.id,clientName:_.label}),y({...g,clientId:_.id,clientName:_.label}))},[g,i]),A=l.useMemo(()=>{let _=r;return b==="active"?_=_.filter(G=>["Backlog","In Progress","On Hold"].includes(G.status)):b==="complete"&&(_=_.filter(G=>["Complete","Cancelled"].includes(G.status))),_=_.filter(Js(x,G=>[G.name,G.displayId,G.clientName])),_},[r,b,x]),E=l.useMemo(()=>({active:r.filter(_=>["Backlog","In Progress","On Hold"].includes(_.status)).length,complete:r.filter(_=>["Complete","Cancelled"].includes(_.status)).length,all:r.length}),[r]),C=[{key:"active",label:"Active",count:E.active},{key:"complete",label:"Completed",count:E.complete},{key:"all",label:"All",count:E.all}],N=(_,G)=>{v(_),k(G)},S=l.useCallback(async()=>{if(!g||!j)return;const G=["estTimeInMins","priority"].includes(j)?T===""?null:Number(T):T;await i(g.id,{[j]:G}),y({...g,[j]:G}),v(null)},[g,j,T,i]),O=l.useCallback(async(_,G)=>{if(!g)return;const Y=["timelineStart","timelineEnd","launchDate"].includes(_)?G?new Date(G):null:G;await i(g.id,{[_]:Y}),y({...g,[_]:Y})},[g,i]),[R,z]=l.useState(null);ee.useEffect(()=>{if(!R)return;const _=r.find(G=>G.id===R);_&&(y(_),z(null))},[r,R]);const[D,L]=l.useState(!1);ee.useEffect(()=>{if(D||!n||r.length===0)return;const _=r.find(G=>G.id===n);_&&(y(_),f("all"),L(!0))},[r,n,D]);const $=l.useCallback(async()=>{const _=ut(ge,"counters","projects"),G=await Dl(ge,async Y=>{const J=await Y.get(_),Z=(J.exists()?J.data().lastNumber:0)+1;return Y.set(_,{lastNumber:Z},{merge:!0}),Z}),B=await Ma(Re(ge,"clientProjects"),{name:"New Project",displayId:`PROJ-${G}`,status:"Backlog",subStatus:null,projectType:null,clientId:null,clientName:null,department:null,estTimeInMins:0,timelineStart:null,timelineEnd:null,launchDate:null,priority:null,shopifyStoreId:null,hubspotDealId:null,qaReviewUrl:null,notionPageId:"",createdAt:ss(),updatedAt:ss()});f("all"),z(B.id)},[]),[q,P]=l.useState([]),[U,V]=l.useState(!1);l.useEffect(()=>{if(!g){P([]);return}V(!0);const _=Ge(Re(ge,"tickets"),Ve("projectId","==",g.id),Nt("ticketNumber","desc"));return qt(_,B=>{P(B.docs.map(Y=>({id:Y.id,...Y.data()}))),V(!1)},()=>V(!1))},[g==null?void 0:g.id]);const M={editField:j,editValue:T,onEdit:N,onSave:S,onEditValueChange:k};return e.jsxs(hn,{title:"Projects",count:A.length,loading:a,error:o,onCreate:$,searchValue:x,onSearchChange:h,onBack:t,onLogoClick:s,tabs:C,activeTab:b,onTabChange:_=>f(_),children:[e.jsxs("div",{className:"space-y-2",children:[A.map(_=>e.jsx("button",{onClick:()=>y(_),className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:_.displayId}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${wO[_.status]||"bg-gray-100 text-gray-600"}`,children:_.status})]}),e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:_.name}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[_.clientName&&e.jsx("span",{children:_.clientName}),_.projectType&&e.jsx("span",{children:_.projectType}),_.department&&e.jsx("span",{children:_.department})]})]}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:nt(_.updatedAt)})]})},_.id)),A.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No projects found"})]}),g&&e.jsxs(Cs,{title:g.name,subtitle:g.displayId,onClose:()=>{y(null),v(null)},footer:e.jsx(nr,{onDelete:async()=>{await d(g.id),y(null)}}),children:[e.jsx(De,{title:"Details"}),e.jsx(oe,{label:"ID",value:g.displayId||"(not assigned)",field:"",...M,readOnly:!0}),e.jsx(oe,{label:"Name",value:g.name,field:"name",...M}),e.jsx(oe,{label:"Status",value:g.status,field:"status",...M,options:bO,onDirectSave:O}),e.jsx(oe,{label:"Sub-Status",value:g.subStatus||"",field:"subStatus",...M,options:vO,onDirectSave:O}),e.jsx(oe,{label:"Project Type",value:g.projectType||"",field:"projectType",...M,options:yO,onDirectSave:O}),e.jsx(oe,{label:"Department",value:g.department||"",field:"department",...M,options:jO,onDirectSave:O}),e.jsx(De,{title:"Client & Store"}),e.jsx(oe,{label:"Client",value:g.clientName||"",field:"clientName",...M,lookupItems:p,onLookupSelect:I}),e.jsx(oe,{label:"Shopify Store",value:((F=c.find(_=>_.id===g.shopifyStoreId))==null?void 0:F.name)||((W=c.find(_=>_.id===g.shopifyStoreId))==null?void 0:W.myshopifyUrl)||"",field:"shopifyStoreId",...M,lookupItems:u,onLookupSelect:w}),e.jsx(De,{title:"Dates"}),e.jsx(oe,{label:"Timeline Start",value:el(g.timelineStart),field:"timelineStart",...M,date:!0,onDirectSave:O}),e.jsx(oe,{label:"Timeline End",value:el(g.timelineEnd),field:"timelineEnd",...M,date:!0,onDirectSave:O}),e.jsx(oe,{label:"Launch Date",value:el(g.launchDate),field:"launchDate",...M,date:!0,onDirectSave:O}),e.jsx(De,{title:"Metrics"}),e.jsx(oe,{label:"Est. Time (mins)",value:g.estTimeInMins?String(g.estTimeInMins):"",field:"estTimeInMins",...M,numeric:!0}),e.jsx(oe,{label:"Priority",value:g.priority!=null?String(g.priority):"",field:"priority",...M,numeric:!0}),e.jsx(De,{title:"Links"}
460),e.jsx(oe,{label:"HubSpot Deal ID",value:g.hubspotDealId||"",field:"hubspotDealId",...M}),e.jsx(oe,{label:"QA Review URL",value:g.qaReviewUrl||"",field:"qaReviewUrl",...M}),e.jsx(De,{title:`Tickets (${q.length})`}),U?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading tickets..."}):q.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No tickets for this project"}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:q.map(_=>e.jsx("div",{className:"bg-background border border-border",style:{padding:"8px 12px",borderRadius:8},children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:2},children:[e.jsx("span",{className:"text-muted-foreground",style:{fontSize:11,fontFamily:"monospace"},children:_.displayId}),e.jsx("span",{style:{fontSize:11,padding:"1px 6px",borderRadius:9999,fontWeight:500,backgroundColor:_.status==="Complete"||_.status==="Done"?"#dcfce7":_.status==="In Progress"?"#f3e8ff":_.status==="In Review"?"#fef3c7":_.status==="Client Approval"?"#cffafe":"#f3f4f6",color:_.status==="Complete"||_.status==="Done"?"#15803d":_.status==="In Progress"?"#7e22ce":_.status==="In Review"?"#b45309":_.status==="Client Approval"?"#0e7490":"#374151"},children:_.status})]}),e.jsx("p",{className:"text-foreground",style:{fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_.name})]}),_.creditsMax!=null&&e.jsxs("span",{className:"text-muted-foreground",style:{fontSize:11,flexShrink:0},children:[_.creditsMax," cr"]})]})},_.id))}),e.jsx(De,{title:"Metadata"}),e.jsx(oe,{label:"Created",value:nt(g.createdAt),field:"",...M,readOnly:!0}),e.jsx(oe,{label:"Updated",value:nt(g.updatedAt),field:"",...M,readOnly:!0})]})]})}const kO={display:"flex",justifyContent:"space-between",fontSize:12,padding:"2px 0"};function dr({label:t,n:s}){return s===0?null:e.jsxs("div",{style:kO,children:[e.jsx("span",{style:{color:"#9ca3af"},children:t}),e.jsx("span",{style:{color:"#e5e7eb",fontFamily:"ui-monospace, monospace"},children:s})]})}function SO({clientId:t,onDeleted:s}){const[n,r]=l.useState(!1),[a,o]=l.useState(null),[i,d]=l.useState(null),m=async()=>{r(!0),d(null);try{const c=await re("deleteClientPreserveHistory",{clientId:t,dryRun:!0});o(c)}catch(c){d((c==null?void 0:c.message)||"Failed to load impact")}finally{r(!1)}},p=async()=>{r(!0),d(null);try{await re("deleteClientPreserveHistory",{clientId:t,dryRun:!1}),o(null),s()}catch(c){d((c==null?void 0:c.message)||"Failed to delete client")}finally{r(!1)}};if(a){const{counts:c,blockedByActiveDeals:u,activeDealNames:x}=a,h=c.contacts+c.stores+c.projects+c.tickets+c.meetings+c.communications+c.sequenceEnrollments+c.closedDeals>0;return e.jsxs("div",{className:"border-t border-border",style:{padding:"12px 0",marginTop:12,display:"flex",flexDirection:"column",gap:10},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,color:"#f59e0b",fontSize:13,fontWeight:500},children:[e.jsx(Dt,{style:{width:14,height:14}}),'Delete "',a.companyName||a.displayId,'"?']}),u?e.jsxs("div",{style:{fontSize:12,color:"#fca5a5",lineHeight:1.5},children:["This client has ",e.jsxs("strong",{children:[c.activeDeals," active deal(s)"]}),":",e.jsx("ul",{style:{margin:"4px 0 4px 16px",padding:0},children:x.map(b=>e.jsx("li",{children:b},b))}),"Close or lose these deals before deleting the client."]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{fontSize:12,color:"#9ca3af",lineHeight:1.5},children:["The company profile will be archived (contacts keep their history).",h?" These records will be unlinked but preserved:":" No linked records found."]}),h&&e.jsxs("div",{style:{background:"rgba(120,120,120,0.08)",borderRadius:6,padding:10},children:[e.jsx(dr,{label:"Contacts",n:c.contacts}),e.jsx(dr,{label:"Shopify stores",n:c.stores}),e.jsx(dr,{label:"Projects",n:c.projects}),e.jsx(dr,{label:"Tickets",n:c.tickets}),e.jsx(dr,{label:"Meetings",n:c.meetings}),e.jsx(dr,{label:"Communications",n:c.communications}),e.jsx(dr,{label:"Sequence enrollments",n:c.sequenceEnrollments}),e.jsx(dr,{label:"Closed deals",n:c.closedDeals})]})]}),i&&e.jsx("div",{style:{fontSize:12,color:"#fca5a5"},children:i}),e.jsxs("div",{style:{display:"flex",gap:8},children:[!u&&e.jsx("button",{onClick:p,disabled:n,style:{padding:"6px 14px",borderRadius:8,fontSize:13,fontWeight:500,backgroundColor:"#ef4444",color:"white",opacity:n?.6:1,border:"none"},children:n?"Deleting...":"Yes, delete"}),e.jsx("button",{onClick:()=>{o(null),d(null)},disabled:n,className:"text-muted-foreground text-sm hover:text-foreground",style:{padding:"6px 14px",background:"transparent",border:"none"},children:"Cancel"})]})]})}return e.jsxs("div",{className:"border-t border-border",style:{padding:"12px 0",marginTop:12},children:[e.jsxs("button",{onClick:m,disabled:n,style:{display:"flex",alignItems:"center",gap:6,fontSize:13,color:"#ef4444",opacity:n?.6:1,background:"transparent",border:"none"},children:[e.jsx(zs,{style:{width:14,height:14}})," ",n?"Loading impact...":"Delete Client"]}),i&&e.jsx("div",{style:{fontSize:12,color:"#fca5a5",marginTop:6},children:i})]})}function Zd({label:t,items:s,emptyText:n,placeholder:r,normalize:a,validate:o,allowEdit:i,onSave:d}){const[m,p]=l.useState(""),[c,u]=l.useState(null),[x,h]=l.useState(null),[b,f]=l.useState(""),g=s||[],y=I=>a?a(I):I.trim().toLowerCase(),j=()=>{const I=y(m);if(!I||g.includes(I)){p(""),u(null);return}const A=(o==null?void 0:o(I,g))??null;if(A){u(A);return}d([...g,I]),p(""),u(null)},v=I=>{h(I),f(g[I]),u(null)},T=()=>{h(null),f(""),u(null)},k=()=>
460{if(x===null)return;const I=y(b),A=g.filter((C,N)=>N!==x);if(!I){d(A),T();return}if(I===g[x]){T();return}if(A.includes(I)){u("Already in the list");return}const E=(o==null?void 0:o(I,A))??null;if(E){u(E);return}d(g.map((C,N)=>N===x?I:C)),T()},w=I=>{d(g.filter((A,E)=>E!==I)),x===I&&T()};return e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:t}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[g.length===0&&e.jsx("div",{className:"text-muted-foreground text-xs italic",children:n||"none"}),g.map((I,A)=>x===A?e.jsx("input",{type:"text",autoFocus:!0,value:b,onChange:E=>f(E.target.value),onBlur:k,onKeyDown:E=>{E.key==="Enter"?(E.preventDefault(),k()):E.key==="Escape"&&(E.preventDefault(),T())},className:"bg-background border border-border text-foreground focus:outline-none focus:border-primary",style:{fontSize:12,padding:"2px 8px",borderRadius:9999,minWidth:180}},`edit-${A}`):e.jsxs("span",{className:"text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full inline-flex items-center gap-1",children:[i?e.jsx("button",{onClick:()=>v(A),title:"Click to edit",className:"hover:text-foreground transition-colors",style:{background:"none",border:"none",padding:0,font:"inherit",color:"inherit",cursor:"pointer"},children:I}):I,e.jsx("button",{onClick:()=>w(A),"aria-label":`Remove ${I}`,className:"hover:text-foreground transition-colors",style:{lineHeight:1},children:"Ã"})]},I))]}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx("input",{type:"text",value:m,onChange:I=>{p(I.target.value),c&&u(null)},onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),j())},placeholder:r||"Add...",className:"flex-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:border-primary"}),e.jsx("button",{onClick:j,disabled:!m.trim(),className:"px-3 py-2 bg-primary text-primary-foreground rounded-lg text-sm disabled:opacity-40",children:"Add"})]}),c&&e.jsx("div",{style:{color:"#b91c1c",fontSize:12,marginTop:6},children:c})]})}function CO({score:t}){if(t==null)return e.jsx("span",{className:"text-muted-foreground text-xs",children:"--"});const s=t>=80?"text-green-500":t>=50?"text-yellow-500":"text-red-500";return e.jsx("span",{className:`text-xs font-semibold ${s}`,children:t})}function TO({level:t}){if(!t)return null;const s={observe:"bg-blue-500/15 text-blue-400",suggest:"bg-yellow-500/15 text-yellow-400",draft:"bg-orange-500/15 text-orange-400",act:"bg-red-500/15 text-red-400"};return e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${s[t]||"bg-muted text-muted-foreground"}`,children:t})}function AO(t){const s=t.trim().toLowerCase().replace(/^#+/,"");return s?`#${s}`:""}function EO({onBack:t,onLogoClick:s}){const{rows:n,loading:r,error:a,updateRow:o,createRow:i}=Xt({collectionName:"clients",orderByField:"name",orderDirection:"asc"}),[d,m]=l.useState(""),[p,c]=l.useState("all"),[u,x]=l.useState(null),[h,b]=l.useState(null),[f,g]=l.useState(""),y=l.useMemo(()=>{let N=n;return p!=="all"&&(N=N.filter(S=>(S.lifecycleStage||"active")===p)),N=N.filter(Js(d,S=>[S.name,S.companyName,S.displayId,S.hubspotCompanyId,S.slackChannels,S.domains])),N},[n,d,p]),j=(N,S)=>{b(N),g(S)},v=l.useCallback(async()=>{if(!u||!h)return;const N=["supportHealthScore","supportTicketVolume"],S=["creditPriceCents"];let O;S.includes(h)?O=f===""?null:Math.round(Number(f)*100):N.includes(h)?O=f===""?null:Number(f):O=f||null,await o(u.id,{[h]:O}),x({...u,[h]:O}),b(null)},[u,h,f,o]),T=l.useCallback(async(N,S)=>{u&&(await o(u.id,{[N]:S}),x({...u,[N]:S}))},[u,o]),[k,w]=l.useState(null);ee.useEffect(()=>{if(!k)return;const N=n.find(S=>S.id===k);N&&(x(N),w(null))},[n,k]);const I=l.useCallback(async()=>{const N=await i({name:"New Client",displayId:"",slackChannels:[],domains:[],notionPageId:""});w(N)},[i]),A=l.useCallback(async N=>{if(!u)return;const O={...u.trust||{level:"observe",permissions:{canSendEmail:!1,canSendSlack:!1,canCreateTasks:!1,canUpdateBilling:!1,canEngageContacts:!1},escalateTo:null,updatedAt:new Date,updatedBy:"manual"},level:N,updatedAt:new Date,updatedBy:"manual"};await o(u.id,{trust:O}),x({...u,trust:O})},[u,o]),E=l.useCallback(async(N,S)=>{if(u!=null&&u.trust)try{const O={...u.trust,permissions:{...u.trust.permissions,[N]:S},updatedAt:new Date,updatedBy:"manual"};await o(u.id,{trust:O}),x({...u,trust:O})}catch(O){console.error("Failed to save trust permission:",O)}},[u,o]),C={editField:h,editValue:f,onEdit:j,onSave:v,onEditValueChange:g};return e.jsxs(hn,{title:"Clients",count:y.length,loading:r,error:a,searchValue:d,onSearchChange:m,onBack:t,onLogoClick:s,onCreate:I,tabs:[{key:"all",label:"All"},{key:"active",label:"Active"},{key:"prospect",label:"Prospect"},{key:"sunset",label:"Sunset"},{key:"archive",label:"Archive"}],activeTab:p,onTabChange:c,children:[e.jsxs("div",{className:"space-y-2",children:[y.map(N=>{var S;return e.jsx("button",{onClick:()=>x(N),className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:N.displayId}),e.jsx(TO,{level:(S=N.trust)==null?void 0:S.level}),e.jsx(CO,{score:N.supportHealthScore})]}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:N.companyName||N.name}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{children:N.name}),N.creditPriceCents!=null&&N.currency&&e.jsxs("span",{children:["$",(N.creditPriceCents/100).toFixed(0)," ",N.currency.toUpperCase(),"/credit"]}),(N.domains||[]).length>0&&e.jsxs("span",{children:[N.domains[0],N.domains.length>1?` +${N.domains.length-1}`:""]})]})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:nt(N.createdAt)})]})},N.id)}),y.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No clients found"})]}),u&&e.jsxs(Cs,{title:u.companyName||u.name,subtitle:`${u.displayId} · ${u.name}`,onClose:()=>{x(null),b(null)},footer:e.jsx(SO,{clientId:u.id,onDeleted:()=>x(null)}),children:[e.jsx(De,{title:"Details"}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:10,fontWeight:600,color:"#9ca3af",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Lifecycle Stage"}),e.jsx("div",{style:{display:"flex",gap:4,marginBottom:8},children:["prospect","active","sunset","archive"].map(N=>e.jsx("button",{onClick:()=>T("lifecycleStage",N),style:{fontSize:11,padding:"3px 10px",borderRadius:9999,border:"none",cursor:"pointer",fontWeight:500,backgroundColor:u.lifecycleStage===N?N==="active"?"rgba(34,197,94,0.2)":N==="prospect"?"rgba(59,130,246,0.2)":N==="sunset"?"rgba(249,115,22,0.2)":"rgba(120,120,120,0.2)":"rgba(120,120,120,0.08)",color:u.lifecycleStage===N?N==="active"?"#4ade80":N==="prospect"?"#60a5fa":N==="sunset"?"#fb923c":"#9ca3af":"#9ca3af"},children:N},N))})]}),e.jsx(oe,{label:"Company Name",value:u.companyName||"",field:"companyName",...C}),e.jsx(oe,{label:"Internal Name",value:u.name,field:"name",...C}),e.jsx(Zd,{label:"Slack Channels",items:u.slackChannels||[],emptyText:"no slack channels",placeholder:"Add slack channel...",normalize:AO,onSave:N=>T("slackChannels",N)}),e.jsx(Zd,{label:"Domains",items:u.domains||[],emptyText:"no domains",placeholder:"Add domain...",onSave:N=>T("domains",N)}
460),e.jsx(oe,{label:"HubSpot Company ID",value:u.hubspotCompanyId||"",field:"hubspotCompanyId",...C,readOnly:!0}),e.jsx(De,{title:"Pricing"}),e.jsx(oe,{label:"Credit Price",value:u.creditPriceCents!=null?String(u.creditPriceCents):"",field:"creditPriceCents",...C,currency:!0}),e.jsx(oe,{label:"Currency",value:u.currency||"",field:"currency",...C,options:["","cad","usd","eur"],onDirectSave:T}),e.jsx(oe,{label:"Stripe Customer ID",value:u.stripeCustomerId||"",field:"stripeCustomerId",...C}),e.jsx(oe,{label:"Subscription Status",value:u.subscriptionStatus||"",field:"subscriptionStatus",...C,readOnly:!0}),e.jsx(De,{title:"Support Health"}),e.jsx(oe,{label:"Health Score",value:u.supportHealthScore!=null?String(u.supportHealthScore):"",field:"supportHealthScore",...C,numeric:!0}),e.jsx(oe,{label:"Ticket Volume",value:u.supportTicketVolume!=null?String(u.supportTicketVolume):"",field:"supportTicketVolume",...C,numeric:!0}),e.jsx(oe,{label:"Top Issue",value:u.supportTopIssue||"",field:"supportTopIssue",...C}),e.jsx(oe,{label:"Last Synced",value:u.supportLastSynced||"",field:"supportLastSynced",...C,readOnly:!0}),e.jsx(De,{title:"Activity"}),e.jsx(oe,{label:"Last Activity",value:nt(u.lastActivityAt),field:"",...C,readOnly:!0}),e.jsx(oe,{label:"Last Communication",value:nt(u.lastCommunicationAt),field:"",...C,readOnly:!0}),e.jsx(De,{title:"Trust (Candlelight)"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Trust Level"}),e.jsx("div",{className:"flex gap-1.5 mt-1.5",children:["observe","suggest","draft","act"].map(N=>{var S;return e.jsx("button",{onClick:()=>A(N),className:(((S=u.trust)==null?void 0:S.level)||"observe")===N?"bg-primary text-primary-foreground":"bg-card text-foreground border border-border",style:{padding:"4px 12px",borderRadius:9999,fontSize:13,fontWeight:500,transition:"all 0.15s"},children:N},N)})})]}),u.trust&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2 mt-2",children:[["canSendEmail","Send Email"],["canSe
460ndSlack","Send Slack"],["canCreateTasks","Create Tasks"],["canUpdateBilling","Update Billing"],["canEngageContacts","Engage Contacts"]].map(([N,S])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:S}),e.jsx("button",{onClick:()=>E(N,!u.trust.permissions[N]),className:u.trust.permissions[N]?"bg-primary":"bg-border",style:{width:40,height:24,borderRadius:12,position:"relative",transition:"background-color 0.2s"},children:e.jsx("span",{style:{position:"absolute",top:4,left:u.trust.permissions[N]?20:4,width:16,height:16,borderRadius:8,backgroundColor:"white",transition:"left 0.2s"}})})]},N))}),e.jsx(oe,{label:"Escalate To",value:u.trust.escalateTo||"",field:"trust.escalateTo",...C})]}),e.jsx(De,{title:"Metadata"}),e.jsx(oe,{label:"Created",value:nt(u.createdAt),field:"",...C,readOnly:!0}),e.jsx(oe,{label:"Updated",value:nt(u.updatedAt),field:"",...C,readOnly:!0})]})]})}function IO({onBack:t,onLogoClick:s}){const{rows:n,loading:r,error:a,updateRow:o,createRow:i,deleteRow:d}=Xt({collectionName:"shopifyStores",orderByField:"name",orderDirection:"asc"}),[m,p]=l.useState(""),[c,u]=l.useState(null),[x,h]=l.useState(null),[b,f]=l.useState(""),g=l.useMemo(()=>n.filter(Js(m,I=>[I.name,I.myshopifyUrl,I.clientName])),[n,m]),y=(I,A)=>{h(I),f(A)},j=l.useCallback(async()=>{!c||!x||(await o(c.id,{[x]:b||null}),u({...c,[x]:b||null}),h(null))},[c,x,b,o]),[v,T]=l.useState(null);ee.useEffect(()=>{if(!v)return;const I=n.find(A=>A.id===v);I&&(u(I),T(null))},[n,v]);const k=l.useCallback(async()=>{const I=await i({name:"New Store",myshopifyUrl:"",onlineStoreUrl:null,clientId:null,clientName:null,slackChannel:null,notionPageId:""});T(I)},[i]),w={editField:x,editValue:b,onEdit:y,onSave:j,onEditValueChange:f};return e.jsxs(hn,{title:"Shopify Stores",count:g.length,loading:r,error:a,searchValue:m,onSearchChange:p,onBack:t,onLogoClick:s,onCreate:k,children:[e.jsxs("div",{className:"space-y-2",children:[g.map(I=>e.jsx("button",{onClick:()=>u(I),className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:I.name||"(unnamed)"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:I.myshopifyUrl||""}),I.clientName&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:I.clientName})]})})},I.id)),g.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No stores found"})]}),c&&e.jsxs(Cs,{title:c.name,onClose:()=>{u(null),h(null)},footer:e.jsx(nr,{onDelete:async()=>{await d(c.id),u(null)}}),children:[e.jsx(De,{title:"Details"}),e.jsx(oe,{label:"Name",value:c.name,field:"name",...w}),e.jsx(oe,{label:"Myshopify URL",value:c.myshopifyUrl,field:"myshopifyUrl",...w}),e.jsx(oe,{label:"Online Store URL",value:c.onlineStoreUrl||"",field:"onlineStoreUrl",...w}),e.jsx(De,{title:"Client"}),e.jsx(oe,{label:"Client",value:c.clientName||"",field:"clientName",...w}),e.jsx(oe,{label:"Slack Channel",value:c.slackChannel||"",field:"slackChannel",...w}),e.jsx(De,{title:"Metadata"}),e.jsx(oe,{label:"Created",value:nt(c.createdAt),field:"",...w,readOnly:!0}),e.jsx(oe,{label:"Updated",value:nt(c.updatedAt),field:"",...w,readOnly:!0})]})]})}const RO="pyannote-community-1",DO=256;function MO(t){if(!t.length)return[];const s=t[0].length,n=new Array(s).fill(0);for(const r of t)for(let a=0;a<s;a++)n[a]+=r[a]||0;for(let r=0;r<s;r++)n[r]/=t.length;return n}async function PO(t){if(t.contactId){const s=await Ze(Ge(Re(ge,"voiceprints"),Ve("contactId","==",t.contactId),Tt(1)));if(!s.empty)return s.docs[0].id}return null}async function LO(t,s,n,r){if(!s||!s.length)throw new Error("no embedding to enroll");const a=await PO(t),o=a?ut(ge,"voiceprints",a):ut(Re(ge,"voiceprints"));return await Dl(ge,async i=>{const d=await i.get(o),m=d.exists()?d.data():{},p=Array.isArray(m.samples)?m.samples:[],c={vector:s,sourceMeetingId:n,confirmedBy:r,createdAt:Date.now()},u=[...p,c],x=MO(u.map(h=>h.vector));i.set(o,{name:t.name,role:t.role||(t.clientId?"client":"internal"),contactId:t.contactId||null,clientId:t.clientId||null,embeddingModel:RO,embeddingDim:s.length||DO,centroid:x,samples:u,sampleC
460ount:u.length,updatedAt:ss()},{merge:!0})}),o.id}async function zO(t){const{meetingId:s,cluster:n,target:r,segments:a,utterances:o,unresolvedClusters:i,confirmedBy:d}=t;n.embedding&&n.embedding.length&&await LO(r,n.embedding,s,d);const m=h=>h.map(b=>b.speaker===n.clusterId?{...b,speaker:r.name}:b),p=m(a),c=m(o),u=i.filter(h=>h.clusterId!==n.clusterId),x=u.length?"needs_review":"done";await er(ut(ge,"meetings",s),{"buckyLive.diarization.segments":p,"buckyLive.diarization.unresolvedClusters":u,"buckyLive.diarization.status":x,"buckyLive.diarizationStatus":x,"buckyLive.transcript.utterances":c})}function ol(t){const s=`${t.firstName||""} ${t.lastName||""}`.trim();return s&&t.companyName?`${s} â ${t.companyName}`:s||t.email||t.id}function OO({meetingId:t,diarization:s,utterances:n}){const{rows:r}=Xt({collectionName:"contacts",orderByField:"firstName",orderDirection:"asc"}),a=s.unresolvedClusters||[],o=s.status||"pending",i=l.useMemo(()=>[...r].sort((m,p)=>ol(m).localeCompare(ol(p))),[r]),d=l.useMemo(()=>i.map(m=>({id:m.id,label:ol(m)})),[i]);return o==="pending"||o==="awaiting-upload"||o==="processing"?e.jsx(bd,{icon:e.jsx(fe,{style:{width:14,height:14},className:"animate-spin"}),text:o==="awaiting-upload"?"Waiting to upload the recording to the diarization serviceâ¦":"Diarization in progress â speaker attribution will appear here when ready."}):o==="failed"?e.jsx(bd,{icon:e.jsx(Dt,{style:{width:14,height:14}}),text:"Diarization failed for this meeting. Check the service logs on the M1.",tone:"danger"}):a.length===0?e.jsx(bd,{icon:e.jsx(Ns,{style:{width:14,height:14}}),text:"All speakers attributed â nothing left to review.",tone:"success"}):e.jsxs("div",{style:{maxHeight:400,overflowY:"auto",display:"flex",flexDirection:"column",gap:10},children:[e.jsx("p",{className:"text-xs text-muted-foreground",style:{marginBottom:2,lineHeight:1.5},children:"Confirm who each unidentified voice belongs to. Confirming teaches the voiceprint library so this person is auto-named on future calls."}),a.map(m=>e.jsx($O,{meetingId:t,cluster:m,contacts:i,contactLookup:d,segments:s.segments||[],utterances:n,unresolvedClusters:a},m.clusterId))]})}function $O({meetingId:t,cluster:s,contacts:n,contactLookup:r,segments:a,utterances:o,unresolvedClusters:i}){var E;const d=l.useMemo(()=>{if(s.suggestedPersonId){const C=r.find(N=>N.id===s.suggestedPersonId);if(C)return C}if(s.suggestedName){const C=n.find(N=>`${N.firstName||""} ${N.lastName||""}`.trim().toLowerCase()===s.suggestedName.toLowerCase());if(C)return{id:C.id,label:ol(C)}}return null},[s,n,r]),[m,p]=l.useState(d),[c,u]=l.useState(null),[x,h]=l.useState(""),[b,f]=l.useState(!1),[g,y]=l.useState(!1),[j,v]=l.useState(null),T=l.useRef(null),[k,w]=l.useState(!1),I=()=>{s.sampleAudioUrl&&(T.current||(T.current=new Audio(s.sampleAudioUrl),T.current.onended=()=>w(!1)),k?T.current.pause():T.current.play(),w(!k))},A=async()=>{var N;const C=m?n.find(S=>S.id===m.id):null;if(!C){v("Pick a contact first.");return}f(!0),v(null);try{const S=`${C.firstName||""} ${C.lastName||""}`.trim()||C.email||"Unknown",O=((N=C.clientIds)==null?void 0:N[0])??null,R=Lr.currentUser;await zO({meetingId:t,cluster:s,target:{name:S,contactId:C.id,clientId:O,role:O?"client":"internal"},segments:a,utterances:o,unresolvedClusters:i,confirmedBy:(R==null?void 0:R.displayName)||(R==null?void 0:R.email)||(R==null?void 0:R.uid)||"unknown"}),y(!0)}catch(S){v(S instanceof Error?S.message:String(S))}finally{f(!1)}};return e.jsxs("div",{className:"bg-background border border-border",style:{borderRadius:8,padding:12,opacity:g?.6:1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6,flexWrap:"wrap"},children:[e.jsx("span",{className:"bg-card border border-border text-foreground",style:{padding:"2px 8px",borderRadius:9999,fontSize:12,fontWeight:600},children:s.clusterId}),s.sampleAudioUrl&&!g&&e.jsxs("button",{onClick:I,className:"bg-card border border-border text-foreground hover:bg-accent",style:{display:"inline-flex",alignItems:"center",gap:5,padding:"3px 10px",borderRadius:9999,fontSize:12},children:[k?e.jsx(xg,{style:{width:12,height:12}}):e.jsx(In,{style:{width:12,height:12}}),k?"Pause":"Listen"]}),s.suggestedName&&!g&&e.jsxs("span",{className:"text-muted-foreground",style:{fontSize:12},children:["suggested: ",e.jsx("strong",{children:s.suggestedName}),typeof s.score=="number"?` (${(s.score*100).toFixed(0)}%)`:""]}),!((E=s.embedding)!=null&&E.length)&&e.jsx("span",{className:"text-muted-foreground",style:{fontSize:11},children:"(too little audio to learn a voiceprint â will relabel only)"})]}),s.sampleText&&e.jsxs("p",{className:"text-sm text-foreground",style:{marginBottom:10,lineHeight:1.5,fontStyle:"italic"},children:["â",s.sampleText,"â"]}),g?e.jsxs("div",{className:"text-primary",style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:13,fontWeight:500},children:[e.jsx(Ns,{style:{width:14,height:14}})," Confirmed as ",m==null?void 0:m.label]}):e.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:8,flexWrap:"wrap"},children:[e.jsx("div",{style:{flex:1,minWidth:220},children:e.jsx(oe,{label:"Assign speaker",value:(m==null?void 0:m.label)||"",field:"contact",editField:c,editValue:x,onEdit:(C,N)=>{u(C),h(N)},onSave:()=>u(null),onEditValueChange:h,lookupItems:r,onLookupSelect:C=>{p(C),v(null)}})}),e.jsxs("button",{onClick:A,disabled:b||!m,className:"bg-primary text-primary-foreground hover:opacity-90",style:{padding:"8px 14px",borderRadius:8,fontSize:12,fontWeight:500,display:"inline-flex",alignItems:"center",gap:6,opacity:b||!m?.5:1},children:[b?e.jsx(fe,{style:{width:13,height:13},className:"animate-spin"}):e.jsx(fN,{style:{width:13,height:13}}),"Confirm"]})]}),j&&e.jsx("p",{style:{color:"#dc2626",fontSize:12,marginTop:6},children:j})]})}function bd({icon:t,text:s,tone:n}){const r=n==="danger"?"#dc2626":void 0;return e.jsxs("div",{className:"bg-background border border-border",style:{borderRadius:8,padding:12,display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{className:n==="success"?"text-primary":"text-muted-foreground",style:{color:r,display:"inline-flex"},children:t}),e.jsx("span",{className:"text-sm text-foreground",style:{color:r},children:s})]})}const BO="meeting-extract",FO="AI Review";function Fh(t){if(!t)return null;if(typeof(t==null?void 0:t.toDate)=="function")return t.toDate();const s=(t==null?void 0:t.seconds)??(t==null?void 0:t._seconds);return typeof s=="number"?new Date(s*1e3):null}function _O(t){const[s,n]=l.useState([]),[r,a]=l.useState(!0);return l.useEffect(()=>{if(!t)return;const o=Ge(Re(ge,"tickets"),Ve("meetingSource.meetingId","==",t));return qt(o,d=>{n(d.docs.map(m=>{const p=m.data();return{id:m.id,displayId:p.displayId||"",name:p.name||"(untitled)",status:p.status||"",projectId:p.projectId??null,projectName:p.projectName??null}}).sort((m,p)=>m.displayId.localeCompare(p.displayId,void 0,{numeric:!0}))),a(!1)},d=>{console.error("[useMeetingExtractedTickets] snapshot failed:",d),a(!1)})},[t]),{tickets:s,loading:r}}function WB(){const[t,s]=l.useState([]),[n,r]=l.useState({}),[a,o]=l.useState(!0),[i,d]=l.useState(null);l.useEffect(()=>{const c=Ge(Re(ge,"tickets"),Ve("source","==",BO),Ve("status","==",FO));return qt(c,x=>{const h=[];x.docs.forEach(b=>{var g;const f=b.data();f.projectId||(g=f.meetingSource)!=null&&g.meetingId&&h.push({id:b.id,displayId:f.displayId||"",name:f.name||"(untitled)",content:f.content??null,status:f.status,projectId:f.projectId??null,clientId:f.clientId??null,clientName:f.clientName??null,department:f.department??null,createdAt:f.createdAt,meetingSource:f.meetingSource})}),s(h),o(!1)},x=>{console.error("[useTriageQueue] snapshot failed:",x),d(x.message),o(!1)})},[]);const m=l.useMemo(()=>Array.from(new Set(t.map(c=>c.meetingSource.meetingId))).sort(),[t]);return l.useEffect(()=>{let c=!1;const u=m.filter(x=>!n[x]);if(u.length)return(async()=>{const x={};await Promise.all(u.map(async h=>{var b,f,g;try{const y=await ps(ut(ge,"meetings",h));if(!y.exists())return;const j=y.data(),v=(b=j.buckyLive)==null?void 0:b.extraction,T=((g=(f=j.buckyLive)==null?void 0:f.transcript)==null?void 0:g.utterances)||[];x[h]={name:j.name||"(untitled)",meetingType:j.meetingType??null,trigger:(v==null?void 0:v.trigger)??null,diarizationStatusAtRun:(v==null?void 0:v.diarizationStatusAtRun)??null,unattributed:!T.s
460ome(k=>!!(k!=null&&k.speaker))}}catch(y){console.error(`[useTriageQueue] meeting ${h} load failed:`,y)}})),!c&&Object.keys(x).length&&r(h=>({...h,...x}))})(),()=>{c=!0}},[m]),{groups:l.useMemo(()=>{const c=new Map;for(const u of t){const x=u.meetingSource;let h=c.get(x.meetingId);h||(h={meetingId:x.meetingId,meetingDisplayId:x.meetingDisplayId||x.meetingId,meetingDate:Fh(x.meetingDate)||Fh(x.extractedAt),clientId:u.clientId,clientName:u.clientName,tickets:[],meta:n[x.meetingId]??null},c.set(x.meetingId,h)),h.tickets.push(u)}return Array.from(c.values()).map(u=>({...u,tickets:u.tickets.slice().sort((x,h)=>x.displayId.localeCompare(h.displayId,void 0,{numeric:!0}))})).sort((u,x)=>{var h,b;return(((h=x.meetingDate)==null?void 0:h.getTime())||0)-(((b=u.meetingDate)==null?void 0:b.getTime())||0)})},[t,n]),totalUntriaged:t.length,loading:a,error:i}}function WO(t){switch(t){case"pending":case"awaiting-upload":return{label:"Diarization queued",color:"#a1a1aa"};case"processing":return{label:"Diarizingâ¦",color:"#3b82f6"};case"needs_review":return{label:"Speakers need review",color:"#f59e0b"};case"done":return{label:"Speakers attributed",color:"#22c55e"};case"failed":return{label:"Diarization failed",color:"#dc2626"};default:return null}}function UO(t){return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function HO(t){if(!t)return null;const s=t.split(/\n\n---\n\n/),n={},r=[],a=[];for(const i of s){const d=i.trim();if(d.startsWith("## Summary")){const m=d.replace(/^## Summary\s*/,""),[p,...c]=m.split(/\n###\s+/);n.headline=p.trim();for(const u of c){const x=u.indexOf(` 461`),h=u.slice(0,x).trim().toLowerCase(),b=u.slice(x).split(` 462`).map(f=>f.replace(/^-\s*/,"").trim()).filter(Boolean);h.startsWith("decisions")?n.decisions=b:h.startsWith("commitments")?n.commitments=b.map(f=>({text:f})):h.startsWith("follow-ups")||h.startsWith("followups")?n.followUps=b:h.startsWith("key facts")&&(n.keyFacts=b)}}else if(d.startsWith("## Bucky Cards")){const p=d.replace(/^## Bucky Cards\s*/,"").split(/\n\n+/);for(const c of p){const u=c.match(/^Q:\s*([\s\S]*?)\nA:\s*([\s\S]*)$/);u&&r.push({triggerText:u[1].trim(),responseText:u[2].trim()})}}else if(d.startsWith("## Full Transcript")){const p=d.replace(/^## Full Transcript\s*/,"").split(` 463`).filter(Boolean);for(const c of p){const u=c.match(/^\[([^\]]+)\]\s*(.*)$/);u&&a.push({text:u[2],startedAt:0,speaker:void 0})}}}return n.headline||r.length>0||a.length>0?{summary:Object.keys(n).length>0?n:null,cards:r,transcript:{utterances:a}}:null}function qO({meetingId:t,description:s,buckyLive:n,editField:r,editValue:a,onEdit:o,onSave:i,onEditValueChange:d}){var k,w,I;const m=l.useMemo(()=>{var A,E,C;return n&&(n.summary||(A=n.cards)!=null&&A.length||(C=(E=n.transcript)==null?void 0:E.utterances)!=null&&C.length)?n:HO(s)},[n,s]),p=(m==null?void 0:m.cards)||[],c=((k=m==null?void 0:m.transcript)==null?void 0:k.utterances)||[],u=(m==null?void 0:m.summary)||null,x=(n==null?void 0:n.extraction)||null,h=(n==null?void 0:n.diarizationStatus)||((w=n==null?void 0:n.diarization)==null?void 0:w.status),b=(n==null?void 0:n.diarization)||(h?{status:h}:null),f=WO(h),g=!!(u||p.length||c.length||b),[y,j]=l.useState(()=>u?"summary":p.length?"questions":"transcript"),{tickets:v}=_O(t);if(!g)return e.jsx(oe,{label:"Description",value:s||"",field:"description",editField:r,editValue:a,onEdit:o,onSave:i,onEditValueChange:d,multiline:!0});const T=({id:A,icon:E,label:C,count:N})=>{const S=y===A;return e.jsxs("button",{onClick:()=>j(A),className:S?"bg-primary text-primary-foreground":"bg-card text-muted-foreground border border-border",style:{padding:"6px 12px",borderRadius:9999,fontSize:12,fontWeight:500,display:"inline-flex",alignItems:"center",gap:6,transition:"all 0.15s"},children:[e.jsx(E,{style:{width:13,height:13}}),C,typeof N=="number"&&e.jsxs("span",{style:{opacity:.7},children:["(",N,")"]})]})};return e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:10,alignItems:"center"},children:[u&&e.jsx(T,{id:"summary",icon:Mn,label:"Summary"}),p.length>0&&e.jsx(T,{id:"questions",icon:nu,label:"Questions Answered",count:p.length}),c.length>0&&e.jsx(T,{id:"transcript",icon:mn,label:"Transcript",count:c.length}),b&&e.jsx(T,{id:"speakers",icon:Hl,label:"Speakers",count:((I=b.unresolvedClusters)==null?void 0:I.length)||void 0}),(x||v.length>0)&&e.jsx(T,{id:"tickets",icon:_r,label:"Tickets",count:v.length||void 0}),f&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,marginLeft:"auto",fontSize:11},className:"text-muted-foreground",title:`Speaker attribution: ${f.label}`,children:[e.jsx("span",{style:{width:7,height:7,borderRadius:9999,background:f.color,flexShrink:0}}),f.label]})]}),y==="summary"&&u&&e.jsxs("div",{className:"bg-background border border-border",style:{borderRadius:8,padding:12,maxHeight:400,overflowY:"auto"},children:[u.headline&&e.jsx("p",{className:"text-sm text-foreground",style:{marginBottom:10,lineHeight:1.5},children:u.headline}),u.decisions&&u.decisions.length>0&&e.jsx(Vi,{title:"Decisions",items:u.decisions}),u.commitments&&u.commitments.length>0&&e.jsx(Vi,{title:"Commitments",items:u.commitments.map(A=>`${A.text}${A.owner?` â ${A.owner}`:""}${A.dueDate?` (due ${A.dueDate})`:""}`)}),u.followUps&&u.followUps.length>0&&e.jsx(Vi,{title:"Follow-ups",items:u.followUps}),u.keyFacts&&u.keyFacts.length>0&&e.jsx(Vi,{title:"Key Facts",items:u.keyFacts})]}),y==="questions"&&p.length>0&&e.jsx("div",{style:{maxHeight:400,overflowY:"auto",display:"flex",flexDirection:"column",gap:10},children:p.map((A,E)=>e.jsxs("div",{className:"bg-background border border-border",style:{borderRadius:8,padding:12},children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",style:{marginBottom:4},children:"Question"}),e.jsx("p",{className:"text-sm text-foreground",style:{marginBottom:10,lineHeight:1.5},children:A.triggerText}),e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",style:{marginBottom:4},children:"Answer"}),e.jsx("p",{className:"text-sm text-foreground",style:{lineHeight:1.5,whiteSpace:"pre-wrap"},children:A.responseText})]},A.id||E))}),y==="transcript"&&c.length>0&&e.jsx("div",{children:e.jsx("div",{className:"bg-background border border-border",style:{borderRadius:8,padding:12,maxHeight:400,overflowY:"auto"},children:c.map((A,E)=>{const C=A.startedAt&&!Number.isNaN(A.startedAt)&&A.startedAt>0;return e.jsxs("div",{style:{display:"flex",gap:10,marginBottom:6,fontSize:13,lineHeight:1.5},children:[C&&e.jsx("span",{className:"text-muted-foreground",style:{fontFamily:"monospace",fontSize:11,flexShrink:0,paddingTop:2},children:UO(A.startedAt)}),A.speaker&&e.jsxs("span",{className:"text-primary",style:{fontWeight:500,flexShrink:0},children:[A.speaker,":"]}),e.jsx("span",{className:"text-foreground",children:A.text})]},A.id||E)})})}),y==="speakers"&&b&&e.jsx(OO,{meetingId:t,diarization:b,utterances:c}),y==="tickets"&&e.jsx(YO,{extraction:x,tickets:v})]})}function VO(t){switch(t){case"running":return{label:"Extracting ticketsâ¦",color:"#3b82f6"};case"done":return{label:"Tickets extracted",color:"#22c55e"};case"failed":return{label:"Extraction failed",color:"#dc2626"};case"skipped":return{label:"Nothing to extract",color:"#a1a1aa"};default:return{label:"Waiting for speaker attribution",color:"#a1a1aa"}}}function YO({extraction:t,tickets:s}){const n=VO(t==null?void 0:t.status),r=s.filter(a=>!a.projectId);return e.jsxs("div",{className:"bg-background border border-border",style:{borderRadius:8,padding:12,maxHeight:400,overflowY:"auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:10},children:[e.jsx("span",{style:{width:7,height:7,borderRadius:9999,background:n.color,flexShrink:0}}),e.jsx("span",{className:"text-sm text-foreground",children:n.label}),(t==null?void 0:t.trigger)==="timeout"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"· ran before diarization finished"})]}),(t==null?void 0:t.error)&&e.jsx("p",{className:"text-xs",style:{color:"#dc2626",marginBottom:10},children:t.error}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",style:{lineHeight:1.5},children:"No tickets from this meeting yet."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",style:{marginBottom:8},children:[s.length," ticket",s.length===1?"":"s",r.length>0&&` · ${r.length} still need${r.length===1?"s":""} a project`]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.map(a=>e.jsxs("div",{className:"bg-card border border-border",style:{borderRadius:6,padding:8},children:[e.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:6},children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:a.displayId}),e.jsx("span",{className:"text-sm text-foreground",style:{lineHeight:1.4},children:a.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground",style:{marginTop:2},children:a.projectName?`${a.status} · ${a.projectName}`:"Awaiting triage"})]},a.id))}),r.length>0&&e.jsx("p",{className:"text-xs text-muted-foreground",style:{marginTop:10,lineHeight:1.5},children:"Assign these on the Meeting Tickets screen. Untriaged tickets are archived after 14 days."})]})]})}function Vi({title:t,items:s}){return e.jsxs("div",{style:{marginBottom:10},children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider",style:{marginBottom:6},children:t}),e.jsx("ul",{style:{paddingLeft:18,margin:0,display:"flex",flexDirection:"column",gap:4},children:s.map((n,r)=>e.jsx("li",{className:"text-sm text-foreground",style:{lineHeight:1.5},children:n},r))})]})}const GO=["","Internal","Workshop","Onboarding","Sales","Client Success","Persona","Kickoff Call","Project Call","Marketing","Discovery","Consulting","Monthly Strategy Call"],KO={Internal:{bg:"#f3f4f6",fg:"#374151"},"Client Success":{bg:"#dcfce7",fg:"#15803d"},Sales:{bg:"#dbeafe",fg:"#1d4ed8"},Onboarding:{bg:"#f3e8ff",fg:"#7e22ce"},Discovery:{bg:"#fef3c7",fg:"#b45309"},"Monthly Strategy Call":{bg:"#e0e7ff",fg:"#4338ca"},"Project Call":{bg:"#cffafe",fg:"#0e7490"},Workshop:{bg:"#fce7f3",fg:"#be185d"},Persona:{bg:"#ffe4e6",fg:"#be123c"},"Kickoff Call":{bg:"#ccfbf1",fg:"#0f766e"},Marketing:{bg:"#ffedd5",fg:"#c2410c"},Consulting:{bg:"#e0f2fe",fg:"#0369a1"},adhoc:{bg:"#f1f5f9",fg:"#334155"},scheduled:{bg:"#d1fae5",fg:"#047857"}},QO={bg:"#f3f4f6",fg:"#4b5563"};function _h(t){return Array.isArray(t)?t.join(", "):typeof t=="string"?t:""}function Wh(t){return Array.isArray(t)?t.length:typeof t=="string"&&t.trim()?t.split(",").length:0}function JO({onBack:t,onLogoClick:s}){const{rows:n,loading:r,error:a,updateRow:o,createRow:i,deleteRow:d}=Xt({collectionName:"meetings",orderByField:"updatedAt",orderDirection:"desc"}),{rows:m}
463=Xt({collectionName:"clients",orderByField:"name",orderDirection:"asc"}),p=l.useMemo(()=>m.map(N=>({id:N.id,label:N.name})),[m]),[c,u]=l.useState(""),[x,h]=l.useState(null),[b,f]=l.useState(null),[g,y]=l.useState(""),j=l.useCallback(async N=>{x&&(await o(x.id,{clientId:N.id,clientName:N.label}),h({...x,clientId:N.id,clientName:N.label}))},[x,o]),v=l.useMemo(()=>{const N=n.filter(Js(c,O=>[O.name,O.displayId,O.clientName,O.meetingType])),S=O=>{if(!O)return 0;const R=parseInt(O.replace(/\D/g,""),10);return Number.isFinite(R)?R:0};return N.slice().sort((O,R)=>S(R.displayId)-S(O.displayId))},[n,c]),T=(N,S)=>{f(N),y(S)},k=l.useCallback(async()=>{!x||!b||(await o(x.id,{[b]:g||null}),h({...x,[b]:g||null}),f(null))},[x,b,g,o]),w=l.useCallback(async(N,S)=>{if(!x)return;const R=["meetingDate"].includes(N)?S?new Date(S):null:S;await o(x.id,{[N]:R}),h({...x,[N]:R})},[x,o]),[I,A]=l.useState(null);ee.useEffect(()=>{if(!I)return;const N=n.find(S=>S.id===I);N&&(h(N),A(null))},[n,I]);const E=l.useCallback(async()=>{const N=await i({name:"New Meeting",displayId:"",description:null,meetingType:null,meetingDate:null,recordingUrl:null,attendees:[],assignTo:[],clientId:null,clientName:null,projectIds:[],ticketIds:[],notionPageId:""});A(N)},[i]),C={editField:b,editValue:g,onEdit:T,onSave:k,onEditValueChange:y};return e.jsxs(hn,{title:"Meetings",count:v.length,loading:r,error:a,searchValue:c,onSearchChange:u,onBack:t,onLogoClick:s,onCreate:E,children:[e.jsxs("div",{className:"space-y-2",children:[v.map(N=>e.jsx("button",{onClick:()=>h(N),className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:N.displayId}),N.meetingType&&(()=>{const S=KO[N.meetingType]||QO;return e.jsx("span",{className:"text-xs rounded-full font-medium",style:{padding:"2px 8px",backgroundColor:S.bg,color:S.fg},children:N.meetingType})})()]}),e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:N.name}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[N.clientName&&e.jsx("span",{children:N.clientName}),Wh(N.attendees)>0&&e.jsxs("span",{children:[Wh(N.attendees)," attendees"]})]})]}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:nt(N.meetingDate)})]})},N.id)),v.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No meetings found"})]}),x&&e.jsxs(Cs,{title:x.name,subtitle:x.displayId,onClose:()=>{h(null),f(null)},footer:e.jsx(nr,{onDelete:async()=>{await d(x.id),h(null)}}),children:[e.jsx(De,{title:"Details"}),e.jsx(oe,{label:"Name",value:x.name,field:"name",...C}),e.jsx(oe,{label:"Meeting Type",value:x.meetingType||"",field:"meetingType",...C,options:GO,onDirectSave:w}),e.jsx(oe,{label:"Meeting Date",value:el(x.meetingDate),field:"meetingDate",...C,date:!0,onDirectSave:w}),e.jsx(De,{title:"People"}),e.jsx(oe,{label:"Client",value:x.clientName||"",field:"clientName",...C,lookupItems:p,onLookupSelect:j}),e.jsx(oe,{label:"Attendees",value:_h(x.attendees),field:"attendees",...C}),e.jsx(oe,{label:"Assign To",value:_h(x.assignTo),field:"assignTo",...C}),e.jsx(De,{title:"Links"}),e.jsx(oe,{label:"Recording URL",value:x.recordingUrl||"",field:"recordingUrl",...C}),x.recordingUrl&&e.jsxs("a",{href:x.recordingUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:["Open recording ",e.jsx(Da,{style:{width:14,height:14}})]}),e.jsx(De,{title:"Content"}),e.jsx(qO,{meetingId:x.id,description:x.description||"",buckyLive:x.buckyLive||null,editField:b,editValue:g,onEdit:T,onSave:k,onEditValueChange:y}),e.jsx(De,{title:"Metadata"}),e.jsx(oe,{label:"Created",value:nt(x.createdAt),field:"",...C,readOnly:!0}),e.jsx(oe,{label:"Updated",value:nt(x.updatedAt),field:"",...C,readOnly:!0})]})]})}function ZO({tech:t,highlight:s}){const n=s?"bg-primary/15 text-primary font-medium":"bg-muted text-muted-foreground";return e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${n}`,children:t})}function XO({contactId:t,contactName:s,icpFitScore:n,lastEnrichedAt:r}){var h,b,f,g,y,j,v,T,k;const[a,o]=l.useState(null),[i,d]=l.useState(!1),[m,p]=l.useState(!1),[c,u]=l.useState(null);l.useEffect(()=>{if(!t)return;d(!0);const w=Ge(Re(ge,"contactEnrichments"),Ve("contactId","==",t),Nt("enrichedAt","desc"),Tt(1));Ze(w).then(I=>{I.empty||o({id:I.docs[0].id,...I.docs[0].data()})}).catch(I=>console.error("Failed to load enrichment:",I)).finally(()=>d(!1))},[t]);const x=async()=>{p(!0),u(null);try{const w=await re("autoEnrichContact",{contactId:t}),I=Ge(Re(ge,"contactEnrichments"),Ve("contactId","==",t),Nt("enrichedAt","desc"),Tt(1)),A=await Ze(I);A.empty||o({id:A.docs[0].id,...A.docs[0].data()})}catch(w){u(w.message||"Enrichment failed")}finally{p(!1)}};return i?e.jsxs("div",{className:"py-2",children:[e.jsx(De,{title:"Enrichment"}),e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Loading enrichment data..."})]}):e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(De,{title:"Enrichment"}),e.jsx("button",{onClick:x,disabled:m,className:"text-xs font-medium px-3 py-1 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors",children:m?"Enriching...":a?"Re-Enrich":"Enrich"})]}),c&&e.jsx("p",{className:"text-xs text-red-400 mb-2",children:c}),!a&&!m&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:'No enrichment data yet. Click "Enrich" to pull data from Apollo.io.'}),a&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-accent rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsxs("div",{className:"flex flex-col items-center justify-center rounded-lg bg-background px-3 py-2 min-w-[56px]",style:{border:"1px solid var(--border)"},children:[e.jsx("span",{className:`text-lg font-bold leading-none ${(((h=a.ai)==null?void 0:h.icpFitScore)??n??0)>=70?"text-green-400":(((b=a.ai)==null?void 0:b.icpFitScore)??n??0)>=40?"text-yellow-400":"text-red-400"}`,children:((f=a.ai)==null?void 0:f.icpFitScore)??n??"â"}),e.jsx("span",{className:"text-[9px] text-muted-foreground uppercase tracking-wider mt-0.5",children:"ICP"})]}),((g=a.ai)==null?void 0:g.icpFitReason)&&e.jsx("p",{className:"text-xs text-muted-foreground leading-snug flex-1",children:a.ai.icpFitReason})]}),((y=a.ai)==null?void 0:y.contactSummary)&&e.jsx("p",{className:"text-xs text-foreground leading-relaxed",children:a.ai.contactSummary})]}),(((j=a.ai)==null?void 0:j.suggestedOutreachAngle)||((v=a.ai)==null?void 0:v.suggestedTalkingPoints)&&a.ai.suggestedTalkingPoints.length>0)&&e.jsxs("div",{className:"bg-accent rounded-lg p-3 space-y-2",children:[((T=a.ai)==null?void 0:T.suggestedOutreachAngle)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground font-medium mb-0.5",children:"Suggested Angle"}),e.jsx("p",{className:"text-xs text-foreground leading-snug",children:a.ai.suggestedOutreachAngle})]}),((k=a.ai)==null?void 0:k.suggestedTalkingPoints)&&a.ai.suggestedTalkingPoints.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground font-medium mb-0.5",children:"Talking Points"}),e.jsx("ul",{className:"text-xs text-foreground space-y-1 pl-3",children:a.ai.suggestedTalkingPoints.map((w,I)=>e.jsx("li",{className:"relative before:content-[''] before:absolute before:left-[-10px] before:top-[7px] before:w-[4px] before:h-[4px] before:rounded-full before:bg-muted-foreground",children:w},I))})]})]}),(a.seniority||a.department||a.location||a.linkedinUrl||a.company)&&e.jsxs("div",{className:"bg-accent rounded-lg p-3 space-y-2.5",children:[(a.seniority||a.department||a.location||a.linkedinUrl)&&e.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[a.seniority&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Seniority:"})," ",a.seniority]}),a.department&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Dept:"})," ",a.department]}),a.location&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Location:"})," ",a.location]}),a.linkedinUrl&&e.jsx("a",{href:a.linkedinUrl,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"LinkedIn"})]}),a.company&&(a.company.name||a.company.industry)&&e.jsxs(e.Fragment,{children:[(a.seniority||a.department||a.location)&&e.jsx("div",{className:"border-t border-border"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.company.name&&e.jsx("span",{className:"text-xs font-medium text-foreground",children:a.company.name}),a.company.isShopify&&a.company.shopifyPlan&&e.jsxs("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-green-500/15 text-green-400",children:["Shopify ",a.company.shopifyPlan]})]}),e.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[a.company.industry&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Industry:"})," ",a.company.industry]}),a.company.employeeRange&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Size:"})," ",a.company.employeeRange]}),a.company.revenueRange&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Rev:"})," ",a.company.revenueRange]}),a.company.fundingStage&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Funding:"})," ",a.company.fundingStage]}),a.company.foundedYear&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Est:"})," ",a.company.foundedYear]})]})]}),a.company.technologies&&a.company.technologies.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:a.company.technologies.map(w=>e.jsx(ZO,{tech:w,highlight:w.toLowerCase().includes("shopify")},w))})]})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Enriched ",nt(a.enrichedAt)," via ",a.provider]})]})]})}const e$={active:{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80"},paused:{backgroundColor:"rgba(249,115,22,0.15)",color:"#fb923c"},completed:{backgroundColor:"rgba(59,130,246,0.15)",color:"#60a5fa"},replied:{backgroundColor:"rgba(168,85,247,0.15)",color:"#c084fc"},bounced:{backgroundColor:"rgba(239,68,68,0.15)",color:"#f87171"},manual_exit:{backgroundColor:"rgba(120,120,120,0.15)",color:"#9ca3af"}};function t$({contactId:t}){const[s,n]=l.useState([]),[r,a]=l.useState(!0),[o,i]=l.useState(null),d=async()=>{a(!0);try{const p=Ge(Re(ge,"sequenceEnrollments"),Ve("contactId","==",t),Nt("createdAt","desc")),u=(await Ze(p)).docs.map(b=>({id:b.id,...b.data()})),x=[...new Set(u.map(b=>b.sequenceId))],h={};await Promise.all(x.map(async b=>{const f=await ps(ut(ge,"outreachSequences",b));f.exists()&&(h[b]=f.data().name)})),n(u.map(b=>({...b,sequenceName:h[b.sequenceId]||b.sequenceId})))}catch(p){console.error("Failed to load contact enrollments:",p)}finally{a(!1)}};l.useEffect(()=>{d()},[t]);const m=async(p,c)=>{if(!p||!["pause","resume","remove"].includes(c)){console.error("Invalid enrollmentId or action");return}i(p);try{await re(c==="pause"?"pauseEnrollment":c==="resume"?"resumeEnrollment":"removeEnrollment",{enrollmentId:p}),await d()}catch(u){console.error(`${c} failed:`,u)}finally{i(null)}};return r?e.jsxs("div",{className:"py-2",children:[e.jsx(De,{title:"Sequences"}),e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Loading..."})]}):s.length===0?e.jsxs("div",{children:[e.jsx(De,{title:"Sequences"}),e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Not enrolled in any sequences."})]}):e.jsxs("div",{children:[e.jsx(De,{title:"Sequences"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:s.map(p=>e.jsxs("div",{className:"bg-accent",style:{borderRadius:8,padding:12,border:"1px solid var(--border)",display:"flex",flexDirection:"column",gap:6},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600},children:p.sequenceName}),e.jsx("span",{style:{fontSize:10,fontWeight:600,padding:"2px 6px",borderRadius:4,...e$[p.status]||{backgroundColor:"rgba(120,120,120,0.15)",color:"#9ca3af"}},children:p.status})]}),e.jsxs("div",{style:{fontSize:11,color:"#9ca3af",display:"flex",flexDirection:"column",gap:2},children:[e.jsxs("span",{children:["Step ",p.currentStepNumber]}),p.nextStepScheduledAt&&p.status==="active"&&e.jsxs("span",{children:["Next: ",nt(p.nextStepScheduledAt)]}),e.jsxs("span",{children:["Enrolled: ",nt(p.createdAt)]})]}),["active","paused"].includes(p.status)&&e.jsxs("div",{style:{display:"flex",gap:6,paddingTop:4},children:[p.status==="active"&&e.jsx("button",{onClick:()=>m(p.id,"pause"),disabled:o===p.id,style:{fontSize:10,padding:"2px 8px",borderRadius:4,backgroundColor:"rgba(249,115,22,0.1)",color:"#fb923c",border:"none",cursor:"pointer"},children:"Pause"}),p.status==="paused"&&e.jsx("button",{onClick:()=>m(p.id,"resume"),disabled:o===p.id,style:{fontSize:10,padding:"2px 8px",borderRadius:4,backgroundColor:"rgba(34,197,94,0.1)",color:"#4ade80",border:"none",cursor:"pointer"},children:"Resume"}),e.jsx("button",{onClick:()=>m(p.id,"remove"),disabled:o===p.id,style:{fontSize:10,padding:"2px 8px",borderRadius:4,backgroundColor:"rgba(239,68,68,0.1)",color:"#f87171",border:"none",cursor:"pointer"},children:"Remove"})]})]}
463,p.id))})]})}const yd=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s$={high:{backgroundColor:"rgba(12,163,12,0.15)",color:"#0ca30c"},medium:{backgroundColor:"rgba(250,178,25,0.15)",color:"#fab219"},low:{backgroundColor:"rgba(236,131,90,0.15)",color:"#ec835a"},none:{backgroundColor:"rgba(120,120,120,0.15)",color:"#9ca3af"}},Uh=` 464.rhythm-root { 465 --rh-series: #2a78d6; 466 --rh-accent: #eb6834; 467 --rh-ink: #0b0b0b; 468 --rh-muted: #828282; 469 --rh-baseline: #c3c2b7; 470 --rh-surface: #ffffff; 471} 472.dark .rhythm-root { 473 --rh-series: #3987e5; 474 --rh-accent: #d95926; 475 --rh-ink: #f2f2f2; 476 --rh-muted: #828282; 477 --rh-baseline: #383835; 478 --rh-surface: #21242f; 479} 480`;function jd(t){if(t==null)return"â";if(t<60)return`${Math.round(t)}m`;if(t<60*24){const n=Math.floor(t/60),r=Math.round(t%60);return r?`${n}h ${r}m`:`${n}h`}const s=t/(60*24);return s<10?`${s.toFixed(1)}d`:`${Math.round(s)}d`}function Yi(t){const s=t<12?"am":"pm";return`${t%12===0?12:t%12}${s}`}function n$(t){if(t==null)return"Pacific (assumed)";const s=t<0?"-":"+",n=Math.abs(t),r=Math.floor(n/60),a=n%60;return`UTC${s}${r}${a?`:${String(a).padStart(2,"0")}`:""}`}function vd({label:t,value:s,hint:n}){return e.jsxs("div",{style:{flex:1,minWidth:0,padding:"8px 10px",borderRadius:8,border:"1px solid var(--border)"},children:[e.jsx("div",{style:{fontSize:15,fontWeight:600,color:"var(--rh-ink)"},children:s}),e.jsx("div",{style:{fontSize:10,color:"var(--rh-muted)",marginTop:2},children:t}),n&&e.jsx("div",{style:{fontSize:9,color:"var(--rh-muted)",marginTop:1},children:n})]})}function Hh({values:t,labelFor:s,emphasisIndex:n,onHover:r,height:a=44}){const o=Math.max(...t,1);return e.jsx("div",{style:{display:"flex",alignItems:"flex-end",gap:2,height:a,borderBottom:"1px solid var(--rh-baseline)"},onMouseLeave:()=>r(null),children:t.map((i,d)=>{const m=n===d;return e.jsx("div",{onMouseEnter:()=>r(d),title:`${s(d)} â ${i} message${i===1?"":"s"}`,"aria-label":`${s(d)}: ${i}`,style:{flex:1,minWidth:0,height:"100%",display:"flex",alignItems:"flex-end",cursor:"default"},children:e.jsx("div",{style:{width:"100%",height:`${Math.max(i/o*100,i===0?2:8)}%`,backgroundColor:i===0?"var(--rh-baseline)":"var(--rh-series)",borderRadius:"3px 3px 0 0",boxShadow:m?"0 0 0 2px var(--rh-accent)":void 0}})},d)})})}function r$({contactId:t,rhythm:s}){var v;const[n,r]=l.useState(s??null),[a,o]=l.useState(!1),[i,d]=l.useState(null),[m,p]=l.useState(null),[c,u]=l.useState(null),[x,h]=l.useState(!1),b=async()=>{o(!0),d(null);try{const T=await re("computeContactRhythm",{contactId:t});r((T==null?void 0:T.rhythm)??null)}catch(T){d((T==null?void 0:T.message)||"Could not compute rhythm.")}finally{o(!1)}},f=e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsx(De,{title:"Rhythm"}),e.jsx("button",{onClick:b,disabled:a,style:{fontSize:10,padding:"2px 8px",borderRadius:4,border:"1px solid var(--border)",background:"transparent",color:"var(--rh-muted)",cursor:a?"default":"pointer"},children:a?"Computingâ¦":n?"Recompute":"Compute"})]});if(!n)return e.jsxs("div",{className:"rhythm-root",children:[e.jsx("style",{children:Uh}),f,e.jsx("p",{style:{fontSize:11,color:"var(--rh-muted)",fontStyle:"italic"},children:i||"No rhythm computed yet."})]});const{sampleSize:g,confidence:y}=n,j=y!=="none";return e.jsxs("div",{className:"rhythm-root",children:[e.jsx("style",{children:Uh}),f,e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:8,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:10,fontWeight:600,padding:"2px 6px",borderRadius:4,...s$[y]},children:y==="none"?"not enough data":`${y} confidence`}),e.jsxs("span",{style:{fontSize:10,color:"var(--rh-muted)"},children:["n=",g.pairedReplies," replies · ",g.theirMessages," from them · ",g.ourSends," from us"]}),n.isStale&&e.jsx("span",{style:{fontSize:10,fontWeight:600,padding:"2px 6px",borderRadius:4,backgroundColor:"rgba(236,131,90,0.15)",color:"#ec835a"},children:"stale"})]}),!j&&e.jsxs("p",{style:{fontSize:11,color:"var(--rh-muted)",marginBottom:8},children:["Not enough history to recommend a send time. Needs at least 3 replies to measure a pattern; there ",g.pairedReplies===1?"is":"are"," ",g.pairedReplies,"."]}),e.jsxs("div",{style:{display:"flex",gap:6,marginBottom:10},children:[e.jsx(vd,{label:"median reply",value:j?jd(n.medianResponseMinutes):"â",hint:j&&n.p90ResponseMinutes!=null?`90th: ${jd(n.p90ResponseMinutes)}`:void 0}),e.jsx(vd,{label:"response rate",value:n.responseRate!=null?`${Math.round(n.responseRate*100)}%`:"â",hint:`of ${g.ourSends} sends`}),e.jsx(vd,{label:"best send hour",value:j&&n.fastestSendHour?Yi(n.fastestSendHour.hour):"â",hint:j&&n.fastestSendHour?`${jd(n.fastestSendHour.medianMinutes)} · n=${n.fastestSendHour.n}`:"needs 2+ per hour"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between",marginBottom:4}
480,children:[e.jsx("span",{style:{fontSize:10,color:"var(--rh-muted)"},children:m!=null?`${Yi(m)} â ${n.hourHistogram[m]} message${n.hourHistogram[m]===1?"":"s"}`:"When they write, by hour"}),e.jsx("button",{onClick:()=>h(T=>!T),style:{fontSize:9,background:"transparent",border:"none",color:"var(--rh-muted)",cursor:"pointer",textDecoration:"underline"},children:x?"chart":"numbers"})]}),x?e.jsx("div",{style:{maxHeight:140,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6},children:e.jsx("table",{style:{width:"100%",fontSize:10,borderCollapse:"collapse",fontVariantNumeric:"tabular-nums"},children:e.jsx("tbody",{children:n.hourHistogram.map((T,k)=>e.jsxs("tr",{style:{borderBottom:"1px solid var(--border)"},children:[e.jsx("td",{style:{padding:"2px 6px",color:"var(--rh-muted)"},children:Yi(k)}),e.jsx("td",{style:{padding:"2px 6px",textAlign:"right",color:"var(--rh-ink)"},children:T})]},k))})})}):e.jsxs(e.Fragment,{children:[e.jsx(Hh,{values:n.hourHistogram,labelFor:Yi,emphasisIndex:((v=n.fastestSendHour)==null?void 0:v.hour)??null,onHover:p}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:9,color:"var(--rh-muted)",marginTop:2},children:[e.jsx("span",{children:"12am"}),e.jsx("span",{children:"6am"}),e.jsx("span",{children:"12pm"}),e.jsx("span",{children:"6pm"}),e.jsx("span",{children:"11pm"})]})]}),e.jsx("div",{style:{fontSize:10,color:"var(--rh-muted)",margin:"10px 0 4px"},children:c!=null?`${yd[c]} â ${n.dayHistogram[c]} message${n.dayHistogram[c]===1?"":"s"}`:"By weekday"}),e.jsx(Hh,{values:n.dayHistogram,labelFor:T=>yd[T],onHover:u,height:28}),e.jsx("div",{style:{display:"flex",gap:2,marginTop:2},children:yd.map(T=>e.jsx("span",{style:{flex:1,fontSize:9,color:"var(--rh-muted)",textAlign:"center"},children:T[0]},T))}),e.jsxs("p",{style:{fontSize:9,color:"var(--rh-muted)",marginTop:10,lineHeight:1.5},children:["Times shown in ",n$(n.utcOffsetMinutes),n.timezoneSource==="inferred"&&` â inferred from ${g.theirMessages} messages`,n.timezoneSource==="manual"&&" â set manually",n.timezoneSource==="address"&&" â from their address, unverified",n.timezoneSource==="unknown"&&" â their timezone is unknown, so this is our clock, not theirs",g.excludedAutomated>0&&`. ${g.excludedAutomated} automated message${g.excludedAutomated===1?"":"s"} excluded (calendar notices, bounces, no-reply).`]}),i&&e.jsx("p",{style:{fontSize:10,color:"#e34948",marginTop:4},children:i})]})}function qh({phoneNumber:t,displayName:s,ticketId:n,clientId:r,contactId:a,variant:o="icon",className:i=""}){const d=Vl(),m=ti(),p=Zu(),c=si(t);if(!d||!m||!c)return null;const u=d.phase!=="idle",x=u||p,h=p?"Bucky Live is using the microphone â end the meeting to place a call":u?"You are already on a call":`Call ${s||cn(c)}`,b=()=>{x||d.startCall({to:c,displayName:s,ticketId:n,clientId:r,contactId:a})};return o==="full"?e.jsxs("button",{onClick:b,disabled:x,title:h,"aria-label":h,className:`flex items-center gap-2 px-3 py-2 rounded-xl bg-primary/10 text-primary hover:opacity-80 disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${i}`,children:[e.jsx(En,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm",children:"Call"})]}):e.jsx("button",{onClick:b,disabled:x,title:h,"aria-label":h,className:`inline-flex items-center justify-center w-8 h-8 rounded-full text-primary hover:bg-primary/10 disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${i}`,children:e.jsx(En,{className:"w-4 h-4"})})}const Xd=t=>t.trim().toLowerCase(),a$=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function Vh(t,s){const n=(t||"").trim().toLowerCase(),r=(s||[]).map(Xd).filter(o=>o&&o!==n),a=Array.from(new Set(r));return n?[n,...a]:a}const eu={PROSPECT:{bg:"#fef3c7",fg:"#a16207"},CLIENT:{bg:"#dcfce7",fg:"#15803d"},PAST_CLIENT:{bg:"#d1fae5",fg:"#047857"},SUBSCRIBER:{bg:"#f3e8ff",fg:"#7e22ce"},NEWSLETTER:{bg:"#e0e7ff",fg:"#4338ca"},VENDOR:{bg:"#ffedd5",fg:"#c2410c"},PARTNER:{bg:"#ccfbf1",fg:"#0f766e"},TEAM:{bg:"#dbeafe",fg:"#1d4ed8"},SERVICE_ACCOUNT:{bg:"#f1f5f9",fg:"#334155"},NOTIFICATION:{bg:"#ffe4e6",fg:"#be123c"},BLACKLIST:{bg:"#fee2e2",fg:"#b91c1c"},OTHER:{bg:"#f3f4f6",fg:"#374151"}},o$={active:{bg:"transparent",fg:"#6b7280"},retired:{bg:"#f1f5f9",fg:"#475569"},deceased:{bg:"#f1f5f9",fg:"#475569"},left_company:{bg:"#f1f5f9",fg:"#475569"},unknown:{bg:"#fef3c7",fg:"#a16207"}};function i$({label:t,reason:s}){const n=t==="Do not contact";return e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full",style:n?{backgroundColor:"#fee2e2",color:"#b91c1c"}:{backgroundColor:"#f1f5f9",color:"#475569"},title:`${s} â all email to this contact is blocked`,children:t})}function ua(t){if(t.categories&&t.categories.length>0)return t.categories;const s=nS(t.lifecycleStage);return s.length>0?s:["OTHER"]}function l$({category:t,onRemove:s}){const n=eu[t]||eu.OTHER;return e.jsxs("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full inline-flex items-center gap-1",style:{backgroundColor:n.bg,color:n.fg},children:[Mu[t],s&&e.jsx("button",{onClick:s,className:"hover:opacity-80",style:{lineHeight:1},children:"Ã"})]})}function c$({items:t,emptyText:s}){return!t||t.length===0?e.jsx("span",{className:"text-muted-foreground text-xs italic",children:s||"none"}):e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:t.map(n=>e.jsx("span",{className:"text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full",children:n},n))})}function d$(t){return t?[t.street,t.city,t.state,t.postalCode,t.country].filter(
480Boolean).join(", "):""}function u$({onBack:t,onLogoClick:s,focusContactId:n,onFocusHandled:r}){var q,P,U,V,M,F;const{rows:a,loading:o,error:i,updateRow:d,deleteRow:m}=Xt({collectionName:"contacts",orderByField:"lastName",orderDirection:"asc"}),[p,c]=l.useState(""),[u,x]=l.useState("CLIENT"),[h,b]=l.useState(!0),[f,g]=l.useState(!1),[y,j]=l.useState(null),[v,T]=l.useState(null),[k,w]=l.useState(""),[I,A]=l.useState(!1),[E,C]=l.useState(new Map);l.useEffect(()=>{Ze(Re(ge,"clients")).then(W=>{const _=new Map;W.docs.forEach(G=>{const B=G.data();_.set(G.id,B.companyName||B.name||G.id)}),C(_)})},[]);const N=l.useRef(!1);l.useEffect(()=>{if(!n||N.current||a.length===0)return;const W=a.find(_=>_.id===n);W&&(N.current=!0,x("all"),j(W),r==null||r())},[n,a,r]);const S=l.useMemo(()=>{let W=a;if(u!=="all"&&(W=W.filter(_=>ua(_).includes(u))),h){const _=["PROSPECT","CLIENT","PAST_CLIENT","PARTNER","TEAM"];W=W.filter(G=>G.isPseudoContact?ua(G).some(B=>_.includes(B)):!0)}return f&&(W=W.filter(_=>!Pd(_).suppressed)),W=W.filter(Js(p,_=>[_.firstName,_.lastName,_.email,_.allEmails,_.companyName,_.jobTitle,_.tags])),W},[a,p,u,h,f]),O=l.useMemo(()=>{const W={all:a.length};for(const _ of a)for(const G of ua(_))W[G]=(W[G]||0)+1;return W},[a]),R=(W,_)=>{T(W),w(_)},z=l.useCallback(async()=>{if(!y||!v)return;const _=["totalRevenue","totalPaymentsCollected"].includes(v)?k===""?null:Number(k):k||null,G={[v]:_};v==="email"&&(G.email=_&&String(_).trim().toLowerCase(),G.allEmails=Vh(G.email,y.additionalEmails||[])),await d(y.id,G),j({...y,...G}),T(null)},[y,v,k,d]),D=l.useCallback(async(W,_)=>{y&&(await d(y.id,{[W]:_}),j({...y,[W]:_}))},[y,d]),L=l.useCallback(async W=>{y&&(await d(y.id,W),j({...y,...W}))},[y,d]),$={editField:v,editValue:k,onEdit:R,onSave:z,onEditValueChange:w};return e.jsxs(hn,{title:"Contacts",count:S.length,loading:o,error:i,searchValue:p,onSearchChange:c,onBack:t,onLogoClick:s,onCreate:()=>A(!0),children:[e.jsx("div",{className:"flex gap-1.5 mb-2 overflow-x-auto pb-1",style:{scrollbarWidth:"none"},children:["all",..._g].map(W=>e.jsxs("button",{onClick:()=>x(W),className:u===W?"bg-primary text-primary-foreground":"bg-card text-muted-foreground border border-border",style:{padding:"4px 12px",borderRadius:9999,fontSize:12,fontWeight:500,whiteSpace:"nowrap",transition:"all 0.15s"},children:[W==="all"?"All":Mu[W]," (",O[W]||0,")"]},W))}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,marginBottom:12,color:"var(--muted-foreground, #999)",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:h,onChange:W=>b(W.target.checked)}),"Hide pseudo-contacts (notification/service/newsletter senders)"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,marginTop:-8,marginBottom:12,color:"var(--muted-foreground, #999)",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:f,onChange:W=>g(W.target.checked)}),"Hide uncontactable (do not contact / retired / deceased / left the company / bounced)"]}),e.jsxs("div",{className:"space-y-2",children:[S.map(W=>e.jsx("button",{onClick:()=>j(W),className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1 flex-wrap",children:[ua(W).map(_=>e.jsx(l$,{category:_},_)),(()=>{const _=Pd(W);return _.suppressed?e.jsx(i$,{label:_.label,reason:_.reason}):null})(),W.isPseudoContact&&e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full bg-muted text-muted-foreground",children:"pseudo"}),W.isPrimary&&e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full bg-primary/15 text-primary",children:"primary"}),(W.tags||[]).length>0&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:W.tags.join(", ")})]}),e.jsxs("p",{className:"text-sm font-medium text-foreground",children:[W.firstName," ",W.lastName]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{children:W.email}),W.companyName&&e.jsx("span",{children:W.companyName}),W.jobTitle&&e.jsx("span",{children:W.jobTitle})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[W.icpFitScore!=null&&!ua(W).some(_=>_==="CLIENT"||_==="PAST_CLIENT")&&e.jsxs("span",{className:"text-xs font-bold px-2 py-0.5 rounded-full",style:W.icpFitScore>=70?{backgroundColor:"#dcfce7",color:"#15803d"}:W.icpFitScore>=40?{backgroundColor:"#fef3c7",color:"#a16207"}:{backgroundColor:"#fee2e2",color:"#b91c1c"},children:["ICP ",W.icpFitScore]}),W.totalPaymentsCollected!=null&&W.totalPaymentsCollected>0&&e.jsxs("span",{className:"text-xs font-medium text-green-500",children:["$",W.totalPaymentsCollected.toLocaleStr
480ing()]})]})]})},W.id)),S.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No contacts found"})]}),y&&e.jsxs(Cs,{title:`${y.firstName} ${y.lastName}`,subtitle:y.email,onClose:()=>{j(null),T(null)},footer:e.jsx(nr,{onDelete:async()=>{await m(y.id),j(null)}}),children:[e.jsx(De,{title:"Identity"}),e.jsx(oe,{label:"First Name",value:y.firstName||"",field:"firstName",...$}),e.jsx(oe,{label:"Last Name",value:y.lastName||"",field:"lastName",...$}),e.jsx(oe,{label:"Email",value:y.email||"",field:"email",...$}),e.jsx(Zd,{label:"Additional Emails",items:y.additionalEmails||[],emptyText:"none",placeholder:"Add another email...",normalize:Xd,allowEdit:!0,validate:W=>a$.test(W)?W===Xd(y.email||"")?"Already the primary email":null:"Enter a valid email address",onSave:W=>L({additionalEmails:W,allEmails:Vh(y.email,W)})}),e.jsx(De,{title:"Phone"}),e.jsx(oe,{label:"Phone",value:y.phone||"",field:"phone",...$}),e.jsx(oe,{label:"Mobile",value:y.mobilePhone||"",field:"mobilePhone",...$}),e.jsx(oe,{label:"WhatsApp",value:y.whatsappPhone||"",field:"whatsappPhone",...$}),e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx(qh,{phoneNumber:y.mobilePhone,displayName:[y.firstName,y.lastName].filter(Boolean).join(" ")||void 0,contactId:y.id,clientId:(q=y.clientIds)==null?void 0:q[0],variant:"full"}
480),e.jsx(qh,{phoneNumber:y.phone,displayName:[y.firstName,y.lastName].filter(Boolean).join(" ")||void 0,contactId:y.id,clientId:(P=y.clientIds)==null?void 0:P[0]})]}),e.jsx(De,{title:"Professional"}),e.jsx(oe,{label:"Job Title",value:y.jobTitle||"",field:"jobTitle",...$}),e.jsx(m$,{value:y.companyName||"",clientsMap:E,linkedClientIds:y.clientIds||[],onSaveName:W=>D("companyName",W||null),onPickClient:(W,_)=>{const G=y.clientIds||[],B=G.includes(W)?G:[...G,W];return L({companyName:_,clientIds:B})}}),e.jsx(oe,{label:"Website",value:y.websiteUrl||"",field:"websiteUrl",...$}),e.jsx(De,{title:"Address"}),e.jsx(oe,{label:"Full Address",value:d$(y.address),field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Timezone",value:((U=y.address)==null?void 0:U.timezone)||"",field:"",...$,readOnly:!0}),e.jsx(De,{title:"CRM"}),e.jsx(h0,{value:ua(y),onChange:async W=>{await D("categories",W)}}),e.jsx(oe,{label:"Pseudo-contact",value:"",field:"isPseudoContact",...$,checkbox:!0,checked:!!y.isPseudoContact,onDirectSave:D}),e.jsx(De,{title:"Contactability"}),e.jsx(x$,{contact:y,onChangeStatus:async W=>{await L(W==="active"?{personStatus:W,personStatusNote:null,personStatusAt:new Date}:{personStatus:W,personStatusAt:new Date})},onChangeNote:async W=>{await D("personStatusNote",W||null)},onChangeDnc:async(W,_)=>{await L({doNotContact:W,doNotContactReason:W&&_||null,doNotContactAt:W?new Date:null})},onChangeDncReason:async W=>{await D("doNotContactReason",W||null)},onClearBounce:async()=>{await L({emailStatus:"unverified",lastBounceReason:null,lastBounceAt:null})}}),e.jsx(oe,{label:"Contact Type",value:y.contactType||"",field:"contactType",...$}),e.jsx(oe,{label:"Contact Owner",value:y.contactOwner||"",field:"contactOwner",...$}),e.jsx(oe,{label:"Lead Status",value:y.leadStatus||"",field:"leadStatus",...$}),e.jsx(oe,{label:"Primary Contact",value:"",field:"isPrimary",...$,checkbox:!0,checked:y.isPrimary,onDirectSave:D}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Tags"}),e.jsx(c$,{items:y.tags||[],emptyText:"no tags"})]}),e.jsx(De,{title:"Companies"}),e.jsx(p$,{contactId:y.id,clientIds:y.clientIds||[],clientsMap:E,onChange:async W=>{await D("clientIds",W)}}),e.jsx(De,{title:"Source"}),e.jsx(oe,{label:"Original Source",value:((V=y.source)==null?void 0:V.original)||"",field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Drill-Down 1",value:((M=y.source)==null?void 0:M.drillDown1)||"",field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Drill-Down 2",value:((F=y.source)==null?void 0:F.drillDown2)||"",field:"",...$,readOnly:!0}),y.about&&e.jsx(oe,{label:"About",value:y.about||"",field:"about",...$,multiline:!0}),e.jsx(De,{title:"Engagement"}),e.jsx(oe,{label:"First Engagement",value:nt(y.firstEngagementDate),field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Last Activity",value:nt(y.lastActivityDate),field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Last Contacted",value:nt(y.lastContactedDate),field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Close Date",value:nt(y.closeDate),field:"",...$,readOnly:!0}),e.jsx(De,{title:"Financial"}),e.jsx(oe,{label:"Total Revenue",value:y.totalRevenue!=null?String(y.totalRevenue):"",field:"totalRevenue",...$,numeric:!0}),e.jsx(oe,{label:"Total Payments Collected",value:y.totalPaymentsCollected!=null?String(y.totalPaymentsCollected):"",field:"totalPaymentsCollected",...$,numeric:!0}),e.jsx(XO,{contactId:y.id,contactName:`${y.firstName} ${y.lastName}`,icpFitScore:y.icpFitScore,lastEnrichedAt:y.lastEnrichedAt}),e.jsx(t$,{contactId:y.id}),e.jsx(r$,{contactId:y.id,rhythm:y.communicationRhythm}),e.jsx(De,{title:"Metadata"}),e.jsx(oe,{label:"HubSpot Contact ID",value:y.hubspotContactId||"",field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Enrichment Source",value:y.enrichmentSource||"",field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Last Enriched",value:nt(y.lastEnrichedAt),field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Created",value:nt(y.createdAt),field:"",...$,readOnly:!0}),e.jsx(oe,{label:"Updated",value:nt(y.updatedAt),field:"",...$,readOnly:!0})]}),I&&e.jsx(h$,{onClose:()=>A(!1),onCreated:(W,_)=>{A(!1),setTimeout(()=>{const G=a.find(B=>B.id===W||(B.email||"").toLowerCase()===_);G&&j(G)},600)}})]})}function m$({value:t,clientsMap:s,linkedClientIds:n,onSaveName:r,onPickClient:a}){const[o,i]=l.useState(!1),[d,m]=l.useState(t),p=l.useRef(!1),c=l.useRef(!1);l.useEffect(()=>{o&&m(t||"")},[o,t]);const u=l.useMemo(()=>{const f=d.trim().toLowerCase(),g=Array.from(s.entries()).map(([y,j])=>({id:y,name:j}));return f?g.filter(y=>y.name.toLowerCase().includes(f)).slice(0,10):g.slice(0,10)},[s,d]),x=l.useMemo(()=>{const f=d.trim().toLowerCase();if(!f)return!1;for(const g of s.values())if(g.toLowerCase()===f)return!0;return!1},[s,d]);if(!o)return e.jsxs("div",{onClick:()=>i(!0),className:"cursor-pointer group",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Company"}),e.jsx("p",{className:"text-sm text-foreground mt-1 group-hover:text-primary transition-colors",children:t||e.jsx("span",{className:"text-muted-foreground italic",children:"empty"})})]});const h=async()=>
480{if(p.current||c.current){p.current=!1,c.current=!1;return}const f=d.trim();f!==(t||"").trim()&&await r(f),i(!1)},b=async(f,g)=>{c.current=!0,await a(f,g),i(!1)};return e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Company"}),e.jsx("input",{autoFocus:!0,type:"text",value:d,onChange:f=>m(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),h()),f.key==="Escape"&&(p.current=!0,i(!1))},onBlur:h,placeholder:"Search companies, or type a new name",className:"w-full mt-1 px-3 py-2 bg-background border border-primary rounded-lg text-sm text-foreground focus:outline-none"}),u.length>0&&e.jsx("div",{className:"border border-border bg-card",style:{maxHeight:200,overflowY:"auto",borderRadius:8,marginTop:4},children:u.map(f=>{const g=n.includes(f.id);return e.jsxs("button",{onMouseDown:y=>y.preventDefault(),onClick:()=>b(f.id,f.name),className:"text-foreground hover:bg-accent text-sm",style:{display:"block",width:"100%",textAlign:"left",padding:"6px 12px"},children:[f.name,g&&e.jsx("span",{className:"text-xs text-muted-foreground",style:{marginLeft:6},children:"· already linked"})]},f.id)})}),d.trim()&&!x&&e.jsxs("p",{className:"text-xs text-muted-foreground",style:{marginTop:4},children:["âµ Save â",d.trim(),"â as free text (no company link)"]})]})}function p$({clientIds:t,clientsMap:s,onChange:n}){const[r,a]=l.useState(!1),[o,i]=l.useState(""),d=async u=>{const x=t.filter(h=>h!==u);await n(x)},m=async u=>{if(t.includes(u))return;const x=[...t,u];await n(x),a(!1),i("")},p=new Set(t),c=l.useMemo(()=>{const u=o.trim().toLowerCase(),x=Array.from(s.entries()).filter(([h])=>!p.has(h)).map(([h,b])=>({id:h,name:b}));return u?x.filter(h=>h.name.toLowerCase().includes(u)).slice(0,50):x.slice(0,50)},[s,p,o]);return e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Linked Companies"}),t.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",style:{marginTop:4},children:"no linked companies"}):e.jsx("div",{className:"flex flex-wrap gap-1",style:{marginTop:4},children:t.map(u=>e.jsxs("span",{className:"text-xs bg-muted text-muted-foreground",style:{padding:"3px 4px 3px 10px",borderRadius:9999,display:"inline-flex",alignItems:"center",gap:6},children:[s.get(u)||u,e.jsx("button",{onClick:()=>d(u),className:"hover:text-red-500",style:{lineHeight:1,fontSize:14,padding:"0 6px 0 2px"},title:"Unlink company",children:"Ã"})]},u))}),e.jsx("button",{onClick:()=>a(u=>!u),className:"bg-card border border-border text-foreground hover:bg-accent",style:{padding:"4px 10px",borderRadius:8,fontSize:11,fontWeight:500,marginTop:6},children:r?"Close":"+ Add company"}),r&&e.jsxs("div",{style:{marginTop:6,border:"1px solid var(--border, #e5e7eb)",borderRadius:8,padding:8},children:[e.jsx("input",{autoFocus:!0,value:o,onChange:u=>i(u.target.value),placeholder:"Search companiesâ¦",className:"w-full bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:border-primary",style:{padding:"6px 10px"}}),c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",style:{marginTop:6},children:s.size===0?"Loading companiesâ¦":"No matching companies"}):e.jsx("div",{className:"space-y-1",style:{marginTop:6,maxHeight:220,overflowY:"auto"},children:c.map(u=>e.jsx("button",{onClick:()=>m(u.id),className:"w-full bg-card border border-border rounded text-left hover:bg-accent",style:{padding:"4px 8px",fontSize:12},children:u.name},u.id))})]})]})}function x$({contact:t,onChangeStatus:s,onChangeNote:n,onChangeDnc:r,onChangeDncReason:a,onClearBounce:o}){const i=Pu(t.personStatus),d=t.personStatusNote||"",m=t.doNotContactReason||"",[p,c]=l.useState(d),[u,x]=l.useState(m);l.useEffect(()=>{c(d)},[d]),l.useEffect(()=>{x(m)},[m]);const h=Pd(t),b=(t.categories||[]).includes("BLACKLIST"),f=t.doNotContact===!0;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"rounded px-2 py-1.5",style:h.suppressed?{backgroundColor:"#fef2f2",border:"1px solid #fecaca"}:{backgroundColor:"#f0fdf4",border:"1px solid #bbf7d0"},children:[e.jsx("p",{className:"text-xs font-medium",style:{color:h.suppressed?"#b91c1c":"#15803d"},children:h.suppressed?"All email blocked":"Can be emailed"}),h.suppressed&&e.jsxs("p",{className:"text-[11px] mt-0.5",style:{color:"#7f1d1d"},children:[h.reason," â this blocks everything, including ticket status updates, approvals and reports. Any active sequence exits on its next run."]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:g=>r(g.target.checked,u.trim())}),e.jsx("span",{className:"font-medium",children:"Do not contact"})]}),b&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:["Also ",e.jsx("strong",{children:"Disabled"})," (Categories) â their Bucky login and all email are blocked. Remove the category to re-enable."]}),f&&e.jsx("input",{value:u,onChange:g=>x(g.target.value),onBlur:()=>{u!==m&&a(u.trim())},placeholder:'Why â e.g. "unsubscribed 12 Aug"',className:"w-full mt-1 bg-transparent border border-border rounded px-2 py-1 text-xs"}),t.doNotContact&&t.doNotContactAt&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Set ",nt(t.doNotContactAt)]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Person Status"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:eS.map(g=>{const y=g===i,j=o$[g];return e.jsx("button",{onClick:()=>{g!==i&&s(g)},style:{padding:"3px 10px",borderRadius:9999,fontSize:11,fontWeight:500,transition:"all 0.15s",...y?g==="active"?{backgroundColor:"#dcfce7",color:"#15803d",border:"none"}:{backgroundColor:j.bg,color:j.fg,border:"none"}:{border:"1px solid var(--border, #e5e7eb)",backgroundColor:"transparent",color:"var(--muted-foreground, #6b7280)"}},children:Wg[g]},g)})}),Md(i)&&e.jsx("input",{value:p,onChange:g=>c(g.target.value),onBlur:()=>{p!==d&&n(p.trim())},placeholder:'Why, and how we know â e.g. "Retired Mar 2026, per Liz"',className:"w-full mt-1 bg-transparent border border-border rounded px-2 py-1 text-xs"}),Md(i)&&t.personStatusAt&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Set ",nt(t.personStatusAt)]})]}),t.emailStatus&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Deliverability"}),e.jsxs("p",{className:"text-xs mt-0.5",children:[t.emailStatus,["bounced","no_mx"].includes(t.emailStatus)&&e.jsx("span",{className:"text-muted-foreground",children:" â blocks all email"})]}),t.lastBounceReason&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:[t.lastBounceReason,t.lastBounceAt&&` · ${nt
480(t.lastBounceAt)}`]}),["bounced","no_mx"].includes(t.emailStatus)&&e.jsx("button",{onClick:()=>o(),className:"text-[11px] mt-1 underline text-muted-foreground hover:text-foreground",children:"Address fixed â clear and allow email again"})]})]})}function h0({value:t,onChange:s}){const n=r=>{const a=t.includes(r)?t.filter(o=>o!==r):[...t,r];s(a.length>0?a:["OTHER"])};return e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Categories"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:_g.map(r=>{const a=t.includes(r),o=eu[r],i={padding:"3px 10px",borderRadius:9999,fontSize:11,fontWeight:500,transition:"all 0.15s"},d=a?{backgroundColor:o.bg,color:o.fg,border:"none"}:{border:"1px solid var(--border, #e5e7eb)",backgroundColor:"transparent",color:"var(--muted-foreground, #6b7280)"};return e.jsx("button",{onClick:()=>n(r),style:{...i,...d},children:Mu[r]},r)})})]})}function h$({onClose:t,onCreated:s}){const[n,r]=l.useState(""),[a,o]=l.useState(""),[i,d]=l.useState(""),[m,p]=l.useState(""),[c,u]=l.useState(""),[x,h]=l.useState(["PROSPECT"]),[b,f]=l.useState(!1),[g,y]=l.useState(!0),[j,v]=l.useState(!1),[T,k]=l.useState(null),w=async()=>{k(null);const A=n.trim().toLowerCase();if(!A.includes("@")){k("A valid email is required");return}v(!0);try{const E=await re("createContact",{email:A,firstName:a,lastName:i,companyName:m,jobTitle:c,categories:x,isPseudoContact:b}),C=(E==null?void 0:E.contactId)||"";if(ce.success(`Contact created${A?`: ${A}`:""}`),g){const N=ce.loading("Backfilling Gmail (last 7 days)â¦");try{const S=await re("manualSyncGmail",{backfillDays:7}),O=(S==null?void 0:S.stored)??0,R=(S==null?void 0:S.cold)??0,z=Math.max(O-R,0);ce.success(O>0?`Pulled ${z} CRM email${z===1?"":"s"}${R>0?` (${R} cold archived)`:""}`:"No new emails to pull",{id:N})}catch(S){console.warn("Backfill sync failed:",S),ce.error("Gmail backfill failed â contact was still created",{id:N})}}s(C,A)}catch(E){k((E==null?void 0:E.message)||"Failed to create contact"),v(!1)}},I="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:border-primary";return e.jsxs(Cs,{title:"New Contact",subtitle:"Manual CRM entry",onClose:j?()=>{}:t,footer:e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{onClick:t,disabled:j,className:"text-muted-foreground hover:text-foreground",style:{padding:"8px 14px",borderRadius:8,fontSize:13},children:"Cancel"}),e.jsxs("button",{onClick:w,disabled:j||!n.trim(),className:"bg-primary text-primary-foreground disabled:opacity-50",style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",borderRadius:8,fontSize:13,fontWeight:500},children:[j&&e.jsx(fe,{className:"animate-spin",style:{width:14,height:14}}),"Create contact"]})]}),children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Email *"}),e.jsx("input",{type:"email",autoFocus:!0,value:n,onChange:A=>r(A.target.value),placeholder:"[email protected]",className:I})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"First name"}),e.jsx("input",{value:a,onChange:A=>o(A.target.value),className:I})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Last name"}),e.jsx("input",{value:i,onChange:A=>d(A.target.value),className:I})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Company"}),e.jsx("input",{value:m,onChange:A=>p(A.target.value),className:I})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Job title"}),e.jsx("input",{value:c,onChange:A=>u(A.target.value),className:I})]}),e.jsx(h0,{value:x,onChange:h}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--muted-foreground, #999)",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:b,onChange:A=>f(A.target.checked)}),"Pseudo-contact (sender/notification address, not a person)"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--muted-foreground, #999)",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:g,onChange:A=>y(A.target.checked)}),"Backfill emails from this address (last 7 days)"]}),T&&e.jsx("div",{className:"bg-red-500/10 text-red-400 text-xs",style:{padding:8,borderRadius:6},children:T})]})}function f$({tech:t,highlight:s}){const n=s?"bg-primary/15 text-primary font-medium":"bg-muted text-muted-foreground";return e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${n}`,children:t})}function g$({clientId:t}){var u;const[s,n]=l.useState(null),[r,a]=l.useState(!1),[o,i]=l.useState(!1),[d,m]=l.useState(null);l.useEffect(()=>{if(!t)return;a(!0);const x=Ge(Re(ge,"contacts"),Ve("clientIds","array-contains",t),Tt(10));Ze(x).then(async h=>{if(!h.empty)for(const b of h.docs){const f=Ge(Re(ge,"contactEnrichments"),Ve("contactId","==",b.id),Nt("enrichedAt","desc"),Tt(1)),g=await Ze(f);if(!g.empty){n({id:g.docs[0].id,...g.docs[0].data()});return}}}).catch(h=>console.error("Failed to load company enrichment:",h)).finally(()=>a(!1))},[t]);const p=async()=>
480{if(!t){m("Client ID is required for enrichment.");return}i(!0),m(null);try{await re("autoEnrichCompany",{clientId:t});const x=Ge(Re(ge,"contacts"),Ve("clientIds","array-contains",t),Tt(10)),h=await Ze(x);for(const b of h.docs){const f=Ge(Re(ge,"contactEnrichments"),Ve("contactId","==",b.id),Nt("enrichedAt","desc"),Tt(1)),g=await Ze(f);if(!g.empty){n({id:g.docs[0].id,...g.docs[0].data()});break}}}catch(x){m(x.message||"Enrichment failed")}finally{i(!1)}};if(r)return e.jsxs("div",{className:"py-2",children:[e.jsx(De,{title:"Enrichment"}),e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Loading..."})]});const c=s==null?void 0:s.company;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(De,{title:"Enrichment"}),e.jsx("button",{onClick:p,disabled:o,className:"text-xs font-medium px-3 py-1 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors",children:o?"Enriching...":s?"Re-Enrich":"Enrich"})]}),d&&e.jsx("p",{className:"text-xs text-red-400 mb-2",children:d}),!s&&!o&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:'No enrichment data. Click "Enrich" to pull company data via a linked contact.'}),s&&c&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-accent rounded-lg p-3 space-y-2.5",children:[(c.name||c.isShopify)&&e.jsxs("div",{className:"flex items-center gap-2",children:[c.name&&e.jsx("span",{className:"text-sm font-medium text-foreground",children:c.name}),c.isShopify&&c.shopifyPlan&&e.jsxs("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-green-500/15 text-green-400",children:["Shopify ",c.shopifyPlan]})]}),c.description&&e.jsx("p",{className:"text-xs text-muted-foreground leading-snug",children:c.description}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs",children:[c.industry&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Industry:"})," ",c.industry]}),c.employeeRange&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Size:"})," ",c.employeeRange]}),c.revenueRange&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Revenue:"})," ",c.revenueRange]}),c.fundingStage&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Funding:"})," ",c.fundingStage]}),c.foundedYear&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Est:"})," ",c.foundedYear]}),c.domain&&e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Domain:"})," ",c.domain]}),c.linkedinUrl&&e.jsx("a",{href:c.linkedinUrl,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"LinkedIn"})]}),c.technologies&&c.technologies.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1 border-t border-border",children:c.technologies.map(x=>e.jsx(f$,{tech:x,highlight:x.toLowerCase().includes("shopify")},x))})]}),((u=s.ai)==null?void 0:u.contactSummary)&&e.jsxs("div",{className:"bg-accent rounded-lg p-3",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground font-medium mb-1",children:"AI Summary (via contact)"}),e.jsx("p",{className:"text-xs text-foreground leading-relaxed",children:s.ai.contactSummary})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Enriched ",nt(s.enrichedAt)," via ",s.provider]})]})]})}function b$({score:t}){if(t==null)return null;const s=t>=80?"text-green-500":t>=50?"text-yellow-500":"text-red-500";return e.jsx("span",{className:`text-xs font-semibold ${s}`,children:t})}function y$({level:t}){if(!t)return null;const s={observe:"bg-blue-500/15 text-blue-400",suggest:"bg-yellow-500/15 text-yellow-400",draft:"bg-orange-500/15 text-orange-400",act:"bg-red-500/15 text-red-400"};return e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${s[t]||"bg-muted text-muted-foreground"}`,children:t})}function Yh({items:t,emptyText:s}){return!t||t.length===0?e.jsx("span",{className:"text-muted-foreground text-xs italic",children:s||"none"}):e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:t.map(n=>e.jsx("span",{className:"text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full",children:n},n))})}function j$({onBack:t,onLogoClick:s}){const{rows:n,loading:r,error:a,updateRow:o,deleteRow:i}
480=Xt({collectionName:"clients",orderByField:"name",orderDirection:"asc"}),[d,m]=l.useState(""),[p,c]=l.useState("all"),[u,x]=l.useState(null),[h,b]=l.useState(null),[f,g]=l.useState(""),[y,j]=l.useState(new Map),[v,T]=l.useState([]),[k,w]=l.useState(!1),[I,A]=l.useState(!1);l.useEffect(()=>{if(n.length===0)return;const q=new Map;Ze(Re(ge,"contacts")).then(P=>{P.docs.forEach(U=>{(U.data().clientIds||[]).forEach(M=>{q.set(M,(q.get(M)||0)+1)})}),j(new Map(q))})},[n.length]);const E=l.useCallback(async q=>{try{const P=Ge(Re(ge,"contacts"),Ve("clientIds","array-contains",q)),U=await Ze(P);T(U.docs.map(V=>{const M=V.data();return{id:V.id,name:`${(M==null?void 0:M.firstName)||""} ${(M==null?void 0:M.lastName)||""}`.trim(),email:(M==null?void 0:M.email)||"",clientIds:(M==null?void 0:M.clientIds)||[]}}))}catch(P){console.error("Error reloading selected contacts:",P),ce.error("Failed to load contacts. Please try again later.")}},[]);l.useEffect(()=>{if(!u){T([]);return}E(u.id)},[u==null?void 0:u.id,E]);const C=l.useMemo(()=>{let q=n;return p==="active"?q=q.filter(P=>P.notionPageId):p==="imported"?q=q.filter(P=>P.hubspotCompanyId&&!P.notionPageId):p==="has-domains"?q=q.filter(P=>(P.domains||[]).length>0):p==="no-domains"&&(q=q.filter(P=>(P.domains||[]).length===0)),q=q.filter(Js(d,P=>[P.name,P.companyName,P.displayId,P.domains,P.slackChannels,P.hubspotCompanyId])),q},[n,d,p]),N=l.useMemo(()=>({all:n.length,active:n.filter(q=>q.notionPageId).length,imported:n.filter(q=>q.hubspotCompanyId&&!q.notionPageId).length,"has-domains":n.filter(q=>(q.domains||[]).length>0).length,"no-domains":n.filter(q=>(q.domains||[]).length===0).length}),[n]),S=(q,P)=>{b(q),g(P)},O=l.useCallback(async()=>{if(!u||!h)return;const q=["supportHealthScore","supportTicketVolume"],P=["creditPriceCents"];let U;P.includes(h)?U=f===""?null:Math.round(Number(f)*100):q.includes(h)?U=f===""?null:Number(f):U=f||null,await o(u.id,{[h]:U}),x({...u,[h]:U}),b(null)},[u,h,f,o]),R=l.useCallback(async(q,P)=>{u&&(await o(u.id,{[q]:P}),x({...u,[q]:P}))},[u,o]),z=l.useCallback(async q=>{if(!u)return;const U={...u.trust||{level:"observe",permissions:{canSendEmail:!1,canSendSlack:!1,canCreateTasks:!1,canUpdateBilling:!1,canEngageContacts:!1},escalateTo:null,updatedAt:new Date,updatedBy:"manual"},level:q,updatedAt:new Date,updatedBy:"manual"};await o(u.id,{trust:U}),x({...u,trust:U})},[u,o]),D=l.useCallback(async(q,P)=>{if(!u||!u.trust)return;const U={...u.trust,permissions:{...u.trust.permissions,[q]:P},updatedAt:new Date,updatedBy:"manual"};await o(u.id,{trust:U}),x({...u,trust:U})},[u,o]),L={editField:h,editValue:f,onEdit:S,onSave:O,onEditValueChange:g},$=[{key:"all",label:"All"},{key:"active",label:"Active"},{key:"imported",label:"Imported"},{key:"has-domains",label:"Has Domains"},{key:"no-domains",label:"No Domains"}];return e.jsxs(hn,{title:"Companies",count:C.length,loading:r,error:a,searchValue:d,onSearchChange:m,onBack:t,onLogoClick:s,onCreate:()=>w(!0),children:[e.jsx("div",{className:"flex gap-1.5 mb-4 overflow-x-auto pb-1",style:{scrollbarWidth:"none"},children:$.map(({key:q,label:P})=>e.jsxs("button",{onClick:()=>c(q),className:p===q?"bg-primary text-primary-foreground":"bg-card text-muted-foreground border border-border",style:{padding:"4px 12px",borderRadius:9999,fontSize:12,fontWeight:500,whiteSpace:"nowrap",transition:"all 0.15s"},children:[P," (",N[q]||0,")"]},q))}),e.jsxs("div",{className:"space-y-2",children:[C.map(q=>{var U;const P=y.get(q.id)||0;return e.jsx("button",{onClick:()=>x(q),className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:q.displayId}),e.jsx(y$,{level:(U=q.trust)==null?void 0:U.level}),e.jsx(b$,{score:q.supportHealthScore}),P>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[P," contact",P!==1?"s":""]})]}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:q.companyName||q.name}),q.companyName&&q.companyName!==q.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:q.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[(q.domains||[]).slice(0,3).map(V=>e.jsx("span",{className:"text-[11px] bg-muted text-muted-foreground px-1.5 py-0.5 rounded",children:V},V)),(q.domains||[]).length>3&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["+",q.domains.length-3]}),(q.slackChannels||[]).length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["#",q.slackChannels[0],q.slackChannels.length>1?` +${q.slackChannels.length-1}`:""]})]})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:nt(q.createdAt)})]})},q.id)}),C.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No companies found"})]}),u&&e.jsxs(Cs,{title:u.companyName||u.name,subtitle:`${u.displayId} · ${u.name}`,onClose:()=>{x(null),b(null)},footer:e.jsx(nr,{onDelete:async()=>{await i(u.id),x(null)}}),children:[e.jsx(De,{title:"Company Details"}),e.jsx(oe,{label:"Company Name",value:u.companyName||"",field:"companyName",...L}),e.jsx(oe,{label:"Internal Name",value:u.name,field:"name",...L}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Domains"}),e.jsx(Yh,{items:u.domains||[],emptyText:"no domains"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Slack Channels"}),e.jsx(Yh,{items:u.slackChannels||[]})]}
480),e.jsx(oe,{label:"HubSpot Company ID",value:u.hubspotCompanyId||"",field:"",...L,readOnly:!0}),e.jsx(De,{title:"Contacts"}),v.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No linked contacts"}):e.jsx("div",{className:"space-y-1.5",children:v.map(q=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm text-foreground",children:q.name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:q.email})]}),e.jsx("button",{onClick:async()=>{const P=(q.clientIds||[]).filter(U=>U!==u.id);await Gs(async()=>{const{doc:U,updateDoc:V,serverTimestamp:M}=await import("./vendor-firebase-Cr-z2ntb.js").then(F=>F.R);return{doc:U,updateDoc:V,serverTimestamp:M}},[]).then(({doc:U,updateDoc:V,serverTimestamp:M})=>V(U(ge,"contacts",q.id),{clientIds:P,updatedAt:M()})),await E(u.id)},className:"text-muted-foreground hover:text-red-500",style:{fontSize:16,lineHeight:1,padding:"0 4px"},title:"Remove from company",children:"Ã"})]},q.id))}),e.jsx("button",{onClick:()=>A(!0),className:"bg-card border border-border text-foreground hover:bg-accent",style:{padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:500,marginTop:6},children:"+ Add contact"}),I&&e.jsx(w$,{clientId:u.id,excludeContactIds:new Set(v.map(q=>q.id)),onClose:()=>A(!1),onAdded:async()=>{await E(u.id)}}),e.jsx(g$,{clientId:u.id}),e.jsx(De,{title:"Support Health"}),e.jsx(oe,{label:"Health Score",value:u.supportHealthScore!=null?String(u.supportHealthScore):"",field:"supportHealthScore",...L,numeric:!0}),e.jsx(oe,{label:"Ticket Volume",value:u.supportTicketVolume!=null?String(u.supportTicketVolume):"",field:"supportTicketVolume",...L,numeric:!0}),e.jsx(oe,{label:"Top Issue",value:u.supportTopIssue||"",field:"supportTopIssue",...L}),e.jsx(oe,{label:"Last Synced",value:u.supportLastSynced||"",field:"",...L,readOnly:!0}),e.jsx(De,{title:"Activity"}),e.jsx(oe,{label:"Last Activity",value:nt(u.lastActivityAt),field:"",...L,readOnly:!0}),e.jsx(oe,{label:"Last Communication",value:nt(u.lastCommunicationAt),field:"",...L,readOnly:!0}),e.jsx(De,{title:"Trust (Candlelight)"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Trust Level"}),e.jsx("div",{className:"flex gap-1.5 mt-1.5",children:["observe","suggest","draft","act"].map(q=>{var P;return e.jsx("button",{onClick:()=>z(q),className:(((P=u.trust)==null?void 0:P.level)||"observe")===q?"bg-primary text-primary-foreground":"bg-card text-foreground border border-border",style:{padding:"4px 12px",borderRadius:9999,fontSize:13,fontWeight:500,transition:"all 0.15s"},children:q},q)})})]}),u.trust&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2 mt-2",children:[["canSendEmail","Send Email"],["canSe
480ndSlack","Send Slack"],["canCreateTasks","Create Tasks"],["canUpdateBilling","Update Billing"],["canEngageContacts","Engage Contacts"]].map(([q,P])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:P}),e.jsx("button",{onClick:()=>D(q,!u.trust.permissions[q]),className:u.trust.permissions[q]?"bg-primary":"bg-border",style:{width:40,height:24,borderRadius:12,position:"relative",transition:"background-color 0.2s"},children:e.jsx("span",{style:{position:"absolute",top:4,left:u.trust.permissions[q]?20:4,width:16,height:16,borderRadius:8,backgroundColor:"white",transition:"left 0.2s"}})})]},q))}),e.jsx(oe,{label:"Escalate To",value:u.trust.escalateTo||"",field:"trust.escalateTo",...L})]}),e.jsx(De,{title:"Billing"}),e.jsx(oe,{label:"Credit Price",value:u.creditPriceCents!=null?String(u.creditPriceCents):"",field:"creditPriceCents",...L,currency:!0}),e.jsx(oe,{label:"Currency",value:u.currency||"",field:"currency",...L,options:["","cad","usd","eur"],onDirectSave:R}),e.jsx(oe,{label:"Stripe Customer ID",value:u.stripeCustomerId||"",field:"stripeCustomerId",...L}),e.jsx(oe,{label:"Subscription Status",value:u.subscriptionStatus||"",field:"",...L,readOnly:!0}),e.jsx(De,{title:"Metadata"}),e.jsx(oe,{label:"Created",value:nt(u.createdAt),field:"",...L,readOnly:!0}),e.jsx(oe,{label:"Updated",value:nt(u.updatedAt),field:"",...L,readOnly:!0})]}),k&&e.jsx(v$,{onClose:()=>w(!1),onCreated:q=>{w(!1),setTimeout(()=>{const P=n.find(U=>U.id===q);P&&x(P)},600)}})]})}function v$({onClose:t,onCreated:s}){const[n,r]=l.useState(""),[a,o]=l.useState(""),[i,d]=l.useState(""),[m,p]=l.useState(""),[c,u]=l.useState(!1),[x,h]=l.useState(null),b=y=>y.split(/[\s,]+/).map(j=>j.trim()).filter(j=>j.length>0),f=async()=>{h(null);const y=n.trim();if(!y){h("Name is required");return}u(!0);try{const j=await re("createCompany",{name:y,companyName:a.trim()||void 0,domains:b(i),slackChannels:b(m)}),v=(j==null?void 0:j.clientId)||"",T=(j==null?void 0:j.displayId)||"";ce.success(`Company created${T?`: ${T}`:""}`),s(v)}catch(j){h((j==null?void 0:j.message)||"Failed to create company"),u(!1)}},g="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:border-primary";return e.jsxs(Cs,{title:"New Company",subtitle:"Manual CRM entry",onClose:c?()=>{}:t,footer:e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{onClick:t,disabled:c,className:"text-muted-foreground hover:text-foreground",style:{padding:"8px 14px",borderRadius:8,fontSize:13},children:"Cancel"}),e.jsxs("button",{onClick:f,disabled:c||!n.trim(),className:"bg-primary text-primary-foreground disabled:opacity-50",style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",borderRadius:8,fontSize:13,fontWeight:500},children:[c&&e.jsx(fe,{className:"animate-spin",style:{width:14,height:14}}),"Create company"]})]}),children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Internal Name *"}),e.jsx("input",{autoFocus:!0,value:n,onChange:y=>r(y.target.value),placeholder:"#slack-channel or short key",className:g}),e.jsx("p",{className:"text-[11px] text-muted-foreground",style:{marginTop:2},children:"Internal identifier â usually matches the Slack channel."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Company Name"}),e.jsx("input",{value:a,onChange:y=>o(y.target.value),placeholder:"e.g. Acme Corporation Inc.",className:g})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Domains"}),e.jsx("input",{value:i,onChange:y=>d(y.target.value),placeholder:"acme.com, acme.shopify.com",className:g})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Slack Channels"}),e.jsx("input",{value:m,onChange:y=>p(y.target.value),placeholder:"acme, acme-internal",className:g})]}),x&&e.jsx("div",{className:"bg-red-500/10 text-red-400 text-xs",style:{padding:8,borderRadius:6},children:x})]})}function w$({clientId:t,excludeContactIds:s,onClose:n,onAdded:r}){const[a,o]=l.useState(""),[i,d]=l.useState([]),[m,p]=l.useState(!0),[c,u]=l.useState(null);l.useEffect(()=>{Ze(Re(ge,"contacts")).then(b=>{d(b.docs.map(f=>{const g=f.data();return{id:f.id,name:`${g.firstName||""} ${g.lastName||""}`.trim(),email:g.email||"",clientIds:g.clientIds||[]}}
480)),p(!1)})},[]);const x=l.useMemo(()=>{const b=a.trim().toLowerCase();return i.filter(f=>!s.has(f.id)).filter(f=>!b||f.name.toLowerCase().includes(b)||f.email.toLowerCase().includes(b)).slice(0,50)},[i,s,a]),h=async b=>{u(b.id);try{const f=Array.from(new Set([...b.clientIds||[],t])),{doc:g,updateDoc:y,serverTimestamp:j}=await Gs(async()=>{const{doc:v,updateDoc:T,serverTimestamp:k}=await import("./vendor-firebase-Cr-z2ntb.js").then(w=>w.R);return{doc:v,updateDoc:T,serverTimestamp:k}},[]);await y(g(ge,"contacts",b.id),{clientIds:f,updatedAt:j()}),await r(),ce.success("Contact added")}catch(f){ce.error((f==null?void 0:f.message)||"Failed to add contact")}finally{u(null)}};return e.jsxs(Cs,{title:"Add Contact",subtitle:"Link an existing contact to this company",onClose:n,children:[e.jsx("input",{autoFocus:!0,value:a,onChange:b=>o(b.target.value),placeholder:"Search by name or emailâ¦",className:"w-full px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:border-primary"}),m?e.jsxs("div",{className:"flex items-center justify-center py-6 text-muted-foreground text-sm",children:[e.jsx(fe,{className:"animate-spin mr-2",style:{width:14,height:14}}),"Loading contactsâ¦"]}):x.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",style:{marginTop:8},children:"No matching contacts"}):e.jsx("div",{className:"space-y-1",style:{marginTop:8,maxHeight:360,overflowY:"auto"},children:x.map(b=>e.jsxs("button",{onClick:()=>h(b),disabled:c===b.id,className:"w-full bg-card border border-border rounded-lg p-2 text-left hover:bg-accent disabled:opacity-50",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm text-foreground",children:b.name||"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:b.email})]}),c===b.id?e.jsx(fe,{className:"animate-spin",style:{width:14,height:14}}):e.jsx("span",{className:"text-xs text-primary",children:"+ Add"})]},b.id))})]})}function lo(t,s,n=300){const[r,a]=l.useState(t),o=l.useRef(t),i=l.useRef(!1),d=l.useRef(null),m=l.useRef(s);l.useEffect(()=>{m.current=s},[s]),l.useEffect(()=>{t!==o.current&&!i.current&&a(t),o.current=t},[t]);const p=l.useCallback(u=>{i.current=!0,a(u),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{i.current=!1,m.current(u)},n)},[n]),c=l.useCallback(()=>{d.current&&(clearTimeout(d.current),d.current=null),i.current&&(i.current=!1,m.current(r))},[r]);return l.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]),[r,p,c]}const f0=[{value:"email",label:"Email"},{value:"linkedin",label:"LinkedIn"},{value:"phone",label:"Phone"},{value:"task",label:"Task"}],N$=[{value:"",label:"No condition (always)"},{value:"opened_no_reply",label:"Opened but no reply"},{value:"no_open",label:"Did not open"},{value:"clicked_no_reply",label:"Clicked but no reply"},{value:"replied",label:"Replied"},{value:"bounced",label:"Bounced"}],Gh=["{{firstName}}","{{lastName}}","{{companyName}}","{{jobTitle}}","{{domain}}","{{industry}}","{{outreachAngle}}","{{icpFitScore}}"];function k$({step:t,index:s,total:n,onUpdate:r,onRemove:a,onMoveUp:o,onMoveDown:i,sequenceGoal:d,allSteps:m}){var O;const[p,c]=l.useState(!1),[u,x]=l.useState(!1),[h,b,f]=lo(t.subject||"",R=>r({subject:R})),[g,y,j]=lo(t.body||"",R=>r({body:R})),[v,T,k]=lo(t.linkedinSubject||"",R=>r({linkedinSubject:R})),[w,I,A]=lo(t.linkedinMessage||"",R=>r({linkedinMessage:R})),[E,C,N]=lo(t.instructions||"",R=>r({instructions:R})),S={email:"â",linkedin:"ð",phone:"ð",task:"ð"};return e.jsxs("div",{className:"bg-accent rounded-lg border border-border overflow-hidden",children:[e.jsxs("button",{onClick:()=>c(!p),className:"w-full flex items-center gap-2 p-3 text-left hover:bg-accent/80 transition-colors",children:[e.jsx("span",{className:"text-xs font-mono text-muted-foreground w-6",children:t.stepNumber}),e.jsx("span",{className:"text-sm",children:S[t.channel]||"?"}),e.jsx("span",{className:"text-xs font-medium text-foreground flex-1 truncate",children:t.channel==="email"?t.subject||"Untitled email":t.channel==="linkedin"?t.linkedinMessage||t.instructions||"LinkedIn step":t.instructions||`${t.channel} step`}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[t.delayDays>0?`+${t.delayDays}d`:"",t.delayHours>0?`${t.delayHours}h`:"",t.delayDays===0&&t.delayHours===0?"immediate":""]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p?"â´":"â¾"})]}),p&&e.jsxs("div",{className:"px-3 pb-3 space-y-2 border-t border-border pt-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Channel"}),e.jsx("select",{value:t.channel,onChange:R=>r({channel:R.target.value}),className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground",children:f0.map(R=>e.jsx("option",{value:R.value,children:R.label},R.value))})]}),e.jsxs("div",{className:"w-16",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Days"}),e.jsx("input",{type:"number",min:0,value:t.delayDays,onChange:R=>r({delayDays:parseInt(R.target.value)||0}),className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground"})]}),e.jsxs("div",{className:"w-16",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Hours"}),e.jsx("input",{type:"number",min:0,max:23,value:t.delayHours,onChange:R=>r({delayHours:parseInt(R.target.value)||0}),className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Condition"}),e.jsx("select",{value:((O=t.condition)==null?void 0:O.type)||"",onChange:R=>r({condition:R.target.value?{type:R.target.value,lookbackSteps:1}:null}),className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground",children:N$.map(R=>e.jsx("option",{value:R.value,children:R.label},R.value))})]}),t.channel==="email"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:async()=>{x(!0);try{const R=m.filter(D=>D.channel==="email"&&D.stepNumber<t.stepNumber).map(D=>
480D.subject).filter(Boolean),z=await re("aiGenerateStepCopy",{channel:t.channel,stepNumber:t.stepNumber,totalSteps:n,sequenceGoal:d||"",previousStepSubjects:R});z.subject&&r({subject:z.subject}),z.body&&r({body:z.body})}catch(R){console.error("AI copy gen failed:",R)}finally{x(!1)}},disabled:u,className:"w-full text-[10px] font-medium py-1 rounded bg-primary/10 text-primary hover:bg-primary/20 disabled:opacity-50 transition-colors mb-1",children:u?"Generating...":"AI Generate Copy"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Subject"}),e.jsx("input",{value:h,onChange:R=>b(R.target.value),onBlur:f,placeholder:"Email subject line...",className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Body (HTML)"}),e.jsx("div",{className:"flex gap-1 flex-wrap",children:Gh.slice(0,4).map(R=>e.jsx("button",{onClick:()=>y(g+" "+R),className:"text-[9px] px-1 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:R},R))})]}),e.jsx("textarea",{value:g,onChange:R=>y(R.target.value),onBlur:j,placeholder:"<p>Hi {{firstName}},</p>...",rows:5,className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground font-mono resize-y"})]})]}),t.channel==="linkedin"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:async()=>{x(!0);try{const R=await re("aiGenerateStepCopy",{channel:t.channel,stepNumber:t.stepNumber,totalSteps:n,sequenceGoal:d||""});R.instructions&&r({linkedinMessage:R.instructions})}catch(R){console.error("AI copy gen failed:",R)}finally{x(!1)}},disabled:u,className:"w-full text-[10px] font-medium py-1 rounded bg-primary/10 text-primary hover:bg-primary/20 disabled:opacity-50 transition-colors mb-1",children:u?"Generating...":"AI Generate Message"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Action Type"}),e.jsxs("select",{value:t.linkedinActionType||"connection_request",onChange:R=>r({linkedinActionType:R.target.value}),className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground",children:[e.jsx("option",{value:"connection_request",children:"Connection Request"}),e.jsx("option",{value:"direct_message",children:"Direct Message"}),e.jsx("option",{value:"inmail",children:"InMail"})]})]}),t.linkedinActionType==="inmail"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Subject"}),e.jsx("input",{value:v,onChange:R=>T(R.target.value),onBlur:k,placeholder:"InMail subject line...",className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Message"}),e.jsx("div",{className:"flex gap-1 flex-wrap",children:Gh.slice(0,4).map(R=>e.jsx("button",{onClick:()=>I(w+" "+R),className:"text-[9px] px-1 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:R},R))})]}),e.jsx("textarea",{value:w,onChange:R=>I(R.target.value),onBlur:A,placeholder:t.linkedinActionType==="connection_request"?"Hi {{firstName}}, I noticed...":t.linkedinActionType==="inmail"?"Hi {{firstName}}, I wanted to reach out about...":"Hi {{firstName}}, thanks for connecting...",rows:4,className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground resize-y"}),(t.linkedinActionType||"connection_request")==="connection_request"&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:2},children:e.jsxs("span",{style:{fontSize:10,fontWeight:500,color:w.length>300?"#f87171":"#9ca3af"},children:[w.length," / 300"]})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Instructions (optional notes)"}),e.jsx("textarea",{value:E,onChange:R=>C(R.target.value),onBlur:N,placeholder:"Additional instructions for manual execution...",rows:2,className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground resize-y"})]})]}),t.channel!=="email"&&t.channel!=="linkedin"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:async()=>{x(!0);try{const R=await re("aiGenerateStepCopy",{channel:t.channel,stepNumber:t.stepNumber,totalSteps:n,sequenceGoal:d||""});R.instructions&&r({instructions:R.instructions})}catch(R){console.error("AI copy gen failed:",R)}finally{x(!1)}},disabled:u,className:"w-full text-[10px] font-medium py-1 rounded bg-primary/10 text-primary hover:bg-primary/20 disabled:opacity-50 transition-colors mb-1",children:u?"Generating...":"AI Generate Instructions"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-muted-foreground",children:"Instructions"}),e.jsx("textarea",{value:E,onChange:R=>C(R.target.value),onBlur:N,placeholder:t.channel==="phone"?"Call and mention...":"Task description...",rows:3,className:"w-full text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground resize-y"})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:o,disabled:s===0,className:"text-[10px] px-2 py-0.5 rounded bg-muted text-muted-foreground disabled:opacity-30",children:"â"}
480),e.jsx("button",{onClick:i,disabled:s===n-1,className:"text-[10px] px-2 py-0.5 rounded bg-muted text-muted-foreground disabled:opacity-30",children:"â"})]}),e.jsx("button",{onClick:a,className:"text-[10px] px-2 py-0.5 rounded bg-red-500/10 text-red-400 hover:bg-red-500/20",children:"Remove Step"})]})]})]})}function S$({steps:t,onChange:s,sequenceGoal:n,senderType:r}){const[a,o]=l.useState(""),[i,d]=l.useState(!1),m=f=>({stepNumber:t.length+1,channel:f,delayDays:t.length===0?0:2,delayHours:0,subject:f==="email"?"":null,body:f==="email"?"":null,textBody:null,instructions:f!=="email"&&f!=="linkedin"?"":null,condition:null,linkedinActionType:f==="linkedin"?"connection_request":null,linkedinMessage:f==="linkedin"?"":null,linkedinSubject:null,abTestId:null,abVariant:null}),p=f=>{const g=m(f);s([...t,g])},c=(f,g)=>{const y=t.map((j,v)=>v===f?{...j,...g}:j);s(y)},u=f=>{const g=t.filter((y,j)=>j!==f).map((y,j)=>({...y,stepNumber:j+1}));s(g)},x=(f,g,y)=>{const j=g+y;if(j<0||j>=f.length)return f;const v=[...f];return[v[g],v[j]]=[v[j],v[g]],v.map((T,k)=>({...T,stepNumber:k+1}))},h=(f,g)=>{const y=x(t,f,g);s(y)},b=async()=>{if(a.trim()){d(!0);try{const f=await re("aiGenerateSequence",{goal:a,senderType:r||"mailjet"});f.steps&&f.steps.length>0&&s(f.steps)}catch(f){console.error("AI sequence generation failed:",f)}finally{d(!1)}}};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"bg-accent rounded-lg p-2.5 space-y-1.5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground font-medium",children:"AI Sequence Builder"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{value:a,onChange:f=>o(f.target.value),placeholder:'e.g. "Book discovery calls with Shopify Plus DTC brands"',className:"flex-1 text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground"}),e.jsx("button",{onClick:b,disabled:i||!a.trim(),className:"text-[10px] font-medium px-3 py-1.5 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors whitespace-nowrap",children:i?"Building...":"Generate"})]})]}),t.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground italic py-2",children:"No steps yet. Use AI to generate a sequence or add steps manually."}),t.map((f,g)=>e.jsx(k$,{step:f,index:g,total:t.length,onUpdate:y=>c(g,y),onRemove:()=>u(g),onMoveUp:()=>h(g,-1),onMoveDown:()=>h(g,1),sequenceGoal:n||a,allSteps:t},`${f.stepNumber}-${g}`)),e.jsx("div",{className:"flex flex-wrap gap-2 pt-3 pb-2",children:f0.map(f=>e.jsxs("button",{onClick:()=>p(f.value),className:"text-xs font-medium px-3 py-1.5 rounded-md bg-muted text-muted-foreground hover:bg-accent hover:text-foreground transition-colors",children:["+ ",f.label]},f.value))})]})}const C$=new Set(["firstName","lastName","fullName","email","jobTitle","phone","seniority","department","location","linkedinUrl","companyName","domain","industry","employeeRange","revenueRange","fundingStage","technologies","shopifyPlan","icpFitScore","outreachAngle","contactSummary","senderName","senderFirstName","senderEmail"]),Kh=/\{\{(\w+)\}\}/g;function ma(t,s){if(!t)return;Kh.lastIndex=0;let n;for(;(n=Kh.exec(t))!==null;)s.add(n[1])}function T$(t){const s=new Set;for(const n of t||[])ma(n.subject,s),ma(n.body,s),ma(n.textBody,s),ma(n.instructions,s),ma(n.linkedinSubject,s),ma(n.linkedinMessage,s);return[...s]}function A$(t){const s=T$(t),n=[],r=[];for(const a of s)(C$.has(a)?n:r).push(a);return{builtIn:n,custom:r}}function E$({open:t,sequenceName:s,contactName:n,builtIn:r,custom:a,enrolling:o,onCancel:i,onConfirm:d}){const[m,p]=l.useState({});l.useEffect(()=>{if(t){const x={};for(const h of a)x[h]="";p(x)}},[t,a]);const c=l.useMemo(()=>a.every(x=>(m[x]||"").trim().length>0),[a,m]),u=()=>{if(!c||o)return;const x={};for(const h of a)x[h]=(m[h]||"").trim();d(x)};return e.jsx(br,{open:t,onOpenChange:x=>{x||i()},children:e.jsxs(yr,{children:[e.jsxs(jr,{children:[e.jsx(vr,{children:"Fill in sequence variables"}),e.jsxs(wr,{children:["Enrolling ",e.jsx("span",{className:"font-medium text-foreground",children:n})," ","in ",e.jsx("span",{className:"font-medium text-foreground",children:s}),"."]})]}),r.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground mb-1.5",children:"Auto-populated from CRM"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(x=>e.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:`{{${x}}}`},x))})]}),a.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:"Required for this contact"}),a.map(x=>e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-mono text-foreground",children:`{{${x}}}`}),e.jsx("input",{value:m[x]||"",onChange:h=>p(b=>({...b,[x]:h.target.value})),placeholder:`Value for ${x}...`,className:"w-full mt-0.5 text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground",autoF
480ocus:x===a[0]})]},x))]}),e.jsxs(Gr,{children:[e.jsx("button",{onClick:i,disabled:o,className:"text-xs font-medium px-3 py-1.5 rounded-md bg-muted text-muted-foreground hover:bg-accent disabled:opacity-50 transition-colors",children:"Cancel"}),e.jsx("button",{onClick:u,disabled:!c||o,className:"text-xs font-medium px-3 py-1.5 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors",children:o?"Enrolling...":"Enroll"})]})]})})}const I$={active:{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80"},paused:{backgroundColor:"rgba(249,115,22,0.15)",color:"#fb923c"},completed:{backgroundColor:"rgba(59,130,246,0.15)",color:"#60a5fa"},replied:{backgroundColor:"rgba(168,85,247,0.15)",color:"#c084fc"},bounced:{backgroundColor:"rgba(239,68,68,0.15)",color:"#f87171"},manual_exit:{backgroundColor:"rgba(120,120,120,0.15)",color:"#9ca3af"},meeting_booked:{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80"},unsubscribed:{backgroundColor:"rgba(239,68,68,0.15)",color:"#f87171"}},R$={sent:"#4ade80",failed:"#f87171",pending_approval:"#facc15"};function D$({sequenceId:t,sequenceName:s,sequenceSteps:n}){const[r,a]=l.useState([]),[o,i]=l.useState(!0),[d,m]=l.useState(!1),[p,c]=l.useState(null),[u,x]=l.useState(null),[h,b]=l.useState(null),[f,g]=l.useState(""),[y,j]=l.useState([]),[v,T]=l.useState(!1),[k,w]=l.useState(null),[I,A]=l.useState(!1),E=l.useRef(null),C=l.useRef();l.useEffect(()=>{const V=M=>{E.current&&!E.current.contains(M.target)&&A(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[]);const N=(V,M)=>{const F=M.toLowerCase();return V.filter(W=>(W.firstName||"").toLowerCase().includes(F)||(W.lastName||"").toLowerCase().includes(F)||(W.email||"").toLowerCase().includes(F)||(W.companyName||"").toLowerCase().includes(F)||(W.websiteUrl||"").toLowerCase().includes(F))},S=l.useCallback(async V=>{if(V.length<2){j([]);return}T(!0);try{const F=(await Ze(Re(ge,"contacts"))).docs.map(_=>({id:_.id,..._.data()})),W=N(F,V).slice(0,10);j(W),A(W.length>0)}catch(M){console.error("Contact search failed:",M)}finally{T(!1)}},[]),O=l.useRef(!1),R=V=>{if(g(V),O.current){O.current=!1;return}w(null),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>S(V),300)},z=V=>{O.current=!0,w(V),g(`${V.firstName} ${V.lastName} (${V.email})`),A(!1)},D=async()=>{if(!t){console.error("Invalid sequenceId provided");return}i(!0);try{const V=Ge(Re(ge,"sequenceEnrollments"),Ve("sequenceId","==",t),Nt("createdAt","desc")),M=await Ze(V);a(M.docs.map(F=>({id:F.id,...F.data()})))}catch(V){console.error("Failed to load enrollments:",V)}finally{i(!1)}};l.useEffect(()=>{D()},[t]);const L=()=>{g(""),w(null),j([])},$=async V=>{if(k){m(!0),x(null);try{await re("enrollContact",{sequenceId:t,contactId:k.id,variables:Object.keys(V).length?V:void 0}),L(),b(null),await D()}catch(M){x(M.message||"Enrollment failed")}finally{m(!1)}}},q=async()=>{if(!k)return;const V=A$(n);V.custom.length===0?await $({}):(x(null),b(V))},P=async(V,M)=>{const F=r;a(M==="remove"?W=>W.filter(_=>_.id!==V):W=>W.map(_=>_.id===V?{..._,status:M==="pause"?"paused":"active"}:_));try{await re(M==="pause"?"pauseEnrollment":M==="resume"?"resumeEnrollment":"removeEnrollment",{enrollmentId:V}),await D()}catch(W){x(W.message||`${M} failed`),a(F)}},U=async(V,M)=>{c(V);try{await re("logManualStep",{enrollmentId:V,stepNumber:M,note:"Completed manually"}),await D()}catch(F){x(F.message||"Log step failed")}finally{c(null)}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",ref:E,children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:f,onChange:V=>R(V.target.value),onFocus:()=>y.length>0&&A(!0),placeholder:"Search by name, email, company, or domain...",className:"flex-1 text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground"}),e.jsx("button",{onClick:q,disabled:d||!k,className:"text-xs font-medium px-3 py-1.5 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors",children:d?"Enrolling...":"Enroll"})]}),I&&e.jsx("div",{className:"absolute z-50 left-0 right-0 top-full mt-1 bg-background border border-border rounded-lg shadow-lg max-h-48 overflow-y-auto",children:y.map(V=>e.jsxs("button",{onClick:()=>z(V),className:"w-full text-left px-3 py-2 hover:bg-accent transition-colors border-b border-border last:border-b-0",children:[e.jsxs("div",{className:"text-xs font-medium text-foreground",children:[V.firstName," ",V.lastName]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:[V.email,V.companyName,V.websiteUrl].filter(
480Boolean).join(" · ")})]},V.id))}),v&&e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Searching..."})]}),u&&e.jsx("p",{className:"text-xs text-red-400",children:u}),o&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Loading enrollments..."}),!o&&r.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contacts enrolled yet."}),r.map(V=>{const F=(V.stepHistory||[]).some(W=>W.status==="pending_approval")?(V.stepHistory||[]).find(W=>W.status==="pending_approval"):null;return e.jsxs("div",{className:"bg-accent rounded-lg",style:{padding:12,display:"flex",flexDirection:"column",gap:8,border:"1px solid var(--border)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:10,fontWeight:600,padding:"2px 6px",borderRadius:4,...I$[V.status]||{backgroundColor:"rgba(120,120,120,0.15)",color:"#9ca3af"}},children:V.status}),e.jsxs("span",{style:{fontSize:12,fontWeight:500},children:[V.contactFirstName," ",V.contactLastName]})]}),e.jsxs("span",{style:{fontSize:10,color:"#9ca3af"},children:["Step ",V.currentStepNumber]})]}),e.jsxs("div",{style:{fontSize:12,color:"#9ca3af"},children:[V.contactEmail,V.nextStepScheduledAt&&V.status==="active"&&e.jsxs("span",{style:{marginLeft:8},children:["Next: ",nt(V.nextStepScheduledAt)]})]}),(V.stepHistory||[]).length>0&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2},children:(V.stepHistory||[]).map((W,_)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:"#9ca3af"},children:[e.jsxs("span",{style:{width:16,textAlign:"right"},children:[W.stepNumber,"."]}),e.jsx("span",{children:W.channel}),e.jsx("span",{style:{color:R$[W.status]||"#9ca3af"},children:W.status}),W.manualNote&&e.jsx("span",{style:{fontStyle:"italic"},children:W.manualNote})]},_))}),e.jsxs("div",{style:{display:"flex",gap:6,paddingTop:4},children:[V.status==="active"&&e.jsx("button",{onClick:()=>P(V.id,"pause"),disabled:p===V.id,style:{fontSize:10,padding:"2px 8px",borderRadius:4,backgroundColor:"rgba(249,115,22,0.1)",color:"#fb923c",border:"none",cursor:"pointer"},children:"Pause"}),V.status==="paused"&&e.jsx("button",{onClick:()=>P(V.id,"resume"),disabled:p===V.id,style:{fontSize:10,padding:"2px 8px",borderRadius:4,backgroundColor:"rgba(34,197,94,0.1)",color:"#4ade80",border:"none",cursor:"pointer"},children:"Resume"}),["active","paused"].includes(V.status)&&e.jsx("button",{onClick:()=>P(V.id,"remove"),disabled:p===V.id,style:{fontSize:10,padding:"2px 8px",borderRadius:4,backgroundColor:"rgba(239,68,68,0.1)",color:"#f87171",border:"none",cursor:"pointer"},children:"Remove"}),F&&e.jsxs("button",{onClick:()=>U(V.id,F.stepNumber),disabled:p===V.id,style:{fontSize:10,padding:"2px 8px",borderRadius:4,backgroundColor:"rgba(96,165,250,0.1)",color:"#60a5fa",border:"none",cursor:"pointer"},children:["Log Step ",F.stepNumber," Done"]})]})]},V.id)}),e.jsx(E$,{open:!!h,sequenceName:s,contactName:k?`${k.firstName||""} ${k.lastName||""}`.trim()||k.email:"",builtIn:(h==null?void 0:h.builtIn)||[],custom:(h==null?void 0:h.custom)||[],enrolling:d,onCancel:()=>{d||b(null)},onConfirm:V=>{$(V)}})]})}const M$={pending_review:{backgroundColor:"rgba(250,204,21,0.15)",color:"#facc15"},approved:{backgroundColor:"rgba(59,130,246,0.15)",color:"#60a5fa"},sending:{backgroundColor:"rgba(59,130,246,0.15)",color:"#60a5fa"},sent:{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80"},failed:{backgroundColor:"rgba(239,68,68,0.15)",color:"#f87171"},rejected:{backgroundColor:"rgba(120,120,120,0.15)",color:"#9ca3af"}},P$={connection_request:"Connection Request",direct_message:"Direct Message",inmail:"InMail"},L$={resolved:{backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80"},pending:{backgroundColor:"rgba(250,204,21,0.15)",color:"#facc15"},not_found:{backgroundColor:"rgba(239,68,68,0.15)",color:"#f87171"}};function z$({sequenceId:t,sequenceName:s}){const[n,r]=l.useState([]),[a,o]=l.useState(!0),[i,d]=l.useState(null),[m,p]=l.useState(null),[c,u]=l.useState(!1),[x,h]=l.useState(null),b=async()=>{o(!0);try{const y=Ge(Re(ge,"linkedinActionQueue"),Ve("sequenceId","==",t),Nt("createdAt","desc")),j=await Ze(y);r(j.docs.map(v=>({id:v.id,...v.data()})))}catch(y){console.error("Failed to load LinkedIn actions:",y)}finally{o(!1)}};l.useEffect(()=>{b()},[t]);const f=n.filter(y=>y.status==="pending_review"),g=async(y,j)=>{const v=y.length>1;v?u(!0):p(y[0]),d(null);const T=n;r(k=>k.map(w=>y.includes(w.id)?{...w,status:j==="approve"?"approved":"rejected"}:w));try{await re("approveLinkedInActions",{actionIds:y,action:j}),await b()}catch(k){d(k.message||`${j} failed`),r(T)}finally{v?u(!1):p(null)}};return e.jsxs("div",{className:"space-y-3",children:[f.length>0&&e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderRadius:8,backgroundColor:"rgba(250,204,21,0.08)",border:"1px solid rgba(250,204,21,0.2)"},children:[e.jsxs("span",{style:{fontSize:12,color:"#facc15",fontWeight:500},children:[f.length," pending review"]}),e.jsx("button",{onClick:()=>g(f.map(y=>y.id),"approve"),disabled:c,style:{fontSize:10,fontWeight:600,padding:"4px 12px",borderRadius:6,backgroundColor:"rgba(34,197,94,0.15)",color:"#4ade80",border:"none",cursor:c?"not-allowed":"pointer",opacity:c?.5:1},children:c?"Approving...":"Approve All Pending"})]}),i&&e.jsx("p",{className:"text-xs text-red-400",children:i}),a&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Loading LinkedIn actions..."}),!a&&n.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No LinkedIn actions queued for this sequence."}),n.map(y=>e.jsxs("div",{className:"bg-accent rounded-lg",style:{padding:12,display:"flex",flexDirection:"column",gap:8,border:"1px solid var(--border)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:10,fontWeight:600,padding:"2px 6px",borderRadius:4,...M$[y.status]||{backgroundColor:"rgba(120,120,120,0.15)",color:"#9ca3af"}},children:y.status.replace("_"," ")}),e.jsx("span",{style:{fontSize:12,fontWeight:500},children:y.contactName})]}),e.jsx("span",{style:{fontSize:10,fontWeight:500,padding:"2px 6px",borderRadius:4,backgroundColor:"rgba(96,165,250,0.12)",color:"#60a5fa"},children:P$[y.actionType]||y.actionType})]}),e.jsxs("div",{style:{fontSize:11,color:"#9ca3af"},children:[y.contactEmail,y.contactCompanyName&&e.jsx("span",{style:{marginLeft:8},children:y.contactCompanyName})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsxs("span",{style:{fontSize:10,fontWeight:500,padding:"1px 5px",borderRadius:4,...L$[y.profileLookupStatus]||{backgroundColor:"rgba(120,120,120,0.15)",color:"#9ca3af"}},children:["Profile: ",y.profileLookupStatus]}),y.profileLookupStatus==="not_found"&&e.jsx("span",{style:{fontSize:10,
480color:"#f87171",fontWeight:500},children:"-- LinkedIn profile not found, action may fail"})]}),e.jsxs("button",{onClick:()=>h(x===y.id?null:y.id),style:{textAlign:"left",background:"none",border:"none",cursor:"pointer",padding:0,fontSize:11,color:"#d1d5db",lineHeight:"1.4"},children:[y.resolvedSubject&&e.jsxs("div",{style:{fontWeight:600,marginBottom:2,color:"#e5e7eb"},children:["Subject: ",y.resolvedSubject]}),x===y.id?y.resolvedMessage:y.resolvedMessage.length>120?y.resolvedMessage.slice(0,120)+"...":y.resolvedMessage,y.resolvedMessage.length>120&&e.jsx("span",{style:{fontSize:10,color:"#60a5fa",marginLeft:4},children:x===y.id?"less":"more"})]}),e.jsxs("div",{style:{fontSize:10,color:"#6b7280",display:"flex",gap:12},children:[y.createdAt&&e.jsxs("span",{children:["Created: ",nt(y.createdAt)]}),y.sentAt&&e.jsxs("span",{children:["Sent: ",nt(y.sentAt)]}),y.reviewedBy&&e.jsxs("span",{children:["Reviewed by: ",y.reviewedBy]})]}),y.error&&e.jsxs("div",{style:{fontSize:10,color:"#f87171",backgroundColor:"rgba(239,68,68,0.08)",padding:"4px 8px",borderRadius:4},children:["Error: ",y.error]}),y.status==="pending_review"&&e.jsxs("div",{style:{display:"flex",gap:6,paddingTop:4},children:[e.jsx("button",{onClick:()=>g([y.id],"approve"),disabled:m===y.id,style:{fontSize:10,padding:"3px 10px",borderRadius:4,backgroundColor:"rgba(34,197,94,0.12)",color:"#4ade80",border:"none",cursor:m===y.id?"not-allowed":"pointer",opacity:m===y.id?.5:1,fontWeight:500},children:"Approve"}),e.jsx("button",{onClick:()=>g([y.id],"reject"),disabled:m===y.id,style:{fontSize:10,padding:"3px 10px",borderRadius:4,backgroundColor:"rgba(239,68,68,0.1)",color:"#f87171",border:"none",cursor:m===y.id?"not-allowed":"pointer",opacity:m===y.id?.5:1,fontWeight:500},children:"Reject"})]})]},y.id))]})}const Qh={active:"bg-green-500/15 text-green-400",draft:"bg-yellow-500/15 text-yellow-400",paused:"bg-orange-500/15 text-orange-400",archived:"bg-muted text-muted-foreground"},O$={mailjet:"Shared (Mailjet)",gmail:"Personal (Gmail)"};function $$({status:t}){const s=Qh[t]||Qh.draft;return e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${s}`,children:t})}const Jh={display:"block",fontSize:10,fontWeight:600,color:"#9ca3af",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"},Zh={width:"100%",fontSize:12,padding:"6px 8px",borderRadius:6,border:"1px solid var(--border)",backgroundColor:"var(--background)",color:"var(--foreground)"};function Gi({label:t,hint:s,checked:n,onChange:r,disabled:a}){return e.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:8,padding:"5px 0",cursor:a?"not-allowed":"pointer",opacity:a?.5:1},children:[e.jsx("input",{type:"checkbox",checked:n,disabled:a,onChange:o=>r(o.target.checked),style:{marginTop:2,flexShrink:0}}),e.jsxs("span",{children:[e.jsx("span",{style:{fontSize:12,color:"var(--foreground)"},children:t}),e.jsx("span",{style:{display:"block",fontSize:10,color:"#9ca3af",marginTop:2,lineHeight:1.4},children:s})]})]})}const Xh={name:"",description:null,status:"draft",sequenceType:"prospecting",senderType:"mailjet",senderGmailUserId:null,steps:[],abTests:[],stats:{totalEnrolled:0,totalCompleted:0,totalReplied:0,totalMeetingsBooked:0,replyRate:0,meetingRate:0},settings:{sendWindow:{startHour:9,endHour:17},sendDays:[1,2,3,4,5],respectTimezone:!0,maxConcurrentPerDay:25,exitOnReply:!0,exitOnMeetingBooked:!0,tracking:!0,plainTextOnly:!1,aiPersonalization:!0,sendAsEmail:null}};function B$({onBack:t,onLogoClick:s}){var q,P,U,V,M,F,W,_,G,B,Y;const{rows:n,loading:r,error:a,createRow:o,updateRow:i,deleteRow:d}=Xt({collectionName:"outreachSequences",orderByField:"updatedAt",orderDirection:"desc"}),[m,p]=l.useState(""),[c,u]=l.useState("all"),[x,h]=l.useState(null),[b,f]=l.useState(null),[g,y]=l.useState(""),[j,v]=l.useState("builder"),[T,k]=l.useState(null),[w,I]=l.useState(!1),[A,E]=l.useState([]);l.useEffect(()=>{re("listGmailAccounts").then(J=>E((J==null?void 0:J.accounts)??[])).catch(()=>{})},[]);const C=l.useMemo(()=>{let J=n;return c!=="all"&&(J=J.filter(H=>H.status===c)),J=J.filter(Js(m,H=>[H.name,H.description])),J},[n,m,c]),N=l.useMemo(()=>{const J={all:n.length};for(const H of n)J[H.status]=(J[H.status]||0)+1;return J},[n]),S=(J,H)=>{f(J),y(H)},O=l.useCallback(async()=>
480{!x||!b||(await i(x.id,{[b]:g||null}),h({...x,[b]:g||null}),f(null))},[x,b,g,i]),R=l.useCallback(async(J,H)=>{x&&(await i(x.id,{[J]:H}),h({...x,[J]:H}))},[x,i]),z=l.useCallback(async(J,H)=>{if(!x)return;const Z={...x.settings,[J]:H};await i(x.id,{settings:Z}),h({...x,settings:Z})},[x,i]),D=async()=>{const H={id:await o({...Xh,name:"New Sequence",createdBy:"manual"}),...Xh,name:"New Sequence",createdBy:"manual",contactOwner:null,createdAt:new Date,updatedAt:new Date};h(H)},L=l.useCallback(J=>{x&&(h(H=>H&&{...H,steps:J}),i(x.id,{steps:J}).catch(H=>{console.error("Failed to persist sequence steps:",H)}))},[x,i]),$={editField:b,editValue:g,onEdit:S,onSave:O,onEditValueChange:y};return e.jsxs(hn,{title:"Sequences",count:C.length,loading:r,error:a,searchValue:m,onSearchChange:p,onBack:t,onLogoClick:s,onCreate:D,children:[e.jsx("div",{className:"flex gap-1.5 mb-4 overflow-x-auto pb-1",style:{scrollbarWidth:"none"},children:["all","active","draft","paused","archived"].map(J=>e.jsxs("button",{onClick:()=>u(J),className:c===J?"bg-primary text-primary-foreground":"bg-card text-muted-foreground border border-border",style:{padding:"4px 12px",borderRadius:9999,fontSize:12,fontWeight:500,whiteSpace:"nowrap",transition:"all 0.15s"},children:[J==="all"?"All":J," (",N[J]||0,")"]},J))}),e.jsxs("div",{className:"space-y-2",children:[C.map(J=>{var H,Z,Q;return e.jsx("button",{onClick:()=>{h(J),v("builder")},className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx($$,{status:J.status}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:J.sequenceType}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:O$[J.senderType]||J.senderType})]}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:J.name}),J.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:J.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[((H=J.steps)==null?void 0:H.length)||0," steps"]}),e.jsxs("span",{children:[((Z=J.stats)==null?void 0:Z.totalEnrolled)||0," enrolled"]}),((Q=J.stats)==null?void 0:Q.replyRate)>0&&e.jsxs("span",{className:"text-green-400",children:[J.stats.replyRate,"% reply"]})]})]})})},J.id)}),C.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No sequences found"})]}),x&&e.jsxs(Cs,{title:x.name||"Untitled Sequence",subtitle:`${x.status} · ${((q=x.steps)==null?void 0:q.length)||0} steps · ${((P=x.stats)==null?void 0:P.totalEnrolled)||0} enrolled`,onClose:()=>{h(null),f(null)},footer:e.jsx(nr,{onDelete:async()=>{await d(x.id),h(null)}}),children:[e.jsx(De,{title:"Details"}),e.jsx(oe,{label:"Name",value:x.name||"",field:"name",...$}),e.jsx(oe,{label:"Description",value:x.description||"",field:"description",...$,multiline:!0}),e.jsx(oe,{label:"Status",value:x.status,field:"status",...$,options:["draft","active","paused","archived"],onDirectSave:R}),e.jsx(oe,{label:"Type",value:x.sequenceType,field:"sequenceType",...$,options:["prospecting","nurture","re-engagement","custom"],onDirectSave:R}),e.jsx(oe,{label:"Sender",value:x.senderType,field:"senderType",...$,options:["mailjet","gmail"],onDirectSave:R}),x.senderType==="gmail"&&e.jsxs("div",{style:{marginBottom:8},children:[e.jsx("label",{style:{display:"block",fontSize:10,fontWeight:600,color:"#9ca3af",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Gmail Account"}),e.jsxs("select",{value:x.senderGmailUserId||"",onChange:J=>{const H=J.target.value||null;R("senderGmailUserId",H)},style:{width:"100%",fontSize:12,padding:"6px 8px",borderRadius:6,border:"1px solid var(--border)",backgroundColor:"var(--background)",color:"var(--foreground)"},children:[e.jsx("option",{value:"",children:"Select Gmail account..."}),A.map(J=>e.jsx("option",{value:J.id,children:J.email},J.id))]}
480),A.length===0&&e.jsx("p",{style:{fontSize:10,color:"#f87171",marginTop:4},children:"No Gmail accounts connected. Connect one in Settings."}),x.senderGmailUserId&&!A.find(J=>J.id===x.senderGmailUserId)&&A.length>0&&e.jsx("p",{style:{fontSize:10,color:"#fb923c",marginTop:4},children:"Selected account no longer found."})]}),e.jsx(De,{title:"Sending Behaviour"}),e.jsxs("div",{style:{marginBottom:8},children:[e.jsx(Gi,{label:"Plain text only",hint:"Sends one text/plain body â no HTML part, no images, no signature markup. Uses each step's plain-text body verbatim. Forces tracking off.",checked:((U=x.settings)==null?void 0:U.plainTextOnly)===!0,onChange:J=>z("plainTextOnly",J)}),e.jsx(Gi,{label:"Open & click tracking",hint:((V=x.settings)==null?void 0:V.plainTextOnly)===!0?"Unavailable in plain-text mode â there is no HTML to instrument.":"Adds a 1Ã1 open pixel and routes every link through the click tracker.",checked:((M=x.settings)==null?void 0:M.tracking)!==!1&&((F=x.settings)==null?void 0:F.plainTextOnly)!==!0,disabled:((W=x.settings)==null?void 0:W.plainTextOnly)===!0,onChange:J=>z("tracking",J)}),e.jsx(Gi,{label:"AI personalised first line",hint:"Prepends a generated opening sentence. Turn off for hand-written emails.",checked:((_=x.settings)==null?void 0:_.aiPersonalization)!==!1,onChange:J=>z("aiPersonalization",J)}),e.jsx(Gi,{label:"Exit on reply",hint:"Stops the sequence as soon as the contact replies â no further steps fire.",checked:((G=x.settings)==null?void 0:G.exitOnReply)!==!1,onChange:J=>z("exitOnReply",J)}),e.jsxs("div",{style:{marginTop:10},children:[e.jsx("label",{style:Jh,children:"Max sends per day"}),e.jsx("input",{type:"number",min:0,defaultValue:((B=x.settings)==null?void 0:B.maxConcurrentPerDay)??25,onBlur:J=>{var Q;const H=parseInt(J.target.value,10),Z=Number.isFinite(H)&&H>=0?H:25;Z!==((Q=x.settings)==null?void 0:Q.maxConcurrentPerDay)&&z("maxConcurrentPerDay",Z)},style:Zh},`cap-${x.id}`),e.jsx("p",{style:{fontSize:10,color:"#9ca3af",marginTop:4},children:"Across the whole sequence. Resets at 00:00 UTC. 0 = no limit."})]}),x.senderType==="gmail"&&e.jsxs("div",{style:{marginTop:10},children:[e.jsx("label",{style:Jh,children:"Send as (alias)"}),e.jsx("input",{type:"email",defaultValue:((Y=x.settings)==null?void 0:Y.sendAsEmail)||"",placeholder:"Leave blank to use the account's own address",onBlur:J=>{var Z;const H=J.target.value.trim()||null;H!==(((Z=x.settings)==null?void 0:Z.sendAsEmail)||null)&&z("sendAsEmail",H)},style:Zh},`alias-${x.id}`),e.jsx("p",{style:{fontSize:10,color:"#9ca3af",marginTop:4},children:"Must be a verified send-as alias on the selected Gmail account, or the send is rejected."})]})]}),e.jsx("div",{className:"flex gap-1.5 mt-3 mb-2",children:["builder","enrollments","linkedin"].map(J=>e.jsx("button",{onClick:()=>v(J),className:j===J?"bg-primary text-primary-foreground":"bg-card text-muted-foreground border border-border",style:{padding:"4px 12px",borderRadius:9999,fontSize:12,fontWeight:500},children:J==="builder"?"Steps":J==="enrollments"?"Enrollments":"LinkedIn"},J))}),j==="builder"&&e.jsx(S$,{steps:x.steps||[],onChange:L,sequenceGoal:x.description,senderType:x.senderType}),j==="enrollments"&&e.jsx(D$,{sequenceId:x.id,sequenceName:x.name,sequenceSteps:x.steps||[]}),j==="linkedin"&&e.jsx(z$,{sequenceId:x.id,sequenceName:x.name}),x.stats&&x.stats.totalEnrolled>0&&e.jsxs(e.Fragment,{children:[e.jsx(De,{title:"Performance"}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,textAlign:"center"},children:[e.jsxs("div",{className:"bg-accent rounded-lg p-2",children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:x.stats.totalEnrolled}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Enrolled"})]}),e.jsxs("div",{className:"bg-accent rounded-lg p-2",children:[e.jsxs("p",{className:"text-lg font-bold text-green-400",children:[x.stats.replyRate,"%"]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Reply Rate"})]}),e.jsxs("div",{className:"bg-accent rounded-lg p-2",children:[e.jsx("p",{className:"text-lg font-bold text-primary",children:x.stats.totalMeetingsBooked}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Meetings"})]})]}),e.jsx("button",{onClick:async()=>{I(!0),k(null);try{const J=await re("aiAnalyzeSequence",{sequenceId:x.id});k(J)}catch(J){console.error("AI analysis failed:",J)}
480finally{I(!1)}},disabled:w,className:"w-full text-xs font-medium py-1.5 rounded-md bg-primary/10 text-primary hover:bg-primary/20 disabled:opacity-50 transition-colors",children:w?"Analyzing...":"AI Analyze Performance"}),T&&e.jsxs("div",{className:"bg-accent rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-foreground leading-relaxed",children:T.analysis}),(T.suggestions||[]).map((J,H)=>e.jsxs("div",{className:"border-t border-border pt-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${J.priority==="high"?"bg-red-500/15 text-red-400":J.priority==="medium"?"bg-yellow-500/15 text-yellow-400":"bg-muted text-muted-foreground"}`,children:J.priority}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Step ",J.stepNumber]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:J.issue}),e.jsx("p",{className:"text-xs text-foreground mt-0.5",children:J.suggestion}),J.newSubject&&e.jsxs("p",{className:"text-xs text-primary mt-0.5 italic",children:['New subject: "',J.newSubject,'"']})]},H))]})]})]})]})}const F$=[{key:"pending_review",label:"Needs review"},{key:"approved",label:"Approved â not sent"},{key:"blocked",label:"Blocked"},{key:"sent",label:"Sent"},{key:"rejected",label:"Rejected"}],ef={0:"#4b5563",1:"#0e7490",2:"#a16207",3:"#15803d",4:"#6d28d9",5:"#be185d"},wd={advance:{bg:"rgba(21,128,61,0.12)",fg:"#15803d",label:"wants to move forward"},objection:{bg:"rgba(161,98,7,0.12)",fg:"#a16207",label:"objection"},question:{bg:"rgba(14,116,144,0.12)",fg:"#0e7490",label:"asking a question"},not_now:{bg:"rgba(75,85,99,0.12)",fg:"#4b5563",label:"not now â accept it"},disqualify:{bg:"rgba(185,28,28,0.12)",fg:"#b91c1c",label:"disqualified"},ooo:{bg:"rgba(75,85,99,0.12)",fg:"#4b5563",label:"auto-reply"}},Nd={backgroundColor:"var(--card)",border:"1px solid var(--border)",borderRadius:8,padding:16,marginBottom:12},Hn=(t,s="var(--foreground)")=>({backgroundColor:t,color:s,border:"none",borderRadius:6,padding:"7px 14px",fontSize:13,cursor:"pointer"});function _$({onBack:t,onLogoClick:s}){const[n,r]=l.useState("pending_review"),[a,o]=l.useState([]),[i,d]=l.useState(!0),[m,p]=l.useState(null),[c,u]=l.useState(new Set),[x,h]=l.useState(null),[b,f]=l.useState(""),[g,y]=l.useState(""),[j,v]=l.useState(null),T=async()=>{d(!0);try{const E=await Ze(Ge(Re(ge,"salesDrafts"),Ve("status","==",n),Nt("generatedAt","desc"),Tt(100)));o(E.docs.map(C=>({id:C.id,...C.data()}))),u(new Set)}catch(E){v(`Load failed: ${E.message}`)}finally{d(!1)}};l.useEffect(()=>{T()},[n]);const k=E=>{const C=new Set(c);C.has(E)?C.delete(E):C.add(E),u(C)},w=async(E,C,N)=>{p(E),v(null);try{await re("reviewSalesDraft",{draftId:E,action:C,editedSubject:N==null?void 0:N.subject,editedBody:N==null?void 0:N.body}),h(null),await T()}catch(S){v(S.message)}finally{p(null)}},I=async E=>{if(c.size!==0){p("dispatch"),v(null);try{const C=await re("dispatchSalesDrafts",{draftIds:Array.from(c),dryRun:E}),N=[`${E?"Dry run â nothing sent.":"Sent"}: ${C.sent}`,`Daily cap ${C.cap}, ${C.alreadySentToday} already sent today, ${C.remainingToday} left.`,...C.skipped.map(S=>`skipped ${S.email}: ${S.reason}`)];v(N.join(` 481`)),E||await T()}catch(C){v(C.message)}finally{p(null)}}},A=l.useMemo(()=>a.filter(E=>E.reviewApproved&&E.lintPassed).length,[a]);return e.jsxs("div",{style:{padding:24,color:"var(--foreground)",maxWidth:980,margin:"0 auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:4},children:[e.jsx("button",{onClick:t,style:Hn("var(--muted)"),children:"â Back"}),e.jsx("h1",{style:{fontSize:20,margin:0,cursor:s?"pointer":"default"},onClick:s,children:"Sales drafts"})]}),e.jsxs("p",{style:{color:"var(--muted-foreground)",fontSize:13,marginTop:4},children:["Approving marks a draft ready. ",e.jsx("strong",{children:"Nothing sends until you dispatch."})]}),e.jsx("div",{style:{display:"flex",gap:8,margin:"16px 0"},children:F$.map(E=>e.jsx("button",{onClick:()=>r(E.key),style:{...Hn(n===E.key?"var(--primary)":"var(--muted)"),color:(n===E.key,"var(--foreground)")},children:E.label},E.key))}),(n==="approved"||n==="pending_review")&&e.jsxs("div",{style:{...Nd,display:"flex",alignItems:"center",gap:12},children:[e.jsxs("span",{style:{fontSize:13},children:[c.size," selected"]}),e.jsx("button",{onClick:()=>I(!0),disabled:!c.size||!!m,style:Hn("var(--muted)"),children:"Dry run"}),e.jsxs("button",{onClick:()=>I(!1),disabled:!c.size||!!m,style:Hn("#16a34a","#fff"),children:["Dispatch ",c.size||""]}),e.jsx("span",{style:{color:"var(--muted-foreground)",fontSize:12},children:"Only approved drafts send. The 25/day cap is shared with every other campaign."})]}),j&&e.jsx("pre",{style:{...Nd,whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:12,color:"#92400e"},children:j}),i&&e.jsx("p",{style:{color:"var(--muted-foreground)"},children:"Loadingâ¦"}),!i&&a.length===0&&e.jsx("p",{style:{color:"var(--muted-foreground)"},children:"Nothing here."}),a.map(E=>{var O,R,z,D;const C=(E.reviewViolations??[]).filter(L=>L.severity==="hard"),N=(E.reviewViolations??[]).filter(L=>L.severity==="warning"),S=x===E.id;return e.jsxs("div",{style:Nd,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:8},children:[(n==="approved"||n==="pending_review")&&e.jsx("input",{type:"checkbox",checked:c.has(E.id),onChange:()=>k(E.id)}),e.jsxs("span",{style:{backgroundColor:`${ef[E.rung]??"#4b5563"}1f`,color:ef[E.rung]??"#4b5563",padding:"2px 8px",borderRadius:4,fontSize:12,fontWeight:600},children:["Rung ",E.rung," · ",E.rungLabel]}),e.jsx("strong",{children:E.contactName||E.contactEmail}),e.jsx("span",{style:{color:"var(--muted-foreground)",fontSize:13},children:E.companyName??E.contactEmail}),E.isReply&&e.jsxs("span",{style:{backgroundColor:((O=wd[E.replyOutcome??""])==null?void 0:O.bg)??"var(--muted)",color:((R=wd[E.replyOutcome??""])==null?void 0:R.fg)??"var(--muted-foreground)",padding:"2px 8px",borderRadius:4,fontSize:12,fontWeight:600},children:["REPLY · ",((z=wd[E.replyOutcome??""])==null?void 0:z.label)??E.replyOutcome]}),E.isReferralAsk&&e.jsxs("span",{style:{backgroundColor:"rgba(161,98,7,0.12)",color:"#a16207",padding:"2px 8px",borderRadius:4,fontSize:12,fontWeight:600},children:["REFERRAL",E.referralProjectName?` · ${E.referralProjectName}`:""]}),E.readyToAdvance&&e.jsxs("span",{style:{backgroundColor:"rgba(109,40,217,0.12)",color:"#6d28d9",padding:"2px 8px",borderRadius:4,fontSize:12},children:["ready to advance ",E.structuralRung," â ",E.intentRung]}
481)]}),e.jsx("div",{style:{fontSize:12,color:"var(--muted-foreground)",marginBottom:8},children:E.reasoning}),E.humanNote&&e.jsxs("div",{style:{marginBottom:10,padding:10,borderRadius:6,background:"rgba(251,191,36,0.18)",color:"#92400e",fontSize:12},children:[e.jsx("strong",{children:"Read before sending:"})," ",E.humanNote]}),E.isReply&&E.replyBody&&e.jsxs("details",{open:!0,style:{marginBottom:10},children:[e.jsx("summary",{style:{cursor:"pointer",fontSize:12,color:"var(--muted-foreground)"},children:"What they said"}),e.jsx("pre",{style:{whiteSpace:"pre-wrap",fontFamily:"ui-monospace, monospace",fontSize:12,background:"rgba(126,204,238,0.10)",borderLeft:"3px solid var(--primary)",padding:10,borderRadius:4,margin:"6px 0 0",color:"var(--foreground)"},children:E.replyBody}),E.objectionVerbatim&&e.jsxs("div",{style:{fontSize:12,color:"#92400e",marginTop:6},children:["Objection captured: â",E.objectionVerbatim,"â â worth adding to the playbook."]})]}),S?e.jsxs(e.Fragment,{children:[e.jsx("input",{value:g,onChange:L=>y(L.target.value),style:{width:"100%",padding:8,marginBottom:8,background:"var(--card)",color:"var(--foreground)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:4}}),e.jsx("textarea",{value:b,onChange:L=>f(L.target.value),rows:14,style:{width:"100%",padding:8,fontFamily:"ui-monospace, monospace",fontSize:13,background:"var(--card)",color:"var(--foreground)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:4}})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{fontSize:13,marginBottom:6},children:[e.jsx("span",{style:{color:"var(--muted-foreground)"},children:"Subject: "}),E.editedSubject??E.subject]}),e.jsx("pre",{style:{whiteSpace:"pre-wrap",fontFamily:"ui-monospace, monospace",fontSize:13,background:"var(--muted)",padding:12,borderRadius:6,margin:0},children:E.editedBody??E.body})]}),C.length>0&&e.jsxs("div",{style:{marginTop:10,padding:10,background:"rgba(185,28,28,0.08)",borderRadius:6},children:[e.jsx("strong",{style:{color:"#b91c1c",fontSize:12},children:"BLOCKED"}),C.map((L,$)=>e.jsxs("div",{style:{fontSize:12,color:"#b91c1c",marginTop:4},children:[e.jsx("em",{children:L.rule}),": â",L.quote,"â â ",L.fix]},$))]}),((D=E.lintHardFailures)==null?void 0:D.length)>0&&e.jsx("div",{style:{marginTop:8,fontSize:12,color:"#b91c1c"},children:E.lintHardFailures.map((L,$)=>e.jsx("div",{children:L},$))}),N.length>0&&e.jsx("div",{style:{marginTop:8,fontSize:12,color:"#92400e"},children:N.map((L,$)=>e.jsxs("div",{children:[L.rule,": ",L.fix]},$))}),e.jsxs("details",{style:{marginTop:10,fontSize:12,color:"var(--muted-foreground)"},children:[e.jsx("summary",{style:{cursor:"pointer"},children:"Placement evidence"}),e.jsx("ul",{style:{margin:"6px 0 0 16px"},children:(E.placementEvidence??[]).map((L,$)=>e.jsx("li",{children:L},$))}),E.reviewerNote&&e.jsxs("div",{style:{marginTop:6},children:["Reviewer: ",E.reviewerNote]}),e.jsxs("div",{style:{marginTop:6},children:["Playbook: ",Object.entries(E.playbookVersions??{}).map(([L,$])=>`${L} v${$}`).join(", ")]})]}),n!=="sent"&&e.jsx("div",{style:{display:"flex",gap:8,marginTop:12},children:S?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>w(E.id,"approve",{subject:g,body:b}),disabled:m===E.id,style:Hn("#16a34a","#fff"),children:"Save & approve"}),e.jsx("button",{onClick:()=>h(null),style:Hn("var(--muted)"),children:"Cancel"})]}):e.jsxs(e.Fragment,{children:[n!=="approved"&&e.jsx("button",{onClick:()=>w(E.id,"approve"),disabled:m===E.id||C.length>0,style:Hn("#16a34a","#fff"),children:"Approve"}),e.jsx("button",{onClick:()=>{h(E.id),y(E.editedSubject??E.subject),f(E.editedBody??E.body)},style:Hn("var(--muted)"),children:"Edit"}),e.jsx("button",{onClick:()=>w(E.id,"reject"),disabled:m===E.id,style:Hn("var(--destructive)","#fff"),children:"Reject"})]})})]},E.id)}),A>0&&n==="pending_review"&&e.jsxs("p",{style:{color:"var(--muted-foreground)",fontSize:12},children:[A," of ",a.length," passed both gates."]})]})}const Al=["discovery","proposal_sent","follow_up","negotiation","closed_won","closed_lost"],pc={discovery:"Discovery",proposal_sent:"Proposal Sent",follow_up:"Follow Up",negotiation:"Negotiation",closed_won:"Closed Won",closed_lost:"Closed Lost"},Wo={discovery:{bg:"rgba(59,130,246,0.15)",text:"#60a5fa"},proposal_sent:{bg:"rgba(168,85,247,0.15)",text:"#c084fc"},follow_up:{bg:"rgba(249,115,22,0.15)",text:"#fb923c"},negotiation:{bg:"rgba(234,179,8,0.15)",text:"#facc15"},closed_won:{bg:"rgba(34,197,94,0.15)",text:"#4ade80"},closed_lost:{bg:"rgba(239,68,68,0.15)",text:"#f87171"}};function Zn(t,s){return new Intl.NumberFormat("en-CA",{style:"currency",currency:s||"cad",minimumFractionDigits:0,maximumFractionDigits:0}).format(t/100)}const g0=4e5,W$=25e5;function tf(t,s){const n=U$(t),r=H$(s),a=q$(r);return{baseFeeCents:n,adSpendFeeCents:a,valueCents:n+a}}function U$(t){return typeof t=="number"&&isFinite(t)&&t>=0?Math.round(t):g0}function H$(t){return isFinite(t)?Math.max(0,t):0}function q$(t){return Math.round(.1*Math.max(0,t-W$))}function V$({stage:t}){const s=Wo[t]||Wo.discovery;return e.jsx("span",{style:{fontSize:10,fontWeight:600,padding:"2px 8px",borderRadius:9999,backgroundColor:s.bg,color:s.text,whiteSpace:"nowrap"},children:pc[t]||t})}function Y$({onClose:t,onCreated:s}){var M;const[n,r]=l.useState(""),[a,o]=l.useState(""),[i,d]=l.useState(""),[m,p]=l.useState(""),[c,u]=l.useState("discovery"),[x,h]=l.useState(""),[b,f]=l.useState(""),[g,y]=l.useState("4000"),[j,v]=l.useState("0"),[T,k]=l.useState(!1),[w,I]=l.useState(""),[A,E]=l.useState([]),[C,N]=l.useState(""),[S,O]=l.useState(!1),[R,z]=l.useState([]),[D,L]=l.useState([]);l.useEffect(()=>{(async()=>{const W=(await Ze(Re(ge,"clients"))).docs.map(_=>({id:_.id,name:_.data().name||_.id}));W.sort((_,G)=>
481_.name.localeCompare(G.name)),E(W)})()},[]),l.useEffect(()=>{if(!a){z([]),d("");return}(async()=>{const F=Ge(Re(ge,"contacts"),Ve("clientIds","array-contains",a)),_=(await Ze(F)).docs.map(G=>{const B=G.data();return{id:G.id,name:`${B.firstName||""} ${B.lastName||""}`.trim()||G.id,email:B.email||""}});_.sort((G,B)=>G.name.localeCompare(B.name)),z(_)})()},[a]),l.useEffect(()=>{if(!a){L([]),p("");return}(async()=>{const F=Ge(Re(ge,"clientProjects"),Ve("clientId","==",a)),_=(await Ze(F)).docs.map(G=>({id:G.id,name:G.data().name||G.id,projectType:G.data().projectType??null}));_.sort((G,B)=>G.name.localeCompare(B.name)),L(_)})()},[a]);const $=l.useMemo(()=>A.filter(Js(C,F=>[F.name])),[A,C]),q=((M=A.find(F=>F.id===a))==null?void 0:M.name)||"",P=D.find(F=>F.id===m),U=((P==null?void 0:P.projectType)||"").toLowerCase()==="marketing",V=async()=>{if(!n.trim()){I("Deal name is required");return}if(!a){I("Client is required");return}k(!0),I("");try{const F={name:n.trim(),clientId:a};i&&(F.contactId=i),m&&(F.projectId=m),c!=="discovery"&&(F.stage=c),x&&(F.expectedCloseDate=x),b.trim()&&(F.notes=b.trim()),U&&(F.baseFeeCents=Math.round((parseFloat(g)||4e3)*100),F.projectedAdSpendCents=Math.round((parseFloat(j)||0)*100));const W=await re("createDeal",F);s((W==null?void 0:W.dealId)||"")}catch(F){I(F.message||"Failed to create deal"),k(!1)}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.75)",padding:16},onClick:t,children:e.jsxs("div",{className:"bg-card border border-border shadow-2xl flex flex-col",style:{maxHeight:"90vh",width:"100%",maxWidth:480,borderRadius:12,overflow:"hidden"},onClick:F=>F.stopPropagation(),children:[e.jsx("div",{className:"bg-primary text-primary-foreground",style:{padding:"16px 20px",flexShrink:0},children:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("h2",{style:{fontSize:18,fontWeight:600},children:"New Deal"}),e.jsx("button",{onClick:t,className:"text-primary-foreground/80 hover:text-primary-foreground",style:{padding:4},children:e.jsx(mt,{style:{width:22,height:22}})})]})}),e.jsxs("div",{style:{overflowY:"auto",minHeight:0,flex:1,padding:"16px 20px"},className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Deal Name *"}),e.jsx("input",{type:"text",value:n,onChange:F=>r(F.target.value),placeholder:"e.g., Q2 Credit Package",className:"w-full mt-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/30"})]}),e.jsxs("div",{style:{position:"relative"},children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Client *"}),e.jsx("input",{type:"text",value:S?C:q,onChange:F=>{N(F.target.value),O(!0)},onFocus:()=>O(!0),placeholder:"Search clients...",className:"w-full mt-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/30"}),S&&e.jsxs("div",{className:"border border-border bg-card",style:{position:"absolute",top:"100%",left:0,right:0,maxHeight:200,overflowY:"auto",borderRadius:8,marginTop:4,zIndex:10},children:[$.length===0&&e.jsx("p",{className:"text-muted-foreground text-sm",style:{padding:"8px 12px"},children:"No clients found"}),$.map(F=>e.jsx("button",{onClick:()=>{o(F.id),N(""),O(!1)},className:"text-foreground hover:bg-accent text-sm",style:{display:"block",width:"100%",textAlign:"left",padding:"8px 12px"},children:F.name},F.id))]})]}),a&&R.length>0&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Contact"}),e.jsxs("select",{value:i,onChange:F=>d(F.target.value),className:"w-full mt-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground",children:[e.jsx("option",{value:"",children:"-- Select contact --"}),R.map(F=>e.jsxs("option",{value:F.id,children:[F.name," ",F.email?`(${F.email})`:""]},F.id))]})]}),a&&D.length>0&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Project"}),e.jsxs("select",{value:m,onChange:F=>p(F.target.value),className:"w-full mt-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground",children:[e.jsx("option",{value:"",children:"-- Select project --"}),D.map(F=>e.jsxs("option",{value:F.id,children:[F.name,(F.projectType||"").toLowerCase()==="marketing"?" (Marketing)":""]},F.id))]})]}),U&&e.jsxs("div",{className:"space-y-3",style:{padding:"12px",borderRadius:8,border:"1px solid var(--border)",backgroundColor:"rgba(120,120,120,0.04)"},children:[e.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Marketing Pricing"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Base Fee (monthly)"}),e.jsx("input",{type:"number",min:"0",step:"100",value:g,onChange:F=>y(F.target.value),className:"w-full mt-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/30"}),e.jsx("p",{className:"text-xs text-muted-foreground",style:{marginTop:2},children:"Defaults to $4,000. Override as needed."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Projected Monthly Ad Spend"}),e.jsx("input",{type:"number",min:"0",step:"100",value:j,onChange:F=>v(F.target.value),className:"w-full mt-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/30"}),e.jsx("p",{className:"text-xs text-muted-foreground",style:{marginTop:2},children:"10% fee applies to spend above $25,000/mo."})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Stage"}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:6},children:Al.map(F=>{const W=Wo[F];return e.jsx("button",{onClick:()=>u(F),style:{fontSize:12,padding:"4px 12px",borderRadius:9999,fontWeight:500,border:"none",cursor:"pointer",backgroundColor:c===F?W.bg:"rgba(120,120,120,0.08)",color:c===F?W.text:"#9ca3af"},children:pc[F]},F)})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Expected Close Date"}),e.jsx("input",{type:"date",value:x,onChange:F=>h(F.target.value),className:"w-full mt-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/30"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("textarea",{value:b,onChange:F=>f(F.target.value),placeholder:"Optional notes...",rows:3,className:"w-full mt-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/30 resize-y"})]}),w&&e.jsx("p",{style:{color:"#f87171",fontSize:13},children:w})]}),e.jsxs("div",{className:"bg-accent border-t border-border",style:{padding:"12px 20px",flexShrink:0,display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx("button",{onClick:t,className:"text-muted-foreground text-sm hover:text-foreground",style:{padding:"8px 16px"},children:"Cancel"}),e.jsx("button",{onClick:V,disabled:T,className:"bg-primary text-primary-foreground",style:{padding:"8px 20px",borderRadius:8,fontSize:13,fontWeight:500,opacity:T?.6:1},children:T?"Creating...":"Create Deal"})]})]})})}function G$({dealId:t,onClose:s}){const[n,r]=l.useState([]),[a,o]=l.useState(""),[i,d]=l.useState(!1),[m,p]=l.useState(""),[c,u]=l.useState(!1);l.useEffect(()=>{(async()=>{const b=(await Ze(Re(ge,"outreachSequences"))).docs.map(f=>({id:f.id,name:f.data().name||f.id}));b.sort((f,g)=>f.name.localeCompare(g.name)),r(b)})()},[]);const x=async()=>
481{if(a){d(!0),p("");try{await re("enrollDealContact",{dealId:t,sequenceId:a}),u(!0),setTimeout(s,1200)}catch(h){p(h.message||"Failed to enroll"),d(!1)}}};return e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.75)",padding:16},onClick:s,children:e.jsxs("div",{className:"bg-card border border-border shadow-2xl",style:{width:"100%",maxWidth:400,borderRadius:12,overflow:"hidden"},onClick:h=>h.stopPropagation(),children:[e.jsx("div",{className:"bg-primary text-primary-foreground",style:{padding:"14px 20px"},children:e.jsx("h3",{style:{fontSize:16,fontWeight:600},children:"Enroll in Sequence"})}),e.jsx("div",{style:{padding:"16px 20px"},className:"space-y-4",children:c?e.jsx("p",{style:{color:"#4ade80",fontSize:14,textAlign:"center",padding:16},children:"Enrolled successfully!"}):e.jsxs(e.Fragment,{children:[e.jsxs("select",{value:a,onChange:h=>o(h.target.value),className:"w-full px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground",children:[e.jsx("option",{value:"",children:"-- Select a sequence --"}),n.map(h=>e.jsx("option",{value:h.id,children:h.name},h.id))]}),m&&e.jsx("p",{style:{color:"#f87171",fontSize:13},children:m}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx("button",{onClick:s,className:"text-muted-foreground text-sm",style:{padding:"8px 16px"},children:"Cancel"}),e.jsx("button",{onClick:x,disabled:i||!a,className:"bg-primary text-primary-foreground",style:{padding:"8px 20px",borderRadius:8,fontSize:13,fontWeight:500,opacity:i||!a?.5:1},children:i?"Enrolling...":"Enroll"})]})]})})]})})}function K$({deal:t,onClose:s,onUpdateStage:n,onUpdate:r,onDelete:a}){const[o,i]=l.useState(null),[d,m]=l.useState(""),[p,c]=l.useState(!1),[u,x]=l.useState(""),[h,b]=l.useState(!1),[f,g]=l.useState(t),[y,j]=l.useState([]);l.useEffect(()=>{g(t)},[t]),l.useEffect(()=>{f.clientId&&(async()=>{const C=Ge(Re(ge,"clientProjects"),Ve("clientId","==",f.clientId)),S=(await Ze(C)).docs.map(O=>({id:O.id,name:O.data().name||O.id,projectType:O.data().projectType??null}));S.sort((O,R)=>O.name.localeCompare(R.name)),j(S)})()},[f.clientId]);const v=(C,N)=>{i(C),m(N)},T=l.useCallback(async()=>{if(!o||!f.id)return;const C=d||null;try{await r(f.id,{[o]:C}),g({...f,[o]:C})}catch(N){console.error("Failed to update deal:",N)}i(null)},[o,d,f,r]),k={editField:o,editValue:d,onEdit:v,onSave:T,onEditValueChange:m},w=f.pricingModel==="marketing",I=async C=>{const N=C.baseFeeCents??f.baseFeeCents,S=C.projectedAdSpendCents??f.projectedAdSpendCents??0,O=tf(N,S),R={pricingModel:"marketing",totalCredits:0,creditPriceCents:0,baseFeeCents:O.baseFeeCents,projectedAdSpendCents:S,adSpendFeeCents:O.adSpendFeeCents,valueCents:O.valueCents};await r(f.id,R),g({...f,...R})},A=C=>{if(C==="closed_lost"){b(!0);return}f.stage!==C&&(g({...f,stage:C}),n(f.id,C))},E=()=>{g({...f,stage:"closed_lost",lostReason:u||null}),b(!1);const C=u||void 0;x(""),n(f.id,"closed_lost",C)};return e.jsxs(e.Fragment,{children:[e.jsxs(Cs,{title:f.name,subtitle:f.clientName||"No client",onClose:s,footer:e.jsx(nr,{onDelete:async()=>{await a(f.id),s()}}),children:[e.jsx(De,{title:"Stage"}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:10,fontWeight:600,color:"#9ca3af",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Current Stage"}),e.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginBottom:8},children:Al.map(C=>{const N=Wo[C];return e.jsx("button",{onClick:()=>A(C),style:{fontSize:11,padding:"3px 10px",borderRadius:9999,border:"none",cursor:"pointer",fontWeight:500,backgroundColor:f.stage===C?N.bg:"rgba(120,120,120,0.08)",color:f.stage===C?N.text:"#9ca3af"},children:pc[C]},C)})}),h&&e.jsxs("div",{style:{marginTop:8},children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Lost Reason"}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:4}
481,children:[e.jsx("input",{autoFocus:!0,type:"text",value:u,onChange:C=>x(C.target.value),placeholder:"Why was this deal lost?",className:"flex-1 px-3 py-2 bg-background border border-border rounded-lg text-sm text-foreground focus:outline-none"}),e.jsx("button",{onClick:E,className:"bg-primary text-primary-foreground",style:{padding:"6px 14px",borderRadius:8,fontSize:13,fontWeight:500},children:"Save"})]})]})]}),e.jsx(De,{title:"Details"}),e.jsx(oe,{label:"Deal Name",value:f.name,field:"name",...k}),e.jsx(oe,{label:"Client",value:f.clientName||"",field:"",...k,readOnly:!0}),e.jsx(oe,{label:"Contact",value:f.contactName?`${f.contactName}${f.contactEmail?` (${f.contactEmail})`:""}`:"",field:"",...k,readOnly:!0}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:10,fontWeight:600,color:"#9ca3af",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Project"}),e.jsxs("select",{value:f.projectId||"",onChange:async C=>{var D;const N=C.target.value||null,S=y.find(L=>L.id===N),O=(S==null?void 0:S.name)||null,R=((S==null?void 0:S.projectType)||"").toLowerCase()==="marketing";let z;if(N&&R){const L=tf(f.baseFeeCents,f.projectedAdSpendCents??0);z={projectId:N,projectName:O,pricingModel:"marketing",totalCredits:0,creditPriceCents:0,baseFeeCents:L.baseFeeCents,projectedAdSpendCents:f.projectedAdSpendCents??0,adSpendFeeCents:L.adSpendFeeCents,valueCents:L.valueCents}}else{let L=0;N&&(await Ze(Ge(Re(ge,"tickets"),Ve("projectId","==",N)))).docs.forEach(P=>{L+=P.data().creditsMax??0});let $=f.creditPriceCents;!$&&f.clientId&&($=((D=(await ps(ut(ge,"clients",f.clientId))).data())==null?void 0:D.creditPriceCents)??2e4),$=$||2e4,z={projectId:N,projectName:O,pricingModel:"development",totalCredits:L,creditPriceCents:$,valueCents:L*$}}await r(f.id,z),g({...f,...z})},style:{width:"100%",fontSize:12,padding:"6px 8px",borderRadius:6,border:"1px solid var(--border)",backgroundColor:"var(--background)",color:"var(--foreground)"},children:[e.jsx("option",{value:"",children:"-- Select project --"}),y.map(C=>e.jsxs("option",{value:C.id,children:[C.name,(C.projectType||"").toLowerCase()==="marketing"?" (Marketing)":""]},C.id))]}),y.length===0&&f.clientId&&e.jsx("p",{style:{fontSize:10,color:"#9ca3af",marginTop:4,fontStyle:"italic"},children:"No projects found for this client."})]}),e.jsx(De,{title:"Value"}),w?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:10,fontWeight:600,color:"#9ca3af",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Base Fee (monthly)"}),e.jsx("input",{type:"number",min:"0",step:"100",defaultValue:((f.baseFeeCents??g0)/100).toString(),onBlur:C=>I({baseFeeCents:Math.round((parseFloat(C.target.value)||4e3)*100)}),style:{width:"100%",fontSize:12,padding:"6px 8px",borderRadius:6,border:"1px solid var(--border)",backgroundColor:"var(--background)",color:"var(--foreground)"}},`bf-${f.baseFeeCents}`)]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:10,fontWeight:600,color:"#9ca3af",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Projected Ad Spend (monthly)"}),e.jsx("input",{type:"number",min:"0",step:"100",defaultValue:((f.projectedAdSpendCents??0)/100).toString(),onBlur:C=>I({projectedAdSpendCents:Math.round((parseFloat(C.target.value)||0)*100)}),style:{width:"100%",fontSize:12,padding:"6px 8px",borderRadius:6,border:"1px solid var(--border)",backgroundColor:"var(--background)",color:"var(--foreground)"}},`as-${f.projectedAdSpendCents}`),e.jsx("p",{style:{fontSize:10,color:"#9ca3af",marginTop:2,fontStyle:"italic"},children:"10% fee applies to spend above $25,000/mo."})]}),e.jsx(oe,{label:"Ad-Spend Fee (monthly)",value:Zn(f.adSpendFeeCents??0,f.currency),field:"",...k,readOnly:!0}),e.jsx(oe,{label:"Value (monthly)",value:f.valueCents?Zn(f.valueCents,f.currency):"",field:"",...k,readOnly:!0}),e.jsx(oe,{label:"Currency",value:(f.currency||"").toUpperCase(),field:"",...k,readOnly:!0})]}):e.jsxs(e.Fragment,{children:[e.jsx(oe,{label:"Value",value:f.valueCents?Zn(f.valueCents,f.currency):"",field:"",...k,readOnly:!0}),e.jsx(oe,{label:"Total Credits",value:f.totalCredits?String(f.totalCredits):"",field:"",...k,readOnly:!0}),e.jsx(oe,{label:"Credit Price",value:f.creditPriceCents?String(f.creditPriceCents):"",field:"",...k,readOnly:!0,currency:!0}),e.jsx(oe,{label:"Currency",value:(f.currency||"").toUpperCase(),field:"",...k,readOnly:!0})]}),e.jsx(De,{title:"Dates"}),e.jsx(oe,{label:"Expected Close Date",value:nt(f.expectedCloseDate),field:"expectedCloseDate",...k}),f.closedAt&&e.jsx(oe,{label:"Closed At",value:nt(f.closedAt),field:"",...k,readOnly:!0}),f.lostReason&&e.jsx(oe,{label:"Lost Reason",value:f.lostReason,field:"lostReason",...k}),e.jsx(De,{title:"Notes"}),e.jsx(oe,{label:"Notes",value:f.notes||"",field:"notes",...k,multiline:!0}),e.jsx(De,{title:"Actions"}),e.jsx("button",{onClick:()=>c(!0),className:"bg-primary text-primary-foreground",style:{padding:"8px 16px",borderRadius:8,fontSize:13,fontWeight:500,width:"100%"},children:"Enroll in Sequence"}),f.sequenceEnrollmentId&&e.jsxs("p",{className:"text-xs text-muted-foreground",style:{marginTop:4},children:["Enrolled: ",f.sequenceEnrollmentId]}),e.jsx(De,{title:"Metadata"}),e.jsx(oe,{label:"Created",value:nt(f.createdAt),field:"",...k,readOnly:!0}),e.jsx(oe,{label:"Updated",value:nt(f.updatedAt),field:"",...k,readOnly:!0})]}),p&&e.jsx(G$,{dealId:f.id,onClose:()=>c(!1)})]})}function Q$({deal:t,onClick:s}){const{attributes:n,listeners:r,setNodeRef:a,transform:o,transition:i,isDragging:d}=sc({id:t.id,data:{type:"deal",deal:t}}),m={transform:lu.Transform.toString(o),transition:i,opacity:d?.4:1};return e.jsx("div",{ref:a,style:m,...n,className:"bg-card border border-border rounded-lg",children:e.jsxs("div",{style:{padding:"10px 12px",display:"flex",alignItems:"flex-start",ga
481p:6},children:[e.jsx("div",{...r,style:{cursor:"grab",paddingTop:2,flexShrink:0},className:"text-muted-foreground",children:e.jsx(Yr,{style:{width:14,height:14}})}),e.jsxs("div",{style:{flex:1,minWidth:0,cursor:"pointer"},onClick:s,children:[e.jsx("p",{className:"text-sm font-medium text-foreground",style:{marginBottom:4,lineHeight:1.3},children:t.name}),t.clientName&&e.jsx("p",{className:"text-xs text-muted-foreground",style:{marginBottom:2},children:t.clientName}),t.contactName&&e.jsx("p",{className:"text-xs text-muted-foreground",style:{marginBottom:2},children:t.contactName}),t.valueCents>0&&e.jsx("p",{className:"text-xs font-semibold text-foreground",style:{marginTop:4},children:Zn(t.valueCents,t.currency)})]})]})})}function J$({deal:t}){return e.jsxs("div",{className:"bg-card border border-primary rounded-lg shadow-xl",style:{padding:"10px 12px",width:220},children:[e.jsx("p",{className:"text-sm font-medium text-foreground",style:{marginBottom:4},children:t.name}),t.clientName&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.clientName}),t.valueCents>0&&e.jsx("p",{className:"text-xs font-semibold text-foreground",style:{marginTop:4},children:Zn(t.valueCents,t.currency)})]})}function Z$({stage:t,deals:s,onDealClick:n}){var d;const{setNodeRef:r,isOver:a}=ou({id:`column-${t}`}),o=Wo[t],i=s.reduce((m,p)=>m+(p.valueCents||0),0);return l.useMemo(()=>s.map(m=>m.id),[s]),e.jsxs("div",{ref:r,style:{minWidth:240,maxWidth:280,flex:"1 0 240px",display:"flex",flexDirection:"column",borderRadius:8,border:a?"2px solid":"1px solid",borderColor:a?o.text:"var(--border)",backgroundColor:a?"rgba(255,255,255,0.02)":"transparent",transition:"border-color 0.15s, background-color 0.15s"},children:[e.jsxs("div",{style:{padding:"10px 12px",borderBottom:"1px solid var(--border)",borderTopLeftRadius:8,borderTopRightRadius:8,backgroundColor:o.bg},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:2},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:o.text},children:pc[t]}),e.jsx("span",{style:{fontSize:11,fontWeight:600,backgroundColor:o.bg,color:o.text,padding:"1px 6px",borderRadius:9999,border:`1px solid ${o.text}33`},children:s.length})]}),i>0&&e.jsx("p",{style:{fontSize:11,color:o.text,opacity:.8},children:Zn(i,((d=s[0])==null?void 0:d.currency)||"cad")})]}),e.jsxs("div",{style:{flex:1,padding:8,display:"flex",flexDirection:"column",gap:6,minHeight:80,overflowY:"auto"},children:[s.map(m=>e.jsx(Q$,{deal:m,onClick:()=>n(m)},m.id)),s.length===0&&e.jsx("p",{className:"text-muted-foreground text-xs",style:{textAlign:"center",padding:"16px 0",opacity:.6},children:"No deals"})]})]})}function X$({onBack:t,onLogoClick:s}){const{rows:n,loading:r,error:a,updateRow:o,deleteRow:i}=Xt({collectionName:"deals",orderByField:"updatedAt",orderDirection:"desc"}),[d,m]=l.useState(""),[p,c]=l.useState("all"),[u,x]=l.useState("list"),[h,b]=l.useState(null),[f,g]=l.useState(!1),[y,j]=l.useState(null),[v,T]=l.useState([]);l.useEffect(()=>{T(n)},[n]);const k=Ho(Rn(Yo,{activationConstraint:{distance:5}}),Rn(Vo)),w=l.useMemo(()=>{let z=v;return p!=="all"&&(z=z.filter(D=>D.stage===p)),z=z.filter(Js(d,D=>[D.name,D.clientName,D.contactName,D.contactEmail,D.projectName,D.notes])),z},[v,d,p]),I=l.useMemo(()=>{const z={discovery:[],proposal_sent:[],follow_up:[],negotiation:[],closed_won:[],closed_lost:[]};w.forEach(D=>{z[D.stage]&&z[D.stage].push(D)});for(const D of Al)z[D].sort((L,$)=>(L.stageOrder||0)-($.stageOrder||0));return z},[w]),A=l.useCallback(async(z,D,L)=>{try{await re("updateDealStage",{dealId:z,stage:D,lostReason:L})}catch($){console.error("Failed to update deal stage:",$)}},[]),E=l.useCallback(z=>{const D=v.find(L=>
481L.id===z.active.id);j(D||null)},[v]),C=l.useCallback(z=>{const{active:D,over:L}=z;if(j(null),!L)return;const $=D.id;let q=null;const P=String(L.id);if(P.startsWith("column-"))q=P.replace("column-","");else{const V=v.find(M=>M.id===P);V&&(q=V.stage)}if(!q)return;const U=v.find(V=>V.id===$);!U||U.stage===q||(T(V=>V.map(M=>M.id===$?{...M,stage:q}:M)),A($,q))},[v,A]),N=l.useCallback(z=>{g(!1)},[]),S=l.useMemo(()=>v.filter(D=>D.stage!=="closed_won"&&D.stage!=="closed_lost").reduce((D,L)=>D+(L.valueCents||0),0),[v]),O=()=>{var z;return e.jsxs(hn,{title:"Deals",count:w.length,loading:r,error:a,searchValue:d,onSearchChange:m,onBack:t,onLogoClick:s,onCreate:()=>g(!0),tabs:[{key:"all",label:"All"},{key:"discovery",label:"Discovery"},{key:"proposal_sent",label:"Proposal Sent"},{key:"follow_up",label:"Follow Up"},{key:"negotiation",label:"Negotiation"},{key:"closed_won",label:"Closed Won"},{key:"closed_lost",label:"Closed Lost"}],activeTab:p,onTabChange:c,children:[e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:12},children:e.jsxs("div",{className:"border border-border",style:{display:"inline-flex",borderRadius:8,overflow:"hidden"},children:[e.jsxs("button",{onClick:()=>x("list"),style:{padding:"6px 12px",display:"flex",alignItems:"center",gap:4,fontSize:12,fontWeight:500,backgroundColor:u==="list"?"var(--primary)":"transparent",color:u==="list"?"var(--primary-foreground)":"var(--muted-foreground)",border:"none",cursor:"pointer"},children:[e.jsx(zm,{style:{width:14,height:14}})," List"]}),e.jsxs("button",{onClick:()=>x("board"),style:{padding:"6px 12px",display:"flex",alignItems:"center",gap:4,fontSize:12,fontWeight:500,backgroundColor:u==="board"?"var(--primary)":"transparent",color:u==="board"?"var(--primary-foreground)":"var(--muted-foreground)",border:"none",cursor:"pointer"},children:[e.jsx(Pm,{style:{width:14,height:14}})," Board"]})]})}),S>0&&e.jsxs("div",{className:"bg-card border border-border rounded-lg",style:{padding:"10px 14px",marginBottom:12,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Active Pipeline Value"}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:Zn(S,((z=v[0])==null?void 0:z.currency)||"cad")})]}),e.jsxs("div",{className:"space-y-2",children:[w.map(D=>e.jsx("button",{onClick:()=>b(D),className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(V$,{stage:D.stage}),D.contactName&&e.jsx("span",{className:"text-xs text-muted-foreground",children:D.contactName})]}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:D.name}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[D.clientName&&e.jsx("span",{children:D.clientName}),D.valueCents>0&&e.jsx("span",{className:"font-semibold text-foreground",children:Zn(D.valueCents,D.currency)}),D.expectedCloseDate&&e.jsxs("span",{children:["Close: ",nt(D.expectedCloseDate)]})]})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:nt(D.updatedAt)})]})},D.id)),w.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No deals found"})]})]})},R=()=>{var z;return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{style:{paddingTop:"var(--spacing-md)",paddingLeft:16,paddingRight:16},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("button",{onClick:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:20,height:20}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Deals Pipeline"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[v.length," deals"]})]}),e.jsxs("button",{onClick:()=>g(!0),className:"bg-primary text-primary-foreground",style:{display:"flex",alignItems:"center",gap:4,padding:"6px 14px",borderRadius:8,fontSize:13,fontWeight:500},children:[e.jsx(Ut,{style:{width:16,height:16}})," New"]})]}),e.jsxs("div",{style:{position:"relative",marginBottom:16,maxWidth:400},children:[e.jsx(Pt,{className:"text-muted-foreground",style:{position:"absolute",left:12,top:"50%",transform:"translateY(-50%)",width:16,height:16,pointerEvents:"none"}}),e.jsx("input",{type:"text",placeholder:"Search deals...",value:d,onChange:D=>m(D.target.value),className:"bg-card border border-border text-foreground placeholder:text-muted-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary/30",style:{width:"100%",paddingLeft:36,paddingRight:16,paddingTop:8,paddingBottom:8,borderRadius:8}})]}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16},children:[e.jsxs("div",{className:"border border-border",style:{display:"inline-flex",borderRadius:8,overflow:"hidden"},children:[e.jsxs("button",{onClick:()=>x("list"),style:{padding:"6px 12px",display:"flex",alignItems:"center",gap:4,fontSize:12,fontWeight:500,backgroundColor:u==="list"?"var(--primary)":"transparent",color:u==="list"?"var(--primary-foreground)":"var(--muted-foreground)",border:"none",cursor:"pointer"},children:[e.jsx(zm,{style:{width:14,height:14}})," List"]}),e.jsxs("button",{onClick:()=>x("board"),style:{padding:"6px 12px",display:"flex",alignItems:"center",gap:4,fontSize:12,fontWeight:500,backgroundColor:u==="board"?"var(--primary)":"transparent",color:u==="board"?"var(--primary-foreground)":"var(--muted-foreground)",border:"none",cursor:"pointer"},children:[e.jsx(Pm,{style:{width:14,height:14}})," Board"]})]}),S>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Pipeline: ",e.jsx("span",{className:"font-semibold text-foreground",children:Zn(S,((z=v[0])==null?void 0:z.currency)||"cad")})]})]}),r?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(fe,{className:"animate-spin mr-2",style:{width:20,height:20}}),"Loading..."]}):a?e.jsx("div",{className:"bg-red-500/10 text-red-400 p-4 rounded-lg text-sm",children:a}):e.jsxs(qo,{sensors:k,collisionDetection:Df,onDragStart:E,onDragEnd:C,children:[e.jsx("div",{style:{display:"flex",gap:12,overflowX:"auto",paddingBottom:16},children:Al.map(D=>e.jsx(Z$,{stage:D,deals:I[D],onDealClick:L=>
481b(L)},D))}),e.jsx(Mf,{children:y?e.jsx(J$,{deal:y}):null})]})]})]})};return e.jsxs(e.Fragment,{children:[u==="list"?O():R(),h&&e.jsx(K$,{deal:h,onClose:()=>b(null),onUpdateStage:A,onUpdate:async(z,D)=>{await o(z,D),b(L=>L?{...L,...D}:null)},onDelete:async z=>{await i(z),b(null)}}),f&&e.jsx(Y$,{onClose:()=>g(!1),onCreated:N})]})}function eB({onBack:t,onLogoClick:s}){const{rows:n,loading:r,error:a,updateRow:o,deleteRow:i}=Xt({collectionName:"project_mappings",orderByField:"projectName",orderDirection:"asc"}),[d,m]=l.useState(""),[p,c]=l.useState(null),[u,x]=l.useState(null),[h,b]=l.useState(""),[f,g]=l.useState(!1),[y,j]=l.useState(""),[v,T]=l.useState(""),[k,w]=l.useState(!1),I=l.useMemo(()=>n.filter(Js(d,D=>[D.id,D.projectName,D.primaryChannel])),[n,d]),A=l.useMemo(()=>n.filter(D=>D.id!==(p==null?void 0:p.id)).map(D=>({id:D.id,label:`${D.projectName} (${D.id})`})),[n,p==null?void 0:p.id]),E=(D,L)=>{x(D),b(L)},C=l.useCallback(async()=>{!p||!u||(await o(p.id,{[u]:h||null}),c({...p,[u]:h||null}),x(null))},[p,u,h,o]);l.useCallback(async(D,L)=>{p&&(await o(p.id,{[D]:L}),c({...p,[D]:L}))},[p,o]);const N=l.useCallback(async D=>{p&&(await o(p.id,{primaryChannel:D.id}),c({...p,primaryChannel:D.id}))},[p,o]),S=l.useCallback(async()=>{p&&(await o(p.id,{primaryChannel:null}),c({...p,primaryChannel:null}))},[p,o]),O=l.useCallback(async()=>{const D=y.replace(/^#/,"").toLowerCase().trim();if(!(!D||!v.trim())){w(!0);try{const L=D.split("-").map($=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ");await qr(ut(ge,"project_mappings",D),{clientName:D,projectName:L,slackChannelId:v.trim(),sunbowlAiProjectId:v.trim(),primaryChannel:null,autoCreated:!1,createdAt:ss(),updatedAt:ss()}),j(""),T(""),g(!1)}finally{w(!1)}}},[y,v]),R={editField:u,editValue:h,onEdit:E,onSave:C,onEditValueChange:b},z=D=>{if(!D)return null;const L=n.find($=>$.id===D);return L?L.projectName:D};return e.jsxs(hn,{title:"Project Mappings",count:I.length,loading:r,error:a,searchValue:d,onSearchChange:m,onBack:t,onLogoClick:s,onCreate:()=>g(!0),children:[e.jsxs("div",{className:"space-y-2",children:[I.map(D=>e.jsx("button",{onClick:()=>c(D),className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:D.projectName}),D.primaryChannel&&e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:11,padding:"2px 8px",borderRadius:4,backgroundColor:"#dbeafe",color:"#1d4ed8",fontWeight:500},children:[e.jsx(cg,{style:{width:10,height:10}}),z(D.primaryChannel)]})]}),e.jsx("p",{className:"text-xs font-mono text-muted-foreground",children:D.id}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Channel: ",D.slackChannelId]})]})})},D.id)),I.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No mappings found"})]}),f&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.75)",padding:16},onClick:()=>g(!1),children:e.jsxs("div",{className:"bg-card border border-border shadow-2xl",style:{width:"100%",maxWidth:400,borderRadius:12,padding:24},onClick:D=>D.stopPropagation(),children:[e.jsx("h3",{className:"text-foreground",style:{fontSize:16,fontWeight:600,marginBottom:16},children:"New Project Mapping"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-foreground",style:{display:"block",fontSize:13,fontWeight:500,marginBottom:4},children:"Channel Name"}),e.jsx("input",{type:"text",value:y,onChange:D=>j(D.target.value),placeholder:"e.g. harper-scott",className:"bg-background text-foreground border border-border",style:{width:"100%",padding:"8px 12px",borderRadius:6,fontSize:14,boxSizing:"border-box"}}),e.jsx("p",{className:"text-muted-foreground",style:{fontSize:11,marginTop:4},children:"Used as doc ID. Will be normalized (lowercase, no #)."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-foreground",style:{display:"block",fontSize:13,fontWeight:500,marginBottom:4},children:"Slack Channel ID"}
481),e.jsx("input",{type:"text",value:v,onChange:D=>T(D.target.value),placeholder:"e.g. C04K9MMTUBZ",className:"bg-background text-foreground border border-border",style:{width:"100%",padding:"8px 12px",borderRadius:6,fontSize:14,boxSizing:"border-box"}})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[e.jsx("button",{onClick:()=>g(!1),className:"text-muted-foreground hover:text-foreground border border-border",style:{flex:1,padding:"10px",borderRadius:8,fontSize:14,fontWeight:500,cursor:"pointer",background:"none"},children:"Cancel"}),e.jsx("button",{onClick:O,disabled:!y.trim()||!v.trim()||k,style:{flex:1,padding:"10px",borderRadius:8,fontSize:14,fontWeight:600,cursor:y.trim()&&v.trim()?"pointer":"not-allowed",border:"none",backgroundColor:y.trim()&&v.trim()?"#3b82f6":"#9ca3af",color:"#ffffff",opacity:k?.6:1},children:k?"Creating...":"Create"})]})]})]})}),p&&e.jsxs(Cs,{title:p.projectName,subtitle:p.id,onClose:()=>{c(null),x(null)},footer:e.jsx(nr,{onDelete:async()=>{await i(p.id),c(null)}}),children:[e.jsx(De,{title:"Details"}),e.jsx(oe,{label:"Project Name",value:p.projectName,field:"projectName",...R}),e.jsx(oe,{label:"Channel Name (doc ID)",value:p.id,field:"",...R,readOnly:!0}),e.jsx(oe,{label:"Slack Channel ID",value:p.slackChannelId,field:"slackChannelId",...R}),e.jsx(oe,{label:"Sunbowl AI Project ID",value:p.sunbowlAiProjectId,field:"sunbowlAiProjectId",...R}),e.jsx(De,{title:"Credit Linking"}),e.jsx(oe,{label:"Primary Channel",value:p.primaryChannel?`${z(p.primaryChannel)} (${p.primaryChannel})`:"",field:"primaryChannel",...R,lookupItems:A,onLookupSelect:N}),p.primaryChannel&&e.jsx("button",{onClick:S,className:"text-muted-foreground hover:text-foreground",style:{fontSize:12,padding:"4px 0",background:"none",border:"none",cursor:"pointer",textDecoration:"underline"},children:"Clear primary channel (this project holds its own credits)"}),!p.primaryChannel&&e.jsx("p",{className:"text-muted-foreground",style:{fontSize:12,lineHeight:1.5},children:"No primary channel set â this project is treated as holding its own credits. Set a primary channel if credits should be drawn from another project."}),e.jsx(De,{title:"Metadata"}),e.jsx(oe,{label:"Auto Created",value:p.autoCreated?"Yes":"No",field:"",...R,readOnly:!0}),e.jsx(oe,{label:"Created",value:nt(p.createdAt),field:"",...R,readOnly:!0}),e.jsx(oe,{label:"Updated",value:nt(p.updatedAt),field:"",...R,readOnly:!0})]})]})}const sf=t=>{var r,a;if(t.source!=="email")return null;const s=(r=t.fromEmail)==null?void 0:r.trim().toLowerCase();if(!s)return null;const n=Math.round(parseFloat(t.timestamp));return Number.isFinite(n)?[s,((a=t.subject)==null?void 0:a.trim())??"",n,t.text??""].join("\0"):null},tB=t=>{const s=new Map;for(const i of t){const d=sf(i);if(!d)continue;const m=s.get(d);m?m.push(i):s.set(d,[i])}let n=!1;for(const i of s.values())if(i.length>1){n=!0;break}if(!n)return t;const r=new Map;for(const[i,d]of s){if(d.length===1)continue;const m=[...d].sort((u,x)=>u.id.localeCompare(x.id)),[p,...c]=m;r.set(i,{...p,duplicateIds:c.map(u=>u.id)})}const a=new Set,o=[];for(const i of t){const d=sf(i);if(!d){o.push(i);continue}const m=r.get(d);if(!m){o.push(i);continue}a.has(d)||(a.add(d),o.push(m))}return o},UB=t=>{var s;return(s=t.duplicateIds)!=null&&s.length?[t.id,...t.duplicateIds]:[t.id]},kd={email:{icon:null,emoji:"âï¸",label:"Email",fg:"#60a5fa",bg:"rgba(59,130,246,0.15)"},note:{icon:pN,label:"Note",fg:"#facc15",bg:"rgba(234,179,8,0.15)"},meeting:{icon:Ss,label:"Meeting",fg:"#c084fc",bg:"rgba(168,85,247,0.15)"},task:{icon:zw,label:"Ticket",fg:"#4ade80",bg:"rgba(34,197,94,0.15)"},call:{icon:En,label:"Call",fg:"#fb923c",bg:"rgba(249,115,22,0.15)"},chat:{icon:_l,label:"Chat",fg:"#22d3ee",bg:"rgba(6,182,212,0.15)"},merge:{icon:Or,label:"Merge",fg:"#a78bfa",bg:"rgba(139,92,246,0.15)"},audit:{icon:bu,label:"Audit",fg:"#f472b6",bg:"rgba(236,72,153,0.15)"}};function nf(t){return t?String(t).trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/+$/,""):""}function sB(t){const s=sr(t);return s?s.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}):""}function nB(t){if(!t)return"";const s=sr(t);if(!s)return"Invalid Date";const r=new Date().getTime()-s.getTime(),a=Math.floor(r/(1e3*60*60*24));return a===0?"Today":a===1?"Yesterday":a<7?s.toLocaleDateString("en-US",{weekday:"long"}):a<30?`${Math.floor(a/7)} weeks ago`:s.toLocaleDateString("en-US",{month:"long",year:"numeric"})}function rB({direction:t}){if(!t)return null;const s=t==="inbound"?"bg-green-500/15 text-green-400":t==="outbound"?"bg-blue-500/15 text-blue-400":"bg-muted text-muted-foreground";return e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${s}`,children:t})}function aB({onBack:t,onLogoClick:s,clientId:n,clientName:r}){const[a,o]=l.useState(n),[i,d]=l.useState(r),[m,p]=l.useState([]),[c,u]=l.useState(!0),[x,h]=l.useState(""),[b,f]=l.useState("all"),[g,y]=l.useState(new Set),[j,v]=l.useState(100),[T,k]=l.useState(""),[w,I]=l.useState([]),[A,E]=l.useState(!1);l.useEffect(()=>{a||(E(!0),Ze(Re(ge,"clients")).then(z=>{const D=z.docs.map(L=>({id:L.id,name:L.data().name||"",companyName:L.data().companyName||null}));D.sort((L,$)=>(L.companyName||L.name).localeCompare($.companyName||$.name)),I(D),E(!1),u(!1)}))},[a]),l.useEffect(()=>{if(!a){u(!1);return}const z=async M=>{const F=Ge(Re(ge,"communications"),Ve("clientIds","array-contains",M),Tt(500));return(await Ze(F)).docs.map(_=>({id:_.id,..._.data()}))},D=async M=>{try{const F=Ge(Re(ge,"slackCommunications"),Ve("clientIds","array-contains",M),Tt(500)),_=(await Ze(F)).docs.map(G=>({id:G.id,...G.data()})).filter(G=>G.source==="email"&&G.isColdOutreach!==!0);return tB(_).map(G=>{const B=G.timestamp!=null?Math.floor(parseFloat(String(G.timestamp))):NaN,Y=Number.isFinite(B)?{seconds:B}:null;return{id:`email_${G.id}`,type:"email",direction:G.isFromClient===!1?"outbound":"inbound",subject:G.subject||G.channelName||"(no subject)",body:G.text||G.snippet||null,from:{name:G.fromName||null,email:G.fromEmail||null},to:Array.isArray(G.toEmails)?G.toEmails.map(J=>({name:null,email:J})):[],participants:[],occurredAt:Y,source:"slackCommunications",location:null,taskStatus:null,hasAttachments:!!G.hasAttachments,threadId:G.gmailThreadId||null,contactIds:G.contactId?[G.contactId]:[],clientIds:Array.isArray(G.clientIds)?G.clientIds:[]}})}catch(F){return console.error("Error fetching emails:",F),[]}},L=async M=>{try{const F=Ge(Re(ge,"tickets"),Ve("clientId","==",M),Tt(200));return(await Ze(F)).docs.map(_=>{const G=_.data(),B=G.updatedAt||G.createdAt||null,Y=G.status?`[${G.status}] `:"",J=G.creditsMin!=null?` · ${G.creditsMin}${G.creditsMax&&G.creditsMax!==G.creditsMin?`â${G.creditsMax}`:""} cr`:"",H=`${Y}${G.displayId||_.id}${J}`;return{id:`ticket_${_.id}`,type:"task",direction:null,subject:`${G.displayId||_.id} â ${G.name||"(untitled)"}
481`,body:[H,G.content||""].filter(Boolean).join(` 482 483`),from:null,to:[],participants:[],occurredAt:B,source:"tickets",location:G.shopifyStoreUrl||null,taskStatus:G.status||null,hasAttachments:Array.isArray(G.screenshots)&&G.screenshots.length>0,threadId:G.projectId||null,contactIds:[],clientIds:G.clientId?[G.clientId]:[]}})}catch(F){return console.error("Error fetching tickets:",F),[]}},$=async M=>{try{const F=Ge(Re(ge,"meetings"),Ve("clientId","==",M),Tt(100));return(await Ze(F)).docs.map(_=>{const G=_.data(),B=G.meetingDate||G.createdAt||null,Y=Array.isArray(G.attendees)&&G.attendees.length?`Attendees: ${G.attendees.join(", ")} 484 485`:"";return{id:`meeting_${_.id}`,type:"meeting",direction:null,subject:`${G.displayId||_.id} â ${G.name||"(untitled meeting)"}`,body:`${Y}${G.description||""}`.trim()||null,from:null,to:[],participants:Array.isArray(G.attendees)?G.attendees:[],occurredAt:B,source:"meetings",location:G.recordingUrl||null,taskStatus:null,hasAttachments:!1,threadId:null,contactIds:[],clientIds:G.clientId?[G.clientId]:[]}})}catch(F){return console.error("Error fetching meetings:",F),[]}},q=async(M,F)=>{const W=await P(M,F);return Array.from(W.entries()).map(([_,G])=>U(_,G))},P=async(M,F)=>{const W=new Map,_=Ge(Re(ge,"siteAudits"),Ve("clientId","==",M),Tt(50));(await Ze(_)).docs.forEach(J=>W.set(J.id,J.data()));const Y=Array.from(new Set(F.map(nf).filter(Boolean))).slice(0,30);if(Y.length>0){const J=Ge(Re(ge,"siteAudits"),Ve("domain","in",Y),Tt(100));(await Ze(J)).docs.forEach(Z=>{W.has(Z.id)||W.set(Z.id,Z.data())})}return W},U=(M,F)=>{const W=F.overallScore!=null?`${F.overallScore}/100`:"pending",_=F.status||"unknown",G=`Site Audit â ${F.domain||"(no domain)"} · ${W} · ${_}`,B=[`Domain: ${F.domain||"?"}`,F.overallScore!=null?`Overall score: ${F.overallScore}/100`:null,F.speedScore!=null?`Speed: ${F.speedScore}`:null,F.structureScore!=null?`Structure: ${F.structureScore}`:null,F.communicationScore!=null?`Communication: ${F.communicationScore}`:null,F.marketingScore!=null?`Marketing: ${F.marketingScore}`:null,F.visualScore!=null?`Visual: ${F.visualScore}`:null].filter(Boolean);return{id:`audit_${M}`,type:"audit",direction:null,subject:G,body:B.join(` 486`),from:null,to:[],participants:[],occurredAt:F.createdAt||null,source:"siteAudits",location:F.domain?`https://${nf(F.domain)}`:null,taskStatus:F.status||null,hasAttachments:!1,threadId:null,contactIds:[],clientIds:F.clientId?[F.clientId]:[]}};(async()=>{var M;u(!0);try{const F=await ps(ut(ge,"clients",a)),W=F.exists()?F.data():{},_=Array.isArray(W.domains)?W.domains:[];console.log("[Timeline] Loading all sources for client:",a);const[G,B,Y,J,H]=await Promise.all([z(a).catch(Q=>(console.error("comms",Q),[])),D(a).catch(Q=>(console.error("emails",Q),[])),L(a).catch(Q=>(console.error("tickets",Q),[])),$(a).catch(Q=>(console.error("meetings",Q),[])),q(a,_).catch(Q=>(console.error("audits",Q),[]))]),Z=[...G,...B,...Y,...J,...H];console.log("[Timeline] Loaded",{comms:G.length,emails:B.length,tickets:Y.length,meetings:J.length,audits:H.length,total:Z.length}),p(Z.sort((Q,K)=>{var pe,me;const X=((pe=Q.occurredAt)==null?void 0:pe.seconds)||0;return(((me=K.occurredAt)==null?void 0:me.seconds)||0)-X}))}catch(F){console.error("Failed to load timeline:",F),(M=F.message)!=null&&M.includes("index")&&console.error("Index required. Create it at the URL in the error above.")}u(!1)})()},[a]);const C=l.useMemo(()=>{const z={all:m.length};for(const D of m)z[D.type]=(z[D.type]||0)+1;return z},[m]),N=l.useMemo(()=>{let z=m;if(b!=="all"&&(z=z.filter(D=>D.type===b)),x){const D=x.toLowerCase();z=z.filter(L=>{var $,q,P,U,V,M;return(($=L.subject)==null?void 0:$.toLowerCase().includes(D))||((q=L.body)==null?void 0:q.toLowerCase().includes(D))||((U=(P=L.from)==null?void 0:P.name)==null?void 0:U.toLowerCase().includes(D))||((M=(V=L.from)==null?void 0:V.email)==null?void 0:M.toLowerCase().includes(D))||(L.to||[]).some(F=>{var W,_;return((W=F.name)==null?void 0:W.toLowerCase().includes(D))||((_=F.email)==null?void 0:_.toLowerCase().includes(D))})})}return z.slice(0,j)},[m,b,x,j]),S=l.useMemo(()=>{const z=[];let D="";for(const L of N){const $=nB(L.occurredAt);$!==D?(z.push({label:$,entries:[L]}),D=$):z[z.length-1].entries.push(L)}return z},[N]),O=z=>{y(D=>{const L=new Set(D);return L.has(z)?L.delete(z):L.add(z),L})},R=["all","email","note","meeting","task","audit","call","chat","merge"];return e.jsxs("div",{className:"min-h-screen bg-background pb-24",children:[e.jsx(Xe,{onLogoClick:s}),e.jsxs("div",{className:"max-w-2xl mx-auto px-4",style:{paddingTop:"var(--spacing-md)"},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("button",{onClick:a&&!n?()=>{o(void 0),d(void 0),p([])}:t,className:"text-muted-foreground hover:text-foreground",children:e.jsx(dt,{style:{width:20,height:20}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Timeline"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a?`${i||"Client"} â ${m.length} interactions`:"Select a client"})]})]}),!a&&e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Pt,{className:"absolute text-muted-foreground",style:{width:16,height:16,left:12,top:"50%",transform:"translateY(-50%)"}}),e.jsx("input",{type:"text",value:T,onChange:z=>k(z.target.value),placeholder:"Search clients...",autoFocus:!0,className:"w-full bg-card border border-border rounded-lg text-sm text-foreground focus:outline-none focus:border-primary",style:{padding:"8px 12px 8px 36px"}})]}),A?e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"Loading clients..."}):e.jsx("div",{className:"space-y-1 max-h-[60vh] overflow-y-auto",children:w.filter(z=>{if(!T)return!0;const D=T.toLowerCase();return(z.companyName||"").toLowerCase().includes(D)||z.name.toLowerCase().includes(D)}).slice(0,50).map(z=>e.jsxs("button",{onClick:()=>{o(z.id),d(z.companyName||z.name),u(!0)},className:"w-full bg-card border border-border rounded-lg p-3 text-left hover:bg-accent transition-colors",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:z.companyName||z.name}),z.companyName&&z.companyName!==z.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:z.name})]},z.id))})]}),a&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Pt,{className:"absolute text-muted-foreground",style:{width:16,height:16,left:12,top:"50%",transform:"translateY(-50%)"}}),e.jsx("input",{type:"text",value:x,onChange:z=>h(z.target.value),placeholder:"Search timeline...",className:"w-full bg-card border border-border rounded-lg text-sm text-foreground focus:outline-none focus:border-primary",style:{padding:"8px 12px 8px 36px"}})]}),a&&e.jsx(Xu,{clientId:a}),e.jsx("div",{className:"flex gap-1.5 mb-4 overflow-x-auto pb-1",style:{scrollbarWidth:"none"},children:R.map(z=>{const D=kd[z],L=C[z]||0;return z!=="all"&&L===0?null:e.jsxs("button",{onClick:()=>f(z),className:b===z?"bg-primary text-primary-foreground":"bg-card text-muted-foreground border border-border",style:{padding:"4px 10px",borderRadius:9999,fontSize:11,fontWeight:500,whiteSpace:"nowrap",transition:"all 0.15s"},children:[z==="all"?"All":(D==null?void 0:D.label)||z," (",L,")"]},z)})}),c?e.jsx("div",{className:"text-center text-muted-foreground py-12 text-sm",children:"Loading timeline..."}):m.length===0?e.jsx("div",{className:"text-center text-muted-foreground py-12 text-sm",children:"No communications foun
486d for this client"}):e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-5 top-0 bottom-0 w-px bg-border"}),S.map(z=>e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background py-1 mb-2",children:e.jsx("span",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider ml-12",children:z.label})}),z.entries.map(D=>{var U,V,M;const L=kd[D.type]||kd.note,$=L.icon,q=g.has(D.id),P=D.body&&D.body.length>0;return e.jsxs("div",{className:"relative flex gap-3 mb-3",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center z-10",style:{color:L.fg,backgroundColor:L.bg},children:L.emoji?e.jsx("span",{style:{fontSize:18},children:L.emoji}):e.jsx($,{style:{width:16,height:16}})}),e.jsxs("div",{className:`flex-1 bg-card border border-border rounded-lg p-3 ${P?"cursor-pointer hover:bg-accent":""} transition-colors`,onClick:()=>P&&O(D.id),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded",style:{color:L.fg,backgroundColor:L.bg},children:L.label}),e.jsx(rB,{direction:D.direction}),D.hasAttachments&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"ð"})]}),D.subject&&e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:D.subject}),((U=D.from)==null?void 0:U.email)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[D.from.name||D.from.email,((V=D.to)==null?void 0:V.length)>0&&e.jsxs("span",{children:[" â ",D.to.map(F=>F.name||F.email).join(", ")]})]}),D.location&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["ð ",D.location]}),!D.subject&&!((M=D.from)!=null&&M.email)&&D.body&&e.jsx("p",{className:"text-sm text-foreground truncate",children:D.body.substring(0,120)})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:sB(D.occurredAt)}),P&&(q?e.jsx(hr,{style:{width:14,height:14},className:"text-muted-foreground"}):e.jsx(Ot,{style:{width:14,height:14},className:"text-muted-foreground"}))]})]}),q&&D.body&&e.jsx("div",{className:"mt-3 pt-3 border-t border-border max-h-80 overflow-y-auto",children:e.jsxs("div",{className:"text-xs text-muted-foreground leading-relaxed",children:[D.body.substring(0,3e3).replace(/\n{3,}/g,` 487 488`).trim().split(` 489 490`).map((F,W)=>e.jsx("p",{className:"mb-2",children:F.replace(/\n/g," ").replace(/\s{2,}/g," ").trim()},W)),D.body.length>3e3&&e.jsx("p",{className:"text-muted-foreground italic",children:"[truncated]"})]})})]})]},D.id)})]},z.label)),N.length>=j&&e.jsx("div",{className:"text-center py-4",children:e.jsx("button",{onClick:()=>v(z=>z+100),className:"text-sm text-primary hover:underline",children:"Load more..."})})]})]})]})]})}const oB=l.lazy(()=>Gs(()=>import("./SiteAuditScreen-a23zHAuX.js"),__vite__mapDeps([5,3,6,2,1,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])).then(t=>({default:t.SiteAuditScreen}))),iB=l.lazy(()=>Gs(()=>import("./CommunicationsHub-NdOYJU9u.js"),__vite__mapDeps([25,1,2,3,7,8,9,10,11,12,13,15,21,16,14,17,18,6,19,20,22,23,24])).then(t=>({default:t.CommunicationsHub}))),lB=l.lazy(()=>Gs(()=>import("./GameBoard-BeXbe_9-.js"),__vite__mapDeps([26,3,15,7,8,9,10,1,2,11,12,13,14,16,17,18,6,19,20,21,22,23,24])).then(t=>({default:t.GameBoard}))),cB=l.lazy(()=>Gs(()=>import("./TranscriptTicketScreen-BQFCOah7.js"),__vite__mapDeps([27,3,7,8,9,10,1,2,11,12,13,15,14,16,17,18,6,19,20,21,22,23,24])).then(t=>({default:t.TranscriptTicketScreen}))),dB=l.lazy(()=>Gs(()=>import("./MarketingResearchScreen-R0npD1Qz.js"),__vite__mapDeps([28,3,7,8,9,10,1,2,11,12,13,17,14,15,16,18,6,19,20,21,22,23,24])).then(t=>({default:t.MarketingResearchScreen})));function co(){return cf(),e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx("div",{className:"w-8 h-8 border-2 border-primary border-t-transparent roun
490ded-full animate-spin"})})}const uB=[{id:"1",name:"Product Page Optimization",channelId:"#chic-fil-a",logoUrl:ka,lastMessage:"I reviewed the changes - looks great! Let's implement.",timestamp:"2m ago",unreadCount:2},{id:"2",name:"Checkout Flow Analysis",channelId:"#hs-figma",logoUrl:Sa,lastMessage:"The A/B test results are ready for review",timestamp:"1h ago",unreadCount:1},{id:"3",name:"Email Campaign Strategy",channelId:"#delta-btc",logoUrl:ni,lastMessage:"Thanks! I'll review the draft this afternoon.",timestamp:"3h ago"},{id:"4",name:"Mobile UX Improvements",channelId:"#chic-fil-a",logoUrl:ka,lastMessage:"Sunbowl Team: We've completed the mobile audit",timestamp:"Yesterday"},{id:"5",name:"Holiday Campaign Prep",channelId:"#hs-figma",logoUrl:Sa,lastMessage:"Perfect timing! When can we start?",timestamp:"Tuesday"}],mB={communications:"Communications",capacity:"Capacity",databases:"Databases","ai-runs":"AI Runs","theme-management":"Theme Previews","theme-deploy":"Theme Deploy","theme-sync":"Theme Sync","seo-automation":"SEO Automation","notification-settings":"Notifications","dialer-settings":"Dialer",subscriptions:"Subscriptions","function-warming":"Server Warming","client-mockups":"Client Mockups","client-ledger":"Client Ledger","client-strategy":"Strategy","site-audit":"Site Audit",estimator:"Estimator",sales:"Sales","create-project":"Create Project","admin-logo-management":"Logo Management","admin-qa-review":"QA Review","seo-home":"SEO Review","ai-insights":"AI Insights","vacation-days":"Vacation & Travel","transcript-tickets":"Meeting Tickets","marketing-research":"Marketing Research","chat-leads":"Chat Leads","duplicate-merge":"Duplicate Merge","model-compare":"Model Compare","conversion-analytics":"Conversion Analytics","profit-projections":"Profit Projections","dmarc-monitoring":"DMARC Monitoring","savi-dashboard":"SAVI","client-setup":"Client Setup","promo-email-review":"Promo Email Review","report-recommendations":"Report Recommendations","job-reports":"Job Reports","content-queue":"Content Queue","intake-admin":"Asset Intake","chat-accounts":"Chat Accounts",hub:"Communications","bookings-admin":"Bookings","client-timeline":"Client Timeline","project-presentation-select":"Project Presentation","project-overview":"Project","project-status":"Status","project-results":"Results","ticket-detail":"Ticket","new-request":"New Request","calendar-booking":"Book a Meeting",credits:"Credits",settings:"Settings","all-channels":"Messages","native-messages":"Messages","channel-list":"Channels","projects-list":"Projects",chat:"Chat","cycle-approvals":"Approvals"},pB=new Set(["login","loading","view-selection","admin-home","company-select"]),xB=t=>t.replace(/-/g," ").replace(/\b\w/g,s=>s.toUpperCase());function hB(){var Yt,is,ne,Ce,Qe,xt;tr();const{user:t,signOut:s,isAdminDomain:n,token:r}=pt(),a=El(!!(t!=null&&t.email)),{impersonatedEmail:o,isImpersonating:i,startImpersonation:d,stopImpersonation:m}=of(),p=ee.useCallback(async()=>i&&o?{impersonateEmail:o}:{},[i,o]),[c,u]=ee.useState("login"),x=ee.useRef(!1),[h,b]=ee.useState(null);ee.useEffect(()=>{const ye=new URLSearchParams(window.location.search);if(ye.get("screen")==="chat")try{sessionStorage.setItem("sb:post-login",JSON.stringify({screen:"chat",lane:ye.get("lane")}))}catch{}},[]),ee.useEffect(()=>{var Et,Ts;if(x.current||!t||(new URLSearchParams(window.location.search).get("screen")==="hub"&&n&&(c==="view-selection"||c==="admin-home")&&(x.current=!0,u("hub")),x.current||a.loading))return;let Me=null;try{Me=JSON.parse(sessionStorage.getItem("sb:post-login")||"null")}catch{Me=null}const Pe=["view-selection","admin-home","company-select","channel-list","all-channels"].includes(c);if((Me==null?void 0:Me.screen)==="chat"&&Pe){x.current=!0;try{sessionStorage.removeItem("sb:post-login")}catch{}const As=Me.lane&&((Et=a.access)!=null&&Et.accounts.some(Fn=>Fn.id===Me.lane))?Me.lane:null;b(As),Le("messages"),u((Ts=a.access)!=null&&Ts.accounts.some(Fn=>Fn.native)?"native-messages":"all-channels")}},[t,n,c,a.loading,a.access]);const f=l.useRef(null),[g,y]=ee.useState(null),[j,v]=ee.useState(null),{isSupported:T,isRegistered:k,fcmToken:w}=kw({userId:t==null?void 0:t.uid,userEmail:(t==null?void 0:t.email)||void 0,token:r||void 0,onNotificationReceived:ye=>{console.log("ð± Push notification received:",ye)},onNotificationTapped:ye=>{var Et;console.log("ð± Push notification tapped:",ye);const Me=ye.data||{},Pe=Me.screen||(Me.type==="new_message"?"communications":"");if(Pe){const Ts={};Object.entries(Me).forEach(([As,Fn])=>{As.startsWith("param_")&&(Ts[As.slice(6)]=Fn)}),Me.projectId&&(Ts.projectId=Me.projectId),Me.channelId&&(Ts.channelId=Me.channelId),(Et=f.current)==null||Et.call(f,{screen:Pe,params:Ts})}}});l.useEffect(()=>{T&&console.log("ð± Push notifications status:",{pushRegistered:k,fcmToken:w?"present":"none"})},[T,k,w]);const[I,A]=ee.useState(!1);console.log("ð¯ App render:",{hasUser:!!t,userEmail:t==null?void 0:t.email,currentScreen:c,isAdminDomain:n});const[E,C]=ee.useState(!1),[N,S]=ee.useState(null),[O,R]=ee.useState(null),[z,D]=ee.useState(null),[L,$]=ee.useState(null),[q,P]=ee.useState(null),[U,V]=ee.useState(null),[M,F]=ee.useState(null),[W,_]=ee.useState(""),[G,B]=ee.useState(""),[Y,J]=ee.useState(null),[H,Z]=ee.useState(""),[Q,K]=ee.useState(""),[X,se]=ee.useState(null),[pe,me]=ee.useState(null),[Ne,at]=ee.useState(null),[ae,xe]=ee.useState("project-overview"),[ze,Le]=ee.useState("home"),[ht,ue]=ee.useState(uB),[we,Be]=ee.useState(null),[Ye,rt]=ee.useState(()=>{const ye=sessionStorage.getItem("pendingCycleDeepLink");if(ye)try{return JSON.parse(ye)}catch{return null}return null}),{pendingCount:te}=Cb(!E&&M?M:void 0);ee.useEffect(()=>{if(console.log("ð App useEffect triggered:",{hasUser:!!t,userEmail:t==null?void 0:t.email,currentScreen:c,isAdminDomain:n,shouldNavigate:!!t&&c==="login"}),t&&c==="login"){console.log("â
Conditions met - navigating from login screen");const ye=t==null?void 0:t.email,Me=xm(ye);console.log("ð Admin check:",{userEmail:ye,isUserAdmin:Me,isAdminDomain:n,isImpersonating:i}),i?(console.log("ð Impersonating - navigating to: loading (client view)"),u("loading")):Ye?(console.log("ð Deep link pending - navigating to: loading (client view)"),u("loading")):Me?(console.log("ð Navigating to: view-selection"),u("view-selection")):(console.log("ð Navigating to: loading"),u("loading"))}else console.log("â¸ï¸ Not navigating:",{reason:t?c!=="login"?"Not on login screen":"Unknown":"No user"})},[t,c,n,i,Ye]),ee.useEffect(()=>{Ye&&t&&c!=="login"&&c!=="loading"&&(console.log("ð Processing pending deep link:",Ye),F(Ye.projectId),_(Ye.projectName),C(!1),u("cycle-approvals"),rt(null),sessionStorage.removeItem("pendingCycleDeepLink"))},[Ye,t,c]);const ve=l.useRef(0),Ae=l.useRef(c),We=l.useRef(!0);l.useEffect(()=>{Ae.current=c},[c]);const ie=l.useCallback((ye,Me)=>{var Ts;if(!((Ts=window.electron)!=null&&Ts.notifications))return;const Pe=ye===1?`New message from ${(Me==null?void 0:Me.companyName)||"a client"}`:`${ye} new messages`,Et=Me!=null&&Me.text?Me.text.substring(0,100)+(Me.text.length>100?"...":""):"You have new messages in the Communications Hub";window.electron.notifications.show({title:Pe,body:Et,silent:!1}).then(As=>{As.success&&console.log("ð¬ Notification shown for new messages")}).catch(As=>{console.error("Failed to show notification:",As)})},[]);l.useEffect(()=>{if(!t||!r)return;const ye=t==null?void 0:t.email;if(!xm(ye))return;console.log("ð Setting up background notification listener for communications...");const Pe=Il("slackCommunications",[],Et=>{const Ts=Et.filter(Jr=>(Jr.hasUnread===!0||Jr.requiresResponse===!0)&&Number.isFinite(parseFloat(Jr.timestamp))),As=Ts.length,Fn=ve.current;
490if(console.log(`ð¬ Background check: ${As} unhandled messages (prev: ${Fn})`),We.current){We.current=!1,ve.current=As,console.log("ð¬ First load - skipping notification");return}if(As>Fn&&Ae.current!=="communications"){const Jr=As-Fn,b0=[...Ts].sort((y0,j0)=>parseFloat(j0.timestamp)-parseFloat(y0.timestamp))[0];console.log(`ð New messages detected! Showing notification for ${Jr} new message(s)`),ie(Jr,b0)}ve.current=As});return()=>{console.log("ð Cleaning up background notification listener"),Pe()}},[t,r,ie]),l.useEffect(()=>{var Me;return(Me=window.electron)!=null&&Me.notifications?window.electron.notifications.onNotificationClicked(Pe=>{console.log("ð Notification clicked:",Pe),Pe.type==="communications"&&u("communications")}):void 0},[]);const Ue=()=>{u("company-select"),Le("home")},Te=ye=>{if(!ye){console.error("Invalid company ID provided:",ye);return}Be(ye),u("channel-list")},He=()=>{Be(null),J(null),u("company-select")},Oe=ye=>{J(ye),u("projects-list")},Je=()=>{u("channel-list"),J(null)},de=(ye,Me,Pe)=>{F(ye),_(Me),B(Pe),u("project-overview")},je=()=>{u("projects-list"),F(null)},qe=(ye,Me,Pe)=>{J(ye),Z(Me),K(Pe),u("chat")},he=()=>{u("all-channels"),J(null),Z(""),K("")},lt=ye=>{se(ye),u("project-overview")},tt=()=>{u("project-status"),Le("home"),se(null),me(null)},Se=()=>{Be(null),J(null),F(null),u(E?"admin-home":"company-select"),Le("home"),se(null)},es=()=>{u("admin-logo-manager")},_e=()=>{u("new-request")},St="tel:+1-555-SUNBOWL",$t=()=>{window.location.href=St},Ct=()=>{u("calendar-booking")},ot=()=>{u("ai-assistant")},fn=()=>{u("new-request")},Vt=ye=>{var Me;switch(Le(ye),ye){case"home":we?(u("channel-list"),J(null),F(null)):u("company-select");break;case"messages":u((Me=a.access)!=null&&Me.accounts.some(Pe=>Pe.native)?"native-messages":"all-channels");break;case"strategy":u("client-strategy");break;case"credits":u("credits");break;case"settings":u("settings");break}},rr=async()=>{try{await s(),u("login")}catch(ye){console.error("Logout failed:",ye)}},Cr=l.useCallback((ye,Me)=>{ue(Pe=>Pe.map(Et=>Et.id===ye?{...Et,logoUrl:Me}:Et))},[]);ht.find(ye=>ye.id===M);const Qr=l.useCallback((ye,Me,Pe)=>{if(!ye||!Me||!Pe){console.error("Invalid deep link parameters:",{cycleId:ye,projectId:Me,projectName:Pe});return}console.log("ð Deep link to cycle:",{cycleId:ye,projectId:Me,projectName:Pe}),rt({cycleId:ye,projectId:Me,projectName:Pe})},[]),{goHome:le}=ik(c,u,Se),Ie=l.useCallback(ye=>{const{screen:Me,params:Pe}=ye;if(!Me){le();return}Pe!=null&&Pe.projectId&&F(Pe.projectId),Pe!=null&&Pe.projectName&&_(Pe.projectName),Pe!=null&&Pe.ticketDisplayId&&$(Pe.ticketDisplayId),Pe!=null&&Pe.runId&&S(Pe.runId),Pe!=null&&Pe.contactId&&R(Pe.contactId),Pe!=null&&Pe.subscriptionId&&D(Pe.subscriptionId);const Et=(Pe==null?void 0:Pe.channelName)||"";if(Pe!=null&&Pe.channelName&&Z(Pe.channelName),Pe!=null&&Pe.channelId&&J(Pe.channelId),Pe!=null&&Pe.ticketDisplayId){n&&!i?u("tickets-table"):(xe("project-status"),u("project-status"));return}Me==="chat"&&(K((Pe==null?void 0:Pe.logoUrl)||""),Pe!=null&&Pe.channelId||J(Et||null)),u(Me)},[le,n,i]);f.current=Ie;const Ke=l.useCallback(()=>{Be(null),J(null),F(null),se(null),Le("home"),n&&!i?(C(!1),u("view-selection")):u("company-select")},[n,i]),Fe=pB.has(c)?[]:[{label:E?"Admin":"Home",onClick:le},{label:mB[c]??xB(c)}];dk({userId:t==null?void 0:t.uid,userEmail:(t==null?void 0:t.email)||void 0,onDeepLink:Ie});const Ht=["admin-home","admin-logo-manager","site-audit","communications","estimator","sales","dollar-orders","capacity","qa-review","admin-qa-review","customer-qa-review","seo-home","seo-capture","seo-review","create-project","ai-insights","vacation-days","transcript-tickets","project-presentation-select","marketing-research","ai-runs","shop-repos","theme-deploy","theme-sync","seo-automation","theme-management","databases","tickets-table","projects-table","clients-table","stores-table","meetings-table","recurring-templates-table","chat-leads","duplicate-merge","model-compare","conversion-analytics","profit-projections","dmarc-monitoring","project-mappings","contacts-table","companies-table","sequences-table","client-timeline","bookings-admin","savi-dashboard","client-setup","promo-email-review","report-recommendations","notification-settings","job-reports","dialer-settings","function-warming","sales-drafts","intake-admin","content-queue","chat-accounts","hub","subscriptions","client-mockups","client-ledger"],At=c==="chat"&&!!Y&&!!(a.access&&a.access.accounts.some(ye=>ye.native&&(ye.handle===H||ye.id===H))),gn=aT({isAdminMode:E,isAdminDomain:n,isImpersonating:i}),Zs=c!=="login"&&c!=="loading"&&c!=="view-selection"&&!Ht.includes(c)&&!At;return e.jsxs(e.Fragment,{children:[e.jsxs(g1,{children:[e.jsx(Bs,{path:"/presentation/:auditId",element:e.jsx(WI,{})}),e.jsx(Bs,{path:"/project-presentation/:projectId",element:e.jsx(zD,{})}),e.jsx(Bs,{path:"/game",element:e.jsx(l.Suspense,{fallback:e.jsx(co,{}),children:e.jsx(lB,{})})}),e.jsx(Bs,{path:"/admin-qa-review",element:e.jsx(Cx,{authToken:r,userEmail:t==null?void 0:t.email})}),e.jsx(Bs,{path:"/approve/:cycleId",element:e.jsx(NT,{onCycleLoaded:Qr})}),e.jsx(Bs,{path:"/approve-email",element:e.jsx(AT,{})}),e.jsx(Bs,{path:"/review-ticket",element:e.jsx(ET,{})}),e.jsx(Bs,{path:"/qa-questionnaire",element:e.jsx(MT,{})}),e.jsx(Bs,{path:"/book/:teamMember/:source",element:e.jsx(Qc,{})}),e.jsx(Bs,{path:"/book/:teamMember",element:e.jsx(Qc,{})}),e.jsx(Bs,{path:"/book",element:e.jsx(Qc,{})}),e.jsx(Bs,{path:"*",element:e.jsx(e.Fragment,{children:e.jsx(Tw,{uid:i||t==null?void 0:t.uid,token:i?void 0:r||void 0,isAdmin:i?!1:n,onDeepLink:Ie,children:e.jsxs(uk,{value:Fe,rootHome:Ke,children:[e.jsxs(gk,{children:[e.jsxs("div",{className:"relative",children:[c==="login"&&e.jsx(e2,{onLogin:()=>{}}),c==="loading"&&e.jsx(s2,{onComplete:Ue}),c==="view-selection"&&t&&e.jsx(p2,{userEmail:t.email||"",onSelectClient:()=>{C(!1),u("loading")},onSelectAdmin:()=>{C(!0),u("admin-home")}}),c==="admin-home"&&e.jsx(uT,{onLogoClick:Se,onLogoManagement:()=>u("admin-logo-management"),onSiteAudit:()=>u("site-audit"),onLegacyHub:()=>u("communications"),onCommunications:()=>{var Me;const ye=(Me=window.electron)==null?void 0:Me.hub;if(ye){ye.openWindow();return}u("hub")},onEstimator:()=>u("estimator"),onSales:()=>u("sales"),onImpersonate:()=>A(!0),onCapacity:()=>u("capacity"),onAdminQAReview:()=>
490{const Pe=(window.screen.width-960)/2,Et=(window.screen.height-1080)/2;window.open("/admin-qa-review","AdminQAReview",`width=960,height=1080,left=${Pe},top=${Et},toolbar=no,menubar=no,location=no`)},onSEOReview:()=>u("seo-home"),onCreateProject:()=>u("create-project"),onAIInsights:()=>u("ai-insights"),onVacationDays:()=>u("vacation-days"),onTranscriptTickets:()=>u("transcript-tickets"),onProjectPresentation:()=>u("project-presentation-select"),onMarketingResearch:()=>u("marketing-research"),onAiRuns:()=>{S(null),u("ai-runs")},onChatLeads:()=>u("chat-leads"),onThemeDeploy:()=>u("theme-deploy"),onThemeSync:()=>u("theme-sync"),onSeoAutomation:()=>u("seo-automation"),onNotificationSettings:()=>u("notification-settings"),onDialerSettings:()=>u("dialer-settings"),onSubscriptions:()=>u("subscriptions"),onFunctionWarming:()=>u("function-warming"),onClientMockups:()=>u("client-mockups"),onClientLedger:()=>u("client-ledger"),onAssetIntake:()=>u("intake-admin"),onChatAccounts:()=>u("chat-accounts"),onThemeManagement:()=>u("theme-management"),onDatabases:()=>u("databases"),onDuplicateMerge:()=>u("duplicate-merge"),onModelCompare:()=>u("model-compare"),onConversionAnalytics:()=>u("conversion-analytics"),onProfitProjections:()=>u("profit-projections"),onDmarcMonitoring:()=>u("dmarc-monitoring"),onSaviDashboard:()=>u("savi-dashboard"),onClientSetup:()=>u("client-setup"),onPromoEmailReview:()=>u("promo-email-review"),onReportRecommendations:()=>u("report-recommendations"),onJobReports:()=>u("job-reports"),onSalesDrafts:()=>u("sales-drafts"),onContentQueue:()=>u("content-queue"),onBookingsAdmin:()=>
490u("bookings-admin"),onTimeline:()=>{V(null),u("client-timeline")},onCreditCruncher:()=>{const Pe=(window.screen.width-1470)/2,Et=(window.screen.height-1e3)/2;window.open("/game","CreditCruncher",`width=1470,height=1000,left=${Pe},top=${Et},toolbar=no,menubar=no,location=no`)}}),c==="admin-logo-manager"&&e.jsx(pT,{onBack:()=>u("settings"),onLogoClick:Se}),c==="admin-logo-management"&&e.jsx(mT,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="site-audit"&&e.jsx(l.Suspense,{fallback:e.jsx(co,{}),children:e.jsx(oB,{onBack:()=>u("admin-home"),onLogoClick:Se})}),c==="communications"&&e.jsx(l.Suspense,{fallback:e.jsx(co,{}),children:e.jsx(iB,{onBack:()=>u("admin-home"),onLogoClick:Se,onOpenTimeline:(ye,Me)=>{V({id:ye,name:Me}),u("client-timeline")}})}),c==="estimator"&&e.jsx(xT,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="sales"&&e.jsx(hT,{onBack:()=>u("admin-home"),onLogoClick:Se,onDollarOrders:()=>u("dollar-orders")}),c==="dollar-orders"&&e.jsx(gT,{onBack:()=>u("sales"),onLogoClick:Se}),c==="capacity"&&e.jsx(II,{onBack:()=>u("admin-home"),onLogoClick:Se,onViewTicketInDatabase:ye=>{$(ye),u("tickets-table")},onViewProjectInDatabase:ye=>{P(ye),u("projects-table")}}),c==="company-select"&&e.jsx(h2,{onCompanySelect:Te,onNewFeatureClick:_e}),c==="channel-list"&&we&&e.jsx(f2,{selectedCompanyId:we,onChannelSelect:Oe,onSettingsClick:()=>{},onCreditClick:()=>{},onLogoClick:Se,onBack:()=>u("company-select")}),c==="projects-list"&&we&&Y&&e.jsx(v2,{selectedCompanyId:we,selectedChannelId:Y,onProjectSelect:de,onSettingsClick:()=>{},onCreditClick:()=>{},onLogoClick:Se,onBack:Je}),c==="all-channels"&&e.jsx(g2,{onChannelSelect:qe,onLogoClick:Se}),c==="native-messages"&&!a.access&&!a.loading&&i&&e.jsx("div",{className:"sb-viewport-column",style:{minWidth:0,padding:24},children:e.jsxs("div",{className:"bg-card border border-border text-muted-foreground",style:{padding:20,borderRadius:12,fontSize:14,lineHeight:1.5,maxWidth:560},children:[e.jsxs("div",{className:"text-foreground",style:{fontWeight:600,marginBottom:6},children:["No chat for ",o]}),a.error||"They have no chat profile yet, so there is nothing to look at."]})}),c==="native-messages"&&a.access&&e.jsx("div",{className:"sb-viewport-column",style:{minWidth:0,paddingBottom:72},children:e.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:e.jsx(Sd,{access:a.access,profileId:a.profileId||"",initialLane:h,getProof:p,impersonating:i})})}),At&&a.access&&e.jsxs("div",{className:"sb-viewport-column",style:{minWidth:0},children:[e.jsx(Xe,{onBack:he}),e.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:e.jsx(Sd,{access:a.access,profileId:a.profileId||"",initialLane:((Yt=a.access.accounts.find(ye=>ye.handle===H||ye.id===H))==null?void 0:Yt.id)??null,getProof:p,impersonating:i})})]}),c==="chat"&&Y&&!At&&e.jsx(B2,{projectId:Y,projectName:H,channelId:H,logoUrl:Q,onBack:he,onUpdateLogo:Cr}),c==="credits"&&e.jsx(F2,{onLogoClick:Se}),c==="client-strategy"&&e.jsx(cT,{getProof:p,onLogoClick:Se}),c==="settings"&&e.jsx(H2,{onBack:()=>{u("channel-list"),Le("home")},onLogout:rr,onLogoClick:Se,onAdminMode:()=>u("view-selection"),onManageLogos:es,chatDigest:(is=a.access)!=null&&is.accounts.some(ye=>ye.native)?((ne=a.profile)==null?void 0:ne.digest)??null:void 0,chatIsStaff:((Ce=a.profile)==null?void 0:Ce.isStaff)===!0}),c==="new-request"&&e.jsx(mS,{onBack:tt,onPhoneRequest:$t,onBookMeeting:Ct,onAIRequest:ot,onLogoClick:Se}),c==="calendar-booking"&&e.jsx(pS,{onBack:fn,onLogoClick:Se}),c==="ai-assistant"&&e.jsx(nT,{onBack:fn,onLogoClick:Se}),c==="project-status"&&e.jsx(X2,{token:r||void 0,projectId:M,projectName:W,ticketDisplayId:L,onBack:He,onLogoClick:Se,onNewRequest:_e,onTicketSelect:ye=>lt(ye),onResolveDeepLinkTicket:ye=>{at({id:ye.id,name:ye.name,status:ye.status,dueDate:ye.dueDate,ticketNumber:ye.ticketNumber,maxCredits:ye.maxCredits,rushOrder:ye.rushOrder,shopifyStoreUrl:ye.shopifyStoreUrl,shopifyThemeId:ye.shopifyThemeId}),xe("project-status"),u("ticket-detail")},onApprove:ye=>{Y?(Z(H),u("chat")):lt(ye)}}),c==="project-overview"&&M&&Y&&e.jsx(oS,{projectId:M,projectName:W,projectStatus:G,channelName:Y,onBack:je,onLogoClick:Se,onTicketClick:ye=>{at(ye),xe("project-overview"),u("ticket-detail")},onReviewChanges:()=>u("customer-qa-review")}),c==="ticket-detail"&&Ne&&e.jsx(uS,{ticketId:Ne.id,ticketName:Ne.name,ticketStatus:Ne.status,ticketDueDate:Ne.dueDate,ticketNumber:Ne.ticketNumber,maxCredits:Ne.maxCredits,rushOrder:Ne.rushOrder,shopifyStoreUrl:Ne.shopifyStoreUrl,shopifyThemeId:Ne.shopifyThemeId,projectName:W,onBack:()=>u(ae)}
490),c==="project-results"&&pe&&e.jsx(rT,{projectId:pe.id,projectTitle:pe.title,channelId:pe.channelId,logoUrl:pe.logoUrl,completionDate:pe.estimatedCompletion,onBack:tt,onLogoClick:Se,onBookCall:Ct}),c==="qa-review"&&e.jsx(Nm,{authToken:r,userEmail:t==null?void 0:t.email,onBack:()=>u("admin-home")}),c==="admin-qa-review"&&e.jsx(Cx,{authToken:r,userEmail:t==null?void 0:t.email,onBack:()=>u("admin-home")}),c==="customer-qa-review"&&M&&e.jsx(Nm,{authToken:r,userEmail:t==null?void 0:t.email,projectId:M,onBack:()=>u("project-overview")}),c==="seo-home"&&e.jsx($R,{onBack:()=>u("admin-home"),onCaptureStore:()=>u("seo-capture"),onSEOReview:()=>u("seo-review")}),c==="seo-capture"&&e.jsx(_R,{authToken:r,onBack:()=>u("seo-home")}),c==="seo-review"&&e.jsx(QR,{authToken:r,userEmail:(t==null?void 0:t.email)||null,onBack:()=>u("seo-home")}),c==="create-project"&&e.jsx(ZR,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="transcript-tickets"&&e.jsx(l.Suspense,{fallback:e.jsx(co,{}),children:e.jsx(cB,{onBack:()=>u("admin-home"),onLogoClick:Se})}),c==="project-presentation-select"&&e.jsx(AD,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="marketing-research"&&e.jsx(l.Suspense,{fallback:e.jsx(co,{}),children:e.jsx(dB,{onBack:()=>u("admin-home"),initialShop:g,onNavigateToProfitProjections:(ye,Me)=>{y(ye),v(Me),u("profit-projections")}})}),c==="ai-runs"&&e.jsx(VD,{onBack:()=>{S(null),u("admin-home")},onLogoClick:Se,initialRunId:N}),c==="shop-repos"&&e.jsx(GD,{onBack:()=>u("databases"),onLogoClick:Se}),c==="theme-deploy"&&e.jsx(QD,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="theme-sync"&&e.jsx(ZD,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="seo-automation"&&e.jsx(rM,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="notification-settings"&&e.jsx(oM,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="dialer-settings"&&e.jsx(cM,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="subscriptions"&&e.jsx(EM,{onBack:()=>u("admin-home"),onLogoClick:Se,focusId:z}),c==="client-mockups"&&e.jsx(DM,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="client-ledger"&&e.jsx(TP,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="function-warming"&&e.jsx(IM,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="theme-management"&&e.jsx(EP,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="client-setup"&&e.jsx(BP,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="promo-email-review"&&e.jsx(t8,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="report-recommendations"&&e.jsx(i8,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="job-reports"&&e.jsx(m8,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="content-queue"&&e.jsx(C8,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="intake-admin"&&e.jsx(D8,{onBack:()=>u("admin-home"),onLogoClick:Se}),t&&a.needsName&&!a.loading&&e.jsx(A0,{initialName:((Qe=a.profile)==null?void 0:Qe.fullName)||t.displayName||"",email:((xt=a.profile)==null?void 0:xt.email)||t.email||void 0,onSave:a.saveName}),c==="hub"&&e.jsx(nL,{onBack:()=>u("admin-home")}),c==="chat-accounts"&&e.jsx(W8,{onBack:()=>u("admin-home")}),c==="databases"&&e.jsx(hO,{onBack:()=>u("admin-home"),onLogoClick:Se,onTickets:()=>u("tickets-table"),onProjects:()=>u("projects-table"),onClients:()=>u("clients-table"),onStores:()=>u("stores-table"),onMeetings:()=>u("meetings-table"),onShopRepos:()=>u("shop-repos"),onRecurringTemplates:()=>u("recurring-templates-table"),onProjectMappings:()=>u("project-mappings"),onContacts:()=>u("contacts-table"),onCompanies:()=>u("companies-table"),onSequences:()=>u("sequences-table"),onDeals:()=>u("deals-table")}),c==="tickets-table"&&e.jsx(gO,{onBack:()=>{$(null),u("databases")},onLogoClick:Se,initialTicketDisplayId:L}),c==="projects-table"&&e.jsx(NO,{onBack:()=>{P(null),u("databases")},onLogoClick:Se,initialProjectId:q}),c==="clients-table"&&e.jsx(EO,{onBack:()=>u("databases"),onLogoClick:Se}),c==="contacts-table"&&e.jsx(u$,{onBack:()=>u("databases"),onLogoClick:Se,focusContactId:O,onFocusHandled:()=>R(null)}),c==="companies-table"&&e.jsx(j$,{onBack:()=>u("databases"),onLogoClick:Se}),c==="client-timeline"&&e.jsx(aB,{onBack:()=>u(U?"communications":"admin-home"),onLogoClick:Se,clientId:U==null?void 0:U.id,clientName:U==null?void 0:U.name}),c==="sequences-table"&&e.jsx(B$,{onBack:()=>u("databases"),onLogoClick:Se}),c==="sales-drafts"&&e.jsx(_$,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="deals-table"&&e.jsx(X$,{onBack:()=>u("databases"),onLogoClick:Se}),c==="stores-table"&&e.jsx(IO,{onBack:()=>u("databases"),onLogoClick:Se}),c==="meetings-table"&&e.jsx(JO,{onBack:()=>u("databases"),onLogoClick:Se}),c==="recurring-templates-table"&&e.jsx(aL,{onBack:()=>u("databases"),onLogoClick:Se}),c==="project-mappings"&&e.jsx(eB,{onBack:()=>u("databases"),onLogoClick:Se}),c==="chat-leads"&&e.jsx(iL,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="duplicate-merge"&&e.jsx(QL,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="model-compare"&&e.jsx(ZL,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="conversion-analytics"&&e.jsx(_z,{onBack:()=>u("admin-home"),onLogoClick:Se,initialShopDomain:g}),c==="profit-projections"&&e.jsx(qz,{onBack:()=>u("admin-home"),onLogoClick:Se,initialShopDomain:g,initialTrafficGrowthPct:j,onNavigateToMarketingResearch:ye=>{y(ye),v(null),u("marketing-research")},onNavigateToConversionRate:ye=>{y(ye),v(null),u("conversion-analytics")}}),c==="dmarc-monitoring"&&e.jsx(eO,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="savi-dashboard"&&e.jsx(uO,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="bookings-admin"&&e.jsx(AR,{authToken:r,onBack:()=>u("admin-home"),onLogoClick:Se}),c==="vacation-days"&&e.jsx(TD,{onBack:()=>u("admin-home"),onLogoClick:Se}),c==="ai-insights"&&e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"sticky top-0 z-50 bg-background border-b border-border p-4",children:e.jsx("button",{onClick:()=>u("admin-home"),className:"text-primary hover:underline",children:"â Back to Admin"})}),e.jsx(pD,{})]}),c==="cycle-approvals"&&M&&e.jsx(vT,{projectId:M,projectName:W,onBack:()=>u("project-overview")}),i&&o&&e.jsx(bT,{email:o,onExit:()=>{m(),window.location.reload()}}),!E&&te>0&&c!=="cycle-approvals"&&e.jsx(kT,{count:te,projectName:W,onClick:()=>u("cycle-approvals")}),Zs&&e.jsx(oT,{activeTab:ze,onTabChange:Vt,showStrategy:gn}),I&&e.jsx(yT,{onClose:()=>A(!1),onImpersonate:ye=>{d(ye),window.location.reload()}})]}),e.jsx(jk,{})]}),e.jsx(ok,{})]})})})})]}),e.jsx(Oa,{position:"bottom-right",richColors:!0,closeButton:!0}),e.jsx(pO,{})]})}let rf=!1;function fB(t){try{return typeof t=="string"?t:t instanceof URL?t.href:t.url||""}catch{return""}}function gB(t,s,n){const r=fB(s),a=P0(r);if(!a||!L0(r))return t(s,n);const o=z0();return O0(o,{fnKey:a}),t(s,n).then(i=>($0(a),um(o),i),i=>{throw um(o),i})}function bB(){if(rf||typeof window>"u"||!window.fetch)return;rf=!0,window.coldStartDemo=M0;const t=window.fetch.bind(window);window.fetch=function(n,r){return gB(t,n,r)}}E0();bB();C0(document.getElementById("root")).render(e.jsx(_1,{children:e.jsx(hB,{})}));export{Aw as A,ke as B,fu as C,zr as D,Lm as E,Id as F,ju as I,Zw as L,Ta as M,gg as R,Xe as S,sy as T,Hl as U,bN as V,Ao as Z,Xt as a,vu as b,Mn as c,Ss as d,fr as e,UE as f,UB as g,tB as h,Qo as i,PT as j,zw as k,zs as l,Js as m,sN as n,pl as o,WB as p,jg as q,Nu as r,Wr as s,ce as t,U8 as u,Xo as v,Mm as w};
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.