PageSourceSearch

https://ultimatenexus.ai/assets/SettingsHub-D_QjCFbw.js

js ultimatenexus.ai collected 2026-10-05 13:11:34 UTC 255,711 bytes, 18 lines download raw bytes

1import{r as l,j as e,a8 as L,N as ce,q as oe,aj as Dt,T as le,w as J,R as te,al as K,s as de,bb as mt,Y as ie,l as ut,bu as Oe,dm as Pt,ci as $t,bf as me,bK as Ee,X as re,A as We,aB as zt,am as It,a$ as ve,bA as Te,a2 as Ne,ao as Le,cx as pt,y as Me,m as qe,b2 as Lt,f as Mt,aU as ht,I as Re,L as Ke,b9 as je,dn as _t,aC as Ft,O as bt,cf as Ut,dp as Bt,dq as Ot,cw as Wt,ck as qt,t as Kt,aa as Yt,D as ge,bC as ft,F as gt,cI as $e,a5 as ye,a9 as He,ah as vt,c4 as Gt,ak as Vt,bl as Ht,c as Xt,af as Jt,aF as Qt,aK as Zt,aL as es,aM as ts,aN as ss,aJ as as,aO as rs,dr as ls,bD as _e,ds as ns,a4 as os,c2 as is,B as cs,ba as ds,U as xs,V as ms,g as us,bJ as ps,dt as hs,d8 as bs,d9 as Y,du as fs,d7 as gs}from"./vendor-DG5Dz7Ik.js";import{b as V,a as O,g as Xe,v as Se,z as Z,u as Ye,l as pe,d as we,ab as vs,c as ke,e as Je,ae as jt}from"./view-analytics-BkPD6vG9.js";import{a as js}from"./view-pricing-oUXlOXyX.js";import{h as ys,i as Ns,j as ws,k as ks,l as Cs,a as Qe,B as G}from"./view-admin-B4Sdd-uD.js";import{M as ue}from"./view-project-Ccb3hXyh.js";import{l as Ss,d as As,c as Es}from"./memoryService-BSojoWAd.js";import{R as Ts}from"./RigorLevelSelector-Dgu3Ne0H.js";import{q as ae,r as ne}from"./view-workflow-builder-CDc7AhbV.js";import{I as Rs}from"./Input-CONSLOXL.js";import{l as Ds,a as Ps,v as $s,r as zs}from"./emailSenderService-CvdVN53_.js";import"./pdf-vendor-BQyayL6K.js";import"./socket-vendor-DENoLIvz.js";import"./auth-vendor-CeReGQmr.js";import"./view-wizard-CJQ0Ev0i.js";import"./view-mission-control-BbTzX6ZV.js";import"./shared-components-CRZb49ua.js";import"./view-reasoning-i8UqGU0O.js";import"./pdf-export-BE1eaTrw.js";import"./consensusService-B6FnfUxf.js";const Is=/^[^@]+@[^@]+\.[^@]+$/,Ls={name:"",email:"",phone:"",street:"",city:"",state:"",zip:"",country:""},Ms=()=>{const[t,s]=l.useState(Ls),[a,r]=l.useState({}),[n,i]=l.useState(!0),[c,x]=l.useState(!1),[m,h]=l.useState(!1),[b,f]=l.useState(null),[y,w]=l.useState(!1),[P,E]=l.useState(0),D=l.useRef(null),g=l.useRef(null);l.useEffect(()=>{let N=!1;return i(!0),w(!1),(async()=>{try{const k=await O("/v1/user/profile");!N&&k&&s(u=>({...u,...k.name!==null&&k.name!==void 0&&{name:k.name},...k.email!==null&&k.email!==void 0&&{email:k.email},...k.phone!==null&&k.phone!==void 0&&{phone:k.phone},...k.street!==null&&k.street!==void 0&&{street:k.street},...k.city!==null&&k.city!==void 0&&{city:k.city},...k.state!==null&&k.state!==void 0&&{state:k.state},...k.zip!==null&&k.zip!==void 0&&{zip:k.zip},...k.country!==null&&k.country!==void 0&&{country:k.country}}))}catch{N||w(!0)}finally{N||i(!1)}})(),()=>{N=!0}},[P]);const p=l.useCallback(N=>S=>{s(k=>({...k,[N]:S.target.value})),(N==="name"||N==="email")&&r(k=>({...k,[N]:void 0}))},[]),C=l.useCallback(()=>{const N={};return(!t.name||t.name.trim().length<2)&&(N.name="Name is required"),(!t.email||!Is.test(t.email))&&(N.email="Valid email required"),N},[t.name,t.email]),o=l.useCallback(async N=>{var k,u;if(N.preventDefault(),y)return;h(!1),f(null);const S=C();if(Object.keys(S).length>0){r(S),S.name?(k=D.current)==null||k.focus():S.email&&((u=g.current)==null||u.focus());return}x(!0);try{await V("/v1/user/profile",t),h(!0)}catch{f("Failed to save profile. Please try again.")}finally{x(!1)}},[t,C,y]),d=Object.values(a).some(Boolean);return n?e.jsxs("div",{className:"max-w-2xl p-12 flex items-center justify-center",role:"status","aria-label":"Loading profile",children:[e.jsx(L,{className:"w-6 h-6 animate-spin text-[var(--color-brand-400)]"}),e.jsx("span",{className:"sr-only",children:"Loading profile..."})]}):y?e.jsxs("div",{className:"max-w-2xl space-y-4",children:[e.jsx("h1",{className:"text-xl font-bold text-[var(--color-text-primary)]",children:"Personal profile"}),e.jsx("p",{role:"alert",className:"text-[var(--color-error)]",children:"Could not load your profile. Your saved details have not been changed."}),e.jsx("button",{type:"button",className:"text-[var(--color-brand-400)] underline",onClick:()=>E(N=>N+1),children:"Retry"})]}):e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h1",{className:"text-xl font-bold text-[var(--color-text-primary)] mb-2",children:"Personal profile"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] mb-6",children:"Your personal contact details, not a business profile or workspace defaults."}),m&&e.jsxs("div",{"data-testid":"save-success",className:"flex items-center gap-2 mb-4 p-3 rounded-lg bg-green-500/10 border border-green-500/30 text-[var(--color-success)]",role:"status",children:[e.jsx(ce,{size:16}),e.jsx("span",{children:"Profile saved successfully"})]}),b&&e.jsxs("div",{className:"flex items-center gap-2 mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/30 text-[var(--color-error)]",role:"alert",children:[e.jsx(oe,{size:16}),e.jsx("span",{children:b})]}),d&&e.jsx("div",{"data-testid":"validation-error",className:"sr-only",role:"alert","aria-live":"assertive",children:"Please fix the errors below"}),e.jsxs("form",{onSubmit:o,"aria-label":"Profile settings",noValidate:!0,children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"profile-name",className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:"Name"}),e.jsx("input",{ref:D,id:"profile-name",type:"text",value:t.name,onChange:p("name"),"aria-required":"true","aria-invalid":!!a.name,className:`w-full px-3 py-2 bg-[var(--color-bg-surface)] border rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-nexus-500 ${a.name?"border-red-500":"border-[var(--color-border-default)]"}`,placeholder:"Your name"}),a.name&&e.jsx("p",{className:"mt-1 text-sm text-[var(--color-error)]",role:"alert",children:a.name})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"profile-email",className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:"Email"}),e.jsx("input",{ref:g,id:"profile-email",type:"email",value:t.email,onChange:p("email"),"aria-required":"true","aria-invalid":!!a.email,className:`w-full px-3 py-2 bg-[var(--color-bg-surface)] border rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-nexus-500 ${a.email?"border-red-500":"border-[var(--color-border-default)]"}`,placeholder:"[email protected]"}),a.email&&e.jsx("p",{className:"mt-1 text-sm text-[var(--color-error)]",role:"alert",children:a.email})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"profile-phone",className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:"Phone"}),e.jsx("input",{id:"profile-phone",type:"tel",value:t.phone,onChange:p("phone"),className:"w-full px-3 py-2 bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-nexus-500",placeholder:"555-1234"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"profile-street",className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:"Street"}),e.jsx("input",{id:"profile-street",type:"text",value:t.street,onChange:p("street"),className:"w-full px-3 py-2 bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-nexus-500",placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"profile-city",className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:"City"}),e.jsx("input",{id:"profile-city",type:"text",value:t.city,onChange:p("city"),className:"w-full px-3 py-2 bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-nexus-500",placeholder:"Springfield"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"profile-state",className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:"State"}),e.jsx("input",{id:"profile-state",type:"text",value:t.state,onChange:p("state"),className:"w-full px-3 py-2 bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-nexus-500",placeholder:"IL"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"profile-zip",className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:"Zip"}),e.jsx("input",{id:"profile-zip",type:"text",value:t.zip,onChange:p("zip"),className:"w-full px-3 py-2 bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-nexus-500",placeholder:"62704"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"profile-country",className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:"Country"}),e.jsx("input",{id:"profile-country",type:"text",value:t.country,onChange:p("country"),className:"w-full px-3 py-2 bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-nexus-500",placeholder:"US"})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx("button",{type:"submit",disabled:c,
1className:"px-6 py-2 min-h-[44px] bg-nexus-600 hover:bg-nexus-500 disabled:opacity-50 disabled:cursor-not-allowed text-white font-bold rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-nexus-500 focus:ring-offset-2 focus:ring-offset-slate-900",children:c?e.jsxs("span",{className:"flex items-center gap-2",role:"status","aria-label":"Saving",children:[e.jsx(L,{size:16,className:"animate-spin"}),"Saving…"]}):"Save Profile"})})]})]})},_s=[{id:"products",label:"Products"},{id:"competitors",label:"Competitors"},{id:"brandVoice",label:"Brand Voice"},{id:"personas",label:"Personas"},{id:"budget",label:"Budget"},{id:"marketingHistory",label:"Marketing History"},{id:"compliance",label:"Compliance"}],Fs=["USD","EUR","GBP","CAD","AUD","SGD","INR","JPY"],Us=["Professional","Casual","Playful","Authoritative","Empathetic","Bold","Minimalist"],Bs=["Social Media","Email","SEO","PPC","Content Marketing","PR","Events","Influencer"],Os={products:[{name:"",description:"",usp:"",pricing:""}],competitors:[{name:"",website:"",strengths:"",weaknesses:""}],brandVoice:{tone:"",personality:"",dos:"",donts:""},personas:[{name:"",ageRange:"",roleTitle:"",painPoints:"",goals:""}],budget:{monthly:"",currency:"USD",channelBreakdown:""},marketingHistory:{channelsUsed:[],pastCampaigns:"",notableWins:"",notableLosses:""}},ee="w-full px-3 py-2 bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-nexus-500/30 focus:border-nexus-500 transition-all text-sm",H=`${ee} resize-none`,B=({label:t,hint:s,children:a})=>{const r=l.useId(),n=a.props.id??r,i=`${r}-hint`,c=a.type==="div";return e.jsxs("div",{role:c?"group":void 0,"aria-labelledby":c?`${r}-label`:void 0,"aria-describedby":c&&s?i:void 0,children:[c?e.jsx("span",{id:`${r}-label`,className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:t}):e.jsx("label",{htmlFor:n,className:"block text-sm font-medium text-[var(--color-text-secondary)] mb-1",children:t}),s&&e.jsx("p",{id:i,className:"text-xs text-[var(--color-text-secondary)] mb-2",children:s}),c?a:te.cloneElement(a,{id:n,"aria-describedby":[a.props["aria-describedby"],s?i:null].filter(Boolean).join(" ")||void 0})]})},Ws=({products:t,onChange:s})=>{const a=(r,n,i)=>{s(t.map((c,x)=>x===r?{...c,[n]:i}:c))};return e.jsxs("div",{className:"space-y-6",children:[t.map((r,n)=>e.jsxs("div",{className:"p-4 bg-[var(--color-bg-surface)] rounded-xl border border-[var(--color-border-default)] space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-semibold text-[var(--color-brand-400)]",children:["Product / Service ",n+1]}),t.length>1&&e.jsx("button",{type:"button",onClick:()=>s(t.filter((i,c)=>c!==n)),className:"text-[var(--color-text-secondary)] hover:text-[var(--color-error)] transition-colors","aria-label":"Remove product",children:e.jsx(le,{size:14})})]}),e.jsx(B,{label:"Name",children:e.jsx("input",{type:"text",value:r.name,onChange:i=>a(n,"name",i.target.value),placeholder:"e.g., Marketing Analytics Platform",className:ee})}),e.jsx(B,{label:"Description",hint:"What it does and who it's for",children:e.jsx("textarea",{rows:3,value:r.description,onChange:i=>a(n,"description",i.target.value),placeholder:"Describe your product or service in 2-3 sentences",className:H})}),e.jsx(B,{label:"Unique Selling Points",hint:"What makes it stand out from alternatives?",children:e.jsx("textarea",{rows:3,value:r.usp,onChange:i=>a(n,"usp",i.target.value),placeholder:"e.g., 10x faster reporting, AI-powered insights, integrates with 100+ tools",className:H})}),e.jsx(B,{label:"Pricing Tier",children:e.jsx("input",{type:"text",value:r.pricing,onChange:i=>a(n,"pricing",i.target.value),placeholder:"e.g., $49/mo starter, $199/mo pro, custom enterprise",className:ee})})]},n)),e.jsxs("button",{type:"button",onClick:()=>s([...t,{name:"",description:"",usp:"",pricing:""}]),className:"flex items-center gap-2 text-[var(--color-brand-400)] hover:text-[var(--color-brand-400)] text-sm font-medium transition-colors",children:[e.jsx(J,{size:14})," Add product / service"]})]})},qs=({competitors:t,onChange:s})=>{const a=(r,n,i)=>{s(t.map((c,x)=>x===r?{...c,[n]:i}:c))};return e.jsxs("div",{className:"space-y-6",children:[t.map((r,n)=>e.jsxs("div",{className:"p-4 bg-[var(--color-bg-surface)] rounded-xl border border-[var(--color-border-default)] space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-semibold text-[var(--color-brand-400)]",children:["Competitor ",n+1]}),t.length>1&&e.jsx("button",{type:"button",onClick:()=>s(t.filter((i,c)=>c!==n)),className:"text-[var(--color-text-secondary)] hover:text-[var(--color-error)] transition-colors","aria-label":"Remove c
1ompetitor",children:e.jsx(le,{size:14})})]}),e.jsx(B,{label:"Name",children:e.jsx("input",{type:"text",value:r.name,onChange:i=>a(n,"name",i.target.value),placeholder:"e.g., Hootsuite",className:ee})}),e.jsx(B,{label:"Website",children:e.jsx("input",{type:"url",value:r.website,onChange:i=>a(n,"website",i.target.value),placeholder:"https://competitor.com",className:ee})}),e.jsx(B,{label:"Their Strengths",hint:"What do they do well?",children:e.jsx("textarea",{rows:3,value:r.strengths,onChange:i=>a(n,"strengths",i.target.value),placeholder:"e.g., strong brand, wide integrations, affordable entry tier",className:H})}),e.jsx(B,{label:"Their Weaknesses",hint:"Where do they fall short?",children:e.jsx("textarea",{rows:3,value:r.weaknesses,onChange:i=>a(n,"weaknesses",i.target.value),placeholder:"e.g., poor AI capabilities, slow support, steep learning curve",className:H})})]},n)),e.jsxs("button",{type:"button",onClick:()=>s([...t,{name:"",website:"",strengths:"",weaknesses:""}]),className:"flex items-center gap-2 text-[var(--color-brand-400)] hover:text-[var(--color-brand-400)] text-sm font-medium transition-colors",children:[e.jsx(J,{size:14})," Add competitor"]})]})},Ks=({brandVoice:t,onChange:s})=>{const a=t.tone?t.tone.split(",").map(n=>n.trim()).filter(Boolean):[],r=n=>{const i=a.includes(n)?a.filter(c=>c!==n):[...a,n];s({...t,tone:i.join(", ")})};return e.jsxs("div",{className:"space-y-5",children:[e.jsx(B,{label:"Tone",hint:"Select all that apply to your brand",children:e.jsx("div",{className:"flex flex-wrap gap-2 mt-1",children:Us.map(n=>e.jsx("button",{type:"button",onClick:()=>r(n),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a.includes(n)?"bg-nexus-600/30 border-nexus-500 text-[var(--color-brand-400)]":"bg-[var(--color-bg-surface)] border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:border-nexus-500/50 hover:text-[var(--color-text-secondary)]"}`,children:n},n))})}),e.jsx(B,{label:"Personality Description",hint:"How would you describe your brand in your own words?",children:e.jsx("textarea",{rows:3,value:t.personality,onChange:n=>s({...t,personality:n.target.value}),placeholder:"e.g., We're approachable experts — we make complex marketing data feel simple and actionable",className:H})}),e.jsx(B,{label:"Writing Dos",hint:"Things your brand always does in communications",children:e.jsx("textarea",{rows:3,value:t.dos,onChange:n=>s({...t,dos:n.target.value}),placeholder:"e.g., Lead with data, use active voice, include clear calls to action, speak to specific pain points",className:H})}),e.jsx(B,{label:"Writing Don'ts",hint:"Things your brand never does",children:e.jsx("textarea",{rows:3,value:t.donts,onChange:n=>s({...t,donts:n.target.value}),placeholder:"e.g., Avoid buzzwords, never use passive voice, don't over-promise results, avoid aggressive sales language",className:H})})]})},Ys=({personas:t,onChange:s})=>{const a=(r,n,i)=>{s(t.map((c,x)=>x===r?{...c,[n]:i}:c))};return e.jsxs("div",{className:"space-y-6",children:[t.map((r,n)=>e.jsxs("div",{className:"p-4 bg-[var(--color-bg-surface)] rounded-xl border border-[var(--color-border-default)] space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-semibold text-[var(--color-brand-400)]",children:["Persona ",n+1]}),t.length>1&&e.jsx("button",{type:"button",onClick:()=>s(t.filter((i,c)=>c!==n)),className:"text-[var(--color-text-secondary)] hover:text-[var(--color-error)] transition-colors","aria-label":"Remove persona",children:e.jsx(le,{size:14})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(B,{label:"Name / Label",children:e.jsx("input",{type:"text",value:r.name,onChange:i=>a(n,"name",i.target.value),placeholder:"e.g., Marketing Manager",className:ee})}),e.jsx(B,{label:"Age Range",children:e.jsx("input",{type:"text",value:r.ageRange,onChange:i=>a(n,"ageRange",i.target.value),placeholder:"e.g., 28-45",className:ee})})]}),e.jsx(B,{label:"Role / Title",children:e.jsx("input",{type:"text",value:r.roleTitle,onChange:i=>a(n,"roleTitle",i.target.value),placeholder:"e.g., Marketing Manager at mid-size SaaS company",className:ee})}),e.jsx(B,{label:"Pain Points",hint:"What frustrates them or holds them back?",children:e.jsx("textarea",{rows:3,value:r.painPoints,onChange:i=>a(n,"painPoints",i.target.value),placeholder:"e.g., Too many tools, not enough consolidated insights; hard to prove ROI to leadership",className:H})}),e.jsx(B,{label:"Goals",hint:"What are they trying to achieve?",children:e.jsx("textarea",{rows:3,value:r.goals,onChange:i=>a(n,"goals",i.target.value),placeholder:"e.g., Reduce reporting time by 50%, increase qualified lead volume, automate social publishing",className:H})})]},n)),e.jsxs("button",{type:"button",onClick:()=>s([...t,{name:"",ageRange:"",roleTitle:"",painPoints:"",goals:""}]),className:"flex items-center gap-2 text-[var(--color-brand-400)] hover:text-[var(--color-brand-400)] text-sm font-medium transition-colors",children:[e.jsx(J,{size:14})," Add persona"]})]})},Gs=({budget:t,onChange:s})=>e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(B,{label:"Monthly Budget",children:e.jsx("input",{type:"number",min:0,value:t.monthly,onChange:a=>s({...t,monthly:a.target.value}),placeholder:"e.g., 5000",className:ee})}),e.jsx(B,{label:"Currency",children:e.jsx("select",{value:t.currency,onChange:a=>s({...t,currency:a.target.value}),className:ee,children:Fs.map(a=>e.jsx("option",{value:a,children:a},a))})})]}),e.jsx(B,{label:"Budget Breakdown by Channel",hint:"Describe how your budget is or should be allocated across channels",children:e.jsx("textarea",{rows:4,value:t.channelBreakdown,onChange:a=>s({...t,channelBreakdown:a.target.value}),placeholder:"e.g., 40% Paid Social, 30% SEO/Content, 20% Email, 10% Events",className:H})})]}),Vs=({marketingHistory:t,onChange:s})=>{const a=r=>{const n=t.channelsUsed,i=n.includes(r)?n.filter(c=>c!==r):[...n,r];s({...t,channelsUsed:i})};return e.jsxs("div",{className:"space-y-5",children:[e.jsx(B,{label:"Channels You've Used",hint:"Check all that apply",children:e.jsx("div",{className:"flex flex-wrap gap-2 mt-1",children:Bs.map(r=>e.jsx("button",{type:"button",onClick:()=>a(r),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${t.channelsUsed.includes(r)?"bg-nexus-600/30 border-nexus-500 text-[var(--color-brand-400)]":"bg-[var(--color-bg-surface)] border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:border-nexus-500/50 hover:text-[var(--color-text-secondary)]"}`,children:r},r))})}),e.jsx(B,{label:"Past Campaigns Summary",hint:"Overview of past marketing campaigns and strategies",children:e.jsx("textarea",{rows:4,value:t.pastCampaigns,onChange:r=>s({...t,pastCampaigns:r.target.value}),placeholder:"e.g., Q4 2025 brand awareness campaign on LinkedIn and Instagram; email nurture sequence targeting trial users",className:H})}),e.jsx(B,{label:"Notable Wins",hint:"What has worked well?",children:e.jsx("textarea",{rows:3,value:t.notableWins,onChange:r=>s({...t,notableWins:r.target.value}),placeholder:"e.g., LinkedIn thought leadership content drove 3x organic reach;
1 webinar series generated 200 qualified leads",className:H})}),e.jsx(B,{label:"Notable Losses / Lessons",hint:"What hasn't worked — and what did you learn?",children:e.jsx("textarea",{rows:3,value:t.notableLosses,onChange:r=>s({...t,notableLosses:r.target.value}),placeholder:"e.g., Cold email outreach had <1% open rate; paid ads without retargeting burned through budget quickly",className:H})})]})},Hs=({postalAddress:t,onChange:s})=>e.jsx("div",{className:"space-y-5",children:e.jsx(B,{label:"CAN-SPAM Mailing Address",hint:"Your physical postal address. US CAN-SPAM law and similar regulations require a valid physical mailing address in the footer of commercial marketing emails. This appears in your email footers.",children:e.jsx("textarea",{rows:3,value:t,onChange:a=>s(a.target.value),placeholder:"e.g., Acme Inc, 500 Market St, Suite 400, San Francisco, CA 94105, USA",maxLength:512,className:H})})}),Xs=()=>{const[t]=l.useState(Xe),[s,a]=l.useState("products"),[r,n]=l.useState(Os),[i,c]=l.useState(""),[x,m]=l.useState(!0),[h,b]=l.useState(!1),[f,y]=l.useState(!1),[w,P]=l.useState(null),[E,D]=l.useState(null),[g,p]=l.useState(0);l.useEffect(()=>{let o=!1;const d=new AbortController,N={signal:d.signal,headers:{"X-Org-Id":t}};return m(!0),D(null),(async()=>{try{const k=await O("/v1/business-profile",N);!o&&k&&n(u=>({...u,...k.products&&{products:k.products},...k.competitors&&{competitors:k.competitors},...k.brandVoice&&{brandVoice:{...u.brandVoice,...k.brandVoice}},...k.personas&&{personas:k.personas},...k.budget&&{budget:{...u.budget,...k.budget}},...k.marketingHistory&&{marketingHistory:{...u.marketingHistory,...k.marketingHistory}}}))}catch{o||D("Could not load workspace defaults. Retry before editing to protect your saved data.")}if(!o)try{const k=await O("/v1/business-profile/postal-address",N);!o&&(k!=null&&k.postalAddress)&&c(k.postalAddress)}catch{o||D("Could not load workspace compliance details. Retry before editing.")}finally{o||m(!1)}})(),()=>{o=!0,d.abort()}},[g,t]);const C=l.useCallback(async()=>{if(x||E||!t||Xe()!==t)return;const o={headers:{"X-Org-Id":t}};b(!0),y(!1),P(null);try{if(s==="compliance")await Se("/v1/business-profile/postal-address",{postalAddress:i.trim()||null},o);else{const d=r[s];await Se(`/v1/business-profile/${s}`,d,o)}y(!0),setTimeout(()=>y(!1),3e3)}catch{P("Failed to save. Please try again.")}finally{b(!1)}},[s,r,i,x,E,t]);return x?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(L,{size:24,className:"animate-spin text-[var(--color-brand-400)]"})}):E?e.jsxs("div",{className:"max-w-3xl space-y-4",children:[e.jsx("h1",{className:"text-xl font-bold text-[var(--color-text-primary)]",children:"Workspace defaults"}),e.jsx("p",{role:"alert",className:"text-[var(--color-error)]",children:E}),e.jsx("button",{type:"button",className:"text-[var(--color-brand-400)] underline",onClick:()=>p(o=>o+1),children:"Retry"})]}):e.jsxs("div",{className:"max-w-3xl space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-[var(--color-text-primary)]",children:"Workspace defaults"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] text-sm mt-1",children:"Shared AI context and compliance details for the entire workspace. These settings are not the selected business’s profile. Manage each separate business from Businesses."}),Object.values(r).every(o=>!o||Array.isArray(o)&&o.length===0)&&e.jsx("div",{className:"mt-3 p-3 bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg text-[var(--color-text-secondary)] text-sm",children:"Add shared defaults only when they apply across your businesses."})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-1 border-b border-[var(--color-border-default)]",children:_s.map(o=>e.jsx("button",{type:"button","aria-pressed":s===o.id,onClick:()=>{a(o.id),y(!1),P(null)},className:`px-4 py-2 rounded-t-lg text-sm font-medium whitespace-nowrap transition-colors ${s===o.id?"bg-nexus-600/20 text-[var(--color-brand-400)] border-b-2 border-nexus-500":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-surface)]"}`,children:o.label},o.id))}),e.jsxs("div",{className:"min-h-[300px]",children:[s==="products"&&e.jsx(Ws,{products:r.products,onChange:o=>n(d=>({...d,products:o}))}),s==="competitors"&&e.jsx(qs,{competitors:r.competitors,onChange:o=>n(d=>({...d,competitors:o}))}),s==="brandVoice"&&e.jsx(Ks,{brandVoice:r.brandVoice,onChange:o=>n(d=>({...d,brandVoice:o}))}),s==="personas"&&e.jsx(Ys,{personas:r.personas,onChange:o=>n(d=>({...d,personas:o}))}),s==="budget"&&e.jsx(Gs,{budget:r.budget,onChange:o=>n(d=>({...d,budget:o}))}),s==="marketingHistory"&&e.jsx(Vs,{marketingHistory:r.marketingHistory,onChange:o=>n(d=>({...d,marketingHistory:o}))}),s==="compliance"&&e.jsx(Hs,{postalAddress:i,onChange:c})]}),f&&e.jsxs("div",{role:"status",className:"flex items-center gap-2 text-[var(--color-success)] text-sm",children:[e.jsx(Dt,{size:16}),"Saved successfully"]}),w&&e.jsxs("div",{className:"flex items-center gap-2 text-[var(--color-error)] text-sm",role:"alert",children:[e.jsx(oe,{size:16}),w]}),e.jsx("div",{className:"flex justify-end pt-2 border-t border-[var(--color-border-default)]",children:e.jsx("button",{type:"button",onClick:()=>void C(),disabled:h,className:"flex items-center gap-2 px-5 py-2.5 rounded-lg bg-nexus-700 hover:bg-nexus-800 text-white font-semibold text-sm transition-all active:scale-95 disabled:opacity-60 disabled:cursor-not-allowed",children:h?e.jsxs(e.Fragment,{children:[e.jsx(L,{size:15,className:"animate-spin"}),"Saving…"]}):"Save this section"})})]})},Js=new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric"});function Qs(t){return Js.format(new Date(t*1e3))}function Zs(t,s){return new Intl.NumberFormat(void 0,{style:"currency",currency:s.toUpperCase(),minimumFractionDigits:2}).format(t/100)}function ea({status:t}){const a={paid:"bg-[var(--color-success-bg)] text-[var(--color-success)]",open:"bg-[var(--color-warning-bg)] text-[var(--color-warning)]",uncollectible:"bg-[var(--color-error-bg)] text-[var(--color-error)]",void:"bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)]",draft:"bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)]"}[t]??"bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)]";return e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium capitalize ${a}`,children:t})}function ze(){return e.jsx("tr",{className:"animate-pulse",children:[1,2,3,4,5].map(t=>e.jsx("td",{className:"whitespace-nowrap px-4 py-3",children:e.jsx("div",{className:"h-4 rounded bg-[var(--color-bg-elevated)]"})},t))})}function ta({limit:t=20}){const[s,a]=l.useState([]),[r,n]=l.useState(!0),[i,c]=l.useState(null);return l.useEffect(()=>{let x=!1;return n(!0),c(null),ys(t).then(m=>{x||a(m)}).catch(m=>{x||c(Z(m,"Failed to load invoices."))}).finally(()=>{x||n(!1)}),()=>{x=!0}},[t]),e.jsxs("div",{className:"rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shadow-sm",children:[e.jsxs("div",{className:"border-b border-[var(--color-border-default)] px-6 py-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--color-text-primary)]",children:"Invoice History"}),e.jsx("p",{className:"mt-0.5 text-sm text-[var(--color-text-secondary)]",children:"Download past invoices as PDFs."})]}),i&&e.jsx("div",{className:"px-6 py-4 text-sm text-[var(--color-error)]",children:i}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full divide-y divide-[var(--color-border-default)] text-sm",children:[e.jsx("thead",{className:"bg-[var(--color-bg-elevated)]",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"whitespace-nowrap px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-[var(--color-text-secondary)]",children:"Invoice #"}),e.jsx("th",{scope:"col",className:"whitespace-nowrap px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-[var(--color-text-secondary)]",children:"Date"}),e.jsx("th",{scope:"col",className:"whitespace-nowrap px-4 py-3 text-right text-xs font-medium uppercase tracking-wide text-[var(--color-text-secondary)]",children:"Amount"}),e.jsx("th",{scope:"col",className:"whitespace-nowrap px-4 py-3 text-left text-xs font-medium uppercase tracking-wide text-[var(--color-text-secondary)]",children:"Status"}),e.jsx("th",{scope:"col",className:"whitespace-nowrap px-4 py-3 text-right text-xs font-medium uppercase tracking-wide text-[var(--color-text-secondary)]",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-[var(--color-border-default)] bg-[var(--color-bg-surface)]",children:r?e.jsxs(e.Fragment,{children:[e.jsx(ze,{}),e.jsx(ze,{}),e.jsx(ze,{})]}):s.length===0&&!i?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"px-4 py-10 text-center text-sm text-[var(--color-text-secondary)]",children:"No invoices yet."})}):s.map(x=>e.jsxs("tr",{className:"hover:bg-[var(--color-bg-elevated)] transition-colors",children:[e.jsx("td",{className:"whitespace-nowrap px-4 py-3 font-mono text-[var(--color-text-primary)]",children:x.number??x.id}),e.jsx("td",{className:"whitespace-nowrap px-4 py-3 text-[var(--color-text-secondary)]",children:Qs(x.date)}),e.jsx("td",{className:"whitespace-nowrap px-4 py-3 text-right text-[var(--color-text-primary)]",children:Zs(x.status==="paid"?x.amountPaid:x.amountDue,x.currency)}),e.jsx("td",{className:"whitespace-nowrap px-4 py-3",children:e.jsx(ea,{status:x.status})}),e.jsx("td",{className:"whitespace-nowrap px-4 py-3 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-3",children:[x.pdfUrl&&e.jsx("a",{href:x.pdfUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[var(--color-info)] hover:text-[var(--color-info)] hover:underline","aria-label":`Download PDF for invoice ${x.number??x.id}`,children:"Download PDF"}),x.hostedUrl&&e.jsx("a",{href:x.hostedUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:underline","aria-label":`View invoice ${x.number??x.id} on Stripe`,children:"View"}),!x.pdfUrl&&!x.hostedUrl&&e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:"—"})]})})]},x.id))})]})})]})}const Ze=(t,s="USD")=>new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t),et=t=>new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),sa={active:"bg-green-500/10 border-green-500/30 text-green-400",past_due:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",canceled:"bg-red-500/10 border-red-500/30 text-red-400",paid:"bg-green-500/10 border-green-500/30 text-green-400",pending:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",failed:"bg-red-500/10 border-red-500/30 text-red-400"},aa={deposit:"Deposit",subscription:"Subscription",ai_compute:"AI Compute",communication:"Communication"},ra=()=>{var _,$,R,I,j;const t=Ye(),[s,a]=l.useState(!1),[r,n]=l.useState(null),[i,c]=l.useState(!0),[x,m]=l.useState(null),[h,b]=l.useState(!1),[f,y]=l.useState(1e3),[w,P]=l.useState(!1),[E,D]=l.useState("llm:google:gemini-2.5-flash"),[g,p]=l.useState(""),[C,o]=l.useState(1),[d,N]=l.useState(!1),[S,k]=l.useState(null),u=l.useCallback(async()=>{m(null),c(!0);try{const T=await Ns();n(T)}catch(T){m(T instanceof Error?T.message:"Failed to load billing data")}finally{c(!1)}},[]);l.useEffect(()=>{u()},[u]);const v=async()=>
1{if(!(!w||h||(r==null?void 0:r.customerPaymentsEnabled)!==!0||r.refillCheckoutAvailable!==!0)){b(!0),m(null);try{const T=await ks(f),F=new URL(T.url);if(F.protocol!=="https:"||F.hostname!=="checkout.stripe.com")throw new Error("Stripe checkout returned an invalid destination.");window.location.assign(F.href)}catch(T){m(T instanceof Error?T.message:"Could not open credit checkout. No payment was confirmed here.")}finally{b(!1)}}},z=async()=>{if(!(!t||s||(r==null?void 0:r.customerPaymentsEnabled)!==!0)){a(!0),m(null);try{const T=await ws({orgId:t});if(!T.ok||!T.url)throw new Error(T.error||"Could not open billing management.");const F=new URL(T.url);if(F.protocol!=="https:"||F.hostname!=="billing.stripe.com")throw new Error("Billing management returned an invalid destination.");window.location.assign(F.href)}catch(T){m(T instanceof Error?T.message:"Could not open billing management.")}finally{a(!1)}}},A=async T=>{T.preventDefault(),N(!0),m(null),k(null);try{k(await Cs({serviceKey:E,providerCostCents:Number(g)*100,operations:C}))}catch(F){m(F instanceof Error?F.message:"Current rates are unavailable.")}finally{N(!1)}};if(i)return e.jsxs("div",{className:"max-w-3xl p-12 flex items-center justify-center",role:"status","aria-label":"Loading billing",children:[e.jsx(L,{className:"w-6 h-6 animate-spin text-nexus-500"}),e.jsx("span",{className:"sr-only",children:"Loading billing data..."})]});if(x&&!r)return e.jsx("div",{className:"max-w-3xl",children:e.jsxs("div",{className:"flex items-center gap-3 p-4 rounded-xl bg-red-500/10 border border-red-500/30 text-[var(--color-error)]",role:"alert",children:[e.jsx(K,{className:"w-5 h-5 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Failed to load billing data"}),e.jsx("p",{className:"text-sm mt-1",children:x})]}),e.jsxs("button",{onClick:u,className:"flex items-center gap-1 px-3 py-1.5 rounded-lg bg-red-500/20 hover:bg-red-500/30 text-[var(--color-error)] text-sm font-medium transition-colors",children:[e.jsx(de,{className:"w-3.5 h-3.5"}),"Retry"]})]})});if(!r)return null;const M={pro:"Operator",enterprise:"Growth",command:"Command"}[((_=r.subscription)==null?void 0:_.planId)??""]??"No active plan";return e.jsxs("div",{className:"max-w-4xl space-y-6",children:[e.jsxs("header",{children:[e.jsx("h2",{className:"text-2xl font-bold text-[var(--color-text-primary)]",children:"Workspace billing"}),e.jsx("p",{className:"mt-2 text-sm text-[var(--color-text-secondary)]",children:"Manage the shared subscription, credit balance and invoices for all your businesses. This is not a single business’s advertising budget."})]}),r.customerPaymentsEnabled===!1&&e.jsx("p",{role:"status",className:"rounded-lg border border-amber-600 p-4 text-sm text-amber-200",children:"Customer payments and credit refills are disabled. Your assigned plan and internal credits remain available; no Stripe checkout or billing portal can be opened."}),x&&e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-red-500/10 border border-red-500/30 text-[var(--color-error)]",role:"alert",children:[e.jsx(K,{size:16}),e.jsx("span",{className:"text-sm",children:x})]}),e.jsxs("div",{className:"bg-slate-800 border border-slate-700 rounded-xl p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-9 h-9 bg-nexus-500/20 rounded-xl flex items-center justify-center",children:e.jsx(mt,{className:"w-4 h-4 text-nexus-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-100",children:"Subscription"}),e.jsx("p",{className:"text-xs text-slate-400",children:"One plan for the workspace and all its businesses"})]})]}),r.subscription?e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-400 block mb-1",children:"Plan"}),e.jsx("span",{className:"text-sm font-medium text-white capitalize",children:M})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-400 block mb-1",children:"Status"}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border ${sa[r.subscription.status]??"text-slate-400"}`,children:[r.subscription.status==="active"&&e.jsx(ce,{className:"w-3 h-3"}),r.subscription.status==="past_due"&&e.jsx(ie,{className:"w-3 h-3"}),r.subscription.status==="canceled"&&e.jsx(K,{className:"w-3 h-3"}),r.subscription.status.replace("_"," ")]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-400 block mb-1",children:"Current period ends"}),e.jsxs("span",{className:"text-sm text-slate-200 flex items-center gap-1",children:[e.jsx(ut,{className:"w-3.5 h-3.5 text-slate-400"}),r.subscription.nextBillingDate?et(r.subscription.nextBillingDate):"Unavailable"]})]})]}):e.jsx("p",{className:"text-sm text-slate-300",children:"No active subscription. Choose a workspace plan to get started."}),e.jsxs("div",{className:"mt-5 flex flex-col sm:flex-row gap-3",children:[r.subscription&&e.jsx("button",{type:"button",onClick:()=>void z(),disabled:s||!t||r.customerPaymentsEnabled!==!0,className:"min-h-[44px] rounded-lg bg-nexus-600 px-4 py-2 text-sm font-semibold text-white hover:bg-nexus-500 disabled:opacity-60",children:s?"Opening Stripe…":"Manage subscription in Stripe"}),e.jsx("a",{href:"/settings/plans",className:"inline-flex min-h-[44px] items-center justify-center rounded-lg border border-slate-600 px-4 py-2 text-sm text-slate-100 hover:bg-slate-700",children:"Compare workspace plans"})]})]}),e.jsxs("div",{className:"bg-slate-800 border border-slate-700 rounded-xl p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-9 h-9 bg-emerald-500/20 rounded-xl flex items-center justify-center",children:e.jsx(Oe,{className:"w-4 h-4 text-emerald-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-100",children:"Wallet Balance (USD)"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Prepaid USD wallet — separate from plan credits"})]})]}),e.jsx("p",{className:"text-2xl font-bold text-white",children:Ze(r.balance,r.currency)}),(($=r.subscription)==null?void 0:$.includedCredits)!==null&&((R=r.subscription)==null?void 0:R.includedCredits)!==void 0&&r.subscription.includedCredits>0&&e.jsxs("p",{className:"text-xs text-slate-400 mt-1",children:[r.subscription.includedCredits.toLocaleStr
1ing()," credits included with plan"]})]}),e.jsxs("section",{className:"bg-slate-800 border border-slate-700 rounded-xl p-5 space-y-3","aria-labelledby":"credit-balance-title",children:[e.jsx("h3",{id:"credit-balance-title",className:"text-sm font-semibold text-slate-100",children:"Usage credits"}),e.jsx("p",{className:"text-2xl font-bold text-white",children:r.creditBalance===void 0?"Unavailable":r.creditBalance.toLocaleString()}),e.jsxs("p",{className:"text-sm text-slate-300",children:["Monthly allotment remaining: ",((I=r.allotmentCredits)==null?void 0:I.toLocaleString())??"Unavailable","."," ","Purchased credits: ",((j=r.purchasedCredits)==null?void 0:j.toLocaleString())??"Unavailable","."]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Monthly credits reset on renewal; purchased credits are retained and can fund eligible metered work. Credits are not an advertising budget, and subscription-tier features require an active plan."}),(r.paidWorkReady!==!0||r.reconciliationRequired)&&e.jsx("p",{role:"status",className:"text-sm text-amber-300",children:r.reconciliationRequired?"Your credit account needs a billing review before paid work can run. Contact support.":"Paid AI work is currently unavailable for this workspace. Check with support before starting paid work."})]}),e.jsxs("section",{className:"bg-slate-800 border border-slate-700 rounded-xl p-5 space-y-3","aria-labelledby":"credit-purchase-title",children:[e.jsx("h3",{id:"credit-purchase-title",className:"text-sm font-semibold text-slate-100",children:"Purchase credits"}),e.jsx("p",{className:"text-sm text-slate-300",children:"Buy credits once, then review and confirm payment in Stripe. Automatic refill is not enabled; a saved subscription card does not authorize extra purchases."}),e.jsx("label",{className:"block text-sm text-slate-300",htmlFor:"purchase-credits",children:"Credits to purchase (50–10,000,000)"}),e.jsx("input",{id:"purchase-credits",type:"number",min:"50",max:"10000000",step:"1",value:f,onChange:T=>{y(Number(T.target.value)),P(!1)},className:"w-full sm:max-w-xs px-3 py-2 bg-slate-700 rounded-lg text-white"}),e.jsx("p",{className:"text-sm text-slate-300",children:"Review the current purchase price and applicable taxes in Stripe. Credits appear only after payment confirmation."}),e.jsxs("label",{className:"flex items-start gap-2 text-sm text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:w,onChange:T=>P(T.target.checked)}),"I want a one-time purchase of ",f.toLocaleString()," credits and will review the payment in Stripe. This does not enable automatic refill."]}),e.jsx("button",{type:"button",onClick:v,disabled:h||!w||r.customerPaymentsEnabled!==!0||r.refillCheckoutAvailable!==!0||!Number.isSafeInteger(f)||f<50||f>1e7,className:"px-4 py-2 bg-nexus-600 rounded-lg text-white disabled:opacity-50",children:h?"Opening Stripe…":"Review one-time purchase in Stripe"}),r.refillCheckoutAvailable!==!0&&e.jsx("p",{className:"text-sm text-amber-300",children:"Credit checkout is currently unavailable."})]}),e.jsxs("details",{className:"bg-slate-800 border border-slate-700 rounded-xl p-5 space-y-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-slate-100",children:"Advanced: estimate credits for a known workload"}),e.jsx("p",{className:"text-sm text-slate-300",children:"For technical teams with a provider-cost estimate and service key. This uses the current billing rate, not a live provider price feed or a binding quote."}),e.jsxs("form",{onSubmit:A,className:"grid gap-3",children:[e.jsxs("label",{className:"text-sm text-slate-300",children:["Service key",e.jsx("input",{required:!0,maxLength:200,value:E,onChange:T=>{D(T.target.value),k(null)},className:"block w-full px-3 py-2 bg-slate-700 rounded-lg text-white"})]}),e.jsxs("label",{className:"text-sm text-slate-300",children:["Your estimated provider cost per operation (USD)",e.jsx("input",{required:!0,type:"number",min:"0",max:"1000000",step:"any",value:g,onChange:T=>{p(T.target.value),k(null)},className:"block w-full px-3 py-2 bg-slate-700 rounded-lg text-white"})]}),e.jsxs("label",{className:"text-sm text-slate-300",children:["Number of operations",e.
1jsx("input",{required:!0,type:"number",min:"1",max:"100000",step:"1",value:C,onChange:T=>{o(Number(T.target.value)),k(null)},className:"block w-full px-3 py-2 bg-slate-700 rounded-lg text-white"})]}),e.jsx("button",{disabled:d,className:"px-4 py-2 bg-nexus-600 rounded-lg text-white disabled:opacity-50",children:d?"Fetching rate…":"Calculate estimated credits"})]}),S&&e.jsxs("div",{role:"status",className:"text-sm text-slate-300",children:[e.jsxs("p",{children:[S.totalCredits.toLocaleString()," estimated credits (",S.credits.toLocaleString()," per operation, ",S.multiplier,"× markup)."]}),e.jsx("p",{children:S.basis}),e.jsxs("p",{children:["Excludes: ",S.excludes]})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Advertising budgets, taxes, external delivery/vendor fees and costs absent from your estimate are excluded. Actual model routing, tokens, media size and delivery destination can change usage; final settlement can exceed the initial reservation."})]}),e.jsxs("div",{className:"bg-slate-800 border border-slate-700 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"flex items-center gap-2 px-5 py-3 border-b border-slate-700",children:e.jsx("h3",{className:"text-sm font-semibold text-slate-100",children:"Recent Transactions"})}),r.transactions.length===0?e.jsx("p",{className:"px-5 py-6 text-sm text-slate-400 text-center",children:"No transactions yet"}):e.jsx("div",{className:"divide-y divide-slate-700/50",children:r.transactions.slice(0,20).map(T=>e.jsxs("div",{className:"flex items-center gap-3 px-5 py-3",children:[e.jsx("div",{className:`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${T.type==="credit"?"bg-green-500/10":"bg-red-500/10"}`,children:T.type==="credit"?e.jsx(Pt,{className:"w-3.5 h-3.5 text-green-400"}):e.jsx($t,{className:"w-3.5 h-3.5 text-red-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-slate-200 truncate",children:T.description}),e.jsxs("p",{className:"text-xs text-slate-400",children:[et(T.timestamp),T.category?` · ${aa[T.category]??T.category}`:""]})]}),e.jsxs("span",{className:`text-sm font-medium whitespace-nowrap ${T.type==="credit"?"text-green-400":"text-red-400"}`,children:[T.type==="credit"?"+":"-",Ze(Math.abs(T.amount),r.currency)]})]},T.id))})]}),r.customerPaymentsEnabled===!0?e.jsx(ta,{}):e.jsx("p",{className:"text-sm text-slate-400",children:"Stripe invoice history is unavailable while customer payments are disabled or their status is unknown."})]})},tt={campaigns:{enabled:!0},mentions:{enabled:!0},billing:{enabled:!0},security:{enabled:!0},agent_actions:{enabled:!0},system:{enabled:!0}},yt=["campaigns","mentions","billing","security","agent_actions","system"],la={campaigns:{title:"Campaign updates",description:"Status changes, completion alerts"},mentions:{title:"Mentions",description:"When someone tags you in a conversation or comment"},billing:{title:"Billing",description:"Invoice ready, usage limit warnings, plan changes"},security:{title:"Security",description:"Login from new device, password changes"},agent_actions:{title:"Agent actions",description:"AI agent execution updates and approvals"},system:{title:"System",description:"Maintenance windows, feature updates"}},na=({checked:t,onChange:s,disabled:a,"aria-label":r})=>e.jsx("button",{type:"button",role:"switch","aria-checked":t,"aria-label":r,disabled:a,onClick:()=>s(!t),className:`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border-2 border-transparent transition-colors focus:outline-none focus:ring-2 focus:ring-teal-500 focus:ring-offset-2 focus:ring-offset-slate-800 disabled:opacity-50 disabled:cursor-not-allowed ${t?"bg-teal-600":"bg-slate-600"}`,children:e.jsx("span",{className:`pointer-events-none inline-block h-4 w-4 rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-4":"translate-x-0"}`})}),oa=()=>e.jsx("div",{className:"space-y-3","aria-label":"Loading notification preferences",children:yt.map(t=>e.jsxs("div",{className:"flex items-center justify-between py-3 animate-pulse",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"h-3.5 w-32 rounded bg-[var(--color-bg-elevated)]"}),e.jsx("div",{className:"h-2.5 w-48 rounded bg-[var(--color-bg-elevated)]"})]}),e.jsx("div",{className:"h-5 w-9 rounded-full bg-[var(--color-bg-elevated)]"})]},t))}),ia=()=>{const[t,s]=l.useState({...tt}),[a,r]=l.useState(!0),[n,i]=l.useState(null),[c,x]=l.useState(null),[m,h]=l.useState(!1),[b,f]=l.useState(!1),[y,w]=l.useState(!1),[P,E]=l.useState(0);l.useEffect(()=>{let p=!1;return r(!0),i(null),O("/v1/push-notifications/preferences").then(C=>{p||(s({...tt,...C}),f(!1))}).catch(C=>{pe.warn("NotificationPreferences","Failed to load preferences",C),p||i("Could not load your saved preferences. Retry before making changes.")}).finally(()=>{p||r(!1)}),()=>{p=!0}},[P]);const D=async()=>{h(!0),x(null),w(!1);try{await Se("/v1/push-notifications/preferences",t),f(!1),w(!0)}catch(p){pe.warn("NotificationPreferences","Failed to save preferences",p),x("Your changes were not saved. Try saving again.")}finally{h(!1)}},g=l.useCallback((p,C)=>{s(o=>({...o,[p]:{enabled:C}})),f(!0),w(!1)},[]);return e.jsxs("div",{className:"max-w-2xl space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold text-[var(--color-text-primary)]",children:"Notifications"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] mt-1",children:"Choose the updates you receive personally across this workspace. Save your changes before leaving."})]}),n&&e.jsxs("div",{role:"alert",className:"text-[var(--color-error)] text-sm",children:[n," ",e.jsx("button",{type:"button",className:"underline",onClick:()=>E(p=>p+1),children:"Retry"})]}),e.jsx("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl overflow-hidden",children:e.jsxs("fieldset",{disabled:a||m||!!n,children:[e.jsx("legend",{className:"sr-only",children:"Push notification delivery preferences"}),a?e.jsx("div",{className:"px-4",children:e.jsx(oa,{})}):e.jsx("div",{className:"px-4 divide-y divide-[var(--color-border-default)]",children:yt.map(p=>{var N;const{title:C,description:o}=la[p],d=((N=t[p])==null?void 0:N.enabled)??!0;return e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsxs("div",{className:"flex-1 min-w-0 pr-4",children:[e.jsx("div",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:C}),e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)] mt-0.5",children:o})]}),e.jsx(na,{checked:d,onChange:S=>g(p,S),disabled:m||!!n,"aria-label":`${d?"Disable":"Enable"} ${C} notifications`})]},p)})})]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("button",{type:"button",onClick:()=>void D(),disabled:!b||m||a||!!n,className:"px-4 py-2 rounded-lg bg-nexus-600 text-white disabled:opacity-50",children:m?"Saving…":"Save preferences"}),b&&!c&&e.jsx("span",{className:"text-sm text-[var(--color-text-secondary)]",children:"Unsaved changes"}),y&&e.jsx("span",{role:"status",className:"text-sm text-[var(--color-success)]",children:"Preferences saved"}),c&&e.jsx("span",{role:"alert",className:"text-sm text-[var(--color-error)]",children:c})]})]})};function Ge(t){return{...t,status:t.revokedAt!==null?"inactive":t.expiresAt!==null&&t.expiresAt<=Date.now()?"expired":"active",createdAt:new Date(t.createdAt).toISOString(),updatedAt:new Date(t.updatedAt).toISOString(),expiresAt:t.expiresAt===null?null:new Date(t.expiresAt).toISOString(),lastUsedAt:t.lastUsedAt===null?null:new Date(t.lastUsedAt).toISOString()}}async function ca(){return(await O("/v1/api-keys")).apiKeys.map(Ge)}async function da(t){const s=await V("/v1/api-keys",{name:t.name,scopes:t.scopes,expiresAt:t.expiresAt||void 0});return{...Ge(s.apiKey),key:s.key}}async function xa(t){return we(`/v1/api-keys/${t}`)}async function ma(t){const s=await V(`/v1/api-keys/${t}/rotate`,{});return{...Ge(s.apiKey),key:s.key}}function st(t){return t?new Date(t).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}):"—"}function ua(t){if(!t)return"Never";const s=Date.now()-new Date(t).getTime(),a=Math.floor(s/6e4);if(a<1)return"Just now";if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}const pa=({status:t})=>{const s={active:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",inactive:"bg-slate-500/20 text-slate-300 border-slate-500/30",expired:"bg-red-500/20 text-red-400 border-red-500/30"};return e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold border ${s[t]}`,children:t.charAt(0).toUpperCase()+t.slice(1)})},ha=({value:t,label:s="Copy"})=>{const[a,r]=l.useState(!1),n=te.useRef(void 0);te.useEffect(()=>()=>{n.current&&clearTimeout(n.current)},[]);const i=async()=>{try{await navigator.clipboard.writeText(t),r(!0),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>r(!1),2e3)}catch{}};return e.jsxs("button",{onClick:i,"aria-label":"Copy to clipboard",className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white text-xs font-medium transition-colors border border-slate-700",children:[a?e.jsx(ve,{size:13,className:"text-emerald-400"}):e.jsx(Te,{size:13}),a?"Copied!":s]})},ba=({onClose:t,onCreate:s,loading:a,error:r})=>{const[n,i]=l.useState(""),[c,x]=l.useState("read"),[m,h]=l.useState("never"),b=f=>{f.preventDefault();const y=m==="never"?null:m==="30d"?new Date(Date.now()+30*864e5).toISOString():m==="90d"?new Date(Date.now()+90*864e5).toISOString():new Date(Date.now()+365*864e5).toISOString();s({name:n.trim(),scopes:c==="write"?["read","write"]:["read"],expiresAt:y})};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl w-full max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-slate-800",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-nexus-500/20 flex items-center justify-center",children:e.jsx(me,{size:18,className:"text-nexus-400"})}),e.jsx("h2",{className:"text-lg font-bold text-white",children:"Create API Key"})]}),e.jsx("button",{onClick:t,"aria-label":"Close",className:"text-slate-300 hover:text-white transition-colors",children:e.jsx(re,{size:20})})]}),e.jsxs("form",{onSubmit:b,className:"p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-semibold text-slate-300 mb-2",children:["Name ",e.jsx("span",{className:"text-red-400",children:"*"})]}),e.jsx("input",{type:"text",value:n,onChange:f=>i(f.target.value),placeholder:"e.g. Production Backend",required:!0,className:"w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-2.5 text-white placeholder-slate-500 focus:outline-none focus:border-nexus-500 transition-colors text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"key-access",className:"block text-sm font-semibold text-slate-300 mb-2",children:"Access"}),e.jsxs("select",{id:"key-access",value:c,onChange:f=>x(f.target.value),className:"w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-2.5 text-white",children:[e.jsx("option",{value:"read",children:"Read only"}),e.jsx("option",{value:"write",children:"Read and write"})]}),e.jsx("p",{className:"text-xs text-slate-400 mt-2",children:"Use read-only access unless the connected tool needs to make changes."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-semibold text-slate-300 mb-2",children:"Expiration"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:["never","30d","90d","1y"].map(f=>e.jsx("button",{type:"button",onClick:()=>h(f),className:`px-3 py-2 rounded-lg text-xs font-semibold border transition-all ${m===f?"bg-nexus-500/20 border-nexus-500 text-nexus-300":"bg-slate-800 border-slate-700 text-slate-300 hover:border-slate-600"}`,children:f==="never"?"Never":f==="30d"?"30 days":f==="90d"?"90 days":"1 year"},f))})]}),r&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-900 border border-red-800 rounded-xl text-red-300 text-sm",children:[e.jsx(K,{size:15}),r]}),e.jsxs("div",{className:"flex gap-3 pt-1",children:[e.jsx("button",{type:"button",onClick:t,className:"flex-1 px-4 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-sm font-semibold transition-colors border border-slate-700",children:"Cancel"}),e.jsxs("button",{type:"submit",disabled:a||!n.trim(),className:"flex-1 px-4 py-2.5 rounded-xl bg-nexus-600 hover:bg-nexus-500 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-semibold transition-colors flex items-center justify-center gap-2",children:[a?e.jsx(L,{size:15,className:"animate-spin"}):e.jsx(J,{size:15}),"Create Key"]})]})]})]})})},fa=({apiKey:t,onClose:s,title:a="API Key Created"})=>{const[r,n]=l.useState(!1);return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl w-full max-w-lg",children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-slate-800",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-emerald-500/20 flex items-center justify-center",children:e.jsx(me,{size:18,className:"text-emerald-400"})}),e.jsx("h2",{className:"text-lg font-bold text-white",children:a})]}),e.jsx("button",{onClick:s,"aria-label":"Close",className:"text-slate-300 hover:text-white transition-colors",children:e.jsx(re,{size:20})})]}),e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-amber-500/10 border border-amber-500/30 rounded-xl",children:[e.jsx(Ee,{size:18,className:"text-amber-400 shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-amber-300 text-sm leading-relaxed",children:[e.jsx("strong",{children:"Copy this key now."})," For security reasons, it will not be shown again after you close this dialog."]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-300 uppercase tracking-wider",children:"Your API Key"}),e.jsx("button",{onClick:()=>n(i=>!i),className:"text-slate-300 hover:text-white transition-colors","aria-label":r?"Hide key":"Reveal key",children:r?e.jsx(zt,{size:15}):e.jsx(It,{size:15})})]}),e.jsxs("div",{className:"flex items-center gap-2 bg-slate-800 border border-slate-700 rounded-xl px-4 py-3",children:[e.jsx("code",{className:"flex-1 text-sm font-mono text-nexus-300 break-all select-all",children:r?t.key:t.key.replace(/./g,"•")}),e.jsx(ha,{value:t.key})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{className:"bg-slate-800 rounded-xl p-3",children:[e.jsx("span",{className:"text-slate-300 text-xs block mb-1",children:"Name"}),e.jsx("span",{className:"text-white font-medium",children:t.name})]}),e.jsxs("div",{className:"bg-slate-800 rounded-xl p-3",children:[e.jsx("span",{className:"text-slate-300 text-xs block mb-1",children:"Prefix"}),e.jsx("code",{className:"text-nexus-300 font-mono text-xs",children:t.prefix})]})]}),e.jsx("button",{onClick:s,className:"w-full px-4 py-2.5 rounded-xl bg-nexus-600 hover:bg-nexus-500 text-white text-sm font-semibold transition-colors",children:"I've saved my key"})]})]})})},at=({title:t,message:s,confirmLabel:a="Confirm",confirmVariant:r="danger",onConfirm:n,onCancel:i,loading:c})=>e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl w-full max-w-sm p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-9 h-9 rounded-xl flex items-center justify-center ${r==="danger"?"bg-red-500/20":"bg-
1amber-500/20"}`,children:e.jsx(K,{size:18,className:r==="danger"?"text-red-400":"text-amber-400"})}),e.jsx("h3",{className:"text-base font-bold text-white",children:t})]}),e.jsx("p",{className:"text-slate-300 text-sm leading-relaxed",children:s}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:i,className:"flex-1 px-4 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-sm font-semibold transition-colors border border-slate-700",children:"Cancel"}),e.jsxs("button",{onClick:n,disabled:c,className:`flex-1 px-4 py-2.5 rounded-xl text-white text-sm font-semibold transition-colors flex items-center justify-center gap-2 disabled:opacity-50 ${r==="danger"?"bg-red-600 hover:bg-red-500":"bg-amber-600 hover:bg-amber-500"}`,children:[c&&e.jsx(L,{size:14,className:"animate-spin"}),a]})]})]})}),ga=({apiKey:t,onDelete:s,onRotate:a,actionLoading:r,canManage:n})=>{const i=r===t.id;return e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3 p-4 bg-slate-800 rounded-xl border border-slate-700/60 hover:border-slate-600 transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-slate-700 flex items-center justify-center shrink-0",children:e.jsx(me,{size:16,className:"text-slate-300"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-white font-semibold text-sm truncate",children:t.name}),e.jsx(pa,{status:t.status})]}),t.description&&e.jsx("p",{className:"text-slate-300 text-xs mt-0.5 truncate",children:t.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 flex-wrap",children:[e.jsxs("code",{className:"text-nexus-300 text-xs font-mono bg-slate-900 px-2 py-0.5 rounded",children:[t.prefix,"••••••••"]}),e.jsxs("span",{className:"flex items-center gap-1 text-slate-400 text-xs",children:[e.jsx(ie,{size:11}),"Created ",st(t.createdAt)]}),t.expiresAt&&e.jsxs("span",{className:"flex items-center gap-1 text-slate-400 text-xs",children:[e.jsx(K,{size:11,className:"text-amber-400"}),"Expires ",st(t.expiresAt)]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 text-slate-300 text-xs mr-2",children:[e.jsx(We,{size:12}),e.jsxs("span",{children:["Last used: ",ua(t.lastUsedAt)]})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>a(t.id),disabled:i,title:"Rotate key",className:"p-2 rounded-lg bg-slate-700 hover:bg-amber-500/20 hover:text-amber-400 text-slate-300 transition-colors disabled:opacity-50 border border-slate-600",children:i?e.jsx(L,{size:14,className:"animate-spin"}):e.jsx(de,{size:14})}),e.jsx("button",{onClick:()=>s(t.id),disabled:i,title:"Delete key",className:"p-2 rounded-lg bg-slate-700 hover:bg-red-500/20 hover:text-red-400 text-slate-300 transition-colors disabled:opacity-50 border border-slate-600",children:e.jsx(le,{size:14})})]})]})]})},va=({onCreate:t,canManage:s})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-slate-800 border border-slate-700 flex items-center justify-center mb-5",children:e.jsx(me,{size:28,className:"text-slate-400"})}),e.jsx("h3",{className:"text-lg font-bold text-[var(--color-text-primary)] mb-2",children:"No API keys"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] max-w-xs text-sm leading-relaxed mb-6",children:s?"Create a key for programmatic access to this workspace.":"Ask a workspace owner or administrator to create a key when an integration needs one."}),s&&e.jsxs("button",{onClick:t,"aria-label":"Create API key",className:"inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-nexus-600 hover:bg-nexus-500 text-white text-sm font-semibold transition-colors",children:[e.jsx(J,{size:16}),"Create Your First API Key"]})]}),ja=()=>{const{role:t,isLoading:s,error:a}=vs(),r=!s&&t==="admin",[n,i]=l.useState([]),[c,x]=l.useState(!0),[m,h]=l.useState(null),[b,f]=l.useState(!1),[y,w]=l.useState(!1),[P,E]=l.useState(null),[D,g]=l.useState(null),[p,C]=l.useState("API Key Created"),[o,d]=l.useState(null),[N,S]=l.useState(null),[k,u]=l.useState(null),v=l.useCallback(async()=>{try{x(!0),h(null);const _=await ca();i(_)}catch(_){pe.warn("ApiKeysPage","Could not load API keys:",_),h("Failed to load API keys. Please try again."),i([])}finally{x(!1)}},[]);l.useEffect(()=>
1{v()},[v]);const z=async _=>{var $;if(r)try{w(!0),E(null);const R=await da(_);i(I=>[R,...I]),f(!1),C("API Key Created"),g(R)}catch(R){const I=(($=R==null?void 0:R.error)==null?void 0:$.message)??"Failed to create API key.";E(I)}finally{w(!1)}},A=async _=>{if(r)try{d(_),await xa(_),i($=>$.filter(R=>R.id!==_))}catch{h("Failed to delete key. Please try again.")}finally{d(null),S(null)}},M=async _=>{if(r)try{d(_);const $=await ma(_);i(R=>R.map(I=>I.id===_?$:I)),u(null),C("API Key Rotated"),g($)}catch{h("Failed to rotate key. Please try again.")}finally{d(null)}};return e.jsxs("div",{className:"p-0 sm:p-4 space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-[var(--color-text-primary)] flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-nexus-500/20 flex items-center justify-center",children:e.jsx(me,{size:20,className:"text-[var(--color-brand-400)]"})}),"API Keys"]}),e.jsx("p",{className:"text-[var(--color-text-secondary)] text-sm mt-1 ml-12",children:"Developer access to this workspace across all businesses. Only workspace owners and administrators can manage keys."})]}),r&&e.jsxs("button",{onClick:()=>{E(null),f(!0)},"aria-label":"Create API key",className:"inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-nexus-600 hover:bg-nexus-500 text-white text-sm font-semibold transition-colors shadow-lg shadow-nexus-900/30",children:[e.jsx(J,{size:16}),"Create API Key"]}),a&&e.jsx("p",{role:"alert",className:"text-sm text-[var(--color-error)]",children:a})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-slate-800 border border-slate-700 rounded-xl text-sm",children:[e.jsx(Ee,{size:16,className:"text-nexus-400 shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-slate-300 leading-relaxed",children:["API keys grant access to your organization's data. Keep them secret and never share them in public repositories or client-side code. Keys are prefixed with ",e.jsx("code",{className:"text-nexus-300 font-mono text-xs bg-slate-900 px-1.5 py-0.5 rounded",children:"nex_live_"}),"."]})]}),m&&e.jsxs("div",{role:"alert",className:"flex items-center gap-3 p-4 bg-red-900 border border-red-800 rounded-xl text-red-300 text-sm",children:[e.jsx(K,{size:16}),e.jsx("span",{className:"flex-1",children:m}),e.jsx("button",{onClick:v,className:"text-red-200 hover:text-white text-xs font-semibold underline",children:"Retry"}),e.jsx("button",{onClick:()=>h(null),className:"text-red-400 hover:text-red-200","aria-label":"Dismiss error",children:e.jsx(re,{size:16})})]}),c?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(L,{size:28,className:"animate-spin text-[var(--color-brand-400)]"})}):m&&n.length===0?null:n.length===0?e.jsx(va,{canManage:r,onCreate:()=>{E(null),f(!0)}}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm text-[var(--color-text-secondary)]",children:[n.length," key",n.length!==1?"s":""]}),e.jsxs("button",{onClick:v,className:"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-xs flex items-center gap-1.5 transition-colors",children:[e.jsx(de,{size:12}),"Refresh"]})]}),n.map(_=>e.jsx(ga,{apiKey:_,canManage:r,onDelete:$=>S($),onRotate:$=>u($),actionLoading:o},_.id))]}),b&&e.jsx(ba,{onClose:()=>f(!1),onCreate:z,loading:y,error:P}),D&&e.jsx(fa,{apiKey:D,title:p,onClose:()=>g(null)}),N&&e.jsx(at,{title:"Delete API Key",message:"Are you sure you want to delete this key? Any applications using it will immediately lose access. This action cannot be undone.",confirmLabel:"Delete Key",confirmVariant:"danger",loading:o===N,onConfirm:()=>A(N),onCancel:()=>S(null)}),k&&e.jsx(at,{title:"Rotate API Key",message:"Rotating will invalidate the current key and generate a new one. Any applications using the current key will need to be updated immediately.",confirmLabel:"Rotate Key",confirmVariant:"warning",loading:o===k,onConfirm:()=>M(k),onCancel:()=>u(null)})]})},ya=te.memo(ja),Na=[{label:"Campaigns",events:["campaign.created","campaign.updated","campaign.completed"]},{label:"Leads",events:["lead.created","lead.updated"]},{label:"Workflows",events:["workflow.started","workflow.completed","workflow.failed"]},{label:"Analytics",events:["analytics.report_ready"]}
1,{label:"Social",events:["social.post_published","social.post_failed"]},{label:"Billing",events:["billing.subscription_updated","billing.payment_succeeded","billing.payment_failed"]}];function De(t){return{...t,active:t.enabled,createdAt:new Date(t.createdAt).toISOString(),updatedAt:new Date(t.updatedAt).toISOString()}}async function wa(){return(await O("/v1/webhooks")).webhooks.map(De)}async function ka(t){return De(await V("/v1/webhooks",{url:t.url,events:t.events,enabled:t.active}))}async function Ca(t,s){return De(await ke(`/v1/webhooks/${t}`,{url:s.url,events:s.events,enabled:s.active}))}async function Sa(t){return we(`/v1/webhooks/${t}`)}async function Aa(t){return V(`/v1/webhooks/${t}/test`,{})}async function Ea(t){return(await O(`/v1/webhooks/${t}/logs`)).logs.map(a=>({id:a.id,webhookId:a.webhookId,event:`Delivery ${a.deliveryId}`,status:a.status==="success"?"success":"failed",statusCode:a.statusCode,responseBody:a.responseBody,duration:a.latencyMs,createdAt:new Date(a.timestamp).toISOString(),retryCount:Math.max(0,a.attempt-1)}))}async function Ta(t){const s=await O(`/v1/webhooks/${t}/stats`);return{...s,avgResponseTime:s.averageLatencyMs}}async function Ra(t){return De(await V(`/v1/webhooks/${t}/rotate-secret`,{}))}function Nt(t){if(!t)return"Never";const s=Date.now()-new Date(t).getTime(),a=Math.floor(s/6e4);if(a<1)return"Just now";if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function wt(t,s=50){return t.length<=s?t:t.slice(0,s)+"…"}const kt=({active:t})=>e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold border ${t?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-slate-500/20 text-slate-300 border-slate-500/30"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-emerald-400":"bg-slate-500"}`}),t?"Active":"Inactive"]}),Da=({status:t})=>{const s={success:"bg-emerald-500/20 text-emerald-400",failed:"bg-red-500/20 text-red-400",pending:"bg-amber-500/20 text-amber-400"},a={success:e.jsx(ce,{size:12}),failed:e.jsx(Re,{size:12}),pending:e.jsx(ie,{size:12})};return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold ${s[t]}`,children:[a[t],t.charAt(0).toUpperCase()+t.slice(1)]})},Pa=({value:t,label:s="Copy"})=>{const[a,r]=l.useState(!1),n=te.useRef(void 0);te.useEffect(()=>()=>{n.current&&clearTimeout(n.current)},[]);const i=async()=>{try{await navigator.clipboard.writeText(t),r(!0),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>r(!1),2e3)}catch{}};return e.jsxs("button",{onClick:i,"aria-label":a?"Copied to clipboard":`Copy ${s}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white text-xs font-medium transition-colors border border-slate-700",children:[a?e.jsx(ve,{size:13,className:"text-emerald-400"}):e.jsx(Te,{size:13}),a?"Copied!":s]})},$a=({selected:t,onChange:s})=>{const a=n=>{s(t.includes(n)?t.filter(i=>i!==n):[...t,n])},r=n=>{const i=n.every(c=>t.includes(c));s(i?t.filter(c=>!n.includes(c)):[...new Set([...t,...n])])};return e.jsx("div",{className:"space-y-3",children:Na.map(n=>{const i=n.events.every(x=>t.includes(x)),c=n.events.some(x=>t.includes(x));return e.jsxs("div",{className:"bg-slate-800 rounded-xl border border-slate-700 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>r(n.events),className:"w-full flex items-center justify-between px-4 py-2.5 text-left hover:bg-slate-700/50 transition-colors",children:[e.jsx("span",{className:"text-sm font-semibold text-slate-200",children:n.label}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-slate-300",children:[n.events.filter(x=>t.includes(x)).length,"/",n.events.length]}),e.jsx("div",{className:`w-4 h-4 rounded flex items-center justify-center border ${i?"bg-nexus-500 border-nexus-500":c?"bg-nexus-500/30 border-nexus-500/50":"border-slate-600"}`,children:(i||c)&&e.jsx(ve,{size:10,className:"text-white"})})]})]}),e.jsx("div",{className:"px-4 pb-3 grid grid-cols-1 gap-1.5",children:n.events.map(x=>e.jsxs("label",{className:"flex items-center gap-2.5 cursor-pointer group",children:[e.jsx("div",{onClick:()=>a(x),className:`w-4 h-4 rounded flex items-center justify-center border shrink-0 transition-colors cursor-pointer ${t.includes(x)?"bg-nexus-500 border-nexus-500":"border-slate-600 group-hover:border-slate-500"}
1`,children:t.includes(x)&&e.jsx(ve,{size:10,className:"text-white"})}),e.jsx("code",{onClick:()=>a(x),className:"text-xs font-mono text-slate-300 group-hover:text-white transition-colors",children:x})]},x))})]},n.label)})})},rt=({webhook:t,onClose:s,onSave:a,loading:r,error:n})=>{const i=!!t,[c,x]=l.useState((t==null?void 0:t.url)??""),[m,h]=l.useState((t==null?void 0:t.events)??[]),[b,f]=l.useState((t==null?void 0:t.active)??!0),y=w=>{w.preventDefault(),a({url:c.trim(),events:m,active:b})};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"webhook-form-title",className:"bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-slate-800 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-nexus-500/20 flex items-center justify-center",children:e.jsx(Ne,{size:18,className:"text-nexus-400"})}),e.jsx("h2",{id:"webhook-form-title",className:"text-lg font-bold text-white",children:i?"Edit Webhook":"Create Webhook"})]}),e.jsx("button",{onClick:s,"aria-label":"Close webhook form",className:"text-slate-300 hover:text-white transition-colors",children:e.jsx(re,{size:20})})]}),e.jsxs("form",{onSubmit:y,className:"flex-1 overflow-y-auto p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-semibold text-slate-300 mb-2",children:["Endpoint URL ",e.jsx("span",{className:"text-red-400",children:"*"})]}),e.jsx("input",{type:"url",value:c,onChange:w=>x(w.target.value),placeholder:"https://your-endpoint.com",required:!0,"aria-required":"true",className:"w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-2.5 text-white placeholder-slate-500 focus:outline-none focus:border-nexus-500 transition-colors text-sm"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("label",{className:"text-sm font-semibold text-slate-300",children:["Events ",e.jsx("span",{className:"text-red-400",children:"*"})]}),e.jsxs("span",{className:"text-xs text-slate-300",children:[m.length," selected"]})]}),e.jsx($a,{selected:m,onChange:h})]}),i&&e.jsxs("div",{className:"flex items-center justify-between p-4 bg-slate-800 rounded-xl border border-slate-700",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-semibold text-slate-200",children:"Active"}),e.jsx("p",{className:"text-xs text-slate-300 mt-0.5",children:"Enable or disable event delivery"})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":b,"aria-label":"Toggle webhook active state",onClick:()=>f(w=>!w),className:`relative w-10 h-6 rounded-full transition-colors ${b?"bg-nexus-500":"bg-slate-700"}`,children:e.jsx("span",{className:`absolute top-1 w-4 h-4 rounded-full bg-white shadow transition-transform ${b?"translate-x-5":"translate-x-1"}`})})]}),n&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-900 border border-red-800 rounded-xl text-red-300 text-sm",children:[e.jsx(K,{size:15}),n]})]}),e.jsxs("div",{className:"flex gap-3 p-6 border-t border-slate-800 shrink-0",children:[e.jsx("button",{type:"button",onClick:s,className:"flex-1 px-4 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-sm font-semibold transition-colors border border-slate-700",children:"Cancel"}),e.jsxs("button",{onClick:y,disabled:r||!c.trim()||m.length===0,className:"flex-1 px-4 py-2.5 rounded-xl bg-nexus-600 hover:bg-nexus-500 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-semibold transition-colors flex items-center justify-center gap-2",children:[r?e.jsx(L,{size:15,className:"animate-spin"}):i?e.jsx(pt,{size:15}):e.jsx(J,{size:15}),i?"Save Changes":"Create Webhook"]})]})]})})},za=({secret:t,title:s="Webhook Secret",onClose:a})=>e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"secret-display-title",className:"bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl w-full max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-slate-800",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-emerald-500/20 flex items-center justify-center",children:e.jsx(me,{size:18,className:"text-emerald-400"})}),e.jsx("h2",{id:"secret-display-title",className:"text-lg font-bold text-white",children:s})]}),e.jsx("button",{onClick:a,"aria-label":"Close secret display",className:"text-slate-300 hover:text-white transition-colors",children:e.jsx(re,{size:20})})]}),e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-amber-500/10 border border-amber-500/30 rounded-xl",children:[e.jsx(Ee,{size:18,className:"text-amber-400 shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-amber-300 text-sm leading-relaxed",children:[e.jsx("strong",{children:"Save this secret now."})," Use it to verify webhook signatures. It will not be shown again."]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-xs font-semibold text-slate-300 uppercase tracking-wider mb-2",children:"Signing Secret"}),e.jsxs("div",{className:"flex items-center gap-2 bg-slate-800 border border-slate-700 rounded-xl px-4 py-3",children:[e.jsx("code",{className:"flex-1 text-xs font-mono text-nexus-300 break-all select-all",children:t}),e.jsx(Pa,{value:t})]})]}),e.jsx("button",{onClick:a,className:"w-full px-4 py-2.5 rounded-xl bg-nexus-600 hover:bg-nexus-500 text-white text-sm font-semibold transition-colors",children:"I've saved my secret"})]})]})}),lt=({title:t,message:s,confirmLabel:a="Confirm",confirmVariant:r="danger",onConfirm:n,onCancel:i,loading:c})=>e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{role:"alertdialog","aria-modal":"true","aria-labelledby":"webhook-confirm-title","aria-describedby":"webhook-confirm-message",className:"bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl w-full max-w-sm p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-9 h-9 rounded-xl flex items-center justify-center ${r==="danger"?"bg-red-500/20":"bg-
1amber-500/20"}`,children:e.jsx(K,{size:18,className:r==="danger"?"text-red-400":"text-amber-400"})}),e.jsx("h3",{id:"webhook-confirm-title",className:"text-base font-bold text-white",children:t})]}),e.jsx("p",{id:"webhook-confirm-message",className:"text-slate-300 text-sm leading-relaxed",children:s}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:i,className:"flex-1 px-4 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-sm font-semibold transition-colors border border-slate-700",children:"Cancel"}),e.jsxs("button",{onClick:n,disabled:c,className:`flex-1 px-4 py-2.5 rounded-xl text-white text-sm font-semibold transition-colors flex items-center justify-center gap-2 disabled:opacity-50 ${r==="danger"?"bg-red-600 hover:bg-red-500":"bg-amber-600 hover:bg-amber-500"}`,children:[c&&e.jsx(L,{size:14,className:"animate-spin"}),a]})]})]})}),Ia=({webhook:t,onClose:s,onRotateSecret:a,onTest:r,actionLoading:n})=>{const[i,c]=l.useState([]),[x,m]=l.useState(null),[h,b]=l.useState(!0),[f,y]=l.useState("logs"),[w,P]=l.useState(null),[E,D]=l.useState(null),[g,p]=l.useState(0);l.useEffect(()=>{let o=!1;return(async()=>{b(!0),D(null);try{const[N,S]=await Promise.all([Ea(t.id),Ta(t.id)]);if(o)return;c(N),m(S)}
1catch{o||D("Could not load delivery history. Retry to see delivery status.")}finally{o||b(!1)}})(),()=>{o=!0}},[t.id,g]);const C=n===t.id;return e.jsxs("div",{className:"bg-slate-900 border border-slate-700 rounded-2xl overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between p-5 border-b border-slate-800",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-white font-semibold text-sm truncate",children:wt(t.url)}),e.jsx(kt,{active:t.active})]}),t.description&&e.jsx("p",{className:"text-slate-300 text-xs mt-1",children:t.description})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 ml-3",children:[e.jsx("button",{onClick:()=>r(t.id),disabled:C,title:"Send test event","aria-label":"Send test event",className:"p-2 rounded-lg bg-slate-800 hover:bg-nexus-500/20 hover:text-nexus-400 text-slate-300 transition-colors border border-slate-700 disabled:opacity-50",children:C?e.jsx(L,{size:14,className:"animate-spin"}):e.jsx(Lt,{size:14})}),e.jsx("button",{onClick:()=>a(t.id),disabled:C,title:"Rotate signing secret","aria-label":"Rotate signing secret",className:"p-2 rounded-lg bg-slate-800 hover:bg-amber-500/20 hover:text-amber-400 text-slate-300 transition-colors border border-slate-700 disabled:opacity-50",children:e.jsx(Mt,{size:14})}),e.jsx("button",{onClick:s,"aria-label":"Collapse webhook details",className:"p-2 rounded-lg text-slate-300 hover:text-white transition-colors",children:e.jsx(Me,{size:16})})]})]}),E&&e.jsxs("p",{role:"alert",className:"p-4 text-sm text-red-300",children:[E," ",e.jsx("button",{type:"button",className:"underline",onClick:()=>p(o=>o+1),children:"Retry"})]}),e.jsx("div",{className:"px-5 py-3 border-b border-slate-800 flex flex-wrap gap-1.5",children:t.events.map(o=>e.jsx("code",{className:"text-xs font-mono bg-slate-800 text-nexus-300 px-2 py-0.5 rounded-md border border-slate-700",children:o},o))}),e.jsx("div",{className:"flex border-b border-slate-800",children:["logs","stats"].map(o=>e.jsxs("button",{onClick:()=>y(o),className:`flex-1 py-3 text-sm font-semibold transition-colors flex items-center justify-center gap-2 ${f===o?"text-nexus-400 border-b-2 border-nexus-500":"text-slate-300 hover:text-slate-300"}`,children:[o==="logs"?e.jsx(We,{size:14}):e.jsx(ht,{size:14}),o.charAt(0).toUpperCase()+o.slice(1)]},o))}),e.jsx("div",{className:"p-5",children:h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(L,{size:24,className:"animate-spin text-nexus-400"})}):E?null:f==="stats"?x?e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:[{label:"Total Deliveries",value:x.totalDeliveries},{label:"Successful",value:x.successfulDeliveries},{label:"Failed",value:x.failedDeliveries},{label:"Success Rate",value:`${x.successRate.toFixed(1)}%`},{label:"Avg Response",value:x.avgResponseTime?`${x.avgResponseTime}ms`:"—"},{label:"Last 24h",value:x.last24hDeliveries??"—"}].map(o=>e.jsxs("div",{className:"bg-slate-800 rounded-xl p-3 border border-slate-700/60",children:[e.jsx("span",{className:"text-slate-300 text-xs block mb-1",children:o.label}),e.jsx("span",{className:"text-white font-bold text-lg",children:o.value})]},o.label))}):e.jsx("p",{className:"text-slate-300 text-sm text-center py-4",children:"No stats available"}):i.length===0?e.jsx("p",{className:"text-slate-300 text-sm text-center py-8",children:"No delivery logs yet"}):e.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:i.map(o=>e.jsxs("div",{className:"bg-slate-800 rounded-xl border border-slate-700/60 overflow-hidden",children:[e.jsxs("button",{onClick:()=>P(w===o.id?null:o.id),"aria-expanded":w===o.id,"aria-label":`Toggle delivery log details for ${o.event}`,className:"w-full flex items-center gap-3 p-3 text-left hover:bg-slate-700/30 transition-colors",children:[e.jsx(Da,{status:o.status}),e.jsx("code",{className:"text-xs font-mono text-slate-300 flex-1 truncate",children:o.event}),o.statusCode&&e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded ${o.statusCode<300?"text-emerald-400":"text-red-400"}`,children:o.statusCode}),o.duration&&e.jsxs("span",{className:"text-xs text-slate-400",children:[o.duration,"ms"]}),e.jsx("span",{className:"text-xs text-slate-400 shrink-0",children:Nt(o.createdAt)}),w===o.id?e.jsx(Me,{size:12,className:"text-slate-300"}):e.jsx(qe,{size:12,className:"text-slate-300"})]}),w===o.id&&(o.requestBody||o.responseBody)&&e.jsxs("div",{className:"border-t border-slate-700 p-3 space-y-2",children:[o.requestBody&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-300 font-semibold block mb-1",children:"Request"}),e.jsx("pre",{className:"text-xs font-mono text-slate-300 bg-slate-900 rounded-lg p-2 overflow-x-auto max-h-24",children:o.requestBody})]}),o.responseBody&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-300 font-semibold block mb-1",children:"Response"}),e.jsx("pre",{className:"text-xs font-mono text-slate-300 bg-slate-900 rounded-lg p-2 overflow-x-auto max-h-24",children:o.responseBody})]})]})]},o.id))})})]})},La=({webhook:t,expanded:s,onToggleExpand:a,onEdit:r,onDelete:n,onRotateSecret:i,onTest:c,actionLoading:x})=>e.jsxs("div",{className:"bg-slate-800 rounded-xl border border-slate-700/60 hover:border-slate-600 transition-colors overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-slate-700 flex items-center justify-center shrink-0",children:e.jsx(Ne,{size:16,className:"text-slate-300"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-white font-semibold text-sm truncate",children:wt(t.url)}),e.jsx(kt,{active:t.active})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 flex-wrap",children:[e.jsxs("span",{className:"text-slate-300 text-xs",children:[t.events.length," event",t.events.length!==1?"s":""]}),t.lastDeliveryAt&&e.jsxs("span",{className:"flex items-center gap-1 text-slate-400 text-xs",children:[e.jsx(We,{size:11}),"Last delivery: ",Nt(t.lastDeliveryAt),t.lastDeliveryStatus&&e.jsxs("span",{className:t.lastDeliveryStatus==="success"?"text-emerald-400":"text-red-400",children:["• ",t.lastDeliveryStatus]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("button",{onClick:r,title:"Edit webhook","aria-label":"Edit webhook",className:"p-2 rounded-lg bg-slate-700 hover:bg-nexus-500/20 hover:text-nexus-400 text-slate-300 transition-colors border border-slate-600",children:e.jsx(pt,{size:14})}),e.jsx("button",{onClick:n,title:"Delete webhook","aria-label":"Delete webhook",className:"p-2 rounded-lg bg-slate-700 hover:bg-red-500/20 hover:text-red-400 text-slate-300 transition-colors border border-slate-600",children:e.jsx(le,{size:14})}),e.jsx("button",{onClick:a,title:s?"Collapse":"View details","aria-expanded":s,"aria-label":s?"Collapse webhook details":"View webhook details",className:"p-2 rounded-lg bg-slate-700 hover:bg-slate-600 text-slate-300 hover:text-white transition-colors border border-slate-600",children:s?e.jsx(Me,{size:14}):e.jsx(qe,{size:14})})]})]}),s&&e.jsx("div",{className:"border-t border-slate-700/60 p-4",children:e.jsx(Ia,{webhook:t,onClose:a,onRotateSecret:i,onTest:c,actionLoading:x})})]}),Ma=({onCreate:t})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-slate-800 border border-slate-700 flex items-center justify-center mb-5",children:e.jsx(Ne,{size:28,className:"text-slate-400"})}),e.jsx("h3",{className:"text-lg font-bold text-[var(--color-text-primary)] mb-2",children:"No webhooks"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] max-w-xs text-sm leading-relaxed mb-6",children:"Create one to receive event notifications."}),e.jsxs("button",{onClick:t,"aria-label":"Create webhook",className:"inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-nexus-600 hover:bg-nexus-500 text-white text-sm font-semibold transition-colors",children:[e.jsx(J,{size:16}),"Create Your First Webhook"]})]}),_a=()=>{const[t,s]=l.useState([]),[a,r]=l.useState(!0),[n,i]=l.useState(null),[c,x]=l.useState(null),[m,h]=l.useState(null),b=l.useRef(void 0);l.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const[f,y]=l.useState(null),[w,P]=l.useState(!1),[E,D]=l.useState(null);Je(w,()=>
1P(!1)),Je(!!E,()=>D(null));const[g,p]=l.useState(!1),[C,o]=l.useState(null),[d,N]=l.useState(null),[S,k]=l.useState(null),[u,v]=l.useState(null),[z,A]=l.useState(null),[M,_]=l.useState(!1),$=U=>{h(U),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>h(null),4e3)},R=l.useCallback(async()=>{try{r(!0),x(null);const U=await wa();s(U)}catch{x("Failed to load webhooks. Please try again.")}finally{r(!1)}},[]);l.useEffect(()=>{R()},[R]);const I=async U=>{var W;try{p(!0),o(null);const q=await ka(U);s(X=>[q,...X]),P(!1),N({secret:q.secret,title:"Webhook Created — Save Your Secret"})}catch(q){const X=((W=q==null?void 0:q.error)==null?void 0:W.message)??"Failed to create webhook.";o(X)}finally{p(!1)}},j=async U=>{var W;if(E)try{p(!0),o(null);const q=await Ca(E.id,U);s(X=>X.map(he=>he.id===q.id?q:he)),D(null),$("Webhook updated successfully.")}catch(q){const X=((W=q==null?void 0:q.error)==null?void 0:W.message)??"Failed to update webhook.";o(X)}finally{p(!1)}},T=async U=>{try{k(U),await Sa(U),s(W=>W.filter(q=>q.id!==U)),v(null)}catch{i("Failed to delete webhook. Please try again.")}finally{k(null)}},F=async U=>{try{i(null),h(null),k(U);const W=await Aa(U);W.status==="success"?$("Test event delivered successfully."):W.status==="pending"?i("Test delivery is pending or waiting for a retry. Delivery has not been confirmed; check delivery history."):i(`Test delivery failed${W.statusCode?` (HTTP ${W.statusCode})`:""}. Check delivery history for details.`)}catch{i("Failed to send test event.")}finally{k(null)}},Q=async U=>{try{k(U);const W=await Ra(U);s(q=>q.map(X=>X.id===U?W:X)),A(null),N({secret:W.secret,title:"Secret Rotated — Save Your New Secret"})}catch{i("Failed to rotate webhook secret.")}finally{k(null)}};return e.jsxs("div",{className:"p-0 sm:p-4 space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-[var(--color-text-primary)] flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-nexus-500/20 flex items-center justify-center",children:e.jsx(Ne,{size:20,className:"text-[var(--color-brand-400)]"})}),"Webhooks"]}),e.jsx("p",{className:"text-[var(--color-text-secondary)] text-sm mt-1 ml-12",children:"Developer connections for workspace-wide events across businesses. Send signed HTTP notifications to your application."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>_(!0),"aria-label":"Open webhook documentation",className:"inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-sm font-medium transition-colors border border-slate-700",children:[e.jsx(Le,{size:14}),"Docs"]}),e.jsxs("button",{onClick:()=>{o(null),P(!0)},"aria-label":"Create webhook",className:"inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-nexus-600 hover:bg-nexus-500 text-white text-sm font-semibold transition-colors shadow-lg shadow-nexus-900/30",children:[e.jsx(J,{size:16}),"Create Webhook"]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-slate-800 border border-slate-700 rounded-xl text-sm",children:[e.jsx(Ee,{size:16,className:"text-nexus-400 shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-slate-300 leading-relaxed",children:["Webhooks are signed with HMAC-SHA256. Verify the ",e.jsx("code",{className:"text-nexus-300 font-mono text-xs bg-slate-900 px-1.5 py-0.5 rounded",children:"X-Nexus-Signature"})," header against your secret to confirm authenticity."]})]}),m&&e.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center gap-3 p-4 bg-emerald-900 border border-emerald-800 rounded-xl text-emerald-300 text-sm",children:[e.jsx(ce,{size:16}),e.jsx("span",{className:"flex-1",children:m}),e.jsx("button",{onClick:()=>h(null),className:"text-emerald-400 hover:text-emerald-200",children:e.jsx(re,{size:16})})]}),(n||c)&&e.jsxs("div",{role:"alert","aria-live":"assertive",className:"flex items-center gap-3 p-4 bg-red-900 border border-red-800 rounded-xl text-red-300 text-sm",children:[e.jsx(K,{size:16}),e.jsx("span",{className:"flex-1",children:n??c}),e.jsx("button",{onClick:R,className:"text-red-200 hover:text-white text-xs font-semibold underline",children:"Retry"}),e.jsx("button",{onClick:()=>{i(null),x(null)},className:"text-red-400 hover:text-red-200","aria-label":"Dismiss error",children:e.jsx(re,{size:16})})]}),a?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(L,{size:28,className:"animate-spin text-[var(--color-brand-400)]"})}):t.length===0?e.jsx(Ma,{onCreate:()=>{o(null),P(!0)}}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm text-[var(--color-text-secondary)]",children:[t.length," webhook",t.length!==1?"s":""]}),e.jsxs("button",{onClick:R,"aria-label":"Refresh webhooks list",className:"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-xs flex items-center gap-1.5 transition-colors",children:[e.jsx(de,{size:12}),"Refresh"]})]}),t.map(U=>e.jsx(La,{webhook:U,expanded:f===U.id,onToggleExpand:()=>y(W=>W===U.id?null:U.id),onEdit:()=>{o(null),D(U)},onDelete:()=>v(U.id),onRotateSecret:W=>A(W),onTest:F,actionLoading:S},U.id))]}),w&&e.jsx(rt,{onClose:()=>P(!1),onSave:I,loading:g,error:C}),E&&e.jsx(rt,{webhook:E,onClose:()=>D(null),onSave:j,loading:g,error:C}),d&&e.jsx(za,{secret:d.secret,title:d.title,onClose:()=>N(null)}),u&&e.jsx(lt,{title:"Delete Webhook",message:"Are you sure you want to delete this webhook? Event deliveries will stop immediately. This action cannot be undone.",confirmLabel:"Delete Webhook",confirmVariant:"danger",loading:S===u,onConfirm:()=>T(u),onCancel:()=>v(null)}),z&&e.jsx(lt,{title:"Rotate Webhook Secret",message:"Rotating will invalidate the current signing secret. You must update your application immediately to verify future deliveries.",confirmLabel:"Rotate Secret",confirmVariant:"warning",loading:S===z,onConfirm:()=>Q(z),onCancel:()=>A(null)}),M&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"webhook-docs-title",className:"bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-slate-800 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-nexus-500/20 flex items-center justify-center",children:e.jsx(Le,{size:18,className:"text-nexus-400"})}),e.jsx("h2",{id:"webhook-docs-title",className:"text-lg font-bold text-white",children:"Webhook Documentation"})]}),e.jsx("button",{type:"button",onClick:()=>_(!1),className:"text-slate-300 hover:text-white transition-colors","aria-label":"Close documentation",children:e.jsx(re,{size:20})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 text-sm text-slate-300",children:[e.jsxs("section",{children:[e.jsx("h3",{className:"text-base font-semibold text-white mb-2",children:"Endpoints"}),e.jsxs("div",{className:"bg-slate-800 rounded-lg p-3 font-mono text-xs space-y-1",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-emerald-400",children:"POST"})," ",e.jsx("span",{className:"text-slate-300",children:"/api/public/v1/webhooks"})," — Create webhook"]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-blue-400",children:"GET"})," ",e.jsx("span",{className:"text-slate-300",children:"/api/public/v1/webhooks"})," — List webhooks"]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-amber-400",children:"PATCH"})," ",e.jsx("span",{className:"text-slate-300",children:"/api/public/v1/webhooks/:id"})," — Update webhook"]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-red-400",children:"DELETE"})," ",e.jsx("span",{className:"text-slate-300",children:"/api/public/v1/webhooks/:id"})," — Delete webhook"]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-emerald-400",children:"POST"})," ",e.jsx("span",{className:"text-slate-300",children:"/api/public/v1/webhooks/:id/test"})," — Send test event"]})]})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-base font-semibold text-white mb-2",children:"Authentication"}),e.jsxs("p",{className:"leading-relaxed",children:["Include your API key in the ",e.jsx("code",{className:"text-nexus-300 font-mono text-xs bg-slate-800 px-1.5 py-0.5 rounded",children:"Authorization"})," header as a Bearer token."]})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-base font-semibold text-white mb-2",children:"Signature Verification"}),e.jsxs("p",{className:"leading-relaxed mb-2",children:["Each delivery includes an ",e.jsx("code",{className:"text-nexus-300 font-mono text-xs bg-slate-800 px-1.5 py-0.5 rounded",children:"X-Nexus-Signature"})," header. Compute HMAC-SHA256 of the raw request body using your webhook secret and compare:"]}),e.jsxs("div",{className:"bg-slate-800 rounded-lg p-3 font-mono text-xs text-slate-300 overflow-x-auto",children:[e.jsx("p",{children:"signature = HMAC_SHA256(secret, rawBody)"}),e.jsx("p",{children:'verify: header === "sha256=" + signature'})]})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-base font-semibold text-white mb-2",children:"Event Types"}),e.jsxs("div",{className:"grid grid-cols-1 gap-1 text-xs",children:[e.jsxs("p",{children:[e.jsx("code",{className:"text-nexus-300 font-mono bg-slate-800 px-1.5 py-0.5 rounded",children:"campaign.created"})," — New campaign created"]}),e.jsxs("p",{children:[e.jsx("code",{className:"text-nexus-300 font-mono bg-slate-800 px-1.5 py-0.5 rounded",children:"campaign.updated"})," — Campaign modified"]}),e.jsxs("p",{children:[e.jsx("code",{className:"text-nexus-300 font-mono bg-slate-800 px-1.5 py-0.5 rounded",children:"campaign.published"})," — Campaign published"]}),e.jsxs("p",{children:[e.jsx("code",{className:"text-nexus-300 font-mono bg-slate-800 px-1.5 py-0.5 rounded",children:"content.approved"})," — Content approved"]}),e.jsxs("p",{children:[e.jsx("code",{className:"text-nexus-300 font-mono bg-slate-800 px-1.5 py-0.5 rounded",children:"content.rejected"})," — Content rejected"]}),e.jsxs("p",{children:[e.jsx("code",{className:"text-nexus-300 font-mono bg-slate-800 px-1.5 py-0.5 rounded",children:"lead.created"})," — New lead captured"]}),e.jsxs("p",{children:[e.jsx("code",{className:"text-nexus-300 font-mono bg-slate-800 px-1.5 py-0.5 rounded",children:"lead.converted"})," — Lead converted"]}),e.jsxs("p",{children:[e.jsx("code",{className:"text-nexus-300 font-mono bg-slate-800 px-1.5 py-0.5 rounded",children:"workflow.completed"})," — Workflow finished"]})]})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-base font-semibold text-white mb-2",children:"Payload Example"}),e.jsx("pre",{className:"bg-slate-800 rounded-lg p-3 font-mono text-xs text-slate-300 overflow-x-auto whitespace-pre",children:`{
2  "id": "evt_abc123",
3  "type": "campaign.published",
4  "createdAt": "2026-02-17T10:30:00Z",
5  "data": {
6    "campaignId": "camp_xyz",
7    "name": "Spring Launch",
8    "status": "published"
9  }
10}`})]})]}),e.jsx("div",{className:"p-6 border-t border-slate-800 shrink-0",children:e.jsx("button",{type:"button",onClick:()=>_(!1),className:"w-full px-4 py-2.5 rounded-xl bg-nexus-600 hover:bg-nexus-500 text-white text-sm font-semibold transition-colors",children:"Close"})})]})})]})},Fa=te.memo(_a);async function nt(t){if(!t)throw new Error("Choose a business before loading dashboards.");return(await O(`/v1/dashboards?projectId=${encodeURIComponent(t)}`)).dashboards}async function Ua(t){if(!t.projectId)throw new Error("Choose a business before creating a dashboard.");return V("/v1/dashboards",t)}async function Ba(t,s){return ke(`/v1/dashboards/${t}`,s)}async function Oa(t){return we(`/v1/dashboards/${t}`)}async function Wa(t){return V(`/v1/dashboards/${t}/set-default`,{})}async function qa(t){return V(`/v1/dashboards/${t}/duplicate`,{})}async function Ka(t){return(await O(`/v1/dashboards/${t}/widgets`)).widgets}async function Ya(t,s){return V(`/v1/dashboards/${t}/widgets`,s)}async function Ga(t,s,a){return ke(`/v1/dashboards/${t}/widgets/${s}`,a)}async function Va(t,s){return we(`/v1/dashboards/${t}/widgets/${s}`)}async function Ha(t,s){return(await Se(`/v1/dashboards/${t}/widgets/positions`,{updates:s.map(({widgetId:r,...n})=>({widgetId:r,position:n}))})).widgets}async function Xa(t){return(await O(`/v1/dashboards/${t}/shares`)).shares}const Ja=({dashboard:t,onOpen:s,onDelete:a,onDuplicate:r,onSetDefault:n,isDeleting:i})=>{const[c,x]=l.useState(!1),m=l.useRef(null);return l.useEffect(()=>{const h=b=>{m.current&&!m.current.contains(b.target)&&x(!1)};return c&&document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[c]),e.jsxs("div",{className:"bg-slate-900 border border-slate-800 rounded-2xl p-5 flex flex-col gap-3 hover:border-nexus-600/50 transition-all group",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("button",{onClick:s,className:"flex-1 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(je,{size:16,className:"text-nexus-400 shrink-0"}),e.jsx("span",{className:"text-white font-semibold text-sm truncate",children:t.name}),t.isDefault&&e.jsx("span",{className:"shrink-0 text-xs bg-nexus-900 text-nexus-400 border border-nexus-700/50 px-1.5 py-0.5 rounded-full font-medium",children:"Default"})]}),t.description&&e.jsx("p",{className:"text-slate-400 text-xs line-clamp-2 mt-1",children:t.description})]}),e.jsxs("div",{className:"relative shrink-0",ref:m,children:[e.jsx("button",{onClick:h=>{h.stopPropagation(),x(b=>!b)},"aria-expanded":c,"aria-label":`Dashboard options for ${t.name}`,className:"p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition-colors opacity-0 group-hover:opacity-100",children:e.jsx(Ot,{size:16})}),c&&e.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-slate-800 border border-slate-700 rounded-xl shadow-xl py-1 min-w-[160px]",children:[e.jsxs("button",{onClick:()=>{x(!1),n()},disabled:t.isDefault,className:"flex items-center gap-2 w-full px-3 py-2 text-sm text-slate-300 hover:bg-slate-700 hover:text-white transition-colors",children:[e.jsx(Wt,{size:14}),t.isDefault?"Current Default":"Set as Default"]}),e.jsxs("button",{onClick:()=>{x(!1),r()},className:"flex items-center gap-2 w-full px-3 py-2 text-sm text-slate-300 hover:bg-slate-700 hover:text-white transition-colors",children:[e.jsx(Te,{size:14})," Duplicate"]}),e.jsx("div",{className:"border-t border-slate-700 my-1"}),e.jsxs("button",{onClick:()=>{x(!1),a()},disabled:i,className:"flex items-center gap-2 w-full px-3 py-2 text-sm text-red-400 hover:bg-red-900 hover:text-red-300 transition-colors disabled:opacity-50",children:[i?e.jsx(L,{size:14,className:"animate-spin"}):e.jsx(le,{size:14}),"Delete"]})]})]})]}),e.jsx("button",{onClick:s,className:"w-full mt-1 bg-slate-800 hover:bg-nexus-700 text-slate-300 hover:text-white text-xs font-semibold py-2 px-3 rounded-lg transition-all",children:"Open Editor"})]})},Qa={text:qt},Za=({widget:t})=>{const{type:s,config:a}=t;return s!=="text"?e.jsx("p",{className:"text-sm text-slate-400 py-3",children:"This saved widget has no connected data source in this editor. Use Results for measured business performance."}):e.jsx("div",{className:"flex-1 px-2 py-2 text-sm text-slate-300 whitespace-pre-wrap overflow-auto",children:String((a==null?void 0:a.content)||"No content")})},er=({widget:t,onDelete:s,onEdit:a,isDeleting:r})=>{const n=Qa[t.type]??Kt;return e.jsxs("div",{className:"bg-slate-900 border border-slate-800 rounded-xl p-4 flex flex-col gap-2 group hover:border-nexus-600/40 transition-all h-full overflow-hidden",role:"region","aria-label":`Widget: ${t.title}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"widget-drag-handle cursor-grab active:cursor-grabbing p-1 rounded-md hover:bg-slate-800 transition-colors shrink-0",role:"button","aria-label":"Drag to reorder 
10widget",tabIndex:0,children:e.jsx(Yt,{size:14,className:"text-slate-400"})}),e.jsx("div",{className:"w-7 h-7 rounded-lg bg-nexus-900 border border-nexus-700/40 flex items-center justify-center shrink-0",children:e.jsx(n,{size:14,className:"text-nexus-400"})}),e.jsx("span",{className:"text-white text-sm font-semibold truncate",children:t.title})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx("button",{onClick:a,"aria-label":`Edit widget ${t.title}`,className:"p-1.5 rounded-lg text-slate-300 hover:text-white hover:bg-slate-800 transition-colors",children:e.jsx(bt,{size:13})}),e.jsx("button",{onClick:s,disabled:r,"aria-label":`Delete widget ${t.title}`,className:"p-1.5 rounded-lg text-slate-300 hover:text-red-400 hover:bg-red-900 transition-colors disabled:opacity-50",children:r?e.jsx(L,{size:13,className:"animate-spin"}):e.jsx(le,{size:13})})]})]}),e.jsx("span",{className:"text-xs text-slate-400 capitalize",children:t.type}),e.jsx(Za,{widget:t})]})},tr=({dashboardId:t,onClose:s})=>{const[a,r]=l.useState([]),[n,i]=l.useState(!1),[c,x]=l.useState(null);return l.useEffect(()=>{let m=!1;return i(!0),Xa(t).then(h=>{m||r(Array.isArray(h)?h:[])}).catch(h=>{m||x(h instanceof Error?h.message:"Failed to load shares")}
10).finally(()=>{m||i(!1)}),()=>{m=!0}},[t]),e.jsx(ue,{isOpen:!0,title:"Dashboard access",onClose:s,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-slate-400",children:"Existing access is listed below. Email invitations are not supported by this dashboard service; no invitation will be sent from this page."}),c&&e.jsx("p",{role:"alert",className:"text-red-400 text-xs",children:c}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-slate-300 text-xs font-semibold uppercase tracking-wider mb-2",children:"Shared With"}),n?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(L,{size:20,className:"animate-spin text-nexus-500"})}):c?null:a.length===0?e.jsx("p",{className:"text-slate-600 text-sm text-center py-4",children:"Not shared with anyone yet"}):e.jsx("ul",{className:"space-y-2",children:a.map(m=>e.jsxs("li",{className:"flex items-center justify-between bg-slate-800 rounded-xl px-3 py-2",children:[e.jsx("span",{className:"text-white text-sm",children:m.sharedWithId??(m.shareType==="link"?"Shared link":"Workspace access")}),e.jsx("span",{className:"text-slate-300 text-xs capitalize",children:m.permission})]},m.id))})]})]})})},sr=({dashboardId:t,onClose:s,onAdded:a})=>{const[r,n]=l.useState(""),[i,c]=l.useState(""),[x,m]=l.useState(!1),[h,b]=l.useState(null),f=async()=>{var y;if(!r.trim()){b("Title is required");return}m(!0),b(null);try{const w=await Ya(t,{type:"text",title:r.trim(),config:{content:i},position:{x:0,y:0,w:4,h:3}});a(w),s()}catch(w){b(((y=w==null?void 0:w.error)==null?void 0:y.message)??"Failed to create widget"),m(!1)}};return e.jsx(ue,{isOpen:!0,title:"Add notes",onClose:s,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-slate-300 text-xs font-semibold uppercase tracking-wider block mb-2",children:"Title"}),e.jsx("input",{type:"text",value:r,onChange:y=>n(y.target.value),placeholder:"e.g. Campaign review notes",className:"w-full bg-slate-800 border border-slate-700 text-white placeholder-slate-500 rounded-xl px-3 py-2 text-sm focus:outline-none focus:border-nexus-500",onKeyDown:y=>y.key==="Enter"&&f()})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-slate-300 text-xs font-semibold uppercase tracking-wider block mb-2",children:"Content"}),e.jsx("textarea",{value:i,onChange:y=>c(y.target.value),rows:3,placeholder:"Your text content...",className:"w-full bg-slate-800 border border-slate-700 text-white placeholder-slate-500 rounded-xl px-3 py-2 text-sm focus:outline-none focus:border-nexus-500 resize-none"})]}),h&&e.jsx("p",{className:"text-red-400 text-xs",children:h}),e.jsxs("div",{className:"flex gap-3 pt-1",children:[e.jsx("button",{onClick:s,className:"flex-1 bg-slate-800 hover:bg-slate-700 text-slate-300 py-2 rounded-xl text-sm font-semibold transition-colors",children:"Cancel"}),e.jsxs("button",{onClick:f,disabled:x,className:"flex-1 bg-nexus-700 hover:bg-nexus-800 disabled:opacity-40 text-white py-2 rounded-xl text-sm font-bold transition-all flex items-center justify-center gap-2",children:[x&&e.jsx(L,{size:14,className:"animate-spin"}),"Add Widget"]})]})]})})},ar=({widget:t,dashboardId:s,onClose:a,onUpdated:r})=>{var w;const[n,i]=l.useState(t.title),[c,x]=l.useState(((w=t.config)==null?void 0:w.content)??""),[m,h]=l.useState(!1),[b,f]=l.useState(null),y=async()=>{var P;if(!n.trim()){f("Title is required");return}h(!0),f(null);try{const E={...t.config};t.type==="text"&&(E.content=c);const D=await Ga(s,t.id,{title:n.trim(),config:E});r(D),a()}catch(E){f(((P=E==null?void 0:E.error)==null?void 0:P.message)??"Failed to update"),h(!1)}};return e.jsx(ue,{isOpen:!0,title:"Edit Widget",onClose:a,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-slate-300 text-xs font-semibold uppercase tracking-wider block mb-2",children:"Title"}),e.jsx("input",{type:"text",value:n,onChange:P=>i(P.target.value),className:"w-full bg-slate-800 border border-slate-700 text-white rounded-xl px-3 py-2 text-sm focus:outline-none focus:border-nexus-500"})]}),t.type==="text"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-slate-300 text-xs font-semibold uppercase tracking-wider block mb-2",children:"Content"}),e.jsx("textarea",{value:c,onChange:P=>x(P.target.value),rows:4,className:"w-full bg-slate-800 border border-slate-700 text-white rounded-xl px-3 py-2 text-sm focus:outline-none focus:border-nexus-500 resize-none"})]}),b&&e.jsx("p",{className:"text-red-400 text-xs",children:b}),e.jsxs("div",{className:"flex gap-3 pt-1",children:[e.jsx("button",{onClick:a,className:"flex-1 bg-slate-800 hover:bg-slate-700 text-slate-300 py-2 rounded-xl text-sm font-semibold transition-colors",children:"Cancel"}),e.jsxs("button",{onClick:y,disabled:m,className:"flex-1 bg-nexus-700 hover:bg-nexus-800 disabled:opacity-40 text-white py-2 rounded-xl text-sm font-bold transition-all flex items-center justify-center gap-2",children:[m&&e.jsx(L,{size:14,className:"animate-spin"}),"Save"]})]})]})})},rr=({onClose:t,onCreated:s,projectId:a})=>{const[r,n]=l.useState(""),[i,c]=l.useState(""),[x,m]=l.useState(!1),[h,b]=l.useState(null),f=async()=>{var y;if(!r.trim()){b("Name is required");return}m(!0),b(null);try{const w=await Ua({name:r.trim(),description:i.trim()||void 0,projectId:a});s(w),t()}catch(w){b(((y=w==null?void 0:w.error)==null?void 0:y.message)??"Failed to create dashboard"),m(!1)}};return e.jsx(ue,{isOpen:!0,title:"New Dashboard",onClose:t,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-slate-300 text-xs font-semibold uppercase tracking-wider block mb-2",children:"Name"}),e.jsx("input",{type:"text",value:r,onChange:y=>n(y.target.value),placeholder:"e.g. Q1 Marketing Performance",className:"w-full bg-slate-800 border border-slate-700 text-white placeholder-slate-500 rounded-xl px-3 py-2 text-sm focus:outline-none focus:border-nexus-500",onKeyDown:y=>y.key==="Enter"&&f()})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-slate-300 text-xs font-semibold uppercase tracking-wider block mb-2",children:["Description ",e.jsx("span",{className:"normal-case text-slate-600 font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:i,onChange:y=>c(y.target.value),placeholder:"What is this dashboard for?",rows:2,className:"w-full bg-slate-800 border border-slate-700 text-white placeholder-slate-500 rounded-xl px-3 py-2 text-sm focus:outline-none focus:border-nexus-500 resize-none"})]}),h&&e.jsx("p",{className:"text-red-400 text-xs",children:h}),e.jsxs("div",{className:"flex gap-3 pt-1",children:[e.jsx("button",{onClick:t,className:"flex-1 bg-slate-800 hover:bg-slate-700 text-slate-300 py-2 rounded-xl text-sm font-semibold transition-colors",children:"Cancel"}),e.jsxs("button",{onClick:f,disabled:x,className:"flex-1 bg-nexus-700 hover:bg-nexus-800 disabled:opacity-40 text-white py-2 rounded-xl text-sm font-bold transition-all flex items-center justify-center gap-2",children:[x&&e.jsx(L,{size:14,className:"animate-spin"}),"Create"]})]})]})})},lr=({dashboard:t,onBack:s,onUpdated:a})=>{const[r,n]=l.useState([]),[i,c]=l.useState(!0),[x,m]=l.useState(null),[h,b]=l.useState(!1),[f,y]=l.useState(!1),[w,P]=l.useState(null),[E,D]=l.useState(null),[g,p]=l.useState(!1),[C,o]=l.useState(t.name),[d,N]=l.useState(!1),[S,k]=l.useState(null),[u,v]=l.useState(!1),{width:z,containerRef:A}=_t(),M=async()=>
10{if(!(!S||u)){v(!0),m(null);try{const R=await Ha(t.id,S.map(I=>({widgetId:I.i,x:I.x,y:I.y,w:I.w,h:I.h})));n(R),k(null)}catch{m("The layout was not saved. Try saving again before leaving.")}finally{v(!1)}}};l.useEffect(()=>{let R=!1;return c(!0),m(null),Ka(t.id).then(I=>{R||n(Array.isArray(I)?I:[])}).catch(I=>{R||m(I instanceof Error?I.message:"Failed to load widgets")}).finally(()=>{R||c(!1)}),()=>{R=!0}},[t.id]);const _=async R=>{D(R);try{await Va(t.id,R),n(I=>I.filter(j=>j.id!==R))}catch(I){pe.error("DashboardsPage","Failed to delete widget",I),m("Could not delete this widget. Try again.")}finally{D(null)}},$=async()=>{if(!C.trim()||C===t.name){p(!1);return}N(!0);try{const R=await Ba(t.id,{name:C.trim()});a(R)}catch{o(t.name),m("Could not save the dashboard name. Try again.")}finally{N(!1),p(!1)}};return e.jsxs("div",{className:"flex flex-col h-full gap-6",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("button",{onClick:s,"aria-label":"Back to dashboards list",className:"flex items-center gap-1.5 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-sm transition-colors",children:[e.jsx(Ft,{size:16})," Dashboards"]}),e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:"/"}),g?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{autoFocus:!0,value:C,onChange:R=>o(R.target.value),onBlur:$,onKeyDown:R=>{R.key==="Enter"&&$(),R.key==="Escape"&&(o(t.name),p(!1))},className:"bg-slate-800 border border-nexus-500 text-white rounded-lg px-2 py-1 text-lg font-bold focus:outline-none"}),d&&e.jsx(L,{size:14,className:"animate-spin text-nexus-400"})]}):e.jsxs("button",{onClick:()=>p(!0),"aria-label":`Edit dashboard name: ${t.name}`,className:"flex items-center gap-2 group",children:[e.jsx("h1",{className:"text-xl font-bold text-[var(--color-text-primary)]",children:t.name}),e.jsx(bt,{size:13,className:"text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-secondary)] transition-colors"})]}),t.isDefault&&e.jsx("span",{className:"text-xs bg-nexus-900 text-[var(--color-brand-400)] border border-nexus-700/50 px-2 py-0.5 rounded-full font-medium",children:"Default"}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>y(!0),className:"flex items-center gap-2 bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white px-3 py-2 rounded-xl text-sm font-semibold transition-colors",children:[e.jsx(Ut,{size:14})," Access"]}),e.jsxs("button",{onClick:()=>b(!0),className:"flex items-center gap-2 bg-nexus-700 hover:bg-nexus-800 text-white px-3 py-2 rounded-xl text-sm font-bold transition-all",children:[e.jsx(J,{size:15})," Add Widget"]})]})]}),e.jsxs("p",{className:"text-sm text-[var(--color-text-secondary)]",children:["A saved notes board for this business. Charts and metrics are not connected in this editor. ",e.jsx(Ke,{to:"/analytics",className:"text-[var(--color-brand-400)] underline",children:"View measured results"}),"."]}),r.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-3 items-center text-sm",children:[e.jsx("button",{type:"button",onClick:()=>void M(),disabled:!S||u,className:"px-4 py-2 rounded-lg bg-slate-800 text-white disabled:opacity-50",children:u?"Saving…":"Save layout"}),e.jsx("span",{className:"text-[var(--color-text-secondary)]",children:"After moving or resizing widgets, save the layout before leaving."})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[var(--color-text-secondary)] text-xs font-semibold uppercase tracking-wider mb-4",children:["Widgets ",!i&&`(${r.length})`]}),x&&e.jsx("p",{role:"alert",className:"text-[var(--color-error)] text-sm mb-4",children:x}),i?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(L,{className:"w-6 h-6 animate-spin text-nexus-500"})}):x&&r.length===0?null:r.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center border-2 border-dashed border-[var(--color-border-default)] rounded-2xl",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-800 rounded-2xl flex items-center justify-center mb-4 text-slate-600",children:e.jsx(je,{size:32})}),e.jsx("h3",{className:"text-[var(--color-text-primary)] font-semibold mb-2",children:"No widgets yet"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] text-sm mb-6 max-w-xs",children:"Add a notes widget to record context for this business. Measured performance lives in Results."}),e.jsxs("button",{onClick:()=>b(!0),className:"flex items-center gap-2 bg-nexus-700 hover:bg-nexus-800 text-white px-5 py-2.5 rounded-xl text-sm font-bold transition-all",children:[e.jsx(J,{size:15})," Add Your First Widget"]})]}):e.jsx("div",{ref:A,children:e.jsx(Bt,{width:z,breakpoints:{lg:1200,md:996,sm:768,xs:480},cols:{lg:12,md:8,sm:4,xs:2},rowHeight:80,layouts:{lg:r.map((R,I)=>{var j,T,F,Q;return{i:R.id,x:((j=R.position)==null?void 0:j.x)??I%3*4,y:((T=R.position)==null?void 0:T.y)??Math.floor(I/3)*3,w:((F=R.position)==null?void 0:F.w)??4,h:((Q=R.position)==null?void 0:Q.h)??3}})},dragConfig:{enabled:!0,handle:".widget-drag-handle"},resizeConfig:{enabled:!0},onLayoutChange:k,children:r.map(R=>e.jsx("div",{"aria-label":`Widget: ${R.title}`,children:e.jsx(er,{widget:R,onDelete:()=>_(R.id),onEdit:()=>P(R),isDeleting:E===R.id})},R.id))})})]}),h&&e.jsx(sr,{dashboardId:t.id,onClose:()=>b(!1),onAdded:R=>n(I=>[...I,R])}),f&&e.jsx(tr,{dashboardId:t.id,onClose:()=>y(!1)}),w&&e.jsx(ar,{widget:w,dashboardId:t.id,onClose:()=>P(null),onUpdated:R=>n(I=>I.map(j=>j.id===R.id?R:j))})]})},nr=({projectId:t})=>{const[s,a]=l.useState([]),[r,n]=l.useState(!0),[i,c]=l.useState(null),[x,m]=l.useState(!1),[h,b]=l.useState(null),[f,y]=l.useState(null),w=l.useCallback(()=>
10{if(!t){n(!1);return}n(!0),c(null),nt(t).then(p=>a(Array.isArray(p)?p:[])).catch(p=>{c("Could not load dashboards. Try again."),pe.warn("DashboardsPage","Could not load dashboards:",p),a([])}).finally(()=>n(!1))},[t]);l.useEffect(()=>{let p=!1;if(b(null),m(!1),a([]),!t){n(!1);return}return n(!0),c(null),nt(t).then(C=>{p||a(Array.isArray(C)?C:[])}).catch(C=>{p||(pe.warn("DashboardsPage","Could not load dashboards:",C),c("Could not load dashboards. Try again."),a([]))}).finally(()=>{p||n(!1)}),()=>{p=!0}},[t]);const P=async p=>{if(window.confirm("Delete this dashboard and its widgets? This cannot be undone.")){y(p);try{await Oa(p),a(C=>C.filter(o=>o.id!==p))}catch{c("Could not delete the dashboard. Try again.")}finally{y(null)}}},E=async p=>{try{const C=await Wa(p);a(o=>o.map(d=>({...d,isDefault:d.id===C.id})))}catch{c("Could not change the default dashboard. Try again.")}},D=async p=>{try{const C=await qa(p);a(o=>[...o,C])}catch{c("Could not duplicate the dashboard. Try again.")}},g=p=>{a(C=>C.map(o=>o.id===p.id?p:o)),(h==null?void 0:h.id)===p.id&&b(p)};return t?h?e.jsx("div",{className:"p-6 h-full overflow-y-auto",children:e.jsx(lr,{dashboard:h,onBack:()=>b(null),onUpdated:g})}):e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-[var(--color-text-primary)] flex items-center gap-2",children:[e.jsx(je,{size:24,className:"text-[var(--color-brand-400)]"}),"Custom Dashboards"]}),e.jsx("p",{className:"text-[var(--color-text-secondary)] text-sm mt-1",children:"Saved notes and dashboard layouts for this business. Use Results for connected performance data."})]}),e.jsxs("button",{onClick:()=>m(!0),className:"flex items-center gap-2 bg-nexus-700 hover:bg-nexus-800 text-white px-4 py-2.5 rounded-xl text-sm font-bold transition-all shadow-lg shadow-nexus-900/30",children:[e.jsx(J,{size:16})," Create Dashboard"]})]}),r?e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(L,{className:"w-8 h-8 animate-spin text-nexus-500"})}):i?e.jsxs("div",{className:"flex flex-col items-center justify-center py-24 text-center",children:[e.jsx(oe,{size:40,className:"text-[var(--color-error)] mb-4"}),e.jsx("p",{className:"text-[var(--color-error)] font-semibold mb-2",children:i}),e.jsx("button",{onClick:w,className:"text-[var(--color-brand-400)] hover:text-[var(--color-brand-400)] text-sm transition-colors mt-2",children:"Try again"})]}):s.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-24 text-center border-2 border-dashed border-[var(--color-border-default)] rounded-2xl",children:[e.jsx("div",{className:"w-20 h-20 bg-slate-800 rounded-2xl flex items-center justify-center mb-6 text-slate-600",children:e.jsx(je,{size:40})}),e.jsx("h2",{className:"text-[var(--color-text-primary)] text-xl font-bold mb-2",children:"Create Your First Dashboard"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] text-sm mb-8 max-w-sm",children:"Organize notes for this business and retain dashboard layouts. This editor does not supply live charts or metrics."}),e.jsxs("button",{onClick:()=>m(!0),className:"flex items-center gap-2 bg-nexus-700 hover:bg-nexus-800 text-white px-6 py-3 rounded-xl font-bold transition-all shadow-xl shadow-nexus-900/30",children:[e.jsx(J,{size:16})," Create Your First Dashboard"]})]}):e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(280px, 1fr))",gap:"1rem"},children:s.map(p=>e.jsx(Ja,{dashboard:p,onOpen:()=>b(p),onDelete:()=>P(p.id),onDuplicate:()=>D(p.id),onSetDefault:()=>E(p.id),isDeleting:f===p.id},p.id))}),x&&e.jsx(rr,{projectId:t,onClose:()=>m(!1),onCreated:p=>{a(C=>[...C,p]),b(p)}})]}):e.jsxs("div",{className:"max-w-2xl space-y-3",children:[e.jsx("h1",{className:"text-xl font-bold text-[var(--color-text-primary)]",children:"Custom dashboards"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Choose a business to organize its notes and dashboards."}),e.jsx(Ke,{to:"/dashboard",className:"text-[var(--color-brand-400)] underline",children:"Choose a business"})]})},or=te.memo(nr);async function ir(t){if(!!t.startDate!=!!t.endDate)throw new Error("Provide both start and end dates");const s=await V("/v1/data/export",{entities:[t.dataType],format:t.format,...t.startDate&&t.endDate?{dateRange:{startDate:t.startDate,endD
10ate:t.endDate}}:{}});return Ct(s.exportId)}async function Ct(t){const{export:s}=await O(`/v1/data/export/${encodeURIComponent(t)}`);return{id:s.exportId,dataType:s.entities.length===1?s.entities[0]:"all",format:s.format,status:s.status,recordCount:s.progress.recordsProcessed,fileSizeBytes:s.fileSizeBytes,createdAt:s.createdAt,completedAt:s.completedAt,error:s.error,downloadUrl:s.downloadUrl}}async function cr(){const t=[];for(let s=0;;s+=100){const a=await O(`/v1/data/export?limit=100&offset=${s}`);if(t.push(...await Promise.all(a.exports.map(r=>Ct(r.exportId)))),!a.hasMore)return t}}async function dr(t){const s=await jt(),a=await fetch(`/api/v1/data/export/${encodeURIComponent(t)}/download`,{headers:s});if(!a.ok)throw new Error(`Download failed (${a.status})`);return a.blob()}async function xr(t){const s=new FormData;s.append("file",t),s.append("dryRun","true"),s.append("conflictStrategy","skip");const a=await fetch("/api/v1/data/import",{method:"POST",headers:await jt(),body:s});if(!a.ok)throw new Error(`Import upload failed (${a.status}): ${await a.text()}`);const r=await a.json();return Pe(r.importId)}async function Pe(t){var r,n,i;const{import:s}=await O(`/v1/data/import/${encodeURIComponent(t)}`),a=(r=s.result)==null?void 0:r.rollbackInfo;return{id:s.importId,fileName:((n=s.metadata)==null?void 0:n.filename)??s.importId,dataType:"supported scope",status:s.status,recordCount:s.progress.totalRecords,processedCount:s.progress.recordsProcessed,errorCount:s.progress.errorCount,previewData:(i=s.preview)==null?void 0:i.changes.map(c=>({action:c.action,entityType:c.entityType,recordId:c.recordId,name:c.name})),canRollback:(a==null?void 0:a.canRollback)&&!!(a.rollbackDeadline&&Date.parse(a.rollbackDeadline)>Date.now()),createdAt:s.createdAt,completedAt:s.completedAt,error:s.error}}async function mr(){const t=[];for(let s=0;;s+=100){const a=await O(`/v1/data/import?limit=100&offset=${s}`);if(t.push(...await Promise.all(a.imports.map(r=>Pe(r.importId)))),!a.hasMore)return t}}async function ur(t){return await V(`/v1/data/import/${encodeURIComponent(t)}/confirm`,{}),Pe(t)}async function pr(t){return await V(`/v1/data/import/${encodeURIComponent(t)}/rollback`,{}),Pe(t)}function hr(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function St(t){return new Date(t).toLocaleString()}function br(t){const s={pending:{label:"Pending",cls:"bg-slate-700 text-slate-300",icon:e.jsx(ie,{size:12})},processing:{label:"Processing",cls:"bg-blue-900 text-blue-300",icon:e.jsx(L,{size:12,className:"animate-spin"})},completed:{label:"Completed",cls:"bg-green-900 text-green-300",icon:e.jsx(ce,{size:12})},failed:{label:"Failed",cls:"bg-red-900 text-red-300",icon:e.jsx(Re,{size:12})},expired:{label:"Expired",cls:"bg-slate-700 text-slate-300",icon:e.jsx(ie,{size:12})}},{label:a,cls:r,icon:n}=s[t]??s.pending;return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${r}`,children:[n,a]})}function fr(t){const s={pending:{label:"Pending",cls:"bg-slate-700 text-slate-300",icon:e.jsx(ie,{size:12})},validating:{label:"Validating",cls:"bg-blue-900 text-blue-300",icon:e.jsx(L,{size:12,className:"animate-spin"})},dry_run:{label:"Preparing preview",cls:"bg-blue-900 text-blue-300",icon:e.jsx(L,{size:12,className:"animate-spin"})},awaiting_confirmation:{label:"Awaiting approval",cls:"bg-yellow-900 text-yellow-300",icon:e.jsx(ie,{size:12})},importing:{label:"Importing",cls:"bg-blue-900 text-blue-300",icon:e.jsx(L,{size:12,className:"animate-spin"})},completed:{label:"Completed",cls:"bg-green-900 text-green-300",icon:e.jsx(ce,{size:12})},failed:{label:"Failed",cls:"bg-red-900 text-red-300",icon:e.jsx(Re,{size:12})},rolled_back:{label:"Rolled Back",cls:"bg-yellow-900 text-yellow-300",icon:e.jsx(K,{size:12})}},{label:a,cls:r,icon:n}=s[t]??s.pending;return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${r}`,children:[n,a]})}const Ce=[{value:"all",label:"All supported entities",description:"Complete supported export scope; exclusions are listed in the package metadata"},{value:"workflows",label:"Workflows",description:"Workflow definitions and run history"},{value:"templates",label:"Report templates",description:"Saved report template configurations"},{value:"settings",label:"Settings",description:"Plan settings and webhook definitions (no secrets)"},{value:"social_accounts",label:"Social accounts",description:"Account metadata without OAuth tokens"},{value:"social_posts",label:"Social posts",description:"Stored posts and publication status"},{value:"conversations",label:"Conversations",description:"Conversations and messages"},{value:"projects",label:"Projects",description:"All project data and settings"},{value:"campaigns",label:"Campaigns",description:"Campaign configurations and results"},{value:"analytics",label:"Analytics",description:"Analytics events and metrics"},{value:"leads",label:"Leads",description:"Lead records and contact info"}],gr=[{value:"csv",label:"CSV"},{value:"json",label:"JSON"},{value:"zip",label:"ZIP"}],Fe=3e3,Ue=200,vr=({exports:t,loading:s,onRefresh:a})=>{var k;const[r,n]=l.useState("projects"),[i,c]=l.useState("csv"),[x,m]=l.useState(""),[h,b]=l.useState(""),[f,y]=l.useState(!1),[w,P]=l.useState(null),[E,D]=l.useState(null),g=t.some(u=>u.status==="pending"||u.status==="processing"),[p,C]=l.useState(!1),o=l.useRef(0),d=l.useRef(a);l.useEffect(()=>{d.current=a},[a]),l.useEffect(()=>{if(!g){C(!1);return}if(p)return;o.current=0;const u=setInterval(()=>{if(o.current>=Ue){C(!0);return}o.current+=1,d.current()},Fe);return()=>clearInterval(u)},[g,p]);const N=async()=>{P(null),y(!0);try{await ir({dataType:r,format:i,startDate:x||void 0,endDate:h||void 0}),a()}catch(u){P(Z(u))}finally{y(!1)}},S=async u=>{D(u.id);try{const v=await dr(u.id),z=URL.createObjectURL(v),A=document.createElement("a");A.href=z,A.download=`export-${u.dataType}-${u.id}.${u.format}`,A.click(),URL.revokeObjectURL(z)}catch(v){P(Z(v))}finally{D(null)}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"bg-slate-900 border border-slate-800 rounded-xl p-6",children:[e.jsxs("h3",{className:"text-white font-semibold text-base mb-4 flex items-center gap-2",children:[e.jsx(ge,{size:18,className:"text-nexus-400"}),"Create Export"]}),e.jsxs("p",{className:"text-sm text-slate-300 mb-4",children:["Exports cover the selected supported stores, not every platform or processor record. Package metadata lists scope and exclusions. For contact-specific access or deleti
10on, ",e.jsx("a",{className:"underline",href:"mailto:[email protected]?subject=Contact%20data%20rights%20request",children:"request help from support"}),". The team must verify your authority before releasing or deleting contact data; do not include passwords or full customer records in the initial request."]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-300 mb-1.5 font-medium uppercase tracking-wider",children:"Data Type"}),e.jsxs("div",{className:"relative",children:[e.jsx("select",{value:r,onChange:u=>n(u.target.value),"aria-label":"Select data type to export",className:"w-full appearance-none bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-nexus-500 pr-8",children:Ce.map(u=>e.jsx("option",{value:u.value,children:u.label},u.value))}),e.jsx(qe,{size:14,className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-300 pointer-events-none"})]}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:(k=Ce.find(u=>u.value===r))==null?void 0:k.description})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-300 mb-1.5 font-medium uppercase tracking-wider",children:"Format"}),e.jsx("div",{className:"flex gap-2",role:"radiogroup","aria-label":"Export format",children:gr.map(u=>e.jsx("button",{role:"radio","aria-checked":i===u.value,onClick:()=>c(u.value),className:`flex-1 py-2.5 rounded-lg text-sm font-medium border transition-all ${i===u.value?"bg-nexus-600 border-nexus-500 text-white":"bg-slate-800 border-slate-700 text-slate-300 hover:border-slate-600 hover:text-white"}`,children:u.label},u.value))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-300 mb-1.5 font-medium uppercase tracking-wider",children:"Start Date (optional)"}),e.jsx("input",{type:"date",value:x,onChange:u=>m(u.target.value),className:"w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-nexus-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-slate-300 mb-1.5 font-medium uppercase tracking-wider",children:"End Date (optional)"}),e.jsx("input",{type:"date",value:h,onChange:u=>b(u.target.value),className:"w-full bg-slate-800 border border-slate-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-nexus-500"})]})]}),w&&e.jsxs("div",{role:"alert",className:"mb-4 p-3 bg-red-900 border border-red-800 rounded-lg text-red-300 text-sm flex items-center gap-2",children:[e.jsx(K,{size:15})," ",w]}),e.jsxs("button",{onClick:N,disabled:f,className:"flex items-center gap-2 bg-nexus-600 hover:bg-nexus-500 disabled:opacity-50 disabled:cursor-not-allowed text-white px-5 py-2.5 rounded-lg text-sm font-medium transition-all",children:[f?e.jsx(L,{size:15,className:"animate-spin"}):e.jsx(ge,{size:15}),f?"Creating Export...":"Create Export"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-[var(--color-text-primary)] font-semibold text-base",children:"Export History"}),e.jsxs("button",{onClick:a,disabled:s,"aria-label":"Refresh export history",className:"flex items-center gap-1.5 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-xs transition-colors",children:[e.jsx(de,{size:13,className:s?"animate-spin":""}),"Refresh"]})]}),p&&e.jsxs("div",{role:"status",className:"mb-3 p-3 bg-yellow-900 border border-yellow-800 rounded-lg text-yellow-200 text-sm flex items-center gap-2",children:[e.jsx(K,{size:15}),e.jsxs("span",{className:"flex-1",children:["Stopped checking automatically after ",Ue," attempts. This export is still marked in progress — check again to see whether it has finished."]}),e.jsx("button",{onClick:()=>{o.current=0,C(!1),a()},className:"text-yellow-100 hover:text-white text-xs font-semibold underline shrink-0",children:"Check again"})]}),s&&t.length===0?e.jsxs("div",{className:"flex items-center justify-center py-12 text-[var(--color-text-secondary)]",children:[e.jsx(L,{size:20,className:"animate-spin mr-2"})," Loading exports…"]}):t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 bg-slate-900 border border-slate-800 rounded-xl text-slate-400",children:[e.jsx(ft,{size:36,className:"mb-3 opacity-40"}
10),e.jsx("p",{className:"font-medium",children:"No exports yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create your first export above."})]}):e.jsx("div",{className:"space-y-2",children:t.map(u=>{var v,z;return e.jsxs("div",{className:"flex items-center justify-between bg-slate-900 border border-slate-800 rounded-xl px-4 py-3 gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(gt,{size:18,className:"text-slate-400 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[((v=Ce.find(A=>A.value===u.dataType))==null?void 0:v.label)??u.dataType," — ",u.format.toUpperCase()]}),e.jsx("p",{className:"text-slate-400 text-xs mt-0.5",children:St(u.createdAt)}),u.error&&e.jsx("p",{role:"alert",className:"text-red-300 text-xs mt-1",children:u.error})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[u.recordCount!==null&&u.recordCount!==void 0&&e.jsxs("span",{className:"text-xs text-slate-300 hidden sm:block",children:[u.recordCount.toLocaleString()," records"]}),u.fileSizeBytes!==null&&u.fileSizeBytes!==void 0&&e.jsx("span",{className:"text-xs text-slate-300 hidden md:block",children:hr(u.fileSizeBytes)}),br(u.status),u.status==="completed"&&e.jsxs("button",{onClick:()=>S(u),disabled:E===u.id,"aria-label":`Download ${((z=Ce.find(A=>A.value===u.dataType))==null?void 0:z.label)??u.dataType} export`,className:"flex items-center gap-1.5 bg-nexus-700 hover:bg-nexus-600 disabled:opacity-50 text-white px-3 py-1.5 rounded-lg text-xs font-medium transition-all",children:[E===u.id?e.jsx(L,{size:12,className:"animate-spin"}):e.jsx(ge,{size:12}),"Download"]})]})]},u.id)})})]})]})},jr=({imports:t,loading:s,onRefresh:a})=>{const r=l.useRef(null),[n,i]=l.useState(!1),[c,x]=l.useState(null),[m,h]=l.useState(null),[b,f]=l.useState(null),[y,w]=l.useState(!1),P=t.some(o=>["pending","validating","dry_run","importing"].includes(o.status));l.useEffect(()=>{if(!P)return;const o=setInterval(a,Fe),d=setTimeout(()=>{clearInterval(o),f("Automatic import status checks stopped after 10 minutes. Use Refresh to check durable job status.")},Fe*Ue);return()=>{clearInterval(o),clearTimeout(d)}},[P,a]);const E=async o=>{f(null),i(!0);try{await xr(o),a()}catch(d){f(Z(d))}finally{i(!1)}},D=o=>{var N;const d=(N=o.target.files)==null?void 0:N[0];d&&E(d),o.target.value=""},g=o=>{o.preventDefault(),w(!1);const d=o.dataTransfer.files[0];d&&E(d)},p=async o=>{x(o);try{await ur(o),a()}catch(d){f(Z(d))}finally{x(null)}},C=async o=>{h(o);try{await pr(o),a()}catch(d){f(Z(d))}finally{h(null)}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"bg-slate-900 border border-slate-800 rounded-xl p-6",children:[e.jsxs("h3",{className:"text-white font-semibold text-base mb-4 flex items-center gap-2",children:[e.jsx($e,{size:18,className:"text-nexus-400"}),"Upload Import File"]}),e.jsxs("div",{onDragOver:o=>{o.preventDefault(),w(!0)},onDragLeave:()=>w(!1),onDrop:g,onClick:()=>{var o;return(o=r.current)==null?void 0:o.click()},className:`relative cursor-pointer border-2 border-dashed rounded-xl p-10 flex flex-col items-center justify-center transition-all ${y?"border-nexus-500 bg-nexus-900":"border-slate-700 hover:border-slate-600 hover:bg-slate-800"}`,children:[e.jsx("input",{ref:r,type:"file",accept:".csv,.json,.zip,.gz","aria-label":"Upload an exported CSV, JSON, ZIP or gzip package",className:"hidden",onChange:D}),n?e.jsxs(e.Fragment,{children:[e.jsx(L,{size:32,className:"text-nexus-400 animate-spin mb-3"}),e.jsx("p",{className:"text-slate-300 font-medium",children:"Uploading…"})]}):e.jsxs(e.Fragment,{children:[e.jsx($e,{size:32,className:"text-slate-400 mb-3"}),e.jsx("p",{className:"text-slate-300 font-medium",children:"Drop an exported CSV, JSON, ZIP or gzip package here"}),e.jsx("p",{className:"text-slate-400 text-sm mt-1",children:"or click to browse"})]})]}),b&&e.jsxs("div",{role:"alert",className:"mt-4 p-3 bg-red-900 border border-red-800 rounded-lg text-red-300 text-sm flex items-center gap-2",children:[e.jsx(K,{size:15})," ",b]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-[var(--color-text-primary)] font-semibold text-base",children:"Import History"}),e.jsxs("button",{onClick:a,disabled:s,"aria-label":"Refresh import history",className:"flex items-center gap-1.5 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] text-xs transition-colors",children:[e.jsx(de,{size:13,className:s?"animate-spin":""}),"Refresh"]})]}),s&&t.length===0?e.jsxs("div",{className:"flex items-center justify-center py-12 text-[var(--color-text-secondary)]",children:[e.jsx(L,{size:20,className:"animate-spin mr-2"})," Loading imports…"]}):t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 bg-slate-900 border border-slate-800 rounded-xl text-slate-400",children:[e.jsx($e,{size:36,className:"mb-3 opacity-40"}),e.jsx("p",{className:"font-medium",children:"No imports yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Upload a file above to get started."})]}):e.jsx("div",{className:"space-y-2",children:t.map(o=>e.jsxs("div",{className:"bg-slate-900 border border-slate-800 rounded-xl px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(gt,{size:18,className:"text-slate-400 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-white text-sm font-medium truncate",children:o.fileName}),e.jsx("p",{className:"text-slate-400 text-xs mt-0.5",children:St(o.createdAt)})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o.recordCount!==null&&o.recordCount!==void 0&&e.jsxs("span",{className:"text-xs text-slate-300 hidden sm:block",children:[o.recordCount.toLocaleStr
10ing()," records"]}),fr(o.status),o.status==="awaiting_confirmation"&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("button",{onClick:()=>p(o.id),disabled:c===o.id,"aria-label":`Confirm import ${o.fileName}`,className:"flex items-center gap-1.5 bg-green-700 hover:bg-green-600 disabled:opacity-50 text-white px-3 py-1.5 rounded-lg text-xs font-medium transition-all",children:[c===o.id?e.jsx(L,{size:12,className:"animate-spin"}):e.jsx(ce,{size:12}),"Confirm"]})}),o.status==="completed"&&o.canRollback&&e.jsxs("button",{onClick:()=>C(o.id),disabled:m===o.id,"aria-label":`Rollback import ${o.fileName}`,className:"flex items-center gap-1.5 bg-slate-700 hover:bg-slate-600 disabled:opacity-50 text-slate-300 px-3 py-1.5 rounded-lg text-xs font-medium transition-all",children:[m===o.id?e.jsx(L,{size:12,className:"animate-spin"}):e.jsx(K,{size:12}),"Rollback"]})]})]}),o.error&&e.jsx("p",{role:"alert",className:"text-red-300 text-sm mt-2",children:o.error}),o.previewData&&o.previewData.length>0&&o.status==="awaiting_confirmation"&&e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[e.jsxs("p",{className:"text-xs text-slate-300 mb-1.5",children:["Preview (first ",o.previewData.length," rows)"]}),e.jsxs("table",{role:"table",className:"w-full text-xs border-collapse",children:[e.jsx("thead",{children:e.jsx("tr",{children:Object.keys(o.previewData[0]).map(d=>e.jsx("th",{className:"text-left px-2 py-1 bg-slate-800 text-slate-300 border border-slate-700 font-medium",children:d},d))})}),e.jsx("tbody",{children:o.previewData.map((d,N)=>e.jsx("tr",{children:Object.values(d).map((S,k)=>e.jsx("td",{className:"px-2 py-1 border border-slate-700 text-slate-300 max-w-[160px] truncate",children:String(S??"")},k))},N))})]})]})]},o.id))})]})]})},yr=()=>{const[t,s]=l.useState([]),[a,r]=l.useState([]),[n,i]=l.useState(!1),[c,x]=l.useState(!1),[m,h]=l.useState(null),[b,f]=l.useState(null),y=l.useCallback(async()=>{i(!0),h(null);try{const P=await cr();s(P)}catch{h("Failed to load exports. Please try again.")}finally{i(!1)}},[]),w=l.useCallback(async()=>{x(!0),f(null);try{const P=await mr();r(P)}catch{f("Failed to load imports. Please try again.")}finally{x(!1)}},[]);return l.useEffect(()=>{y(),w()},[y,w]),e.jsxs("div",{className:"p-0 sm:p-4 max-w-4xl mx-auto space-y-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-nexus-500/20 flex items-center justify-center",children:e.jsx(ge,{size:20,className:"text-[var(--color-brand-400)]"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-[var(--color-text-primary)]",children:"Export & import"}),e.jsx("p",{className:"text-[var(--color-text-secondary)] mt-1 text-sm",children:"Workspace-wide data transfer across all businesses. Export a backup or import supported records with a preview before confirming."})]})]}),e.jsxs("section",{"aria-label":"Export data",children:[m&&e.jsxs("div",{role:"alert",className:"mb-4 p-3 bg-red-900 border border-red-800 rounded-lg text-red-300 text-sm flex items-center gap-2",children:[e.jsx(K,{size:15}),e.jsx("span",{className:"flex-1",children:m}),e.jsx("button",{onClick:y,className:"text-red-200 hover:text-white text-xs font-semibold underline",children:"Retry"})]}),e.jsx(vr,{exports:t,loading:n,onRefresh:y})]}),e.jsx("hr",{className:"border-[var(--color-border-default)]"}),e.jsxs("section",{"aria-label":"Import data",children:[b&&e.jsxs("div",{role:"alert",className:"mb-4 p-3 bg-red-900 border border-red-800 rounded-lg text-red-300 text-sm flex items-center gap-2",children:[e.jsx(K,{size:15}),e.jsx("span",{className:"flex-1",children:b}),e.jsx("button",{onClick:w,className:"text-red-200 hover:text-white text-xs font-semibold underline",children:"Retry"})]}),e.jsx(jr,{imports:a,loading:c,onRefresh:w})]})]})},Nr=te.memo(yr),Ve={ai_requests:"AI Requests",workflow_runs:"Workflow Runs",posts:"Social Posts",ai_tokens:"AI Tokens",api_calls:"API Calls",agent_seconds:"Agent Time",storage_bytes:"Storage",fine_tuning_rows:"Fine-Tuning Rows",kg_nodes:"Knowledge Graph Nodes"},wr=[{label:"AI Usage",resources:["ai_requests","ai_tokens","fine_tuning_rows"]},{label:"API Calls",resources:["api_calls","posts"]},{label:"Agent Time",resources:["agent_seconds","workflow_runs"]},{label:"Storage",resources:["storage_bytes","kg_nodes"]}];
10function kr(t,s){return s<0?"No count cap":At(t,s)}function At(t,s){return t==="storage_bytes"?s>=1073741824?`${(s/1073741824).toFixed(1)} GB`:`${Math.round(s/1048576)} MB`:t==="agent_seconds"?`${Math.round(s/60)} min`:t==="ai_tokens"?s>=1e6?`${(s/1e6).toFixed(1)}M`:`${Math.round(s/1e3)}K`:s.toLocaleString()}function Cr(t){const{percentUsed:s,status:a,limit:r}=t;return r<0?"bg-green-500":a==="blocked"||s>=100?"bg-red-500":s>=90?"bg-orange-500":s>=80?"bg-amber-500":"bg-green-500"}function Sr(t){const{percentUsed:s,status:a,limit:r}=t;return r<0?"text-[var(--color-success)]":a==="blocked"||s>=100?"text-[var(--color-error)]":s>=90||s>=80?"text-[var(--color-warning)]":"text-[var(--color-success)]"}function Ar({resource:t}){const s=Math.min(t.percentUsed,100),a=t.limit<0,r=Cr(t),n=Sr(t),i=Ve[t.resource]??t.resource,c=At(t.resource,t.used),x=kr(t.resource,t.limit);return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium text-[var(--color-text-primary)]",children:i}),e.jsx("span",{className:`font-semibold ${n}`,children:a?`${c} used · No count cap`:`${c} / ${x} (${Math.round(s)}%)`})]}),e.jsx("div",{className:"w-full h-2.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden",role:a?void 0:"progressbar","aria-hidden":a||void 0,"aria-valuenow":a?void 0:Math.round(s),"aria-valuemin":a?void 0:0,"aria-valuemax":a?void 0:100,"aria-label":a?void 0:`${i} usage`,children:e.jsx("div",{className:`h-full rounded-full transition-all duration-300 ${r}`,style:{width:a?"0%":`${s}%`}})}),t.message&&e.jsx("p",{className:`text-xs ${n}`,children:t.message})]})}function Er({onSummaryLoaded:t,refreshIntervalMs:s=6e4}){const[a,r]=l.useState(null),[n,i]=l.useState(!0),[c,x]=l.useState(null),m=l.useCallback(async(b=!1)=>{b||i(!0),x(null);try{const f=await Qe();r(f),t==null||t(f)}catch{x("Failed to load usage data. Please refresh the page.")}finally{b||i(!1)}},[t]);if(l.useEffect(()=>{let b=!1;return(async()=>{i(!0),x(null);try{const f=await Qe();b||(r(f),t==null||t(f))}catch{b||x("Failed to load usage data. Please refresh the page.")}finally{b||i(!1)}})(),()=>{b=!0}},[t]),l.useEffect(()=>{if(!s)return;const b=setInterval(()=>{m(!0)},s);return()=>clearInterval(b)},[s,m]),n)return e.jsxs("div",{className:"bg-[var(--color-bg-surface)] rounded-lg shadow p-6 space-y-6","aria-busy":"true","aria-label":"Loading usage data",children:[e.jsx("div",{className:"h-5 bg-[var(--color-bg-elevated)] rounded w-1/3 animate-pulse"}),[0,1,2,3].map(b=>e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"h-3.5 bg-[var(--color-bg-elevated)] rounded w-1/5 animate-pulse"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[0,1].map(f=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("div",{className:"h-3 bg-[var(--color-bg-elevated)] rounded w-1/4 animate-pulse"}),e.jsx("div",{className:"h-3 bg-[var(--color-bg-elevated)] rounded w-1/5 animate-pulse"})]}),e.jsx("div",{className:"h-2.5 bg-[var(--color-bg-elevated)] rounded-full animate-pulse"})]},f))})]},b))]});if(c)return e.jsxs("div",{className:"bg-[var(--color-bg-surface)] rounded-lg shadow p-6",children:[e.jsx("p",{className:"text-sm text-[var(--color-error)]",children:c}),e.jsx("button",{type:"button",onClick:()=>void m(!1),className:"mt-3 text-sm font-medium text-[var(--color-info)] hover:text-[var(--color-info)]",children:"Retry"})]});if(!a)return e.jsx(e.Fragment,{});const h=new Map(a.resources.map(b=>[b.resource,b]));return e.jsxs("div",{className:"bg-[var(--color-bg-surface)] rounded-lg shadow p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("h3",{className:"text-base font-semibold text-[var(--color-text-primary)]",children:"Usage today (UTC)"}),e.jsxs("span",{className:"inline-flex items-center rounded-full bg-[var(--color-info-bg)] px-2.5 py-0.5 text-xs font-medium text-[var(--color-info)] ring-1 ring-inset ring-indigo-600/20",children:[a.plan.name," Plan"]})]}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Resource counts reset at 00:00 UTC. These are daily usage counts, not billing-cycle totals."}),e.jsxs("p",{className:"text-sm text-[var(--color-text-secondary)]",children:["A resource with no count cap is not free or unlimited AI spending. AI credits, workspace budgets, provider limits, and other resource limits still apply. ",e.jsx("a",{href:"/settings/billing",className:"underline",children:"View billing and remaining credits"}),"."]}),wr.map(b=>{const f=b.resources.map(y=>h.get(y)).filter(y=>y!==void 0);return f.length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wider text-[var(--color-text-secondary)]",children:b.label}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:f.map(y=>e.jsx(Ar,{resource:y},y.resource))})]},b.label)}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] text-right",children:"Updates every minute · Period resets at midnight UTC"})]})}function Tr({isOpen:t,resource:s,onClose:a}){if(!t)return null;const r=Ve[s]??s;return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",role:"dialog","aria-modal":"true","aria-labelledby":"upgrade-modal-title","aria-describedby":"upgrade-modal-desc",children:e.jsxs("div",{className:"relative bg-[var(--color-bg-surface)] rounded-xl shadow-2xl max-w-md w-full mx-4 p-6 space-y-4",children:[e.jsx("button",{type:"button",onClick:a,className:"absolute top-4 right-4 text-[var(--color-text-secondary)] hover:text-[var(--color-text-secondary)] transition-colors","aria-label":"Close modal",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}),e.jsx("div",{className:"flex items-center justify-center w-12 h-12 rounded-full bg-[var(--color-error-bg)] mx-auto",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6 text-[var(--color-error)]",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01M12 3a9 9 0 100 18A9 9 0 0012 3z"})})}),e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("h2",{id:"upgrade-modal-title",className:"text-lg font-semibold text-[var(--color-text-primary)]",children:"Daily Limit Reached"}),e.jsxs("p",{id:"upgrade-modal-desc",className:"text-sm text-[var(--color-text-secondary)]",children:["You've reached your daily ",e.jsx("strong",{children:r})," limit on the Free plan. Upgrade to Pro for higher limits and uninterrupted access."]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 pt-2",children:[e.jsx("a",{href:"/settings/plans",className:"flex-1 inline-flex items-center justify-center px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2",children:"Upgrade to Pro"}),e.jsx("button",{type:"button",onClick:a,className:"flex-1 inline-flex items-center justify-center px-4 py-2 rounded-lg bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)] text-sm font-medium hover:bg-[var(--color-bg-elevated)] transition-colors focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2",children:"Close"})]})]})})}function Rr(){const[t,s]=l.useState(null),[a,r]=l.useState(null),n=l.useRef(new Set);l.useEffect(()=>{if(!t)return;const c=setTimeout(()=>s(null),5e3);return()=>clearTimeout(c)},[t]);const i=l.useCallback(c=>{for(const x of c.resources){if(x.percentUsed<80)continue;let m;x.threshold!==void 0?m=x.threshold:x.percentUsed>=100?m=100:x.percentUsed>=90?m=90:m=80;const h=`${x.resource}:${m}`;if(n.current.has(h))continue;n.current.add(h);const b=Ve[x.resource]??x.resource,f=Math.round(x.percentUsed);if(x.status==="blocked"&&c.plan.planId===null){r({resource:x.resource});continue}let y;f>=100?y=`You've reached your daily ${b} limit. Overage charges may apply.`:f>=90?y=`You've used ${f}% of your daily ${b} quota. Consider upgrading.`:y=`You've used ${f}% of your daily ${b} quota.`,s({type:f>=100?"error":"warning",message:y})}},[]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold text-[var(--color-text-primary)]",children:"Usage & Limits"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] mt-1",children:"Monitor your resource consumption across all metered categories."})]}),e.jsx(Er,{onSummaryLoaded:i}),a&&e.jsx(Tr,{isOpen:!0,resource:a.resource,onClose:()=>r(null)}),t&&e.jsxs("div",{role:"alert","aria-live":"polite",className:`fixed top-4 right-4 z-50 max-w-sm w-full rounded-lg shadow-lg px-4 py-3 flex items-start gap-3 ${t.type==="error"?"bg-red-600 text-white":"bg-amber-500 text-white"}`,children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 shrink-0 mt-0.5",viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})}),e.jsx("div",{className:"flex-1 text-sm font-medium",children:t.message}),e.jsx("button",{type:"button",onClick:()=>s(null),className:"shrink-0 text-white/80 hover:text-white transition-colors","aria-label":"Dismiss notification",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4",viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]})]})}
10function Dr(t){try{return new Date(t).toLocaleString()}catch{return t}}function Pr(t){if(!t)return null;const s=new Date(t).getTime()-Date.now();return Math.max(0,Math.floor(s/864e5))}const $r=()=>{const[t,s]=l.useState([]),[a,r]=l.useState(0),[n,i]=l.useState(!0),[c,x]=l.useState(null),[m,h]=l.useState(null),[b,f]=l.useState(!1),[y,w]=l.useState(!1),[P,E]=l.useState(null),[D,g]=l.useState(0),p=l.useCallback(async()=>{i(!0),x(null);try{const d=await Ss({limit:50,offset:D});d.memories.length===0&&D>0&&g(Math.max(0,Math.floor((d.total-1)/50)*50)),s([...d.memories]),r(d.total)}catch(d){x(d instanceof Error?d.message:"Failed to load memories"),s([])}finally{i(!1)}},[D]);l.useEffect(()=>{p()},[p]);const C=async d=>{h(d),x(null);try{await As(d),s(N=>N.filter(S=>S.id!==d)),r(N=>Math.max(0,N-1)),E("Memory deleted"),setTimeout(()=>E(null),3e3)}catch(N){x(N instanceof Error?N.message:"Failed to delete memory")}finally{h(null)}},o=async()=>{w(!0),x(null);try{const d=await Es();s([]),r(0),g(0),f(!1),E(`Cleared ${d.deleted} memories`),setTimeout(()=>E(null),3e3)}catch(d){x(d instanceof Error?d.message:"Failed to clear memories")}finally{w(!1)}};return e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap gap-3 items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ye,{size:24,className:"text-[var(--color-brand-400)]"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-[var(--color-text-primary)]",children:"Conversation memory"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Review what the AI copilot remembers from your conversations across this workspace, not just the selected business."})]})]}),e.jsxs("button",{onClick:()=>void p(),disabled:n,className:"inline-flex items-center gap-2 px-3 py-2 bg-slate-800 hover:bg-slate-700 rounded-lg text-sm text-white disabled:opacity-50","aria-label":"Refresh memories",children:[e.jsx(de,{size:14,className:n?"animate-spin":""}),"Refresh"]})]}),P&&e.jsxs("div",{role:"status",className:"flex items-center gap-2 px-4 py-3 bg-green-900 border border-green-700 rounded-lg text-green-300 text-sm",children:[e.jsx(ce,{size:16}),P]}),c&&e.jsxs("div",{role:"alert",className:"flex items-center gap-2 px-4 py-3 bg-red-900 border border-red-700 rounded-lg text-red-300 text-sm",children:[e.jsx(Re,{size:16}),c]}),!c&&!n&&e.jsxs("div",{className:"flex flex-wrap gap-3 items-center justify-between p-4 bg-slate-900 border border-slate-800 rounded-lg",children:[e.jsxs("div",{className:"text-sm text-slate-300",children:[e.jsx("span",{className:"font-semibold text-white",children:a})," memories stored"]}),e.jsxs("button",{onClick:()=>f(!0),disabled:a===0||n,className:"inline-flex items-center gap-2 px-4 py-2 bg-red-900 hover:bg-red-900 border border-red-700 rounded-lg text-sm text-red-300 disabled:opacity-50","aria-label":"Clear all memories",children:[e.jsx(le,{size:14}),"Clear All"]})]}),n&&t.length===0?e.jsxs("div",{className:"flex items-center justify-center py-12 text-[var(--color-text-secondary)]",children:[e.jsx(L,{size:20,className:"animate-spin mr-2"}),"Loading memories..."]}):c&&t.length===0?null:t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-[var(--color-text-secondary)]",children:[e.jsx(ye,{size:32,className:"mb-3 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No memories stored yet."}),e.jsx("p",{className:"text-xs mt-1",children:"Memories accumulate as you chat with the AI copilot."})]}):e.jsx("div",{className:"space-y-3",children:t.map(d=>{const N=Pr(d.expiresAt);return e.jsx("div",{className:"p-4 bg-slate-900 border border-slate-800 rounded-lg",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-2 flex-wrap",children:[e.jsx("span",{className:"px-2 py-0.5 bg-nexus-600/20 text-nexus-400 rounded text-xs font-medium",children:d.agentType}),d.topic&&e.jsx("span",{className:"px-2 py-0.5 bg-slate-800 text-slate-300 rounded text-xs",children:d.topic}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-slate-500",children:[e.jsx(ie,{size:11}),Dr(d.createdAt)]}),N!==null&&e.jsxs("span",{className:"text-xs text-slate-500",children:["expires in ",N,"d"]})]}),e.jsx("p",{className:"text-sm text-slate-300 line-clamp-3",children:d.summary})]}),e.jsx("button",{onClick:()=>void C(d.id),disabled:m===d.id,className:"p-2 text-slate-400 hover:text-red-400 disabled:opacity-50","aria-label":`Delete memory ${d.id}`,children:m===d.id?e.jsx(L,{size:16,className:"animate-spin"}):e.jsx(le,{size:16})})]})},d.id)})}),a>50&&!c&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 text-sm text-slate-300",children:[e.jsx("button",{type:"button",disabled:n||D===0,onClick:()=>g(d=>Math.max(0,d-50)),className:"px-3 py-2 bg-slate-800 rounded-lg disabled:opacity-50",children:"Previous"}),e.jsxs("span",{children:[D+1,"–",Math.min(D+50,a)," of ",a]}),e.jsx("button",{type:"button",disabled:n||D+50>=a,onClick:()=>g(d=>d+50),className:"px-3 py-2 bg-slate-800 rounded-lg disabled:opacity-50",children:"Next"})]}),b&&e.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"
10clear-memory-title",className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-slate-900 border border-slate-700 rounded-xl max-w-md w-full p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(K,{size:24,className:"text-red-400"}),e.jsx("h2",{id:"clear-memory-title",className:"text-lg font-bold text-white",children:"Clear all memories?"})]}),e.jsxs("p",{className:"text-sm text-slate-300",children:["This will permanently delete all ",a," of your conversation memories. The AI copilot will no longer remember previous sessions. This action cannot be undone."]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>f(!1),disabled:y,className:"px-4 py-2 bg-slate-800 hover:bg-slate-700 rounded-lg text-sm text-white disabled:opacity-50",children:"Cancel"}),e.jsxs("button",{onClick:()=>void o(),disabled:y,className:"inline-flex items-center gap-2 px-4 py-2 bg-red-700 hover:bg-red-600 rounded-lg text-sm text-white disabled:opacity-50",children:[y&&e.jsx(L,{size:14,className:"animate-spin"}),y?"Clearing...":"Delete Everything"]})]})]})})]})};async function zr(){return O("/v1/ai/preferences")}async function Ir(t){return V("/v1/ai/preferences",t)}async function Et(){return O("/v1/ai/models")}async function Lr(){return O("/v1/ai/health/providers")}async function Mr(){return O("/v1/ai/preferences/budget")}async function _r(t){return ke("/v1/ai/preferences/budget",{monthlyBudgetCents:t})}async function Fr(t){return V("/v1/ai/compare",t)}async function Ur(t,s){return O(`/v1/ai/usage/time-series?startDate=${encodeURIComponent(t)}&endDate=${encodeURIComponent(s)}`)}const ot={content_generation:{label:"Writing content",icon:Xt},chat:{label:"Conversations",icon:He},reasoning:{label:"Planning and analysis",icon:ye},function_calling:{label:"Using connected tools",icon:Ht},embedding:{label:"Searching saved knowledge",icon:ft},code_generation:{label:"Writing code",icon:Vt},image_generation:{label:"Creating images",icon:Gt},fine_tuning:{label:"Training custom models",icon:vt},analytics_narration:{label:"Explaining analytics",icon:He},adversarial_consensus:{label:"Comparing critical viewpoints",icon:ye}};function Br({toast:t,onDismiss:s}){return e.jsxs("div",{role:"status","aria-live":"polite",className:`fixed top-4 right-4 z-50 flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium shadow-lg animate-fade-in ${t.type==="success"?"bg-[var(--color-bg-surface)] text-[var(--color-success)] border border-emerald-500/30":"bg-[var(--color-bg-surface)] text-[var(--color-error)] border border-red-500/30"}`,children:[t.message,e.jsx("button",{onClick:s,className:"ml-2 text-current opacity-60 hover:opacity-100",children:"×"})]})}function Or(t){const{inputPer1M:s,outputPer1M:a}=t.pricing,r=(s*500+a*500)/1e6;return r<.01?"<$0.01":`$${r.toFixed(2)}`}function Wr(t){const s={};for(const a of t){const r=a.provider;s[r]||(s[r]=[]),s[r].push(a)}return s}function qr(){const[t,s]=l.useState(null),[a,r]=l.useState(null),[n,i]=l.useState(!0),[c,x]=l.useState(null),[m,h]=l.useState(null),b=l.useRef(null),[f,y]=l.useState(null),w=l.useCallback(o=>{b.current&&clearTimeout(b.current),h(o),b.current=setTimeout(()=>{h(null),b.current=null},2500)},[]);l.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const P=l.useCallback(async()=>{i(!0),x(null);try{const[o,d]=await Promise.all([zr(),Et()]);s(o),r(d)}catch(o){const d=o instanceof Error?o.message:"Failed to load routing configuration";x(d)}finally{i(!1)}},[]);l.useEffect(()=>{P()},[P]);const E=l.useCallback(async(o,d,N)=>{const S=ot[o.taskType],k=(S==null?void 0:S.label)??o.taskType;y(o.taskType);try{const u=await Ir({taskType:o.taskType,primaryModel:d==="primaryModel"?N:o.primaryModel,fallbackModel:d==="fallbackModel"?N:o.fallbackModel??void 0});s(v=>v&&{...v,preferences:v.preferences.map(z=>z.taskType===o.taskType?{...z,...u}:z)}),w({type:"success",message:`Model updated for ${k}`})}catch(u){const v=u instanceof Error?u.message:"Failed to save preference";w({type:"error",message:v})}finally{y(null)}},[w]);if(n)return e.jsx("div",{className:"space-y-2",children:Array.from({length:8}).map((o,d)=>e.jsxs("div",{className:"flex items-center gap-4 py-3",children:[e.jsx("div",{className:"w-[180px] h-5 bg-[var(--color-bg-surface)] rounded animate-pulse"}),e.jsx("div",{className:"flex-1 h-9 bg-[var(--color-bg-surface)] rounded animate-pulse"}),e.jsx("div",{className:"flex-1 h-9 bg-[var(--color-bg-surface)] rounded animate-pulse"}),e.jsx("div",{className:"w-[100px] h-5 bg-[var(--color-bg-surface)] rounded animate-pulse"}),e.jsx("div",{className:"w-[60px] flex justify-center",children:e.jsx("div",{className:"w-2 h-2 bg-[var(--color-bg-surface)] rounded-full animate-pulse"})})]},d))});if(c)return e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12 text-center",children:[e.jsx(oe,{size:32,className:"text-[var(--color-error)]"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Unable to load model routing configuration. Check your network connection and reload."}),e.jsx("button",{onClick:()=>void P(),className:"px-4 py-2 text-sm font-medium rounded-lg bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors",children:"Reload Settings"})]});const D=(a==null?void 0:a.models.filter(o=>o.available))??[],g=Wr(D),p=(a==null?void 0:a.models)??[],C=(a==null?void 0:a.defaultRouting)??{};return e.jsxs("div",{className:"space-y-4",children:[m&&e.jsx(Br,{toast:m,onDismiss:()=>h(null)}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Each selection saves immediately for future workspace AI requests. There is no separate Save button. Tasks that explicitly choose a model can override these defaults; changing a preference does not rerun existing work."}),D.length===0&&e.jsx("p",{role:"status",className:"text-sm text-[var(--color-text-secondary)]",children:"No provider models are available. Saved preferences remain visible below. Ask your workspace administrator to configure a provider, then reload these settings."}),((t==null?void 0:t.preferences)??[]).map(o=>{var v;const d=ot[o.taskType]??{label:o.taskType,icon:vt},N=d.icon,S=p.find(z=>z.model===o.primaryModel),k=((v=C[o.taskType])==null?void 0:v.primary)===o.primaryModel,u=(S==null?void 0:S.available)??!1;return e.jsxs("div",{className:"flex flex-col gap-3 py-4 px-3 rounded-lg border border-[var(--color-border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2 w-full md:w-[180px] shrink-0",children:[e.jsx(N,{size:16,className:"text-[var(--color-text-secondary)]"}),e.jsx("span",{className:"text-sm font-medium text-[var(--color-text-primary)]",children:d.label})]}),e.jsxs("p",{className:"text-xs text-[var(--color-text-secondary)] break-all",children:["Primary: ",o.primaryModel,". Fallback: ",o.fallbackModel||"None","."]}),e.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-[var(--color-text-secondary)]",children:"Primary"}),e.jsxs("select",{value:o.primaryModel,disabled:f!==null,onChange:z=>void E(o,"primaryModel",z.target.value),className:"w-full bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm text-[var(--color-text-primary)] focus:outline-none focus:ring-2 focus:ring-violet-500 focus:border-transparent","aria-label":`Primary model for ${d.label}`,children:[!u&&e.jsxs("option",{value:o.primaryModel,children:[o.primaryModel," (Unavailable)"]}),Object.entries(g).map(([z,A])=>e.jsx("optgroup",{label:z,children:A.map(M=>{var _;return e.jsxs("option",{value:M.model,children:[M.model,((_=C[o.taskType])==null?void 0:_.primary)===M.model?" (Recommended)":""]},M.model)})},z))]}),k&&e.jsx("span",{className:"hidden md:inline-flex ml-1 text-xs px-2 py-0.5 rounded bg-vi
10olet-500/10 text-[var(--color-info)] whitespace-nowrap",title:`This is the platform default for ${d.label}. Optimized for cost and quality.`,children:"Recommended"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mb-1",children:"Fallback"}),e.jsxs("select",{value:o.fallbackModel??"",disabled:f!==null,onChange:z=>void E(o,"fallbackModel",z.target.value),className:"w-full bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm text-[var(--color-text-primary)] focus:outline-none focus:ring-2 focus:ring-violet-500 focus:border-transparent","aria-label":`Fallback model for ${d.label}`,children:[e.jsx("option",{value:"",children:"None"}),o.fallbackModel&&!D.some(z=>z.model===o.fallbackModel)&&e.jsxs("option",{value:o.fallbackModel,children:[o.fallbackModel," (Unavailable)"]}),Object.entries(g).map(([z,A])=>e.jsx("optgroup",{label:z,children:A.map(M=>e.jsx("option",{value:M.model,children:M.model},M.model))},z))]})]}),e.jsx("div",{className:"w-full md:w-[100px] text-right",children:e.jsxs("span",{className:"text-xs font-mono text-[var(--color-text-secondary)]",children:["Estimated cost: ",S?`${Or(S)}/req`:"unavailable"]})}),e.jsxs("div",{className:"w-full md:w-[60px] flex md:justify-center",children:[e.jsx("span",{className:`inline-block w-2 h-2 rounded-full ${u?"bg-emerald-500":"bg-[var(--color-bg-elevated)]"}`,"aria-hidden":"true"}),e.jsx("span",{role:"status",className:"text-xs text-[var(--color-text-secondary)]",children:f===o.taskType?"Saving…":u?"Provider available":"Provider unavailable"})]})]},o.taskType)})]})}const Kr={google:{displayName:"Google (Gemini)",color:"#4285F4"},anthropic:{displayName:"Anthropic (Claude)",color:"#c084fc"},openai:{displayName:"OpenAI (GPT)",color:"#10a37f"},xai:{displayName:"x.ai (Grok)",color:"#f97316"},openrouter:{displayName:"OpenRouter",color:"#f43f5e"}};function Yr(t){switch(t){case"healthy":return"bg-emerald-500";case"degraded":return"bg-amber-500";case"down":return"bg-red-500";case"not_configured":default:return"bg-slate-500"}}function Gr(t){switch(t){case"healthy":return"Provider healthy";case"degraded":return"Provider degraded";case"down":return"Provider down";case"not_configured":default:return"Provider not configured"}}function Vr({provider:t}){const s=Kr[t.provider]??{displayName:t.provider,color:"#8b5cf6"};return e.jsxs("div",{className:"bg-slate-950 border border-slate-800 rounded-xl p-6 relative",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:s.displayName}),e.jsx("span",{className:`w-2 h-2 rounded-full ${Yr(t.status)}`,"aria-hidden":"true"})]}),e.jsx("p",{className:"text-xs text-slate-300 mb-3",children:Gr(t.status)}),t.configured?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-slate-400",children:"Latency"}),e.jsx("span",{className:"text-white font-mono text-xs",children:t.latencyP95Ms!==null?`p95 ${t.latencyP95Ms}ms`:"—"})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-slate-400",children:"Error Rate"}),e.jsx("span",{className:"text-white font-mono text-xs",children:t.errorRate!==null?`${t.errorRate.toFixed(1)}%`:"—"})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-slate-400",children:"Models"}),e.jsxs("span",{className:"text-white font-mono text-xs",children:[t.modelCount," available"]})]})]}):e.jsx("p",{className:"text-sm text-slate-500",children:"API key not set. Configure this provider to use its models."}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 rounded-b-xl",style:{backgroundColor:s.color}})]})}function Hr(){const[t,s]=l.useState(null),[a,r]=l.useState(!0),[n,i]=l.useState(null),c=l.useCallback(async()=>{r(!0),i(null);try{const m=await Lr();s(m)}catch(m){const h=m instanceof Error?m.message:"Failed to load provider status";i(h)}finally{r(!1)}},[]);if(l.useEffect(()=>{c()},[c]),a)return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:Array.from({length:5}).map((m,h)=>e.jsxs("div",{className:"bg-slate-950 border border-slate-800 rounded-xl p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"w-32 h-4 bg-slate-800 rounded animate-pulse"}),e.jsx("div",{className:"w-2 h-2 bg-slate-800 rounded-full animate-pulse"})]}),e.jsx("div",{className:"w-full h-3 bg-slate-800 rounded animate-pulse"}),e.jsx("div",{className:"w-3/4 h-3 bg-slate-800 rounded animate-pulse"}),e.jsx("div",{className:"w-1/2 h-3 bg-slate-800 rounded animate-pulse"})]},h))});if(n)return e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12 text-center",children:[e.jsx(oe,{size:32,className:"text-[var(--color-error)]"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Unable to load provider status. The server may be temporarily unavailable."}),e.jsx("button",{onClick:()=>void c(),className:"px-4 py-2 text-sm font-medium rounded-lg bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors",children:"Reload Settings"})]});const x=(t==null?void 0:t.providers)??[];return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:x.map(m=>e.jsx(Vr,{provider:m},m.provider))})}const Xr={google:"#4285F4",anthropic:"#c084fc",openai:"#10a37f",xai:"#f97316",openrouter:"#f43f5e"};function Jr({toast:t,onDismiss:s}){return e.jsxs("div",{role:"status","aria-live":"polite",className:`fixed top-4 right-4 z-50 flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium shadow-lg animate-fade-in ${t.type==="success"?"bg-[var(--color-bg-surface)] text-[var(--color-success)] border border-emerald-500/30":"bg-[var(--color-bg-surface)] text-[var(--color-error)] border border-red-500/30"}`,children:[t.message,e.jsx("button",{onClick:s,className:"ml-2 text-current opacity-60 hover:opacity-100",children:"×"})]})}function fe(t){return(t/100).toFixed(2)}function it(t){return new Date(t+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric"})}function Qr(){const t=new Date,s=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0");return`${s}-${a}
10-01`}function Zr(){const t=new Date,s=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${s}-${a}-${r}`}function el(t){const s=new Set;for(const a of t)for(const r of Object.keys(a))r!=="date"&&s.add(r);return Array.from(s)}function tl(){const[t,s]=l.useState(0),[a,r]=l.useState(null),[n,i]=l.useState([]),[c,x]=l.useState(!0),[m,h]=l.useState(null),[b,f]=l.useState(null),[y,w]=l.useState(!1),P=l.useRef(!1),E=l.useRef(null),D=l.useCallback(A=>{E.current&&clearTimeout(E.current),f(A),E.current=setTimeout(()=>{f(null),E.current=null},2500)},[]);l.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]);const g=l.useCallback(async()=>{x(!0),h(null);try{const[A,M]=await Promise.all([Mr(),Ur(Qr(),Zr())]);r(A),i(M),s((A.monthlyBudgetCents??0)/100)}catch(A){const M=A instanceof Error?A.message:"Failed to load budget data";h(M)}finally{x(!1)}},[]);l.useEffect(()=>{g()},[g]);const p=l.useCallback(async A=>{if(P.current||!a)return;const M=A===0?null:Math.round(A*100);if(M!==a.monthlyBudgetCents){P.current=!0,w(!0);try{const _=await _r(M);r(_),s((_.monthlyBudgetCents??0)/100),D({type:"success",message:"Budget updated"})}catch(_){s((a.monthlyBudgetCents??0)/100);const $=_ instanceof Error?_.message:"Failed to save budget";D({type:"error",message:$})}finally{P.current=!1,w(!1)}}},[a,D]);if(c)return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Array.from({length:3}).map((A,M)=>e.jsxs("div",{className:"bg-slate-950 border border-slate-800 rounded-xl p-6",children:[e.jsx("div",{className:"h-4 w-24 bg-slate-800 rounded animate-pulse mb-3"}),e.jsx("div",{className:"h-7 w-20 bg-slate-800 rounded animate-pulse mb-2"}),e.jsx("div",{className:"h-3 w-32 bg-slate-800 rounded animate-pulse"})]},M))}),e.jsx("div",{className:"bg-slate-950 border border-slate-800 rounded-xl p-6",children:e.jsx("div",{className:"h-[300px] bg-slate-800 rounded animate-pulse"})})]});if(m)return e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12 text-center",children:[e.jsx(oe,{size:32,className:"text-[var(--color-error)]"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Unable to load budget and usage data. Check your network connection and reload."}),e.jsx("button",{onClick:()=>void g(),className:"px-4 py-2 text-sm font-medium rounded-lg bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors",children:"Reload Settings"})]});const C=(a==null?void 0:a.monthlyBudgetCents)!=null,o=(a==null?void 0:a.currentMonthSpendCents)??0,d=(a==null?void 0:a.budgetRemainingCents)??null,N=(a==null?void 0:a.projectedMonthEndCents)??0,S=(a==null?void 0:a.percentUsed)??0,k=el(n),u=new Date().getDate(),v=u>0?u:1;let z=null;return C&&S>=100?z="Budget limit reached -- all AI requests are using economy models until next month.":C&&S>=90?z="Your org has used 90% of this month's AI budget. Economy model fallback is imminent.":C&&S>=80&&(z="Heads up -- your org has used 80% of this month's AI budget. Requests will auto-downgrade to economy models at the limit."),e.jsxs("div",{className:"space-y-6",children:[b&&e.jsx(Jr,{toast:b,onDismiss:()=>f(null)}),z&&e.jsxs("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg px-4 py-2 flex items-center gap-2",children:[e.jsx(K,{size:18,className:"text-[var(--color-warning)] shrink-0"}),e.jsx("span",{className:"text-sm text-[var(--color-warning)]",children:z})]}),e.jsxs("div",{className:"bg-slate-950 border border-slate-800 rounded-xl p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wider text-slate-500 mb-4",children:"Monthly Budget"}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx("div",{className:"flex-1",children:e.jsx("input",{type:"range",min:0,max:500,step:5,value:t,disabled:y,onChange:A=>s(Number(A.target.value)),onMouseUp:A=>void p(Number(A.currentTarget.value)),onTouchEnd:A=>void p(Number(A.currentTarget.value)),onKeyUp:A=>{["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(A.key)&&p(Number(A.currentTarget.value))},onBlur:A=>void p(Number(A.currentTarget.value)),className:"w-full h-2 rounded-lg appearance-none cursor-pointer accent-violet-500 bg-slate-700","aria-label":"Monthly AI budget in dollars"})}),e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{"aria-live":"polite",className:"text-2xl font-semibold text-white",children:t===0?"No limit":`$${t}`}),t>0&&e.jsx("span",{className:"text-sm text-slate-400",children:"/mo"})]}),e.jsx("input",{type:"number",min:0,max:500,step:5,value:t,disabled:y,onChange:A=>{const M=Math.max(0,Math.min(500,Number(A.target.value)||0));s(M)},onBlur:A=>void p(Number(A.currentTarget.value)),className:"w-20 bg-slate-900 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white text-center focus:outline-none focus:ring-2 focus:ring-violet-500 focus:border-transparent","aria-label":"Budget amount in dollars"})]}),y&&e.jsx("p",{role:"status",className:"mt-2 text-sm text-slate-400",children:"Saving budget…"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-slate-950 border border-slate-800 rounded-xl p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Oe,{size:16,className:"text-slate-400"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Spent This Month"})]}),e.jsxs("p",{className:"text-2xl font-semibold text-white",children:["$",fe(o)]}),e.jsx("p",{className:"text-sm text-slate-400 mt-1",children:C?`of $${fe(a.monthlyBudgetCents)} budget`:"No budget limit set"})]}),e.jsxs("div",{className:"bg-slate-950 border border-slate-800 rounded-xl p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Jt,{size:16,className:"text-slate-400"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Budget Remaining"})]}),e.jsx("p",{className:`text-2xl font-semibold ${C&&d!=null&&d>0?"text-emerald-500":"text-white"}`,children:C&&d!=null?`$${fe(d)}`:"Unlimited"}),e.jsx("p",{className:"text-sm text-slate-400 mt-1",children:C?`${Math.max(0,100-S).toFixed(0)}% remaining`:"No limit configured"})]}),e.jsxs("div",{className:"bg-slate-950 border border-slate-800 rounded-xl p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ut,{size:16,className:"text-slate-400"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Projected EOM"})]}),e.jsxs("p",{className:"text-2xl font-semibold text-white",children:["$",fe(N)]}),e.jsxs("p",{className:"text-sm text-slate-400 mt-1",children:["Based on ",v,"-day trend"]})]})]}),e.jsxs("div",{className:"bg-slate-950 border border-slate-800 rounded-xl p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wider text-slate-500 mb-4",children:"Daily AI Spend by Provider"}),n.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-white mb-2",children:"No usage data yet"}),e.jsx("p",{className:"text-sm text-slate-400 max-w-md",children:"AI spend data will appear here after your first AI-powered request."})]}):e.jsx(Qt,{width:"100%",height:300,children:e.jsxs(Zt,{data:n,children:[e.jsx(es,{strokeDasharray:"3 3",stroke:"#334155"}),e.jsx(ts,{dataKey:"date",stroke:"#94a3b8",tick:{fontSize:12},tickFormatter:it}),e.jsx(ss,{stroke:"#94a3b8",tickFormatter:A=>`$${(Number(A)/100).toFixed(0)}`}),e.jsx(as,{contentStyle:{backgroundColor:"#0f172a",border:"1px solid #334155",borderRadius:"8px",fontSize:"12px"},labelFormatter:A=>it(String(A)),formatter:(A,M)=>[`$${fe(Number(A))}`,String(M).charAt(0).toUpperCase()+String(M).slice(1)]}),k.map(A=>e.jsx(rs,{dataKey:A,stackId:"cost",fill:Xr[A]??"#6b7280",name:A},A))]})})]})]})}function sl(t){return t>=1e3?`${(t/1e3).toFixed(1)}s`:`${Math.round(t)}ms`}function al(t){return`$${(t/100).toFixed(3)}`}function rl(t){return`${t} tok`}function ll(t){const s={};for(const a of t)s[a.provider]||(s[a.provider]=[]),s[a.provider].push(a);return s}function nl(){const[t,s]=l.useState(""),[a,r]=l.useState(["",""]),[n,i]=l.useState([]),[c,x]=l.useState([]),[m,h]=l.useState(!1),[b,f]=l.useState(null),[y,w]=l.useState(!0);l.useEffect(()=>{let d=!1;async function N(){try{const S=await Et();if(d)return;const k=S.models.filter(v=>v.available);i(k);const u=k.slice(0,2).map(v=>v.model);r(u.length>=2?u:[...u,...Array(2-u.length).fill("")])}catch(S){d||f(S instanceof Error?S.message:"Failed to load models")}finally{d||w(!1)}}return N(),()=>{d=!0}},[]);const P=l.useCallback((d,N)=>{r(S=>{const k=[...S];return k[d]=N,k})},[]),E=l.useCallback(()=>{r(d=>d.length>=4?d:[...d,""])},[]),D=l.useCallback(d=>{r(N=>N.length<=2?N:N.filter((S,k)=>k!==d))},[]),g=l.useCallback(async()=>
10{const d=a.filter(Boolean);if(!(d.length<2||!t.trim())){h(!0),x([]),f(null);try{const N=await Fr({prompt:t.trim(),models:d,maxTokens:1024});x(N.results)}catch(N){f(N instanceof Error?N.message:"Comparison failed")}finally{h(!1)}}},[a,t]);if(y)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"h-20 bg-[var(--color-bg-surface)] rounded-lg animate-pulse"}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"h-10 flex-1 bg-[var(--color-bg-surface)] rounded-lg animate-pulse"}),e.jsx("div",{className:"h-10 flex-1 bg-[var(--color-bg-surface)] rounded-lg animate-pulse"})]})]});if(b&&c.length===0&&!m&&n.length===0)return e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12 text-center",children:[e.jsx(oe,{size:32,className:"text-[var(--color-error)]"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:b}),e.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 text-sm font-medium rounded-lg bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors",children:"Reload Settings"})]});const p=ll(n),o=a.filter(Boolean).length>=2&&t.trim().length>0&&!m;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl p-6 space-y-4",children:[e.jsx("textarea",{value:t,onChange:d=>s(d.target.value),placeholder:"Enter a prompt to compare across models...",rows:3,className:"w-full bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg p-2 text-sm text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] resize-y focus:outline-none focus:ring-2 focus:ring-violet-500 focus:border-transparent",style:{maxHeight:"12rem"},"aria-label":"Comparison prompt"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[a.map((d,N)=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("select",{value:d,onChange:S=>P(N,S.target.value),className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm text-[var(--color-text-primary)] focus:outline-none focus:ring-2 focus:ring-violet-500 focus:border-transparent min-w-[200px]","aria-label":`Model ${N+1} selector`,children:[e.jsx("option",{value:"",children:"Select model..."}),Object.entries(p).map(([S,k])=>e.jsx("optgroup",{label:S,children:k.map(u=>{const v=a.some((z,A)=>A!==N&&z===u.model);return e.jsxs("option",{value:u.model,disabled:v,children:[u.model,v?" (selected)":""]},u.model)})},S))]}),a.length>2&&e.jsx("button",{onClick:()=>D(N),className:"p-1 text-[var(--color-text-secondary)] hover:text-[var(--color-error)] transition-colors","aria-label":`Remove model ${N+1}`,children:e.jsx(re,{size:14})})]},N)),a.length<4&&e.jsxs("button",{onClick:E,className:"flex items-center gap-1 text-sm text-[var(--color-info)] hover:text-[var(--color-info)] transition-colors",children:[e.jsx(ls,{size:16}),"Add Model"]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("button",{onClick:()=>void g(),disabled:!o,className:"bg-gradient-to-r from-violet-600 to-purple-600 text-white px-6 py-2 rounded-lg font-semibold disabled:opacity-50 disabled:cursor-not-allowed transition-opacity",children:m?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(L,{size:16,className:"animate-spin"}),"Running..."]}):"Run Comparison"}),b&&c.length>0&&e.jsx("span",{className:"text-sm text-[var(--color-error)]",children:b})]})]}),b&&c.length===0&&n.length>0&&e.jsxs("div",{className:"bg-red-500/10 border border-red-500/30 rounded-lg px-4 py-2 flex items-center gap-2",children:[e.jsx(oe,{size:18,className:"text-[var(--color-error)] shrink-0"}),e.jsx("span",{className:"text-sm text-[var(--color-error)]",children:"One or more models failed to respond. Check provider status on the Providers tab."})]}),m&&e.jsx("div",{className:`grid gap-4 ${a.filter(Boolean).length<=2?"grid-cols-2":a.filter(Boolean).length===3?"grid-cols-2 lg:grid-cols-3":"grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}
10`,children:a.filter(Boolean).map(d=>{const N=n.find(S=>S.model===d);return e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-[var(--color-border-default)]",children:[e.jsx("p",{className:"text-sm font-semibold text-[var(--color-text-primary)]",children:d}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)]",children:(N==null?void 0:N.provider)??"Unknown"})]}),e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx(L,{size:24,className:"animate-spin text-[var(--color-info)]"})})]},d)})}),!m&&c.length>0&&e.jsx("div",{className:`grid gap-4 ${c.length<=2?"grid-cols-2":c.length===3?"grid-cols-2 lg:grid-cols-3":"grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}`,children:c.map(d=>{const N=n.find(S=>S.model===d.model);return e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-[var(--color-border-default)]",children:[e.jsx("p",{className:"text-sm font-semibold text-[var(--color-text-primary)]",children:d.model}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)]",children:d.provider??(N==null?void 0:N.provider)??"Unknown"})]}),e.jsx("div",{className:"flex-1 max-h-80 overflow-y-auto p-4",children:d.error?e.jsx("p",{className:"text-sm text-[var(--color-error)]",children:d.error}):e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap",children:d.text??"No response"})}),!d.error&&e.jsxs("div",{className:"px-4 py-3 border-t border-[var(--color-border-default)] flex flex-wrap gap-2",children:[d.latencyMs!=null&&e.jsx("span",{className:"inline-flex items-center gap-1 text-xs font-mono px-2 py-1 rounded bg-[var(--color-bg-surface)] text-[var(--color-info)]",children:sl(d.latencyMs)}),d.costCents!=null&&e.jsx("span",{className:"inline-flex items-center gap-1 text-xs font-mono px-2 py-1 rounded bg-[var(--color-bg-surface)] text-[var(--color-success)]",children:al(d.costCents)}),d.outputTokens!=null&&e.jsx("span",{className:"inline-flex items-center gap-1 text-xs font-mono px-2 py-1 rounded bg-[var(--color-bg-surface)] text-[var(--color-text-secondary)]",children:rl(d.outputTokens)})]})]},d.model)})}),!m&&c.length===0&&!b&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-[var(--color-text-primary)] mb-2",children:"Compare AI models side by side"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] max-w-md",children:"Select two or more models above, enter a prompt, and click Run Comparison to see quality, speed, and cost differences."})]})]})}const ol=["routing","providers","budget","compare","consensus"],il={routing:"Routing",providers:"Providers",budget:"Budget",compare:"Compare",consensus:"Consensus"};function cl(){const[t,s]=l.useState("routing");return e.jsxs("div",{className:"max-w-4xl space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx(_e,{size:24,className:"text-[var(--color-info)]"}),e.jsx("h1",{className:"text-xl font-semibold text-[var(--color-text-primary)]",children:"AI model controls"})]}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Advanced workspace-wide model routing, providers and budget controls. These are shared across businesses, not settings for an individual AI teammate."}),e.jsx("div",{"aria-label":"AI model sections",className:"flex flex-wrap gap-1 border-b border-[var(--color-border-default)]",children:ol.map(a=>e.jsx("button",{type:"button","aria-pressed":t===a,onClick:()=>s(a),className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${t===a?"border-violet-500 text-[var(--color-info)]":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:il[a]},a))}),e.jsxs("div",{className:"animate-fade-in",children:[t==="routing"&&e.jsx(qr,{}),t==="providers"&&e.jsx(Hr,{}),t==="budget"&&e.jsx(tl,{}),t==="compare"&&e.jsx(nl,{}),t==="consensus"&&e.jsx(Ts,{})]})]})}const se="/v1/brand-governance",xe={listRules:t=>{const s=new URLSearchParams;t!=null&&t.contentType&&s.set("contentType",t.contentType),(t==null?void 0:t.isActive)!==void 0&&s.set("isActive",String(t.isActive)),t!=null&&t.take&&s.set("take",String(t.take)),t!=null&&t.cursor&&s.set("cursor",t.curs
10or);const a=s.toString();return O(`${se}/rules${a?`?${a}`:""}`)},getRule:t=>O(`${se}/rules/${t}`),createRule:t=>V(`${se}/rules`,t),updateRule:(t,s)=>ke(`${se}/rules/${t}`,s),deleteRule:t=>we(`${se}/rules/${t}`),listApprovals:t=>{const s=new URLSearchParams;t!=null&&t.status&&s.set("status",t.status),t!=null&&t.take&&s.set("take",String(t.take)),t!=null&&t.cursor&&s.set("cursor",t.cursor);const a=s.toString();return O(`${se}/approvals${a?`?${a}`:""}`)},decideApproval:(t,s)=>V(`${se}/approvals/${t}/decide`,s),listAuditLogs:t=>{const s=new URLSearchParams;t!=null&&t.contentType&&s.set("contentType",t.contentType),t!=null&&t.take&&s.set("take",String(t.take)),t!=null&&t.cursor&&s.set("cursor",t.cursor);const a=s.toString();return O(`${se}/audit-logs${a?`?${a}`:""}`)},scoreContent:t=>V(`${se}/score`,t)},ct=[{value:"forbidden_terms",label:"Forbidden Terms",description:"Block content containing specific keywords"},{value:"required_disclaimers",label:"Required Disclaimers",description:"Require specific text (e.g., opt-out links)"},{value:"voice_similarity",label:"Brand Voice",description:"Score similarity to brand voice (AI-powered)"},{value:"tone_consistency",label:"Tone Consistency",description:"Enforce allowed tone(s) via AI detection"},{value:"length_constraints",label:"Length Constraints",description:"Enforce min/max character limits"},{value:"forbidden_patterns",label:"Forbidden Patterns",description:"Block content matching a regex pattern"}],dl=[{value:"any",label:"All content types"},{value:"sms",label:"SMS"},{value:"email",label:"Email"},{value:"social",label:"Social"},{value:"ads",label:"Ads"}],xl=[{value:"auto_approve",label:"Auto-approve on pass"},{value:"flag_for_review",label:"Flag for review on fail"},{value:"block",label:"Block on fail (hard rule)"}];function dt(t){switch(t){case"forbidden_terms":return{terms:[],case_sensitive:!1};case"required_disclaimers":return{disclaimers:[]};case"voice_similarity":return{min_score:.7};case"tone_consistency":return{allowed_tones:["professional"]};case"length_constraints":return{min_chars:0,max_chars:1600};case"forbidden_patterns":return{regex:"",match_type:"contains"}}}const ml=({rule:t,onSave:s,onClose:a})=>{var _;const r=te.useId(),n=!!t,[i,c]=l.useState(!1),[x,m]=l.useState(null),[h,b]=l.useState((t==null?void 0:t.ruleType)??"forbidden_terms"),[f,y]=l.useState((t==null?void 0:t.contentType)??"any"),[w,P]=l.useState((t==null?void 0:t.name)??""),[E,D]=l.useState((t==null?void 0:t.description)??""),[g,p]=l.useState((t==null?void 0:t.config)??dt(h)),[C,o]=l.useState((t==null?void 0:t.weight)??1),[d,N]=l.useState((t==null?void 0:t.threshold)??70),[S,k]=l.useState((t==null?void 0:t.action)??"flag_for_review"),[u,v]=l.useState((t==null?void 0:t.isActive)??!0);l.useEffect(()=>{t||p(dt(h))},[h,t]);const z=async $=>{$.preventDefault(),c(!0),m(null);try{const R=h==="forbidden_terms"?"terms":h==="required_disclaimers"?"disclaimers":h==="tone_consistency"?"allowed_tones":null,I=R?g[R]:null,j=R&&Array.isArray(I)?{...g,[R]:I.map(Q=>Q.trim()).filter(Boolean)}:g,T={ruleType:h,contentType:f,name:w,description:E||void 0,config:j,weight:C,threshold:d,action:S,isActive:u},F=n?await xe.updateRule(t.id,T):await xe.createRule(T);s(F)}catch(R){m(R instanceof Error?R.message:"Failed to save rule")}finally{c(!1)}},A=($,R)=>{p(I=>({...I,[$]:R}))},M=()=>{switch(h){case"forbidden_terms":{const $=Array.isArray(g.terms)?g.terms.join(`
11`):"";return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-terms`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Forbidden Terms (one per line)"}),e.jsx("textarea",{id:`${r}-terms`,className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm min-h-[100px] focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]",value:$,onChange:R=>A("terms",R.target.value.split(`
12`)),placeholder:`e.g. guaranteed
13100% free
14act now`})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--color-text-primary)]",children:[e.jsx("input",{type:"checkbox",checked:g.case_sensitive===!0,onChange:R=>A("case_sensitive",R.target.checked),className:"rounded"}),"Case sensitive"]})]})}case"required_disclaimers":{const $=Array.isArray(g.disclaimers)?g.disclaimers.join(`
15`):"";return e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-disclaimers`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Required Disclaimers (one per line — must appear verbatim in content)"}),e.jsx("textarea",{id:`${r}-disclaimers`,className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm min-h-[100px] focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]",value:$,onChange:R=>A("disclaimers",R.target.value.split(`
16`)),placeholder:`e.g. Reply STOP to opt out
17Privacy policy applies`})]})}case"voice_similarity":{const $=typeof g.min_score=="number"?g.min_score:.7;return e.jsxs("div",{children:[e.jsxs("label",{htmlFor:`${r}-similarity`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:["Minimum Similarity Score: ",Math.round($*100),"%"]}),e.jsx("input",{id:`${r}-similarity`,type:"range",min:0,max:100,value:Math.round($*100),onChange:R=>A("min_score",parseInt(R.target.value,10)/100),className:"w-full accent-teal-500"}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-1",children:"AI will rate how well generated content matches your brand voice on a 0-100 scale."})]})}case"tone_consistency":{const $=Array.isArray(g.allowed_tones)?g.allowed_tones.join(","):"";return e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-tones`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Allowed Tones (comma-separated)"}),e.jsx("input",{id:`${r}-tones`,type:"text",className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]",value:$,onChange:R=>A("allowed_tones",R.target.value.split(",")),placeholder:"professional, friendly, empathetic"})]})}case"length_constraints":return e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-min-chars`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Min chars"}),e.jsx("input",{id:`${r}
17-min-chars`,type:"number",className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]",value:typeof g.min_chars=="number"?g.min_chars:0,min:0,onChange:$=>A("min_chars",parseInt($.target.value,10)||0)})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-max-chars`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Max chars"}),e.jsx("input",{id:`${r}-max-chars`,type:"number",className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]",value:typeof g.max_chars=="number"?g.max_chars:1600,min:1,onChange:$=>A("max_chars",parseInt($.target.value,10)||1600)})]})]});case"forbidden_patterns":return e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-pattern`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Regex Pattern"}),e.jsx("input",{id:`${r}-pattern`,type:"text",className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]",value:typeof g.regex=="string"?g.regex:"",onChange:$=>A("regex",$.target.value),placeholder:String.raw`e.g. \b(click here|act now)\b`}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-1",children:"Case-insensitive by default. Test your regex at regex101.com."})]})}};return e.jsx(ue,{isOpen:!0,onClose:a,title:n?"Edit workspace rule":"New workspace rule",size:"xl",closeOnBackdrop:!i,closeOnEscape:!i,showCloseButton:!i,children:e.jsx("form",{onSubmit:z,className:"text-[var(--color-text-primary)]",children:e.jsxs("fieldset",{disabled:i,className:"min-w-0 space-y-5",children:[x&&e.jsx("div",{role:"alert",className:"bg-red-50 text-red-700 text-sm px-3 py-2 rounded-lg",children:x}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-type`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Rule Type"}),e.jsx("select",{id:`${r}-type`,value:h,onChange:$=>b($.target.value),disabled:n,className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 disabled:bg-[var(--color-bg-muted)] bg-[var(--color-bg-surface)]",children:ct.map($=>e.jsx("option",{value:$.value,children:$.label},$.value))}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-1",children:(_=ct.find($=>$.value===h))==null?void 0:_.description})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-name`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Name"}),e.jsx("input",{id:`${r}-name`,type:"text",required:!0,maxLength:100,value:w,onChange:$=>P($.target.value),className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]",placeholder:"e.g. No financial promises"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-content-type`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Applies to content type"}),e.jsx("select",{id:`${r}-content-type`,value:f,onChange:$=>y($.target.value),className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]",children:dl.map($=>e.jsx("option",{value:$.value,children:$.label},$.value))})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h3",{className:"text-sm font-medium text-[var(--color-text-primary)] mb-3",children:"Rule Configuration"}),M()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-weight`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Weight (importance)"}),e.jsx("input",{id:`${r}
17-weight`,type:"number",step:.1,min:.1,max:5,value:C,onChange:$=>o(parseFloat($.target.value)||1),className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]"}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-0.5",children:"1.0 = normal, 2.0 = critical"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-threshold`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"Threshold (0-100)"}),e.jsx("input",{id:`${r}-threshold`,required:!0,type:"number",min:0,max:100,value:Number.isNaN(d)?"":d,onChange:$=>N($.target.valueAsNumber),className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]"}),e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-0.5",children:"Fail if rule score is below this"})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${r}-action`,className:"block text-sm font-medium text-[var(--color-text-primary)] mb-1",children:"On failure"}),e.jsx("select",{id:`${r}-action`,value:S,onChange:$=>k($.target.value),className:"min-h-11 w-full border border-[var(--color-border-default)] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 bg-[var(--color-bg-surface)]",children:xl.map($=>e.jsx("option",{value:$.value,children:$.label},$.value))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--color-text-primary)]",children:[e.jsx("input",{type:"checkbox",checked:u,onChange:$=>v($.target.checked),className:"rounded accent-teal-500"}),"Rule is active"]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{type:"button",onClick:a,className:"min-h-11 px-4 py-2 text-sm text-[var(--color-text-primary)] border border-[var(--color-border-default)] rounded-lg hover:bg-[var(--color-bg-muted)]",children:"Cancel"}),e.jsx("button",{type:"submit",disabled:i,className:"min-h-11 px-4 py-2 text-sm font-medium text-white bg-teal-700 rounded-lg hover:bg-teal-800 disabled:opacity-50",children:i?"Saving…":n?"Save Changes":"Create Rule"})]})]})})})},Ie={approved:{label:"Approve",bg:"bg-green-700 hover:bg-green-800",text:"text-white"},rejected:{label:"Reject",bg:"bg-red-700 hover:bg-red-800",text:"text-white"},changes_requested:{label:"Request Changes",bg:"bg-amber-700 hover:bg-amber-800",text:"text-white"}},ul=({onCountChange:t})=>{const[s,a]=l.useState([]),[r,n]=l.useState(!0),[i,c]=l.useState(null),[x,m]=l.useState({}),[h,b]=l.useState(null),[f,y]=l.useState("pending"),w=l.useCallback(async()=>{n(!0),b(null);try{const g=await xe.listApprovals({status:f||void 0,take:50});a(g),f==="pending"&&(t==null||t(g.length))}catch(g){b(g instanceof Error?g.message:"Failed to load approvals")}finally{n(!1)}},[f,t]);l.useEffect(()=>{w()},[w]);const P=async(g,p)=>{c(g);try{await xe.decideApproval(g,{decision:p,feedback:x[g]}),await w()}catch(C){b(C instanceof Error?C.message:"Decision failed")}finally{c(null)}},E=g=>new Date(g).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),D=g=>{const p=new Date(g).getTime()-Date.now(),C=Math.floor(p/36e5);return C<1?"Expires soon":C<24?`Expires in ${C}h`:`Expires ${E(g)}`};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:["pending","approved","rejected",""].map(g=>e.jsx("button",{onClick:()=>y(g),"aria-pressed":f===g,className:`min-h-11 px-3 py-2 text-sm rounded-full border transition-colors ${f===g?"bg-teal-700 text-white border-teal-700":"text-[var(--color-text-secondary)] border-[var(--color-border-default)] hover:bg-[var(--color-bg-muted)]"}`,children:g===""?"All":g.charAt(0).toUpperCase()+g.slice(1)},g||"all"))}),e.jsx("button",{onClick:()=>{w()},className:"min-h-11 px-2 text-sm text-teal-700 dark:text-teal-300",children:"Refresh"})]}),h&&e.jsx("div",{role:"alert",className:"bg-red-50 text-red-700 text-sm px-3 py-2 rounded-lg",children:h}),r?e.jsx("div",{role:"status",className:"text-center py-8 text-[var(--color-text-secondary)] text-sm",children:"Loading approval tasks…"}):h&&s.length===0?null:s.length===0?e.jsx("div",{className:"text-center py-12 text-[var(--color-text-secondary)]",children:e.jsxs("p",{className:"text-sm",children:["No ",f||""," approval tasks"]})}):e.jsx("div",{className:"space-y-3",children:s.map(g=>e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl p-4 space-y-3 shadow-sm",children:[e.jsxs("div",{className:"flex flex-wrap 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:[e.jsx("span",{className:"text-xs font-medium text-[var(--color-text-secondary)] uppercase tracking-wide",children:g.contentType}),e.jsx("span",{className:"text-xs text-[var(--color-text-secondary)]",children:g.status})]}),g.contentSnip&&e.jsx("p",{className:"text-sm text-[var(--color-text-primary)] line-clamp-2",children:g.contentSnip})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("div",{className:"text-xs text-[var(--color-text-secondary)]",children:E(g.createdAt)}),g.status==="pending"&&e.jsx("div",{className:"text-xs text-orange-500 mt-0.5",children:D(g.expiresAt)})]})]}),e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)]",children:["Score: ",e.jsxs("span",{className:"font-medium text-[var(--color-text-primary)]",children:[g.score,"/100"]})," · ","Requires ",e.jsx("span",{className:"font-medium",children:g.requiredApprovers})," approver(s)"]}),g.status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text","aria-label":`Feedback for ${g.contentType}
17 approval`,placeholder:"Optional feedback or notes…",value:x[g.id]??"",onChange:p=>m(C=>({...C,[g.id]:p.target.value})),className:"min-h-11 w-full text-sm bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] border border-[var(--color-border-default)] rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-teal-500"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:["approved","rejected","changes_requested"].map(p=>e.jsx("button",{onClick:()=>{P(g.id,p)},disabled:i===g.id,className:`min-h-11 px-3 py-2 text-sm font-medium rounded-lg transition-opacity ${Ie[p].bg} ${Ie[p].text} disabled:opacity-50`,children:i===g.id?"…":Ie[p].label},p))})]}),g.status!=="pending"&&e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)]",children:["Status:"," ",e.jsx("span",{className:g.status==="approved"?"text-green-600 font-medium":g.status==="rejected"?"text-red-600 font-medium":"text-yellow-600 font-medium",children:g.status}),g.feedback&&e.jsxs("span",{className:"ml-2 text-[var(--color-text-secondary)] italic",children:["“",g.feedback,"”"]})]})]},g.id))})]})},pl=[{id:"rules",label:"Rules"},{id:"approvals",label:"Approval Inbox"},{id:"audit",label:"Audit Log"}],hl={auto_approve:"Auto-approve",flag_for_review:"Flag for review",block:"Block (hard)"},bl={voice_similarity:"Brand Voice",forbidden_terms:"Forbidden Terms",required_disclaimers:"Required Disclaimers",tone_consistency:"Tone Consistency",length_constraints:"Length Limits",forbidden_patterns:"Forbidden Patterns"},fl=()=>{const[t,s]=l.useState("rules"),[a,r]=l.useState(0),[n,i]=l.useState([]),[c,x]=l.useState(!0),[m,h]=l.useState(null),[b,f]=l.useState(!1),[y,w]=l.useState(null),[P,E]=l.useState(null),[D,g]=l.useState([]),[p,C]=l.useState(!1),[o,d]=l.useState(null),N=l.useCallback(async()=>{x(!0),h(null);try{const v=await xe.listRules({take:100});i(v)}catch(v){h(v instanceof Error?v.message:"Failed to load rules")}finally{x(!1)}},[]),S=l.useCallback(async()=>{C(!0),d(null);try{const v=await xe.listAuditLogs({take:100});g(v)}catch(v){d(v instanceof Error?v.message:"Failed to load audit log")}finally{C(!1)}},[]);l.useEffect(()=>{N()},[N]),l.useEffect(()=>{t==="audit"&&S()},[t,S]);const k=async v=>{if(window.confirm("Delete this rule? This cannot be undone.")){E(v);try{await xe.deleteRule(v),i(z=>z.filter(A=>A.id!==v))}catch(z){h(z instanceof Error?z.message:"Delete failed")}finally{E(null)}}},u=v=>{i(z=>{const A=z.findIndex(M=>M.id===v.id);if(A>=0){const M=[...z];return M[A]=v,M}return[v,...z]}),f(!1),w(null)};return e.jsxs("div",{className:"max-w-4xl mx-auto px-4 py-8 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-[var(--color-text-primary)]",children:"Brand Governance"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] mt-1",children:"Workspace-wide content checks, approvals and scoring history. These rules apply across your businesses, not only the selected business."})]}),e.jsx("div",{className:"border-b border-[var(--color-border-default)]",children:e.jsx("nav",{"aria-label":"Brand governance sections",className:"flex flex-wrap gap-1 -mb-px",children:pl.map(v=>e.jsxs("button",{onClick:()=>s(v.id),"aria-pressed":t===v.id,className:`min-h-11 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${t===v.id?"border-teal-500 text-teal-700 dark:text-teal-300":"border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"}`,children:[v.label,v.id==="approvals"&&a>0&&e.jsx("span",{className:"ml-1.5 bg-teal-700 text-white text-xs rounded-full px-1.5 py-0.5",children:a})]},v.id))})}),t==="rules"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-sm text-[var(--color-text-secondary)]",children:[n.length," loaded rules (up to 100)"]}),e.jsx("button",{onClick:()=>{w(null),f(!0)},className:"flex min-h-11 items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-teal-700 rounded-lg hover:bg-teal-800",children:"+ New Rule"})]}),m&&e.jsxs("div",{role:"alert",className:"bg-red-50 text-red-700 text-sm px-3 py-2 rounded-lg",children:[m," ",e.jsx("button",{type:"button",onClick:()=>void N(),className:"min-h-11 px-2 underline",children:"Retry loading rules"})]}),c?e.jsx("div",{role:"status",className:"text-center py-8 text-[var(--color-text-secondary)] text-sm",children:"Loading rules…"}):m&&n.length===0?null:n.length===0?e.jsxs("div",{className:"text-center py-12 text-[var(--color-text-secondary)]",children:[e.jsx("p",{className:"text-sm font-medium",children:"No rules configured yet"}),e.jsx("p",{className:"text-xs mt-1",children:"Add rules to start scoring AI-generated content."})]}):e.jsx("div",{className:"space-y-2",children:n.map(v=>e.jsxs("div",{className:"bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] rounded-xl p-4 flex flex-col sm:flex-row items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-[var(--color-text-primary)] text-sm",children:v.name}),e.jsx("span",{className:"text-xs bg-[var(--color-bg-muted)] text-[var(--color-text-secondary)] px-2 py-0.5 rounded-full",children:bl[v.ruleType]??v.ruleType}),v.contentType!=="any"&&e.jsx("span",{className:"text-xs bg-teal-50 text-teal-700 px-2 py-0.5 rounded-full",children:v.contentType}),!v.isActive&&e.jsx("span",{className:"text-xs text-[var(--color-text-secondary)]",children:"(disabled)"})]}),e.jsxs("div",{className:"text-xs text-[var(--color-text-secondary)] space-x-3",children:[e.jsxs("span",{children:["Weight: ",e.jsxs("strong",{children:[v.weight,"×"]})]}),e.jsxs("span",{children:["Threshold: ",e.jsx("strong",{children:v.threshold})]}
17),e.jsxs("span",{children:["On fail: ",e.jsx("strong",{children:hl[v.action]??v.action})]})]}),v.description&&e.jsx("p",{className:"text-xs text-[var(--color-text-secondary)] mt-1",children:v.description})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>{w(v),f(!0)},className:"min-h-11 text-sm text-teal-700 dark:text-teal-300 px-3 py-2 rounded-lg hover:bg-[var(--color-bg-muted)]",children:"Edit"}),e.jsx("button",{onClick:()=>{k(v.id)},disabled:P===v.id,className:"min-h-11 text-sm text-red-600 dark:text-red-300 px-3 py-2 rounded-lg hover:bg-[var(--color-bg-muted)] disabled:opacity-50",children:P===v.id?"…":"Delete"})]})]},v.id))})]}),t==="approvals"&&e.jsx(ul,{onCountChange:r}),t==="audit"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-[var(--color-text-secondary)]",children:[D.length," loaded log entries (up to 100)"]}),e.jsx("button",{onClick:()=>{S()},className:"min-h-11 px-2 text-sm text-teal-700 dark:text-teal-300 hover:text-teal-800 dark:hover:text-teal-200",children:"Refresh"})]}),o&&e.jsx("div",{role:"alert",className:"bg-red-50 text-red-700 text-sm px-3 py-2 rounded-lg",children:o}),p?e.jsx("div",{role:"status",className:"text-center py-8 text-[var(--color-text-secondary)] text-sm",children:"Loading audit log…"}):o&&D.length===0?null:D.length===0?e.jsxs("div",{className:"text-center py-12 text-[var(--color-text-secondary)]",children:[e.jsx("p",{className:"text-sm",children:"No audit log entries yet."}),e.jsx("p",{className:"text-xs mt-1",children:"Entries appear after AI content is scored."})]}):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:"text-left text-xs text-[var(--color-text-secondary)] border-b",children:[e.jsx("th",{className:"pb-2 pr-4 font-medium",children:"Date"}),e.jsx("th",{className:"pb-2 pr-4 font-medium",children:"Type"}),e.jsx("th",{className:"pb-2 pr-4 font-medium",children:"Content Preview"}),e.jsx("th",{className:"pb-2 pr-4 font-medium",children:"Score"}),e.jsx("th",{className:"pb-2 font-medium",children:"Action"})]})}),e.jsx("tbody",{className:"divide-y divide-[var(--color-border-default)]",children:D.map(v=>e.jsxs("tr",{className:"text-xs text-[var(--color-text-primary)]",children:[e.jsx("td",{className:"py-2 pr-4 whitespace-nowrap text-[var(--color-text-secondary)]",children:new Date(v.createdAt).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}),e.jsx("td",{className:"py-2 pr-4",children:e.jsx("span",{className:"bg-[var(--color-bg-muted)] text-[var(--color-text-secondary)] px-2 py-0.5 rounded-full",children:v.contentType})}),e.jsx("td",{className:"py-2 pr-4 max-w-[200px] truncate text-[var(--color-text-secondary)] italic",children:v.contentSnip??"—"}),e.jsx("td",{className:"py-2 pr-4",children:e.jsxs("span",{children:[v.score,"/100"]})}),e.jsx("td",{className:"py-2 text-[var(--color-text-secondary)]",children:v.action})]},v.id))})]})})]}),b&&e.jsx(ml,{rule:y,onSave:u,onClose:()=>{f(!1),w(null)}})]})};async function gl(t={}){const s=new URLSearchParams;t.take!==void 0&&s.set("take",String(t.take)),t.cursor&&s.set("cursor",t.cursor),t.toolName&&s.set("toolName",t.toolName);const a=s.toString()?`?${s.toString()}`:"";return O(`/v1/mcp/dashboard/audit-logs${a}`)}function Tt(){return`${window.location.origin}/v1/mcp`}function Rt(t){return JSON.stringify({mcpServers:{ultimatenexus:{url:t,headers:{Authorization:"Bearer <YOUR_API_KEY>"}}}},null,2)}function Ae({text:t,label:s="Copy"}){const[a,r]=l.useState(!1),[n,i]=l.useState(!1),c=l.useCallback(async()=>{i(!1);try{await navigator.clipboard.writeText(t),r(!0),setTimeout(()=>r(!1),2e3)}catch{i(!0),r(!1)}},[t]);return e.jsxs("button",{onClick:c,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-slate-700 hover:bg-slate-600 text-slate-300 hover:text-white transition-colors",children:[a?e.jsx(ve,{size:12,className:"text-green-400"}):e.jsx(Te,{size:12}),n?"Copy failed — select text manually":a?"Copied!":s]})}function vl(){const t=Tt(),s=Rt(t);return e.jsxs("div",{className:"bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-4",children:[e.jsx("h2",{className:"text-base font-semibold text-white",children:"Connection Setup"}),e.jsx("p",{className:"text-sm text-slate-400",children:"Use this URL to connect your AI tools to the UltimateNexus MCP server."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-medium text-slate-400 uppercase tracking-wide",children:"MCP Server URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{readOnly:!0,value:t,className:"flex-1 bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white font-mono focus:outline-none"}),e.jsx(Ae,{text:t,label:"Copy URL"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs font-medium text-slate-400 uppercase tracking-wide",children:"Claude Desktop Config"}),e.jsx(Ae,{text:s,label:"Copy Config"})]}),e.jsx("pre",{className:"bg-slate-800 border border-slate-700 rounded-lg px-4 py-3 text-xs text-slate-300 font-mono overflow-x-auto whitespace-pre",children:s}),e.jsxs("p",{className:"text-xs text-slate-500",children:["Add this to"," ",e.jsx("code",{className:"text-slate-400",children:"~/.claude/claude_desktop_config.json"}),", replacing"," ",e.jsx("code",{className:"text-slate-400",children:"<YOUR_API_KEY>"})," with an API key from below."]})]})]})}function jl(){return e.jsxs("section",{className:"bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-3",children:[e.jsx("h2",{className:"text-base font-semibold text-white",children:"Worksp
17ace API keys"}),e.jsx("p",{className:"text-sm text-slate-400",children:"A workspace owner or administrator can create a key. Keys can access workspace data across businesses; only connect tools you trust."}),e.jsx(Ke,{to:"/settings/api-keys",className:"inline-flex px-4 py-2 rounded-lg bg-nexus-600 text-white text-sm",children:"Manage API keys"})]})}function yl(){const[t,s]=l.useState("claude"),a=Tt();return e.jsxs("div",{className:"bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-4",children:[e.jsx("h2",{className:"text-base font-semibold text-white",children:"Setup Guides"}),e.jsx("div",{className:"flex gap-2 border-b border-slate-800",children:["claude","chatgpt"].map(r=>e.jsx("button",{onClick:()=>s(r),className:`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${t===r?"bg-nexus-600/20 text-nexus-400 border border-b-0 border-nexus-500/30":"text-slate-400 hover:text-white"}`,children:r==="claude"?"Claude Desktop":"ChatGPT / Custom GPT"},r))}),t==="claude"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-400",children:[e.jsx(ns,{size:16}),e.jsx("span",{children:"Connect Claude Desktop to your UltimateNexus account in 3 steps"})]}),[{step:1,title:"Create an API key",desc:"Use the API Keys section above to create a new key. Copy the key value — it is only shown once.",code:void 0},{step:2,title:"Add MCP server config",desc:"Open (or create) ~/.claude/claude_desktop_config.json and add the server block below.",code:Rt(a)},{step:3,title:"Restart Claude Desktop",desc:"Quit and reopen Claude Desktop. The UltimateNexus tools will appear in your tool list.",code:void 0}].map(({step:r,title:n,desc:i,code:c})=>e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"shrink-0 w-7 h-7 rounded-full bg-nexus-600/20 border border-nexus-500/30 flex items-center justify-center text-xs font-bold text-nexus-400",children:r}),e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-white",children:n}),e.jsx("p",{className:"text-xs text-slate-400",children:i}),c&&e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"bg-slate-800 border border-slate-700 rounded-lg px-4 py-3 text-xs text-slate-300 font-mono overflow-x-auto whitespace-pre",children:c}),e.jsx("div",{className:"absolute top-2 right-2",children:e.jsx(Ae,{text:c})})]})]})]},r)),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-500 pt-2",children:[e.jsx(Le,{size:12}),e.jsx("a",{href:"https://modelcontextprotocol.io/docs/getting-started",target:"_blank",rel:"noopener noreferrer",className:"hover:text-nexus-400 transition-colors",children:"MCP documentation"})]})]}),t==="chatgpt"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-400",children:[e.jsx(os,{size:16}),e.jsx("span",{children:"Connect ChatGPT or a Custom GPT to UltimateNexus"})]}),[{step:1,title:"Create an API key",desc:"Use the API Keys section above to create a key with read + write scopes.",code:void 0},{step:2,title:"Add Action to your Custom GPT",desc:'In ChatGPT, open your Custom GPT editor → Actions → Add new action. Set the authentication to "API Key" with the header Authorization: Bearer <key>.',code:void 0},{step:3,title:"Import the OpenAPI schema",desc:"Use the MCP server URL as the base URL. The tools/call endpoint accepts JSON-formatted requests.",code:`Base URL: ${a}
18Auth header: Authorization: Bearer <YOUR_API_KEY>`}].map(({step:r,title:n,desc:i,code:c})=>e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"shrink-0 w-7 h-7 rounded-full bg-nexus-600/20 border border-nexus-500/30 flex items-center justify-center text-xs font-bold text-nexus-400",children:r}),e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-white",children:n}),e.jsx("p",{className:"text-xs text-slate-400",children:i}),c&&e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"bg-slate-800 border border-slate-700 rounded-lg px-4 py-3 text-xs text-slate-300 font-mono overflow-x-auto whitespace-pre",children:c}),e.jsx("div",{className:"absolute top-2 right-2",children:e.jsx(Ae,{text:c})})]})]})]},r))]})]})}function Nl(){const[t,s]=l.useState([]),[a,r]=l.useState(!1),[n,i]=l.useState(!1),[c,x]=l.useState(null),m=async()=>{try{r(!0),x(null);const h=await gl({take:50});s(h.logs),i(!0)}catch(h){x(h instanceof Error?h.message:"Failed to load audit logs")}finally{r(!1)}};return e.jsxs("div",{className:"bg-slate-900 border border-slate-700 rounded-xl p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold text-white",children:"Audit Logs"}),!n&&e.jsx("button",{onClick:()=>void m(),disabled:a,className:"text-xs px-3 py-1.5 rounded-lg bg-slate-700 hover:bg-slate-600 text-slate-300 hover:text-white transition-colors disabled:opacity-50",children:a?"Loading...":"Load audit logs"})]}),c&&e.jsx("p",{className:"text-sm text-red-400 bg-red-900/20 border border-red-500/20 rounded-lg px-4 py-2",children:c}),!n&&!a&&e.jsx("p",{className:"text-sm text-slate-500 text-center py-4",children:'Click "Load audit logs" to see recent MCP c
18alls.'}),n&&t.length===0&&e.jsx("p",{className:"text-sm text-slate-500 text-center py-4",children:"No MCP calls yet."}),n&&t.length>0&&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:"text-left text-xs text-slate-500 uppercase tracking-wide border-b border-slate-800",children:[e.jsx("th",{className:"pb-2 pr-4",children:"Tool"}),e.jsx("th",{className:"pb-2 pr-4",children:"Result"}),e.jsx("th",{className:"pb-2 pr-4",children:"Status"}),e.jsx("th",{className:"pb-2 pr-4",children:"Duration"}),e.jsx("th",{className:"pb-2",children:"Time"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-800",children:t.map(h=>e.jsxs("tr",{className:"text-slate-300",children:[e.jsx("td",{className:"py-2 pr-4 font-mono text-xs text-nexus-400",children:h.toolName}),e.jsx("td",{className:"py-2 pr-4 text-xs text-slate-400 max-w-[200px] truncate",children:h.resultSummary}),e.jsx("td",{className:"py-2 pr-4",children:e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${h.success?"bg-green-900/30 text-green-400":"bg-red-900/30 text-red-400"}`,children:h.success?"ok":"error"})}),e.jsxs("td",{className:"py-2 pr-4 text-xs text-slate-500",children:[h.durationMs,"ms"]}),e.jsx("td",{className:"py-2 text-xs text-slate-500",children:new Date(h.createdAt).toLocaleString()})]},h.id))})]})})]})}const wl=()=>e.jsxs("div",{className:"space-y-6 max-w-4xl",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold text-[var(--color-text-primary)]",children:"Connect AI tools"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)] mt-1",children:"Developer setup: connect external AI tools to this entire workspace using the Model Context Protocol (MCP), not to an individual business."})]}),e.jsx(vl,{}),e.jsx(jl,{}),e.jsx(yl,{}),e.jsx(Nl,{})]}),kl=({orgId:t="",currentUserId:s=""})=>{const a=t||(()=>{try{return localStorage.getItem("nexus_org_id")??""}catch{return""}})(),[r,n]=l.useState([]),[i,c]=l.useState([]),[x,m]=l.useState([]),[h,b]=l.useState(!0),[f,y]=l.useState(null),[w,P]=l.useState("users"),[E,D]=l.useState(new Set),[g,p]=l.useState(""),[C,o]=l.useState(!1),[d,N]=l.useState({name:"",description:"",permissions:[]}),[S,k]=l.useState(null),u=(S==null?void 0:S.orgId)===a&&S.permissions.includes(ae.MANAGE_USERS),v=l.useRef(0);l.useEffect(()=>(k(null),c([]),n([]),m([]),D(new Set),o(!1),N({name:"",description:"",permissions:[]}),z(),()=>{v.current+=1}),[a,s]);const z=async()=>{const j=++v.current;if(!a||!s){b(!1),y("Select a workspace and sign in to manage team access");return}try{b(!0),y(null);const[T,F,Q]=await Promise.all([ne.getRoles(a),ne.getOrgUsers(a),ne.getUserPermissions(s,a)]);if(j!==v.current)return;k({orgId:a,permissions:Q.permissions}),n(T),c(F)}catch(T){if(j!==v.current)return;const F=T instanceof Error?T.message:"Failed to load data";F.includes("403")||F.includes("Forbidden")||F.includes("permission")?y("Insufficient permissions. RBAC roles may need to be configured for this organization."):y(F)}finally{j===v.current&&b(!1)}},A=async()=>{try{const j=await ne.getAuditLogs(a,{limit:100});m(j)}catch(j){y(j instanceof Error?j.message:"Failed to load audit logs")}},M=async(j,T)=>{if(j!==s&&u)try{await ne.assignRole(j,a,T),await z()}catch(F){y(F instanceof Error?F.message:"Failed to assign role")}},_=async()=>{if(u){if(!g||E.size===0){y("Please select users and a role");return}try{const j=Array.from(E).filter(T=>T!==s).map(T=>({userId:T,roleId:g}));if(j.length===0){y("Cannot assign roles: only your own account was selected");return}await ne.bulkAssignRoles(a,j),D(new Set),p(""),await z()}catch(j){y(j instanceof Error?j.message:"Failed to bulk assign roles")}}},$=async()=>{if(u){if(!d.name||d.permissions.length===0){y("Role name and at least one permission required");return}try{await ne.createCustomRole(a,d.name,d.description,d.permissions),o(!1),N({name:"",description:"",permissions:[]}),await z()}catch(j){y(j instanceof Error?j.message:"Failed to create role")}}},R=j=>{const T=new Set(E);T.has(j)?T.delete(j):T.add(j),D(T)},I=j=>{const T=d.permissions.includes(j)?d.permissions.filter(F=>F!==j):[...d.permissions,j];N({...d,permissions:T})};return h?e.jsxs("div",{className:"p-12 flex items-center justify-center",role:"status","aria-label":"Loading",children:[e.jsx(L,{className:"w-8 h-8 animate-spin text-nexus-500"}),e.jsx("span",{className:"sr-only",children:"Loading..."})]}):f&&i.length===0&&r.length===0?e.jsxs("div",{className:"p-8 text-center",role:"alert",children:[e.jsx(K,{className:"w-12 h-12 text-amber-400 mx-auto mb-4"}),e.jsx("p",{className:"text-slate-300 font-medium mb-2",children:"Unable to Load"}),e.jsx("p",{className:"text-slate-300 mb-4 text-sm",children:f}),e.jsx(G,{onClick:z,leftIcon:e.jsx(de,{className:"w-4 h-4"}),"aria-label":"Retry loading",children:"Retry"})]}):e.jsxs("div",{className:"space-y-6 text-slate-200 [&_th]:px-3 [&_th]:py-3 [&_th]:text-left [&_th]:text-xs [&_th]:font-semibold [&_th]:text-slate-400 [&_td]:px-3 [&_td]:py-4 [&_td]:align-top [&_td]:text-sm [&_tbody_tr]:border-t [&_tbody_tr]:border-slate-700 [&_select]:rounded-lg [&_select]:border [&_select]:border-slate-600 [&_select]:bg-slate-900 [&_select]:p-2 [&_select]:text-sm [&_select]:text-slate-200 [&_select:disabled]:opacity-50",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Team Roles & Permissions"}),e.jsxs("p",{className:"max-w-4xl text-sm leading-relaxed text-slate-400",children:["For interns, assign ",e.jsx("strong",{className:"text-slate-200",children:"Contributor (draft-only / intern)"}
18),": save and reopen drafts without AI spending, approval, publishing, scheduling or execution. Editor and ordinary Member access include publishing and execution; neither is draft-only. Custom roles retain their exact grants."]}),e.jsxs("div",{className:"flex flex-wrap gap-2 border-b border-slate-700 pb-3","aria-label":"Team access views",children:[e.jsx(G,{variant:w==="users"?"primary":"ghost","aria-pressed":w==="users",onClick:()=>P("users"),children:"Team Members"}),e.jsx(G,{variant:w==="roles"?"primary":"ghost","aria-pressed":w==="roles",onClick:()=>P("roles"),children:"Roles"}),e.jsx(G,{variant:w==="audit"?"primary":"ghost","aria-pressed":w==="audit",onClick:()=>{P("audit"),A()},children:"Activity Log"})]})]}),f&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-200",role:"alert",children:[f,e.jsx(G,{variant:"ghost",onClick:()=>y(null),"aria-label":"Dismiss error",children:"×"})]}),w==="users"&&e.jsxs("div",{className:"space-y-4 overflow-x-auto",children:[E.size>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("span",{children:[E.size," users selected"]}),e.jsxs("select",{"aria-label":"Role for selected members",value:g,onChange:j=>p(j.target.value),children:[e.jsx("option",{value:"",children:"Select role..."}),r.map(j=>e.jsx("option",{value:j.id,children:j.name},j.id))]}),e.jsx(G,{onClick:_,disabled:!u,children:"Assign Role"}),e.jsx(G,{variant:"ghost",onClick:()=>D(new Set),children:"Clear"})]}),e.jsxs("table",{className:"w-full min-w-[720px] border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:e.jsx("input",{type:"checkbox","aria-label":"Select other workspace members",disabled:!u||!i.some(j=>j.userId!==s),checked:i.some(j=>j.userId!==s)&&i.filter(j=>j.userId!==s).every(j=>E.has(j.userId)),onChange:j=>{j.target.checked?D(new Set(i.filter(T=>T.userId!==s).map(T=>T.userId))):D(new Set)}})}),e.jsx("th",{children:"Workspace member"}),e.jsx("th",{children:"Effective role"}),e.jsx("th",{children:"Effective authority"}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:i.map(j=>{var F,Q,U,W,q,X,he;const T=j.userId===s;return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("input",{type:"checkbox","aria-label":`Select ${j.name||j.email||"workspace member"}`,checked:E.has(j.userId),onChange:()=>R(j.userId),disabled:T||!u})}),e.jsxs("td",{children:[j.name||j.email||"Member profile unavailable",j.name&&j.email&&e.jsx("div",{children:j.email}),T&&e.jsx("span",{className:"ml-2 inline-block rounded bg-nexus-500/15 px-2 py-0.5 text-xs text-nexus-300",children:"You"})]}),e.jsxs("td",{children:[((F=j.role)==null?void 0:F.name)||"No permissions",e.jsx("div",{className:"mt-1 text-xs text-slate-400",children:j.roleSource==="membership"?`Inherited from ${j.membershipRole} membership`:"Explicit workspace assignment"})]}),e.jsx("td",{className:"max-w-sm leading-relaxed",children:e.jsxs("span",{children:["Draft editing: ",(Q=j.role)!=null&&Q.permissions.includes(ae.EDIT_CONTENT)||(U=j.role)!=null&&U.permissions.includes(ae.EDIT_CAMPAIGNS)?"allowed":"no",";"," ","publish / schedule: ",(W=j.role)!=null&&W.permissions.includes(ae.PUBLISH_CONTENT)?"allowed":"no",";"," ","approval: ",(q=j.role)!=null&&q.permissions.includes(ae.AGENT_APPROVE)?"allowed":"no",";"," ","AI generation: ",(X=j.role)!=null&&X.permissions.includes(ae.USE_AI)?"allowed":"no",";"," ","execution: ",(he=j.role)!=null&&he.permissions.includes(ae.AGENT_EXECUTE)?"allowed":"no","."]})}),e.jsx("td",{children:e.jsxs("select",{"aria-label":`Role for ${j.name||j.email||"workspace member"}`,value:j.roleId,onChange:be=>M(j.userId,be.target.value),disabled:T||!u,children:[e.jsx("option",{value:"",children:"Select role..."}),r.map(be=>e.jsx("option",{value:be.id,children:be.name},be.id))]})})]},j.userId)})})]})]}),w==="roles"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsx(G,{onClick:()=>o(!0),disabled:!u,children:"Create Custom Role"})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:r.map(j=>e.jsxs("div",{className:"space-y-3 rounded-xl border border-slate-700 bg-slate-900/50 p-5",children:[e.jsxs("h3",{className:"font-semibold",children:[j.name,j.isCustom&&e.jsx("span",{className:"ml-2 roun
18ded bg-nexus-500/15 px-2 py-0.5 text-xs text-nexus-300",children:"Custom"})]}),e.jsx("p",{className:"text-sm text-slate-400",children:j.description}),e.jsxs("details",{className:"text-sm",children:[e.jsxs("summary",{className:"cursor-pointer py-2 text-slate-300",children:["Permissions (",j.permissions.length,")"]}),e.jsx("ul",{className:"mt-2 grid gap-1 text-slate-400 sm:grid-cols-2",children:j.permissions.map(T=>e.jsx("li",{children:T.replace(/_/g," ")},T))})]})]},j.id))}),e.jsx(ue,{isOpen:C,onClose:()=>o(!1),title:"Create Custom Role",size:"full",children:e.jsxs("div",{className:"space-y-5",children:[f&&e.jsx("p",{role:"alert",className:"rounded-lg bg-red-500/10 p-3 text-sm text-red-200",children:f}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"team-role-name",className:"block text-sm font-medium text-slate-200",children:"Role Name"}),e.jsx("input",{id:"team-role-name",className:"w-full rounded-lg border border-slate-600 bg-slate-950 p-3 text-slate-100",type:"text",value:d.name,onChange:j=>N({...d,name:j.target.value}),placeholder:"e.g., Content Manager"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"team-role-description",className:"block text-sm font-medium text-slate-200",children:"Description"}),e.jsx("textarea",{id:"team-role-description",className:"w-full rounded-lg border border-slate-600 bg-slate-950 p-3 text-slate-100",value:d.description,onChange:j=>N({...d,description:j.target.value}),placeholder:"Describe the role's responsibilities"})]}),e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-slate-200",children:"Permissions"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 lg:grid-cols-3",children:Object.values(ae).map(j=>e.jsxs("label",{className:"flex min-h-10 cursor-pointer items-center gap-2 rounded-lg border border-slate-700 px-3 py-2 text-sm text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:d.permissions.includes(j),onChange:()=>I(j)}),j.replace(/_/g," ")]},j))})]}),e.jsxs("div",{className:"flex justify-end gap-3 border-t border-slate-700 pt-4",children:[e.jsx(G,{onClick:$,disabled:!u||!d.name.trim()||!d.permissions.length,children:"Create Role"}),e.jsx(G,{variant:"ghost",onClick:()=>o(!1),children:"Cancel"})]})]})})]}),w==="audit"&&e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[680px] border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Timestamp"}),e.jsx("th",{children:"User"}),e.jsx("th",{children:"Action"}),e.jsx("th",{children:"Resource"}),e.jsx("th",{children:"Details"})]})}),e.jsx("tbody",{children:x.map(j=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(j.timestamp).toLocaleString()}),e.jsx("td",{children:j.userId}),e.jsx("td",{children:j.action}),e.jsxs("td",{children:[j.resource,j.resourceId&&` (${j.resourceId})`]}),e.jsx("td",{children:j.details&&e.jsx("code",{children:JSON.stringify(j.details,null,2)})})]},j.id))})]})})]})},Be="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4 sm:p-6 space-y-4",Cl={pending:"Ownership pending",dns_required:"Provider DNS required",verified:"Verified"};function xt({record:t}){const[s,a]=l.useState(""),r=async(n,i)=>{try{await navigator.clipboard.writeText(n),a(`${i} copied.`)}catch{a("Clipboard unavailable. Select and copy the name or value below manually.")}};return e.jsxs("div",{className:"rounded-lg border border-[var(--color-border-default)] p-3 space-y-2 text-sm min-w-0",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Type:"})," ",t.type,t.priority!==void 0&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("strong",{children:"Priority:"})," ",t.priority]}),t.status&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("strong",{children:"Provider status:"})," ",t.status]})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Name / host"}),e.jsx("code",{className:"block break-all select-text mt-1",children:t.name})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Value / target"}),e.jsx("code",{className:"block break-all select-text mt-1",children:t.value})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(G,{type:"button",variant:"outline",size:"sm",onClick:()=>void r(t.name,"Record name"),"aria-label":`Copy record name ${t.name}`,children:"Copy name"}),e.jsx(G,{type:"button",variant:"outline",size:"sm",onClick:()=>void r(t.value,"Record value"),"aria-label":`Copy record value for ${t.name}`,children:"Copy value"})]}),e.jsx("p",{role:"status",className:"text-[var(--color-text-secondary)]",children:s})]})}
18function Sl({domain:t,canManage:s,providerAvailable:a,onUpdate:r,onRemove:n,onBusyChange:i}){const[c,x]=l.useState(null),[m,h]=l.useState(""),[b,f]=l.useState(""),[y,w]=l.useState(!1),[P,E]=l.useState(""),D=async()=>{if(!(!s||c||!a)){x("verify"),i(!0);try{const p=await $s(t.id);r(p),h(""),E("Verification check completed. See the current status and DNS instructions below. No email was sent.")}catch(p){E(""),h(`${Z(p,"Verification request failed.")} Check your connection and DNS records, then retry. If provider access is denied, ask the platform operator to grant domain-management access to the email provider key.`)}finally{x(null),i(!1)}}},g=async()=>{if(!(!s||c)){x("remove"),i(!0);try{await zs(t.id),n(t.id)}catch(p){f(`${Z(p,"Removal request failed.")} Check your connection and retry. The workspace binding is not confirmed removed.`)}finally{x(null),i(!1)}}};return e.jsxs("section",{className:Be,"aria-label":`Sender domain ${t.domain}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold break-all",children:t.domain}),e.jsx("span",{className:"rounded-full border border-[var(--color-border-default)] px-3 py-1 text-sm",children:Cl[t.status]})]}),t.verifiedAt&&e.jsxs("p",{className:"text-sm text-[var(--color-text-secondary)]",children:["Last verified: ",new Date(t.verifiedAt).toLocaleString()]}),t.verificationExpiresAt&&e.jsxs("p",{className:"text-sm text-[var(--color-text-secondary)]",children:["Verification refresh due: ",new Date(t.verificationExpiresAt).toLocaleString(),". Sending requires a fresh check after this time."]}),t.message&&e.jsx("p",{className:"text-sm",children:t.message}),P&&e.jsx("p",{role:"status",className:"text-sm",children:P}),m&&e.jsx("p",{role:"alert",className:"text-sm text-[var(--color-error)]",children:m}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"1. Prove workspace ownership"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Add this TXT record at your DNS host. Keep it in place for future ownership checks. If your DNS host appends the domain automatically, enter only the relative host name."}),e.jsx(xt,{record:t.ownershipRecord})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"2. Authenticate with the email provider"}),t.providerRecords.length>0?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Add the provider records below exactly as returned, including MX priority where shown. DNS propagation may take time. Recheck after publishing them."}),t.providerRecords.map((p,C)=>e.jsx(xt,{record:p},`${p.type}:${p.name}:${C}`))]}):e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Provider records appear after ownership is verified and the provider accepts domain setup. No provider records have been returned yet."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(G,{type:"button",onClick:()=>void D(),disabled:!s||!a||c!==null,loading:c==="verify",children:t.status==="pending"?"Verify ownership":"Recheck verification"}),e.jsx(G,{type:"button",variant:"danger",disabled:!s||c!==null,onClick:()=>w(!0),children:"Remove domain"})]}),e.jsx(ue,{isOpen:y,onClose:()=>{c||w(!1)},title:"Remove sender domain?",role:"alertdialog",closeOnEscape:!c,closeOnBackdrop:!c,showCloseButton:!c,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"break-words",children:["Remove ",e.jsx("strong",{children:t.domain})," from this workspace? New sends using custom addresses at this domain will be blocked immediately; the separately available platform sender is unaffected. Already accepted email cannot be recalled. This removes the workspace binding, not DNS records at your DNS host."]}),b&&e.jsx("p",{role:"alert",className:"text-sm text-[var(--color-error)]",children:b}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(G,{type:"button",variant:"secondary",disabled:c!==null,onClick:()=>w(!1),children:"Cancel"}),e.jsx(G,{type:"button",variant:"danger",loading:c==="remove",disabled:!s||c!==null,onClick:()=>void g(),children:"Remove workspace binding"})]})]})})]})}function Al({orgId:t,currentUserId:s}){var S,k;const[a,r]=l.useState(null),[n,i]=l.useState(!0),[c,x]=l.useState(""),[m,h]=l.useState(""),[b,f]=l.useState(!1),[y,w]=l.useState(0),[P,E]=l.useState(""),[D,g]=l.useState(!1),[p,C]=l.useState(!1),[o,d]=l.useState("");l.useEffect(()=>{let u=!0;if(!t){x("Select a workspace to view email senders."),i(!1);return}return i(!0),Ds().then(v=>{u&&(r(v),x(""))}).catch(v=>{u&&x(`${Z(v,"Could not load email senders.")} Check your connection and workspace access, then choose Refresh status.`)}).finally(()=>{u&&i(!1)}),s&&ne.getUserPermissions(s,t).then(v=>{u&&(f(v.orgId===t&&v.userId===s&&v.permissions.includes(ae.MANAGE_INTEGRATIONS)),h(""))}).catch(v=>{u&&(f(!1),h(`${Z(v,"Could not verify your permissions.")} Refresh status to retry; changes remain disabled.`))}),()=>{u=!1}},[t,s,y]);const N=async u=>
18{if(u.preventDefault(),!(!b||D||n||p)){g(!0);try{const v=await Ps(P.trim());r(z=>z&&{...z,domains:[...z.domains.filter(A=>A.id!==v.id),v]}),E(""),d("")}catch(v){d(`${Z(v,"Could not add this domain.")} Enter a domain only (for example, mail.example.com), check your connection, and retry. Your input has been kept.`)}finally{g(!1)}}};return e.jsxs("div",{className:"space-y-6 text-[var(--color-text-primary)]",children:[e.jsxs("header",{className:"space-y-2",children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Email senders"}),e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Verify a domain you control to permit sender addresses at that exact domain in this workspace. Subdomains need their own verification. Campaign review and sending are separate; DNS setup and verification do not send emails."})]}),e.jsx(G,{type:"button",variant:"outline",loading:n,disabled:n||D||p,onClick:()=>w(u=>u+1),children:"Refresh status"}),n&&e.jsx("p",{role:"status",children:"Loading sender settings…"}),c&&e.jsx("p",{role:"alert",className:"text-sm text-[var(--color-error)]",children:c}),m&&e.jsx("p",{role:"alert",className:"text-sm text-[var(--color-error)]",children:m}),a&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:Be,"aria-label":"Email provider",children:[e.jsx("h3",{className:"font-semibold",children:"Email provider"}),a.provider?e.jsxs("p",{children:["Configured provider: ",e.jsx("strong",{children:a.provider==="resend"?"Resend":"SendGrid"})]}):e.jsx("p",{role:"status",children:"No email provider is configured. Ask the platform operator to configure Resend or SendGrid. You can prepare an ownership TXT record, but verification and email sending are unavailable until a provider is configured."}),((S=a.delivery)==null?void 0:S.reason)&&e.jsx("p",{role:"status",className:"text-sm text-[var(--color-warning)]",children:a.delivery.reason}),((k=a.delivery)==null?void 0:k.queueEnabled)&&a.provider&&e.jsx("p",{className:"text-sm",children:"Queue processing is enabled by configuration. Sender, consent, approval, spending and worker availability are checked separately; this is not a delivery receipt."}),a.defaultFrom?e.jsxs("p",{className:"break-words",children:["Platform sender: ",e.jsx("strong",{children:a.defaultFrom}),". This exact address is available without domain setup",!a.provider&&" once an email provider is configured","."]}):e.jsx("p",{children:"No platform sender is available. A verified workspace domain is required for a custom sender."})]}),!b&&e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"Read-only access. Ask a workspace administrator with Manage integrations permission to add, verify, or remove domains."}),e.jsxs("form",{onSubmit:u=>void N(u),className:Be,children:[e.jsx("h3",{className:"font-semibold",children:"Add a sender domain"}),e.jsx(Rs,{label:"Sender domain",value:P,onChange:u=>E(u.target.value),placeholder:"mail.example.com",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,required:!0,maxLength:253,disabled:!b||D,hint:"Use a domain you control, not an email address or website URL."}),o&&e.jsx("p",{role:"alert",className:"text-sm text-[var(--color-error)]",children:o}),e.jsx(G,{type:"submit",loading:D,disabled:!b||D||n||p||!P.trim(),children:"Add domain"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Workspace sender domains"}),a.domains.length===0&&e.jsx("p",{className:"text-sm text-[var(--color-text-secondary)]",children:"No sender domains added. Add a domain above to receive your workspace ownership TXT record."}),a.domains.map(u=>e.jsx(Sl,{domain:u,canManage:b&&!n&&!D&&!p,providerAvailable:a.provider!==null,onBusyChange:C,onUpdate:v=>r(z=>z&&{...z,domains:z.domains.map(A=>A.id===v.id?v:A)}),onRemove:v=>r(z=>z&&{...z,domains:z.domains.filter(A=>A.id!==v)})},u.id))]})]})]})}function El({orgId:t,currentUserId:s=""}){const a=Ye(),r=t||a;return e.jsx(Al,{orgId:r,currentUserId:s},`${r}:${s}`)}const Tl=[{label:"Your account & workspace",items:[{to:"/settings/profile",label:"Personal profile",icon:cs},{to:"/settings/business-profile",label:"Workspace defaults",icon:ds},{to:"/settings/team",label:"Team access",icon:xs},{to:"/settings/notifications",label:"Notifications",icon:ms},{to:"/settings/email-senders",label:"Email senders",icon:us}]},{label:"Billing & usage",items:[{to:"/settings/billing",label:"Billing",icon:Oe},{to:"/settings/plans",label:"Plans",icon:mt},{to:"/settings/usage",label:"Usage",icon:ht}]},{label:"Developer connections",advanced:!0,items:[{to:"/settings/api-keys",label:"API keys",icon:me},{to:"/settings/webhooks",label:"Webhooks",icon:Ne},{to:"/settings/mcp",label:"Connect AI tools",icon:_e}]},{label:"Advanced workspace settings",advanced:!0,items:[{to:"/settings/export",label:"Export & import",icon:ge},{to:"/settings/memory",label:"Conversation memory",icon:ye},{to:"/settings/ai-models",label:"AI model controls",icon:_e},{to:"/settings/brand-governance",label:"Brand approval rules",icon:ps},{to:"/settings/dashboards",label:"Custom dashboards",icon:je}]}],Hl=({projectId:t,currentUserId:s})=>{const a=Ye(),{pathname:r}=is();return e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 p-4 md:p-6 min-h-full",children:[e.jsxs("nav",{"aria-label":"Settings navigation",className:"grid grid-cols-1 sm:grid-cols-2 md:flex md:flex-col gap-4 md:w-56 shrink-0 border-b md:border-b-0 md:border-r border-[var(--color-border-default)] pb-4 md:pr-4",children:[Tl.map(({label:n,advanced:i,items:c})=>e.jsxs("details",{open:!i||c.some(x=>r===x.to),children:[e.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-[var(--color-text-primary)] py-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-nexus-400",children:n}),e.jsx("div",{className:"space-y-1",children:c.map(({to:x,label:m,icon:h})=>e.jsxs(hs,{to:x,className:({isActive:b})=>`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-nexus-400 ${b?"bg-nexus-600/20 text-[var(--color-brand-400)] border border-nexus-500/30":"text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-surface)]"}`,children:[e.jsx(h,{size:16,"aria-hidden":"true"}),m]},x))})]},n)),e.jsx("button",{type:"button",onClick:()=>window.dispatchEvent(new Event("nexus-onboarding-restarted")),className:"min-h-11 rounded-lg px-3 py-2 text-left text-sm text-[var(--color-text-secondary)] underline hover:text-[var(--color-text-primary)]",children:"Open optional setup guide"})]}),e.jsx("div",{className:"flex-1 min-w-0 max-w-5xl",children:e.jsxs(bs,{children:[e.jsx(Y,{path:"profile",element:e.jsx(Ms,{})}),e.jsx(Y,{path:"notifications",element:e.jsx(ia,{})}),e.jsxs(Y,{element:a?e.jsx(fs,{},a):e.jsx("p",{role:"status",children:"Choose a workspace to manage its settings."}),children:[e.jsx(Y,{path:"business-profile",element:e.jsx(Xs,{})}),e.jsx(Y,{path:"team",element:e.jsx(kl,{orgId:a,currentUserId:s})}),e.jsx(Y,{path:"email-senders",element:e.jsx(El,{orgId:a,currentUserId:s})}),e.jsx(Y,{path:"plans",element:e.jsx(js,{})}),e.jsx(Y,{path:"billing",element:e.jsx(ra,{})}),e.jsx(Y,{path:"api-keys",element:e.jsx(ya,{})}),e.jsx(Y,{path:"webhooks",element:e.jsx(Fa,{})}),e.jsx(Y,{path:"dashboards",element:e.jsx(or,{projectId:t},t)}),e.jsx(Y,{path:"export",element:e.jsx(Nr,{})}),e.jsx(Y,{path:"usage",element:e.jsx(Rr,{})}),e.jsx(Y,{path:"memory",element:e.jsx($r,{})}),e.jsx(Y,{path:"ai-models",element:e.jsx(cl,{})}),e.jsx(Y,{path:"brand-governance",element:e.jsx(fl,{})}),e.jsx(Y,{path:"mcp",element:e.jsx(wl,{})})]}),e.jsx(Y,{path:"*",element:e.jsx(gs,{to:"/settings/profile",replace:!0})})]})})]})};export{Hl as SettingsHub,Hl as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.