PageSourceSearch

https://app.onplana.com/assets/OrgSettings-lfCCzB-a.js

js onplana.com collected 2026-09-24 13:42:14 UTC 482,864 bytes, 38 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DjV5vjrK.js","assets/query-BE1DiFew.js","assets/vendor-sdx-pE5z.js","assets/zustand-CtF44swa.js","assets/ui-Di_C2VxR.js","assets/dnd-DIIJ__ms.js","assets/index-BKQ8CFYp.css"])))=>i.map(i=>d[i]);
2import{e as Q,u as Qe,h as yr,a2 as si,bU as ri,bV as ni,bW as ii,aB as $e,U as ts,S as oe,V as Cs,aE as oi,a as Vt,aK as $a,bX as li,aF as qn,z as k,g as U,X as Ht,R as Ja,Q as B,W as Lr,aQ as ua,bx as Or,bY as Ir,aR as or,a4 as Xa,a5 as qr,bZ as di,b_ as ci,b$ as gi,c0 as mi,bz as xi,bA as ui,a6 as et,c1 as pi,d as As,s as hi,K as bi,ad as lr,m as yi,Y as _n,c2 as fi,c3 as ki,N as Za,a8 as ja,a9 as Kt,y as za,bj as qs,c4 as ji,a0 as vi,aA as Ni,c5 as Si,c6 as wi,c7 as Ci,v as Ua,bI as Ai,c8 as Ei,c9 as _r,ca as cs,bp as _s,L as Pi,cb as Ti,O as Ri,Z as Mi,cc as Fi,cd as Di,aq as Us,by as Ur,ai as Li}from"./index-DjV5vjrK.js";import{u as ee,j as e,a as g,b as _e,c as $,v as Oi}from"./query-BE1DiFew.js";import{c as va,a3 as Ii,C as Gt,g as Es,X as ft,a2 as At,d4 as qi,q as je,x as Un,f as Bn,a4 as ke,P as ct,w as _i,c6 as Ha,D as ta,d5 as Ui,d6 as Bi,ai as fr,aW as Ki,d7 as Br,t as ha,O as gt,ak as Gi,n as dr,E as cr,aV as kr,ab as st,bb as $i,am as Ps,aN as Kn,o as jr,d8 as Gn,S as Kr,a5 as Qa,I as kt,cp as Hi,bk as gr,c2 as vr,ao as Gr,a0 as $n,m as dt,u as Wi,U as ba,N as Bs,d9 as Hn,bC as Vi,br as zi,bS as Qi,aE as Ya,
2cY as Ns,ay as Yi,cn as Ji,av as Xi,$ as Zi,cH as $r,F as eo,ba as to,b1 as $t,aD as es,da as ao,M as Wn,bR as so,bY as mr,ap as ro,ae as no,bE as io,db as xr,cL as oo,cx as lo,aZ as co,aQ as gs,B as Hr,cV as go,Z as Wr,dc as Vr,cr as Ba,ce as mo,ch as zr,bD as Qr,as as Nr,cq as xo}from"./ui-Di_C2VxR.js";import{u as vs}from"./ScrollFade-zmD_8fKD.js";import{b as Vn,u as zn,L as Wt}from"./vendor-sdx-pE5z.js";import{f as Yr}from"./bytes-De0xaTHi.js";import{H as pa}from"./HelpTip-DMrWLis_.js";import{d as uo,P as ms,b as po,a as Jr,B as ho}from"./BulkClassifyModal-Db9Cflmr.js";import{O as bo,a as yo}from"./RolePreviewPanel-rcY7MOXZ.js";import{c as fo}from"./orgMemberAuthority-DAdpzPBD.js";import{f as Wa}from"./format-CDaLFclC.js";import{S as ya}from"./SearchSelect-HptHqF7E.js";import{c as fa}from"./compliance-BC2PhFd2.js";import{c as ka}from"./customFields-Df2bTPaX.js";import{M as ko}from"./MemberTeamPicker-DAUB12GC.js";import{D as Xr,w as Ut,a as Qn}from"./workingCalendars-B3FV765j.js";import{c as Ks}from"./ccbMembers-DdvyaVEN.js";import{g as Gs}from"./gateReviewers-CDIsinFN.js";import{t as jo}from"./timesheets-BmkwLkZV.js";import{f as xs,S as vo,c as No,C as $s}from"./currency-lJ-I5GR9.js";import"./zustand-CtF44swa.js";import"./dnd-DIIJ__ms.js";import"./differenceInCalendarDays-Ba0vNSC1.js";import"./startOfWeek-CrXuXMlh.js";import"./useAnchoredPanel-Cu_U-ioc.js";import"./ChipAvatar-DvOebvmg.js";function So(){const{t}=Q(),a=Qe(j=>j.currentOrg),s=Qe(j=>j.user),l=yr(),i=si(),c=!!(a!=null&&a.trialPlanEndsAt),{data:r}=ee({queryKey:["trial-eligibility",a==null?void 0:a.id],queryFn:()=>$e.getTrialEligibility(),enabled:!!(a!=null&&a.id)&&!c&&!l,staleTime:600*1e3,retry:!1}),o=(r==null?void 0:r.trialDays)??14,{confirmAndClaim:x,isClaiming:d,ConfirmUI:u}=ri(o),h=ni({eligibility:r==null?void 0:r.eligibility,trialPlanEndsAt:a==null?void 0:a.trialPlanEndsAt,orgRole:a==null?void 0:a.role});if(ii(h,!l,a==null?void 0:a.id,s==null?void 0:s.id),h!=="offer"||l)return null;const f=(a==null?void 0:a.role)==="OWNER";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"card p-5 border-indigo-200 dark:border-indigo-800 bg-indigo-50/60 dark:bg-indigo-900/20",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(va,{className:"w-5 h-5 mt-0.5 flex-shrink-0 text-indigo-600 dark:text-indigo-400"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:t("trial.offerTitle",{count:o,defaultValue_one:"Try Enterprise free for {{count}} day",defaultValue_other:"Try Enterprise free for {{count}} days"})}),e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 mt-1",children:t("trial.offerBodyOwner","Governance workflows, audit logs, SSO and scenario planning, unlocked for your whole workspace. No card, and it ends by itself.")}),f&&i?e.jsxs("button",{className:"btn-primary mt-3 inline-flex items-center gap-1.5 text-sm",onClick:x,disabled:d,children:[d?t("trial.starting","Starting…"):t("trial.startCta","Start free trial"),e.jsx(Ii,{className:"w-4 h-4"})]}):e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-3",children:t("trial.cardOwnerOnly","An owner of this workspace can start the trial.")})]})]})}),u]})}function Hs(t){return t>=1e6?`${(t/1e6).toFixed(t%1e6===0?0:1)}M`:t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}function Zr(t){try{return new Date(t).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}catch{return t}}function wo(t){if(!t)return!1;const a=new Date(t).getFullYear();return Number.isFinite(a)&&a>=9e3}function Co({monthly:t,canBuy:a}){const{t:s}=Q(),[l,i]=g.useState(!1),{data:c,isLoading:r,isError:o,refetch:x}=ts({queryKey:["ai-credits"],queryFn:$e.getAiCredits,staleTime:6e4}),d=c==null?void 0:c.pools,u=t.limit===null?null:Math.max(t.limit-t.used,0),h=t.freeAiOneTime===!0,f=(d==null?void 0:d.totalRemaining)??0,j=d!=null&&d.nearestExpiry&&!wo(d.nearestExpiry)?d.nearestExpiry:null;return e.jsxs("div",{className:"rounded-lg border border-gray-200 dark:border-gray-700 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(va,{className:"w-4 h-4 text-indigo-600"})," ",s("aiCredit.title","AI credit")]}),a&&e.jsx("button",{className:"btn-secondary text-xs",onClick:()=>i(!0),children:s("aiCredit.buy","Buy AI credit")})]}),r?e.jsx(oe,{className:"h-20 rounded"}):o?e.jsx(Cs,{compact:!0,onRetry:()=>{x()}}):h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded bg-indigo-50 dark:bg-indigo-900/20 p-3",children:[e.jsx("div",{className:"text-xs text-indigo-700 dark:text-indigo-300",children:s("aiCredit.oneTimeLabel","AI tokens left (one-time bonus)")}),e.jsx("div",{className:"text-lg font-semibold mt-0.5",children:Hs(f)}),e.jsx("div",{className:"text-[11px] text-indigo-500 dark:text-indigo-400 mt-0.5 flex items-center gap-1",children:j?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{className:"w-3 h-3"})," ",s("aiCredit.someExpires","Some credit expires {{date}}",{date:Zr(j)})]}):s("aiCredit.noExpire","Does not expire")})]}),e.jsx("p",{className:"text-[11px] text-gray-400",children:s("aiCredit.oneTimeNote","Your plan includes a one-time AI token bonus that does not renew monthly. When it runs out, buy AI credit or upgrade to keep using AI.")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded bg-gray-50 dark:bg-gray-900/40 p-3",children:[e.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:s("aiCredit.monthlyLabel","Monthly allowance left")}),e.jsx("div",{className:"text-lg font-semibold mt-0.5",children:u===null?s("aiCredit.unlimited","Unlimited"):Hs(u)}),e.jsx("div",{className:"text-[11px] text-gray-400 mt-0.5",children:s("aiCredit.resetsMonthly","Resets monthly ({{month}})",{month:t.month})})]}),e.jsxs("div",{className:"rounded bg-indigo-50 dark:bg-indigo-900/20 p-3",children:[e.jsx("div",{className:"text-xs text-indigo-700 dark:text-indigo-300",children:s("aiCredit.purchasedLabel","Purchased credit left")}),e.jsx("div",{className:"text-lg font-semibold mt-0.5",children:Hs(f)}),e.jsx("div",{className:"text-[11px] text-indigo-500 dark:text-indigo-400 mt-0.5 flex items-center gap-1",children:j?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{className:"w-3 h-3"})," ",s("aiCredit.expires","Expires {{date}}",{date:Zr(j)})]}):s("aiCredit.noActive","No active credit")})]})]}),e.jsx("p",{className:"text-[11px] text-gray-400",children:s("aiCredit.purchasedNote","Purchased credit is used before your monthly allowance, and expires {{days}} days after purchase.",{days:(c==null?void 0:c.ttlDays)??90})})]}),e.jsx(oi,{open:l,onClose:()=>i(!1)})]})}function Ao({open:t,onClose:a}){const{t:s}=Q(),l=Vt({open:t,onClose:a}),i=_e(),{data:c,isLoading:r}=ee({queryKey:["agent-days"],queryFn:$e.getAgentDays,enabled:t,staleTime:6e4}),[o,x]=g.useState(null),[d,u]=g.useState(1),[h,f]=g.useState(null),j=(c==null?void 0:c.denominations)??[],b=j.find(S=>S.usd===o)??null,y=b?b.usd*d:0,N=b?b.days*d:0,p=$({mutationFn:()=>$e.buyAgentDays(o,d),onSuccess:S=>{if(S.url){window.location.href=S.url;return}i.invalidateQueries({queryKey:["agent-days"]}),a()},onError:S=>{var C,G;return f(((G=(C=S==null?void 0:S.response)==null?void 0:C.data)==null?void 0:G.error)??s("agentDays.checkoutError","Could not start checkout. Please try again."))}});return t?e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4",onClick:a,children:e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md max-h-[90dvh] overflow-y-auto",onClick:S=>S.stopPropagation(),ref:l,role:"dialog","aria-modal":"true","aria-labelledby":"buy-agent-days-modal-title",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b dark:border-gray-700",children:[e.jsxs("h2",{id:"buy-agent-days-modal-title",className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Es,{className:"w-5 h-5 text-indigo-600"})," ",s("agentDays.buy","Buy agent-days")]}),e.jsx("button",{onClick:a,className:"p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700","aria-label":s("common.close","Close"),children:e.jsx(ft,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"px-5 py-4 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:s("agentDays.modalIntro","One agent-day runs one hosted agent for a day, however many times it is called. Days included with your plan are used first.")}),r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(At,{className:"w-6 h-6 animate-spin text-indigo-600"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:s("agentDays.amount","Amount")}),e.jsx("div",{className:"grid grid-cols-4 gap-2",children:j.map(S=>e.jsxs("button",{type:"button",onClick:()=>x(S.usd),className:`px-2 py-2 rounded border text-sm font-semibold transition-colors ${o===S.usd?"border-indigo-600 bg-indigo-50 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300":"border-gray-300 dark:border-gray-600 hover:border-indigo-400"}`,children:["$",S.usd]},S.usd))}),b&&e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1.5",children:s("agentDays.daysPer","{{days}} agent-days per ${{usd}}",{days:b.days,usd:b.usd})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:s("agentDays.quantity","Quantity")}),e.jsx("input",{type:"number",min:1,max:50,value:d,onChange:S=>u(Math.max(1,Math.min(50,parseInt(S.target.value,10)||1))),className:"input w-24"})]}),b&&e.jsxs("div",{className:"rounded bg-gray-50 dark:bg-gray-900/40 p-3 text-sm space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:s("agentDays.totalDays","Total agent-days")}),e.jsx("span",{className:"font-semibold",children:N})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:s("agentDays.totalPrice","Total price")}),e.jsxs("span",{className:"font-semibold",children:["$",y.toFixed(2)]})]})]}),e.jsx("p",{className:"text-xs text-emerald-700 dark:text-emerald-400",children:s("agentDays.noExpiryNote","Agent-days you buy never expire. Only the days included with your plan each month expire at the end of that month.")}),h&&e.jsx("p",{className:"text-sm text-red-600",children:h})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t dark:border-gray-700",children:[e.jsx("button",{onClick:a,className:"btn-secondary",children:s("common.cancel","Cancel")}),e.jsx("button",{onClick:()=>{f(null),p.mutate()},disabled:!b||p.isPending,className:"btn-primary",children:p.isPending?s("agentDays.starting","Starting..."):b?s("agentDays.buyAmount","Buy ${{amount}}",{amount:y.toFixed(2)}):s("agentDays.selectAmount","Select an amount")})]})]})}):null}function Eo(){for(const t of $a){const a=li[t];if(typeof a=="number"&&a>0)return{label:qn[t]??t,days:a}}return null}function Po({canBuy:t}){const{t:a}=Q(),[s,l]=g.useState(!1),{data:i,isLoading:c,isError:r,refetch:o}=ts({queryKey:["agent-days"],queryFn:$e.getAgentDays,staleTime:6e4}),x=(i==null?void 0:i.unlimited)===!0,d=(i==null?void 0:i.balance)??0,u=(i==null?void 0:i.pendingAllowance)??0,h=(i==null?void 0:i.includedPerMonth)??0,f=!x&&d>0&&d<=3,j=Eo();return e.jsxs("div",{className:"rounded-lg border border-gray-200 dark:border-gray-700 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Es,{className:"w-4 h-4 text-indigo-600"})," ",a("agentDays.title","Hosted agent-days")]}),t&&!x&&e.jsx("button",{className:"btn-secondary text-xs",onClick:()=>l(!0),children:a("agentDays.buy","Buy agent-days")})]}),c?e.jsx(oe,{className:"h-20 rounded"}):r?e.jsx(Cs,{compact:!0,onRetry:()=>{o()}}):x?e.jsxs("div",{className:"rounded bg-indigo-50 dark:bg-indigo-900/20 p-3",children:[e.jsx("div",{className:"text-xs text-indigo-700 dark:text-indigo-300",children:a("agentDays.balanceLabel","Agent-days left")}),e.jsxs("div",{className:"text-lg font-semibold mt-0.5 flex items-center gap-1.5",children:[e.jsx(qi,{className:"w-5 h-5"})," ",a("agentDays.unlimited","Unlimited")]}),e.jsx("div",{className:"text-[11px] text-indigo-500 dark:text-indigo-400 mt-0.5",children:a("agentDays.unlimitedNote","Included with your plan")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded p-3 ${f?"bg-amber-50 dark:bg-amber-900/20":"bg-indigo-50 dark:bg-indigo-900/20"}`,children:[e.jsx("div",{className:`text-xs ${f?"text-amber-700 dark:text-amber-300":"text-indigo-700 dark:text-indigo-300"}`,children:a("agentDays.balanceLabel","Agent-days left")}),e.jsx("div",{className:"text-lg font-semibold mt-0.5",children:d}),e.jsx("div",{className:`text-[11px] mt-0.5 ${f?"text-amber-600 dar
2k:text-amber-400":"text-indigo-500 dark:text-indigo-400"}`,children:f?a("agentDays.runningLow","Running low"):u>0?a("agentDays.includesAllowance","Includes {{days}} from your plan this month",{days:u}):a("agentDays.neverExpire","Purchased days never expire")})]}),e.jsxs("div",{className:"rounded bg-gray-50 dark:bg-gray-900/40 p-3",children:[e.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:a("agentDays.includedLabel","Included each month")}),e.jsx("div",{className:"text-lg font-semibold mt-0.5",children:h}),e.jsx("div",{className:"text-[11px] text-gray-400 mt-0.5",children:h>0?a("agentDays.includedMonth","Renews monthly ({{month}})",{month:(i==null?void 0:i.month)??""}):a("agentDays.includedNone","Not included on this plan")})]})]}),e.jsxs("p",{className:"text-[11px] text-gray-400",children:[h>0?a("agentDays.note","One agent-day runs one hosted agent for a day, however many times it is called. Your included days are used first and expire at the end of the month; days you buy never expire."):a("agentDays.noteNoAllowance","One agent-day runs one hosted agent for a day, however many times it is called. This plan includes none, so buy days to run a hosted agent. Days you buy never expire."),h===0&&j&&e.jsxs(e.Fragment,{children:[" ",a("agentDays.upgradeLadder","{{plan}} includes {{days}} agent-days a month, and higher plans include more.",{plan:j.label,days:j.days})]})]})]}),e.jsx(Ao,{open:s,onClose:()=>l(!1)})]})}function To(t){const{t:a}=Q(),[s,l]=g.useState("impact"),[i,c]=g.useState(!1),[r,o]=g.useState(!1),[x,d]=g.useState(""),u=ee({queryKey:["downgrade-impact",t.targetPlan],queryFn:()=>$e.getDowngradeImpact(t.targetPlan),staleTime:60*1e3}),h=$({mutationFn:async()=>{const b=u.data,y=await $e.acknowledgeDowngrade({targetPlan:b.toPlan,impactHash:b.impactHash,ackExportSeen:i,ackLoginImpactSeen:r});return $e.createCheckout(t.targetPlan,t.interval,y.token)},onSuccess:b=>{t.onComplete(b)},onError:b=>{var N,p;const y=(p=(N=b==null?void 0:b.response)==null?void 0:N.data)==null?void 0:p.code;if(y==="ACK_HASH_STALE"||y==="IMPACT_STALE"){k.error(a("downgrade.toastImpactChanged","The impact has changed since you opened this flow. Refreshing the summary.")),u.refetch(),l("impact");return}if(y==="ACK_EXPIRED"){k.error(a("downgrade.toastConfirmExpired","Confirmation expired. Please re-confirm.")),l("confirm");return}k.error(U(b,"downgrade"))}}),f=u.data,j=g.useMemo(()=>!(!f||x.trim()!==t.orgName.trim()||f.lockedFeatures.some(N=>N.complianceCritical)&&!i||f.lockedFeatures.some(N=>N.loginImpact)&&!r),[x,t.orgName,i,r,f]);return u.isLoading?e.jsx(Ws,{onClose:t.onCancel,children:e.jsxs("div",{className:"px-6 py-16 flex flex-col items-center text-slate-500",children:[e.jsx(At,{className:"w-6 h-6 animate-spin mb-3 text-indigo-600"}),e.jsx("span",{className:"text-sm",children:a("downgrade.calculatingImpact","Calculating impact…")})]})}):u.isError||!f?e.jsx(Ws,{onClose:t.onCancel,children:e.jsxs("div",{className:"px-6 py-12 text-center",children:[e.jsx(je,{className:"w-8 h-8 text-red-500 mx-auto mb-3"}),e.jsx("p",{className:"text-sm text-slate-700 dark:text-slate-300",children:a("downgrade.loadFailed","Couldn't load downgrade impact. Please try again.")}),e.jsx("button",{onClick:t.onCancel,className:"btn-secondary mt-4",children:a("downgrade.close","Close")})]})}):e.jsxs(Ws,{onClose:t.onCancel,children:[e.jsx(Ro,{step:s,onClose:t.onCancel}),s==="impact"&&e.jsx(Fo,{impact:f,target:{label:t.targetLabel,price:t.targetPrice,interval:t.interval},onClose:t.onCancel}),s==="seats"&&e.jsx(Oo,{impact:f}),s==="confirm"&&e.jsx(Io,{impact:f,orgName:t.orgName,typedOrgName:x,onTypedOrgNameChange:d,ackedExport:i,onAckedExportChange:c,ackedLoginImpact:r,onAckedLoginImpactChange:o}),e.jsx(Mo,{step:s,canAdvanceConfirm:j,isSubmitting:h.isPending,onCancel:t.onCancel,onBack:()=>l(s==="confirm"?"seats":"impact"),onNext:()=>l(s==="impact"?"seats":"confirm"),onSubmit:()=>h.mutate()})]})}function Ws({children:t,onClose:a}){const s=Vt({open:!0,onClose:a});return e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:l=>{l.target===l.currentTarget&&a()},children:e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto",ref:s,role:"dialog","aria-modal":"true","aria-labelledby":"downgrade-step-title",children:t})})}function Ro({step:t,onClose:a}){const{t:s}=Q(),l=t==="impact"?1:t==="seats"?2:3,i=t==="impact"?s("downgrade.stepImpactTitle","Review what changes"):t==="seats"?s("downgrade.stepSeatsTitle","Resolve seat overage"):s("downgrade.stepConfirmTitle","Confirm downgrade");return e.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold text-indigo-600 dark:text-indigo-400 uppercase tracking-wide",children:s("downgrade.stepOf","Step {{n}} of 3",{n:l})}),e.jsx("h3",{id:"downgrade-step-title",className:"text-lg font-bold text-gray-900 dark:text-white mt-1",children:i})]}),e.jsx("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-xl leading-none","aria-label":s("downgrade.close","Close"),children:e.jsx(ft,{className:"w-5 h-5"})})]})}function Mo({step:t,canAdvanceConfirm:a,isSubmitting:s,onCancel:l,onBack:i,onNext:c,onSubmit:r}){const{t:o}=Q();return e.jsxs("div",{className:"px-6 py-3 bg-gray-50 dark:bg-gray-900/40 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between",children:[e.jsx("button",{onClick:t==="impact"?l:i,disabled:s,className:"text-sm text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white inline-flex items-center gap-1",children:t==="impact"?o("downgrade.cancel","Cancel"):e.jsxs(e.Fragment,{children:[e.jsx(_i,{className:"w-4 h-4"}),o("downgrade.back","Back")]})}),t==="confirm"?e.jsx("button",{onClick:r,disabled:!a||s,className:"px-4 py-2 text-sm font-semibold rounded-md bg-red-600 hover:bg-red-700 disabled:bg-red-300 disabled:cursor-not-allowed text-white inline-flex items-center gap-2",children:s?e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-4 h-4 animate-spin"}),o("downgrade.processing","Processing…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ha,{className:"w-4 h-4"}),o("downgrade.downgradeNow","Downgrade now")]})}):e.jsxs("button",{onClick:c,className:"px-4 py-2 text-sm font-semibold rounded-md bg-indigo-600 hover:bg-indigo-700 text-white inline-flex items-center gap-1",children:[t==="impact"?o("downgrade.nextSeats","Next: Seats"):o("downgrade.nextConfirm","Next: Confirm"),e.jsx(Un,{className:"w-4 h-4"})]})]})}function Fo({impact:t,target:a,onClose:s}){const{t:l}=Q(),i=-t.monthlyDeltaUsd,c=t.lockedFeatures.filter(o=>o.complianceCritical),r=t.lockedFeatures.filter(o=>!o.complianceCritical);return e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"rounded-lg bg-slate-50 dark:bg-slate-900/40 border border-slate-200 dark:border-slate-700 p-4 flex items-center justify-between text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 dark:text-slate-400",children:l("downgrade.current","Current")}),e.jsx("div",{className:"font-semibold text-slate-900 dark:text-white",children:yt(t.fromPlan)})]}),e.jsx(Un,{className:"w-5 h-5 text-slate-400"}),e.jsxs("div",{className:"text-end",children:[e.jsx("div",{className:"text-xs text-slate-500 dark:text-slate-400",children:l("downgrade.new","New")}),e.jsx("div",{className:"font-semibold text-indigo-700 dark:text-indigo-300",children:l("downgrade.perSeatMo","{{label}} · ${{price}}/seat/mo",{label:a.label,price:a.price})})]})]}),i>0&&e.jsx("div",{className:"text-xs text-emerald-700 dark:text-emerald-400 -mt-3",children:e.jsx(Ht,{i18nKey:"downgrade.estimatedSaving",values:{amount:`$${Math.round(i).toLocaleStr
2ing()}/mo`},components:[e.jsx("span",{className:"font-semibold"})],defaults:"Estimated saving: <0>{{amount}}</0>. Stripe applies prorated credit on your next invoice."})}),c.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Bn,{className:"w-4 h-4 text-amber-600"}),e.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:l("downgrade.exportBeforeHeading","Export before downgrading")})]}),e.jsx("p",{className:"text-xs text-slate-500 dark:text-slate-400 mb-2",children:l("downgrade.exportBeforeBody","These compliance-critical records become read-only for 30 days, then hidden. Download a CSV now if you need to retain them externally.")}),e.jsx("ul",{className:"divide-y divide-slate-200 dark:divide-slate-700 border border-slate-200 dark:border-slate-700 rounded-lg overflow-hidden text-sm",children:c.map(o=>e.jsx(en,{feature:o,variant:"compliance"},o.key))})]}),r.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ke,{className:"w-4 h-4 text-slate-500"}),e.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:l("downgrade.readOnlyHeading","Becomes read-only, then hidden")})]}),e.jsx("p",{className:"text-xs text-slate-500 dark:text-slate-400 mb-2",children:l("downgrade.readOnlyBody","Records are preserved in the database. After the 30-day grace window the corresponding sections of the app disappear; upgrading later restores live access without re-creating anything.")}),e.jsx("ul",{className:"divide-y divide-slate-200 dark:divide-slate-700 border border-slate-200 dark:border-slate-700 rounded-lg overflow-hidden text-sm",children:r.map(o=>e.jsx(en,{feature:o,variant:"info"},o.key))})]}),t.lockedFeatures.length===0&&e.jsx("div",{className:"rounded-lg bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 p-4 text-sm text-emerald-800 dark:text-emerald-300",children:l("downgrade.noFeaturesLost","No features are lost on this downgrade. Only seat counts and billing rate change.")}),e.jsx(Do,{onClose:s})]})}function Do({onClose:t}){const a=Qe(c=>{var r;return(r=c.currentOrg)==null?void 0:r.role}),[s,l]=Vn();if(a!=="OWNER")return null;const i=c=>{c.preventDefault();const r=new URLSearchParams(s);r.set("tab","general"),l(r,{replace:!1}),t(),setTimeout(()=>{const o=document.getElementById("data-export");o==null||o.scrollIntoView({behavior:"smooth",block:"start"})},80)};return e.jsx("div",{className:"text-xs text-slate-500 dark:text-slate-400 border-t border-slate-200 dark:border-slate-700 pt-3",children:e.jsx(Ht,{i18nKey:"downgrade.fullExportPointer",components:[e.jsx("a",{href:"?tab=general#data-export",onClick:i,className:"font-medium text-indigo-600 hover:text-indigo-800 dark:text-indigo-400 dark:hover:text-indigo-300 underline"})],defaults:"Want a full archive of the org's data (projects, tasks, members, comments, audit log, retention policy) in one ZIP? <0>Open the Org data export panel</0> on the General tab (OWNER only, one export per 24h)."})})}function en({feature:t,variant:a}){const{t:s}=Q(),l=g.useMemo(()=>{const i=Object.entries(t.counts).filter(([,c])=>c>0);return i.length===0?null:i.map(([c,r])=>`${qo(c)}: ${r.toLocaleString()}`).join(" · ")},[t.counts]);return e.jsxs("li",{className:`flex items-center justify-between px-3 py-2.5 ${a==="compliance"?"bg-amber-50/30 dark:bg-amber-900/10":""}`,children:[e.jsxs("div",{className:"min-w-0 me-3",children:[e.jsxs("div",{className:"font-medium text-gray-900 dark:text-white flex items-center gap-2",children:[t.label,t.loginImpact&&e.jsx("span",{className:"text-[10px] uppercase font-bold tracking-wide text-amber-700 bg-amber-100 dark:bg-amber-900/40 dark:text-amber-300 px-2 py-0.5 rounded",children:s("downgrade.loginImpactBadge","Login impact")})]}),l&&e.jsx("div",{className:"text-xs text-slate-500 dark:text-slate-400 mt-0.5",children:l})]}),t.exportSupported?e.jsx(Lo,{featureKey:t.key}):e.jsx("span",{className:"text-xs text-slate-400 dark:text-slate-500 italic flex-shrink-0",children:s("downgrade.hidden","Hidden")})]})}function Lo({featureKey:t}){const{t:a}=Q(),[s,l]=g.useState(!1),i=async()=>
2{l(!0);try{const{blob:c,filename:r}=await $e.exportFeature(t),o=URL.createObjectURL(c),x=document.createElement("a");x.href=o,x.download=r,document.body.appendChild(x),x.click(),x.remove(),URL.revokeObjectURL(o),k.success(a("downgrade.exportedToast","Exported {{filename}}",{filename:r}))}catch(c){k.error(U(c,"export"))}finally{l(!1)}};return e.jsxs("button",{onClick:i,disabled:s,className:"text-xs font-semibold text-indigo-600 hover:text-indigo-800 dark:text-indigo-400 dark:hover:text-indigo-300 inline-flex items-center gap-1 flex-shrink-0 disabled:opacity-50",children:[s?e.jsx(At,{className:"w-3 h-3 animate-spin"}):e.jsx(ta,{className:"w-3 h-3"}),a("downgrade.exportCsv","Export CSV")]})}function Oo({impact:t}){var x;const{t:a}=Q(),{seat:s}=t,l=s.guestsOver>0,i=s.membersOver>0,c=(((x=t.storage)==null?void 0:x.overBytes)??0)>0,r=t.planColumns??[],o=l||i||c||r.length>0;return e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[!o&&e.jsxs("div",{className:"rounded-lg bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 p-4 flex items-start gap-3",children:[e.jsx(ct,{className:"w-5 h-5 text-emerald-600 mt-0.5 flex-shrink-0"}),e.jsx("div",{className:"text-sm text-emerald-800 dark:text-emerald-300",children:a("downgrade.seatsFit","Your current member + guest counts fit within the {{plan}} plan. No seat changes required.",{plan:yt(t.toPlan)})})]}),l&&e.jsx("div",{className:"rounded-lg border border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-900/20 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(je,{className:"w-5 h-5 text-amber-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-amber-900 dark:text-amber-200 text-sm",children:a("downgrade.guestSeatsBilling",{count:s.guestsOver,defaultValue_one:"{{count}} guest seat will start billing",defaultValue_other:"{{count}} guest seats will start billing"})}),e.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-300 mt-1",children:a("downgrade.guestBillingBody",{count:s.newFreeGuestSeats,plan:yt(t.toPlan),currentGuests:s.currentGuests,guestsOver:s.guestsOver,cost:s.extraGuestMonthlyCost.toFixed(0),defaultValue_one:"{{plan}} includes {{count}} free guest seat. You have {{currentGuests}} active guests. The extra {{guestsOver}} will be charged at the regular seat rate (+${{cost}}/mo).",defaultValue_other:"{{plan}} includes {{count}} free guest seats. You have {{currentGuests}} active guests. The extra {{guestsOver}} will be charged at the regular seat rate (+${{cost}}/mo)."})}),e.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-300 mt-2",children:e.jsx(Ht,{i18nKey:"downgrade.guestRemoveHint",components:[e.jsx("a",{href:"/people?tab=members",className:"underline font-medium"})],defaults:"To avoid the charge, remove excess guests from <0>People → Members</0> before completing this downgrade, then come back to refresh."})})]})]})}),i&&e.jsx("div",{className:"rounded-lg border border-red-300 dark:border-red-700 bg-red-50 dark:bg-red-900/20 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(je,{className:"w-5 h-5 text-red-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-red-900 dark:text-red-200 text-sm",children:a("downgrade.membersOverCap",{count:s.membersOver,defaultValue_one:"{{count}} member over the new plan's hard cap",defaultValue_other:"{{count}} members over the new plan's hard cap"})}),e.jsx("p",{className:"text-xs text-red-800 dark:text-red-300 mt-1",children:e.jsx(Ht,{i18nKey:"downgrade.membersOverBody",values:{plan:yt(t.toPlan),max:s.newMaxMembers===-1?a("downgrade.unlimited","unlimited"):String(s.newMaxMembers),currentMembers:s.currentMembers,membersOver:s.membersOver},components:[e.jsx("a",{href:"/people?tab=members",className:"underline font-medium"})],defaults:"{{plan}} allows up to {{max}} members. You have {{currentMembers}}. Member access for the {{membersOver}} over-cap users may be restricted after downgrade. Remove members from <0>People → Members</0> first if you need to stay within the cap."})})]})]})}),c&&t.storage&&e.jsx("div",{className:"rounded-lg border border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-900/20 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(je,{className:"w-5 h-5 text-amber-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-amber-900 dark:text-amber-200 text-sm",children:a("downgrade.storageExceedsHeading","Storage use exceeds the new plan's limit")}),e.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-300 mt-1",children:a("downgrade.storageExceedsBody","{{plan}} includes {{limit}} of file storage; your workspace currently uses {{used}}. Nothing is deleted and every existing file stays readable and downloadable, but adding new files (uploads, attachments, document saves, and recycle-bin restores) will be blocked until usage is below the new limit. Free up space from your document libraries and task attachments, or keep a plan with more storage.",{plan:yt(t.toPlan),limit:Yr(t.storage.newLimitBytes),used:Yr(t.storage.usedBytes)})})]})]})}),r.map(d=>{const u=d.disposition==="removed";return e.jsx("div",{className:`rounded-lg border p-4 ${u?"border-red-300 dark:border-red-700 bg-red-50 dark:bg-red-900/20":"border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-900/20"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(je,{className:`w-5 h-5 mt-0.5 flex-shrink-0 ${u?"text-red-600":"text-amber-600"}`}),e.jsxs("div",{children:[e.jsx("div",{className:`font-semibold text-sm ${u?"text-red-900 dark:text-red-200":"text-amber-900 dark:text-amber-200"}`,children:d.key==="publishedApps"?a("downgrade.publishedAppsOverHeading",{count:d.over,defaultValue_one:"{{count}} published app over the new plan limit",defaultValue_other:"{{count}} published apps over the new plan limit"}):d.key==="customDomains"?a("downgrade.customDomainsOverHeading",{count:d.over,defaultValue_one:"{{count}} custom domain will be disconnected",defaultValue_other:"{{count}} custom domains will be disconnected"}):a("downgrade.projectsOverHeading",{count:d.over,defaultValue_one:"{{count}} project over the new plan limit",defaultValue_other:"{{count}} projects over the new plan limit"})}),e.jsx("p",{className:`text-xs mt-1 ${u?"text-red-800 dark:text-red-300":"text-amber-800 dark:text-amber-300"}`,children:d.key==="publishedApps"?a("downgrade.publishedAppsOverBody","{{plan}} includes {{limit}} live published app(s); you have {{current}}. Your existing apps stay online and nothing is taken down, but publishing a new one is blocked until you are back under the limit.",{plan:yt(t.toPlan),limit:d.newLimit,current:d.current}):d.key==="customDomains"?a("downgrade.customDomainsOverBody","{{plan}} includes {{limit}} custom domain(s); you have {{current}} connected. The {{over}} most recently added will be DISCONNECTED and their apps will stop serving on those domains; the older ones keep working. Upgrading again and re-adding them restores service.",{plan:yt(t.toPlan),limit:d.newLimit,current:d.current,over:d.over}):a("downgrade.projectsOverBody","{{plan}} includes {{limit}} project(s); you have {{current}}. Your existing projects stay open and nothing is deleted, but creating a new one is blocked until you are back under the limit.",{plan:yt(t.toPlan),limit:d.newLimit,current:d.current})})]})]})},d.key)}),e.jsxs("div",{className:"rounded-lg bg-slate-50 dark:bg-slate-900/40 border border-slate-200 dark:border-slate-700 p-4 text-sm",children:[e.jsxs("div",{className:"flex justify-between mb-1",children:[e.jsx("span",{className:"text-slate-600 dar
2k:text-slate-400",children:a("downgrade.billableSeatsRate","Billable seats × per-seat rate")}),e.jsxs("span",{className:"font-medium text-slate-900 dark:text-white",children:["$",t.newMonthlyTotalUsd.toFixed(0),"/mo"]})]}),l&&e.jsxs("div",{className:"flex justify-between mb-1",children:[e.jsx("span",{className:"text-slate-600 dark:text-slate-400",children:a("downgrade.ofWhichGuestOverage","Of which guest overage")}),e.jsxs("span",{className:"font-medium text-amber-700 dark:text-amber-300",children:["+$",s.extraGuestMonthlyCost.toFixed(0),"/mo"]})]}),e.jsxs("div",{className:"flex justify-between pt-2 mt-2 border-t border-slate-200 dark:border-slate-700 font-semibold",children:[e.jsx("span",{className:"text-slate-900 dark:text-white",children:a("downgrade.estimatedNewMonthly","Estimated new monthly")}),e.jsxs("span",{className:"text-slate-900 dark:text-white",children:["$",t.newMonthlyTotalUsd.toFixed(0),"/mo"]})]}),t.monthlyDeltaUsd<0&&e.jsx("div",{className:"text-xs text-emerald-700 dark:text-emerald-400 mt-1",children:a("downgrade.savesVsCurrent","Saves ${{amount}}/mo vs current plan.",{amount:Math.abs(Math.round(t.monthlyDeltaUsd)).toLocaleString()})})]})]})}function Io({impact:t,orgName:a,typedOrgName:s,onTypedOrgNameChange:l,ackedExport:i,onAckedExportChange:c,ackedLoginImpact:r,onAckedLoginImpactChange:o}){const{t:x}=Q(),d=t.lockedFeatures.some(f=>f.complianceCritical),u=t.lockedFeatures.some(f=>f.loginImpact),h=s.trim()===a.trim();return e.jsxs("div",{className:"px-6 py-5 space-y-4",children:[e.jsxs("div",{className:"rounded-lg bg-slate-50 dark:bg-slate-900/40 border border-slate-200 dark:border-slate-700 p-3 text-sm space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-600 dark:text-slate-400",children:x("downgrade.from","From")}),e.jsx("span",{className:"font-medium text-slate-900 dark:text-white",children:yt(t.fromPlan)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-600 dark:text-slate-400",children:x("downgrade.to","To")}),e.jsx("span",{className:"font-medium text-indigo-700 dark:text-indigo-300",children:yt(t.toPlan)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-600 dark:text-slate-400",children:x("downgrade.effect","Effect")}),e.jsx("span",{className:"font-medium text-slate-900 dark:text-white",children:x("downgrade.effectValue","Immediate, prorated")})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-600 dark:text-slate-400",children:x("downgrade.graceWindow","Read-only grace window")}),e.jsx("span",{className:"font-medium text-slate-900 dark:text-white",children:x("downgrade.graceWindowValue","30 days")})]})]}),d&&e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:i,onChange:f=>c(f.target.checked),className:"mt-0.5 rounded text-indigo-600 focus:ring-indigo-500"}),e.jsx("span",{className:"text-slate-700 dark:text-slate-200",children:x("downgrade.ackExport","I have exported audit logs, governance records, change requests, and webhook configs I need to retain.")})]}),u&&e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:f=>o(f.target.checked),className:"mt-0.5 rounded text-indigo-600 focus:ring-indigo-500"}),e.jsx("span",{className:"text-slate-700 dark:text-slate-200",children:x("downgrade.ackLoginImpact","I understand SSO / SCIM / IP allowlist controls will be disabled. Users will sign in with email + password (or social) and the IP gate will no longer enforce.")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 dark:text-slate-200 mb-1",children:e.jsx(Ht,{i18nKey:"downgrade.typeToConfirm",values:{orgName:a},components:[e.jsx("span",{className:"font-mono bg-slate-100 dark:bg-slate-800 px-1.5 py-0.5 rounded text-xs"})],defaults:"Type <0>{{orgName}}</0> to confirm"})}),e.jsx("input",{type:"text",value:s,onChange:f=>l(f.target.value),autoFocus:!0,className:`w-full border rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-white text-gray-900 dark:bg-gray-700 dark:text-gray-100 ${s.length===0?"border-slate-300 dark:border-slate-600":h?"border-emerald-500":"border-red-400"}`,placeholder:a}),s.length>0&&!h&&e.jsx("p",{className:"text-xs text-red-600 mt-1",children:x("downgrade.nameMismatch","Name doesn't match.")})]})]})}function yt(t){return{FREE:"Free",STARTER:"Starter",PRO:"Professional",BUSINESS:"Business",ENTERPRISE:"Enterprise",ENTERPRISE_PLUS:"Enterprise+"}[t]??t}function qo(t){const a={last90Days:"Last 90 days",deliveriesThisMonth:"Deliveries this month",timesheetEntriesLast30Days:"Timesheet entries (30d)",valuesCaptured:"Values captured",keyResults:"Key results",oauthConnections:"OAuth connections",projectLinks:"Project links",inReview:"In review",provisionedUsersMax:"Provisioned users (max)"};return a[t]?a[t]:t.replace(/([A-Z])/g," $1").replace(/^./,s=>s.toUpperCase())}function _o({targetPlan:t,orgId:a}){const{t:s}=Q(),{data:l,isLoading:i,isError:c}=ts({queryKey:["plan-diff",a,t],queryFn:()=>$e.getPlanDiff(t),staleTime:300*1e3,refetchOnWindowFocus:!1});if(i)return e.jsx("div",{className:"mb-4 h-16 rounded-lg bg-gray-50 dark:bg-gray-700/50 animate-pulse"});if(c)return e.jsx("p",{className:"mb-4 text-xs text-gray-500 dark:text-gray-400",children:s("planDiff.unavailable","We could not load the plan comparison. Your plan change is unaffected.")});if(!l||!l.enabled)return null;const{gained:r,lost:o,limits:x}=l;if(r.length===0&&o.length===0&&x.length===0)return null;const d=x.filter(h=>h.better),u=x.filter(h=>!h.better);return e.jsxs("div",{className:"mb-4 rounded-lg border border-gray-200 dark:border-gray-600 p-4 space-y-3",children:[r.length>0&&e.jsx(us,{tone:"gain",title:s("planDiff.youGain","What you get"),items:r.map(h=>h.label)}),d.length>0&&e.jsx(us,{tone:"gain",title:s("planDiff.limitsUp","Limits that go up"),items:d.map(h=>`${h.label}: ${h.from} to ${h.to}`)}),o.length>0&&e.jsx(us,{tone:"loss",title:s("planDiff.youLose","What you lose"),items:o.map(h=>h.label)}),u.length>0&&e.jsx(us,{tone:"loss",title:s("planDiff.limitsDown","Limits that go down"),items:u.map(h=>`${h.label}: ${h.from} to ${h.to}`)})]})}function us({tone:t,title:a,items:s}){const l=t==="gain",i=l?Ui:Bi;return e.jsxs("div",{children:[e.jsxs("p",{className:`flex items-center gap-1.5 text-xs font-semibold mb-1.5 ${l?"text-emerald-700 dark:text-emerald-400":"text-amber-700 dark:text-amber-400"}`,children:[e.jsx(i,{className:"w-3.5 h-3.5","aria-hidden":"true"}),a]}),e.jsx("ul",{className:"space-y-1",children:s.map(c=>e.jsxs("li",{className:"flex items-start gap-1.5 text-sm text-gray-700 dark:text-gray-300",children:[l?e.jsx(fr,{className:"w-3.5 h-3.5 mt-0.5 flex-shrink-0 text-emerald-600 dark:text-emerald-400","aria-hidden":"true"}):e.jsx(Ki,{className:"w-3.5 h-3.5 mt-0.5 flex-shrink-0 text-amber-600 dar
2k:text-amber-400","aria-hidden":"true"}),e.jsx("span",{children:c})]},c))})]})}const Uo="https://marketplace.microsoft.com/product/devsoftsolutions.onplana",Bo=t=>[e.jsx(e.Fragment,{children:"Complete checkout on Microsoft Marketplace with your Microsoft billing."}),e.jsx(e.Fragment,{children:"Microsoft brings you back to Onplana to finish setup."}),e.jsxs(e.Fragment,{children:["Choose ",e.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-200",children:"Use an existing workspace"})," and select"," ",e.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-200",children:t||"this workspace"})," to activate the plan here."]})];function Ko({orgName:t,planCode:a,hasActiveStripeSub:s}){const l=yr(),i=Qe(o=>{var x;return(x=o.currentOrg)==null?void 0:x.product}),[c,r]=g.useState(!1);return l||i==="SERVICES"?null:e.jsx("div",{className:"card p-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-50 dark:bg-blue-900/30 flex items-center justify-center flex-shrink-0",children:e.jsx(Br,{className:"w-5 h-5 text-blue-600 dark:text-blue-400"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white",children:"Prefer to buy through Microsoft?"}),e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 mt-1",children:"Pay on your existing Microsoft billing with one consolidated invoice, and draw it down against an Azure consumption commitment (MACC). Same plans, identical product. Buying with a card or Google / Microsoft sign-in above still works, this is an extra path, not a replacement."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.jsxs("a",{href:Uo,target:"_blank",rel:"noopener noreferrer",onClick:()=>Ja("marketplace_upgrade_clicked",{plan:a,hasStripeSub:s}),className:"inline-flex items-center gap-1.5 rounded-lg border border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/20 px-3.5 py-2 text-sm font-medium text-blue-700 dark:text-blue-300 hover:bg-blue-100 dark:hover:bg-blue-900/40 transition-colors",children:[e.jsx(Br,{className:"w-4 h-4"}),"Buy through Microsoft Marketplace",e.jsx(ha,{className:"w-3.5 h-3.5"})]}),e.jsxs("button",{type:"button",onClick:()=>r(o=>!o),"aria-expanded":c,className:"inline-flex items-center gap-1 text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors",children:[e.jsx(gt,{className:`w-3.5 h-3.5 transition-transform ${c?"rotate-180":""}`}),"How it works"]})]}),c&&e.jsx("ol",{className:"mt-3 space-y-2",children:Bo(t).map((o,x)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm text-gray-600 dark:text-gray-300",children:[e.jsx("span",{className:"mt-0.5 flex-shrink-0 w-5 h-5 rounded-full bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 text-xs font-semibold flex items-center justify-center",children:x+1}),e.jsx("span",{children:o})]},x))}),s&&e.jsx("div",{className:"mt-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/10 border border-amber-200 dark:border-amber-700/40",children:e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-400",children:"This workspace bills through Stripe today. A workspace bills through Stripe or Microsoft, not both, so cancel the Stripe subscription (Manage payment & invoices, above) before linking a Marketplace purchase here."})})]})]})})}function Go({orgId:t}){const{t:a}=Q(),s=_e(),[l,i]=g.useState(!1),c=fo(Qe(d=>{var u;return(u=d.currentOrg)==null?void 0:u.role})),{data:r}=ee({queryKey:["org-external-requests",t],queryFn:()=>B.externalAccessRequests(t),retry:!1}),o=(r==null?void 0:r.enabled)===!0,x=async()=>{if(l||!r||!c)return;i(!0);const d=!o;try{await B.setExternalAccessRequests(t,d),s.invalidateQueries({queryKey:["org-external-requests",t]}),k.success(d?a("orgSettings.extRequests.enabledToast","External access requests enabled. Ask links on opted-in resources are live again."):a("orgSettings.extRequests.disabledToast","External access requests disabled. Every ask link in this organization is now inactive."))}catch(u){k.error(U(u,"update external access requests"))}finally{i(!1)}};return e.jsx("div",{className:"rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-50 dark:bg-amber-900/30 flex items-center justify-center flex-shrink-0",children:e.jsx(Gi,{className:"w-4 h-4 text-amber-600 dar
2k:text-amber-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:a("orgSettings.extRequests.title","External access requests")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:a("orgSettings.extRequests.desc",'The organization-wide half of the ask-link double opt-in. When on, restricted resources whose owners also enabled "Allow access requests by link" can be requested by outsiders, who verify their email first; nothing is granted without your approval. Turning this off instantly deactivates every ask link; per-resource opt-ins are kept for when you turn it back on.')}),!c&&e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1.5",children:a("orgSettings.extRequests.ownerAdminOnly","Only organization owners and admins can change this.")})]}),e.jsx("button",{role:"switch","aria-checked":o,"aria-label":a("orgSettings.extRequests.title","External access requests"),disabled:l||!r||!c,title:c?void 0:a("orgSettings.extRequests.ownerAdminOnly","Only organization owners and admins can change this."),onClick:x,className:`relative inline-flex h-5 w-9 flex-shrink-0 items-center rounded-full transition-colors disabled:opacity-50 ${o?"bg-amber-500":"bg-gray-300 dark:bg-gray-600"}`,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${o?"translate-x-4 rtl:-translate-x-4":"translate-x-0.5 rtl:-translate-x-0.5"}`})})]})})}function $o({onCancel:t,onConfirm:a}){const{t:s}=Q(),[l,i]=g.useState(new Set),[c,r]=g.useState(!1),[o,x]=g.useState(null),d=Vt({open:!0,onClose:()=>{c||t()}}),{data:u,isLoading:h,isError:f,refetch:j,isFetching:b}=ee({queryKey:["directory-impact"],queryFn:()=>Lr.directoryImpact(),staleTime:0}),y=(u==null?void 0:u.projects)??[],N=y.filter(C=>!C.hideFromDirectory&&!l.has(C.id)).length,p=C=>i(G=>{const R=new Set(G);return R.has(C)?R.delete(C):R.add(C),R}),S=async()=>{r(!0),x(null);try{l.size>0&&await Lr.bulkDirectoryVisibility([...l].map(C=>({projectId:C,hideFromDirectory:!0}))),a()}catch(C){x(U(C,s("directoryEnable.action","hide those projects"))),r(!1)}};return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-labelledby":"directory-enable-review-title",className:"bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-lg max-h-[85vh] flex flex-col",children:[e.jsxs("div",{className:"p-5 border-b border-gray-200 dark:border-gray-700",children:[e.jsxs("h3",{id:"directory-enable-review-title",className:"text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2",children:[e.jsx(ke,{className:"w-4 h-4 text-indigo-500 flex-shrink-0"}),s("directoryEnable.title","Turn on the project directory?")]}),e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 mt-2",children:h?s("directoryEnable.counting","Checking what this would show…"):s("directoryEnable.body",{count:N,defaultValue_one:"Members will be able to see the name and owner of {{count}} project in this organization, but nothing inside it.",defaultValue_other:"Members will be able to see the names and owners of {{count}} projects in this organization, but nothing inside them."})}),!h&&y.length>0&&e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-2",children:s("directoryEnable.hint","If any name is sensitive on its own, hide it here first. You can change this later in the project settings.")})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-5",children:f?e.jsxs("div",{className:"text-center py-6",children:[e.jsx(je,{className:"w-7 h-7 mx-auto mb-2 text-amber-500"}),e.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-200 mb-2",children:s("directoryEnable.loadFailed","Could not check which projects this would show.")}),e.jsx("button",{type:"button",onClick:()=>j(),disabled:b,className:"text-sm font-semibold text-indigo-600 dark:text-indigo-400 hover:underline disabled:opacity-50",children:s("common.retry","Retry")})]}):h?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(C=>e.jsx("div",{className:"h-10 bg-gray-100 dark:bg-gray-700 rounded-lg animate-pulse"},C))}):e.jsx("ul",{className:"divide-y divide-gray-100 dark:divide-gray-700",children:y.map(C=>{const G=C.hideFromDirectory||l.has(C.id);return e.jsxs("li",{className:"flex items-center gap-3 py-2",children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:`block text-sm truncate ${G?"text-gray-400 dark:text-gray-500 line-through":"text-gray-800 dark:text-gray-200"}`,children:C.name}),C.owner&&e.jsx("span",{className:"block text-xs text-gray-500 dark:text-gray-400 truncate",children:C.owner.name})]}),C.hideFromDirectory?e.jsxs("span",{className:"text-xs text-gray-400 dark:text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(dr,{className:"w-3.5 h-3.5"}),s("directoryEnable.alreadyHidden","Already hidden")]}):e.jsx("button",{type:"button",onClick:()=>p(C.id),className:`text-xs font-medium flex items-center gap-1 flex-shrink-0 px-2 py-1 rounded-md border transition-colors ${l.has(C.id)?"border-indigo-500 text-indigo-600 dark:text-indigo-400 bg-indigo-50 dark:bg-indigo-900/20":"border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700/40"}`,children:l.has(C.id)?e.jsxs(e.Fragment,{children:[e.jsx(dr,{className:"w-3.5 h-3.5"}),s("directoryEnable.willHide","Will hide")]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"w-3.5 h-3.5"}),s("directoryEnable.hideIt","Hide")]})})]},C.id)})})}),e.jsxs("div",{className:"p-5 border-t border-gray-200 dark:border-gray-700",children:[o&&e.jsx("p",{className:"text-sm text-rose-600 dar
2k:text-rose-400 mb-3",role:"alert",children:o}),e.jsxs("div",{className:"flex items-center justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:t,disabled:c,className:"btn-secondary text-sm",children:s("common.cancel","Cancel")}),e.jsxs("button",{type:"button",onClick:S,disabled:c||h||f,className:"btn-primary text-sm inline-flex items-center gap-2 disabled:opacity-60",children:[c&&e.jsx(At,{className:"w-4 h-4 animate-spin"}),l.size>0?s("directoryEnable.confirmWithHides",{count:l.size,defaultValue_one:"Hide {{count}} and turn it on",defaultValue_other:"Hide {{count}} and turn it on"}):s("directoryEnable.confirm","Turn it on")]})]})]})]})})}const tn=["MANAGER","MEMBER","CONTRIBUTOR","VIEWER"];function an({title:t,hint:a,open:s,onToggle:l,children:i}){return e.jsxs("section",{className:"border border-gray-200 dark:border-gray-700 rounded-xl bg-white dark:bg-gray-800/40",children:[e.jsxs("button",{type:"button",onClick:l,"aria-expanded":s,className:"w-full flex items-start gap-2.5 px-4 py-3 text-start group",children:[e.jsx(gt,{className:`w-4 h-4 mt-0.5 flex-shrink-0 text-gray-400 transition-transform ${s?"rotate-180":""}`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"font-medium text-gray-900 dark:text-white group-hover:text-indigo-600 dark:group-hover:text-indigo-400 transition-colors",children:t}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:a})]})]}),s&&e.jsx("div",{className:"px-4 pb-4 space-y-3",children:i})]})}const sn=["ADMIN","MANAGER","MEMBER","GUEST"],Vs=["#6366f1","#8b5cf6","#ec4899","#ef4444","#f97316","#eab308","#22c55e","#06b6d4"];function Ho(t){const a={};for(const s of t)a[s.group]||(a[s.group]=[]),a[s.group].push(s);return a}const Wo=new Map(or.map(t=>[t.key,t.label]));function rn(t){return Wo.get(t)??t}function nn(t,a){return t==="org.project.discover"&&a==="GUEST"}function ps(t,a,s){switch(a){case"org.project.create":return t("permMatrix.perm.orgProjectCreate.label","Create new projects");case"org.project.view.all":return t("permMatrix.perm.orgProjectViewAll.label","View all org projects");case"org.project.discover":return t("permMatrix.perm.orgProjectDiscover.label","Browse all project names");case"org.portfolio.manage":return t("permMatrix.perm.orgPortfolioManage.label","Create & manage portfolios");case"org.scenario.manage":return t("permMatrix.perm.orgScenarioManage.label","Create & manage scenario planning");case"org.ratecard.manage":return t("permMatrix.perm.orgRatecardManage.label","Manage rate cards (billing rates)");case"org.governance.review":return t("permMatrix.perm.orgGovernanceReview.label","Conduct gate reviews & view scoring data");case"org.governance.manage":return t("permMatrix.perm.orgGovernanceManage.label","Manage gate reviewers & criteria");case"org.member.invite":return t("permMatrix.perm.orgMemberInvite.label","Invite & manage org invitations");case"org.formconfig.manage":return t("permMatrix.perm.orgFormconfigManage.label","Configure org-wide form fields");case"org.webhook.manage":return t("permMatrix.perm.orgWebhookManage.label","Manage outgoing webhooks");case"org.team.manage":return t("permMatrix.perm.orgTeamManage.label","Manage teams");case"org.calendar.manage":return t("permMatrix.perm.orgCalendarManage.label","Manage working c
2alendars");case"org.integration.manage":return t("permMatrix.perm.orgIntegrationManage.label","Manage native integrations");case"org.intake.manage":return t("permMatrix.perm.orgIntakeManage.label","Manage intake forms");case"org.timesheet.enforcement.manage":return t("permMatrix.perm.orgTimesheetEnforcementManage.label","Manage timesheet enforcement");case"org.compliance.manage":return t("permMatrix.perm.orgComplianceManage.label","Manage compliance evidence + exceptions");case"org.library.view":return t("permMatrix.perm.orgLibraryView.label","View organization libraries");case"org.library.contribute":return t("permMatrix.perm.orgLibraryContribute.label","Add / edit organization documents");case"org.library.manage":return t("permMatrix.perm.orgLibraryManage.label","Create & manage organization libraries");case"org.mcp.destructive.manage":return t("permMatrix.perm.orgMcpDestructiveManage.label","Manage agent destructive-op policy");case"org.playground.publish":return t("permMatrix.perm.orgPlaygroundPublish.label","Publish Maker apps to a live URL");case"org.playground.secrets.manage":return t("permMatrix.perm.orgPlaygroundSecretsManage.label","Manage Maker app secrets");case"org.playground.secrets.bind":return t("permMatrix.perm.orgPlaygroundSecretsBind.label","Bind payment credentials to Maker apps");case"org.agent.connect":return t("permMatrix.perm.orgAgentConnect.label","Connect & use external AI agents");case"org.navigation.manage":return t("permMatrix.perm.orgNavigationManage.label","Customize sidebar navigation");case"task.create":return t("permMatrix.perm.taskCreate.label","Create tasks");case"task.edit.any":return t("permMatrix.perm.taskEditAny.label","Edit any task");case"task.edit.own":return t("permMatrix.perm.taskEditOwn.label","Edit own assigned tasks");case"task.delete":return t("permMatrix.perm.taskDelete.label","Delete tasks");case"task.assign":return t("permMatrix.perm.taskAssign.label","Assign tasks to others");case"task.status.change":return t("permMatrix.perm.taskStatusChange.label","Change task status");case"project.edit":return t("permMatrix.perm.projectEdit.label","Edit project settings");case"project.members.manage":return t("permMatrix.perm.projectMembersManage.label","Manage project members");case"project.delete":return t("permMatrix.perm.projectDelete.label","Delete project");case"automation.manage":return t("permMatrix.perm.automationManage.label","Manage automations & workflows");case"milestone.create":return t("permMatrix.perm.milestoneCreate.label","Create milestones");case"template.create":return t("permMatrix.perm.templateCreate.label","Save project as template");case"budget.read":return t("permMatrix.perm.budgetRead.label","View project budget");case"sprint.manage":return t("permMatrix.perm.sprintManage.label","Manage sprints & backlog");case"dependency.manage":return t("permMatrix.perm.dependencyManage.label","Manage task dependencies");default:return s}}function on(t,a,s){switch(a){case"org.project.create":return t("permMatrix.perm.orgProjectCreate.desc","Allows creating new projects within the organization. The creator automatically becomes project-OWNER and gains full control of that project. Default is open (any Member+) to match modern PM-tool norms, turn off for stricter PMO governance where projects must originate from the proposal pipeline.");case"org.project.view.all":return t("permMatrix.perm.orgProjectViewAll.desc","See every project in the organization. Without this, users only see projects they own or are members of.");case"org.project.discover":return t("permMatrix.perm.orgProjectDiscover.desc","See that a project exists and who owns it, without being able to open it. Shows the name and the owner only, never the description, status, progress, dates, budget, members or anything inside. Lets someone ask for access to a project they would otherwise have no way to find. Guests never get this, whatever this matrix says. A project owner can hide an individual project from the directory in its settings.");case"org.portfolio.manage":return t("permMatrix.perm.orgPortfolioManage.desc","Create portfolios, add/remove projects, and view aggregated health and budget data across projects.");case"org.scenario.manage":return t("permMatrix.perm.orgScenarioManage.desc","Run what-if scenarios to model the impact of adding, remov
2ing, or rescheduling projects in a portfolio.");case"org.ratecard.manage":return t("permMatrix.perm.orgRatecardManage.desc","Set hourly billing rates at the org, role, or individual level for cost tracking and invoicing.");case"org.governance.review":return t("permMatrix.perm.orgGovernanceReview.desc","Submit approval/rejection decisions at governance gates and view weighted scoring criteria for proposals.");case"org.governance.manage":return t("permMatrix.perm.orgGovernanceManage.desc","Add or remove designated gate reviewers, configure evaluation criteria per gate, and manage governance settings.");case"org.member.invite":return t("permMatrix.perm.orgMemberInvite.desc","Send invitations to add new members to the organization, list pending invitations, revoke unaccepted invitations, and resend expired ones.");case"org.formconfig.manage":return t("permMatrix.perm.orgFormconfigManage.desc","Customize which fields appear on the project / task / proposal / change-request creation forms, and which are required.");case"org.webhook.manage":return t("permMatrix.perm.orgWebhookManage.desc","Register, edit, test, or delete webhooks that fire on org events (task.created, project.updated, etc.). View delivery history.");case"org.team.manage":return t("permMatrix.perm.orgTeamManage.desc","Create / edit / delete teams and add or remove team members. Teams are used for workload tracking and group-based invitations.");case"org.calendar.manage":return t("permMatrix.perm.orgCalendarManage.desc","Define org-wide working calendars (work days, hours per day, holidays, exceptions) used by Gantt scheduling and resource planning.");case"org.integration.manage":return t("permMatrix.perm.orgIntegrationManage.desc","Connect or disconnect Slack / Teams / GitHub / Jira integrations and edit their config (webhook URLs, tokens, project keys).");case"org.intake.manage":return t("permMatrix.perm.orgIntakeManage.desc","Create, edit, delete intake forms (public submission portals). View submissions and convert them to projects or proposals.");case"org.timesheet.enforcement.manage":return t("permMatrix.perm.orgTimesheetEnforcementManage.desc","Enable/disable timesheet compliance enforcement, set the deadline + exempt roles, and configure reminder cadence. Hard prerequisite: at least 1 rate card must be configured. Defaults to Admin+ because enforcement affects b
2illing-adjacent compliance posture.");case"org.compliance.manage":return t("permMatrix.perm.orgComplianceManage.desc","Grant or revoke compliance exceptions (medical leave, secondment) and generate evidence exports (PDF/CSV for SOX/HIPAA auditors). Defaults to Owner+ because these are forensic / financial-grade operations.");case"org.library.view":return t("permMatrix.perm.orgLibraryView.desc","See and read the tenant-level Workspace: org-wide document libraries (folders) plus their documents and lists. Default Member+, org documents are shared by default.");case"org.library.contribute":return t("permMatrix.perm.orgLibraryContribute.desc","Upload, create, and edit documents and their metadata inside org-level libraries. Default Member+.");case"org.library.manage":return t("permMatrix.perm.orgLibraryManage.desc","Create, rename, and delete org-level libraries (and manage their sharing). Default Manager+.");case"org.mcp.destructive.manage":return t("permMatrix.perm.orgMcpDestructiveManage.descDefaultOn","Edit the per-org list that decides which destructive operations (e.g. delete task, delete project) AI agents may run. Until an admin saves a choice, the recoverable deletes are allowed. Default Admin+ (matrix-configurable to Owner-only). This gates editing the policy, not the destructive ops themselves.");case"org.playground.publish":return t("permMatrix.perm.orgPlaygroundPublish.desc","Publish, unpublish, or roll back an Onplana Maker app to a live <slug>.onplana.app URL. Building, the dev preview, and code export stay all-plans and lower-role; pushing an app to a PUBLIC URL is the org gate. Default Admin+.");case"org.playground.secrets.manage":return t("permMatrix.perm.orgPlaygroundSecretsManage.desc","Bind, list, or remove per-app secrets and environment variables for an Onplana Maker app (e.g. a Stripe key). The secret value is held in a private Key Vault, never in app code. Default Admin+ (matrix-configurable).");case"org.playground.secrets.bind":return t("permMatrix.perm.orgPlaygroundSecretsBind.desc","Bind or replace the Stripe webhook signing secret that lets a published Maker app take payments (the managed Stripe-unlock). Split from general secrets management so an org can grant env-var management without payment-credential binding. Binding is always a human typing into a form; agents can never do it. Default Admin+.");case"org.agent.connect":return t("permMatrix.perm.orgAgentConnect.desc","Allow this role to connect and use external AI agents (Claude Code, Claude Desktop, Cursor, Codex, and other MCP clients). Default Member+ so teams can self-serve. Tighten to Admin+ for stricter governance. Works alongside the per-user / per-team allow-deny lists in Settings, AI and Storage; a caller must clear both.");case"org.navigation.manage":return t("permMatrix.perm.orgNavigationManage.desc","Edit the organization sidebar: rename default items, hide and re-add items, reorder them, and add custom links. This is a display overlay only, hiding an item never restricts access to its page. Project-level navigation is editable by project Owners/Managers instead. Default Admin+.");case"task.create":return t("permMatrix.perm.taskCreate.desc","Create new tasks and subtasks within the project, including setting title, description, priority, and dates.");case"task.edit.any":return t("permMatrix.perm.taskEditAny.desc","Modify any task in the project regardless of who created it or who it is assigned to.");case"task.edit.own":return t("permMatrix.perm.taskEditOwn.desc","Edit only tasks assigned to you. Cannot modify tasks owned by or assigned to other team members.");case"task.delete":return t("permMatrix.perm.taskDelete.desc","Permanently remove tasks from the project. Deleted tasks are moved to the recycle bin for 30 days.");case"task.assign":return t("permMatrix.perm.taskAssign.desc","Change the assignee on tasks. Without this, users can only assign tasks to themselves.");case"task.status.change":return t("permMatrix.perm.taskStatusChange.desc","Move tasks between statuses (To Do, In Progress, Review, Done, Blocked). Required for Kanban drag-and-drop.");case"project.edit":return t("permMatrix.perm.projectEdit.desc","Modify project name, description, status, dates, budget, and other project-level settings.");case"project.members.manage":return t("permMatrix.perm.projectMembersManage.desc","Invite or remove project members and change their project roles (Project Manager, Project Member, Project Contributor, Project Viewer).");case"project.delete":return t("permMatrix.perm.projectDelete.desc","Permanently delete the project and all its tasks, sprints, and documents. This action cannot be undone.");case"automation.manage":return t("permMatrix.perm.automationManage.desc","Create, edit, and delete automation rules and multi-step workflows that run on project events.");case"milestone.create":return t("permMatrix.perm.milestoneCreate.desc","Add milestone markers to the project timeline. Milestones appear as diamond markers on the Gantt chart.");case"template.create":return t("permMatrix.perm.templateCreate.desc","Snapshot the current project structure (tasks, custom fields, settings) as a reusable template for new projects.");case"budget.read":return t("permMatrix.perm.budgetRead.desc","See the project budget, actual spend, cost variance, and financial reports in Finance.");case"sprint.manage":return t("permMatrix.perm.sprintManage.desc","Create, start, and complete sprints. Move tasks between the backlog and active sprints.");case"dependency.manage":return t("permMatrix.perm.dependencyManage.desc","Create and remove dependency links between tasks (Finish-to-Start, Start-to-Start, etc.) that affect scheduling.");default:return s}}function Vo(t,a){switch(a){case"Organization Actions":return t("permMatrix.group.organizationActions","Organization Actions");case"Governance":return t("permMatrix.group.governance","Governance");case"Tasks":return t("permMatrix.group.tasks","Tasks");case"Project Management":return t("permMatrix.group.projectManagement","Project Management");case"Sprints & Planning":return t("permMatrix.group.sprintsPlanning","Sprints & Planning");default:return a}}function zs(t,a){return Xa(t,a)}function ln(t,a){switch(a){case"OWNER":return t("permMatrix.orgRole.owner.desc","Immutable. Full access to everything. Only one per org, the founding member. Cannot be restricted.");case"ADMIN":return t("permMatrix.orgRole.admin.desc","Full org administration except transferring ownership. Manages billing, security, member roles, and feature settings.");case"MANAGER":return t("permMatrix.orgRole.manager.desc","Cross-project leadership. Creates/manages projects, portfolios, scenarios, and rate cards. Conducts gate reviews. Good fit for PMO leads and team leads.");
2case"MEMBER":return t("permMatrix.orgRole.member.desc","Individual contributor. Sees only projects they own or are invited to. Can be promoted to a higher role on specific projects.");case"GUEST":return t("permMatrix.orgRole.guest.desc","External collaborator (client, contractor, reviewer). Project-scoped only, cannot see org-wide pages like Portfolio, Goals, or Reports.");default:return gi[a]??""}}function dn(t,a){switch(a){case"OWNER":return t("permMatrix.projectRole.owner.desc","The project's owner (project.ownerId). Full control over this project. Exactly one per project.");case"MANAGER":return t("permMatrix.projectRole.manager.desc","Project lead. Edits/deletes any task, manages members, configures automations, manages sprints, dependencies, milestones, and budget.");case"MEMBER":return t("permMatrix.projectRole.member.desc","Full individual contributor. Creates tasks, edits their own tasks (not others'), tracks time, comments.");case"CONTRIBUTOR":return t("permMatrix.projectRole.contributor.desc","Light participant. Creates tasks and edits their own, cannot delete or reassign others' work.");case"VIEWER":return t("permMatrix.projectRole.viewer.desc","Read-only access. Sees project data in reports and dashboards but cannot create, edit, or delete anything.");default:return mi[a]??""}}function hs(t,a,s){switch(a){case"open":return t("permMatrix.preset.open.label","Open");case"standard":return t("permMatrix.preset.standard.label","Standard (recommended)");case"strict":return t("permMatrix.preset.strict.label","Strict");case"pmo":return t("permMatrix.preset.pmo.label","Formal PMO");default:return s}}function zo(t,a,s){switch(a){case"open":return t("permMatrix.preset.open.blurb","Any member can do almost anything. Modern PM-tool defaults.");case"standard":return t("permMatrix.preset.standard.blurb","Members run their own work. Portfolio Managers oversee teams. Admins govern.");case"strict":return t("permMatrix.preset.strict.blurb","Members consume the platform; Portfolio Managers + Admins build it.");case"pmo":return t("permMatrix.preset.pmo.blurb","Projects originate from the proposal pipeline. Every config change is centralised.");default:return s}}function Qo(t,a,s){switch(a){case"open":return t("permMatrix.preset.open.recommendedFor","Flat teams, startups, design studios, speed over governance.");case"standard":return t("permMatrix.preset.standard.recommendedFor","Most orgs (10-500 people). Balanced delegation.");case"strict":return t("permMatrix.preset.strict.recommendedFor","Enterprise rollouts that need centralised setup but per-portfolio delivery.");case"pmo":return t("permMatrix.preset.pmo.recommendedFor","PMOs migrating from MS Project Online or running gated portfolios.");default:return s}}function Yo({orgId:t,canEdit:a,allowCustomRoles:s=!1,planLockedForCustomization:l=!1,onUpgradeClick:i}){var xt;const{currentOrg:c}=Qe(),r=a&&!l,{t:o}=Q(),x=_e(),{data:d,isLoading:u,isError:h}=ee({queryKey:["org-permissions",t],queryFn:()=>Or.get(t),staleTime:6e4}),[f,j]=g.useState(ua),[b,y]=g.useState(!1),[N,p]=g.useState([]),[S,C]=g.useState(!1),[G,R]=g.useState(""),[Z,te]=g.useState(Vs[0]),A=g.useRef(null),[P,z]=g.useState(null),[M,J]=g.useState(""),[ae,re]=g.useState(null),H=uo(f),ge=ae?ms.find(w=>w.key===ae)??null:null,_=g.useMemo(()=>ge?po(f,Jr(ge,f)):[],[ge,f]),se=ge?hs(o,ge.key,ge.label):"",[ne,Ye]=g.useState(!1),[T,ie]=g.useState(!0),[Le,we]=g.useState(!0);g.useEffect(()=>{d&&(j(d.policy),p(d.customRoles??[]))},[d]),g.useEffect(()=>{var w;S&&((w=A.current)==null||w.focus())},[S]);const Ue=JSON.stringify(f)!==JSON.stringify(d==null?void 0:d.policy)||JSON.stringify(N)!==JSON.stringify((d==null?void 0:d.customRoles)??[]),Je=$({mutationFn:()=>Or.update(t,{policy:f,customRoles:N}),onSuccess:w=>{x.setQueryData(["org-permissions",t],w),k.success(o("permMatrix.toast.saved","Permission policy saved"))},onError:w=>k.error(U(w,"save permission policy"))}),Pe=Ir(f)&&!Ir((d==null?void 0:d.policy)??null),mt=()=>{j({...ua}),p([]),k(o("permMatrix.toast.reset","Reset to default permissions"),{icon:"↩"})},F=()=>{d&&(j(d.policy),p(d.customRoles??[]))},ue=(w,X)=>{!r||X==="OWNER"||nn(w,X)||j(pe=>{var le;return{...pe,[w]:{...pe[w],[X]:!((le=pe[w])!=null&&le[X]),OWNER:!0}}})},me=()=>{const w=G.trim();if(!w)return;const X=w.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");
2if(!X){k.error(o("permMatrix.toast.invalidRoleName","Invalid role name"));return}const pe=di.map(Me=>Me.toLowerCase());if(N.some(Me=>Me.key===X)||pe.includes(X)){k.error(o("permMatrix.toast.roleExists","A role with this name already exists"));return}const le={key:X,label:w,color:Z};p(Me=>[...Me,le]),j(Me=>{const Te={};for(const ve of Object.keys(ua))Te[ve]={...Me[ve]??ua[ve],[X]:!1,OWNER:!0};return Te}),R(""),te(Vs[0]),C(!1),k.success(o("permMatrix.toast.roleAdded",'Custom role "{{name}}" added, set permissions below, then Save',{name:w}))},O=w=>{const X=N.find(pe=>pe.key===w);p(pe=>pe.filter(le=>le.key!==w)),j(pe=>{const le={};for(const Me of Object.keys(pe)){const{[w]:Te,...ve}=pe[Me];le[Me]=ve}return le}),X&&k(o("permMatrix.toast.roleRemoved",'Removed custom role "{{name}}"',{name:X.label}),{icon:"🗑"})},Ce=(w,X)=>{z(w),J(X)},Re=w=>{const X=M.trim();X&&p(pe=>pe.map(le=>le.key===w?{...le,label:X}:le)),z(null)},He=[...tn,...N.map(w=>w.key)],Et=w=>{var X;return ci[w]?qr(o,w):((X=N.find(pe=>pe.key===w))==null?void 0:X.label)??w},We=or.filter(w=>w.isOrgLevel),Oe=or.filter(w=>!w.isOrgLevel),jt=Ho(Oe);return u?e.jsxs("div",{className:"flex items-center justify-center py-16 text-gray-400 dark:text-gray-500",children:[e.jsx("div",{className:"w-5 h-5 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin me-2"}),o("permMatrix.loading","Loading permissions…")]}):e.jsxs("div",{className:"space-y-3",children:[h&&e.jsxs("div",{className:"flex items-start gap-2.5 px-4 py-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg text-sm text-amber-800 dark:text-amber-300",children:[e.jsx(je,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{className:"flex-1",children:o("permMatrix.loadError","Couldn't load this organization's saved permission policy. Showing platform defaults, which may not match your actual configuration.")})]}),l&&e.jsxs("div",{className:"flex items-start gap-2.5 px-4 py-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg text-sm text-amber-800 dark:text-amber-300",children:[e.jsx(ke,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsxs("span",{className:"flex-1",children:[e.jsx("strong",{children:o("permMatrix.viewingDefaultsLead","Viewing defaults.")})," ",o("permMatrix.viewingDefaultsBody","Every organization uses this permission matrix, roles you assign when inviting members behave exactly as shown below. To customize which role can do what, upgrade to the Professional plan or above (custom roles require Business or above).")]}),i&&e.jsx("button",{onClick:i,className:"text-xs font-semibold text-amber-800 dark:text-amber-300 underline hover:no-underline whitespace-nowrap",children:o("permMatrix.upgrade","Upgrade →")})]}),e.jsxs("div",{className:"flex items-start gap-2.5 px-4 py-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg text-sm text-blue-700 dark:text-blue-300",children:[e.jsx(kr,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:l?o("permMatrix.infoViewOnly","Columns are roles you can assign when inviting members. Hover a role header for a full description of what that role can do."):e.jsxs(e.Fragment,{children:[o("permMatrix.infoEditable","Changes apply to all projects in this organization. You can define custom roles and assign them when inviting project members."),!r&&` ${o("permMatrix.infoOwnerOnly","Only the Org Owner can edit the permission matrix, this prevents self-granting permissions.")}`]})})]}),Ue&&r&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg text-sm text-amber-700 dark:text-amber-400",children:[e.jsx(je,{className:"w-4 h-4 flex-shrink-0"}),o("permMatrix.unsavedChanges","You have unsaved changes")]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("h3",{className:"font-medium text-gray-900 dark:text-white",children:o("permMatrix.title","Permission Matrix")}),r&&e.jsxs("div",{className:"flex items-center gap-2",children:[s?e.jsxs("button",{onClick:()=>{C(!0),we(!0)},disabled:S,className:`flex items-center gap-1.5 text-sm text-indigo-600 dark:text-indigo-400
3                           hover:text-indigo-700 dark:hover:text-indigo-300
4                           px-3 py-1.5 rounded-lg border border-indigo-200 dark:border-indigo-700
5                           hover:border-indigo-300 dark:hover:border-indigo-600
6                           disabled:opacity-50 transition-colors`,children:[e.jsx(st,{className:"w-3.5 h-3.5"})," ",o("permMatrix.addCustomRole","Add Custom Role")]}):e.jsxs("button",{onClick:i,className:`flex items-center gap-1.5 text-sm text-amber-600 dar
6k:text-amber-400
7                           hover:text-amber-700 dark:hover:text-amber-300
8                           px-3 py-1.5 rounded-lg border border-amber-200 dark:border-amber-700
9                           hover:border-amber-300 dark:hover:border-amber-600 transition-colors`,children:[e.jsx(ke,{className:"w-3.5 h-3.5"})," ",o("permMatrix.customRolesLocked","Custom Roles (Business+)")]}),e.jsxs("button",{onClick:mt,className:`flex items-center gap-1.5 text-sm text-gray-500 dark:text-gray-400
10                         hover:text-gray-700 dark:hover:text-gray-200
11                         px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700
12                         hover:border-gray-300 dark:hover:border-gray-600 transition-colors`,children:[e.jsx($i,{className:"w-3.5 h-3.5"})," ",o("permMatrix.resetToDefaults","Reset to Defaults")]})]})]}),r&&e.jsxs("div",{className:"rounded-lg border border-gray-200 dark:border-gray-700 bg-gradient-to-br from-indigo-50/40 via-transparent to-violet-50/40 dark:from-indigo-900/10 dark:to-violet-900/10",children:[e.jsxs("button",{type:"button",onClick:()=>Ye(w=>!w),className:"w-full flex items-center gap-2.5 px-4 py-2.5 text-start","aria-expanded":ne,children:[e.jsx(va,{className:"w-4 h-4 text-indigo-500 flex-shrink-0"}),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-sm font-semibold text-gray-900 dark:text-white",children:o("permMatrix.presetsTitle","Permission posture presets")}),H&&e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide text-emerald-700 dark:text-emerald-400 bg-emerald-100 dark:bg-emerald-900/40 px-1.5 py-0.5 rounded",children:o("permMatrix.presetActiveChip","Active: {{preset}}",{preset:hs(o,H,((xt=ms.find(w=>w.key===H))==null?void 0:xt.label)??H)})}),!H&&e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded",children:o("permMatrix.presetCustomChip","Custom")})]}),!ne&&e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:o("permMatrix.presetsCollapsedHint","Click to switch posture (Open / Standard / Strict / Formal PMO).")})]}),e.jsx(gt,{className:`w-4 h-4 text-gray-400 dark:text-gray-500 flex-shrink-0 transition-transform ${ne?"rotate-180":""}`})]}),ne&&e.jsxs("div",{className:"px-4 pb-3 -mt-1",children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:o("permMatrix.presetsIntro","Pick a posture to stamp a coherent set of toggles below. You can still hand-tune individual permissions before saving.")}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-2",children:ms.map(w=>{const X=H===w.key,pe=ae===w.key;return e.jsxs("button",{onClick:()=>re(pe?null:w.key),className:`text-start p-3 rounded-lg border transition-all
13                    ${pe?"border-indigo-500 bg-indigo-50 dark:bg-indigo-900/30 ring-2 ring-indigo-300 dark:ring-indigo-600":X?"border-emerald-300 dark:border-emerald-700 bg-emerald-50/60 dark:bg-emerald-900/15":"border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 hover:border-indigo-300 dark:hover:border-indigo-600 hover:bg-indigo-50/50 dark:hover:bg-indigo-900/15"}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx("span",{className:"font-semibold text-sm text-gray-900 dark:text-white",children:hs(o,w.key,w.label)}),X&&!pe&&e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide text-emerald-700 dark:text-emerald-400 bg-emerald-100 dark:bg-emerald-900/40 px-1.5 py-0.5 rounded",children:o("permMatrix.presetActiveBadge","active")})]}),e.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 leading-snug",children:zo(o,w.key,w.blurb)}),e.jsx("p",{className:"text-[11px] text-gray-400 dark:text-gray-500 mt-1.5 italic",children:Qo(o,w.key,w.recommendedFor)})]},w.key)})}),ae&&e.jsxs("div",{className:"mt-3 px-3 py-2.5 bg-indigo-100 dark:bg-indigo-900/30 rounded-lg text-xs text-indigo-900 dark:text-indigo-200",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(je,{className:"w-3.5 h-3.5 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"flex-1",children:_.length===0?o("permMatrix.presetNoChanges","Your policy already matches {{preset}}. Applying it changes nothing.",{preset:se}
13):o("permMatrix.presetDiffIntro",{count:_.length,preset:se,defaultValue_one:"Applying {{preset}} changes {{count}} org-level permission. Project-level rows and custom roles are left as they are, and nothing is saved until you click Save.",defaultValue_other:"Applying {{preset}} changes {{count}} org-level permissions. Project-level rows and custom roles are left as they are, and nothing is saved until you click Save."})}),e.jsx("button",{onClick:()=>{Ja("preset_diff_reviewed",{preset:ae,changes:_.length,outcome:"cancelled"}),re(null)},className:"text-xs px-2 py-1 rounded text-indigo-700 dark:text-indigo-300 hover:bg-indigo-200 dark:hover:bg-indigo-800/40",children:o("common.cancel","Cancel")}),e.jsx("button",{onClick:()=>{const w=ms.find(X=>X.key===ae);w&&(Ja("preset_diff_reviewed",{preset:w.key,changes:_.length,outcome:"applied"}),j(Jr(w,f)),k.success(o("permMatrix.toast.presetApplied",'Applied "{{preset}}" preset, review and save',{preset:hs(o,w.key,w.label)}))),re(null)},className:"btn-primary text-xs px-2.5 py-1",children:o("permMatrix.applyPreset","Apply preset")})]}),_.length>0&&e.jsx("ul",{"data-testid":"preset-diff",className:"mt-2.5 ms-5 space-y-0.5",children:_.map(w=>e.jsxs("li",{className:"flex items-baseline gap-2 leading-relaxed",children:[e.jsx("span",{className:`w-3 flex-shrink-0 text-center font-bold ${w.after?"text-emerald-600 dark:text-emerald-400":"text-rose-500 dark:text-rose-400"}`,"aria-hidden":"true",children:w.after?"+":"−"}),e.jsx("span",{className:"min-w-0",children:w.after?o("permMatrix.presetDiffGrant","{{role}} gains {{permission}}",{role:Xa(o,w.role),permission:ps(o,w.key,rn(w.key))}):o("permMatrix.presetDiffRevoke","{{role}} loses {{permission}}",{role:Xa(o,w.role),permission:ps(o,w.key,rn(w.key))})})]},`${w.key}-${w.role}`))})]})]})]}),e.jsx(Go,{orgId:t}),e.jsxs(an,{open:T,onToggle:()=>ie(w=>!w),title:o("permMatrix.orgActions","Organization-Level Actions"),hint:o("permMatrix.orgActionsHint","Controls what org members can do across the entire organization. Columns are org-membership roles."),children:[e.jsx("div",{className:"overflow-auto rounded-lg border border-gray-200 dark:border-gray-700 max-h-[55vh]",children:e.jsxs("table",{className:"w-full text-sm",style:{minWidth:"500px"},children:[e.jsx("thead",{className:"sticky top-0 z-20",children:e.jsxs("tr",{className:"border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/95 backdrop-blur",children:[e.jsx("th",{className:`text-start px-4 py-2 font-medium text-gray-600 dark:text-gray-400 w-64
14                               sticky start-0 z-30 bg-gray-50 dark:bg-gray-800/95 shadow-[1px_0_0_0_#e5e7eb] dark:shadow-[1px_0_0_0_#374151]`,children:o("permMatrix.permissionColumn","Permission")}),e.jsx("th",{className:"text-center px-3 py-2 font-medium text-gray-600 dark:text-gray-400 w-28",children:e.jsxs("div",{className:"flex flex-col items-center gap-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[zs(o,"OWNER"),e.jsx(pa,{text:ln(o,"OWNER"),size:"xs"})]}),e.jsx(ke,{className:"w-3 h-3 text-gray-400 dark:text-gray-500"})]})}),sn.map(w=>e.jsx("th",{className:"text-center px-3 py-2 font-medium text-gray-600 dark:text-gray-400 w-28",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[zs(o,w),e.jsx(pa,{text:ln(o,w),size:"xs"})]})},w))]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700/60",children:We.map(({key:w,label:X,description:pe})=>{const le=ps(o,w,X),Me=on(o,w,pe);return e.jsxs("tr",{className:"bg-white dark:bg-gray-800/50 hover:bg-gray-50/40 dark:hover:bg-gray-800/80 transition-colors",children:[e.jsx("td",{className:`px-4 py-1.5 text-gray-700 dark:text-gray-300
15                                 sticky start-0 z-10 bg-white dark:bg-gray-800
16                                 shadow-[1px_0_0_0_#e5e7eb] dark:shadow-[1px_0_0_0_#374151]`,children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[le,Me&&e.jsx(pa,{text:Me,size:"xs"})]})}),e.jsx("td",{className:"text-center px-3 py-1.5",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("div",{className:"w-5 h-5 rounded bg-indigo-100 dark:bg-indigo-900/40 flex items-center justify-center",children:e.jsx(ke,{className:"w-3 h-3 text-indigo-500 dark:text-indigo-400"})})})}),sn.map(Te=>{var fe,Fe;const ve=((fe=f[w])==null?void 0:fe[Te])??((Fe=ua[w])==null?void 0:Fe[Te])??!1,Ve=zs(o,Te);if(nn(w,Te))return e.jsx("td",{className:"text-center px-3 py-1.5",children:e.jsx("span",{className:"text-[11px] font-medium text-gray-400 dark:text-gray-500",title:o("permMatrix.fixedDeniedTitle","Guests never get this. They are told at invite time that they see only the project they were invited to."),children:o("permMatrix.fixedDenied","Never")})},Te);const Ie=["w-5 h-5 rounded border-2 flex items-center justify-center transition-all",r?"cursor-pointer hover:scale-110":"cursor-not-allowed opacity-70",ve?"bg-indigo-500 dark:bg-indigo-600 border-indigo-500 dark:border-indigo-600":"bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600"].join(" ");return e.jsx("td",{className:"text-center px-3 py-1.5",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("button",{onClick:()=>ue(w,Te),disabled:!r,className:Ie,title:r?ve?o("permMatrix.toggleRevokeTitle",'Revoke "{{permission}}" for {{role}}',{permission:le,role:Ve}):o("permMatrix.toggleGrantTitle",'Grant "{{permission}}" for {{role}}',{permission:le,role:Ve}):void 0,"aria-label":ve?o("permMatrix.toggleAllowedAria","{{permission}}, {{role}}: allowed",{permission:le,role:Ve}):o("permMatrix.toggleDeniedAria","{{permission}}, {{role}}
16: denied",{permission:le,role:Ve}),children:ve&&e.jsx("svg",{className:"w-3 h-3 text-white",viewBox:"0 0 12 12",fill:"none",children:e.jsx("path",{d:"M2 6l3 3 5-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})})},Te)})]},w)})})]})}),e.jsx(bo,{policy:f,plan:(c==null?void 0:c.plan)??null,surface:"matrix",compact:!0})]}),e.jsxs(an,{open:Le,onToggle:()=>we(w=>!w),title:o("permMatrix.projectPerms","Project-Level Permissions"),hint:o("permMatrix.projectPermsHint","Controls what each project role can do within a specific project. Applies to all projects in the org."),children:[r&&!s&&e.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg text-sm text-amber-700 dark:text-amber-300",children:[e.jsx(ke,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1",children:o("permMatrix.customRolesUpgrade","Custom roles require the Business plan or above.")}),i&&e.jsx("button",{onClick:i,className:"text-xs font-medium text-amber-700 dark:text-amber-300 underline hover:no-underline whitespace-nowrap",children:o("permMatrix.upgrade","Upgrade →")})]}),S&&r&&s&&e.jsxs("div",{className:"px-4 py-3.5 bg-indigo-50 dark:bg-indigo-900/20 border border-indigo-200 dark:border-indigo-700 rounded-lg space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold text-indigo-700 dark:text-indigo-300 uppercase tracking-wide",children:o("permMatrix.newCustomRole","New Custom Role")}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("input",{ref:A,type:"text",value:G,onChange:w=>R(w.target.value),onKeyDown:w=>{w.key==="Enter"&&me(),w.key==="Escape"&&(C(!1),R(""))},placeholder:o("permMatrix.newRolePlaceholder","e.g. QA Engineer, Security Auditor, Tech Lead…"),className:"input flex-1 min-w-52 text-sm"}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 me-0.5",children:o("permMatrix.colorLabel","Color:")}),Vs.map(w=>e.jsx("button",{type:"button",onClick:()=>te(w),className:`w-5 h-5 rounded-full transition-transform ${Z===w?"ring-2 ring-offset-1 ring-gray-400 dark:ring-gray-500 scale-110":"hover:scale-110"}`,style:{backgroundColor:w},title:w},w))]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[G.trim()&&e.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1.5",children:[o("permMatrix.previewLabel","Preview:"),e.jsx("span",{className:"font-medium px-2.5 py-0.5 rounded-full text-white text-xs",style:{backgroundColor:Z},children:G.trim()})]}),e.jsxs("div",{className:"flex items-center gap-2 ms-auto",children:[e.jsx("button",{onClick:me,disabled:!G.trim(),className:"btn-primary text-sm px-3 py-1.5 disabled:opacity-50",children:o("permMatrix.addRole","Add Role")}),e.jsx("button",{onClick:()=>{C(!1),R("")},className:"btn-secondary text-sm px-3 py-1.5",children:o("common.cancel","Cancel")})]})]})]}),!S&&N.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:o("permMatrix.customRolesChipsLabel","Custom roles:")}),N.map(w=>e.jsx("span",{className:"text-xs font-medium px-2.5 py-0.5 rounded-full text-white",style:{backgroundColor:w.color??"#6366f1"},children:w.label},w.key))]}),e.jsx("div",{className:"overflow-auto rounded-lg border border-gray-200 dark:border-gray-700 max-h-[60vh]",children:e.jsxs("table",{className:"w-full text-sm",style:{minWidth:`${320+He.length*112}px`},children:[e.jsx("thead",{className:"sticky top-0 z-20",children:e.jsxs("tr",{className:"border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/95 backdrop-blur",children:[e.jsx("th",{className:`text-start px-4 py-2 font-medium text-gray-600 dark:text-gray-400 w-64
17                             sticky start-0 z-30 bg-gray-50 dark:bg-gray-800/95 shadow-[1px_0_0_0_#e5e7eb] dark:shadow-[1px_0_0_0_#374151]`,children:o("permMatrix.permissionColumn","Permission")}),e.jsx("th",{className:"text-center px-3 py-2 font-medium text-gray-600 dark:text-gray-400 w-32",children:e.jsxs("div",{className:"flex flex-col items-center gap-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[qr(o,"OWNER"),e.jsx(pa,{text:dn(o,"OWNER"),size:"xs"})]}),e.jsx(ke,{className:"w-3 h-3 text-gray-400 dark:text-gray-500"})]})}),tn.map(w=>e.jsx("th",{className:"text-center px-3 py-2 font-medium text-gray-600 dark:text-gray-400 w-32",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[Et(w),e.jsx(pa,{text:dn(o,w),size:"xs"})]})},w)),N.map(w=>e.jsx("th",{className:"text-center px-3 py-2 w-32",children:P===w.key?e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx("input",{autoFocus:!0,value:M,onChange:X=>J(X.target.value),onKeyDown:X=>{X.key==="Enter"&&Re(w.key),X.key==="Escape"&&z(null)},onBlur:()=>Re(w.key),className:`w-24 text-xs border border-indigo-300 dark:border-indigo-600 rounded
18                                   px-1.5 py-0.5 text-center bg-white dark:bg-gray-700
19                                   text-gray-900 dark:text-white`}),e.jsx("button",{onMouseDown:X=>{X.preventDefault(),Re(w.key)},className:"text-green-500 hover:text-green-600",children:e.jsx(fr,{className:"w-3 h-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 group/hdr",children:[e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full text-white truncate max-w-[7rem]",style:{backgroundColor:w.color??"#6366f1"},title:w.label,children:w.label}),r&&e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover/hdr:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>Ce(w.key,w.label),className:"p-0.5 text-gray-400 hover:text-blue-500 rounded transition-colors",title:o("permMatrix.renameRoleTitle",'Rename "{{name}}"',{name:w.label}),children:e.jsx(Ps,{className:"w-2.5 h-2.5"})}),e.jsx("button",{onClick:()=>O(w.key),className:"p-0.5 text-gray-400 hover:text-red-500 rounded transition-colors",title:o("permMatrix.deleteRoleTitle",'Delete "{{name}}" role',{name:w.label}),children:e.jsx(ft,{className:"w-2.5 h-2.5"})})]})]})},w.key))]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700/60",children:Object.entries(jt).flatMap(([w,X],pe)=>[e.jsx("tr",{className:"bg-gray-50/60 dark:bg-gray-800/30",children:e.jsx("td",{colSpan:2+He.length,className:`px-4 py-1.5 text-[11px] font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider
20                             sticky start-0 z-10 bg-gray-50 dark:bg-gray-800`,children:Vo(o,w)})},`hdr-${pe}`),...X.map(({key:le,label:Me,description:Te})=>{const ve=ps(o,le,Me),Ve=on(o,le,Te);return e.jsxs("tr",{className:"bg-white dark:bg-gray-800/50 hover:bg-gray-50/40 dark:hover:bg-gray-800/80 transition-colors",children:[e.jsx("td",{className:`px-4 py-1.5 text-gray-700 dark:text-gray-300
21                                 sticky start-0 z-10 bg-white dark:bg-gray-800
22                                 shadow-[1px_0_0_0_#e5e7eb] dark:shadow-[1px_0_0_0_#374151]`,children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[ve,Ve&&e.jsx(pa,{text:Ve,size:"xs"})]})}),e.jsx("td",{className:"text-center px-3 py-1.5",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("div",{className:"w-5 h-5 rounded bg-indigo-100 dark:bg-indigo-900/40 flex items-center justify-center",children:e.jsx(ke,{className:"w-3 h-3 text-indigo-500 dark:text-indigo-400"})})})}),He.map(Ie=>{var ut,vt;const fe=((ut=f[le])==null?void 0:ut[Ie])??((vt=ua[le])==null?void 0:vt[Ie])??!1,Fe=Et(Ie),tt=["w-5 h-5 rounded border-2 flex items-center justify-center transition-all",r?"cursor-pointer hover:scale-110":"cursor-not-allowed opacity-70",fe?"bg-indigo-500 dark:bg-indigo-600 border-indigo-500 dark:border-indigo-600":"bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600"].join(" ");return e.jsx("td",{className:"text-center px-3 py-1.5",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("button",{onClick:()=>ue(le,Ie),disabled:!r,className:tt,title:r?fe?o("permMatrix.toggleRevokeTitle",'Revoke "{{permission}}" for {{role}}',{permission:ve,role:Fe}):o("permMatrix.toggleGrantTitle",'Grant "{{permission}}" for {{role}}',{permission:ve,role:Fe}):void 0,"aria-label":fe?o("permMatrix.toggleAllowedAria","{{permission}}, {{role}}: allowed",{permission:ve,role:Fe}):o("permMatrix.toggleDeniedAria","{{permission}}, {{role}}: denied",{permission:ve,role:Fe}),children:fe&&e.jsx("svg",{className:"w-3 h-3 text-white",viewBox:"0 0 12 12",fill:"none",children:e.jsx("path",{d:"M2 6l3 3 5-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})})},Ie)})]},le)})])})]})}),e.jsx(yo,{policy:f,surface:"matrix",compact:!0})]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap text-xs text-gray-400 dark:text-gray-500",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ke,{className:"w-3 h-3"}),o("permMatrix.legendOwner","Owner always has full access and cannot be restricted")]}),N.length>0&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-indigo-400 dark:bg-indigo-500 inline-block"}),o("permMatrix.legendCustomRoles",{count:N.length,defaultValue_one:"{{count}} custom role, assign them when inviting project members",defaultValue_other:"{{count}} custom roles, assign them when inviting project members"})]})]}),r&&e.jsxs("div",{className:"flex justify-end gap-3 pt-2 border-t border-gray-100 dark:border-gray-700",children:[e.jsx("button",{onClick:F,disabled:!Ue||Je.isPending,className:"btn-secondary text-sm disabled:opacity-50",children:o("common.cancel","Cancel")}),e.jsxs("button",{onClick:()=>Pe?y(!0):Je.mutate(),disabled:!Ue||Je.isPending,className:"btn-primary flex items-center gap-2 text-sm disabled:opacity-50",children:[e.jsx(Kn,{className:"w-4 h-4"}),Je.isPending?o("permMatrix.saving","Saving…"):o("permMatrix.saveChanges","Save Changes")]})]}),b&&e.jsx($o,{onCancel:()=>y(!1),onConfirm:()=>{y(!1),Je.mutate()}})]})}function Jo({orgId:t,isOwner:a}){const{t:s}=Q(),{currentOrg:l,setCurrentOrg:i}=Qe(),[c,r]=g.useState(!1);if(!(a&&!!xi()&&(l==null?void 0:l.id)===t&&ui(l)==="FREE")||!l)return null;const x=l.sessionRecordingEnabled!==!1,d=async()=>{if(c)return;r(!0);const u=!x;try{await B.setSessionRecording(t,u),i({...l,sessionRecordingEnabled:u}),k.success(u?s("orgSettings.sessionRec.enabledToast","Session analytics enabled for this workspace"):s("orgSettings.sessionRec.disabledToast","Session analytics disabled for this workspace"))}catch(h){k.error(U(h,"update session analytics settings"))}finally{r(!1)}};return e.jsx("div",{className:"rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-indigo-50 dark:bg-indigo-900/30 flex items-center justify-center flex-shrink-0",children:e.jsx(jr,{className:"w-4 h-4 text-indigo-600 dark:text-indigo-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:s("orgSettings.sessionRec.title","Product session analytics")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:s("orgSettings.sessionRec.subtitle","On free workspaces, members may opt in to de-identified, fully-masked session analytics (Microsoft Clarity) that help us improve the product. Turn this off to disable it for everyone in this workspace, no matter their personal choice.")})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":x,disabled:c,onClick:d,className:`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors ${x?"bg-indigo-600":"bg-gray-300 dark:bg-gray-600"} ${c?"opacity-50":""}`,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${x?"translate-x-6 rtl:-translate-x-6":"translate-x-1 rtl:-translate-x-1"}`})})]})})}const cn={SEV1:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",SEV2:"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300",SEV3:"bg-yellow-50 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300",SEV4:"bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400"},Xo={SEV1:"Critical",SEV2:"High",SEV3:"Medium",SEV4:"Low"},Zo={OPS:"bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-200",SECURITY:"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300",UX:"bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300",AI:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300",BILLING:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300"};function el({orgId:t}){const{data:a,isLoading:s,isError:l,refetch:i}=ee({queryKey:["org-health-findings",t],queryFn:()=>B.getHealthFindings(t),staleTime:6e4}),c=(a==null?void 0:a.findings)??[],r=g.useRef(null);return g.useEffect(()=>{s||l||!a||r.current!==t&&(r.current=t,Ja("org_health_viewed",{findings:c.length,categories:[...new Set(c.map(o=>o.category))].sort().join(","),securityGated:!!a.securityGated}))},[t,s,l,a,c]),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx(Gn,{className:"w-6 h-6 text-indigo-600 dark:text-indigo-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Worksp
22ace health"}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 max-w-2xl",children:"Issues Onplana has noticed in your workspace, in plain language, each with the recommended next step. Only your organization's own findings are shown."})]})]}),s?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((o,x)=>e.jsx(oe,{className:"h-20 w-full"},x))}):l?e.jsxs("div",{className:"card p-8 text-center text-red-600 dark:text-red-400 text-sm",children:["Could not load health findings. ",e.jsx("button",{onClick:()=>i(),className:"underline",children:"Retry"})]}):c.length===0?e.jsxs("div",{className:"card p-10 text-center",children:[e.jsx(ct,{className:"w-10 h-10 mx-auto mb-3 text-emerald-500 dark:text-emerald-400"}),e.jsx("div",{className:"text-sm font-medium text-gray-800 dark:text-gray-200",children:"All clear"}),e.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"No open health findings for your workspace right now."})]}):e.jsx("div",{className:"space-y-2",children:c.map(o=>e.jsxs("div",{className:"card p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1.5",children:[e.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${cn[o.severity]??cn.SEV4}`,children:Xo[o.severity]??o.severity}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${Zo[o.category]??"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300"}`,children:o.category})]}),e.jsx("div",{className:"font-semibold text-gray-900 dark:text-gray-100",children:o.title}),e.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300 mt-0.5",children:o.summary}),o.guidance&&e.jsxs("div",{className:"text-sm text-gray-800 dark:text-gray-200 mt-2 flex items-start gap-1.5",children:[e.jsx("span",{className:"text-indigo-500 dark:text-indigo-400 mt-0.5",children:"→"}),e.jsx("span",{children:o.guidance})]}),o.docsHref&&e.jsxs("a",{href:o.docsHref,target:"_blank",rel:"noopener noreferrer",onClick:()=>Ja("org_health_guidance_opened",{category:o.category,severity:o.severity,href:o.docsHref}),className:"inline-flex items-center gap-1 text-xs text-indigo-600 dark:text-indigo-400 hover:underline mt-2",children:["Learn more ",e.jsx(ha,{className:"w-3 h-3"})]})]},o.id))}),(a==null?void 0:a.securityGated)&&e.jsxs("div",{className:"mt-4 flex items-start gap-2 text-xs text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-800/60 rounded p-3",children:[e.jsx(je,{className:"w-4 h-4 text-amber-500 dark:text-amber-400 shrink-0 mt-0.5"}),e.jsx("span",{children:"Security-category findings are part of the audit-log telemetry, available on the Enterprise plan."})]})]})}const tl={PASS:{bg:"bg-green-50 dark:bg-green-900/20",border:"border-green-200 dark:border-green-800",icon:e.jsx(ct,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),badge:"bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400"},WARN:{bg:"bg-amber-50 dark:bg-amber-900/20",border:"border-amber-200 dark:border-amber-800",icon:e.jsx(je,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),badge:"bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400"},FAIL:{bg:"bg-red-50 dark:bg-red-900/20",border:"border-red-200 dark:border-red-800",icon:e.jsx(Qa,{className:"w-5 h-5 text-red-500 flex-shrink-0"}),badge:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-400"}},al=90;function sl(t,a){switch(a){case"Controls":return t("orgSecurity.tab.controls","Controls");case"Health":return t("orgSecurity.tab.health","Health");case"Access Review":return t("orgSecurity.tab.accessReview","Access Review");case"Security Events":return t("orgSecurity.tab.securityEvents","Security Events");case"Audit Export":return t("orgSecurity.tab.auditExport","Audit Export")}}function rl(t,a){switch(a){case"PASS":return t("orgSecurity.controlStatus.pass","PASS");case"WARN":return t("orgSecurity.controlStatus.warn","WARN");case"FAIL":return t("orgSecurity.controlStatus.fail","FAIL")}}function gn(t,a){if(a==="all")return t;const s=a==="agents";return t.filter(l=>!!l.isAgentPersona===s)}function nl(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"_")}function mn(t,a){return t(`orgSecurity.control.${a.id}.label`,a.label)}function il(t,a){return t(`orgSecurity.category.${nl(a)}`,a)}function xn(t,a){return a.detailKey?t(`orgSecurity.control.${a.id}.detail.${a.detailKey}`,{defaultValue:a.detail,...a.params??{}}):a.detail}function ol(t,a){switch(a){case 0:return t("orgSecurity.passwordPolicy.expiry.never","Never");case 30:return t("orgSecurity.passwordPolicy.expiry.days30","30 days");case 60:return t("orgSecurity.passwordPolicy.expiry.days60","60 days");case 90:return t("orgSecurity.passwordPolicy.expiry.days90","90 days");case 180:return t("orgSecurity.passwordPolicy.expiry.days180","180 days");default:return t("orgSecurity.common.daysValue","{{days}} days",{days:a})}}function ll(t,a){switch(a){case"requireUppercase":return t("orgSecurity.passwordPolicy.requireUppercase","Require uppercase letter (A-Z)");case"requireNumbers":return t("orgSecurity.passwordPolicy.requireNumbers","Require number (0-9)");case"requireSpecialChars":return t("orgSecurity.passwordPolicy.requireSpecialChars","Require special character (!@#$...)");default:return""}}function dl(t,a){switch(a){case 1:return t("orgSecurity.sessionPolicy.duration.hours1","1 hour");case 4:return t("orgSecurity.sessionPolicy.duration.hours4","4 hours");case 8:return t("orgSecurity.sessionPolicy.duration.hours8","8 hours");case 24:return t("orgSecurity.sessionPolicy.duration.hours24","24 hours (1 day)");case 72:return t("orgSecurity.sessionPolicy.duration.hours72","72 hours (3 days)");case 168:return t("orgSecurity.sessionPolicy.duration.days7","7 days");case 336:return t("orgSecurity.sessionPolicy.duration.days14","14 days");case 720:return t("orgSecurity.sessionPolicy.duration.days30","30 days");default:return t("orgSecurity.common.hoursValue","{{hours}} hours",{hours:a})}}function cl(t,a){switch(a){case 0:return t("orgSecurity.sessionPolicy.idle.disabled","Disabled");case 15:return t("orgSecurity.sessionPolicy.idle.minutes15","15 minutes");case 30:return t("orgSecurity.sessionPolicy.idle.minutes30","30 minutes");case 60:return t("orgSecurity.sessionPolicy.idle.minutes60","60 minutes");case 120:return t("orgSecurity.sessionPolicy.idle.hours2","2 hours");default:return t("orgSecurity.common.minutesValue","{{minutes}} minutes",{minutes:a})}}function gl(t,a){switch(a){case 0:return t("orgSecurity.sessionPolicy.oauthTtl.default","Default (90 days)");case 7:return t("orgSecurity.sessionPolicy.oauthTtl.days7","7 days");case 14:return t("orgSecurity.sessionPolicy.oauthTtl.days14","14 days");case 30:return t("orgSecurity.sessionPolicy.oauthTtl.days30","30 days");case 60:return t("orgSecurity.sessionPolicy.oauthTtl.days60","60 days");default:return t("orgSecurity.common.daysValue","{{days}} days",{days:a})}}function ml({data:t}){var o,x;const{t:a}=Q(),s=t.slice(-14),l=Math.max(...s.map(d=>d.count),1),i=280,c=48,r=Math.floor((i-8)/s.length)-2;return e.jsxs("svg",{viewBox:`0 0 ${i} ${c+14}`,className:"w-full max-w-xs","aria-label":a("orgSecurity.events.chartAriaLabel","Failed logins per day"),children:[s.map((d,u)=>{const h=Math.max(Math.round(d.count/l*c),d.count>0?2:1),f=4+u*(r+2);return e.jsx("rect",{x:f,y:c-h,width:r,height:h,className:d.count>0?"fill-red-400 dark:fill-red-600":"fill-gray-200 dark:fill-gray-700",rx:1,children:e.jsx("title",{children:a("orgSecurity.events.chartBarTooltip",{date:d.date,count:d.count,defaultValue_one:"{{date}}: {{count}} failed attempt",defaultValue_other:"{{date}}: {{count}} failed attempts"})})},d.date)}),s.length>0&&e.jsx("text",{x:4,y:c+12,fontSize:8,className:"fill-gray-400",children:(o=s[0])==null?void 0:o.date.slice(5)}),s.length>1&&e.jsx("text",{x:i-4,y:c+12,textAnchor:"end",fontSize:8,className:"fill-gray-400",children:(x=s[s.length-1])==null?void 0:x.date.slice(5)})]})}function xl({pass:t,warn:a,fail:s}){const l=t+a+s;if(l===0)return null;const i=Math.round((t+a*.5)/l*100),c=36,r=2*Math.PI*c,o=r-i/100*r,x=i>=80?"text-green-500":i>=50?"text-amber-500":"text-red-500",d=i>=80?"text-green-100 dark:text-green-900/30":i>
22=50?"text-amber-100 dark:text-amber-900/30":"text-red-100 dark:text-red-900/30";return e.jsxs("div",{className:"relative w-20 h-20 flex-shrink-0",children:[e.jsxs("svg",{viewBox:"0 0 80 80",className:"w-full h-full -rotate-90",children:[e.jsx("circle",{cx:"40",cy:"40",r:c,fill:"none",strokeWidth:"6",className:`stroke-current ${d}`}),e.jsx("circle",{cx:"40",cy:"40",r:c,fill:"none",strokeWidth:"6",strokeLinecap:"round",className:`stroke-current ${x} transition-all duration-700`,strokeDasharray:r,strokeDashoffset:o})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:`text-lg font-bold ${x}`,children:i}),e.jsx("span",{className:"text-[9px] text-gray-400 font-medium -mt-0.5",children:"/ 100"})]})]})}function Bt({id:t,collapsed:a,toggle:s,children:l}){const i=!a[t];return e.jsxs("div",{className:"card overflow-hidden",children:[e.jsx("div",{role:"button",tabIndex:0,"aria-expanded":i,onClick:()=>s(t),onKeyDown:c=>{c.target===c.currentTarget&&(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),s(t))},className:"w-full flex items-center cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500",children:e.jsx("div",{className:"flex-1",children:l[0]})}),e.jsx("div",{className:`grid transition-all duration-200 ease-in-out ${i?"grid-rows-[1fr]":"grid-rows-[0fr]"}`,children:e.jsx("div",{className:"overflow-hidden",children:l[1]})})]})}function ur({checked:t,onChange:a,disabled:s,title:l}){return e.jsx("button",{onClick:a,disabled:s,role:"switch","aria-checked":t,"aria-label":l,className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50 ${t?"bg-indigo-600":"bg-gray-300 dark:bg-gray-600"}`,title:l,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-6 rtl:-translate-x-6":"translate-x-1 rtl:-translate-x-1"}`})})}const ul=["Controls","Health","Access Review","Security Events","Audit Export"],Yn={Controls:"controls",Health:"health","Access Review":"access-review","Security Events":"security-events","Audit Export":"audit-export"},pl=Object.fromEntries(Object.entries(Yn).map(([t,a])=>[a,t]));function un(t){return t?pl[t]??null:null}const hl={Controls:e.jsx(kt,{className:"w-3.5 h-3.5"}),Health:e.jsx(Gn,{className:"w-3.5 h-3.5"}),"Access Review":e.jsx(ba,{className:"w-3.5 h-3.5"}),"Security Events":e.jsx(jr,{className:"w-3.5 h-3.5"}),"Audit Export":e.jsx(ta,{className:"w-3.5 h-3.5"})};function bl({orgId:t,orgSlug:a,hasScimToken:s,isOwner:l,subTab:i,onSubTabChange:c}){var Ft,La,Xt,ca,Oa,Dt,ls,Ia;const{t:r,i18n:o}=Q(),x=vs(),[d,u]=g.useState("Controls"),h=i??d,f=m=>{u(m),c==null||c(m)},[j,b]=g.useState({"2fa":!0,ip:!0,retention:!0,pwPolicy:!0,sessPolicy:!0,apiTokens:!0,scim:!0,compliance:!0}),{user:y,currentOrg:N}=Qe(),p=(N==null?void 0:N.role)==="OWNER",S=_e(),C=et("scim"),G=et("ipAllowlist"),R=pi(N==null?void 0:N.product),Z=C||!R,te=G||!R,A=et("auditLogs"),{showConfirm:P,ConfirmUI:z}=As(),M=$({mutationFn:m=>B.resetUserTwoFactor(t,m),onSuccess:m=>{S.invalidateQueries({queryKey:["org-security-access",t]}),S.invalidateQueries({queryKey:["org-security-controls",t]}),k.success(m.message??r("orgSecurity.toast.twoFaReset","2FA reset"))},onError:m=>{var W,q;const D=(q=(W=m==null?void 0:m.response)==null?void 0:W.data)==null?void 0:q.code;D==="CROSS_ORG_2FA_RESET_DENIED"?k.error(r("orgSecurity.toast.crossOrgResetDenied","User belongs to other orgs, contact platform support to reset 2FA across orgs.")):D==="OWNER_RESET_REQUIRES_OWNER"?k.error(r("orgSecurity.toast.ownerResetRequiresOwner","Only an org OWNER can reset another OWNER's 2FA.")):k.error(U(m,"reset 2FA"))}});function J(m){b(D=>({...D,[m]:!D[m]}))}const ae=ee({queryKey:["org-security-controls",t],queryFn:()=>B.getSecurityControls(t),staleTime:6e4}),re=ee({queryKey:["org-security-access",t],queryFn:()=>B.getSecurityAccessReview(t),staleTime:6e4,enabled:h==="Access Review"}),[H,ge]=g.useState(""),[_,se]=g.useState("name"),[ne,Ye]=g.useState(!0),[T,ie]=g.useState(0),[Le,we]=g.useState(!1),[Ue,Je]=g.useState("humans"),Pe=g.useMemo(()=>new Date(Date.now()-al*864e5),[]),mt=g.useMemo(()=>{var m;return(((m=re.data)==null?void 0:m.rows)??[]).some(D=>D.isAgentPersona)},[re.data]),F=g.useMemo(()=>{var q;const m=((q=re.data)==null?void 0:q.rows)??[],D=H.toLowerCase();let W=D?m.filter(Ee=>Ee.name.toLowerCase().includes(D)||Ee.email.toLowerCase().includes(D)):m;return W=gn(W,Ue),Le&&(W=W.filter(Ee=>Ee.lastLoginAt&&new Date(Ee.lastLoginAt)<Pe)),[...W].sort((Ee,Ge)=>{let wt=0;if(_==="name"&&(wt=Ee.name.localeCompare(Ge.name)),_==="role"&&(wt=Ee.orgRole.localeCompare(Ge.orgRole)),_==="lastLogin"){const Lt=Ee.lastLoginAt?new Date(Ee.lastLoginAt).getTime():0,Ot=Ge.lastLoginAt?new Date(Ge.lastLoginAt).getTime():0;wt=Lt-Ot}return ne?wt:-wt})},[re.data,H,_,ne,Le,Ue,Pe]);function ue(m){_===m?(Ye(D=>!D),ie(0)):(se(m),Ye(!0),ie(0))}const[me,O]=g.useState(30),Ce=ee({queryKey:["org-security-events",t,me],queryFn:()=>B.getSecurityEvents(t,me),staleTime:6e4,enabled:h==="Security Events"}),Re=ee({queryKey:["org-security-settings",t],queryFn:()=>B.getSecuritySettings(t),staleTime:6e4,enabled:h==="Controls"}),He=((Ft=Re.data)==null?void 0:Ft.require2FA)??!1,Et=((La=Re.data)==null?void 0:La.ssoTrustIdpMfa)??!0,We=ee({queryKey:["org-security-access",t],queryFn:()=>B.getSecurityAccessReview(t),staleTime:6e4,enabled:h==="Controls"}),Oe=g.useMemo(()=>{var m;return(((m=We.data)==null?void 0:m.rows)??[]).filter(D=>!D.twoFaEnabled&&!D.isAgentPersona)},[We.data]),jt=Oe.some(m=>m.userId===(y==null?void 0:y.id)),xt=g.useMemo(()=>{const m=Oe.slice(0,3).map(q=>q.name);let D;try{D=new Intl.ListFormat(o.language,{style:"narrow",type:"unit"}).format(m)}catch{D=m.join(", ")}const W=Oe.length-m.length;return W>0?r("orgSecurity.twoFa.blockedNamesOverflow",{count:W,names:D,defaultValue_one:"{{names}} and {{count}} other",defaultValue_other:"{{names}} and {{count}} others"}):D},[Oe,o.language,r]),w=((Xt=We.data)==null?void 0:Xt.total)??0,X=g.useMemo(()=>{var m;return gn(((m=We.data)==null?void 0:m.rows)??[],"humans").length},[We.data]),[pe,le]=g.useState(!1),Me=Vt({open:pe,onClose:()=>le(!1)}),Te=$({mutationFn:m=>B.saveSecuritySettings(t,{require2FA:m}),onSuccess:m=>{k.success(m.require2FA?r("orgSecurity.toast.twoFaEnforceEnabled","2FA enforcement enabled"):r("orgSecurity.toast.twoFaEnforceDisabled","2FA enforcement disabled")),S.invalidateQueries({queryKey:["org-security-settings",t]}),S.invalidateQueries({queryKey:["org-security-controls",t]}),le(!1)},onError:m=>k.error(U(m,"update 2FA enforcement"))}),ve=$({mutationFn:m=>B.saveSecuritySettings(t,{ssoTrustIdpMfa:m}),onSuccess:m=>{k.success(m.ssoTrustIdpMfa?r("orgSecurity.toast.ssoTrustEnabled","SSO sessions with IdP MFA now satisfy 2FA enforcement"):r("orgSecurity.toast.ssoTrustDisabled","SSO users must also enrol Onplana TOTP")),S.invalidateQueries({queryKey:["org-security-settings",t]})},onError:m=>k.error(U(m,"update security settings"))});function Ve(){!He&&Oe.length>0?le(!0):Te.mutate(!He)}const Ie=ee({queryKey:["org-ip-allowlist",t],queryFn:()=>B.getIpAllowlist(t),staleTime:6e4,enabled:h==="Controls"}),[fe,Fe]=g.useState(""),[tt,ut]=g.useState(""),vt=g.useRef(null),Xe=$({mutationFn:m=>B.saveIpAllowlist(t,m),onSuccess:()=>{k.success(r("orgSecurity.toast.ipAllowlistSaved","IP allowlist saved")),S.invalidateQueries({queryKey:["org-ip-allowlist",t]}),S.invalidateQueries({queryKey:["org-security-controls",t]})},onError:m=>k.error(U(m,"save IP allowlist"))}),at=((ca=Ie.data)==null?void 0:ca.ips)??[],Na=((Oa=Ie.data)==null?void 0:Oa.planSupported)??!1,pt=((Dt=Ie.data)==null?void 0:Dt.yourIp)??"",aa=!!pt&&!(((ls=Ie.data)==null?void 0:ls.yourIpAllowed)??!1)&&!at.includes(pt);function as(){pt&&Xe.mutate([...at,pt])}function Sa(m){const D=m.trim();if(!D)return r("orgSecurity.ipAllowlist.errorEmpty","Enter an IP address or CIDR range");const W=/^(\d{1,3}\.){3}\d{1,3}$/,q=/^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/,Ee=/^[0-9a-fA-F:]+$/;return!W.test(D)&&!q.test(D)&&!Ee.test(D)?r("orgSecurity.ipAllowlist.errorInvalid","Must be a valid IPv4 (e.g. 203.0.113.5), CIDR (e.g. 10.0.0.0/8), or IPv6"):at.includes(D)?r("orgSecurity.ipAllowlist.errorDuplicate","Already in the allowlist"):""}function ht(){var W;const m=fe.trim(),D=Sa(m);if(D){ut(D);return}
22ut(""),Fe(""),Xe.mutate([...at,m]),(W=vt.current)==null||W.focus()}function Be(m){Xe.mutate(at.filter(D=>D!==m))}const Ke=ee({queryKey:["org-retention-policy",t],queryFn:()=>B.getRetentionPolicy(t),staleTime:6e4,enabled:h==="Controls"}),[rt,wa]=g.useState("STANDARD"),[Ca,sa]=g.useState(""),[Nt,ra]=g.useState(""),[Aa,Pt]=g.useState(""),[ss,Ea]=g.useState(""),[Ts,nt]=g.useState(!1);g.useEffect(()=>{var m,D,W;Ke.data&&!Ts&&(wa(Ke.data.preset),sa(Ke.data.notes??""),ra(((m=Ke.data.orgDataDays)==null?void 0:m.toString())??""),Pt(((D=Ke.data.auditLogDays)==null?void 0:D.toString())??""),Ea(((W=Ke.data.userDataDays)==null?void 0:W.toString())??""))},[Ke.data,Ts]);const zt=$({mutationFn:()=>B.saveRetentionPolicy(t,{preset:rt,orgDataDays:rt==="CUSTOM"&&parseInt(Nt)||null,auditLogDays:rt==="CUSTOM"&&parseInt(Aa)||null,userDataDays:rt==="CUSTOM"&&parseInt(ss)||null,notes:Ca||null}),onSuccess:()=>{k.success(r("orgSecurity.toast.retentionSaved","Retention policy saved")),nt(!1),S.invalidateQueries({queryKey:["org-retention-policy",t]}),S.invalidateQueries({queryKey:["org-security-controls",t]})},onError:m=>k.error(U(m,"save retention policy"))}),[Pa,na]=g.useState({minLength:8,requireUppercase:!0,requireNumbers:!0,requireSpecialChars:!0,maxAgeDays:0}),[Ta,St]=g.useState(!1);g.useEffect(()=>{var m;(m=Re.data)!=null&&m.passwordPolicy&&!Ta&&na(Re.data.passwordPolicy)},[Re.data,Ta]);const Ra=$({mutationFn:m=>B.saveSecuritySettings(t,{passwordPolicy:m}),onSuccess:()=>{k.success(r("orgSecurity.toast.passwordPolicySaved","Password policy saved")),St(!1),S.invalidateQueries({queryKey:["org-security-settings",t]}),S.invalidateQueries({queryKey:["org-security-controls",t]})},onError:m=>k.error(U(m,"save password policy"))}),[Rs,Qt]=g.useState({sessionTimeoutHours:168,idleTimeoutMinutes:0}),[Ma,rs]=g.useState(!1);g.useEffect(()=>{var m;(m=Re.data)!=null&&m.sessionPolicy&&!Ma&&Qt(Re.data.sessionPolicy)},[Re.data,Ma]);const ia=$({mutationFn:m=>B.saveSecuritySettings(t,{sessionPolicy:m}),onSuccess:()=>{k.success(r("orgSecurity.toast.sessionPolicySaved","Session policy saved")),rs(!1),S.invalidateQueries({queryKey:["org-security-settings",t]}),S.invalidateQueries({queryKey:["org-security-controls",t]})},onError:m=>k.error(U(m,"save session policy"))}),Ms=$({mutationFn:()=>B.forceLogoutAll(t),onSuccess:m=>{k.success(r("orgSecurity.toast.forcedReauth",{count:m.affectedUsers,defaultValue_one:"Forced re-authentication for {{count}} member. You will be logged out on your next request.",defaultValue_other:"Forced re-authentication for {{count}} members. You will be logged out on your next request."}))},onError:m=>k.error(U(m,"force re-authentication"))}),Tt=()=>{P({title:r("orgSecurity.forceLogout.confirmTitle","Force re-authentication for all members?"),message:r("orgSecurity.forceLogout.confirmMessage","This includes you, your session will end on your next page load. Use this after tightening the session timeout so existing tokens don't outlive the new policy."),confirmLabel:r("orgSecurity.forceLogout.confirmLabel","Force logout"),variant:"warning",onOk:()=>Ms.mutate()})},ns=ee({queryKey:["org-api-tokens",t],queryFn:()=>B.getOrgApiTokens(t),staleTime:6e4,enabled:h==="Controls"}),[Fs,Rt]=g.useState(null),de=$({mutationFn:m=>B.revokeOrgApiToken(t,m),onSuccess:()=>{k.success(r("orgSecurity.toast.tokenRevoked","Token revoked")),Rt(null),S.invalidateQueries({queryKey:["org-api-tokens",t]}),S.invalidateQueries({queryKey:["org-security-controls",t]})},onError:m=>k.error(U(m,"revoke token"))}),[ze,Ne]=g.useState(null),[it,oa]=g.useState(!1),Mt=$({mutationFn:()=>B.generateScimToken(t),onSuccess:m=>{Ne(m),S.invalidateQueries({queryKey:["organization",t]}),k.success(r("orgSecurity.toast.scimTokenGenerated","SCIM token generated"))},onError:m=>k.error(U(m,"generate SCIM token"))}),la=$({mutationFn:()=>B.revokeScimToken(t),onSuccess:()=>{Ne(null),oa(!1),S.invalidateQueries({queryKey:["organization",t]}),k.success(r("orgSecurity.toast.scimTokenRevoked","SCIM token revoked"))},onError:m=>k.error(U(m,"revoke SCIM token"))}),[Yt,Fa]=g.useState("csv"),[is,Da]=g.useState(Wa(hi(new Date,30),"yyyy-MM-dd")),[ot,os]=g.useState(Wa(new Date,"yyyy-MM-dd")),Jt=B.securityAuditExportUrl(t,{format:Yt,from:is,to:ot}),he=(Ia=ae.data)==null?void 0:Ia.summary,Ds=g.useMemo(()=>{var D;const m=new Map;for(const W of((D=ae.data)==null?void 0:D.controls)??[]){const q=m.get(W.category)??[];q.push(W),m.set(W.category,q)}return m},[ae.data]),da=g.useMemo(()=>{var D;return(((D=We.data)==null?void 0:D.rows)??[]).filter(W=>W.lastLoginAt&&new Date(W.lastLoginAt)<Pe).length},[We.data,Pe]);return e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"card p-6 bg-gradient-to-br from-white to-gray-50/80 dark:from-gray-800 dark:to-gray-800/80",children:e.jsxs("div",{className:"flex items-center gap-6",children:[he?e.jsx(xl,{pass:he.pass,warn:he.warn,fail:he.fail}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center flex-shrink-0",children:e.jsx(Kr,{className:"w-8 h-8 text-gray-300 dark:text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-1.5",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:r("orgSecurity.header.title","Security & Compliance")}),he&&(()=>{const m=he.pass+he.warn+he.fail,D=m>0?Math.round((he.pass+he.warn*.5)/m*100):0,W=D>=80?r("orgSecurity.header.postureGood","Good"):D>=50?r("orgSecurity.header.postureNeedsAttention","Needs Attention"):r("orgSecurity.header.postureCritical","Critical"),q=D>=80?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":D>=50?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400";return e.jsx("span",{className:`text-xs font-bold px-2.5 py-0.5 rounded-full uppercase tracking-wide ${q}`,children:W})})()]}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mb-3",children:r("orgSecurity.header.subtitle","Monitor your organization's security posture, manage access controls, and maintain compliance evidence.")}),he&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ct,{className:"w-4 h-4 text-green-500"}),e.jsx("span",{className:"text-sm font-semibold text-green-700 dark:text-green-400",children:r("orgSecurity.header.passedCount",{count:he.pass,defaultValue_one:"{{count}} passed",defaultValue_other:"{{count}} passed"})})]}),he.warn>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(je,{className:"w-4 h-4 text-amber-500"}),e.jsx("span",{className:"text-sm font-semibold text-amber-700 dark:text-amber-400",children:r("orgSecurity.header.warningCount",{count:he.warn,defaultValue_one:"{{count}} warning",defaultValue_other:"{{count}} warnings"})})]}),he.fail>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Qa,{className:"w-4 h-4 text-red-500"}),e.jsx("span",{className:"text-sm font-semibold text-red-700 dark:text-red-400",children:r("orgSecurity.header.failedCount",{count:he.fail,defaultValue_one:"{{count}} failed",defaultValue_other:"{{count}} failed"})})]}),e.jsx("span",{className:"text-xs text-gray-400 ms-1 whitespace-nowrap",children:r("orgSecurity.header.controlsEvaluated",{count:he.pass+he.warn+he.fail,defaultValue_one:"{{count}} control evaluated",defaultValue_other:"{{count}} controls evaluated"})})]})]})]})}),e.jsx("div",{ref:x.ref,style:x.style,className:"flex gap-1 border-b border-gray-200 dark:border-gray-700 max-md:overflow-x-auto max-md:[&>button]:shrink-0 max-md:[&>button]:whitespace-nowrap scrollbar-hide",children:ul.map(m=>e.jsxs("button",{onClick:()=>f(m),className:`flex items-center gap-1.5 px-4 py-3 text-sm font-medium border-b-2 transition-colors ${h===m?"border-indigo-500 text-indigo-600 dark:text-indigo-400":"border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"}`,children:[hl[m],sl(r,m),m==="Controls"&&he&&he.fail>0&&e.jsx("span",{className:"ms-1 px-1.5 py-0.5 text-[11px] font-bold rounded-full bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",children:he.fail}),m==="Access Review"&&w>0&&e.jsx("span",{className:"ms-1 px-1.5 py-0.5 text-[11px] font-bold rounded-full bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400",children:w})]},m))}),h==="Controls"&&(ae.isLoading?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5",children:[e.jsx(oe,{className:"h-24 rounded-xl w-full"}),e.jsx(oe,{className:"h-40 rounded-xl w-full"}),e.jsx(oe,{className:"h-32 rounded-xl w-full"})]}):e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5",children:[e.jsx(Jo,{orgId:t,isOwner:!!l}),(()=>{var D;const m=(((D=ae.data)==null?void 0:D.controls)??[]).filter(W=>W.status==="FAIL");return m.length===0?null:e.jsxs("div",{className:"md:col-span-2 xl:col-span-3 rounded-xl border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Qa,{className:"w-4 h-4 text-red-500 flex-shrink-0"}),e.jsx("span",{className:"text-sm font-semibold text-red-700 dark:text-red-400",children:r("orgSecurity.controls.criticalIssues",{count:m.length,defaultValue_one:"{{count}} Critical Issue Requires Attention",defaultValue_other:"{{count}} Critical Issues Require Attention"})})]}),e.jsx("div",{className:"space-y-2",children:m.map(W=>e.jsxs("div",{className:"flex gap-2 text-xs text-red-700 dark:text-red-300",children:[e.jsxs("span",{className:"font-semibold whitespace-nowrap",children:[mn(r,W),":"]}),e.jsx("span",{className:"text-red-600 dark:text-red-400",children:xn(r,W)})]},W.id))})]})})(),e.jsx("div",{className:"md:col-span-2 xl:col-span-3",children:e.jsx(Qs,{label:r("orgSecurity.section.securityConfiguration","Security Configuration")})}),e.jsxs(Bt,{id:"2fa",collapsed:j,toggle:J,children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 bg-indigo-50 dark:bg-indigo-950/40 border-s-4 border-s-indigo-500 rounded-t-xl transition-colors",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-indigo-100 dark:bg-indigo-900/40 flex items-center justify-center flex-shrink-0",children:e.jsx(kt,{className:"w-4 h-4 text-indigo-600 dark:text-indigo-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:r("orgSecurity.twoFa.title","Enforce 2FA for All Members")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r("orgSecurity.twoFa.subtitle","Block org access for any member who has not set up two-factor authentication.")})]}),!He&&Oe.length>0&&e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full bg-amber-100 dar
22k:bg-amber-900/30 text-amber-700 dark:text-amber-400 border border-amber-200 dark:border-amber-700",children:r("orgSecurity.twoFa.withoutTwoFaBadge",{count:Oe.length,defaultValue_one:"{{count}} without 2FA",defaultValue_other:"{{count}} without 2FA"})}),e.jsx("div",{onClick:m=>m.stopPropagation(),children:e.jsx(ur,{checked:He,onChange:Ve,disabled:Te.isPending||Re.isLoading,title:He?r("orgSecurity.twoFa.toggleDisable","Disable 2FA enforcement"):r("orgSecurity.twoFa.toggleEnable","Enable 2FA enforcement")})})]}),e.jsxs("div",{className:"px-5 py-3 space-y-2 border-t border-gray-100 dark:border-gray-700/50",children:[He?e.jsxs(e.Fragment,{children:[Oe.length>0?e.jsxs("div",{className:"flex items-start gap-2 text-xs text-red-700 dark:text-red-400 bg-red-50 dark:bg-red-900/20 rounded-lg p-3 border border-red-200 dark:border-red-700",children:[e.jsx(Hi,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),e.jsxs("span",{children:[e.jsx("strong",{children:r("orgSecurity.twoFa.blockedHeadline",{count:Oe.length,defaultValue_one:"{{count}} member is currently blocked",defaultValue_other:"{{count}} members are currently blocked"})})," ",e.jsx(Ht,{i18nKey:"orgSecurity.twoFa.blockedDetail",values:{names:xt},components:[e.jsx("strong",{})],defaults:"They do not have 2FA enabled: {{names}}. Direct them to <0>Settings → Security</0>."})]})]}):e.jsxs("div",{className:"flex items-start gap-2 text-xs text-green-700 dark:text-green-400 bg-green-50 dark:bg-green-900/20 rounded-lg p-3 border border-green-200 dark:border-green-700",children:[e.jsx(ct,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),e.jsxs("span",{children:[e.jsx("strong",{children:r("orgSecurity.twoFa.allCompliantHeadline","All members are compliant.")})," ",r("orgSecurity.twoFa.allCompliantDetail","Everyone in this org has 2FA enabled.")]})]}),e.jsx("p",{className:"text-[11px] text-gray-400 dark:text-gray-500",children:r("orgSecurity.twoFa.enforcementNote","Note: platform super-admins bypass this restriction. Enabling this does not automatically set up 2FA, each member must scan a QR code in their Security Settings.")})]}):e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:Oe.length>0?r("orgSecurity.twoFa.notEnforcedSummary",{amount:Oe.length,count:X,defaultValue_one:"{{amount}} of {{count}} member hasn't enabled 2FA yet. Enabling enforcement will immediately block them.",defaultValue_other:"{{amount}} of {{count}} members haven't enabled 2FA yet. Enabling enforcement will immediately block them."}):r("orgSecurity.twoFa.notEnforcedSafe","All current members have 2FA enabled, safe to enforce.")}),He&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-gray-200 dark:border-gray-700/50",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white mb-0.5",children:r("orgSecurity.ssoTrust.title","Trust IdP MFA for SSO sessions")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r("orgSecurity.ssoTrust.description","When on, SSO users whose IdP (Entra, Okta, etc.) attested MFA satisfy this requirement without also enrolling Onplana TOTP. Off = require local TOTP regardless of IdP MFA (paranoid posture, may cause double-MFA UX).")})]}),e.jsx(ur,{checked:Et,onChange:()=>ve.mutate(!Et),disabled:ve.isPending||Re.isLoading,title:Et?r("orgSecurity.ssoTrust.toggleDisable","Disable IdP MFA trust"):r("orgSecurity.ssoTrust.toggleEnable","Enable IdP MFA trust")})]}),e.jsxs("p",{className:"mt-2 text-[11px] text-gray-400 dark:text-gray-500",children:[r("orgSecurity.ssoTrust.detectionNotePrefix","Detected via OIDC")," ",e.jsx("code",{className:"font-mono",children:"amr"})," ",r("orgSecurity.ssoTrust.detectionNoteMiddle","claim or SAML")," ",e.jsx("code",{className:"font-mono",children:"AuthnContextClassRef"}),"."," ",r("orgSecurity.ssoTrust.detectionNoteSuffix","Per-session, new SSO logins are checked individually.")]})]})]})]}),pe&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-md w-full",ref:Me,role:"dialog","aria-modal":"true","aria-labelledby":"two-fa-confirm-title",children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 border-b border-gray-200 dark:border-gray-700",children:[e.jsx("div",{className:"w-9 h-9 rounded-full bg-amber-100 dar
22k:bg-amber-900/40 flex items-center justify-center flex-shrink-0",children:e.jsx(je,{className:"w-5 h-5 text-amber-600 dark:text-amber-400"})}),e.jsx("h3",{id:"two-fa-confirm-title",className:"text-base font-semibold text-gray-900 dark:text-white",children:r("orgSecurity.twoFaModal.title","Enable 2FA Enforcement?")})]}),e.jsxs("div",{className:"px-5 py-4 space-y-3",children:[e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:e.jsx(Ht,{i18nKey:"orgSecurity.twoFaModal.intro",count:Oe.length,components:[e.jsx("strong",{className:"text-red-600 dark:text-red-400"})],defaults:"The following {{count}} members will be <0>immediately blocked</0> from accessing this organization until they set up 2FA:"})}),e.jsx("div",{className:"max-h-40 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700 divide-y divide-gray-100 dark:divide-gray-700",children:Oe.map(m=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-gray-200 dark:bg-gray-600 flex items-center justify-center text-xs font-semibold text-gray-600 dark:text-gray-300 flex-shrink-0",children:m.name.charAt(0).toUpperCase()}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-900 dark:text-white truncate",children:[m.name,m.userId===(y==null?void 0:y.id)&&e.jsx("span",{className:"ms-1.5 text-[10px] font-bold text-indigo-500 bg-indigo-50 dark:bg-indigo-900/30 px-1.5 py-0.5 rounded-full",children:r("orgSecurity.twoFaModal.youBadge","you")})]}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:m.email})]}),e.jsx("span",{className:"ms-auto text-xs font-medium text-gray-500 dark:text-gray-400 flex-shrink-0",children:Xa(r,m.orgRole)})]},m.userId))}),jt&&e.jsxs("div",{className:"flex items-start gap-2 text-xs text-red-700 dark:text-red-400 bg-red-50 dark:bg-red-900/20 rounded-lg p-3 border border-red-200 dark:border-red-700",children:[e.jsx(je,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),e.jsxs("span",{children:[e.jsx("strong",{children:r("orgSecurity.twoFaModal.includesYouHeadline","This includes you.")})," ",r("orgSecurity.twoFaModal.includesYouPrefix","You will also be blocked until you enable 2FA in")," ",e.jsx("a",{href:"/settings?tab=security",className:"underline font-semibold",children:r("orgSecurity.twoFa.settingsSecurityPath","Settings → Security")}),"."," ",r("orgSecurity.twoFaModal.includesYouSuffix","Set up 2FA first before enabling enforcement.")]})]}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:r("orgSecurity.twoFaModal.note","Enforcement does not enable 2FA automatically, each member must set it up themselves by scanning a QR code with an authenticator app.")})]}),e.jsxs("div",{className:"flex gap-2 justify-end px-5 py-4 border-t border-gray-200 dark:border-gray-700",children:[e.jsx("button",{onClick:()=>le(!1),className:"btn-secondary",children:r("common.cancel","Cancel")}),e.jsx("button",{onClick:()=>Te.mutate(!0),disabled:Te.isPending,className:"btn-danger flex items-center gap-1.5 disabled:opacity-50",children:Te.isPending?r("orgSecurity.twoFaModal.enabling","Enabling..."):r("orgSecurity.twoFaModal.confirmButton",{count:Oe.length,defaultValue_one:"Enable & Block {{count}} Member",defaultValue_other:"Enable & Block {{count}} Members"})})]})]})}),te&&e.jsxs(Bt,{id:"ip",collapsed:j,toggle:J,children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 bg-emerald-50 dark:bg-emerald-950/40 border-s-4 border-s-emerald-500 rounded-t-xl transition-colors",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-emerald-100 dark:bg-emerald-900/40 flex items-center justify-center flex-shrink-0",children:e.jsx(gr,{className:"w-4 h-4 text-emerald-600 dark:text-emerald-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:r("orgSecurity.ipAllowlist.title","IP Allowlist")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r("orgSecurity.ipAllowlist.subtitle","Restrict org access to specific IPs or CIDR ranges. Leave empty to allow all IPs.")})]}),!Na&&!Ie.isLoading&&e.jsxs("span",{className:"flex items-center gap-1 text-xs font-medium text-amber-600 dar
22k:text-amber-400 bg-amber-50 dark:bg-amber-900/30 px-2 py-1 rounded-full border border-amber-200 dark:border-amber-700",children:[e.jsx(ke,{className:"w-3 h-3"})," ",r("orgSecurity.ipAllowlist.enterprisePlusBadge","ENTERPRISE+")]}),Na&&at.length>0&&e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400",children:r("orgSecurity.ipAllowlist.ruleCount",{count:at.length,defaultValue_one:"{{count}} rule",defaultValue_other:"{{count}} rules"})})]}),e.jsx("div",{className:"px-5 py-4 space-y-3 border-t border-gray-100 dark:border-gray-700/50",children:!Na&&!Ie.isLoading?e.jsxs("div",{className:"flex items-start gap-3 py-2",children:[e.jsx(ke,{className:"w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:[r("orgSecurity.ipAllowlist.lockedPrefix","IP allowlist enforcement requires the")," ",e.jsx("strong",{children:r("orgSecurity.ipAllowlist.enterprisePlanName","ENTERPRISE")})," ",r("orgSecurity.ipAllowlist.lockedSuffix","plan or above.")]}),e.jsx("a",{href:"/org/settings?tab=billing",className:"text-xs text-indigo-500 hover:underline mt-0.5 inline-block",children:r("orgSecurity.ipAllowlist.upgradeLink","Upgrade plan →")})]})]}):e.jsxs(e.Fragment,{children:[Ie.isLoading?e.jsx("div",{className:"py-1 space-y-1",children:e.jsx(oe,{className:"h-4 rounded w-full",rows:2})}):at.length===0?e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 italic py-1",children:r("orgSecurity.ipAllowlist.emptyState","No IP restrictions, all IPs can access this organization.")}):e.jsx("div",{className:"flex flex-wrap gap-2",children:at.map(m=>e.jsxs("span",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-indigo-50 dark:bg-indigo-900/30 border border-indigo-200 dark:border-indigo-700 rounded-full text-xs font-mono text-indigo-700 dark:text-indigo-300",children:[m,e.jsx("button",{onClick:()=>Be(m),disabled:Xe.isPending,className:"text-indigo-400 hover:text-red-500 dark:hover:text-red-400 transition-colors disabled:opacity-40",title:r("orgSecurity.ipAllowlist.removeIp","Remove"),"aria-label":r("orgSecurity.ipAllowlist.removeIpAria","Remove {{ip}} from the allowlist",{ip:m}),children:e.jsx(Qa,{className:"w-3.5 h-3.5"})})]},m))}),e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{ref:vt,type:"text",value:fe,onChange:m=>{Fe(m.target.value),ut("")},onKeyDown:m=>m.key==="Enter"&&ht(),placeholder:r("orgSecurity.ipAllowlist.inputPlaceholder","203.0.113.5 or 10.0.0.0/8"),"aria-label":r("orgSecurity.ipAllowlist.inputAriaLabel","IP address or CIDR range"),className:`input w-full font-mono text-sm ${tt?"border-red-400 focus:ring-red-400":""}`,disabled:Xe.isPending}),tt&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:tt})]}),e.jsxs("button",{onClick:ht,disabled:Xe.isPending||!fe.trim(),className:"btn-primary flex items-center gap-1.5 whitespace-nowrap disabled:opacity-50",children:[e.jsx(st,{className:"w-3.5 h-3.5"})," ",r("orgSecurity.ipAllowlist.addIp","Add IP")]})]}),pt&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-gray-600 dark:text-gray-300",children:[e.jsx("span",{children:r("orgSecurity.ipAllowlist.yourIp","Your current IP address")}),e.jsx("code",{className:"font-mono bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 px-1.5 py-0.5 rounded",children:pt}),aa&&e.jsx("button",{type:"button",onClick:as,disabled:Xe.isPending,className:"text-indigo-600 dark:text-indigo-400 hover:underline disabled:opacity-50",children:r("orgSecurity.ipAllowlist.addMyIp","Add my IP")})]}),e.jsxs("p",{className:"text-[11px] text-gray-400 dark:text-gray-500 leading-relaxed",children:[r("orgSecurity.ipAllowlist.hintAcceptsIpv4","Accepts IPv4 addresses")," (",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 rounded",children:"203.0.113.5"}),"),"," ",r("orgSecurity.ipAllowlist.hintCidrRanges","CIDR ranges")," (",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 rounded",children:"10.0.0.0/8"}),"),"," ",r("orgSecurity.ipAllowlist.hintIpv6Bypass","or IPv6 addresses. SUPER_ADMIN accounts bypass this restriction.")," ",r("orgSecurity.ipAllowlist.hintPress","Press")," ",e.jsx("kbd",{className:"bg-gray-100 dark:bg-gray-700 px-1 rounded text-[10px]",children:r("orgSecurity.ipAllowlist.enterKey","Enter")})," ",r("orgSecurity.ipAllowlist.hintToAdd","to add.")]})]})})]}),e.jsxs(Bt,{id:"retention",collapsed:j,toggle:J,children:[e.jsx(Tl,{data:Ke.data??null,loading:Ke.isLoading}),e.jsx(Rl,{data:Ke.data??null,loading:Ke.isLoading,preset:rt,notes:Ca,customOrgDays:Nt,customAuditDays:Aa,customUserDays:ss,saving:zt.isPending,onPresetChange:m=>{wa(m),nt(!0)},onNotesChange:m=>{sa(m),nt(!0)},onCustomOrgDays:m=>{ra(m),nt(!0)},onCustomAuditDays:m=>{Pt(m),nt(!0)},onCustomUserDays:m=>{Ea(m),nt(!0)},onSave:()=>zt.mutate()})]}),e.jsx("div",{className:"md:col-span-2 xl:col-span-3",children:e.jsx(Qs,{label:r("orgSecurity.section.policies","Policies")})}),e.jsx(jl,{policy:Pa,dirty:Ta,saving:Ra.isPending,loading:Re.isLoading,collapsed:j,toggle:J,onChange:(m,D)=>{na(W=>({...W,[m]:D})),St(!0)},onSave:()=>Ra.mutate(Pa)}),e.jsx(wl,{policy:Rs,dirty:Ma,saving:ia.isPending,loading:Re.isLoading,collapsed:j,toggle:J,onChange:(m,D)=>{Qt(W=>({...W,[m]:D})),rs(!0)},onSave:()=>ia.mutate(Rs),onForceLogoutAll:Tt,isOwner:p}),Z&&e.jsxs(Bt,{id:"scim",collapsed:j,toggle:J,children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 bg-sky-50 dark:bg-sky-950/40 border-s-4 border-s-sky-500 rounded-t-xl transition-colors",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-sky-100 dark:bg-sky-900/40 flex items-center justify-center flex-shrink-0",children:e.jsx(vr,{className:"w-4 h-4 text-sky-600 dark:text-sky-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:r("orgSecurity.scim.title","SCIM Provisioning")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r("orgSecurity.scim.subt
22itle","Automate user provisioning and deprovisioning via SCIM 2.0 (Azure AD, Okta, Google Workspace).")})]}),C?s?e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300 flex-shrink-0",children:[e.jsx(ct,{className:"w-3 h-3"})," ",r("orgSecurity.scim.badgeEnabled","Enabled")]}):e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400 flex-shrink-0",children:r("orgSecurity.scim.badgeNotConfigured","Not configured")}):e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300 flex-shrink-0",children:[e.jsx(ke,{className:"w-3 h-3"})," ",r("orgSecurity.scim.badgeEnterprise","Enterprise")]})]}),e.jsx("div",{className:"px-5 py-4 space-y-4 border-t border-gray-100 dark:border-gray-700/50",children:C?e.jsxs("div",{className:"space-y-4",children:[a&&(()=>{const m=`${bi||window.location.origin}/scim/v2/${a}`;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:r("orgSecurity.scim.endpointLabel","SCIM Endpoint URL")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{readOnly:!0,className:"input flex-1 font-mono text-xs","aria-label":r("orgSecurity.scim.endpointLabel","SCIM Endpoint URL"),value:m}),e.jsx("button",{className:"btn-secondary px-3",title:r("orgSecurity.scim.copyEndpoint","Copy endpoint URL"),"aria-label":r("orgSecurity.scim.copyEndpoint","Copy endpoint URL"),onClick:()=>{navigator.clipboard.writeText(m),k.success(r("orgSecurity.toast.endpointCopied","Endpoint URL copied"))},children:e.jsx(Gr,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"rounded-lg bg-indigo-50 dark:bg-indigo-900/10 border border-indigo-200 dark:border-indigo-700/40 p-3 text-xs",children:[e.jsx("p",{className:"font-semibold text-indigo-800 dark:text-indigo-300 mb-1.5",children:r("orgSecurity.scim.roleAssignmentTitle","Role assignment")}),e.jsxs("p",{className:"text-indigo-700 dark:text-indigo-400 mb-2",children:[e.jsx("span",{className:"font-semibold",children:r("orgSecurity.scim.recommendedLabel","Recommended:")})," ",r("orgSecurity.scim.recommendedPrefix","every SCIM user lands as a")," ",e.jsx("strong",{children:r("orgSecurity.scim.memberRoleName","MEMBER")})," ",r("orgSecurity.scim.recommendedSuffix","by default. Leave role mapping unconfigured in your IdP and promote individuals to MANAGER or ADMIN from the People page when needed.")]}),e.jsx("p",{className:"text-indigo-700 dark:text-indigo-400 mb-2",children:r("orgSecurity.scim.idpDrivenIntro","For IdP-driven roles instead, pick one:")}),e.jsxs("ul",{className:"space-y-2 text-indigo-700 dark:text-indigo-400",children:[e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold",children:r("orgSecurity.scim.option1Label","Option 1, per-user attribute.")})," ",r("orgSecurity.scim.option1Prefix","Map your IdP's role attribute to"),e.jsx("code",{className:"mx-1 px-1 py-0.5 rounded bg-indigo-100 dark:bg-indigo-900/40 font-mono",children:"roles[primary eq true].value"}),r("orgSecurity.scim.option1Middle","with")," ",e.jsx("code",{className:"font-mono",children:"MEMBER"}),", ",e.jsx("code",{className:"font-mono",children:"MANAGER"}),", ",r("orgSecurity.scim.orWord","or")," ",e.jsx("code",{className:"font-mono",children:"ADMIN"}),"."," ",r("orgSecurity.scim.option1Suffix","Travels on the user resource, no groups required.")]}),e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold",children:r("orgSecurity.scim.option2Label","Option 2, group-based.")})," ",r("orgSecurity.scim.option2Prefix","Onplana exposes three SCIM groups; displayName must be exactly"),e.jsx("code",{className:"ms-1 font-mono",children:"Members"}),",",e.jsx("code",{className:"ms-1 font-mono",children:"Managers"}),", ",r("orgSecurity.scim.orWord","or"),e.jsx("code",{className:"ms-1 font-mono",children:"Admins"}),"."," ",r("orgSecurity.scim.option2Middle","Other names get HTTP 400. If your IdP groups use different names (e.g.")," ",e.jsx("code",{className:"font-mono",children:"Sales"}),", ",e.jsx("code",{className:"font-mono",children:"Engineering-EU"}),r("orgSecurity.scim.option2Rewrite","), rewrite")," ",e.jsx("code",{className:"font-mono",children:"displayName"})," ",r("orgSecurity.scim.option2Suffix","on the wire via mapping rules. No directory rename needed.")]})]})]})]})})(),ze&&e.jsxs("div",{className:"rounded-lg bg-yellow-50 dark:bg-yellow-900/10 border border-yellow-300 dark:border-yellow-700/50 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{className:"w-4 h-4 text-yellow-600 dark:text-yellow-400 shrink-0"}),e.jsx("p",{className:"text-sm font-semibold text-yellow-800 dark:text-yellow-300",children:ze.warning})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{readOnly:!0,className:"input flex-1 font-mono text-xs","aria-label":r("orgSecurity.scim.tokenAriaLabel","SCIM token"),value:ze.token}),e.jsx("button",{className:"btn-secondary px-3",title:r("orgSecurity.scim.copyToken","Copy token"),"aria-label":r("orgSecurity.scim.copyToken","Copy token"),onClick:()=>{navigator.clipboard.writeText(ze.token),k.success(r("orgSecurity.toast.tokenCopied","Token copied"))},children:e.jsx(Gr,{className:"w-4 h-4"})})]}),e.jsx("button",{className:"text-xs text-yellow-700 dark:text-yellow-400 hover:underline",onClick:()=>Ne(null),children:r("orgSecurity.scim.dismiss","Dismiss")})]}),l&&e.jsxs("div",{className:"flex gap-3 flex-wrap",children:[e.jsxs("button",{className:"btn-secondary flex items-center gap-2 text-sm",onClick:()=>Mt.mutate(),disabled:Mt.isPending,children:[e.jsx($n,{className:`w-4 h-4 ${Mt.isPending?"animate-spin":""}`}),s?r("orgSecurity.scim.rotateToken","Rotate Token"):r("orgSecurity.scim.generateToken","Generate Token")]}),s&&!it&&e.jsxs("button",{className:"btn-danger flex items-center gap-2 text-sm",onClick:()=>oa(!0),children:[e.jsx(dt,{className:"w-4 h-4"})," ",r("orgSecurity.scim.revokeToken","Revoke Token")]}),it&&e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-red-50 dark:bg-red-900/10 border border-red-200 dark:border-red-700/50",children:[e.jsx("span",{className:"text-sm text-red-700 dark:text-red-400",children:r("orgSecurity.scim.revokeConfirmMessage","This will disable all SCIM provisioning. Continue?")}),e.jsx("button",{className:"btn-danger text-xs px-3",onClick:()=>la.mutate(),disabled:la.isPending,children:la.isPending?r("orgSecurity.scim.revoking","Revoking..."):r("orgSecurity.scim.revokeConfirmYes","Yes, Revoke")}),e.jsx("button",{className:"btn-secondary text-xs px-3",onClick:()=>oa(!1),children:r("common.cancel","Cancel")})]})]})]}):e.jsxs("div",{className:"rounded-lg bg-amber-50 dark:bg-amber-900/10 border border-amber-200 dark:border-amber-700/50 p-4 flex items-start gap-3",children:[e.jsx(ke,{className:"w-4 h-4 text-amber-600 dar
22k:text-amber-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-amber-800 dark:text-amber-300 font-medium",children:r("orgSecurity.scim.lockedTitle","SCIM requires Enterprise plan")}),e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-400 mt-0.5",children:r("orgSecurity.scim.lockedSubtitle","Upgrade to enable automated user provisioning.")})]}),e.jsx("a",{href:"/org/settings?tab=billing",className:"btn-primary text-xs px-3 py-1 shrink-0",children:r("orgSecurity.scim.upgradeButton","Upgrade")})]})})]}),e.jsx("div",{className:"md:col-span-2 xl:col-span-3",children:e.jsx(Qs,{label:r("orgSecurity.section.apiTokensCompliance","API Tokens & Compliance")})}),e.jsx("div",{className:"md:col-span-2 xl:col-span-3",children:e.jsx(Al,{tokens:ns.data??[],loading:ns.isLoading,revokeTokenId:Fs,revoking:de.isPending,collapsed:j,toggle:J,onRevokeClick:Rt,onRevokeConfirm:m=>de.mutate(m),onRevokeCancel:()=>Rt(null)})}),e.jsx("div",{className:"md:col-span-2 xl:col-span-3",children:e.jsxs(Bt,{id:"compliance",collapsed:j,toggle:J,children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 bg-gray-100 dark:bg-gray-700/50 rounded-t-xl transition-colors",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-gray-200 dark:bg-gray-600 flex items-center justify-center flex-shrink-0",children:e.jsx(Kr,{className:"w-4 h-4 text-gray-600 dark:text-gray-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:r("orgSecurity.controlDetail.title","Control Detail")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r("orgSecurity.controlDetail.subtitle","Individual check results grouped by category.")})]}),he&&e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400",children:r("orgSecurity.controlDetail.checkCount",{count:he.pass+he.warn+he.fail,defaultValue_one:"{{count}} check",defaultValue_other:"{{count}} checks"})})]}),e.jsx("div",{className:"px-5 py-4 space-y-4 border-t border-gray-100 dark:border-gray-700/50",children:[...Ds.entries()].map(([m,D])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-widest mb-2.5",children:il(r,m)}
22),e.jsx("div",{className:`grid gap-2.5 ${D.length===1?"grid-cols-1 max-w-lg":"sm:grid-cols-2 xl:grid-cols-3"}`,children:D.map(W=>{const q=tl[W.status];return e.jsxs("div",{className:`flex gap-3 p-4 rounded-xl border ${q.bg} ${q.border}`,children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:q.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:mn(r,W)}),e.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded-full tracking-wide ${q.badge}`,children:rl(r,W.status)})]}),e.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 leading-relaxed",children:xn(r,W)})]})]},W.id)})})]},m))})]})})]})),h==="Health"&&e.jsx(el,{orgId:t}),h==="Access Review"&&e.jsxs("div",{className:"card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap px-5 py-4 border-b border-gray-100 dark:border-gray-700/50",children:[e.jsxs("div",{className:"relative flex-1 min-w-40 max-w-60",children:[e.jsx(Wi,{className:"absolute start-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none"}),e.jsx("input",{value:H,onChange:m=>{ge(m.target.value),ie(0)},placeholder:r("orgSecurity.accessReview.searchPlaceholder","Search members..."),"aria-label":r("orgSecurity.accessReview.searchPlaceholder","Search members..."),className:"input ps-8 py-1.5 text-sm w-full"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-400 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:Le,onChange:m=>{we(m.target.checked),ie(0)},className:"w-3.5 h-3.5 rounded border-gray-300 dark:border-gray-600 text-amber-500 focus:ring-amber-400"}),r("orgSecurity.accessReview.dormantOnly","Dormant only"),da>0&&e.jsx("span",{className:"text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-amber-100 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400",children:da})]}),mt&&e.jsx("div",{className:"inline-flex items-center gap-0.5 bg-gray-100 dark:bg-gray-800 p-1 rounded-lg",role:"group","aria-label":r("people.members.identityFilterLabel","Filter by identity type"),children:["humans","agents","all"].map(m=>{var Ee;const D=((Ee=re.data)==null?void 0:Ee.rows)??[],W=m==="humans"?D.filter(Ge=>!Ge.isAgentPersona).length:m==="agents"?D.filter(Ge=>Ge.isAgentPersona).length:D.length,q=m==="humans"?r("people.members.identity.humans","Humans"):m==="agents"?r("people.members.identity.agents","Agents"):r("people.members.filter.all","All");return e.jsxs("button",{type:"button","aria-pressed":Ue===m,onClick:()=>{Je(m),ie(0)},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${Ue===m?"bg-white dark:bg-gray-700 text-indigo-600 dark:text-indigo-400 shadow-sm":"text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"}`,children:[q," ",e.jsx("span",{className:"opacity-60",children:W})]},m)})}),e.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1 ms-auto",children:[e.jsx(ba,{className:"w-3.5 h-3.5"}),r("orgSecurity.accessReview.memberCount",{count:F.length,defaultValue_one:"{{count}} member",defaultValue_other:"{{count}} members"})]}),e.jsxs("a",{href:B.securityAuditExportUrl(t,{format:"csv"}),target:"_blank",rel:"noopener noreferrer",className:"btn-secondary flex items-center gap-1.5 text-xs py-1.5",children:[e.jsx(ta,{className:"w-3.5 h-3.5"})," ",r("orgSecurity.accessReview.exportAuditLog","Export audit log")]})]}),e.jsx("div",{className:"overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-50 dark:bg-gray-800/60 border-b border-gray-200 dark:border-gray-700",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2.5 text-start",children:e.jsxs("button",{onClick:()=>ue("name"),className:"flex items-center gap-1 text-xs font-semibold text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white",children:[r("orgSecurity.accessReview.colMember","Member"),_==="name"?ne?e.jsx(Bs,{className:"w-3 h-3"}):e.jsx(gt,{className:"w-3 h-3"}):null]})}),e.jsx("th",{className:"px-4 py-2.5 text-start",children:e.jsxs("button",{onClick:()=>ue("role"),className:"flex items-center gap-1 text-xs font-semibold text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white",children:[r("orgSecurity.accessReview.colRole","Role"),_==="role"?ne?e.jsx(Bs,{className:"w-3 h-3"}):e.jsx(gt,{className:"w-3 h-3"}):null]})}),e.jsx("th",{className:"px-4 py-2.5 text-start text-xs font-semibold text-gray-600 dark:text-gray-400",children:r("orgSecurity.accessReview.colTwoFa","2FA")}),e.jsx("th",{className:"px-4 py-2.5 text-start",children:e.jsxs("button",{onClick:()=>ue("lastLogin"),className:"flex items-center gap-1 text-xs font-semibold text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white",children:[r("orgSecurity.accessReview.colLastLogin","Last Login"),_==="lastLogin"?ne?e.jsx(Bs,{className:"w-3 h-3"}):e.jsx(gt,{className:"w-3 h-3"}):null]})}),e.jsx("th",{className:"px-4 py-2.5 text-start text-xs font-semibold text-gray-600 dark:text-gray-400",children:r("orgSecurity.accessReview.colIp","IP")}),e.jsx("th",{className:"px-4 py-2.5 text-start text-xs font-semibold text-gray-600 dark:text-gray-400",children:r("orgSecurity.accessReview.colStatus","Status")}),e.jsx("th",{className:"px-4 py-2.5 text-end text-xs font-semibold text-gray-600 dark:text-gray-400",children:r("orgSecurity.accessReview.colActions","Actions")})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700/60",children:re.isLoading?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-4",children:e.jsx(oe,{className:"h-8 rounded w-full",rows:4})})}):F.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-8 text-center text-sm text-gray-400",children:r("orgSecurity.accessReview.emptyState","No members found")})}):(()=>{const D=Math.ceil(F.length/20),W=Math.min(T,Math.max(0,D-1));return F.slice(W*20,(W+1)*20).map(q=>{const Ee=q.lastLoginAt&&new Date(q.lastLoginAt)<Pe;return e.jsxs("tr",{className:`hover:bg-gray-50 dark:hover:bg-gray-800/40 ${Ee?"bg-amber-50/50 dark:bg-amber-900/10":""}`,children:[e.jsxs("td",{className:"px-4 py-2.5",children:[e.jsx("p",{className:"font-medium text-gray-900 dark:text-white text-sm",children:q.name}),e.jsx("p",{className:"text-xs text-gray-400",children:q.email})]}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${q.orgRole==="OWNER"?"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300":q.orgRole==="ADMIN"?"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300":q.orgRole==="MANAGER"?"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300":q.orgRole==="GUEST"?"bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300":"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300"}`,children:Xa(r,q.orgRole)})}),e.jsx("td",{className:"px-4 py-2.5",children:q.isAgentPersona?e.jsxs("span",{className:"flex items-center gap-1 text-xs text-gray-400 dark:text-gray-500",title:r("orgSecurity.accessReview.agentTwoFaTooltip","Agent service accounts authenticate via PAT/MCP, 2FA does not apply"),children:[e.jsx(Es,{className:"w-3.5 h-3.5"})," ",r("orgSecurity.accessReview.twoFaNotApplicable","N/A")]}):q.twoFaEnabled?e.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-600 dark:text-green-400 font-medium",children:[e.jsx(ct,{className:"w-3.5 h-3.5"})," ",r("orgSecurity.accessReview.twoFaOn","On")]}):e.jsxs("span",{className:"flex items-center gap-1 text-xs text-amber-600 dar
22k:text-amber-400",children:[e.jsx(je,{className:"w-3.5 h-3.5"})," ",r("orgSecurity.accessReview.twoFaOff","Off")]})}),e.jsx("td",{className:"px-4 py-2.5 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap",children:q.lastLoginAt?Wa(new Date(q.lastLoginAt),"MMM d, yyyy"):e.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:r("orgSecurity.accessReview.never","Never")})}),e.jsx("td",{className:"px-4 py-2.5 text-xs text-gray-400 font-mono",children:q.lastLoginIp??"-"}),e.jsx("td",{className:"px-4 py-2.5",children:Ee?e.jsx("span",{className:"text-[10px] font-bold text-amber-600 dark:text-amber-400 bg-amber-100 dark:bg-amber-900/30 px-1.5 py-0.5 rounded-full",children:r("orgSecurity.accessReview.statusDormant","DORMANT")}):q.isActive?e.jsx("span",{className:"text-[10px] font-medium text-green-600 dark:text-green-400",children:r("orgSecurity.accessReview.statusActive","Active")}):e.jsx("span",{className:"text-[10px] font-medium text-gray-400",children:r("orgSecurity.accessReview.statusInactive","Inactive")})}),e.jsx("td",{className:"px-4 py-2.5 text-end",children:(()=>{const Ge=!!q.isAgentPersona,wt=q.userId===(y==null?void 0:y.id),Lt=!q.twoFaEnabled,Ot=q.otherOrgCount>0,qa=q.orgRole==="OWNER"&&!p,qe=Ge||wt||Lt||Ot||qa,be=Ge?r("orgSecurity.resetTwoFa.reasonAgent","Agent service accounts do not use 2FA"):wt?r("orgSecurity.resetTwoFa.reasonSelf","Use Settings → Security to manage your own 2FA"):Lt?r("orgSecurity.resetTwoFa.reasonNoTwoFa","User does not have 2FA enabled"):Ot?r("orgSecurity.resetTwoFa.reasonCrossOrg",{count:q.otherOrgCount,defaultValue_one:"User is in {{count}} other org, contact platform support for cross-org reset",defaultValue_other:"User is in {{count}} other orgs, contact platform support for cross-org reset"}):qa?r("orgSecurity.resetTwoFa.reasonOwnerLockout","Only an org OWNER can reset another OWNER's 2FA"):r("orgSecurity.resetTwoFa.reasonDefault","Reset 2FA for {{name}}",{name:q.name});return e.jsx("button",{disabled:qe||M.isPending,title:be,"aria-label":r("orgSecurity.resetTwoFa.buttonAria","Reset 2FA for {{name}}",{name:q.name}),className:"p-1.5 text-gray-400 hover:text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded transition-colors disabled:opacity-30 disabled:cursor-not-allowed",onClick:()=>P({title:r("orgSecurity.resetTwoFa.confirmTitle",'Reset 2FA for "{{name}}"?',{name:q.name}),message:r("orgSecurity.resetTwoFa.confirmMessage","Their TOTP device + backup codes will be wiped. They'll be emailed instructions to re-enroll. Use this for users who lost their authenticator AND don't have a working backup code."),variant:"danger",confirmLabel:r("orgSecurity.resetTwoFa.confirmLabel","Reset 2FA"),onOk:()=>M.mutate(q.userId)}),children:e.jsx(kt,{className:"w-4 h-4"})})})()})]},q.userId)})})()})]})})}),(()=>{const D=Math.ceil(F.length/20);if(D<=1)return null;const W=Math.min(T,Math.max(0,D-1));return e.jsxs("div",{className:"flex items-center justify-between text-sm text-gray-600 dark:text-gray-400 px-5 py-3 border-t border-gray-100 dark:border-gray-700/50",children:[e.jsx("button",{onClick:()=>ie(q=>Math.max(0,q-1)),disabled:W===0,className:"px-3 py-1.5 rounded border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 disabled:opacity-40 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:cursor-not-allowed",children:r("orgSecurity.pagination.previous","← Previous")}),e.jsx("span",{children:r("orgSecurity.pagination.pageStatus","Page {{page}} / {{totalPages}} ({{amount}} members)",{page:W+1,totalPages:D,amount:F.length})}),e.jsx("button",{onClick:()=>ie(q=>Math.min(D-1,q+1)),disabled:W>=D-1,className:"px-3 py-1.5 rounded border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 disabled:opacity-40 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:cursor-not-allowed",children:r("orgSecurity.pagination.next","Next →")})]})})()]}),h==="Security Events"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:r("orgSecurity.events.periodLabel","Period:")}),[7,14,30,90].map(m=>e.jsx("button",{onClick:()=>O(m),className:`px-3 py-1 text-sm rounded-lg border transition-colors ${me===m?"bg-indigo-50 dark:bg-indigo-900/30 border-indigo-300 dark:border-indigo-700 text-indigo-600 dark:text-indigo-400":"border-gray-200 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-gray-300"}`,children:r("orgSecurity.events.periodOption","{{days}}d",{days:m})},m))]}),Ce.isLoading?e.jsxs("div",{className:"space-y-4",children:[e.jsx(oe,{className:"h-32 rounded-lg w-full"}),e.jsx(oe,{className:"h-48 rounded-lg w-full"})]}):Ce.data?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"card p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"w-4 h-4 text-red-500"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:r("orgSecurity.events.failedLoginsTitle","Failed Login Attempts (targeting your members)")}),Ce.data.failedLogins.total>50&&e.jsx("span",{className:"text-[10px] bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 px-1.5 py-0.5 rounded-full font-bold",children:r("orgSecurity.events.elevatedBadge","ELEVATED")})]}),e.jsx("span",{className:"text-xl font-bold text-gray-900 dark:text-white",children:Ce.data.failedLogins.total})]}),e.jsx(ml,{data:Ce.data.failedLogins.dailyCounts}),Ce.data.failedLogins.total>0&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4 mt-3 pt-3 border-t border-gray-100 dark:border-gray-700",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-400 uppercase mb-1.5",children:r("orgSecurity.events.targetedAccounts","Targeted accounts")}
22),Ce.data.failedLogins.topEmails.map(m=>e.jsxs("div",{className:"flex justify-between text-xs py-0.5",children:[e.jsx("span",{className:"text-gray-700 dark:text-gray-300 truncate max-w-[160px]",children:m.email}),e.jsxs("span",{className:"text-red-500 font-semibold ms-2",children:[m.count,"×"]})]},m.email))]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-400 uppercase mb-1.5",children:r("orgSecurity.events.sourceIps","Source IPs")}),Ce.data.failedLogins.topIPs.map(m=>e.jsxs("div",{className:"flex justify-between text-xs py-0.5",children:[e.jsx("span",{className:"text-gray-700 dark:text-gray-300 font-mono",children:m.ip}),e.jsxs("span",{className:"text-red-500 font-semibold ms-2",children:[m.count,"×"]})]},m.ip))]})]}),Ce.data.failedLogins.total===0&&e.jsx("p",{className:"text-xs text-gray-400 mt-2",children:r("orgSecurity.events.noFailedLogins","No failed login attempts in this period.")})]}),e.jsxs("div",{className:"card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-gray-100 dark:border-gray-700",children:[e.jsx(jr,{className:"w-4 h-4 text-indigo-500"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:r("orgSecurity.events.accessControlTitle","Access Control Events")}),e.jsx("span",{className:"text-xs text-gray-400 ms-auto",children:r("orgSecurity.events.eventCount",{count:Ce.data.orgEvents.length,defaultValue_one:"{{count}} event",defaultValue_other:"{{count}} events"})})]}),e.jsx("div",{className:"divide-y divide-gray-100 dark:divide-gray-700",children:Ce.data.orgEvents.length===0?e.jsx("p",{className:"px-4 py-6 text-xs text-gray-400 text-center",children:r("orgSecurity.events.noAccessControlEvents","No access control events in this period.")}):Ce.data.orgEvents.map(m=>e.jsxs("div",{className:"flex items-start gap-3 px-4 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-800/40",children:[e.jsx("span",{className:`mt-0.5 text-[10px] font-mono font-semibold px-1.5 py-0.5 rounded flex-shrink-0 ${m.action==="ORG_MEMBER_REMOVED"?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":m.action==="PERMISSION_POLICY_UPDATED"?"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400":"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400"}`,children:m.action.replace(/_/g," ")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("span",{className:"text-xs text-gray-700 dark:text-gray-300",children:[r("orgSecurity.events.byPrefix","by")," "]}),e.jsx("span",{className:"text-xs font-medium text-gray-900 dark:text-white",children:m.userEmail}),m.details&&e.jsxs("span",{className:"text-xs text-gray-400 ms-1",children:["· ",typeof m.details=="object"?JSON.stringify(m.details).slice(0,60):String(m.details)]})]}),e.jsxs("span",{className:"text-[10px] text-gray-400 whitespace-nowrap flex items-center gap-1 flex-shrink-0",children:[e.jsx(Gt,{className:"w-3 h-3"}),Wa(new Date(m.createdAt),"MMM d, HH:mm")]})]},m.id))})]})]}):null]}),h==="Audit Export"&&!A&&e.jsx("div",{className:"card p-6 max-w-lg",children:e.jsx(lr,{featureKey:"auditLogs",compact:!0})}),h==="Audit Export"&&A&&e.jsxs("div",{className:"card p-6 max-w-lg",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-5",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-indigo-100 dark:bg-indigo-900/40 flex items-center justify-center flex-shrink-0",children:e.jsx(ta,{className:"w-5 h-5 text-indigo-600 dark:text-indigo-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 dark:text-white",children:r("orgSecurity.auditExport.title","Export Audit Log")}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:r("orgSecurity.auditExport.subtitle","Download a complete audit trail for compliance reviews and security audits.")})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:r("orgSecurity.auditExport.from","From")}),e.jsx("input",{type:"date",value:is,onChange:m=>Da(m.target.value),"aria-label":r("orgSecurity.auditExport.from","From"),className:"input text-sm w-full"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1",children:r("orgSecurity.auditExport.to","To")}),e.jsx("input",{type:"date",value:ot,onChange:m=>os(m.target.value),"aria-label":r("orgSecurity.auditExport.to","To"),className:"input text-sm w-full"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1.5",children:r("orgSecurity.auditExport.format","Format")}),e.jsx("div",{className:"flex gap-2",children:["csv","json"].map(m=>e.jsx("button",{onClick:()=>Fa(m),className:`px-4 py-1.5 text-sm rounded-lg border transition-colors ${Yt===m?"bg-indigo-50 dark:bg-indigo-900/30 border-indigo-300 dark:border-indigo-700 text-indigo-600 dark:text-indigo-400":"border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:border-gray-300"}`,children:m.toUpperCase()},m))})]}),e.jsxs("a",{href:Jt,target:"_blank",rel:"noopener noreferrer",className:"btn-primary flex items-center justify-center gap-2 w-full",children:[e.jsx(ta,{className:"w-4 h-4"})," ",r("orgSecurity.auditExport.downloadButton","Download {{format}}",{format:Yt.toUpperCase()})]}),e.jsxs("div",{className:"rounded-lg bg-gray-50 dark:bg-gray-800/50 border border-gray-100 dark:border-gray-700/50 p-3.5 space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5",children:r("orgSecurity.auditExport.detailsTitle","Export details")}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:r("orgSecurity.auditExport.detailsIncludes","Includes: timestamp, user, action, resource, IP address, change details")}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:r("orgSecurity.auditExport.detailsScope","Scoped to this organization only, no cross-org data")}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:r("orgSecurity.auditExport.detailsLimits","Maximum 50,000 rows per export. All times in UTC.")})]})]})]}),z]})}function Qs({label:t}){return e.jsxs("div",{className:"flex items-center gap-3 pt-3 pb-1",children:[e.jsx("div",{className:"flex-1 h-px bg-gradient-to-r from-gray-200 dark:from-gray-700 to-transparent"}),e.jsx("span",{className:"text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider whitespace-nowrap",children:t}),e.jsx("div",{className:"flex-1 h-px bg-gradient-to-l from-gray-200 dark:from-gray-700 to-transparent"})]})}const yl=[8,10,12,14,16,20,24,32],fl=[0,30,60,90,180],kl=["requireUppercase","requireNumbers","requireSpecialChars"];function jl({policy:t,dirty:a,saving:s,loading:l,collapsed:i,toggle:c,onChange:r,onSave:o}){const{t:x}=Q();return e.jsxs(Bt,{id:"pwPolicy",collapsed:i,toggle:c,children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 bg-orange-50 dark:bg-orange-950/40 border-s-4 border-s-orange-500 rounded-t-xl transition-colors",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-orange-100 dar
22k:bg-orange-900/40 flex items-center justify-center flex-shrink-0",children:e.jsx(ke,{className:"w-4 h-4 text-orange-600 dark:text-orange-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:x("orgSecurity.passwordPolicy.title","Password Policy")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:x("orgSecurity.passwordPolicy.subtitle","Set minimum password complexity requirements for all organization members.")})]}),a&&e.jsx("span",{className:"text-[10px] font-medium px-2 py-0.5 rounded-full bg-amber-100 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400",children:x("orgSecurity.common.unsaved","Unsaved")})]}),e.jsx("div",{className:"px-5 py-4 space-y-4 border-t border-gray-100 dark:border-gray-700/50",children:l?e.jsx(oe,{className:"h-20 rounded w-full"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:x("orgSecurity.passwordPolicy.minLength","Minimum Length")}),e.jsx("select",{value:t.minLength,onChange:d=>r("minLength",Number(d.target.value)),"aria-label":x("orgSecurity.passwordPolicy.minLength","Minimum Length"),className:"input w-full text-sm",children:yl.map(d=>e.jsx("option",{value:d,children:x("orgSecurity.passwordPolicy.charactersOption",{count:d,defaultValue_one:"{{count}} character",defaultValue_other:"{{count}} characters"})},d))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:x("orgSecurity.passwordPolicy.expiryLabel","Password Expiry")}),e.jsx("select",{value:t.maxAgeDays,onChange:d=>r("maxAgeDays",Number(d.target.value)),"aria-label":x("orgSecurity.passwordPolicy.expiryLabel","Password Expiry"),className:"input w-full text-sm",children:fl.map(d=>e.jsx("option",{value:d,children:ol(x,d)},d))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-medium text-gray-600 dark:text-gray-400",children:x("orgSecurity.passwordPolicy.complexityTitle","Complexity Requirements")}),kl.map(d=>{const u=ll(x,d);return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:u}),e.jsx(ur,{checked:t[d],onChange:()=>r(d,!t[d]),title:u})]},d)})]}),a&&e.jsx("div",{className:"flex justify-end pt-1",children:e.jsx("button",{onClick:o,disabled:s,className:"btn-primary flex items-center gap-1.5 disabled:opacity-50",children:s?x("orgSecurity.common.saving","Saving..."):x("orgSecurity.common.savePolicy","Save Policy")})})]})})]})}const vl=[1,4,8,24,72,168,336,720],Nl=[0,15,30,60,120],Sl=[0,7,14,30,60];function wl({policy:t,dirty:a,saving:s,loading:l,collapsed:i,toggle:c,onChange:r,onSave:o,onForceLogoutAll:x,isOwner:d}){const{t:u}=Q();return e.jsxs(Bt,{id:"sessPolicy",collapsed:i,toggle:c,children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 bg-cyan-50 dark:bg-cyan-950/40 border-s-4 border-s-cyan-500 rounded-t-xl transition-colors",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-cyan-100 dark:bg-cyan-900/40 flex items-center justify-center flex-shrink-0",children:e.jsx(Gt,{className:"w-4 h-4 text-cyan-600 dark:text-cyan-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:u("orgSecurity.sessionPolicy.title","Session Policy")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:u("orgSecurity.sessionPolicy.subtitle","Control how long sessions last and when idle users are automatically logged out.")})]}),a&&e.jsx("span",{className:"text-[10px] font-medium px-2 py-0.5 rounded-full bg-amber-100 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400",children:u("orgSecurity.common.unsaved","Unsaved")})]}),e.jsx("div",{className:"px-5 py-4 space-y-4 border-t border-gray-100 dark:border-gray-700/50",children:l?e.jsx(oe,{className:"h-16 rounded w-full"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:u("orgSecurity.sessionPolicy.durationLabel","Session Duration")}),e.jsx("select",{value:t.sessionTimeoutHours,onChange:h=>r("sessionTimeoutHours",Number(h.target.value)),"aria-label":u("orgSecurity.sessionPolicy.durationLabel","Session Duration"),className:"input w-full text-sm",children:vl.map(h=>e.jsx("option",{value:h,children:dl(u,h)},h))}),e.jsx("p",{className:"text-[11px] text-gray-400 mt-1",children:u("orgSecurity.sessionPolicy.durationHint","Users must re-login after this period regardless of activity.")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:u("orgSecurity.sessionPolicy.idleLabel","Idle Timeout")}),e.jsx("select",{value:t.idleTimeoutMinutes,onChange:h=>r("idleTimeoutMinutes",Number(h.target.value)),"aria-label":u("orgSecurity.sessionPolicy.idleLabel","Idle Timeout"),className:"input w-full text-sm",children:Nl.map(h=>e.jsx("option",{value:h,children:cl(u,h)},h))}),e.jsx("p",{className:"text-[11px] text-gray-400 mt-1",children:u("orgSecurity.sessionPolicy.idleHint","Auto-logout after this period of inactivity. 0 = disabled.")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:u("orgSecurity.sessionPolicy.oauthTtlLabel","Connected App Tokens")}),e.jsx("select",{value:t.oauthTokenTtlDays??0,onChange:h=>r("oauthTokenTtlDays",Number(h.target.value)),"aria-label":u("orgSecurity.sessionPolicy.oauthTtlLabel","Connected App Tokens"),className:"input w-full text-sm",children:Sl.map(h=>e.jsx("option",{value:h,children:gl(u,h)},h))}),e.jsx("p",{className:"text-[11px] text-gray-400 mt-1",children:u("orgSecurity.sessionPolicy.oauthTtlHint","Sign-in lifetime for OAuth-connected apps and agents (desktop app, MCP clients). Applies to new connections only.")})]})]}),a&&e.jsx("div",{className:"flex justify-end pt-1",children:e.jsx("button",{onClick:o,disabled:s,className:"btn-primary flex items-center gap-1.5 disabled:opacity-50",children:s?u("orgSecurity.common.saving","Saving..."):u("orgSecurity.common.savePolicy","Save Policy")})}),d&&e.jsx("div",{className:"pt-3 border-t border-gray-100 dark:border-gray-700/50",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:u("orgSecurity.forceLogout.title","Apply session policy to all active sessions")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:u("orgSecurity.forceLogout.description","Existing sessions keep running until their original expiry. Use this to force every member (including you) to re-authenticate right now under the new policy.")})]}),e.jsx("button",{onClick:x,className:"btn-secondary flex-shrink-0 text-xs whitespace-nowrap",children:u("orgSecurity.forceLogout.button","Force logout all")})]})})]})})]})}const Cl={WILDCARD:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",PROJECTS_READ:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",PROJECTS_WRITE:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",TASKS_READ:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",TASKS_WRITE:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",MEMBERS_READ:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",WEBHOOKS_MANAGE:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",PLAYGROUND_READ:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",PLAYGROUND_WRITE:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400"};function Al({tokens:t,loading:a,revokeTokenId:s,revoking:l,collapsed:i,toggle:c,onRevokeClick:r,onRevokeConfirm:o,onRevokeCancel:x}){const{t:d}=Q();return e.jsxs(Bt,{id:"apiTokens",collapsed:i,toggle:c,children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 bg-rose-50 dark:bg-rose-950/40 border-s-4 border-s-rose-500 rounded-t-xl transition-colors",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-rose-100 dar
22k:bg-rose-900/40 flex items-center justify-center flex-shrink-0",children:e.jsx(vr,{className:"w-4 h-4 text-rose-600 dark:text-rose-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:d("orgSecurity.apiTokens.title","API Tokens")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:d("orgSecurity.apiTokens.subtitle","View and manage all active Personal Access Tokens across this organization.")})]}),t.length>0&&e.jsx("span",{className:"text-xs font-medium px-2 py-0.5 rounded-full bg-rose-100 dark:bg-rose-900/30 text-rose-700 dark:text-rose-400",children:d("orgSecurity.apiTokens.activeCount",{count:t.length,defaultValue_one:"{{count}} active",defaultValue_other:"{{count}} active"})})]}),e.jsx("div",{className:"border-t border-gray-100 dark:border-gray-700/50",children:a?e.jsx("div",{className:"p-4",children:e.jsx(oe,{className:"h-16 rounded w-full"})}):t.length===0?e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 italic",children:d("orgSecurity.apiTokens.emptyState","No active API tokens in this organization. Members can create tokens in Settings → Developer.")})}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-50 dark:bg-gray-800/60 border-y border-gray-200 dark:border-gray-700",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-start text-xs font-semibold text-gray-600 dark:text-gray-400",children:d("orgSecurity.apiTokens.colToken","Token")}),e.jsx("th",{className:"px-4 py-2 text-start text-xs font-semibold text-gray-600 dark:text-gray-400",children:d("orgSecurity.apiTokens.colOwner","Owner")}),e.jsx("th",{className:"px-4 py-2 text-start text-xs font-semibold text-gray-600 dark:text-gray-400",children:d("orgSecurity.apiTokens.colScopes","Scopes")}),e.jsx("th",{className:"px-4 py-2 text-start text-xs font-semibold text-gray-600 dark:text-gray-400",children:d("orgSecurity.apiTokens.colLastUsed","Last Used")}),e.jsx("th",{className:"px-4 py-2 text-start text-xs font-semibold text-gray-600 dark:text-gray-400",children:d("orgSecurity.apiTokens.colExpires","Expires")}),e.jsx("th",{className:"px-4 py-2 text-end text-xs font-semibold text-gray-600 dark:text-gray-400"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700/60",children:t.map(u=>e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/40",children:[e.jsxs("td",{className:"px-4 py-2.5",children:[e.jsx("p",{className:"font-medium text-gray-900 dark:text-white text-sm",children:u.name}),e.jsxs("p",{className:"text-xs text-gray-400 font-mono",children:[u.tokenPrefix,"..."]})]}),e.jsxs("td",{className:"px-4 py-2.5",children:[e.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:u.user.name}),e.jsx("p",{className:"text-xs text-gray-400",children:u.user.email})]}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.scopes.slice(0,3).map(h=>e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${Cl[h]??"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400"}`,children:h.replace(/_/g," ")},h)),u.scopes.length>3&&e.jsx("span",{className:"text-[10px] text-gray-400",children:d("orgSecurity.apiTokens.moreScopes","+{{amount}}",{amount:u.scopes.length-3})})]})}),e.jsx("td",{className:"px-4 py-2.5 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap",children:u.lastUsedAt?yi(new Date(u.lastUsedAt),{addSuffix:!0}):e.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:d("orgSecurity.apiTokens.never","Never")})}),e.jsx("td",{className:"px-4 py-2.5 text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap",children:u.expiresAt?Wa(new Date(u.expiresAt),"MMM d, yyyy"):e.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:d("orgSecurity.apiTokens.never","Never")})}),e.jsx("td",{className:"px-4 py-2.5 text-end",children:s===u.id?e.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[e.jsx("span",{className:"text-xs text-red-600 dark:text-red-400",children:d("orgSecurity.apiTokens.revokePrompt","Revoke?")}),e.jsx("button",{onClick:()=>o(u.id),disabled:l,className:"btn-danger text-xs px-2 py-1",children:l?d("orgSecurity.apiTokens.revoking","Revoking..."):d("orgSecurity.apiTokens.revokeYes","Yes")}),e.jsx("button",{onClick:x,className:"btn-secondary text-xs px-2 py-1",children:d("orgSecurity.apiTokens.revokeNo","No")})]}):e.jsx("button",{onClick:()=>r(u.id),className:"text-xs text-red-500 hover:text-red-700 dark:hover:text-red-400 font-medium","aria-label":d("orgSecurity.apiTokens.revokeAria","Revoke token {{name}}",{name:u.name}),children:d("orgSecurity.apiTokens.revoke","Revoke")})})]},u.id))})]})})})]})}const El={STANDARD:"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300",GDPR:"bg-blue-100 dar
22k:bg-blue-900/30 text-blue-700 dark:text-blue-300",HIPAA:"bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300",FINRA:"bg-indigo-100 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300",SOC2:"bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300",CUSTOM:"bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300"};function Pl(t,a){switch(a){case"STANDARD":return t("orgSecurity.retention.preset.standard","STANDARD");case"GDPR":return t("orgSecurity.retention.preset.gdpr","GDPR");case"HIPAA":return t("orgSecurity.retention.preset.hipaa","HIPAA");case"FINRA":return t("orgSecurity.retention.preset.finra","FINRA");case"SOC2":return t("orgSecurity.retention.preset.soc2","SOC2");case"CUSTOM":return t("orgSecurity.retention.preset.custom","CUSTOM");default:return a}}function Tl({data:t,loading:a}){const{t:s}=Q();return e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 bg-purple-50 dark:bg-purple-950/40 border-s-4 border-s-purple-500 rounded-t-xl transition-colors",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-purple-100 dark:bg-purple-900/40 flex items-center justify-center flex-shrink-0",children:e.jsx(Gt,{className:"w-4 h-4 text-purple-600 dark:text-purple-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:s("orgSecurity.retention.title","Data Retention Policy")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s("orgSecurity.retention.subtitle","Controls how long org data, audit logs, and user records are kept before permanent deletion.")})]}),t&&!a&&e.jsx("span",{className:`text-xs font-semibold px-2 py-0.5 rounded-full flex-shrink-0 ${El[t.preset]}`,children:Pl(s,t.preset)})]})}function Rl({data:t,loading:a,preset:s,notes:l,customOrgDays:i,customAuditDays:c,customUserDays:r,saving:o,onPresetChange:x,onNotesChange:d,onCustomOrgDays:u,onCustomAuditDays:h,onCustomUserDays:f,onSave:j}){const{t:b}=Q(),y=(t==null?void 0:t.presets)??{},N=t==null?void 0:t.effective;function p(S){return S===0?b("orgSecurity.retention.forever","Forever"):S>=365?b("orgSecurity.retention.years","{{amount}} yr",{amount:(S/365).toFixed(1).replace(".0","")}):b("orgSecurity.retention.days","{{amount}} days",{amount:S})}return e.jsx("div",{className:"px-5 py-4 space-y-4 border-t border-gray-100 dark:border-gray-700/50",children:a?e.jsx("p",{className:"text-xs text-gray-400 py-2",children:b("orgSecurity.retention.loading","Loading policy...")}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-gray-700 dark:text-gray-300 mb-2",children:b("orgSecurity.retention.presetTitle","Compliance Preset")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Object.keys(y).map(S=>e.jsxs("button",{onClick:()=>x(S),className:`text-start p-2.5 rounded-lg border text-xs transition-colors ${s===S?"border-indigo-500 bg-indigo-50 dark:bg-indigo-900/30":"border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500"}`,children:[e.jsx("p",{className:`font-semibold mb-0.5 ${s===S?"text-indigo-700 dark:text-indigo-300":"text-gray-900 dark:text-white"}`,children:y[S].label}),e.jsx("p",{className:"text-gray-500 dark:text-gray-400 leading-snug line-clamp-2",children:y[S].description})]},S))})]}),s==="CUSTOM"&&e.jsx("div",{className:"grid grid-cols-3 gap-3",children:[{id:"orgData",label:b("orgSecurity.retention.customOrgDays","Org data (days)"),value:i,onChange:u,placeholder:"30"},{id:"auditLogs",label:b("orgSecurity.retention.customAuditDays","Audit logs (days)"),value:c,onChange:h,placeholder:"365"},{id:"userData",label:b("orgSecurity.retention.customUserDays","User data (days)"),value:r,onChange:f,placeholder:"90"}].map(S=>e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:S.label}),e.jsx("input",{type:"number",min:1,max:9999,value:S.value,onChange:C=>S.onChange(C.target.value),placeholder:S.placeholder,"aria-label":S.label,className:"input w-full text-sm"})]},S.id))}),N&&e.jsx("div",{className:"flex gap-3 flex-wrap",children:[{id:"orgData",label:b("orgSecurity.retention.effectiveOrgData","Org data"),days:s==="CUSTOM"&&parseInt(i)||N.orgDataDays},{id:"auditLogs",label:b("orgSecurity.retention.effectiveAuditLogs","Audit logs"),days:s==="CUSTOM"&&parseInt(c)||N.auditLogDays},{id:"userData",label:b("orgSecurity.retention.effectiveUserData","User data"),days:s==="CUSTOM"&&parseInt(r)||N.userDataDays}].map(S=>e.jsxs("div",{className:"flex-1 min-w-[80px] bg-gray-50 dark:bg-gray-800 rounded-lg px-3 py-2 text-center border border-gray-100 dark:border-gray-700",children:[e.jsx("p",{className:"text-base font-bold text-gray-900 dark:text-white",children:p(S.days)}),e.jsx("p",{className:"text-[11px] text-gray-500 dark:text-gray-400 mt-0.5",children:S.label})]},S.id))}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:[b("orgSecurity.retention.notesLabel","Compliance Notes")," ",e.jsx("span",{className:"font-normal text-gray-400",children:b("orgSecurity.retention.notesHint","(optional, stored with your audit evidence)")})]}
22),e.jsx("textarea",{value:l,onChange:S=>d(S.target.value),rows:2,maxLength:1e3,placeholder:b("orgSecurity.retention.notesPlaceholder","e.g. HIPAA BAA signed 2026-01-15. Reviewed by Legal. Applies to PHI data."),"aria-label":b("orgSecurity.retention.notesLabel","Compliance Notes"),className:"input w-full text-sm resize-none"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{onClick:j,disabled:o,className:"btn-primary flex items-center gap-1.5 disabled:opacity-50",children:o?b("orgSecurity.common.saving","Saving..."):b("orgSecurity.common.savePolicy","Save Policy")})})]})})}function Ml({org:t}){const{t:a}=Q(),s=_e(),[l,i]=g.useState(t.aiPerUserCapPct!=null),[c,r]=g.useState(t.aiPerUserCapPct??30),o=g.useRef(t.aiPerUserCapPct);g.useEffect(()=>{o.current!==t.aiPerUserCapPct&&(i(t.aiPerUserCapPct!=null),r(t.aiPerUserCapPct??30),o.current=t.aiPerUserCapPct)},[t.aiPerUserCapPct]);const x=$({mutationFn:f=>B.update(t.id,{aiPerUserCapPct:f}),onSuccess:()=>{k.success(a("orgSettings.aiCap.saved","AI policy updated")),s.invalidateQueries({queryKey:["organization",t.id]}),s.invalidateQueries({queryKey:["subscription"]})},onError:f=>k.error(U(f,"update AI policy"))}),d=t.aiPerUserCapPct??null,u=l?c:null,h=d!==u;return e.jsxs("div",{className:"mt-6 pt-5 border-t border-gray-200 dark:border-gray-700",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:a("orgSettings.aiCap.title","Per-user AI cap")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5 max-w-xl",children:a("orgSettings.aiCap.subtitle","By default, your org's AI tokens are a shared pool - any member can use any of them. Enable this to cap each user at a percentage of the pool so one heavy user can't drain the month's allowance for everyone.")})]}),e.jsxs("label",{className:"inline-flex items-center gap-2 cursor-pointer flex-shrink-0",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:f=>i(f.target.checked),className:"h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"}),e.jsx("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:l?a("orgSettings.aiCap.on","On"):a("orgSettings.aiCap.off","Off")})]})]}),l&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("input",{type:"range",min:1,max:100,step:1,value:c,onChange:f=>r(Number(f.target.value)),className:"flex-1 accent-indigo-600","aria-label":a("orgSettings.aiCap.sliderAria","Per-user cap percentage")}),e.jsxs("div",{className:"w-20 flex items-center gap-1",children:[e.jsx("input",{type:"number",min:1,max:100,value:c,onChange:f=>r(Math.max(1,Math.min(100,Number(f.target.value)||1))),className:"input w-16 text-center py-1 text-sm"}),e.jsx("span",{className:"text-sm text-gray-500",children:"%"})]})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:a("orgSettings.aiCap.explainer","Each user capped at {{pct}}% of the monthly org pool. With {{members}} current members, that means each user can use up to ~{{share}}× a single seat's share.",{pct:c,members:t._count.members,share:Math.floor(c/100*t._count.members*100)/100})})]}),h&&e.jsxs("div",{className:"mt-4 flex items-center gap-3",children:[e.jsx("button",{onClick:()=>x.mutate(u),disabled:x.isPending,className:"btn-primary text-xs px-3 py-1.5",children:x.isPending?a("orgSettings.saving","Saving…"):a("orgSettings.save","Save")}),e.jsx("button",{onClick:()=>{i(d!=null),r(d??30)},disabled:x.isPending,className:"text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200",children:a("common.cancel","Cancel")})]})]})}const Fl={enabled:!0,mode:"all",userIds:[],teamIds:[]},pn=(t,a)=>t.length===a.length&&[...t].sort().join(",")===[...a].sort().join(",");function Dl(t,a){switch(a){case"all":return t("orgSettings.agentAccess.modeAll","Everyone can use agents");case"allowlist":return t("orgSettings.agentAccess.modeAllowlist","Only selected users / teams");case"denylist":return t("orgSettings.agentAccess.modeDenylist","Everyone except selected users / teams");default:return a}}function Ll({orgId:t,canEdit:a,value:s}){var re;const{t:l}=Q(),i=_e(),c=s??Fl,[r,o]=g.useState(c.enabled),[x,d]=g.useState(c.mode),[u,h]=g.useState(c.userIds),[f,j]=g.useState(c.teamIds),b=H=>H==null?"":String(H),y=H=>{const ge=H.trim();if(ge==="")return null;const _=parseInt(ge,10);return Number.isFinite(_)?_:null},[N,p]=g.useState(b(c.maxConnections)),[S,C]=g.useState(b(c.maxPerUser)),R=(re=ee({queryKey:["agent-access-status",t],queryFn:()=>B.agentAccessStatus(t),enabled:a}).data)==null?void 0:re.connectionUsage,Z=r&&x!=="all",te=ee({queryKey:["org-members",t],queryFn:()=>B.members(t),enabled:Z}
22),A=ee({queryKey:["teams",t],queryFn:()=>_n.list(),enabled:Z}),P=g.useMemo(()=>(te.data??[]).filter(H=>!H.user.isAgentPersona).map(H=>({id:H.userId,label:H.user.name,sublabel:H.user.email})),[te.data]),z=g.useMemo(()=>(A.data??[]).map(H=>({id:H.id,label:H.name})),[A.data]),M=r!==c.enabled||x!==c.mode||!pn(u,c.userIds)||!pn(f,c.teamIds)||N!==b(c.maxConnections)||S!==b(c.maxPerUser),J=$({mutationFn:()=>B.updateAiControls(t,{agentAccess:{enabled:r,mode:x,userIds:x==="all"?[]:u,teamIds:x==="all"?[]:f,maxConnections:y(N),maxPerUser:y(S)}}),onSuccess:()=>{i.invalidateQueries({queryKey:["org-ai-controls",t]}),i.invalidateQueries({queryKey:["agent-access-status",t]}),k.success(l("orgSettings.agentAccess.saved","Agent access updated"))},onError:H=>k.error(U(H,"update agent access"))}),ae=()=>{o(c.enabled),d(c.mode),h(c.userIds),j(c.teamIds),p(b(c.maxConnections)),C(b(c.maxPerUser))};return e.jsxs("section",{className:"bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-6",children:[e.jsxs("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 mb-1 flex items-center gap-2",children:[e.jsx(Es,{className:"w-4 h-4 text-indigo-600"})," ",l("orgSettings.agentAccess.title","External AI agents")]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-4",children:l("orgSettings.agentAccess.subtitle","Control who may connect and use external AI agents (Claude Code, Claude Desktop, Codex, Cursor, and other MCP clients). The organization owner can always use agents.")}),e.jsxs("label",{className:"flex items-center justify-between gap-4 py-2",children:[e.jsxs("span",{className:"text-sm text-gray-800 dark:text-gray-200",children:[l("orgSettings.agentAccess.masterToggle","Allow external AI agents"),e.jsx("span",{className:"block text-xs text-gray-500 dark:text-gray-400",children:r?l("orgSettings.agentAccess.masterOnHint","On. Usable per the rules below."):l("orgSettings.agentAccess.masterOffHint","Off. No one but the owner can use agents.")})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":r,disabled:!a,onClick:()=>o(H=>!H),className:`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors disabled:opacity-50 ${r?"bg-indigo-600":"bg-gray-300 dark:bg-gray-600"}`,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${r?"translate-x-6 rtl:-translate-x-6":"translate-x-1 rtl:-translate-x-1"}`})})]}),r&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx("div",{className:"space-y-2",children:["all","allowlist","denylist"].map(H=>e.jsxs("label",{className:"flex items-start gap-2 text-sm text-gray-800 dark:text-gray-200",children:[e.jsx("input",{type:"radio",name:"agent-access-mode",checked:x===H,disabled:!a,onChange:()=>d(H),className:"mt-0.5"}),e.jsx("span",{children:Dl(l,H)})]},H))}),x!=="all"&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 pt-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1",children:l("orgSettings.agentAccess.usersLabel","Users")}),e.jsx(ya,{options:P,selected:u,onChange:h,placeholder:x==="allowlist"?l("orgSettings.agentAccess.usersAllowPlaceholder","Users who may use agents"):l("orgSettings.agentAccess.usersDenyPlaceholder","Users blocked from agents"),searchPlaceholder:l("orgSettings.agentAccess.searchMembers","Search members…"),multiple:!0,disabled:!a,ariaLabel:l("orgSettings.agentAccess.usersAria","Select users for agent access")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1",children:l("orgSettings.agentAccess.teamsLabel","Teams")}),e.jsx(ya,{options:z,selected:f,onChange:j,placeholder:x==="allowlist"?l("orgSettings.agentAccess.teamsAllowPlaceholder","Teams who may use agents"):l("orgSettings.agentAccess.teamsDenyPlaceholder","Teams blocked from agents"),searchPlaceholder:l("orgSettings.agentAccess.searchTeams","Search teams…"),multiple:!0,disabled:!a,ariaLabel:l("orgSettings.agentAccess.teamsAria","Select teams for agent access")}),e.jsx("p",{className:"mt-1 text-[11px] text-gray-400",children:l("orgSettings.agentAccess.teamsHint","Team membership is evaluated live, so changes to a team take effect automatically.")})]})]})]}),e.jsxs("div",{className:"mt-4 border-t border-gray-100 dark:border-gray-700 pt-3",children:[e.jsx("div",{className:"text-sm font-medium text-gray-800 dark:text-gray-200",children:l("orgSettings.agentAccess.connectionsTitle","Registered connections")}),R&&e.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:[R.orgCap===-1?l("orgSettings.agentAccess.registeredUnlimited","{{registered}} registered (unlimited)",{registered:R.current}):l("orgSettings.agentAccess.registeredOfCap","{{registered}} of {{cap}} registered",{registered:R.current,cap:R.orgCap}),R.concurrentCap>0&&R.concurrentCap!==-1&&e.jsxs("span",{className:"ms-1",children:["·"," ",l("orgSettings.agentAccess.concurrentCap","up to {{concurrent}} may run at once (plan limit)",{concurrent:R.concurrentCap})]}),R.concurrentCap===-1&&e.jsxs("span",{className:"ms-1",children:["· ",l("orgSettings.agentAccess.concurrentUnlimited","unlimited concurrent sessions")]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 mt-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1",children:l("orgSettings.agentAccess.maxConnectionsLabel","Max registered connections (blank = plan default)")}),e.jsx("input",{type:"number",min:-1,value:N,disabled:!a,onChange:H=>p(H.target.value),placeholder:l("orgSettings.agentAccess.maxConnectionsPlaceholder","plan default"),className:"w-full text-sm border border-gray-300 dark:border-gray-600 dark:bg-gray-900 rounded-lg px-2 py-1 disabled:opacity-50"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1",children:l("orgSettings.agentAccess.maxPerUserLabel","Per-user cap (blank = unlimited)")}),e.jsx("input",{type:"number",min:-1,value:S,disabled:!a,onChange:H=>C(H.target.value),placeholder:l("orgSettings.agentAccess.maxPerUserPlaceholder","unlimited"),className:"w-full text-sm border border-gray-300 dark:border-gray-600 dark:bg-gray-900 rounded-lg px-2 py-1 disabled:opacity-50"})]})]}),e.jsx("p",{className:"mt-1 text-[11px] text-gray-400",children:l("orgSettings.agentAccess.capsHint","Registered connections are agent tokens that exist in y
22our org. Concurrent sessions (how many agents run at the same time) is a separate plan limit shown above. −1 = unlimited, 0 = block new registrations.")})]}),a&&M&&e.jsxs("div",{className:"mt-4 flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>J.mutate(),disabled:J.isPending,className:"px-3 py-1.5 text-sm rounded-lg bg-indigo-600 text-white hover:bg-indigo-700 disabled:opacity-50",children:J.isPending?l("orgSettings.saving","Saving…"):l("orgSettings.agentAccess.saveChanges","Save changes")}),e.jsx("button",{type:"button",onClick:ae,disabled:J.isPending,className:"px-3 py-1.5 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-200",children:l("orgSettings.agentAccess.discard","Discard")})]})]})}function Ol(t,a){switch(a){case"chat":return t("orgSettings.aiUsage.groupChat","Chat");case"planning":return t("orgSettings.aiUsage.groupPlanning","Planning");case"project":return t("orgSettings.aiUsage.groupProject","Project");case"portfolio":return t("orgSettings.aiUsage.groupPortfolio","Portfolio");case"reports":return t("orgSettings.aiUsage.groupReports","Reports");case"tasks":return t("orgSettings.aiUsage.groupTasks","Tasks");case"intake":return t("orgSettings.aiUsage.groupIntake","Intake");case"risk":return t("orgSettings.aiUsage.groupRisk","Risk");default:return a}}function Il(t,a){switch(a){case"aiAdvanced":return t("orgSettings.aiUsage.planLockBusiness","Requires BUSINESS+ plan, upgrade to enable");default:return t("orgSettings.aiUsage.planLockPro","Requires PRO+ plan, upgrade to enable")}}function Va(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${(t/1024/1024/1024).toFixed(2)} GB`}const ql=["chat","planning","project","portfolio","reports","tasks","intake","risk"];function _l({org:t,canEdit:a}){const{t:s}=Q(),l=_e(),[i,c]=g.useState(()=>{const _=typeof window<"u"?localStorage.getItem("org-ai-usage-range"):null;return _==="1d"||_==="7d"||_==="30d"||_==="90d"?_:"30d"});g.useEffect(()=>{typeof window<"u"&&localStorage.setItem("org-ai-usage-range",i)},[i]);const{data:r,isLoading:o,isFetching:x,refetch:d}=ee({queryKey:["org-ai-controls",t.id,i],queryFn:()=>B.getAiControls(t.id,i),staleTime:3e4}),[u,h]=g.useState(null),[f,j]=g.useState(null),[b,y]=g.useState(!1);g.useEffect(()=>{r!=null&&r.settings&&(h(r.settings.master),j(new Set(r.settings.disabled)))},[r==null?void 0:r.settings]);const N=g.useMemo(()=>{if(!(r!=null&&r.settings)||!f||!u)return!1;if(u!==r.settings.master||f.size!==r.settings.disabled.length)return!0;for(const _ of r.settings.disabled)if(!f.has(_))return!0;return!1},[r==null?void 0:r.settings,u,f]),[p,S]=g.useState(""),[C,G]=g.useState("WARN");g.useEffect(()=>{r!=null&&r.costCap&&(S(r.costCap.capUsd!=null?String(r.costCap.capUsd):""),G(r.costCap.enforcement))},[r==null?void 0:r.costCap]),g.useMemo(()=>{if(!(r!=null&&r.costCap))return!1;const _=r.costCap.capUsd,se=p.trim()===""?null:Number(p);return _!==se||C!==r.costCap.enforcement},[r==null?void 0:r.costCap,p,C]),$({mutationFn:()=>{const _=p.trim()===""?null:Number(p);return B.updateAiControls(t.id,{costCapUsd:_,costCapEnforcement:C})},onSuccess:()=>{k.success(s("orgSettings.aiUsage.toastCostCapUpdated","Cost cap updated")),l.invalidateQueries({queryKey:["org-ai-controls",t.id]})},onError:_=>k.error(U(_,"save cost cap"))});const R=$({mutationFn:()=>B.updateAiControls(t.id,{master:u??"enabled",disabled:Array.from(f??[])}),onSuccess:()=>{k.success(s("orgSettings.aiUsage.toastControlsUpdated","AI controls updated")),l.invalidateQueries({queryKey:["org-ai-controls",t.id]})},onError:_=>k.error(U(_,"save AI settings"))}),[Z,te]=g.useState(!1),[A,P]=g.useState(null),M=Vt({open:Z&&!!A,onClose:()=>{te(!1),P(null)}});function J(){const _=u==="disabled"&&(r==null?void 0:r.settings.master)==="enabled",se=new Set((r==null?void 0:r.settings.disabled)??[]),T=[...f??new Set].filter(ie=>!se.has(ie)).map(ie=>r==null?void 0:r.catalog.find(Le=>Le.id===ie)).filter(ie=>!!ie);return{masterFlip:_,newlyDisabled:T}}function ae(){const{masterFlip:_,newlyDisabled:se}=J();if(!_&&se.length===0){R.mutate();return}P(_?{title:s("orgSettings.aiUsage.confirmDisableAllTitle","Disable all AI features?"),body:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:s("orgSettings.aiUsage.confirmDisableAllBody","This will turn off every AI feature for everyone in your organization. The floating AI assistant icon will disappear, and AI buttons across the app will be greyed out.")}),e.jsx("p",{className:"mt-2 text-gray-500 text-xs",children:s("orgSettings.aiUsage.confirmDisableAllNote","Existing AI-generated content (risks, suggestions, plans) stays visible. You can re-enable any time.")})]}),affected:[]}:{title:s("orgSettings.aiUsage.confirmDisableSomeTitle",{count:se.length,defaultValue_one:"Disable {{count}} AI feature?",defaultValue_other:"Disable {{count}} AI features?"}),body:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:s("orgSettings.aiUsage.confirmDisableSomeBody","Members will see these features greyed out with a tooltip pointing them to you.")}),e.jsx("p",{className:"mt-2 text-gray-500 text-xs",children:s("orgSettings.aiUsage.confirmDisableSomeNote","Existing data already generated by these features stays visible. You can re-enable any time.")})]}),affected:se.map(ne=>ne.name)}),te(!0)}const re=g.useMemo(()=>{const _=new Map;for(const se of(r==null?void 0:r.catalog)??[]){const ne=_.get(se.group)??[];ne.push(se),_.set(se.group,ne)}return ql.map(se=>[se,_.get(se)??[]]).filter(([,se])=>se.length>0)},[r==null?void 0:r.catalog]);if(o||!r)return e.jsxs("div",{className:"space-y-8","aria-busy":"true",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{className:"h-5 w-48 rounded"}),e.jsx(oe,{className:"h-3 w-96 rounded"})]}),e.jsx(oe,{className:"h-8 w-8 rounded"})]}
22),e.jsx(oe,{className:"h-64 rounded-xl"}),e.jsx(oe,{className:"h-40 rounded-xl"}),e.jsx(oe,{className:"h-72 rounded-xl"}),e.jsx(oe,{className:"h-48 rounded-xl"})]});const H=u==="disabled",ge=(f==null?void 0:f.size)??0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-base font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[e.jsx(va,{className:"w-5 h-5 text-purple-600"}),s("orgSettings.aiUsage.title","AI and Storage")]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1 max-w-2xl",children:s("orgSettings.aiUsage.subtitle","Control which AI features are on for your organization and check your storage quota. Changes are tenant-scoped, they don't affect other organizations.")})]}),e.jsx("button",{onClick:()=>d(),className:"btn-secondary p-1.5",title:s("orgSettings.aiUsage.refresh","Refresh"),children:e.jsx($n,{className:`w-4 h-4 ${x?"animate-spin":""}`})})]}),e.jsxs("section",{className:"bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-6",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 mb-1",children:s("orgSettings.aiUsage.featuresTitle","AI features")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-4",children:s("orgSettings.aiUsage.featuresSubtitle","Master switch turns every AI feature off at once. Per-feature toggles let you keep some on while disabling others. Plan-locked features can't be enabled until you upgrade your plan.")}),e.jsxs("div",{className:"flex items-center justify-between border border-gray-200 dark:border-gray-700 rounded-lg p-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:s("orgSettings.aiUsage.masterLabel","All AI features")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:H?s("orgSettings.aiUsage.masterOffHint","Disabled, every AI request will be rejected for this organization."):s("orgSettings.aiUsage.masterOnHint","Enabled, individual features below honor their own toggle.")})]}),e.jsxs("label",{className:"inline-flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",disabled:!a,checked:!H,onChange:_=>h(_.target.checked?"enabled":"disabled"),className:"h-5 w-9 rounded-full appearance-none bg-gray-300 dark:bg-gray-600 checked:bg-purple-600 transition-colors"}),e.jsx("span",{className:`text-xs font-medium ${H?"text-gray-500":"text-purple-600"}`,children:H?s("orgSettings.aiUsage.toggleOff","Off"):s("orgSettings.aiUsage.toggleOn","On")})]})]}),e.jsxs("button",{type:"button",onClick:()=>y(_=>!_),"aria-expanded":b,className:"w-full flex items-center gap-2 px-1 py-1 text-xs font-medium text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors",children:[e.jsx(gt,{className:`w-4 h-4 transition-transform ${b?"rotate-180":""}`}),s("orgSettings.aiUsage.customizeToggle","Customize individual features"),e.jsxs("span",{className:"font-normal text-gray-400 dark:text-gray-500",children:["(",s("orgSettings.aiUsage.featureCount",{count:r.catalog.length,defaultValue_one:"{{count}} feature",defaultValue_other:"{{count}} features"}),ge>0?s("orgSettings.aiUsage.featureCountOff",", {{offCount}} off",{offCount:ge}):"",")"]})]}),b&&e.jsx("div",{className:"space-y-5 mt-3",children:re.map(([_,se])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-2",children:Ol(s,_)}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:se.map(ne=>{const Ye=(f==null?void 0:f.has(ne.id))??!1,T=!H&&!Ye&&!ne.planLocked;return e.jsxs("div",{className:`border border-gray-200 dark:border-gray-700 rounded-lg p-3 flex items-start justify-between gap-3 ${ne.planLocked?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-gray-100 truncate",children:ne.name}),ne.planLocked&&e.jsxs("span",{title:Il(s,ne.feature),className:"inline-flex items-center gap-1 text-[10px] uppercase tracking-wide bg-amber-100 dar
22k:bg-amber-900/30 text-amber-800 dark:text-amber-300 px-1.5 py-0.5 rounded",children:[e.jsx(ke,{className:"w-3 h-3"})," ",s("orgSettings.aiUsage.planLockBadge","Plan")]})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:ne.description}),e.jsxs("p",{className:"text-[10px] text-gray-400 dark:text-gray-500 mt-1 flex items-center gap-1",children:[e.jsx(kr,{className:"w-3 h-3"})," ",ne.usedBy]})]}),e.jsx("label",{className:"inline-flex items-center cursor-pointer flex-shrink-0",children:e.jsx("input",{type:"checkbox",disabled:!a||ne.planLocked||H,checked:T,onChange:ie=>{if(!f)return;const Le=new Set(f);ie.target.checked?Le.delete(ne.id):Le.add(ne.id),j(Le)},className:"h-4 w-4 rounded border-gray-300 text-purple-600 focus:ring-purple-500"})})]},ne.id)})})]},_))}),a&&N&&e.jsxs("div",{className:"mt-5 flex items-center justify-end gap-3 pt-4 border-t border-gray-100 dark:border-gray-700",children:[e.jsxs("span",{className:"text-xs text-amber-700 flex items-center gap-1",children:[e.jsx(je,{className:"w-3.5 h-3.5"})," ",s("orgSettings.aiUsage.unsavedChanges","Unsaved changes")]}),e.jsx("button",{onClick:()=>{h(r.settings.master),j(new Set(r.settings.disabled))},disabled:R.isPending,className:"btn-secondary text-xs py-1.5",children:s("common.cancel","Cancel")}),e.jsx("button",{onClick:ae,disabled:R.isPending,className:"btn-primary text-xs py-1.5 disabled:opacity-50",children:R.isPending?s("orgSettings.aiUsage.saving","Saving..."):s("orgSettings.aiUsage.saveChanges","Save changes")})]}),r.settings.updatedAt&&e.jsx("p",{className:"text-[10px] text-gray-400 dark:text-gray-500 mt-3",children:s("orgSettings.aiUsage.lastChanged","Last changed {{when}}",{when:new Date(r.settings.updatedAt).toLocaleString()})})]}),e.jsxs("section",{className:"bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-6",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 mb-1",children:s("orgSettings.aiUsage.fairShareTitle","Fair-share policy")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:s("orgSettings.aiUsage.fairShareSubtitle","Optional: prevent any single member from monopolising the org's monthly AI budget.")}),e.jsx(Ml,{org:t})]}),e.jsx(Ll,{orgId:t.id,canEdit:a,value:r.settings.agentAccess}),fi,ki,e.jsxs("section",{className:"bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-6",children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[e.jsx(Hn,{className:"w-4 h-4 text-purple-600"})," ",s("orgSettings.aiUsage.storageTitle","Storage")]}),e.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:[s("orgSettings.aiUsage.storageSubtitle","File attachments + document libraries. Plan:")," ",e.jsx("span",{className:"font-mono",children:r.storage.planLabel}),"."]})]})}),r.storage.unlimited?e.jsxs("div",{className:"border border-green-200 bg-green-50 dark:bg-green-900/20 dark:border-green-700 rounded-lg p-4",children:[e.jsxs("p",{className:"text-sm text-green-800 dark:text-green-300 flex items-center gap-2",children:[e.jsx(ct,{className:"w-4 h-4"})," ",s("orgSettings.aiUsage.storageUnlimited","Unlimited storage on this plan")]}),e.jsx("p",{className:"text-xs text-green-700 dark:text-green-400 mt-1",children:s("orgSettings.aiUsage.storageCurrentlyUsing","Currently using {{amount}}.",{amount:Va(r.storage.usedBytes)})})]}):e.jsx(Ul,{storage:r.storage})]}),Z&&A&&e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-md w-full mx-4 p-6",ref:M,role:"dialog","aria-modal":"true","aria-labelledby":"ai-usage-confirm-title",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx("div",{className:"flex-shrink-0 w-9 h-9 rounded-full bg-amber-100 text-amber-700 flex items-center justify-center",children:e.jsx(je,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{id:"ai-usage-confirm-title",className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:A.title}),e.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-300 mt-1.5",children:A.body})]})]}),A.affected.length>0&&e.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg p-3 mb-4 bg-gray-50 dark:bg-gray-900/50",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide font-semibold text-gray-500 mb-2",children:s("orgSettings.aiUsage.willBeDisabled","Will be disabled")}),e.jsx("ul",{className:"text-xs text-gray-700 dark:text-gray-200 space-y-1",children:A.affected.map(_=>e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-red-500"})," ",_]},_))})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>{te(!1),P(null)},disabled:R.isPending,className:"btn-secondary text-sm py-1.5",children:s("common.cancel","Cancel")}),e.jsx("button",{onClick:()=>{R.mutate(void 0,{onSettled:()=>{te(!1),P(null)}})},disabled:R.isPending,className:"btn-danger text-sm py-1.5 disabled:opacity-50",children:R.isPending?s("orgSettings.aiUsage.saving","Saving..."):s("orgSettings.aiUsage.confirmDisableCta","Yes, disable")})]})]})})]})}function Ul({storage:t}){const{t:a}=Q(),s=t.limitBytes>0?Math.min(100,t.usedBytes/t.limitBytes*100):0,l=s>=80?"bg-red-500":s>=60?"bg-amber-500":"bg-green-500";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-2",children:[e.jsxs("p",{className:"text-2xl font-bold text-gray-900 dark:text-gray-100",children:[Va(t.usedBytes),e.jsx("span",{className:"text-sm font-normal text-gray-500 dark:text-gray-400 ms-2",children:a("orgSettings.aiUsage.storageOfLimit","of {{limit}} ({{pct}}%)",{limit:Va(t.limitBytes),pct:s.toFixed(1)})})]}),s>=80&&e.jsxs("span",{className:"text-xs text-red-700 flex items-center gap-1",children:[e.jsx(je,{className:"w-3.5 h-3.5"}),a("orgSettings.aiUsage.storageApproachingLimit","Approaching limit, consider an upgrade")]})]}),e.jsx("div",{className:"w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2 overflow-hidden",children:e.jsx("div",{className:`${l} h-full transition-all`,style:{width:`${s}%`}})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mt-4",children:[e.jsx(hn,{label:a("orgSettings.aiUsage.breakdownWorkspaceFiles","Workspace files"),value:Va(t.breakdown.workspaceBytes),icon:e.jsx(Vi,{className:"w-3.5 h-3.5"})}),e.jsx(hn,{label:a("orgSettings.aiUsage.breakdownTaskAttachments","Task attachments"),value:Va(t.breakdown.taskBytes),icon:e.jsx(Hn,{className:"w-3.5 h-3.5"})})]})]})}function hn({label:t,value:a,icon:s}){return e.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg p-3",children:[e.jsxs("p",{className:"text-[10px] uppercase tracking-wide text-gray-500 dark:text-gray-400 font-semibold flex items-center gap-1",children:[s,t]}),e.jsx("p",{className:"text-base font-semibold text-gray-900 dark:text-gray-100 mt-1",children:a})]})}const Bl=["OWNER","ADMIN","MANAGER","MEMBER","GUEST"];function bn(t,a){switch(a){case"OWNER":return t("orgSettings.enforcement.role.owner","Owner");case"ADMIN":return t("orgSettings.enforcement.role.admin","Admin");case"MANAGER":return t("orgSettings.enforcement.role.manager","Portfolio Manager");case"MEMBER":return t("orgSettings.enforcement.role.member","Member");case"GUEST":return t("orgSettings.enforcement.role.guest","Guest");default:return a}}function Kl({orgId:t,draft:a,onChange:s,disabled:l}){const{t:i}=Q(),[c,r]=g.useState("teams"),o=a.expectedHoursOverrides??{teams:{},roles:{},users:{}},x=o.teams??{},d=o.roles??{},u=o.users??{},{data:h=Za}
22=ee({queryKey:["teams",t],queryFn:()=>_n.list(),staleTime:5*6e4}),{data:f=Za}=ee({queryKey:["org-members",t],queryFn:()=>B.members(t),staleTime:5*6e4}),j=C=>s({...a,expectedHoursOverrides:{...o,teams:C}}),b=C=>s({...a,expectedHoursOverrides:{...o,roles:C}}),y=C=>s({...a,expectedHoursOverrides:{...o,users:C}}),N=g.useMemo(()=>h.filter(C=>!x[C.id]).map(C=>({id:C.id,label:C.name})),[h,x]),p=g.useMemo(()=>Bl.filter(C=>!d[C]).map(C=>({id:C,label:bn(i,C)})),[d,i]),S=g.useMemo(()=>f.filter(C=>!C.user.isAgentPersona&&!u[C.userId]).map(C=>({id:C.userId,label:C.user.name,sublabel:C.user.email})),[f,u]);return e.jsxs("div",{className:"rounded-lg border border-gray-200 dark:border-gray-700 p-4 bg-white dark:bg-gray-800/40",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300",children:i("orgSettings.enforcement.overrides.title","Expected hours overrides")}),e.jsx("p",{className:"text-[10px] text-gray-500 dark:text-gray-400 mt-0.5",children:i("orgSettings.enforcement.overrides.resolutionHint","Resolution order: user → team → role → org default. First match wins.")})]}),!l&&e.jsxs("div",{className:"flex items-center gap-1 text-[10px]",children:[e.jsx("span",{className:"text-gray-400",children:i("orgSettings.enforcement.overrides.conflictLabel","Multi-team conflict:")}),e.jsxs("select",{value:a.multiTeamConflict??"most-generous",onChange:C=>s({...a,multiTeamConflict:C.target.value}),"aria-label":i("orgSettings.enforcement.overrides.conflictAria","Multi-team conflict strategy"),className:"text-[10px] border border-gray-200 dark:border-gray-700 rounded px-1 py-0.5 bg-white text-gray-900 dark:bg-gray-800 dark:text-gray-200",children:[e.jsx("option",{value:"most-generous",children:i("orgSettings.enforcement.overrides.conflictMostGenerous","Most generous (lower hours)")}),e.jsx("option",{value:"first-team",children:i("orgSettings.enforcement.overrides.conflictFirstTeam","First team (alphabetical)")}),e.jsx("option",{value:"most-restrictive",children:i("orgSettings.enforcement.overrides.conflictMostRestrictive","Most restrictive (higher hours)")})]}),e.jsx("span",{className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 cursor-help",title:i("orgSettings.enforcement.overrides.conflictTooltip",`Resolves the case where a user belongs to multiple teams that each carry an expected-hours override.
23
24• Most generous → picks the lower hours value (most lenient to the user)
25• Most restrictive → picks the higher hours value (strictest expectation)
26• First team → uses whichever override is alphabetically first by team name
27
28Default is Most generous on the principle that multi-team employees should not be overburdened.`),children:e.jsx(zi,{className:"w-3 h-3"})})]})]}),e.jsxs("div",{className:"inline-flex bg-gray-100 dark:bg-gray-700/50 p-0.5 rounded-md mb-3",children:[e.jsx(Ys,{active:c==="teams",onClick:()=>r("teams"),icon:e.jsx(ba,{className:"w-3 h-3"}),label:i("orgSettings.enforcement.overrides.tabTeams","Teams"),count:Object.keys(x).length}),e.jsx(Ys,{active:c==="roles",onClick:()=>r("roles"),icon:e.jsx(kt,{className:"w-3 h-3"}),label:i("orgSettings.enforcement.overrides.tabRoles","Roles"),count:Object.keys(d).length}),e.jsx(Ys,{active:c==="users",onClick:()=>r("users"),icon:e.jsx(Qi,{className:"w-3 h-3"}),label:i("orgSettings.enforcement.overrides.tabUsers","Users"),count:Object.keys(u).length})]}),c==="teams"&&e.jsxs("div",{className:"space-y-2",children:[Object.entries(x).length===0&&e.jsx(Zs,{text:i("orgSettings.enforcement.overrides.teamsEmpty","No team overrides configured. Add one to set a different weekly expectation for a team.")}),Object.entries(x).map(([C,G])=>{const R=h.find(Z=>Z.id===C);return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-gray-200 dark:border-gray-700",children:[e.jsx("span",{className:"text-xs font-medium text-gray-900 dark:text-gray-100 flex-1 min-w-0 truncate",children:(R==null?void 0:R.name)??i("orgSettings.enforcement.overrides.deletedTeam","(deleted team: {{id}})",{id:C.slice(0,8)})}),e.jsx(Js,{value:G.hoursPerWeek,onChange:Z=>j({...x,[C]:{...G,hoursPerWeek:Z}}),disabled:l}),e.jsx("span",{className:"text-[10px] text-gray-400",children:i("orgSettings.enforcement.overrides.hoursPerWeekUnit","h/wk")}),e.jsx(Xs,{disabled:l,onClick:()=>{const{[C]:Z,...te}=x;j(te)}})]},C)}),!l&&N.length>0&&e.jsx(er,{placeholder:i("orgSettings.enforcement.overrides.pickTeam","Pick a team to override…"),options:N,onAdd:C=>j({...x,[C]:{hoursPerWeek:32}})})]}),c==="roles"&&e.jsxs("div",{className:"space-y-2",children:[Object.entries(d).length===0&&e.jsx(Zs,{text:i("orgSettings.enforcement.overrides.rolesEmpty","No role overrides configured. Use this for role-wide rules like 'Portfolio Managers expected to log 35h/week (less IC time)'.")}),Object.entries(d).map(([C,G])=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-gray-200 dark:border-gray-700",children:[e.jsx("span",{className:"text-xs font-medium text-gray-900 dark:text-gray-100 flex-1 min-w-0",children:bn(i,C)}),e.jsx(Js,{value:G.hoursPerWeek,onChange:R=>b({...d,[C]:{hoursPerWeek:R}}),disabled:l}),e.jsx("span",{className:"text-[10px] text-gray-400",children:i("orgSettings.enforcement.overrides.hoursPerWeekUnit","h/wk")}),e.jsx(Xs,{disabled:l,onClick:()=>{const{[C]:R,...Z}=d;b(Z)}})]},C)),!l&&p.length>0&&e.jsx(er,{placeholder:i("orgSettings.enforcement.overrides.pickRole","Pick a role to override…"),options:p,onAdd:C=>b({...d,[C]:{hoursPerWeek:35}})})]}),c==="users"&&e.jsxs("div",{className:"space-y-2",children:[Object.entries(u).length===0&&e.jsx(Zs,{text:i("orgSettings.enforcement.overrides.usersEmpty","No per-user overrides. Use this for one-off cases like phased return-to-work, parental leave, or contractor schedules.")}),Object.entries(u).map(([C,G])=>{const R=f.find(Z=>Z.userId===C);return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-gray-200 dark:border-gray-700",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-gray-900 dark:text-gray-100 truncate",children:(R==null?void 0:R.user.name)??i("orgSettings.enforcement.overrides.deletedUser","(deleted user)")}),R&&e.jsx("p",{className:"text-[10px] text-gray-500 dark:text-gray-400 truncate",children:R.user.email})]}),e.jsxs("label",{className:"text-[10px] text-gray-500 dark:text-gray-400 inline-flex items-center gap-1",children:[e.jsx("input",{type:"checkbox",checked:!!G.exempt,onChange:Z=>y({...u,[C]:{...G,exempt:Z.target.checked}}),disabled:l,className:"accent-indigo-600"}),i("orgSettings.enforcement.overrides.exempt","Exempt")]}),e.jsx(Js,{value:G.hoursPerWeek,onChange:Z=>y({...u,[C]:{...G,hoursPerWeek:Z}}),disabled:l||!!G.exempt}),e.jsx("span",{className:`text-[10px] ${G.exempt?"text-gray-300 line-through":"text-gray-400"}`,children:i("orgSettings.enforcement.overrides.hoursPerWeekUnit","h/wk")}),e.jsx(Xs,{disabled:l,onClick:()=>{const{[C]:Z,...te}=u;y(te)}})]},C)}),!l&&S.length>0&&e.jsx(er,{placeholder:i("orgSettings.enforcement.overrides.pickUser","Pick a member to override…"),options:S,onAdd:C=>y({...u,[C]:{hoursPerWeek:24}})})]})]})}function Ys({active:t,onClick:a,icon:s,label:l,count:i}){return e.jsxs("button",{type:"button",onClick:a,className:`px-2.5 py-1 rounded text-[11px] font-medium inline-flex items-center gap-1 transition-colors ${t?"bg-white dark:bg-gray-800 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700"}`,children:[s,l,e.jsx("span",{className:`text-[9px] font-bold px-1 rounded-full ${t?"bg-indigo-100 text-indigo-700":"bg-gray-200 dark:bg-gray-700 text-gray-500"}`,children:i})]})}function Js({value:t,onChange:a,disabled:s}){const{t:l}=Q();return e.jsx("input",{type:"number",min:0,max:168,step:.5,value:t,onChange:i=>a(Number(i.target.value)||0),disabled:s,"aria-label":l("orgSettings.enforcement.overrides.hoursInputAria","Expected hours per week"),className:"w-16 text-xs border border-gray-200 dark:border-gray-700 rounded px-2 py-0.5 bg-white text-gray-900 dark:bg-gray-800 dark:text-gray-200 text-end font-mono"})}function Xs({disabled:t,onClick:a}){const{t:s}=Q();return e.jsx("button",{type:"button",onClick:a,disabled:t,className:"text-gray-400 hover:text-red-500 disabled:opacity-50 disabled:cursor-not-allowed p-0.5","aria-label":s("orgSettings.enforcement.overrides.removeAria","Remove override"),children:e.jsx(ft,{className:"w-3.5 h-3.5"})})}function Zs({text:t}){return e.jsx("p",{className:"text-[11px] text-gray-400 dark:text-gray-500 italic px-2 py-3",children:t})}function er({placeholder:t,options:a,onAdd:s}){const{t:l}=Q();return e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(st,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),e.jsx(ya,{options:a,selected:[],onChange:i=>{i[0]&&s(i[0])},placeholder:t,searchPlaceholder:l("orgSettings.enforcement.overrides.searchPlaceholder","Search…"),multiple:!1,className:"flex-1"})]})}const yn=["OWNER","ADMIN","MANAGER","MEMBER","GUEST"],Gl=[1,2,3,4,5,6,7];function Sr(t,a){switch(a){case 1:return t("orgSettings.enforcement.day.monday","Monday");case 2:return t("orgSettings.enforcement.day.tuesday","Tuesday");case 3:return t("orgSettings.enforcement.day.wednesday","Wednesday");case 4:return t("orgSettings.enforcement.day.thursday","Thursday");
28case 5:return t("orgSettings.enforcement.day.friday","Friday");case 6:return t("orgSettings.enforcement.day.saturday","Saturday");case 7:return t("orgSettings.enforcement.day.sunday","Sunday");default:return""}}const fn=["UTC","America/Los_Angeles","America/Denver","America/Chicago","America/New_York","America/Toronto","America/Sao_Paulo","Europe/London","Europe/Madrid","Europe/Paris","Europe/Berlin","Europe/Athens","Africa/Johannesburg","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Tokyo","Asia/Seoul","Australia/Sydney","Pacific/Auckland"];function $l({orgId:t}){var Z,te;const{t:a}=Q(),s=_e(),l=zn(),{currentOrg:i,user:c}=Qe(),r=yr(),o=g.useMemo(()=>{if(c!=null&&c.timezone)return c.timezone;try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}},[c==null?void 0:c.timezone]),{policy:x}=ja(),d=g.useMemo(()=>Kt(x,"org.timesheet.enforcement.manage",i==null?void 0:i.role),[x,i==null?void 0:i.role]),u=et("auditLogs"),{data:h,isLoading:f}=ee({queryKey:["timesheet-enforcement-settings",t],queryFn:()=>B.getTimesheetEnforcementSettings(t),staleTime:3e4}),[j,b]=g.useState(!1),[y,N]=g.useState(!1),[p,S]=g.useState(null);g.useEffect(()=>{if(!h)return;const{_prereqs:A,...P}=h;S(P)},[h]);const C=g.useMemo(()=>{if(!h||!p)return!1;const{_prereqs:A,...P}=h;return JSON.stringify(P)!==JSON.stringify(p)},[h,p]),G=$({mutationFn:()=>B.saveTimesheetEnforcementSettings(t,p),onSuccess:A=>{k.success(A.enabled?a("orgSettings.enforcement.toast.enabled","Compliance enforcement enabled, reminder worker will pick up settings on the next hourly tick."):a("orgSettings.enforcement.toast.disabled","Enforcement disabled.")),s.invalidateQueries({queryKey:["timesheet-enforcement-settings",t]})},onError:A=>{var z,M;((M=(z=A==null?void 0:A.response)==null?void 0:z.data)==null?void 0:M.code)==="RATE_CARDS_REQUIRED"?k.error(J=>e.jsxs("div",{className:"flex flex-col gap-2 max-w-sm",children:[e.jsx("p",{className:"text-sm font-semibold",children:a("orgSettings.enforcement.toast.rateCardsTitle","Set up rate cards first")}),e.jsx("p",{className:"text-xs text-gray-600",children:a("orgSettings.enforcement.toast.rateCardsBody","Compliance enforcement needs at least one active rate card so the cost-at-risk KPI works. Add one before enabling enforcement.")}),e.jsx("button",{type:"button",onClick:()=>{k.dismiss(J.id),l("/rate-cards")},className:"text-xs font-semibold text-indigo-600 hover:underline self-start",children:a("orgSettings.enforcement.toast.rateCardsCta","Open rate cards →")})]}),{duration:8e3}):k.error(U(A,"save enforcement settings"))}});if(f||!p||!h)return e.jsx(oe,{className:"h-72 rounded-xl"});const R=h._prereqs;return e.jsxs("div",{className:"border border-indigo-200 dark:border-indigo-700 rounded-xl p-5 bg-white dark:bg-gray-800/40 shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 pb-4 border-b border-gray-100 dark:border-gray-700",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(Ya,{className:"w-4 h-4 text-indigo-500"}),e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-white",children:a("orgSettings.enforcement.title","Compliance enforcement")}),e.jsx("span",{className:"text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300",children:"PRO+"})]}),e.jsx("p",{className:"text-[11px] text-gray-500 dark:text-gray-400 leading-relaxed",children:a("orgSettings.enforcement.subtitle","Track who's logging hours and remind people when they fall short of their expected weekly capacity. Visibility-only at this tier, hard lock-outs land at ENTE
28RPRISE.")}),e.jsxs("p",{className:"text-[10px] text-gray-400 dark:text-gray-500 mt-1",children:[a("orgSettings.enforcement.permissionLabel","Permission:")," ",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 py-0.5 rounded text-[10px]",children:"org.timesheet.enforcement.manage"})," ",a("orgSettings.enforcement.permissionDefault","· default ADMIN+")]})]}),e.jsx("button",{disabled:!d||G.isPending,onClick:()=>S({...p,enabled:!p.enabled}),role:"switch","aria-checked":p.enabled,"aria-label":a("orgSettings.enforcement.enableAria","Enable compliance enforcement"),className:`relative flex-shrink-0 inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 ${p.enabled?"bg-indigo-600":"bg-gray-200 dark:bg-gray-700"} ${d?"":"opacity-60 cursor-not-allowed"}`,title:d?void 0:a("orgSettings.enforcement.requiresPermission","Requires org.timesheet.enforcement.manage permission"),children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${p.enabled?"translate-x-6 rtl:-translate-x-6":"translate-x-1 rtl:-translate-x-1"}`})})]}),e.jsxs("div",{className:"mt-4 rounded-lg border border-amber-200 dark:border-amber-800/40 bg-amber-50 dark:bg-amber-900/20 p-3",children:[e.jsx("p",{className:"text-[11px] font-semibold text-amber-900 dark:text-amber-200 mb-2",children:a("orgSettings.enforcement.prereq.title","Prerequisites (enforced by Onplana)")}),e.jsxs("div",{className:"space-y-1.5 text-[11px]",children:[e.jsx(kn,{ok:R.rateCardsConfigured,label:a("orgSettings.enforcement.prereq.rateCards","At least 1 rate card configured ({{found}} found)",{found:R.rateCardCount}),link:"/rate-cards",linkLabel:a("orgSettings.enforcement.prereq.manageLink","Manage")}),e.jsx(kn,{ok:R.billableFieldVisible!==!1,label:a("orgSettings.enforcement.prereq.billableField","Project billable field visible on project forms"),link:"/org/settings?tab=configuration&subtab=custom-fields",linkLabel:a("orgSettings.enforcement.prereq.builtInFieldsLink","Built-in Fields")})]}),d&&e.jsxs("button",{onClick:()=>b(!0),className:"mt-3 text-[11px] font-medium text-indigo-700 dark:text-indigo-300 inline-flex items-center gap-1.5 hover:underline",children:[e.jsx(Ns,{className:"w-3.5 h-3.5"}),a("orgSettings.enforcement.prereq.bulkClassify","Bulk-classify projects (review billable / non-billable mix before enabling)")]})]}),e.jsx(ho,{open:j,onClose:()=>b(!1)}),e.jsxs("button",{type:"button",onClick:()=>N(A=>!A),"aria-expanded":y,className:"mt-4 w-full flex items-center gap-1.5 text-xs font-semibold text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors",children:[e.jsx(gt,{className:`w-4 h-4 transition-transform ${y?"rotate-180":""}`}),a("orgSettings.enforcement.settingsToggle","Enforcement settings"),e.jsx("span",{className:"font-normal text-gray-400 dark:text-gray-500",children:u?a("orgSettings.enforcement.settingsToggleHintWithMode","(expected hours, deadline, reminders, exemptions, enforcement mode)"):a("orgSettings.enforcement.settingsToggleHint","(expected hours, deadline, reminders, exemptions)")})]}),y&&e.jsxs("div",{className:"space-y-5 pt-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:a("orgSettings.enforcement.expected.label","Expected hours per member")}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ka,{checked:p.expectedHoursSource==="capacity",onClick:()=>S({...p,expectedHoursSource:"capacity"}),disabled:!d,title:a("orgSettings.enforcement.expected.capacityTitle","Per-user capacity"),hint:a("orgSettings.enforcement.expected.capacityHint","Reads from ResourceCapacity")}),e.jsx(Ka,{checked:p.expectedHoursSource==="fixed",onClick:()=>S({...p,expectedHoursSource:"fixed"}),disabled:!d,title:a("orgSettings.enforcement.expected.fixedTitle","Fixed"),hint:a("orgSettings.enforcement.expected.fixedHint","Same for everyone (set below)")})]}),e.jsx("p",{className:"text-[10px] text-gray-400 mt-1.5",children:a("orgSettings.enforcement.expected.overrideHint","Override this baseline per team, role, or user in the Expected hours overrides editor below. Resolution order: user → team → role → org default.")}),p.expectedHoursSource==="fixed"&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("label",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:a("orgSettings.enforcement.expected.hoursPerWeekLabel","Hours/week:")}),e.jsx("input",{type:"number",min:1,max:168,value:p.fixedHoursPerWeek,onChange:A=>S({...p,fixedHoursPerWeek:Number(A.target.value)||0}),disabled:!d,"aria-label":a("orgSettings.enforcement.expected.hoursPerWeekAri
28a","Fixed expected hours per week"),className:"input text-xs py-1 w-20 text-center font-mono"})]})]}),e.jsx(Kl,{orgId:t,draft:p,onChange:S,disabled:!d}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:[a("orgSettings.enforcement.threshold.label","Compliance threshold")," ",e.jsx("span",{className:"text-gray-400 font-normal ms-1",children:a("orgSettings.enforcement.threshold.hint","(% of expected hours required to be considered compliant)")})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"range",min:.5,max:1,step:.05,value:p.compliantThreshold,onChange:A=>S({...p,compliantThreshold:Number(A.target.value)}),disabled:!d,"aria-label":a("orgSettings.enforcement.threshold.aria","Compliance threshold"),className:"flex-1 accent-indigo-600"}),e.jsx("span",{className:"text-xs font-mono w-12 text-end",children:a("orgSettings.enforcement.threshold.value","{{pct}}%",{pct:Math.round(p.compliantThreshold*100)})})]})]}),e.jsx(tr,{checked:p.requireIsBillable,onChange:A=>S({...p,requireIsBillable:A}),disabled:!d,title:e.jsxs("span",{children:[a("orgSettings.enforcement.requireBillable.titlePrefix","Require")," ",e.jsx("code",{className:"text-[10px] bg-gray-100 dark:bg-gray-700 px-1 py-0.5 rounded",children:"isBillable"})," ",a("orgSettings.enforcement.requireBillable.titleSuffix","on every project")]}),hint:a("orgSettings.enforcement.requireBillable.hint","When on, the Custom Fields → Billable field is forced visible + required. It drives billable-hours reporting; cost at risk prices the total-hours gap.")}),e.jsx(tr,{checked:!!p.timeOffRequireApproval,onChange:A=>S({...p,timeOffRequireApproval:A}),disabled:!d,title:e.jsx("span",{children:a("orgSettings.enforcement.timeOffApproval.title","Time off needs approval")}),hint:a("orgSettings.enforcement.timeOffApproval.hint","When on, a member’s time off waits for a timesheet approver (or an owner or admin) to approve it. Only approved days reduce planned capacity and expected hours.")}),e.jsx(tr,{checked:p.requireRateCards,onChange:()=>{},disabled:!0,title:e.jsxs("span",{children:[a("orgSettings.enforcement.rateCardPrereq.title","Hard prereq: rate cards configured")," ",e.jsx("span",{className:"ms-2 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300",children:a("orgSettings.enforcement.rateCardPrereq.lockedBadge","Locked on")})]}),hint:a("orgSettings.enforcement.rateCardPrereq.hint","Enforcement requires at least one rate card. This cannot be disabled.")}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:a("orgSettings.enforcement.deadline.label","Submission deadline")}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("select",{value:p.deadline.dayOfWeek,onChange:A=>S({...p,deadline:{...p.deadline,dayOfWeek:Number(A.target.value)}}),disabled:!d,"aria-label":a("orgSettings.enforcement.deadline.dayAria","Deadline day of week"),className:"input text-xs py-1.5",children:Gl.map(A=>e.jsx("option",{value:A,children:Sr(a,A)},A))}),e.jsx("span",{className:"text-xs text-gray-500",children:a("orgSettings.enforcement.deadline.at","at")}),e.jsx("select",{value:p.deadline.hour,onChange:A=>S({...p,deadline:{...p.deadline,hour:Number(A.target.value)}}),disabled:!d,"aria-label":a("orgSettings.enforcement.deadline.hourAria","Deadline hour"),className:"input text-xs py-1.5",children:Array.from({length:24}).map((A,P)=>e.jsx("option",{value:P,children:wr(a,P)},P))}),e.jsx("span",{className:"text-xs text-gray-500",children:a("orgSettings.enforcement.deadline.in","in")}),e.jsxs("select",{value:p.deadline.timezone,onChange:A=>S({...p,deadline:{...p.deadline,timezone:A.target.value}}),disabled:!d,"aria-label":a("orgSettings.enforcement.deadline.timezoneAria","Deadline timezone"),className:"input text-xs py-1.5 font-mono",children:[!fn.includes(p.deadline.timezone)&&e.jsx("option",{value:p.deadline.timezone,children:p.deadline.timezone}),fn.map(A=>e.jsx("option",{value:A,children:A},A))]}),d&&p.deadline.timezone!==o&&e.jsx("button",{type:"button",onClick:()=>S({...p,deadline:{...p.deadline,timezone:o}}),className:"text-[11px] text-indigo-600 hover:underline",title:a("orgSettings.enforcement.deadline.useMyTimezoneTitle","Switch the deadline timezone to your profile setting ({{timezone}})",{timezone:o}),children:a("orgSettings.enforcement.deadline.useMyTimezone","Use my timezone ({{timezone}})",{timezone:o})})]}),e.jsxs("p",{className:"text-[10px] text-gray-400 mt-1.5",children:[a("orgSettings.enforcement.deadline.storedHint","Stored as the org-level deadline timezone, every viewer sees the same wall-clock time. Holidays follow your")," ",e.jsx(Wt,{to:"/org/settings?tab=configuration&subtab=calendars",className:"text-indigo-600 hover:underline",children:a("orgSettings.enforcement.deadline.calendarLink","working c
28alendar's shift policy")}),"."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:a("orgSettings.enforcement.reminders.label","Reminders")}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(bs,{checked:p.reminderCadence.perUserNudge,onChange:A=>S({...p,reminderCadence:{...p.reminderCadence,perUserNudge:A}}),disabled:!d,title:a("orgSettings.enforcement.reminders.perUserNudgeTitle","Per-user nudge"),hint:a("orgSettings.enforcement.reminders.perUserNudgeHint",`Sent {{when}}, "You've logged X of Y hours. Submit by {{deadline}}."`,{when:Wl(a,p),deadline:Hl(a,p)})}),e.jsx(bs,{checked:p.reminderCadence.adminDigest,onChange:A=>S({...p,reminderCadence:{...p.reminderCadence,adminDigest:A}}),disabled:!d,title:a("orgSettings.enforcement.reminders.adminDigestTitle","Admin digest"),hint:a("orgSettings.enforcement.reminders.adminDigestHint","Monday 9am, weekly summary to OWNER + ADMIN with non-compliant members + cost at risk.")}),u?e.jsxs("div",{className:"space-y-2",children:[e.jsx(bs,{checked:((Z=p.escalation)==null?void 0:Z.enabled)??!1,onChange:A=>{var P;return S({...p,escalation:{enabled:A,template:((P=p.escalation)==null?void 0:P.template)??"STANDARD"}})},disabled:!d,title:e.jsxs("span",{children:[a("orgSettings.enforcement.escalation.title","Escalation chain")," ",e.jsx("span",{className:"ms-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",children:"ENTERPRISE"})]}),hint:a("orgSettings.enforcement.escalation.hint","Hourly worker advances each non-compliant member through the chain. Auto-resolves when they catch up.")}),((te=p.escalation)==null?void 0:te.enabled)&&e.jsxs("div",{className:"ms-6 mt-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-[11px] text-gray-700 dark:text-gray-300",children:a("orgSettings.enforcement.escalation.templateLabel","Template:")}),e.jsxs("select",{value:p.escalation.template,onChange:A=>S({...p,escalation:{enabled:p.escalation.enabled,template:A.target.value}}),disabled:!d,"aria-label":a("orgSettings.enforcement.escalation.templateAria","Escalation template"),className:"input text-[11px] py-1",children:[e.jsx("option",{value:"LIGHT",children:a("orgSettings.enforcement.escalation.templateLight","Light, 2 nudges, no blocks")}),e.jsx("option",{value:"STANDARD",children:a("orgSettings.enforcement.escalation.templateStandard","Standard, user → manager → owner")}),e.jsx("option",{value:"STRICT",children:a("orgSettings.enforcement.escalation.templateStrict","Strict, block at day 5")})]})]}),p.escalation.template==="STRICT"&&e.jsx("p",{className:"text-[10px] text-amber-700 dark:text-amber-400 bg-amber-50/50 dark:bg-amber-950/20 border border-amber-200/50 dark:border-amber-800/40 rounded px-2 py-1",children:a("orgSettings.enforcement.escalation.strictNote","ⓘ The day-5 BLOCK step currently sends a notification to the user; per-user enforcement override that fully blocks ships in Phase 3d. Org-level HARD_BLOCK above remains in effect regardless.")})]})]}):e.jsx(bs,{checked:p.reminderCadence.escalation,onChange:()=>{},disabled:!0,title:e.jsxs("span",{children:[a("orgSettings.enforcement.escalation.title","Escalation chain")," ",e.jsx("span",{className:"ms-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",children:"ENTERPRISE+"})]}),hint:a("orgSettings.enforcement.escalation.lockedHint","Multi-step nudges with hard-lock at the end.")})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:a("orgSettings.enforcement.exemptRoles.label","Exempt from compliance")}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:yn.map(A=>{const P=p.exemptRoles.includes(A);return e.jsxs("button",{type:"button",disabled:!d,onClick:()=>S({...p,exemptRoles:P?p.exemptRoles.filter(z=>z!==A):[...p.exemptRoles,A]}),"aria-pressed":P,className:`text-[11px] font-semibold px-2.5 py-1 rounded-full border ${P?"bg-gray-100 text-gray-700 border-gray-300 dark:bg-gray-700 dark:text-gray-200":"bg-white text-gray-400 border-gray-200 hover:border-gray-300 dark:bg-gray-800 dark:border-gray-600"} ${d?"":"opacity-60 cursor-not-allowed"}`,children:[A," ",P?"✕":"+"]},A)})}),e.jsx("p",{className:"text-[10px] text-gray-400 mt-1.5",children:a("orgSettings.enforcement.exemptRoles.hint","Members in these roles are not counted in compliance stats and don't receive nudges.")})]}),u?e.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg p-3 bg-gray-50/40 dark:bg-gray-800/30 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ke,{className:"w-3.5 h-3.5 text-gray-700 dark:text-gray-300"}),e.jsx("span",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300",children:a("orgSettings.enforcement.mode.label","Enforcement mode")}),e.jsx("span",{className:"ms-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",children:"ENTERPRISE"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[e.jsx(Ka,{checked:(p.enforcementMode??"WARN")==="WARN",onClick:()=>S({...p,enforcementMode:"WARN"}),disabled:!d,title:a("orgSettings.enforcement.mode.warnTitle","Warn"),hint:a("orgSettings.enforcement.mode.warnHint","Compliance is visible + reminders fire. Mutations stay open.")}),e.jsx(Ka,{checked:p.enforcementMode==="SOFT_BLOCK",onClick:()=>S({...p,enforcementMode:"SOFT_BLOCK"}),disabled:!d,title:a("orgSettings.enforcement.mode.softBlockTitle","Soft block"),hint:a("orgSettings.enforcement.mode.softBlockHint","Persistent banner on every page. Mutations still allowed.")}
28),e.jsx(Ka,{checked:p.enforcementMode==="HARD_BLOCK",onClick:()=>S({...p,enforcementMode:"HARD_BLOCK"}),disabled:!d,title:a("orgSettings.enforcement.mode.hardBlockTitle","Hard block"),hint:a("orgSettings.enforcement.mode.hardBlockHint","Server-side 403 on task/project/sprint mutations until prior week is filed.")})]}),p.enforcementMode==="HARD_BLOCK"&&e.jsxs("div",{className:"space-y-2 pt-1 border-t border-gray-100 dark:border-gray-700",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs text-gray-700 dark:text-gray-300",children:a("orgSettings.enforcement.hardBlock.gracePeriodLabel","Grace period")}),e.jsx("input",{type:"number",min:0,max:30,value:p.hardBlockGracePeriodDays??3,onChange:A=>S({...p,hardBlockGracePeriodDays:Number(A.target.value)}),disabled:!d,"aria-label":a("orgSettings.enforcement.hardBlock.gracePeriodAria","Grace period in days"),className:"input text-xs py-1 w-20"}),e.jsx("span",{className:"text-xs text-gray-500",children:a("orgSettings.enforcement.hardBlock.gracePeriodHint","days after deadline before lock fires")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs text-gray-700 dark:text-gray-300 whitespace-nowrap",children:a("orgSettings.enforcement.hardBlock.autoUnlockLabel","Auto-unlock on submission")}),e.jsx("input",{type:"checkbox",checked:p.unlockOnSubmission??!0,onChange:A=>S({...p,unlockOnSubmission:A.target.checked}),disabled:!d,"aria-label":a("orgSettings.enforcement.hardBlock.autoUnlockLabel","Auto-unlock on submission"),className:"accent-indigo-600"}),e.jsx("span",{className:"text-[10px] text-gray-500",children:a("orgSettings.enforcement.hardBlock.autoUnlockHint","Lock clears as soon as the user submits the missing week.")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-gray-700 dark:text-gray-300 mb-1",children:a("orgSettings.enforcement.hardBlock.exemptRolesLabel","Roles exempt from hard-lock")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:yn.map(A=>{const P=(p.hardBlockExemptRoles??["OWNER","ADMIN"]).includes(A);return e.jsxs("button",{type:"button",disabled:!d,onClick:()=>{const z=p.hardBlockExemptRoles??["OWNER","ADMIN"];S({...p,hardBlockExemptRoles:P?z.filter(M=>M!==A):[...z,A]})},"aria-pressed":P,className:`text-[10px] font-semibold px-2 py-0.5 rounded-full border ${P?"bg-gray-100 text-gray-700 border-gray-300 dark:bg-gray-700 dark:text-gray-200":"bg-white text-gray-400 border-gray-200 hover:border-gray-300 dark:bg-gray-800 dark:border-gray-600"} ${d?"":"opacity-60 cursor-not-allowed"}`,children:[A," ",P?"✕":"+"]},A)})}),e.jsx("p",{className:"text-[10px] text-gray-400 mt-1",children:a("orgSettings.enforcement.hardBlock.exemptRolesHint","OWNER + ADMIN are exempt by default so admins can always unblock locked users.")})]})]})]}):e.jsxs("div",{className:"border border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-3 bg-gray-50/40 dark:bg-gray-800/30 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-700 dark:text-gray-300 flex items-center gap-1.5",children:[e.jsx(ke,{className:"w-3.5 h-3.5"})," ",a("orgSettings.enforcement.upsell.title","Hard-lock + audit trail"),e.jsx("span",{className:"ms-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",children:"ENTERPRISE+"})]}),e.jsx("p",{className:"text-[10px] text-gray-500 dark:text-gray-400 mt-0.5",children:a("orgSettings.enforcement.upsell.body","Block task editing until the previous week is submitted. Every miss/lock writes an AuditLog row for SOX/HIPAA evidence.")})]}),!r&&e.jsx(Wt,{to:"/billing",className:"text-[11px] font-medium text-indigo-600 hover:underline whitespace-nowrap",children:a("orgSettings.enforcement.upsell.cta","Vie
28w Enterprise →")})]})]}),d&&C&&e.jsxs("div",{className:"mt-4 flex items-center justify-end gap-3 pt-3 border-t border-gray-100 dark:border-gray-700",children:[e.jsxs("span",{className:"text-xs text-amber-700 flex items-center gap-1",children:[e.jsx(je,{className:"w-3.5 h-3.5"})," ",a("orgSettings.enforcement.unsavedChanges","Unsaved changes")]}),e.jsx("button",{disabled:G.isPending,onClick:()=>{if(h){const{_prereqs:A,...P}=h;S(P)}},className:"btn-secondary text-xs py-1.5",children:a("common.cancel","Cancel")}),e.jsxs("button",{disabled:G.isPending,onClick:()=>G.mutate(),className:"btn-primary text-xs py-1.5 disabled:opacity-50 flex items-center gap-1.5",children:[G.isPending&&e.jsx(At,{className:"w-3.5 h-3.5 animate-spin"}),G.isPending?a("orgSettings.saving","Saving…"):a("orgSettings.enforcement.saveChanges","Save changes")]})]}),!d&&e.jsxs("div",{className:"mt-4 pt-3 border-t border-gray-100 dark:border-gray-700 flex items-center gap-2 text-[11px] text-gray-500 dark:text-gray-400",children:[e.jsx(ke,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{children:[a("orgSettings.enforcement.readOnlyPrefix","Read-only, your role doesn't have")," ",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 py-0.5 rounded text-[10px]",children:"org.timesheet.enforcement.manage"}),"."]})]})]})}function kn({ok:t,label:a,link:s,linkLabel:l}){const{t:i}=Q();return e.jsxs("div",{className:"flex items-center gap-2",children:[t?e.jsx(ct,{className:"w-3.5 h-3.5 text-emerald-600 flex-shrink-0"}):e.jsx(je,{className:"w-3.5 h-3.5 text-amber-600 flex-shrink-0"}),e.jsx("span",{className:t?"text-gray-700 dark:text-gray-300":"text-amber-800 dark:text-amber-200",children:a}),s&&e.jsxs(Wt,{to:s,className:"text-indigo-600 hover:underline ms-auto flex items-center gap-0.5",children:[l??i("orgSettings.enforcement.prereq.openLink","Open")," ",e.jsx(ha,{className:"w-3 h-3"})]})]})}function Ka({checked:t,onClick:a,disabled:s,title:l,hint:i,badge:c}){return e.jsxs("button",{type:"button",disabled:s,onClick:a,className:`text-start border rounded-lg p-2.5 transition-colors ${t?"border-indigo-400 bg-indigo-50 dark:bg-indigo-900/30 dark:border-indigo-600":"border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600"} ${s?"opacity-60 cursor-not-allowed":""}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("input",{type:"radio",checked:t,onChange:()=>{},disabled:s,className:"accent-indigo-600 pointer-events-none"}),e.jsx("span",{className:"text-xs font-medium text-gray-900 dark:text-gray-100",children:l})]}),e.jsxs("p",{className:"text-[10px] text-gray-500 dark:text-gray-400 mt-0.5",children:[i,c&&e.jsx("span",{className:"ms-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-purple-100 text-purple-700",children:c})]})]})}function tr({checked:t,onChange:a,disabled:s,title:l,hint:i}){return e.jsxs("div",{className:"flex items-start justify-between gap-3 pb-3 border-b border-gray-100 dark:border-gray-700",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300",children:l}),e.jsx("p",{className:"text-[10px] text-gray-500 dark:text-gray-400 mt-0.5",children:i})]}),e.jsx("button",{disabled:s,onClick:()=>a(!t),"aria-pressed":t,className:`relative inline-flex h-5 w-9 items-center rounded-full flex-shrink-0 transition-colors ${t?"bg-indigo-600":"bg-gray-300 dark:bg-gray-600"} ${s?"opacity-70 cursor-not-allowed":""}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 transform rounded-full bg-white shadow transition-transform ${t?"translate-x-5 rtl:-translate-x-5":"translate-x-1 rtl:-translate-x-1"}`})})]})}function bs({checked:t,onChange:a,disabled:s,title:l,hint:i}){return e.jsxs("label",{className:`flex items-start gap-2.5 p-2.5 rounded-lg bg-gray-50/60 dark:bg-gray-800/40 ${s?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[e.jsx("input",{type:"checkbox",checked:t,onChange:c=>a(c.target.checked),disabled:s,className:"mt-0.5 accent-indigo-600"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-gray-900 dark:text-gray-100",children:l}),e.jsx("p",{className:"text-[10px] text-gray-500 dark:text-gray-400 mt-0.5",children:i})]})]})}function wr(t,a){const s=a>=12?t("orgSettings.enforcement.time.pm","pm"):t("orgSettings.enforcement.time.am","am"),l=(a+11)%12+1;return t("orgSettings.enforcement.time.hour","{{hour}}:00 {{ampm}}",{hour:l,ampm:s})}function Hl(t,a){return t("orgSettings.enforcement.time.dayAtHour","{{day}} {{hour}}",{day:Sr(t,a.deadline.dayOfWeek),hour:wr(t,a.deadline.hour)})}function Wl(t,a){const s=Math.max(0,a.deadline.hour-1);return t("orgSettings.enforcement.time.dayAtHour","{{day}} {{hour}}",{day:Sr(t,a.deadline.dayOfWeek),hour:wr(t,s)})}function Vl(){const t=new Date;return t.setDate(t.getDate()-30),t.toISOString().slice(0,10)}function zl(){return new Date().toISOString().slice(0,10)}function jn(t,a){switch(a){case"csv":return t("orgSettings.evidence.formatCsv","CSV (Vanta / Drata / SecurityScorecard)");case"json":return t("orgSettings.evidence.formatJson","JSON (full payload + audit events)");default:return a}}function Ql(){const{t}=Q(),{currentOrg:a}=Qe(),{policy:s}=ja(),l=et("auditLogs"),i=Kt(s,"org.compliance.manage",a==null?void 0:a.role),[c,r]=g.useState(Vl()),[o,x]=g.useState(zl()),[d,u]=g.useState("csv"),h=$({mutationFn:async()=>
28{if(d==="csv"){const y=await fa.downloadEvidenceCsv(c,o);return vn(y,`compliance-evidence-${c}-to-${o}.csv`),{format:"csv"}}const j=await fa.getEvidence(c,o),b=new Blob([JSON.stringify(j,null,2)],{type:"application/json"});return vn(b,`compliance-evidence-${c}-to-${o}.json`),{format:"json",weeks:j.period.weeks,events:j.auditEvents.length}},onSuccess:j=>{k.success(t("orgSettings.evidence.toastExported","Evidence exported ({{format}})",{format:j.format.toUpperCase()}))},onError:j=>{var N,p;const b=(N=j==null?void 0:j.response)==null?void 0:N.status,y=(p=j==null?void 0:j.response)==null?void 0:p.data;b===400&&(y!=null&&y.maxDays)?k.error(t("orgSettings.evidence.toastRangeTooLong","Date range too long, capped at {{maxDays}} days. Run multiple exports for longer periods.",{maxDays:y.maxDays})):b===403?k.error(t("orgSettings.evidence.toastForbidden","You don't have permission to export compliance evidence.")):k.error(U(j,"export evidence"))}});if(!l)return null;const f=Math.max(0,Math.round((new Date(o).getTime()-new Date(c).getTime())/864e5)+1);return e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yi,{className:"w-4 h-4 text-emerald-600 dark:text-emerald-400"}),e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:t("orgSettings.evidence.title","Compliance evidence export")}),e.jsx("span",{className:"ms-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",children:t("orgSettings.evidence.enterpriseBadge","ENTERPRISE")})]}),e.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 -mt-2",children:[t("orgSettings.evidence.descriptionBefore","Generate SOX/HIPAA-grade evidence reports for an external auditor. Each export writes an AuditLog row (TIMESHEET_EVIDENCE_EXPORTED) to preserve the chain of custody. Auditors with a")," ",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 rounded",children:"COMPLIANCE_READ"})," ",t("orgSettings.evidence.descriptionAfter","PAT can fetch the same JSON directly.")]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:t("orgSettings.evidence.fieldFrom","From")}),e.jsx("input",{type:"date",value:c,onChange:j=>r(j.target.value),className:"input text-xs py-1.5 w-full"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:t("orgSettings.evidence.fieldTo","To")}),e.jsx("input",{type:"date",value:o,onChange:j=>x(j.target.value),className:"input text-xs py-1.5 w-full"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:t("orgSettings.evidence.fieldFormat","Format")}),e.jsxs("select",{value:d,onChange:j=>u(j.target.value),className:"input text-xs py-1.5 w-full",children:[e.jsx("option",{value:"csv",children:jn(t,"csv")}),e.jsx("option",{value:"json",children:jn(t,"json")})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-gray-100 dark:border-gray-700",children:[e.jsxs("p",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:[t("orgSettings.evidence.rangeLabel","Range:")," ",e.jsx("span",{className:"font-medium",children:t("orgSettings.evidence.dayCount",{count:f,defaultValue_one:"{{count}} day",defaultValue_other:"{{count}} days"})}),f>90&&e.jsx("span",{className:"ms-2 text-amber-600",children:t("orgSettings.evidence.capWarning","(exceeds 90-day cap; will be rejected)")}),f<=0&&e.jsx("span",{className:"ms-2 text-amber-600",children:t("orgSettings.evidence.dateOrderWarning","The 'To' date must be after 'From'.")})]}),e.jsxs("button",{type:"button",onClick:()=>h.mutate(),disabled:h.isPending||f>90||f<=0,className:"btn-primary text-xs py-1.5 flex items-center gap-1.5 disabled:opacity-50",children:[h.isPending?e.jsx(At,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ta,{className:"w-3.5 h-3.5"}),h.isPending?t("orgSettings.evidence.generating","Generating…"):t("orgSettings.evidence.generate","Generate")]})]}),e.jsxs("p",{className:"text-[10px] text-gray-400 mt-1",children:[t("orgSettings.evidence.patHintBefore","Need an auditor PAT? Issue one with the")," ",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 rounded",children:"COMPLIANCE_READ"})," ",t("orgSettings.evidence.patHintAfter","scope from")," ",e.jsx(Wt,{to:"/settings",className:"text-indigo-600 hover:underline",children:t("orgSettings.evidence.patHintLink","Settings → Developer → API tokens")}),"."]})]}):e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-gray-500 dark:text-gray-400 pt-2 border-t border-gray-100 dark:border-gray-700",children:[e.jsx(ke,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{children:[t("orgSettings.evidence.readOnly","Read-only, your role doesn't have")," ",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 py-0.5 rounded text-[10px]",children:"org.compliance.manage"}),"."]})]})]})}
28function vn(t,a){const s=URL.createObjectURL(t),l=document.createElement("a");l.href=s,l.download=a,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(s),0)}const Nn={start:t=>za.get(`/organizations/${t}/export`,{responseType:"blob"}),list:(t,a=5)=>za.get(`/organizations/${t}/exports`,{params:{limit:a}})};function Yl(t,a){switch(a){case"PENDING":return t("orgSettings.dataExport.statusPending","Pending");case"RUNNING":return t("orgSettings.dataExport.statusRunning","Running");case"COMPLETED":return t("orgSettings.dataExport.statusCompleted","Completed");case"FAILED":return t("orgSettings.dataExport.statusFailed","Failed");default:return a}}function Jl(t,a){return!a&&a!==0?"-":a<1024?t("orgSettings.dataExport.bytes","{{amount}} B",{amount:a}):a<1024*1024?t("orgSettings.dataExport.kilobytes","{{amount}} KB",{amount:(a/1024).toFixed(1)}):t("orgSettings.dataExport.megabytes","{{amount}} MB",{amount:(a/1024/1024).toFixed(1)})}function Xl(t){if(!t)return"-";try{return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}async function Zl(t){if(!t||typeof t.text!="function")return null;try{const a=await t.text();return JSON.parse(a)}catch{return null}}function ed({orgId:t}){var x;const{t:a}=Q(),s=_e(),[l,i]=g.useState(!1),r=(x=ee({queryKey:["org-data-exports",t],queryFn:async()=>(await Nn.list(t,5)).data,enabled:!!t}).data)==null?void 0:x[0],o=async()=>{var d,u;if(!l){i(!0);try{const h=await Nn.start(t),f=new Blob([h.data],{type:"application/zip"}),b=(h.headers["content-disposition"]||h.headers["Content-Disposition"]||"").match(/filename="?([^";]+)"?/i),y=b?b[1]:`onplana-org-export-${t}.zip`,N=window.URL.createObjectURL(f),p=document.createElement("a");p.href=N,p.download=y,document.body.appendChild(p),p.click(),p.remove(),window.URL.revokeObjectURL(N),k.success(a("orgSettings.dataExport.toastDownloaded","Export downloaded")),s.invalidateQueries({queryKey:["org-data-exports",t]})}catch(h){const f=h,j=(d=f==null?void 0:f.response)==null?void 0:d.status,b=await Zl((u=f==null?void 0:f.response)==null?void 0:u.data);if(j===429){const y=(b==null?void 0:b.retryAfterSeconds)??0,N=Math.floor(y/3600),p=Math.ceil(y%3600/60),S=y>=3600?a("orgSettings.dataExport.waitHoursMinutes","{{hours}}h {{minutes}}m",{hours:N,minutes:p}):a("orgSettings.dataExport.waitMinutes","{{minutes}}m",{minutes:p});k.error(a("orgSettings.dataExport.toastRateLimited","Already exported within the last 24 hours. Next export available in {{when}}.",{when:S}),{duration:6e3})}else j===413?k.error(a("orgSettings.dataExport.toastTooLarge","Your organization is too large for self-service export. Contact support and we will generate one for you."),{duration:8e3}):k.error((b==null?void 0:b.error)||a("orgSettings.dataExport.toastFailed","Failed to export organization data"));s.invalidateQueries({queryKey:["org-data-exports",t]})}finally{i(!1)}}};return e.jsxs("div",{id:"data-export",className:"border-t border-gray-200 dark:border-gray-700 pt-6 mt-6 scroll-mt-20",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 mb-1",children:a("orgSettings.dataExport.title","Data export")}),e.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 mb-3",children:a("orgSettings.dataExport.description","Download a ZIP archive of this organization's data. Includes projects, tasks, comments, timesheet entries, members, governance proposals, and the last 90 days of audit log.")}),e.jsxs("p",{className:"text-xs text-gray-600 dark:text-gray-400 mb-3",children:[e.jsx("strong",{children:a("orgSettings.dataExport.filesExcludedWarning","Workspace documents and file attachments are NOT included.")})," ",e.jsx(Ht,{i18nKey:"orgSettings.dataExport.filesExcludedWhere",defaults:"Download organization-wide files from <0>Workspace</0>, and each project's files from its Documents → Document Folders, before any deletion countdown ends. File bytes are unrecoverable once the organization is deleted.",components:[e.jsx(Wt,{to:"/workspace",className:"underline"})]})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-4",children:a("orgSettings.dataExport.exclusions","Excludes: passwords, 2FA secrets, API token values, OAuth refresh tokens, integration credentials. Rate limit: 1 export per day per organization.")}),r&&e.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400 mb-3",children:[e.jsx("span",{className:"font-medium",children:a("orgSettings.dataExport.mostRecent","Most recent export:")})," ",Xl(r.createdAt),r.fileSize?e.jsxs(e.Fragment,{children:[" · ",Jl(a,r.fileSize)]}):null," ",e.jsxs("span",{className:"text-gray-400",children:["(",Yl(a,r.status),")"]})]}),e.jsxs("button",{type:"button",onClick:o,disabled:l,className:"btn-primary text-sm inline-flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(ta,{className:"w-4 h-4"}),l?a("orgSettings.dataExport.preparing","Preparing export…"):a("orgSettings.dataExport.exportAction","Export organization data")]})]})}function td(){const{t}=Q(),a=_e(),{currentOrg:s}=Qe(),{policy:l}=ja(),i=et("auditLogs"),c=Kt(l,"org.compliance.manage",s==null?void 0:s.role),[r,o]=g.useState(!0),[x,d]=g.useState(!1),{data:u,isLoading:h,isError:f,refetch:j}=ts({queryKey:["timesheet-exceptions",s==null?void 0:s.id,r],queryFn:()=>fa.listExceptions(r),enabled:!!(s!=null&&s.id)&&i&&c,staleTime:3e4}),b=$({mutationFn:y=>fa.revokeException(y),onSuccess:()=>{a.invalidateQueries({queryKey:["timesheet-exceptions"]}),k.success(t("orgSettings.exceptions.toastRevoked","Exception revoked"))},onError:y=>k.error(U(y,"revoke exception"))});return i?e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ji,{className:"w-4 h-4 text-amber-600 dar
28k:text-amber-400"}),e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:t("orgSettings.exceptions.title","Timesheet exceptions")}),e.jsx("span",{className:"ms-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",children:t("orgSettings.exceptions.enterpriseBadge","ENTERPRISE")}),e.jsxs("div",{className:"ms-auto flex items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-gray-600 dark:text-gray-400",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:y=>o(y.target.checked),className:"accent-indigo-600"}),t("orgSettings.exceptions.activeOnly","Active only")]}),c&&e.jsxs("button",{onClick:()=>d(!0),className:"btn-secondary text-xs py-1 flex items-center gap-1",children:[e.jsx(st,{className:"w-3.5 h-3.5"})," ",t("orgSettings.exceptions.grant","Grant")]})]})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 -mt-2",children:t("orgSettings.exceptions.description","Date-bounded, revocable exemptions from compliance enforcement. Use for sick leave, sabbatical, parental leave, or new-hire onboarding. Grant + revoke both write AuditLog rows for evidence trails.")}),c?h?e.jsx("div",{className:"text-xs text-gray-400 py-4 text-center",children:t("common.loading","Loading...")}):f?e.jsx(Cs,{onRetry:()=>j(),compact:!0}):!u||u.exceptions.length===0?e.jsxs("div",{className:"text-center py-4",children:[e.jsx(kt,{className:"w-5 h-5 text-gray-300 mx-auto"}),e.jsx("p",{className:"text-xs text-gray-400 mt-1.5",children:r?t("orgSettings.exceptions.emptyActive","No active exceptions."):t("orgSettings.exceptions.emptyAll","No exceptions on record.")})]}):e.jsx("div",{className:"overflow-x-auto -mx-1",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-start text-[10px] uppercase tracking-wide text-gray-500 dark:text-gray-400 border-b border-gray-100 dark:border-gray-700",children:[e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.exceptions.thUser","User")}),e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.exceptions.thPeriod","Period")}),e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.exceptions.thReason","Reason")}),e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.exceptions.thGrantedBy","Granted by")}),e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.exceptions.thStatus","Status")}),e.jsx("th",{className:"py-1.5 px-1 w-8"})]})}),e.jsx("tbody",{children:u.exceptions.map(y=>e.jsx(ad,{exception:y,onRevoke:()=>b.mutate(y.id)},y.id))})]})}):e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-gray-500 dark:text-gray-400 pt-2 border-t border-gray-100 dark:border-gray-700",children:[e.jsx(ke,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{children:[t("orgSettings.exceptions.readOnly","Read-only, your role doesn't have")," ",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 py-0.5 rounded text-[10px]",children:"org.compliance.manage"}),"."]})]}),x&&s&&e.jsx(sd,{orgId:s.id,onClose:()=>d(!1),onGranted:()=>{a.invalidateQueries({queryKey:["timesheet-exceptions"]}),d(!1)}})]}):null}function ad({exception:t,onRevoke:a}){const{t:s}=Q(),l=t.revokedAt==null,i=t.fromDate.slice(0,10),c=t.toDate.slice(0,10);return e.jsxs("tr",{className:"border-b border-gray-50 dark:border-gray-800 last:border-0",children:[e.jsx("td",{className:"py-1.5 px-1",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium text-gray-800 dark:text-gray-200",children:t.user.name}),e.jsx("span",{className:"text-[10px] text-gray-400",children:t.user.email})]})}),e.jsxs("td",{className:"py-1.5 px-1 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:[i," → ",c]}),e.jsx("td",{className:"py-1.5 px-1 text-gray-600 dark:text-gray-400 max-w-[240px] truncate",title:t.reason,children:t.reason}),e.jsx("td",{className:"py-1.5 px-1 text-gray-500 truncate max-w-[140px]",children:t.grantedBy.name}),e.jsx("td",{className:"py-1.5 px-1",children:l?e.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",children:s("orgSettings.exceptions.statusActive","Active")}
28):e.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400",children:s("orgSettings.exceptions.statusRevoked","Revoked")})}),e.jsx("td",{className:"py-1.5 px-1",children:l&&e.jsx("button",{onClick:a,title:s("orgSettings.exceptions.revokeTitle","Revoke"),className:"text-gray-300 hover:text-red-500 transition-colors",children:e.jsx(dt,{className:"w-3.5 h-3.5"})})})]})}function sd({orgId:t,onClose:a,onGranted:s}){const{t:l}=Q(),[i,c]=g.useState(""),[r,o]=g.useState(()=>new Date().toISOString().slice(0,10)),[x,d]=g.useState(()=>{const p=new Date;return p.setDate(p.getDate()+7),p.toISOString().slice(0,10)}),[u,h]=g.useState(""),f=Vt({open:!0,onClose:a}),{data:j=Za}=ee({queryKey:["org-members",t],queryFn:()=>B.members(t),staleTime:6e4}),b=g.useMemo(()=>j.filter(p=>p.role!=="GUEST"&&!p.user.isAgentPersona).map(p=>({id:p.user.id,label:p.user.name,sublabel:l("orgSettings.exceptions.memberSublabel","{{email}} · {{role}}",{email:p.user.email,role:p.role})})),[j,l]),y=$({mutationFn:()=>fa.grantException({userId:i,fromDate:r,toDate:x,reason:u}),onSuccess:()=>{k.success(l("orgSettings.exceptions.toastGranted","Exception granted")),s()},onError:p=>{k.error(U(p,"grant exception"))}}),N=i&&r&&x&&u.trim().length>=3&&new Date(x)>=new Date(r);return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md p-5 space-y-4 max-h-[90dvh] overflow-y-auto",ref:f,role:"dialog","aria-modal":"true","aria-labelledby":"exceptions-panel-title",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{id:"exceptions-panel-title",className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:l("orgSettings.exceptions.modalTitle","Grant timesheet exception")}),e.jsx("button",{onClick:a,"aria-label":l("common.close","Close"),className:"text-gray-400 hover:text-gray-600",children:e.jsx(ft,{className:"w-4 h-4"})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:l("orgSettings.exceptions.fieldUser","User")}),e.jsx(ya,{options:b,selected:i?[i]:[],onChange:p=>c(p[0]??""),placeholder:l("orgSettings.exceptions.selectMember","Select a member"),searchPlaceholder:l("orgSettings.exceptions.searchMembers","Search by name or email…"),multiple:!1})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:l("orgSettings.exceptions.fieldFrom","From")}),e.jsx("input",{type:"date",value:r,onChange:p=>o(p.target.value),className:"input text-xs py-1.5 w-full"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:l("orgSettings.exceptions.fieldTo","To")}),e.jsx("input",{type:"date",value:x,onChange:p=>d(p.target.value),className:"input text-xs py-1.5 w-full"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-700 dark:text-gray-300 mb-1.5",children:[l("orgSettings.exceptions.fieldReason","Reason")," ",e.jsx("span",{className:"text-gray-400 font-normal",children:l("orgSettings.exceptions.reasonHint","(audited; min 3 chars, max 500)")})]}),e.jsx("textarea",{value:u,onChange:p=>h(p.target.value.slice(0,500)),rows:3,placeholder:l("orgSettings.exceptions.reasonPlaceholder","e.g. Sick leave through end of week, doctor's note on file"),className:"input text-xs w-full"}),e.jsx("p",{className:"text-[10px] text-gray-400 mt-0.5 text-end",children:l("orgSettings.exceptions.charCount","{{used}}/{{max}}",{used:u.length,max:500})})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-gray-100 dark:border-gray-700",children:[e.jsx("button",{onClick:a,className:"btn-secondary text-xs py-1.5",children:l("common.cancel","Cancel")}),e.jsxs("button",{onClick:()=>y.mutate(),disabled:!N||y.isPending,className:"btn-primary text-xs py-1.5 flex items-center gap-1.5 disabled:opacity-50",children:[y.isPending&&e.jsx(At,{className:"w-3.5 h-3.5 animate-spin"}),y.isPending?l("orgSettings.exceptions.granting","Granting…"):l("orgSettings.exceptions.grantAction","Grant exception")]})]})]})})}function rd(t,a){switch(a){case"LIGHT":return t("orgSettings.escalations.templateLight","Light");case"STANDARD":return t("orgSettings.escalations.templateStandard","Standard");case"STRICT":return t("orgSettings.escalations.templateStrict","Strict");default:return a}}
28function nd(t,a){switch(a){case"user":return t("orgSettings.escalations.targetUser","User");case"manager":return t("orgSettings.escalations.targetManager","Manager");case"owner":return t("orgSettings.escalations.targetOwner","Owner");case"team":return t("orgSettings.escalations.targetTeam","Team");case"webhook_url":return t("orgSettings.escalations.targetWebhook","Webhook");default:return a}}function id(){const{t}=Q(),{currentOrg:a}=Qe(),{policy:s}=ja(),l=et("auditLogs"),i=Kt(s,"org.compliance.manage",a==null?void 0:a.role),[c,r]=g.useState("active"),{data:o,isLoading:x}=ee({queryKey:["escalations",a==null?void 0:a.id,c],queryFn:()=>fa.listEscalations(c),enabled:!!(a!=null&&a.id)&&l&&i,staleTime:3e4});return l?e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xi,{className:"w-4 h-4 text-rose-600 dark:text-rose-400"}),e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:t("orgSettings.escalations.title","Active escalations")}),e.jsx("span",{className:"ms-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",children:t("orgSettings.escalations.enterpriseBadge","ENTERPRISE")}),o&&e.jsx("span",{className:"ms-2 text-[11px] text-gray-500 dark:text-gray-400",children:o.enabled?e.jsxs(e.Fragment,{children:[t("orgSettings.escalations.templateLabel","Template:")," ",e.jsx("strong",{children:rd(t,o.template.name)})," · ",t("orgSettings.escalations.stepCount",{count:o.template.steps.length,defaultValue_one:"{{count}} step",defaultValue_other:"{{count}} steps"})]}):e.jsx("span",{className:"text-amber-600",children:t("orgSettings.escalations.disabledHint","Escalation disabled, turn on in Reminders above to start advancing.")})}),e.jsx("div",{className:"ms-auto flex items-center gap-2",children:e.jsxs("select",{value:c,onChange:d=>r(d.target.value),className:"input text-xs py-1",children:[e.jsx("option",{value:"active",children:t("orgSettings.escalations.filterActive","Active only")}),e.jsx("option",{value:"all",children:t("orgSettings.escalations.filterAll","Including resolved")})]})})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 -mt-2",children:t("orgSettings.escalations.description","Read-only view of the escalation chain. The hourly worker advances rows forward when each step's delay elapses. Clear an escalation by granting a TimesheetException or asking the user to submit the missing week.")}),i?x?e.jsx("div",{className:"text-xs text-gray-400 py-4 text-center",children:t("common.loading","Loading...")}):!o||o.escalations.length===0?e.jsxs("div",{className:"text-center py-4",children:[e.jsx(kt,{className:"w-5 h-5 text-emerald-300 mx-auto"}),e.jsx("p",{className:"text-xs text-gray-400 mt-1.5",children:c==="active"?t("orgSettings.escalations.emptyActive","No active escalations, everyone is current."):t("orgSettings.escalations.emptyAll","No escalations on record.")})]}):e.jsx("div",{className:"overflow-x-auto -mx-1",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-start text-[10px] uppercase tracking-wide text-gray-500 dark:text-gray-400 border-b border-gray-100 dark:border-gray-700",children:[e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.escalations.thUser","User")}),e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.escalations.thWeek","Week")}),e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.escalations.thProgress","Progress")}),e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.escalations.thLastStep","Last step")}),e.jsx("th",{className:"py-1.5 px-1",children:t("orgSettings.escalations.thStatus","Status")}),e.jsx("th",{className:"py-1.5 px-1 w-8"})]})}),e.jsx("tbody",{children:o.escalations.map(d=>e.jsx(od,{row:d},d.id))})]})}):e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-gray-500 dark:text-gray-400 pt-2 border-t border-gray-100 dark:border-gray-700",children:[e.jsx(ke,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{children:[t("orgSettings.escalations.readOnly","Read-only, your role doesn't have")," ",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 py-0.5 rounded text-[10px]",children:"org.compliance.manage"}),"."]})]})]}):null}function od({row:t}){const{t:a}=Q(),s=t.resolvedAt!=null,l=t.history.length>0?t.history[t.history.length-1]:null;return e.jsxs("tr",{className:"border-b border-gray-50 dark:border-gray-800 last:border-0 align-top",children:[e.jsx("td",{className:"py-2 px-1",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium text-gray-800 dark:text-gray-200",children:t.user.name}),e.jsx("span",{className:"text-[10px] text-gray-400",children:t.user.email})]})}),e.jsx("td",{className:"py-2 px-1 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:t.weekStart}),e.jsx("td",{className:"py-2 px-1",children:e.jsxs("div",{className:"flex items-center gap-0.5",children:[Array.from({length:t.stepCount}).map((i,c)=>e.jsx("span",{title:c<t.currentStep?a("orgSettings.escalations.stepFiredTitle","Step {{number}}, fired",{number:c+1}):a("orgSettings.escalations.stepTitle","Step {{number}}",{number:c+1}),className:`w-2.5 h-2.5 rounded-full border ${c<t.currentStep?s?"bg-emerald-400 border-emerald-500":"bg-rose-400 border-rose-500":"bg-transparent border-gray-300 dark:border-gray-600"}`},c)),e.jsxs("span",{className:"ms-1.5 text-[10px] text-gray-500",children:[t.currentStep,"/",t.stepCount]})]})}),e.jsx("td",{className:"py-2 px-1 text-gray-600 dark:text-gray-400",children:l?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:l.name}),e.jsxs("span",{className:"text-[10px] text-gray-400",children:[new Date(l.at).toLocaleDateString()," → ",nd(a,l.target)]})]}):e.jsx("span",{className:"text-gray-400",children:a("orgSettings.escalations.pendingFirstStep","pending first step")})}),e.jsx("td",{className:"py-2 px-1",children:s?e.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",children:a("orgSettings.escalations.statusResolved","Resolved")}):t.currentStep>=t.stepCount?e.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300 inline-flex items-center gap-1",children:[e.jsx(je,{className:"w-2.5 h-2.5"})," ",a("orgSettings.escalations.statusExhausted","Exhausted")]}):e.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300",children:a("orgSettings.escalations.statusActive","Active")}
28)}),e.jsx("td",{className:"py-2 px-1",children:e.jsx(Wt,{to:`/logs?actionPrefix=TIMESHEET_&userId=${t.userId}`,title:a("orgSettings.escalations.auditHistoryTitle","Audit history for {{name}}",{name:t.user.name}),className:"text-gray-300 dark:text-gray-600 hover:text-indigo-500 transition-colors inline-block",children:e.jsx(Zi,{className:"w-3.5 h-3.5"})})})]})}const Ga=[{key:"isBillable",defaultLabel:"Billable",labelKey:"customFields.builtIn.isBillable.label",description:"Marks a project as client-billable for cost reporting and timesheet compliance. Used by Cost at Risk computation, Capacity Planner billable utilization toggle, and Finance framing.",descriptionKey:"customFields.builtIn.isBillable.description",icon:e.jsx($r,{className:"w-5 h-5 text-emerald-700 dark:text-emerald-300"})},{key:"clientName",defaultLabel:"Client / customer",labelKey:"customFields.builtIn.clientName.label",description:"Optional free-text client label that appears alongside the project name on billable work. Phase 1, a proper Client model lands in Phase 3.",descriptionKey:"customFields.builtIn.clientName.description",icon:e.jsx($r,{className:"w-5 h-5 text-emerald-700 dark:text-emerald-300"})}];function ar(t,a){return t(a.labelKey,a.defaultLabel)}function ld({orgId:t,canEdit:a}){const{t:s}=Q(),l=_e(),{data:i,isLoading:c}=ee({queryKey:["org-form-config",t],queryFn:()=>B.getFormConfig(t),staleTime:6e4}),{data:r,isLoading:o}=ee({queryKey:["timesheet-enforcement-settings",t],queryFn:()=>B.getTimesheetEnforcementSettings(t),staleTime:6e4}),[x,d]=g.useState({});g.useEffect(()=>{var b;if(!i)return;const j={};for(const y of Ga){const N=(b=i.fields)==null?void 0:b[y.key];j[y.key]={visible:(N==null?void 0:N.visible)??!0,required:(N==null?void 0:N.required)??!1,label:(N==null?void 0:N.label)??""}}d(j)},[i]);const u=g.useMemo(()=>!!(r!=null&&r.enabled&&(r!=null&&r.requireIsBillable)),[r==null?void 0:r.enabled,r==null?void 0:r.requireIsBillable]);g.useEffect(()=>{u&&d(j=>({...j,isBillable:{...j.isBillable,visible:!0,required:!0}}))},[u]);const h=g.useMemo(()=>{var j;if(!i)return!1;for(const b of Ga){const y=(j=i.fields)==null?void 0:j[b.key],N=x[b.key];if(N&&(N.visible!==((y==null?void 0:y.visible)??!0)||N.required!==((y==null?void 0:y.required)??!1)||N.label!==((y==null?void 0:y.label)??"")))return!0}return!1},[i,x]),f=$({mutationFn:()=>{const j={...(i==null?void 0:i.fields)??{}};for(const b of Ga){const y=x[b.key];y&&(j[b.key]={visible:y.visible,required:y.required,label:y.label.trim()||void 0})}return B.saveFormConfig(t,j)},onSuccess:()=>{k.success(s("customFields.builtIn.toast.saved","Built-in field config saved")),l.invalidateQueries({queryKey:["org-form-config",t]})},onError:j=>k.error(U(j,"save field config"))});return c||o?e.jsx(oe,{className:"h-48 rounded-xl"}):r!=null&&r.enabled?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-bold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"text-indigo-500",children:"⚙"})," ",s("customFields.builtIn.heading","Built-in Fields")]}),e.jsx("p",{className:"text-[11px] text-gray-500 dark:text-gray-400 mt-0.5",children:s("customFields.builtIn.headingSubtitle","Native project fields with built-in compliance support. Toggle visibility, mark required, or rename.")})]}),h&&a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[11px] text-amber-700 flex items-center gap-1",children:[e.jsx(je,{className:"w-3 h-3"})," ",s("customFields.builtIn.unsaved","Unsaved")]}),e.jsx("button",{disabled:f.isPending,onClick:()=>{var b;if(!i)return;const j={};for(const y of Ga){const N=(b=i.fields)==null?void 0:b[y.key];j[y.key]={visible:(N==null?void 0:N.visible)??!0,required:(N==null?void 0:N.required)??!1,label:(N==null?void 0:N.label)??""}}d(j)},className:"btn-secondary text-xs py-1.5",children:s("customFields.builtIn.reset","Reset")}),e.jsxs("button",{disabled:f.isPending,onClick:()=>f.mutate(),className:"btn-primary text-xs py-1.5 flex items-center gap-1.5 disabled:opacity-50",children:[f.isPending&&e.jsx(At,{className:"w-3.5 h-3.5 animate-spin"}),f.isPending?s("customFields.saving","Saving…"):s("customFields.builtIn.saveChanges","Save changes")]})]})]}),e.jsx("div",{className:"space-y-3",children:Ga.map(j=>{const b=x[j.key];if(!b)return null;const y=j.key==="isBillable"&&u;return e.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-xl p-4 bg-white dark:bg-gray-800/40",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-100 dark:bg-emerald-900/40 flex items-center justify-center flex-shrink-0",children:j.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:ar(s,j)}),e.jsx("span",{className:"text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300",children:s("customFields.builtIn.badge","Built-in")}),y&&e.jsxs("span",{className:"text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300 inline-flex items-center gap-1",children:[e.jsx(ke,{className:"w-2.5 h-2.5"})," ",s("customFields.builtIn.lockedBadge","Locked by enforcement")]})]}),e.jsx("p",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:s(j.descriptionKey,j.description)})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-3",children:[e.jsx(Sn,{checked:b.visible,onChange:N=>d(p=>({...p,[j.key]:{...p[j.key],visible:N}})),disabled:!a||y,title:s("customFields.builtIn.visibleToggle","Visible on project form"),hint:s("customFields.builtIn.visibleToggleHint","Shows the field on Edit Project / New Project")}),e.jsx(Sn,{checked:b.required,onChange:N=>d(p=>({...p,[j.key]:{...p[j.key],required:N}})),disabled:!a||y,title:s("customFields.builtIn.requiredToggle","Required field"),hint:y?s("customFields.builtIn.requiredToggleLockedHint","🔒 Forced ON by Timesheet enforcement"):s("customFields.builtIn.requiredToggleHint","Block project save when missing")})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("label",{className:"block text-[11px] font-semibold text-gray-700 dark:text-gray-300 mb-1",children:[s("customFields.builtIn.labelOverride","Label override"),e.jsx("span",{className:"text-gray-400 font-normal ms-1",children:s("customFields.builtIn.labelOverrideDefault",'(default: "{{label}}")',{label:ar(s,j)})})]}),e.jsx("input",{type:"text",value:b.label,onChange:N=>d(p=>({...p,[j.key]:{...p[j.key],label:N.target.value}})),disabled:!a,placeholder:ar(s,j),className:"input text-xs py-1.5 w-full max-w-xs",maxLength:60}),e.jsx("p",{className:"text-[10px] text-gray-400 mt-1",children:s("customFields.builtIn.labelOverrideHint",'Replace with industry-specific term if needed (e.g. "Chargeable", "Client work").')})]})]},j.key)})}),!a&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-gray-500 dark:text-gray-400",children:[e.jsx(ke,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{children:[s("customFields.builtIn.readOnlyNote","Read-only, your role doesn't have")," ",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-700 px-1 py-0.5 rounded text-[10px]",children:"org.formconfig.manage"}),"."]})]})]}):e.jsx("div",{className:"rounded-xl border border-dashed border-gray-300 dark:border-gray-700 bg-gray-50/40 dark:bg-gray-800/20 p-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center flex-shrink-0",children:e.jsx(Ya,{className:"w-4 h-4 text-gray-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300",children:s("customFields.builtIn.locked.title","Built-in compliance fields")}),e.jsx("p",{className:"text-[11px] text-gray-500 dark:text-gray-400 mt-1",children:s("customFields.builtIn.locked.description","Native fields like {{billableLabel}} and {{clientLabel}} are configured here when timesheet enforcement is enabled. Enforcement controls whether these fields are required on every project + drives the cost-at-risk math.",{billableLabel:s("customFields.builtIn.isBillable.label","Billable"),clientLabel:s("customFields.builtIn.clientName.label","Client / customer")})}),e.jsx(Wt,{to:"/org/settings?tab=configuration&subtab=timesheets",className:"inline-block mt-2 text-[11px] font-semibold text-indigo-600 hover:underline",children:s("customFields.builtIn.locked.cta","Open Timesheets settings →")})]})]})})}function Sn({checked:t,onChange:a,disabled:s,title:l,hint:i}){return e.jsxs("div",{className:"flex items-start justify-between gap-3 p-2.5 rounded-lg bg-gray-50/60 dark:bg-gray-800/40",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:l}),e.jsx("p",{className:"text-[10px] text-gray-500 dark:text-gray-400 mt-0.5",children:i})]}),e.jsx("button",{disabled:s,onClick:()=>a(!t),"aria-pressed":t,className:`relative inline-flex h-5 w-9 items-center rounded-full flex-shrink-0 transition-colors ${t?"bg-indigo-600":"bg-gray-300 dark:bg-gray-600"} ${s?"opacity-70 cursor-not-allowed":""}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 transform rounded-full bg-white shadow transition-transform ${t?"translate-x-5 rtl:-translate-x-5":"translate-x-1 rtl:-translate-x-1"}`})})]})}const wn=[{key:"name",label:"Title",labelKey:"customFields.projectField.name",locked:!0},{key:"owner",label:"Owner",labelKey:"customFields.projectField.owner",locked:!1},{key:"description",label:"Description",labelKey:"customFields.projectField.description",locked:!1},{key:"status",label:"Status",labelKey:"customFields.projectField.status",locked:!1},{key:"budget",label:"Budget (USD)",labelKey:"customFields.projectField.budget",locked:!1},{key:"startDate",label:"Start date",labelKey:"customFields.projectField.startDate",locked:!1},{key:"endDate",label:"End date",labelKey:"customFields.projectField.endDate",locked:!1},{key:"attachments",label:"Attachments",labelKey:"customFields.projectField.attachments",locked:!1},{key:"comments",label:"Comments",labelKey:"customFields.projectField.comments",locked:!1}],Cn={owner:{visible:!0,required:!1},description:{visible:!0,required:!1},status:{visible:!0,required:!1},budget:{visible:!0,required:!1},startDate:{visible:!0,required:!0},endDate:{visible:!0,required:!0},attachments:{visible:!0,required:!1},comments:{visible:!0,required:!1}},An=[{key:"title",label:"Task title",labelKey:"customFields.taskField.title",locked:!0},{key:"description",label:"Description",labelKey:"customFields.taskField.description",locked:!1},{key:"status",label:"Status",labelKey:"customFields.taskField.status",locked:!1},{key:"priority",label:"Priority",labelKey:"customFields.taskField.priority",locked:!1},{key:"assignee",label:"Assignee",labelKey:"customFields.taskField.assignee",locked:!1},{key:"startDate",label:"Start date",labelKey:"customFields.taskField.startDate",locked:!1},{key:"dueDate",label:"Due date",labelKey:"customFields.taskField.dueDate",locked:!1},{key:"estimatedHours",label:"Estimated hours",labelKey:"customFields.taskField.estimatedHours",locked:!1},{key:"progress",label:"Progress",labelKey:"customFields.taskField.progress",locked:!1},{key:"sprint",label:"Sprint",labelKey:"customFields.taskField.sprint",locked:!1},{key:"epic",label:"Epic",labelKey:"customFields.taskField.epic",locked:!1},{key:"milestone",label:"Milestone flag",labelKey:"customFields.taskField.milestone",locked:!1},{key:"constraintType",label:"Scheduling constraint",labelKey:"customFields.taskField.constraintType",locked:!1},{key:"constraintDate",label:"Constraint date",labelKey:"customFields.taskField.constraintDate",locked:!1},{key:"deadline",label:"Hard deadline",labelKey:"customFields.taskField.deadline",locked:!1},{key:"recurringRule",label:"Repeat",labelKey:"customFields.taskField.recurringRule",locked:!1},{key:"attachments",label:"Attachments",labelKey:"customFields.taskField.attachments",locked:!1},{key:"comments",label:"Comments",labelKey:"customFields.taskField.comments",locked:!1}],En={description:{visible:!0,required:!1},status:{visible:!0,required:!1},priority:{visible:!0,required:!1},assignee:{visible:!0,required:!1},startDate:{visible:!0,required:!1},dueDate:{visible:!0,required:!1},estimatedHours:{visible:!0,required:!1},progress:{visible:!0,required:!1},sprint:{visible:!0,required:!1},epic:{visible:!0,required:!1},milestone:{visible:!0,required:!1},constraintType:{visible:!0,required:!1},constraintDate:{visible:!0,required:!1},deadline:{visible:!0,required:!1},recurringRule:{visible:!0,required:!1},attachments:{visible:!0,required:!1},comments:{visible:!0,required:!1}},Pn=[{key:"title",label:"Title",labelKey:"customFields.proposalField.title",locked:!0},{key:"description",label:"Description",labelKey:"customFields.proposalField.description",locked:!1},{key:"priority",label:"Priority",labelKey:"customFields.proposalField.priority",locked:!1},{key:"riskLevel",label:"Risk Level",labelKey:"customFields.proposalField.riskLevel",locked:!1},{key:"estimatedBudget",label:"Est. Budget ($)",labelKey:"customFields.proposalField.estimatedBudget",locked:!1},{key:"estimatedDuration",label:"Est. Duration (weeks)",labelKey:"customFields.proposalField.estimatedDuration",locked:!1},{key:"department",label:"Department",labelKey:"customFields.proposalField.department",locked:!1},{key:"strategicAlignment",label:"Strategic Alignment",labelKey:"customFields.proposalField.strategicAlignment",locked:!1},{key:"expectedBenefits",label:"Expected Benefits",labelKey:"customFields.proposalField.expectedBenefits",locked:!1},{key:"sponsorId",label:"Sponsor",labelKey:"customFields.proposalField.sponsorId",locked:!1},{key:"proposedProjectOwnerId",label:"Proposed Project Owner",labelKey:"customFields.proposalField.proposedProjectOwnerId",locked:!1},{key:"businessJustification",label:"Business Justification",labelKey:"customFields.proposalField.businessJustification",locked:!1},{key:"attachments",label:"Attachments",labelKey:"customFields.proposalField.attachments",locked:!1},{key:"comments",label:"Comments",labelKey:"customFields.proposalField.comments",locked:!1}],Tn={description:{visible:!0,required:!1},priority:{visible:!0,required:!1},riskLevel:{visible:!0,required:!1},estimatedBudget:{visible:!0,required:!1},estimatedDuration:{visible:!0,required:!1},department:{visible:!0,required:!1},strategicAlignment:{visible:!0,required:!1},expectedBenefits:{visible:!0,required:!1},sponsorId:{visible:!0,required:!1},proposedProjectOwnerId:{visible:!0,required:!1},businessJustification:{visible:!0,required:!1},attachments:{visible:!0,required:!1},comments:{visible:!0,required:!1}},pr={TEXT:{icon:oo,color:"text-violet-500 bg-violet-50 dark:bg-violet-900/30"},TEXTAREA:{icon:xr,color:"text-violet-600 bg-violet-50 dark:bg-violet-900/30"},NUMBER:{icon:io,color:"text-blue-500 bg-blue-50 dark:bg-blue-900/30"},DATE:{icon:no,color:"text-green-500 bg-green-50 dark:bg-green-900/30"},DROPDOWN:{icon:ro,color:"text-amber-500 bg-amber-50 dark:bg-amber-900/30"},MULTI_SELECT:{icon:Ns,color:"text-amber-600 bg-amber-50 dark:bg-amber-900/30"},CHECKBOX:{icon:mr,color:"text-teal-500 bg-teal-50 dark:bg-teal-900/30"},URL:{icon:so,color:"text-pink-500 bg-pink-50 dark:bg-pink-900/30"},EMAIL:{icon:Wn,color:"text-sky-500 bg-sky-50 dark:bg-sky-900/30"},PHONE:{icon:ao,color:"text-emerald-500 bg-emerald-50 dark:bg-emerald-900/30"},CURRENCY:{icon:es,color:"text-lime-600 bg-lime-50 dark:bg-lime-900/30"},RATING:{icon:$t,color:"text-orange-500 bg-orange-50 dark:bg-orange-900/30"}};function hr(t,a){switch(a){case"TEXT":return t("customFields.fieldType.text","Text");case"TEXTAREA":return t("customFields.fieldType.textarea","Multi-line");case"NUMBER":return t("customFields.fieldType.number","Number");case"DATE":return t("customFields.fieldType.date","Date");case"DROPDOWN":return t("customFields.fieldType.dropdown","Dropdown");case"MULTI_SELECT":return t("customFields.fieldType.multiSelect","Multi-select");case"CHECKBOX"
28:return t("customFields.fieldType.checkbox","Checkbox");case"URL":return t("customFields.fieldType.url","URL / Link");case"EMAIL":return t("customFields.fieldType.email","Email");case"PHONE":return t("customFields.fieldType.phone","Phone");case"CURRENCY":return t("customFields.fieldType.currency","Currency");case"RATING":return t("customFields.fieldType.rating","Rating");default:return a}}const br={PROJECT:{color:"bg-amber-50 text-amber-700 dark:bg-amber-900/20 dark:text-amber-300 border border-amber-200 dark:border-amber-800"},TASK:{color:"bg-indigo-50 text-indigo-700 dark:bg-indigo-900/20 dark:text-indigo-300 border border-indigo-200 dark:border-indigo-800"},PROPOSAL:{color:"bg-purple-50 text-purple-700 dark:bg-purple-900/20 dark:text-purple-300 border border-purple-200 dark:border-purple-800"}};function Cr(t,a){switch(a){case"PROJECT":return t("customFields.entityType.project","Project form");case"TASK":return t("customFields.entityType.task","Task form");case"PROPOSAL":return t("customFields.entityType.proposal","Proposal");default:return a}}function dd(t,a){switch(a){case"PROJECT":return t("customFields.entityTypeShort.project","Project");case"TASK":return t("customFields.entityTypeShort.task","Task");case"PROPOSAL":return t("customFields.entityTypeShort.proposal","Proposal");default:return a}}function ys({id:t,icon:a,title:s,subtitle:l,count:i,accentColor:c,dirty:r,onSave:o,saving:x,defaultClosed:d,children:u}){const{t:h}=Q(),f=`enterprise-accordion-${t}`,[j,b]=g.useState(()=>{try{const N=localStorage.getItem(f);return N!==null?N!=="closed":!d}catch{return!d}}),y=()=>{const N=!j;b(N);try{localStorage.setItem(f,N?"open":"closed")}catch{}};return e.jsxs("div",{"data-accordion-id":t,className:`rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden mb-3 border-s-4 ${c}`,children:[e.jsxs("button",{type:"button",onClick:y,className:"w-full flex items-center gap-3 px-4 py-3.5 bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100/80 dark:hover:bg-gray-700/40 transition-colors text-start",children:[e.jsx("span",{className:"flex-shrink-0 opacity-70",children:a}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"font-semibold text-sm text-gray-800 dark:text-gray-100",children:s}),l&&e.jsx("span",{className:"ms-2 text-xs text-gray-400 dark:text-gray-500 font-normal",children:l})]}),i!==void 0&&e.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-gray-400 bg-gray-200 dark:bg-gray-700 px-2 py-0.5 rounded-full flex-shrink-0",children:i}),r&&o&&e.jsxs("button",{type:"button",onClick:N=>{N.stopPropagation(),o()},disabled:x,className:"btn-primary text-xs py-1 px-3 flex items-center gap-1.5 flex-shrink-0",children:[e.jsx(Kn,{className:"w-3.5 h-3.5"}),x?h("customFields.saving","Saving…"):h("customFields.save","Save")]}),e.jsx(gt,{className:`w-4 h-4 text-gray-400 flex-shrink-0 transition-transform duration-200 ${j?"rotate-180":""}`})]}),j&&e.jsx("div",{className:"px-4 pb-4 pt-3 border-t border-gray-100 dark:border-gray-700 space-y-2 bg-white dark:bg-gray-800",children:u})]})}function sr({label:t,locked:a,cfg:s,canEdit:l,onUpdate:i}){const{t:c}=Q(),[r,o]=g.useState(!1),x=s.label||t,[d,u]=g.useState(x),h=g.useRef(null),f=()=>{!l||a||(u(x),o(!0),setTimeout(()=>{var y;return(y=h.current)==null?void 0:y.select()},0))},j=()=>{const y=d.trim();if(!y||y===x){o(!1);return}i({label:y===t?void 0:y}),o(!1)},b=()=>{u(x),o(!1)};return e.jsxs("div",{className:`flex items-center gap-3 py-2.5 px-4 rounded-xl border transition-colors ${a?"bg-gray-50 dark:bg-gray-800/50 border-gray-100 dark:border-gray-700/60":"bg-white dark:bg-gray-800 border-gray-100 dark:border-gray-700 hover:border-gray-200 dark:hover:border-gray-600"}`,children:[e.jsx("div",{className:"flex-shrink-0 w-4 flex items-center justify-center",children:a&&e.jsx(ke,{className:"w-3.5 h-3.5 text-gray-300 dark:text-gray-600"})}),e.jsx("div",{className:`flex-1 text-sm min-w-0 ${a?"text-gray-500 dark:text-gray-400":"font-medium text-gray-900 dark:text-white"}`,children:r?e.jsx("input",{ref:h,value:d,onChange:y=>u(y.target.value),onKeyDown:y=>{y.key==="Enter"&&j(),y.key==="Escape"&&b()},onBlur:j,className:"text-sm font-medium text-gray-900 dark:text-white bg-gray-50 dark:bg-gray-700 border border-indigo-300 dark:border-indigo-500 rounded px-2 py-0.5 outline-none focus:ring-1 focus:ring-indigo-400 w-48",autoFocus:!0}):e.jsxs("span",{className:"inline-flex items-center gap-1",children:[!a&&l?e.jsxs("button",{onClick:f,className:"group/lbl inline-flex items-center gap-1 hover:text-indigo-600 dark:hover:text-indigo-400 cursor-text",title:c("customFields.clickToRename","Click to rename"),children:[x,e.jsx(Ps,{className:"w-3 h-3 text-gray-300 dark:text-gray-600 opacity-0 group-hover/lbl:opacity-100 transition-opacity"})]}):e.jsx("span",{children:x}),s.label&&s.label!==t&&e.jsx("span",{className:"text-[10px] text-gray-400 dark:text-gray-500 ms-1",title:c("customFields.defaultLabelTitle","Default: {{label}}",{label:t}),children:c("customFields.wasLabel","(was {{label}})",{label:t})}),a&&e.jsx("span",{className:"ms-2 text-xs text-gray-400 dark:text-gray-500 font-normal",children:c("customFields.alwaysShownRequired","always shown · always required")})]})}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:a?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 border border-indigo-200 dark:border-indigo-800",children:[e.jsx(cr,{className:"w-3 h-3"})," ",c("customFields.visible","Visible")]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full bg-red-50 dark:bg-red-900/20 text-red-500 dark:text-red-400 border border-red-200 dark:border-red-800",children:[e.jsx($t,{className:"w-3 h-3"})," ",c("customFields.required","Required")]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!l,onClick:()=>i(s.visible?{visible:!1,required:!1}:{visible:!0}),className:`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full border transition-all ${s.visible?"bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 border-indigo-200 dark:border-indigo-800":"bg-gray-100 dark:bg-gray-700 text-gray-400 dark:text-gray-500 border-gray-200 dark:border-gray-600"}
28 ${l?"hover:opacity-80 cursor-pointer":"opacity-50 cursor-not-allowed"}`,children:[s.visible?e.jsx(cr,{className:"w-3 h-3"}):e.jsx(dr,{className:"w-3 h-3"}),s.visible?c("customFields.visible","Visible"):c("customFields.hidden","Hidden")]}),e.jsxs("button",{type:"button",disabled:!l||!s.visible,onClick:()=>i({required:!s.required}),className:`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full border transition-all ${s.required&&s.visible?"bg-red-50 dark:bg-red-900/20 text-red-500 dark:text-red-400 border-red-200 dark:border-red-800":"bg-gray-100 dark:bg-gray-700 text-gray-400 dark:text-gray-500 border-gray-200 dark:border-gray-600"} ${!l||!s.visible?"opacity-50 cursor-not-allowed":"hover:opacity-80 cursor-pointer"}`,children:[e.jsx($t,{className:"w-3 h-3"}),s.required?c("customFields.required","Required"):c("customFields.optional","Optional")]})]})})]})}function Rn({initial:t,onSave:a,onCancel:s}){var j;const{t:l}=Q(),i=_e(),[c,r]=g.useState((t==null?void 0:t.entityType)??"PROJECT"),[o,x]=g.useState({name:(t==null?void 0:t.name)??"",description:(t==null?void 0:t.description)??"",fieldType:(t==null?void 0:t.fieldType)??"TEXT",required:(t==null?void 0:t.required)??!1,defaultValue:(t==null?void 0:t.defaultValue)??"",optionsRaw:((j=t==null?void 0:t.options)==null?void 0:j.join(`
29`))??""}),d=$({mutationFn:()=>{const b={name:o.name,description:o.description||void 0,fieldType:o.fieldType,entityType:c,required:o.required,defaultValue:o.defaultValue||void 0,options:o.fieldType==="DROPDOWN"||o.fieldType==="MULTI_SELECT"?o.optionsRaw.split(`
30`).map(y=>y.trim()).filter(Boolean):void 0};return t?ka.updateDefinition(t.id,b):ka.createDefinition(b)},onSuccess:()=>{if(i.invalidateQueries({queryKey:["custom-field-definitions"]}),k.success(t?l("customFields.toast.fieldUpdated","Field updated"):l("customFields.toast.fieldCreated","Field created")),!t){try{localStorage.setItem("enterprise-accordion-custom-fields","open")}catch{}setTimeout(()=>{const b=document.querySelector('[data-accordion-id="custom-fields"]');b==null||b.scrollIntoView({behavior:"smooth",block:"start"})},50)}a()},onError:b=>k.error(U(b,"save field"))}),u=pr[o.fieldType],h=br[c],f=Vt({open:!0,onClose:s});return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4",onClick:b=>{b.target===b.currentTarget&&s()},children:e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-lg mx-4 overflow-hidden border border-gray-200 dark:border-gray-700",ref:f,role:"dialog","aria-modal":"true","aria-labelledby":"custom-field-form-title",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-4 bg-indigo-50 dark:bg-indigo-900/30 border-b border-indigo-100 dark:border-indigo-800",children:[e.jsx("h4",{id:"custom-field-form-title",className:"font-semibold text-base text-indigo-900 dark:text-indigo-200",children:t?l("customFields.form.editTitle","Edit Enterprise Field"):l("customFields.form.newTitle","New Enterprise Field")}),e.jsx("button",{onClick:s,"aria-label":l("common.close","Close"),className:"p-1 text-indigo-400 hover:text-indigo-600 dark:hover:text-indigo-300 rounded transition-colors",children:e.jsx(ft,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"p-5 space-y-4 max-h-[70vh] overflow-y-auto",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-2",children:l("customFields.form.appearsIn","Appears in")}),t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-semibold px-3 py-1 rounded-full ${h.color}`,children:Cr(l,c)}),e.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:l("customFields.form.entityTypeLocked","cannot be changed after creation")})]}):e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["PROJECT","TASK","PROPOSAL"].map(b=>{const y={PROJECT:"📁",TASK:"✅",PROPOSAL:"🛡️"},N=c===b,p=b==="PROJECT"?N?"bg-amber-50 border-amber-400 text-amber-800 dark:bg-amber-900/30 dark:border-amber-600 dar
30k:text-amber-200":"border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400 hover:border-amber-300":b==="TASK"?N?"bg-indigo-50 border-indigo-400 text-indigo-800 dark:bg-indigo-900/30 dark:border-indigo-600 dark:text-indigo-200":"border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400 hover:border-indigo-300":N?"bg-purple-50 border-purple-400 text-purple-800 dark:bg-purple-900/30 dark:border-purple-600 dark:text-purple-200":"border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400 hover:border-purple-300";return e.jsxs("button",{type:"button",onClick:()=>r(b),className:`flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold border-2 transition-all bg-white dark:bg-gray-800 ${p}`,children:[y[b]," ",dd(l,b)]},b)})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1.5",children:[l("customFields.form.fieldName","Field name")," ",e.jsx("span",{className:"text-red-500 normal-case font-normal",children:"*"})]}),e.jsx("input",{className:"input text-sm",placeholder:l("customFields.form.fieldNamePlaceholder","e.g. Client Name"),value:o.name,onChange:b=>x(y=>({...y,name:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1.5",children:l("customFields.form.fieldType","Field type")}),e.jsx("select",{className:"input text-sm",value:o.fieldType,onChange:b=>x(y=>({...y,fieldType:b.target.value})),children:Object.keys(pr).map(b=>e.jsx("option",{value:b,children:hr(l,b)},b))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 items-start",children:[e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1.5 rounded-lg ${u.color}`,children:[e.jsx(u.icon,{className:"w-3.5 h-3.5"}),hr(l,o.fieldType)]}),e.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:l("customFields.form.inputType","input type")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1.5",children:[l("customFields.form.helpText","Help text")," ",e.jsx("span",{className:"normal-case font-normal",children:l("customFields.form.optionalSuffix","(optional)")})]}),e.jsx("input",{className:"input text-sm",placeholder:l("customFields.form.helpTextPlaceholder","Shown below the field"),value:o.description,onChange:b=>x(y=>({...y,description:b.target.value}))})]})]}),(o.fieldType==="DROPDOWN"||o.fieldType==="MULTI_SELECT")&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1.5",children:[l("customFields.form.options","Options")," ",e.jsx("span",{className:"normal-case font-normal",children:l("customFields.form.optionsHint","(one per line)")})]}),e.jsx("textarea",{className:"input text-sm resize-none font-mono",rows:4,placeholder:l("customFields.form.optionsPlaceholder",`Option A
31Option B
32Option C`),value:o.optionsRaw,onChange:b=>x(y=>({...y,optionsRaw:b.target.value}))}),o.optionsRaw&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:o.optionsRaw.split(`
33`).filter(Boolean).map((b,y)=>e.jsx("span",{className:"text-xs bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300 px-2 py-0.5 rounded-full",children:b.trim()},y))})]}),e.jsxs("div",{className:"flex items-end gap-4",children:[!["CHECKBOX","DROPDOWN","MULTI_SELECT","RATING"].includes(o.fieldType)&&e.jsxs("div",{className:"flex-1",children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1.5",children:[l("customFields.form.defaultValue","Default value")," ",e.jsx("span",{className:"normal-case font-normal",children:l("customFields.form.optionalSuffix","(optional)")})]}),e.jsx("input",{className:"input text-sm",type:o.fieldType==="NUMBER"||o.fieldType==="CURRENCY"?"number":o.fieldType==="DATE"?"date":o.fieldType==="EMAIL"?"email":o.fieldType==="PHONE"?"tel":o.fieldType==="URL"?"url":"text",placeholder:l("customFields.form.defaultValuePlaceholder","Pre-filled value"),value:o.defaultValue,onChange:b=>x(y=>({...y,defaultValue:b.target.value}))})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none pb-1 flex-shrink-0",children:[e.jsx("input",{type:"checkbox",className:"w-4 h-4 rounded border-gray-300 text-indigo-600",checked:o.required,onChange:b=>x(y=>({...y,required:b.target.checked}))}),e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:l("customFields.required","Required")}),o.required&&e.jsx("span",{className:"text-xs text-red-500 font-medium",children:"*"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 bg-gray-50 dark:bg-gray-800/60 border-t border-gray-100 dark:border-gray-700",children:[e.jsx("button",{onClick:s,className:"btn-secondary text-sm py-1.5 px-3",children:l("common.cancel","Cancel")}),e.jsxs("button",{onClick:()=>d.mutate(),disabled:!o.name.trim()||d.isPending||(o.fieldType==="DROPDOWN"||o.fieldType==="MULTI_SELECT")&&!o.optionsRaw.trim(),className:"btn-primary text-sm py-1.5 px-4 flex items-center gap-1.5",children:[e.jsx(fr,{className:"w-3.5 h-3.5"}),d.isPending?l("customFields.saving","Saving…"):t?l("customFields.form.updateField","Update field"):l("customFields.addField","Add field")]})]})]})})}function cd({field:t,canEdit:a,onEdit:s,onDelete:l}){var G;const{t:i}=Q(),c=pr[t.fieldType],r=br[t.entityType]??br.PROJECT,o=c.icon,x=_e(),[d,u]=g.useState(!1),[h,f]=g.useState(t.name),j=g.useRef(null),b=$({mutationFn:R=>ka.updateDefinition(t.id,{name:R}),onSuccess:()=>{x.invalidateQueries({queryKey:["custom-field-definitions"]}),k.success(i("customFields.toast.fieldRenamed","Field renamed")),u(!1)},onError:R=>k.error(U(R,"rename field"))}),y=t.showInGrid!==!1,N=$({mutationFn:R=>ka.updateDefinition(t.id,{showInGrid:R}),onSuccess:()=>{x.invalidateQueries({queryKey:["custom-field-definitions"]}),k.success(y?i("customFields.toast.hiddenFromGrid","Hidden from Grid by default"):i("customFields.toast.shownOnGrid","Shown on Grid by default"))},onError:R=>k.error(U(R,"update Grid visibility"))}),p=()=>{a&&(f(t.name),u(!0),setTimeout(()=>{var R;return(R=j.current)==null?void 0:R.select()},0))},S=()=>{const R=h.trim();if(!R||R===t.name){u(!1);return}b.mutate(R)},C=()=>{f(t.name),u(!1)};return e.jsxs("div",{className:`flex items-center gap-3 py-3 px-4 bg-white dark:bg-gray-800 rounded-xl border
34                    border-gray-100 dark:border-gray-700 hover:border-gray-200 dark:hover:border-gray-600 transition-colors`,children:[e.jsx("span",{className:`text-[11px] font-semibold px-2 py-0.5 rounded-full whitespace-nowrap flex-shrink-0 ${r.color}`,children:Cr(i,t.entityType)}),e.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 ${c.color}`,children:e.jsx(o,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("input",{ref:j,value:h,onChange:R=>f(R.target.value),onKeyDown:R=>{R.key==="Enter"&&S(),R.key==="Escape"&&C()},onBlur:S,disabled:b.isPending,className:"text-sm font-medium text-gray-900 dark:text-white bg-gray-50 dark:bg-gray-700 border border-indigo-300 dark:border-indigo-500 rounded px-2 py-0.5 outline-none focus:ring-1 focus:ring-indigo-400 w-48",autoFocus:!0}),b.isPending&&e.jsx("span",{className:"text-[11px] text-indigo-500",children:i("customFields.saving","Saving…")})]}):e.jsxs("button",{onClick:a?p:void 0,className:`text-sm font-medium text-gray-900 dark:text-white ${a?"group/name inline-flex items-center gap-1 hover:text-indigo-600 dark:hover:text-indigo-400 cursor-text":""}`,title:a?i("customFields.clickToRename","Click to rename"):void 0,children:[t.name,a&&e.jsx(Ps,{className:"w-3 h-3 text-gray-300 dark:text-gray-600 opacity-0 group-hover/name:opacity-100 transition-opacity"})]}),t.required&&e.jsx("span",{className:"text-[11px] font-medium text-red-500 bg-red-50 dark:bg-red-900/20 px-1.5 py-0.5 rounded",children:i("customFields.required","Required")}),t.defaultValue&&e.jsx("span",{className:"text-[11px] text-gray-400 dark:text-gray-500 bg-gray-50 dark:bg-gray-700 px-1.5 py-0.5 rounded",children:i("customFields.defaultValueChip","default: {{value}}",{value:t.defaultValue})})]}),t.description&&e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 truncate mt-0.5",children:t.description}),(t.fieldType==="DROPDOWN"||t.fieldType==="MULTI_SELECT")&&t.options&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:t.options.map((R,Z)=>e.jsx("span",{className:"text-[11px] text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-700 border border-gray-100 dark:border-gray-600 px-1.5 py-0.5 rounded-full",children:R},Z))})]}),e.jsxs("div",{className:"flex items-center gap-2 ms-2 flex-shrink-0",children:[e.jsx("span",{className:`text-xs font-medium px-2 py-0.5 rounded-full ${c.color}`,children:hr(i,t.fieldType)}),((G=t._count)==null?void 0:G.values)>0&&e.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500 whitespace-nowrap",children:i("customFields.usesCount",{count:t._count.values,defaultValue_one:"{{count}} use",defaultValue_other:"{{count}} uses"})}),t.entityType==="TASK"&&a&&e.jsxs("button",{onClick:()=>N.mutate(!y),disabled:N.isPending,title:y?i("customFields.gridToggle.onTitle","Showing on Grid view by default. Click to opt out for everyone."):i("customFields.gridToggle.offTitle","Hidden from Grid view by default. Click to show it again."),className:`inline-flex items-center gap-1 text-[11px] font-medium px-2 py-0.5 rounded-full border transition-colors whitespace-nowrap
35              ${y?"bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 border-indigo-200 dark:border-indigo-800 hover:bg-indigo-100 dark:hover:bg-indigo-900/30":"bg-gray-50 dark:bg-gray-800 text-gray-400 dark:text-gray-500 border-gray-200 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700"}`,children:[e.jsx(lo,{className:"w-3 h-3"}),y?i("customFields.gridToggle.on","On Grid"):i("customFields.gridToggle.off","Off Grid")]}),a&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:s,title:i("customFields.editAllProperties","Edit all properties"),className:"p-1.5 text-gray-400 hover:text-indigo-600 dark:hover:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 rounded transition-colors",children:e.jsx(co,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:l,title:i("customFields.deleteField","Delete field"),className:"p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors",children:e.jsx(dt,{className:"w-3.5 h-3.5"})})]})]})]})}function gd(){const{t}=Q(),{currentOrg:a}=Qe(),s=_e(),{showConfirm:l,ConfirmUI:i}=As(),{policy:c}=ja(),r=Kt(c,"org.formconfig.manage",a==null?void 0:a.role),[o,x]=g.useState(!1),[d,u]=g.useState(null),[h,f]=g.useState({}),[j,b]=g.useState(!1),{data:y,isLoading:N}=ee({queryKey:["org-form-config",a==null?void 0:a.id],queryFn:()=>B.getFormConfig(a.id),enabled:!!(a!=null&&a.id),staleTime:6e4});g.useEffect(()=>
35{y!=null&&y.fields&&(f(y.fields),b(!1))},[y]);const p=$({mutationFn:()=>B.saveFormConfig(a.id,h),onSuccess:F=>{f(F.fields),b(!1),s.invalidateQueries({queryKey:["org-form-config",a==null?void 0:a.id]}),k.success(t("customFields.toast.projectFormSaved","Project form settings saved"))},onError:F=>k.error(U(F,"save form settings"))}),S=(F,ue)=>{f(me=>({...me,[F]:{...me[F]??Cn[F]??{visible:!0,required:!1},...ue}})),b(!0)},C=F=>h[F]??Cn[F]??{visible:!0,required:!1},[G,R]=g.useState({}),[Z,te]=g.useState(!1),{data:A,isLoading:P}=ee({queryKey:["org-task-form-config",a==null?void 0:a.id],queryFn:()=>B.getTaskFormConfig(a.id),enabled:!!(a!=null&&a.id),staleTime:6e4});g.useEffect(()=>{A!=null&&A.fields&&(R(A.fields),te(!1))},[A]);const z=$({mutationFn:()=>B.saveTaskFormConfig(a.id,G),onSuccess:F=>{R(F.fields),te(!1),s.invalidateQueries({queryKey:["org-task-form-config",a==null?void 0:a.id]}),k.success(t("customFields.toast.taskFormSaved","Task form settings saved"))},onError:F=>k.error(U(F,"save task form settings"))}),M=(F,ue)=>{R(me=>({...me,[F]:{...me[F]??En[F]??{visible:!0,required:!1},...ue}})),te(!0)},J=F=>G[F]??En[F]??{visible:!0,required:!1},[ae,re]=g.useState({}),[H,ge]=g.useState(!1),{data:_,isLoading:se}=ee({queryKey:["org-proposal-form-config",a==null?void 0:a.id],queryFn:()=>B.getProposalFormConfig(a.id),enabled:!!(a!=null&&a.id),staleTime:6e4});g.useEffect(()=>{_!=null&&_.fields&&(re(_.fields),ge(!1))},[_]);const ne=$({mutationFn:()=>B.saveProposalFormConfig(a.id,ae),onSuccess:F=>{re(F.fields),ge(!1),s.invalidateQueries({queryKey:["org-proposal-form-config",a==null?void 0:a.id]}),k.success(t("customFields.toast.proposalFormSaved","Proposal form settings saved"))},onError:F=>k.error(U(F,"save proposal form settings"))}),Ye=(F,ue)=>{re(me=>({...me,[F]:{...me[F]??Tn[F]??{visible:!0,required:!1},...ue}})),ge(!0)},T=F=>ae[F]??Tn[F]??{visible:!0,required:!1},{data:ie=Za,isLoading:Le,isError:we,refetch:Ue}=ts({queryKey:["custom-field-definitions"],queryFn:()=>ka.listDefinitions()}),Je=$({mutationFn:F=>ka.deleteDefinition(F),onSuccess:()=>{s.invalidateQueries({queryKey:["custom-field-definitions"]}),k.success(t("customFields.toast.fieldDeleted","Field deleted"))},onError:F=>k.error(U(F,"delete custom field"))}),Pe=[...ie].sort((F,ue)=>{const me=["PROJECT","TASK","PROPOSAL"],O=me.indexOf(F.entityType)-me.indexOf(ue.entityType);return O!==0?O:(F.order??0)-(ue.order??0)}),mt=F=>{var O;const ue=((O=F._count)==null?void 0:O.values)??0,me=ue>0?t("customFields.confirmDeleteWithValues",{name:F.name,count:ue,defaultValue_one:'Delete "{{name}}"? This will remove {{count}} saved value across all records.',defaultValue_other:'Delete "{{name}}"? This will remove {{count}} saved values across all records.'}):t("customFields.confirmDelete",'Delete "{{name}}"?',{name:F.name});l({title:t("customFields.deleteField","Delete field"),message:me,confirmLabel:t("common.delete","Delete"),variant:"danger",onOk:()=>Je.mutate(F.id)})};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white",children:t("customFields.heading","Enterprise Fields")}),e.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-0.5",children:t("customFields.headingSubtitle","Fields defined here appear on project, task, and proposal forms across the organization")})]}),r&&e.jsxs("button",{onClick:()=>{u(null),x(!0)},className:"btn-primary flex items-center gap-2 text-sm",children:[e.jsx(st,{className:"w-4 h-4"})," ",t("customFields.addField","Add field")]})]}),o&&e.jsx(Rn,{onSave:()=>x(!1),onCancel:()=>x(!1)}),d&&e.jsx(Rn,{initial:d,onSave:()=>u(null),onCancel:()=>u(null)}),e.jsx(ys,{id:"project-form",icon:e.jsx(eo,{className:"w-4 h-4 text-amber-500"}),title:t("customFields.section.projectForm","Project Form Fields"),subtitle:t("customFields.fieldsCount",{count:wn.length,defaultValue_one:"{{count}} field",defaultValue_other:"{{count}} fields"}),accentColor:"border-s-amber-400",dirty:r&&j,onSave:()=>p.mutate(),saving:p.isPending,children:N?[1,2,3,4,5,6].map(F=>e.jsx("div",{className:"h-11 bg-gray-100 dark:bg-gray-800 rounded-xl animate-pulse"},F)):wn.map(({key:F,label:ue,labelKey:me,locked:O})=>e.jsx(sr,{label:t(me,ue),locked:O,cfg:O?{visible:!0,required:!0}:C(F),canEdit:r,onUpdate:Ce=>S(F,Ce)},F))}),e.jsx(ys,{id:"proposal-form",icon:e.jsx(kt,{className:"w-4 h-4 text-purple-500"}),title:t("customFields.section.proposalForm","Proposal Form Fields"),subtitle:t("customFields.fieldsCount",{count:Pn.length,defaultValue_one:"{{count}} field",defaultValue_other:"{{count}} fields"}),accentColor:"border-s-purple-400",dirty:r&&H,onSave:()=>ne.mutate(),saving:ne.isPending,children:se?[1,2,3,4,5,6,7,8,9,10].map(F=>e.jsx("div",{className:"h-11 bg-gray-100 dark:bg-gray-800 rounded-xl animate-pulse"},F)):Pn.map(({key:F,label:ue,labelKey:me,locked:O})=>e.jsx(sr,{label:t(me,ue),locked:O,cfg:O?{visible:!0,required:!0}:T(F),canEdit:r,onUpdate:Ce=>Ye(F,Ce)},F))}),e.jsx(ys,{id:"task-form",icon:e.jsx(to,{className:"w-4 h-4 text-indigo-500"}),title:t("customFields.section.taskForm","Task Form Fields"),subtitle:t("customFields.fieldsCount",{count:An.length,defaultValue_one:"{{count}} field",defaultValue_other:"{{count}} fields"}),accentColor:"border-s-indigo-400",dirty:r&&Z,onSave:()=>z.mutate(),saving:z.isPending,children:P?[1,2,3,4,5,6,7,8].map(F=>e.jsx("div",{className:"h-11 bg-gray-100 dark:bg-gray-800 rounded-xl animate-pulse"},F)):An.map(({key:F,label:ue,labelKey:me,locked:O})=>e.jsx(sr,{label:t(me,ue),locked:O,cfg:O?{visible:!0,required:!0}:J(F),canEdit:r,onUpdate:Ce=>M(F,Ce)},F))}),e.jsxs(ys,{id:"custom-fields",icon:e.jsx(va,{className:"w-4 h-4 text-blue-500"}),title:t("customFields.section.customFields","Custom Fields"),subtitle:t("customFields.section.customFieldsSubtitle","Extended data fields on forms"),count:ie.length,accentColor:"border-s-blue-400",defaultClosed:!0,children:[Le?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(F=>e.jsx("div",{className:"h-14 bg-gray-100 dark:bg-gray-800 rounded-xl animate-pulse"},F))}):we?e.jsx(Cs,{onRetry:()=>Ue()}):Pe.length===0&&!o?e.jsxs("div",{className:"text-center py-10 border-2 border-dashed border-gray-200 dark:border-gray-700 rounded-xl",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center mx-auto mb-3",children:e.jsx(st,{className:"w-5 h-5 text-gray-300 dark:text-gray-600"})}),e.jsx("p",{className:"text-gray-500 dark:text-gray-400 text-sm font-medium mb-1",children:t("customFields.empty.title","No enterprise fields yet")}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mb-3",children:t("customFields.empty.description","Fields you add here will appear on every project or task form in this org")}),r&&e.jsxs("button",{onClick:()=>x(!0),className:"btn-secondary text-sm",children:[e.jsx(st,{className:"w-4 h-4 inline me-1"})," ",t("customFields.empty.cta","Add your first field")]})]}):e.jsx(e.Fragment,{children:["PROJECT","TASK","PROPOSAL"].map(F=>{const ue=Pe.filter(O=>O.entityType===F);if(ue.length===0)return null;const me=Cr(t,F);return e.jsxs("div",{children:[e.jsx("p",{className:`text-[11px] font-semibold uppercase tracking-wider mb-1.5 px-1 ${F==="PROJECT"?"text-amber-600 dar
35k:text-amber-400":F==="TASK"?"text-indigo-600 dark:text-indigo-400":"text-purple-600 dark:text-purple-400"}`,children:me}),e.jsx("div",{className:"space-y-2 mb-3",children:ue.map(O=>e.jsx(cd,{field:O,canEdit:r,onEdit:()=>{x(!1),u(O)},onDelete:()=>mt(O)},O.id))})]},F)})}),Pe.length>0&&e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 pt-2 border-t border-gray-100 dark:border-gray-700",children:t("customFields.adminOnlyNote","Only Owners and Admins can add, edit, or remove enterprise fields.")})]}),i]})}function md(t,a){return t?"value":a?"unknown":"loading"}function Ss(t){return t<10?`0${t}`:`${t}`}function Jn(t){return`${t.getFullYear()}-${Ss(t.getMonth()+1)}-${Ss(t.getDate())}`}function I(t,a,s){return`${t}-${Ss(a)}-${Ss(s)}`}function De(t,a,s,l){const c=new Date(t,a-1,1).getDay();let r=s-c;r<0&&(r+=7);const o=1+r+(l-1)*7;return I(t,a,o)}function ws(t,a,s){const l=new Date(t,a,0);let c=l.getDay()-s;c<0&&(c+=7);const r=l.getDate()-c;return I(t,a,r)}function xd(t){const a=t%19,s=Math.floor(t/100),l=t%100,i=Math.floor(s/4),c=s%4,r=Math.floor((s+8)/25),o=Math.floor((s-r+1)/3),x=(19*a+s-i-o+15)%30,d=Math.floor(l/4),u=l%4,h=(32+2*c+2*d-x-u)%7,f=Math.floor((a+11*x+22*h)/451),j=Math.floor((x+h-7*f+114)/31),b=(x+h-7*f+114)%31+1;return new Date(t,j-1,b)}function Se(t,a){const s=xd(t);return s.setDate(s.getDate()+a),Jn(s)}const ud={code:"US",name:"United States",flag:"🇺🇸",generate:t=>[{date:I(t,1,1),name:"New Year's Day"},{date:De(t,1,1,3),name:"Martin Luther King Jr. Day"},{date:De(t,2,1,3),name:"Presidents' Day"},{date:ws(t,5,1),name:"Memorial Day"},{date:I(t,6,19),name:"Juneteenth"},{date:I(t,7,4),name:"Independence Day"},{date:De(t,9,1,1),name:"Labor Day"},{date:De(t,10,1,2),name:"Columbus Day"},{date:I(t,11,11),name:"Veterans Day"},{date:De(t,11,4,4),name:"Thanksgiving Day"},{date:I(t,12,25),name:"Christmas Day"}]},pd={code:"GB",name:"United Kingdom",flag:"🇬🇧",generate:t=>[{date:I(t,1,1),name:"New Year's Day"},{date:Se(t,-2),name:"Good Friday"},{date:Se(t,1),name:"Easter Monday"},{date:De(t,5,1,1),name:"Early May Bank Holiday"},{date:ws(t,5,1),name:"Spring Bank Holiday"},{date:ws(t,8,1),name:"Summer Bank Holiday"},{date:I(t,12,25),name:"Christmas Day"},{date:I(t,12,26),name:"Boxing Day"}]},hd={code:"CA",name:"Canada",flag:"🇨🇦",generate:t=>{let a=new Date(t,4,24);for(;a.getDay()!==1;)a.setDate(a.getDate()-1);return[{date:I(t,1,1),name:"New Year's Day"},{date:De(t,2,1,3),name:"Family Day"},{date:Se(t,-2),name:"Good Friday"},{date:Se(t,1),name:"Easter Monday"},{date:Jn(a),name:"Victoria Day"},{date:I(t,7,1),name:"Canada Day"},{date:De(t,9,1,1),name:"Labour Day"},{date:De(t,10,1,2),name:"Thanksgiving"},{date:I(t,11,11),name:"Remembrance Day"},{date:I(t,12,25),name:"Christmas Day"},{date:I(t,12,26),name:"Boxing Day"}]}},bd={code:"AU",name:"Australia",flag:"🇦🇺",generate:t=>[{date:I(t,1,1),name:"New Year's Day"},{date:I(t,1,26),name:"Australia Day"},{date:Se(t,-2),name:"Good Friday"},{date:Se(t,-1),name:"Easter Saturday"},{date:Se(t,1),name:"Easter Monday"},{date:I(t,4,25),name:"ANZAC Day"},{date:I(t,12,25),name:"Christmas Day"},{date:I(t,12,26),name:"Boxing Day"}]},yd={code:"DE",name:"Germany",flag:"🇩🇪",generate:t=>[{date:I(t,1,1),name:"Neujahrstag"},{date:Se(t,-2),name:"Karfreitag"},{date:Se(t,1),name:"Ostermontag"},{date:I(t,5,1),name:"Tag der Arbeit"},{date:Se(t,39),name:"Christi Himmelfahrt"},{date:Se(t,50),name:"Pfingstmontag"},{date:I(t,10,3),name:"Tag der Deutschen Einheit"},{date:I(t,12,25),name:"1. Weihnachtstag"},{date:I(t,12,26),name:"2. Weihnachtstag"}]},fd={code:"FR",name:"France",flag:"🇫🇷",generate:t=>[{date:I(t,1,1),name:"Jour de l'An"},{date:Se(t,1),name:"Lundi de Pâques"},{date:I(t,5,1),name:"Fête du Travail"},{date:I(t,5,8),name:"Victoire 1945"},{date:Se(t,39),name:"Ascension"},{date:Se(t,50),name:"Lundi de Pentecôte"},{date:I(t,7,14),name:"Fête Nationale"},{date:I(t,8,15),name:"Assomption"},{date:I(t,11,1),name:"Toussaint"},{date:I(t,11,11),name:"Armistice"},{date:I(t,12,25),name:"Noël"}]},kd={code:"IE",name:"Ireland",flag:"🇮🇪",generate:t=>[{date:I(t,1,1),name:"New Year's Day"},{date:De(t,2,1,1),name:"St. Brigid's Day"},{date:I(t,3,17),name:"St. Patrick's Day"},{date:Se(t,1),name:"Easter Monday"},{date:De(t,5,1,1),name:"May Bank Holiday"},{date:De(t,6,1,1),name:"June Bank Holiday"},{date:De(t,8,1,1),name:"August Bank Holiday"},{date:ws(t,10,1),name:"October Bank Holiday"},{date:I(t,12,25),name:"Christmas Day"},{date:I(t,12,26),name:"St. Stephen's Day"}]},jd={code:"IN",name:"India",flag:"🇮🇳",generate:t=>[{date:I(t,1,26),name:"Republic Day"},{date:I(t,8,15),name:"Independence Day"},{date:I(t,10,2),name:"Gandhi Jayanti"}]},vd={code:"JP",name:"Japan",flag:"🇯🇵",generate:t=>[{date:I(t,1,1),name:"Ganjitsu"},{date:De(t,1,1,2),name:"Seijin-no-Hi"},{date:I(t,2,11),name:"Kenkoku Kinen-no-Hi"},{date:I(t,2,23),name:"Tenno Tanjobi"},{date:I(t,3,20),name:"Shunbun-no-Hi"},{date:I(t,4,29),name:"Showa-no-Hi"},{date:I(t,5,3),name:"Kenpo Kinenbi"},{date:I(t,5,4),name:"Midori-no-Hi"},{date:I(t,5,5),name:"Kodomo-no-Hi"},{date:De(t,7,1,3),name:"Umi-no-Hi"},{date:I(t,8,11),name:"Yama-no-Hi"},{date:De(t,9,1,3),name:"Keiro-no-Hi"},{date:I(t,9,23),name:"Shubun-no-Hi"},{date:De(t,10,1,2),name:"Taiiku-no-Hi"},{date:I(t,11,3),name:"Bunka-no-Hi"},{date:I(t,11,23),name:"Kinro Kansha-no-Hi"}]},Nd={code:"NL",name:"Netherlands",flag:"🇳🇱",generate:t=>[{date:I(t,1,1),name:"Nieuwjaarsdag"}
35,{date:Se(t,-2),name:"Goede Vrijdag"},{date:Se(t,0),name:"Eerste Paasdag"},{date:Se(t,1),name:"Tweede Paasdag"},{date:I(t,4,27),name:"Koningsdag"},{date:I(t,5,5),name:"Bevrijdingsdag"},{date:Se(t,39),name:"Hemelvaartsdag"},{date:Se(t,49),name:"Eerste Pinksterdag"},{date:Se(t,50),name:"Tweede Pinksterdag"},{date:I(t,12,25),name:"Eerste Kerstdag"},{date:I(t,12,26),name:"Tweede Kerstdag"}]},Sd={code:"NZ",name:"New Zealand",flag:"🇳🇿",generate:t=>[{date:I(t,1,1),name:"New Year's Day"},{date:I(t,1,2),name:"Day after New Year's Day"},{date:I(t,2,6),name:"Waitangi Day"},{date:Se(t,-2),name:"Good Friday"},{date:Se(t,1),name:"Easter Monday"},{date:I(t,4,25),name:"ANZAC Day"},{date:De(t,6,1,1),name:"King's Birthday"},{date:De(t,10,1,4),name:"Labour Day"},{date:I(t,12,25),name:"Christmas Day"},{date:I(t,12,26),name:"Boxing Day"}]},wd={code:"SG",name:"Singapore",flag:"🇸🇬",generate:t=>[{date:I(t,1,1),name:"New Year's Day"},{date:Se(t,-2),name:"Good Friday"},{date:I(t,5,1),name:"Labour Day"},{date:I(t,8,9),name:"National Day"},{date:I(t,12,25),name:"Christmas Day"}]},fs=new Date().getFullYear(),Cd=[fs-1,fs,fs+1,fs+2],Mn=[bd,hd,fd,yd,jd,kd,vd,Nd,Sd,wd,pd,ud],rr={list:()=>za.get("/timesheet-approvers").then(t=>t.data),add:t=>za.post("/timesheet-approvers",{userId:t}).then(a=>a.data),remove:t=>za.delete(`/timesheet-approvers/${t}`).then(a=>a.data)},Ad={OWNER:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300",ADMIN:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300",MANAGER:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300",MEMBER:"bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300",GUEST:"bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300"},Ed={OWNER:e.jsx(xo,{className:"w-3 h-3"}),ADMIN:e.jsx(kt,{className:"w-3 h-3"}),MANAGER:e.jsx(ke,{className:"w-3 h-3"})};function Fn(t){return t("orgSettings.general.ownerActionsTooltip","Owner-only actions: change the plan / cancel subscription, edit the permission matrix, and transfer ownership. Day-to-day admin actions (member management, governance, integrations) are also available to Admins.")}function Dn(t,a){switch(a){case"OWNER":return t("orgSettings.role.owner","Owner");case"ADMIN":return t("orgSettings.role.admin","Admin");case"MANAGER":return t("orgSettings.role.manager","Portfolio Manager");case"MEMBER":return t("orgSettings.role.member","Member");case"GUEST":return t("orgSettings.role.guest","Guest");default:return Ri[a]??a}}function lt(t,a,s){if(Di(s,a))return t("orgSettings.plan.services","Services");switch(a){case"FREE":return t("orgSettings.plan.free","Free");case"STARTER":return t("orgSettings.plan.starter","Starter");case"PRO":return t("orgSettings.plan.pro","Professional");case"BUSINESS":return t("orgSettings.plan.business","Business");case"ENTERPRISE":return t("orgSettings.plan.enterprise","Enterprise");case"ENTERPRISE_PLUS":return t("orgSettings.plan.enterprisePlus","Enterprise+ (Self-Hosted)");default:return qn[a]??a}}function qt(t,a){switch(a){case"PROPOSAL_REVIEW":return t("orgSettings.gate.proposalReview","Proposal Review");case"BUSINESS_CASE_REVIEW":return t("orgSettings.gate.businessCaseReview","Business Case Review");case"PLAN_REVIEW":return t("orgSettings.gate.planReview","Plan Review");default:return a}}function _t(t,a){switch(a){case"SCORE":return t("orgSettings.criteria.type.score","Slider");case"RATING":return t("orgSettings.criteria.type.rating","Stars");case"YES_NO":return t("orgSettings.criteria.type.yesNo","Pass/Fail");case"SCALE":return t("orgSettings.criteria.type.scale","Scale");case"DROPDOWN":return t("orgSettings.criteria.type.dropdown","Dropdown");case"TEXT":return t("orgSettings.criteria.type.text","Text");default:return a}}const Ln=["general","permissions","governance","configuration","security","ai-usage","billing"],ea={general:void 0,permissions:["OWNER","ADMIN","MANAGER"],governance:["OWNER","ADMIN","MANAGER"],configuration:["OWNER","ADMIN","MANAGER"],security:["OWNER","ADMIN"],"ai-usage":["OWNER","ADMIN"],billing:void 0};function ks(t,a,s,l){if(t==="billing")return s;const i=ea[t],c=!i||i.includes(a);return t==="governance"?c&&l:c}
35const On={members:"permissions",people:"permissions","custom-fields":"configuration",classification:"governance",calendars:"configuration",timesheets:"configuration"};function nr(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function js({label:t,used:a,limit:s,format:l}){const{t:i}=Q(),c=s?Math.round(a/s*100):0,r=Math.min(c,100),o=s!==null&&a>s,x=!o&&r>=80,d=l??(f=>String(f)),u=o?"text-red-600 dark:text-red-400":x?"text-amber-600 dark:text-amber-400":"text-gray-700 dark:text-gray-300",h=o?"bg-red-500":x?"bg-amber-500":"bg-indigo-500";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[e.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:t}),e.jsxs("span",{className:`font-medium ${u}`,children:[d(a)," / ",s!==null?d(s):"∞"]})]}),s!==null&&s>0&&e.jsx("div",{className:"h-2 bg-gray-100 dark:bg-gray-700 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${h}`,style:{width:`${r}%`}})}),o&&e.jsx("p",{className:"text-[11px] text-red-500 dark:text-red-400 mt-1",children:i("orgSettings.usage.overLimitBy","Over your plan limit by {{amount}}.",{amount:d(a-s)})})]})}function In({freeGuests:t}){const{t:a}=Q();return!t||t.free<=0?null:e.jsx("p",{className:"mt-1.5 text-[11px] text-gray-500 dark:text-gray-400",children:a("orgSettings.usage.freeGuestSeatsLine","Free guest seats in use: {{inUse}} of {{free}}. Guests in them don't take a seat.",{inUse:t.inUse,free:t.free})})}function ir({label:t,icon:a,children:s,used:l,cap:i,loading:c,action:r,note:o}){const x=i===void 0||i===-1||i>=999999,d=l!==void 0&&!x&&i>0,u=d?Math.min(Math.round(l/i*100),100):0,h=d&&l>i,f=d&&!h&&u>=80,j=h?"bg-red-500":f?"bg-amber-500":"bg-indigo-500";return e.jsxs("div",{className:"rounded-xl border border-gray-200 dark:border-gray-700 bg-gray-50/60 dark:bg-gray-800/40 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400",children:[a,t]}),r]}),c?e.jsx(oe,{className:"h-6 w-16 rounded"}):s||e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:`text-lg font-bold ${h?"text-red-600 dark:text-red-400":"text-gray-900 dark:text-white"}`,children:l}),e.jsxs("span",{className:"text-sm text-gray-400 dark:text-gray-500",children:["/ ",x?"∞":i]})]}),!x&&e.jsx("div",{className:"mt-2 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${j}`,style:{width:`${u}%`}})}),o]})]})}const Pd=["Pacific/Auckland","Australia/Sydney","Asia/Tokyo","Asia/Shanghai","Asia/Singapore","Asia/Kolkata","Asia/Dubai","Asia/Karachi","Africa/Nairobi","Europe/Istanbul","Africa/Johannesburg","Europe/Berlin","Europe/Paris","Europe/Madrid","Europe/London","Africa/Lagos","America/Sao_Paulo","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Pacific/Honolulu"];function oc(){var Ar,Er,Pr,Tr,Rr,Mr,Fr,Dr;const{t}=Q(),a=vs(),s=vs(),l=vs(),{currentOrg:i,user:c,organizations:r,setCurrentOrg:o,setOrganizations:x,logout:d,token:u,setAuth:h}=Qe(),f=()=>{Pi.me().then(n=>{n.user&&n.organizations&&u&&h(u,n.user,n.organizations)}).catch(()=>{})},j=qs(n=>n.clearSuspension),b=qs(n=>n.setTimesheetLock),y=qs(n=>n.setRequires2FA),N=_e(),p=zn(),[S,C]=Vn(),{canManage:G,isResolved:R}=ji(),Z=et("projectClassification"),te=et("changeControl"),A=et("governance"),P=Z||te||A,[z,M]=g.useState(()=>{const n=S.get("tab")??"";if(!n)return"general";const v=(i==null?void 0:i.role)??"",E=On[n]??n;return Ln.includes(E)&&ks(E,v,G,P)?E:"general"}),[J,ae]=g.useState((i==null?void 0:i.name)??"");g.useEffect(()=>{ae((i==null?void 0:i.name)??"")},[i==null?void 0:i.id,i==null?void 0:i.name]);const[re,H]=g.useState("monthly"),[ge,_]=g.useState(!1),{showConfirm:se,ConfirmUI:ne}=As(),[Ye,T]=g.useState(!1),[ie,Le]=g.useState(""),[we,Ue]=g.useState(null),Je=Vt({open:!!we,onClose:()=>Ue(null)}),[Pe,mt]=g.useState(null),F=et("permissionMatrix"),ue=et("customRoles"),me=et("timeTracking"),O=(i==null?void 0:i.id)||"",Ce=g.useRef(null),Re=$({mutationFn:n=>vi.uploadOrgLogo(n),onSuccess:n=>{i&&o({...i,logo:n.url}),N.invalidateQueries({queryKey:["organization",O]}),k.success(t("orgSettings.general.logoUpdated","Logo updated"))},onError:n=>k.error(U(n,"upload logo"))}),He=ee({queryKey:["organization",O],queryFn:()=>B.get(O),enabled:!!O}),Et=ee({queryKey:["org-members",O],queryFn:()=>B.members(O),enabled:!!O}),We=Ni(),Oe=ee({queryKey:["billing-upcoming",i==null?void 0:i.id],queryFn:$e.getUpcoming,enabled:z==="billing"&&!!((Ar=We.data)!=null&&Ar.organization.stripeSubscriptionId),staleTime:60*1e3,retry:!1}),jt=ee({queryKey:["billing-plans"],queryFn:$e.getPlans,staleTime:300*1e3}),xt=Object.fromEntries((jt.data??[]).map(n=>[n.code,n.pricePerSeatMonthly])),w=Object.fromEntries((jt.data??[]).map(n=>[n.code,n.freeGuestSeats??0])),X=Si(i==null?void 0:i.product),pe=(n,v)=>Ti(n,v,i==null?void 0:i.product,Ur),le=wi(Ci,X,i==null?void 0:i.product,Ur),Me=jt.data!==void 0,Te=jt.isError,ve=(n,v)=>{const E=md(Me,Te);return e.jsx("td",{className:`px-3 py-2.5 text-center text-gray-700 dark:text-gray-300 ${n===ds?"bg-indigo-50/50 dark:bg-indigo-900/10":""}`,children:E==="value"?v:E==="unknown"?e.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"-"}):e.jsx("span",{"aria-hidden":"true",className:"inline-block h-3 w-8 rounded bg-gray-200 dark:bg-gray-700 animate-pulse align-middle"})},n)},Ve=Object.fromEntries((jt.data??[]).map(n=>[n.code,{maxMembers:n.maxMembers,maxProjects:n.maxProjects,storageGb:n.storageGb,monthlyAiTokens:n.monthlyAiTokens,aiTokensPerSeat:n.aiTokensPerSeat??0}])),Ie=ee({queryKey:["classification-config",O],queryFn:()=>B.getClassificationConfig(O),enabled:!!O&&z==="governance",staleTime:6e4}),[fe,Fe]=g.useState({}),tt=Ie.data,ut=$({mutationFn:n=>B.saveClassificationConfig(O,n),onSuccess:()=>{k.success(t("orgSettings.classification.saved","Classification settings saved")),N.invalidateQueries({queryKey:["classification-config",O]}),N.invalidateQueries({queryKey:["classification-config"]})},onError:n=>k.error(U(n,"save classification settings"))});Oi.useEffect(()=>{tt&&Fe(tt)},[tt]);const vt=g.useMemo(()=>!!tt&&JSON.stringify(fe)!==JSON.stringify(tt),[tt,fe]),Xe=$({mutationFn:n=>B.update(O,{name:n}),onSuccess:n=>{k.success(t("orgSettings.general.orgUpdated","Organization updated")),N.invalidateQueries({queryKey:["organization",O]}),i&&o({...i,name:n.name}),B.list().then(v=>{x(v.map(E=>
35({id:E.id,name:E.name,slug:E.slug,logo:E.logo,plan:E.plan,role:E.role})))})},onError:n=>k.error(U(n,"update organization"))}),at=$({mutationFn:n=>B.update(O,{timezone:n}),onSuccess:()=>{k.success(t("orgSettings.general.timezoneSaved","Timezone updated")),N.invalidateQueries({queryKey:["organization",O]})},onError:n=>k.error(U(n,"update timezone"))}),[Na]=g.useState("permissions"),pt=S.get("subtab"),[aa,as]=g.useState(()=>{const n=pt;return n==="gate-reviewers"||n==="ccb"||n==="criteria"||n==="classification"?n:"classification"}),Sa=[...Z?["classification"]:[],...te?["ccb"]:[],...A?["gate-reviewers","criteria"]:[]],ht=Sa.includes(aa)?aa:Sa[0]??"classification",[Be,Ke]=g.useState(()=>{const n=pt;return n==="calendars"||n==="timesheets"||n==="currency"||n==="custom-fields"?n:"custom-fields"}),[rt,wa]=g.useState(()=>un(pt)??"Controls");g.useEffect(()=>{const n=S.get("tab"),v=S.get("subtab");if(n){const E=On[n]??n;Ln.includes(E)&&E!==z&&ks(E,(i==null?void 0:i.role)??"",G,P)&&M(E)}if(v){["classification","gate-reviewers","ccb","criteria"].includes(v)&&v!==aa&&as(v),["custom-fields","calendars","timesheets","currency"].includes(v)&&v!==Be&&Ke(v);const E=un(v);E&&E!==rt&&wa(E)}},[S,G]),g.useEffect(()=>{if(!R&&S.get("tab")==="billing")return;const n=z==="general"?null:z;let v=null;z==="governance"&&ht!==Sa[0]&&(v=ht),z==="configuration"&&Be!=="custom-fields"&&(v=Be),z==="security"&&rt!=="Controls"&&(v=Yn[rt]);const E=new URLSearchParams(window.location.search),Y=E.get("tab"),K=E.get("subtab");if(Y===n&&K===v)return;const V=new URLSearchParams(E);n===null?V.delete("tab"):V.set("tab",n),v===null?V.delete("subtab"):V.set("subtab",v),C(V,{replace:!0})},[z,aa,Be,rt,R]);const[Ca,sa]=g.useState(!1),[Nt,ra]=g.useState([]),Aa=ee({queryKey:["ccb-members"],queryFn:Ks.list,enabled:!!O&&z==="governance"&&te,staleTime:6e4}),Pt=Aa.data??[],ss=new Set(Pt.map(n=>n.userId)),Ea=[{key:"type",label:t("orgSettings.ccb.field.type","Change Type"),alwaysRequired:!0},{key:"priority",label:t("orgSettings.ccb.field.priority","Priority")},{key:"description",label:t("orgSettings.ccb.field.description","Description"),alwaysRequired:!0},{key:"approvalThreshold",label:t("orgSettings.ccb.field.approvalThreshold","Approval Threshold")},{key:"designatedReviewers",label:t("orgSettings.ccb.field.designatedReviewers","Designated Reviewers")},{key:"scheduleImpact",label:t("orgSettings.ccb.field.scheduleImpact","Schedule Impact (days)")},{key:"budgetImpact",label:t("orgSettings.ccb.field.budgetImpact","Budget Impact (amount)")},{key:"scopeDescription",label:t("orgSettings.ccb.field.scopeDescription","Scope Changes")},{key:"resourceDescription",label:t("orgSettings.ccb.field.resourceDescription","Resource Changes")},{key:"justification",label:t("orgSettings.ccb.field.justification","Business Justification")},{key:"alternativesConsidered",label:t("orgSettings.ccb.field.alternativesConsidered","Alternatives Considered")},{key:"customerImpact",label:t("orgSettings.ccb.field.customerImpact","Customer / User Impact")},{key:"complianceNotes",label:t("orgSettings.ccb.field.complianceNotes","Compliance & Regulatory Notes")},{key:"rollbackPlan",label:t("orgSettings.ccb.field.rollbackPlan","Rollback / Remediation Plan")},{key:"linkedRisks",label:t("orgSettings.ccb.field.linkedRisks","Linked Risks")}],nt=((Er=ee({queryKey:["ccb-form-config",O],queryFn:()=>B.getCcbFormConfig(O),enabled:!!O&&z==="governance"&&te,staleTime:3e4}).data)==null?void 0:Er.fields)??{},zt=$({mutationFn:n=>B.saveCcbFormConfig(O,n),onSuccess:()=>{N.invalidateQueries({queryKey:["ccb-form-config",O]}),k.success(t("orgSettings.ccb.formSettingsSaved","CCB form settings saved"))},onError:n=>k.error(U(n,"save CCB form settings"))}),Pa=(n,v,E)=>{var K,V;const Y={};for(const ce of Ea)Y[ce.key]={visible:((K=nt[ce.key])==null?void 0:K.visible)??!0,required:((V=nt[ce.key])==null?void 0:V.required)??!1};v==="visible"&&!E&&(Y[n].required=!1),Y[n][v]=E,zt.mutate(Y)},na=$({mutationFn:n=>Promise.all(n.map(v=>Ks.add(v))),onSuccess:(n,v)=>{k.success(t("orgSettings.ccb.membersAdded",{count:v.length,defaultValue_one:"{{count}} CCB member added",defaultValue_other:"{{count}} CCB members added"})),ra([]),sa(!1)},onError:n=>k.error(U(n,"add CCB member")),onSettled:()=>N.invalidateQueries({queryKey:["ccb-members"]})}),Ta=$({mutationFn:n=>Ks.remove(n),onSuccess:()=>{k.success(t("orgSettings.ccb.memberRemoved","CCB member removed")),N.invalidateQueries({queryKey:["ccb-members"]})},onError:n=>k.error(U(n,"remove CCB member"))}),[St,Ra]=g.useState({PROPOSAL_REVIEW:[],BUSINESS_CASE_REVIEW:[],PLAN_REVIEW:[]}),Qt=ee({queryKey:["gate-reviewers"],queryFn:()=>Gs.list(),enabled:!!O&&z==="governance"&&A,staleTime:6e4}).data??[],Ma=n=>Qt.filter(v=>v.gate===n),rs=new Set(Qt.map(n=>`${n.gate}:${n.userId}`)),ia=$({mutationFn:({userIds:n,gate:v})=>Promise.all(n.map(E=>Gs.add(E,v))),onSuccess:(n,{userIds:v,gate:E})=>{k.success(t("orgSettings.gateReviewers.added",{count:v.length,defaultValue_one:"{{count}} gate reviewer added",defaultValue_other:"{{count}} gate reviewers added"})),Ra(Y=>({...Y,[E]:[]}))},onError:n=>k.error(U(n,"add gate reviewer")),onSettled:()=>N.invalidateQueries({queryKey:["gate-reviewers"]})}),Ms=$({mutationFn:n=>Gs.remove(n),onSuccess:()=>{k.success(t("orgSettings.gateReviewers.removed","Gate reviewer removed")),N.invalidateQueries({queryKey:["gate-reviewers"]})},onError:n=>k.error(U(n,"remove gate reviewer"))}),[Tt,ns]=g.useState("PROPOSAL_REVIEW"),[Fs,Rt]=g.useState(!1),[de,ze]=g.useState(null),[Ne,it]=g.useState({name:"",description:"",fieldType:"SCORE",options:"",maxScore:10,weight:1}),oa=ee({queryKey:["evaluation-criteria",O,Tt],queryFn:()=>Ua.listCriteria(Tt),enabled:!!O&&z==="governance"&&A,staleTime:3e4}),Mt=oa.data??[],la=Mt.length>0&&!Mt[0].organizationId,Yt=$({mutationFn:n=>Ua.createCriteria(n),onSuccess:()=>{k.success(t("orgSettings.criteria.added","Criteria added")),Rt(!1),it({
35name:"",description:"",fieldType:"SCORE",options:"",maxScore:10,weight:1}),N.invalidateQueries({queryKey:["evaluation-criteria"]})},onError:n=>k.error(U(n,"add evaluation criteria"))}),Fa=$({mutationFn:({id:n,data:v})=>Ua.updateCriteria(n,v),onSuccess:()=>{k.success(t("orgSettings.criteria.updated","Criteria updated")),ze(null),N.invalidateQueries({queryKey:["evaluation-criteria"]})},onError:n=>k.error(U(n,"update evaluation criteria"))}),is=$({mutationFn:n=>Ua.deleteCriteria(n),onSuccess:()=>{k.success(t("orgSettings.criteria.removed","Criteria removed")),N.invalidateQueries({queryKey:["evaluation-criteria"]})},onError:n=>k.error(U(n,"remove evaluation criteria"))}),Da=$({mutationFn:n=>Ua.forkCriteria(n),onSuccess:()=>{k.success(t("orgSettings.criteria.forked","Default criteria copied - you can now edit and delete them")),N.invalidateQueries({queryKey:["evaluation-criteria"]})},onError:n=>k.error(U(n,"customize criteria"))}),[ot,os]=g.useState(!1),[Jt,he]=g.useState("managers"),[Ds,da]=g.useState(!1),[Ft,La]=g.useState(""),Xt=ee({queryKey:["timesheet-settings",O],queryFn:()=>B.getTimesheetSettings(O),enabled:!!O&&z==="configuration"&&Be==="timesheets",staleTime:6e4});g.useEffect(()=>{Xt.data&&(os(Xt.data.enabled),he(Xt.data.mode))},[Xt.data]);const ca=$({mutationFn:n=>B.saveTimesheetSettings(O,n),onSuccess:()=>{k.success(t("orgSettings.timesheets.settingsSaved","Timesheet settings saved")),N.invalidateQueries({queryKey:["timesheet-settings"]})},onError:n=>k.error(U(n,"save timesheet settings"))}),Oa=ee({queryKey:["timesheet-approvers"],queryFn:rr.list,enabled:!!O&&z==="configuration"&&Be==="timesheets"&&ot&&Jt==="approvers",staleTime:6e4}),Dt=Oa.data??[],ls=new Set(Dt.map(n=>n.userId)),Ia=$({mutationFn:n=>rr.add(n),onSuccess:()=>{k.success(t("orgSettings.timesheets.approverAdded","Timesheet approver added")),La(""),da(!1),N.invalidateQueries({queryKey:["timesheet-approvers"]})},onError:n=>k.error(U(n,"add timesheet approver"))}),m=$({mutationFn:n=>rr.remove(n),onSuccess:()=>{k.success(t("orgSettings.timesheets.approverRemoved","Timesheet approver removed")),N.invalidateQueries({queryKey:["timesheet-approvers"]})},onError:n=>k.error(U(n,"remove timesheet approver"))});g.useEffect(()=>{var n;((n=We.data)==null?void 0:n.organization.billingInterval)==="year"&&H("annual")},[(Pr=We.data)==null?void 0:Pr.organization.billingInterval]),g.useEffect(()=>{i&&(ks(z,i.role,G,P)||M("general"))},[i==null?void 0:i.role,G]),g.useEffect(()=>{S.get("checkout")==="success"&&(C(n=>(n.delete("checkout"),n),{replace:!0}),(async()=>{var v;let n=!1;try{const E=await N.fetchQuery({queryKey:["billing-subscription",i==null?void 0:i.id],queryFn:()=>$e.getSubscription()});n=((v=E==null?void 0:E.organization)==null?void 0:v.billingStatus)==="incomplete"}catch{}n?k.success(t("orgSettings.billing.paymentProcessing","Payment received. Bank transfers take a few days to clear, and your plan updates as soon as it does."),{duration:8e3}):k.success(t("orgSettings.billing.subscriptionActivated","Subscription activated! Your plan has been updated.")),f()})())},[]);const D=$({mutationFn:({planCode:n,interval:v})=>$e.createCheckout(n,v),onSuccess:n=>{n.url?window.location.href=n.url:n.upgraded&&n.plan?(k.success(t("orgSettings.billing.planUpdatedTo","Plan updated to {{plan}}",{plan:lt(t,n.plan.code,i==null?void 0:i.product)})),N.invalidateQueries({queryKey:["billing-subscription"]}),i&&o({...i,plan:n.plan.code}),f()):n.devMode&&n.plan&&(k.success(t("orgSettings.billing.planChangedTo","Plan changed to {{plan}}",{plan:lt(t,n.plan.code,i==null?void 0:i.product)})),N.invalidateQueries({queryKey:["billing-subscription"]}),i&&o({...i,plan:n.plan.code}),f())},onError:n=>k.error(U(n,"start checkout"))}),W=n=>Math.round(n*.8),q=$({mutationFn:()=>$e.createPortal(),onSuccess:n=>{window.location.href=n.url},onError:n=>k.error(U(n,"open billing portal"))}),Ee=$({mutationFn:n=>$e.changePlan(n),onSuccess:n=>{k.success(t("orgSettings.billing.planChangedTo","Plan changed to {{plan}}",{plan:lt(t,n.plan.code,i==null?void 0:i.product)})),N.invalidateQueries({queryKey:["billing-subscription"]}),i&&o({...i,plan:n.plan.code}),f()},onError:n=>k.error(U(n,"change plan"))}),Ge=$({mutationFn:()=>B.delete(O),onSuccess:()=>{k.success(t("orgSettings.dangerZone.orgDeleted","Organization deleted"));const n=v=>{o(v),j(),b(null),y(!1),N.invalidateQueries(),p("/dashboard")};B.list().then(v=>{const E=v.map(Y=>({id:Y.id,name:Y.name,slug:Y.slug,logo:Y.logo??null,plan:Y.plan,role:Y.role}));E.length>0?(x(E),n(E[0])):(d(),p("/login"))}).catch(()=>{const v=(r??[]).filter(E=>E.id!==O);v.length>0?(x(v),n(v[0])):(d(),p("/login"))})},onError:n=>k.error(U(n,"delete organization"))}),Lt=(((Tr=ee({queryKey:["projects",O,"demo-probe"],queryFn:async()=>(await Li(()=>import("./index-DjV5vjrK.js").then(v=>v.cC),__vite__mapDeps([0,1,2,3,4,5,6])).then(v=>v.projectsApi.listPaginated(1,100))).data.filter(v=>v.isDemo),enabled:!!O&&((i==null?void 0:i.role)==="OWNER"||(i==null?void 0:i.role)==="ADMIN"),staleTime:6e4}).data)==null?void 0:Tr.length)??0)>0,Ot=$({mutationFn:()=>B.clearDemo(O),onSuccess:n=>{N.invalidateQueries({queryKey:["projects"]}),N.invalidateQueries({queryKey:["tasks"]}),N.invalidateQueries({queryKey:["dashboard"]}),n.deletedProjects>0?k.success(t("orgSettings.sampleData.removed",{count:n.deletedProjects,defaultValue_one:"Removed {{count}} sample project.",defaultValue_other:"Removed {{count}} sample projects."})):k(t("orgSettings.sampleData.nothingToDelete","No sample data to delete"),{icon:"ℹ"})},onError:n=>k.error(U(n,"delete sample data"))}),qa=g.useRef(!1);if(g.useEffect(()=>{const n=(S.get("startCheckout")||"").toUpperCase();if(!n||qa.current||!["STARTER","PRO","BUSINESS","ENTERPRISE"].includes(n))return;qa.current=!0;const v=(S.get("interval")||"").toLowerCase(),E=v==="annual"?"annual"
35:v==="monthly"?"monthly":re,Y=new URLSearchParams(S);if(Y.delete("startCheckout"),Y.delete("interval"),C(Y,{replace:!0}),(i==null?void 0:i.role)!=="OWNER"){k.error(t("orgSettings.billing.ownerOnlyPurchase","Only the organization owner can purchase a plan."));return}H(E),D.mutate({planCode:n,interval:E})},[]),!i)return e.jsx("div",{className:"p-8 text-center text-gray-500 dark:text-gray-400",children:t("orgSettings.noOrgSelected","No organization selected.")});const qe=i.role==="OWNER"||i.role==="ADMIN"||i.role==="MANAGER",be=i.role==="OWNER",Ls=J.trim().length>0&&J.trim()!==i.name,Xn=i.role==="OWNER",{policy:Os}=ja(),Ze=Kt(Os,"org.governance.manage",i.role),Zn=Kt(Os,"org.formconfig.manage",i.role);Kt(Os,"org.member.invite",i.role);const Ae=He.data,Is=Et.data||[],L=We.data,ga=((Rr=L==null?void 0:L.organization)==null?void 0:Rr.billingSource)==="MARKETPLACE"||!!((Mr=L==null?void 0:L.organization)!=null&&Mr.marketplaceStatus),ds=(i.plan??"FREE").toUpperCase().replace(/[ -]/g,"_"),_a=Ai({plan:i.plan,trialPlanEndsAt:i.trialPlanEndsAt}).toUpperCase().replace(/[ -]/g,"_"),ei=[{id:"general",label:t("orgSettings.tab.general","General")},{id:"permissions",label:t("orgSettings.tab.permissions","Permissions"),roles:ea.permissions,icon:e.jsx(vr,{className:"w-3.5 h-3.5"})},{id:"governance",label:t("orgSettings.tab.governance","Governance"),roles:ea.governance,icon:e.jsx(kt,{className:"w-3.5 h-3.5"})},{id:"configuration",label:t("orgSettings.tab.configuration","Configuration"),roles:ea.configuration,icon:e.jsx(gs,{className:"w-3.5 h-3.5"})},{id:"security",label:t("orgSettings.tab.security","Security & Compliance"),roles:ea.security,icon:e.jsx(ke,{className:"w-3.5 h-3.5"})},{id:"ai-usage",label:t("orgSettings.tab.aiStorage","AI and Storage"),roles:ea["ai-usage"],icon:e.jsx(va,{className:"w-3.5 h-3.5"})},{id:"billing",label:t("orgSettings.tab.billing","Billing"),roles:ea.billing,icon:e.jsx(Ha,{className:"w-3.5 h-3.5"})}].filter(n=>ks(n.id,i.role,G,P));return e.jsxs("div",{className:"p-6 w-full",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"w-10 h-10 bg-indigo-500 rounded-xl flex items-center justify-center",children:e.jsx(Hr,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"flex items-center gap-3 flex-wrap",children:e.jsx("h1",{className:"text-xl font-bold text-gray-900 dark:text-white",children:t("orgSettings.title","Organization Settings")})}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:i.name})]})]}),e.jsx("div",{ref:a.ref,style:a.style,className:"flex gap-1 mb-6 bg-gray-100 dark:bg-gray-800 rounded-lg p-1 w-fit max-md:w-full max-md:overflow-x-auto max-md:[&>button]:shrink-0 max-md:[&>button]:whitespace-nowrap scrollbar-hide",children:ei.map(n=>e.jsxs("button",{onClick:()=>M(n.id),className:`flex items-center gap-1.5 px-4 py-2 rounded-md text-sm font-medium transition-colors ${z===n.id?"bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"}`,children:[n.icon,n.label]},n.id))}),z==="general"&&e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"card p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsxs("button",{type:"button",onClick:()=>{var n;return qe&&((n=Ce.current)==null?void 0:n.click())},disabled:Re.isPending||!qe,className:`relative w-20 h-20 rounded-2xl overflow-hidden group flex-shrink-0 border-2 border-gray-200 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 ${qe?"cursor-pointer":"cursor-default"}`,title:qe?t("orgSettings.general.changeLogoTooltip","Click to change logo"):void 0,children:[i!=null&&i.logo?e.jsx("img",{src:i.logo,alt:i.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full bg-indigo-100 dark:bg-indigo-900/40 flex items-center justify-center",children:e.jsx("span",{className:"text-3xl font-bold text-indigo-600 dark:text-indigo-400",children:(Fr=i==null?void 0:i.name)==null?void 0:Fr.charAt(0).toUpperCase()})}),qe&&e.jsx("div",{className:"absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:Re.isPending?e.jsx("div",{className:"w-5 h-5 border-2 border-white border-t-transparent roun
35ded-full animate-spin"}):e.jsx(go,{className:"w-5 h-5 text-white"})})]}),e.jsx("input",{ref:Ce,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",className:"hidden",onChange:n=>{var E;const v=(E=n.target.files)==null?void 0:E[0];v&&Re.mutate(v),n.target.value=""}}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-base font-bold text-gray-900 dark:text-white truncate",children:i==null?void 0:i.name}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium ${Ad[i.role]}`,children:[Ed[i.role],Dn(t,i.role)]}),e.jsx("span",{title:Fn(t),"aria-label":Fn(t),className:"inline-flex text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 cursor-help",children:e.jsx(kr,{className:"w-3.5 h-3.5"})})]}),qe?e.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:t("orgSettings.general.logoHint","Click logo to upload • JPEG, PNG, GIF, WebP • max 5 MB")}):e.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:t("orgSettings.general.logoAdminOnly","Only owners and admins can change the logo")})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("orgSettings.general.orgName","Organization Name")}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("input",{type:"text",className:"input flex-1",value:J,onChange:n=>ae(n.target.value),onKeyDown:n=>{n.key==="Enter"&&qe&&Ls&&!Xe.isPending&&Xe.mutate(J.trim())},disabled:!qe}),qe&&e.jsx("button",{onClick:()=>Ls&&Xe.mutate(J.trim()),disabled:!Ls||Xe.isPending,className:"btn-primary px-4",children:Xe.isPending?t("orgSettings.saving","Saving…"):t("orgSettings.save","Save")})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("orgSettings.general.timezone","Timezone")}),e.jsxs("select",{className:"input",value:((Dr=He.data)==null?void 0:Dr.timezone)??"",disabled:!qe||at.isPending,onChange:n=>at.mutate(n.target.value||null),children:[e.jsx("option",{value:"",children:t("orgSettings.general.timezoneUtc","UTC (default)")}),Pd.map(n=>e.jsx("option",{value:n,children:n},n))]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:t("orgSettings.general.timezoneHelp","Scheduled emails are sent during working hours in this timezone.")})]}),(()=>{var K,V,ce;const n=Ve[ds],v=n==null?void 0:n.maxMembers,E=n==null?void 0:n.maxProjects,Y=He.isLoading||!Ae;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(ir,{label:t("orgSettings.general.statPlan","Plan"),icon:e.jsx(Wr,{className:"w-3.5 h-3.5 text-indigo-500"}),action:be?e.jsx("button",{onClick:()=>M("billing"),className:"text-xs font-medium text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300",children:t("orgSettings.general.statPlanChange","Change")}):void 0,children:e.jsx("span",{className:"text-lg font-bold capitalize text-gray-900 dark:text-white",children:lt(t,ds,i==null?void 0:i.product)})}),e.jsx(ir,{label:t("orgSettings.general.statMembers","Members"),icon:e.jsx(ba,{className:"w-3.5 h-3.5 text-gray-400"}),used:Ae!=null&&Ae.seats?Ae.seats.used:((K=Ae==null?void 0:Ae._count)==null?void 0:K.members)??0,cap:Ae!=null&&Ae.seats?Ae.seats.limit??-1:v,loading:Y,note:e.jsx(In,{freeGuests:(V=Ae==null?void 0:Ae.seats)==null?void 0:V.freeGuests})}),e.jsx(ir,{label:t("orgSettings.general.statProjects","Projects"),icon:e.jsx(Hr,{className:"w-3.5 h-3.5 text-gray-400"}),used:((ce=Ae==null?void 0:Ae._count)==null?void 0:ce.projects)??0,cap:E,loading:Y})]})})(),(be||i.role==="ADMIN")&&e.jsxs("div",{className:"border-t border-gray-200 dark:border-gray-700 pt-6",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-white mb-1",children:t("orgSettings.sampleData.title","Sample data")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-4",children:t("orgSettings.sampleData.description","Delete the auto-seeded demo project(s) in this organization. This is safe to run at any time - it only removes projects that were flagged as sample data.")}),e.jsxs("button",{type:"button",onClick:()=>{se({title:t("orgSettings.sampleData.confirmTitle","Delete sample data?"),message:t("orgSettings.sampleData.confirmMessage","All demo projects (and their tasks, epics, sprints, milestones, and risks) will be removed. This cannot be undone."),confirmLabel:t("orgSettings.sampleData.confirmLabel","Delete sample data"),variant:"danger",onOk:()=>Ot.mutate()})},disabled:Ot.isPending||!Lt,className:"btn-secondary text-sm disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",title:Lt?void 0:t("orgSettings.sampleData.noneTooltip","No sample data in this organization"),children:[e.jsx(dt,{className:"w-4 h-4"}),Ot.isPending?t("orgSettings.deleting","Deleting…"):Lt?t("orgSettings.sampleData.confirmLabel","Delete sample data"):t("orgSettings.sampleData.nothingToDelete","No sample data to delete")]})]}),be&&e.jsx(ed,{orgId:O}),be&&e.jsxs("div",{className:"border-t border-red-200 dark:border-red-800/50 pt-6",children:[e.jsx("h3",{className:"text-sm font-semibold text-red-700 dark:text-red-400 mb-1",children:t("orgSettings.dangerZone.title","Danger Zone")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-4",children:t("orgSettings.dangerZone.description","Delete this organization. Members will lose access immediately. A super-admin can restore it if needed.")}),Ye?e.jsxs("div",{className:"rounded-lg border border-red-300 dark:border-red-700 bg-red-50 dark:bg-red-900/10 p-4 space-y-3",children:[e.jsxs("p",{className:"text-sm text-red-800 dark:text-red-300 font-medium",children:[t("orgSettings.dangerZone.typeNamePrefix","Type")," ",e.jsx("span",{className:"font-mono font-bold",children:i.name})," ",t("orgSettings.dangerZone.typeNameSuffix","to confirm deleti
35on")]}),e.jsx("input",{type:"text",className:"input w-full",placeholder:i.name,value:ie,onChange:n=>Le(n.target.value),autoFocus:!0}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>Ge.mutate(),disabled:ie!==i.name||Ge.isPending,className:"btn-danger flex items-center gap-2 text-sm disabled:opacity-50 disabled:cursor-not-allowed",children:Ge.isPending?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"})," ",t("orgSettings.deleting","Deleting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(dt,{className:"w-4 h-4"})," ",t("orgSettings.dangerZone.deletePermanently","Delete permanently")]})}),e.jsx("button",{onClick:()=>{T(!1),Le("")},className:"btn-secondary text-sm",disabled:Ge.isPending,children:t("common.cancel","Cancel")})]})]}):e.jsxs("button",{onClick:()=>T(!0),className:"btn-danger flex items-center gap-2 text-sm",children:[e.jsx(dt,{className:"w-4 h-4"}),t("orgSettings.dangerZone.deleteOrg","Delete Organization")]})]})]})}),z==="permissions"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50/60 dark:bg-gray-800/40 text-xs text-gray-600 dark:text-gray-400",children:[e.jsx(ba,{className:"w-3.5 h-3.5 flex-shrink-0 text-gray-400 dark:text-gray-500"}),e.jsx("span",{className:"flex-1 truncate",children:t("orgSettings.permissions.peopleBanner","Looking for team members and invitations? They live on the People & Teams page.")}),e.jsxs(Wt,{to:"/people",className:"inline-flex items-center gap-1 font-medium text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 whitespace-nowrap",children:[t("orgSettings.permissions.openPeople","Open People & Teams"),e.jsx(ha,{className:"w-3 h-3"})]})]}),Na==="permissions"&&qe&&e.jsx("div",{className:"card p-4",children:e.jsx(Yo,{orgId:O,canEdit:Xn,allowCustomRoles:ue,planLockedForCustomization:!F,onUpgradeClick:()=>M("billing")})})]}),z==="ai-usage"&&Ae&&e.jsx(_l,{org:Ae,canEdit:be||i.role==="ADMIN"}),z==="billing"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(So,{}),We.isLoading?e.jsxs("div",{className:"card p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(oe,{className:"h-5 w-32 rounded"}),e.jsx(oe,{className:"h-8 w-24 rounded"})]}),e.jsx(oe,{className:"h-3 w-full rounded",rows:2}),e.jsx(oe,{className:"h-12 w-full rounded"})]}):L?(()=>{const n=L.stripe,v=L.stripeEnabled,E=!!L.organization.stripeCustomerId,Y=!!L.organization.stripeSubscriptionId,K=L.organization.billingStatus,V={active:{label:t("orgSettings.billing.status.active","Active"),cls:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300",Icon:ct},trialing:{label:t("orgSettings.billing.status.trialing","Trial"),cls:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300",Icon:Gt},past_due:{label:t("orgSettings.billing.status.pastDue","Past due"),cls:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300",Icon:Vr},incomplete:{label:t("orgSettings.billing.status.incomplete","Payment pending"),cls:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300",Icon:Gt},canceled:{label:t("orgSettings.billing.status.canceled","Canceled"),cls:"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400",Icon:Qa}},ce=V[K??"active"]??V.active,Ct=ce.Icon;return e.jsxs("div",{className:"card p-6",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-lg font-bold text-gray-900 dark:text-white",children:lt(t,L.plan.code,i==null?void 0:i.product)}),e.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",children:t("orgSettings.billing.currentPlan","Current Plan")}),v&&K&&e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${ce.cls}`,children:[e.jsx(Ct,{className:"w-3 h-3"}),ce.label]}),v&&L.organization.billingInterval==="year"&&e.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",children:t("orgSettings.billing.annualBadge","Annual · 20% off")}),!v&&!ga&&e.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",children:t("orgSettings.billing.demoModeBadge","Demo Mode")}),ga&&e.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",children:t("orgSettings.billing.marketplaceBadge","Microsoft Marketplace")})]}),(()=>
35{if(Ei(L.organization.trialPlanEndsAt)){const xa=new Date(L.organization.trialPlanEndsAt);return e.jsxs("div",{className:"mt-1 space-y-0.5",children:[e.jsx("p",{className:"text-gray-500 dark:text-gray-400 text-sm",children:t("orgSettings.billing.enterpriseTrialEnds","Enterprise trial, ends {{date}}",{date:xa.toLocaleDateString(void 0,{day:"numeric",month:"short",year:"numeric"})})}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:t("orgSettings.billing.trialNoCharge","No charge. Your workspace returns to Free when the trial ends.")})]})}const xe=v&&L.organization.billingInterval==="year",Zt=_r(i==null?void 0:i.product,L.plan.code)??xt[L.plan.code]??L.plan.pricePerSeatMonthly,bt=xe?W(Zt):Zt,ye=L.guestSeats,It=(ye==null?void 0:ye.billableMembers)??L.usage.members.used,ma=bt*It;return bt===0?e.jsxs("div",{className:"mt-1 space-y-0.5",children:[e.jsx("p",{className:"text-gray-500 dark:text-gray-400 text-sm",children:t("orgSettings.billing.freeForever","Free forever")}),ye&&ye.freeGuestSeats>0&&e.jsxs("p",{className:"text-xs text-green-600 dark:text-green-400 flex items-center gap-1",children:[e.jsx(Ba,{className:"w-3 h-3"}),t("orgSettings.billing.freeGuestSeatsIncluded",{count:ye.freeGuestSeats,defaultValue_one:"{{count}} free guest seat included",defaultValue_other:"{{count}} free guest seats included"})]})]}):e.jsxs("div",{className:"mt-1 space-y-0.5",children:[e.jsxs("p",{className:"text-gray-500 dark:text-gray-400 text-sm",children:[t("orgSettings.billing.pricePerSeatMonth","${{price}}/seat/month",{price:bt}),xe&&e.jsxs("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:[" ",t("orgSettings.billing.billedAnnuallyParen","(billed annually)")]})]}),ye&&e.jsxs("p",{className:`text-xs flex items-center gap-1 ${ye.freeGuestSeats>0?"text-green-600 dark:text-green-400":"text-gray-400 dark:text-gray-500"}`,children:[e.jsx(Ba,{className:"w-3 h-3"}),ye.freeGuestSeats>0?t("orgSettings.billing.freeGuestSeatsIncluded",{count:ye.freeGuestSeats,defaultValue_one:"{{count}} free guest seat included",defaultValue_other:"{{count}} free guest seats included"}):t("orgSettings.billing.noFreeGuestSeats","No free guest seats on this plan")]}),Y&&e.jsxs("div",{className:"space-y-0.5 pt-0.5",children:[e.jsxs("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:[t("orgSettings.billing.seatMath",{count:It,price:bt,defaultValue_one:"{{count}} billable seat × ${{price}}",defaultValue_other:"{{count}} billable seats × ${{price}}"})," = ",e.jsx("span",{className:"font-semibold text-gray-700 dark:text-gray-300",children:t("orgSettings.billing.perMonthAmount","${{amount}}/month",{amount:ma.toFixed(2)})})]}),ye&&ye.freeCredit>0&&e.jsxs("p",{className:"text-xs text-green-600 dark:text-green-400",children:["✓ ",t("orgSettings.billing.freeGuestSeatsUsed",{count:ye.freeGuestSeats,used:ye.freeCredit,defaultValue_one:"{{used}} of {{count}} free guest seat used",defaultValue_other:"{{used}} of {{count}} free guest seats used"}),ye.totalGuests>ye.freeGuestSeats?` · ${t("orgSettings.billing.guestSeatsBilledAtFullRate",{count:ye.totalGuests-ye.freeGuestSeats,defaultValue_one:"{{count}} billed at full rate",defaultValue_other:"{{count}} billed at full rate"})}`:""]})]})]})})(),(n==null?void 0:n.currentPeriodEnd)&&e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-0.5",children:n.cancelAtPeriodEnd?t("orgSettings.billing.cancelsOn","Cancels on {{date}}",{date:new Date(n.currentPeriodEnd).toLocaleDateString()}):t("orgSettings.billing.renewsOn","Renews on {{date}}",{date:new Date(n.currentPeriodEnd).toLocaleDateString()})}),(()=>{var ye;const xe=(ye=Oe.data)==null?void 0:ye.upcoming;if(!xe)return null;const Zt=!(n!=null&&n.cancelAtPeriodEnd)&&!!(n!=null&&n.currentPeriodEnd)&&!!xe.chargeAt&&new Date(n.currentPeriodEnd).toDateString()===new Date(xe.chargeAt).toDateString(),bt=xe.chargeAt&&!Zt?new Date(xe.chargeAt).toLocaleDateString():null;return e.jsxs("div",{className:"mt-1.5 space-y-0.5",children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:bt?t("orgSettings.billing.nextChargeOn","Estimated next charge {{amount}} on {{date}}",{amount:xs(xe.amountDue,xe.currency),date:bt}):t("orgSettings.billing.nextCharge","Estimated next charge {{amount}}",{amount:xs(xe.amountDue,xe.currency)})}),xe.prorationAmount!==0&&e.jsx("p",{className:`text-xs ${xe.prorationAmount>
350?"text-amber-600 dark:text-amber-400":"text-green-600 dark:text-green-400"}`,children:xe.prorationAmount>0?t("orgSettings.billing.includesProration","Includes {{amount}} for seat and plan changes made this period",{amount:xs(xe.prorationAmount,xe.currency)}):t("orgSettings.billing.includesProrationCredit","Includes {{amount}} credit for seat and plan changes made this period",{amount:xs(Math.abs(xe.prorationAmount),xe.currency)})})]})})(),(n==null?void 0:n.trialEnd)&&e.jsx("p",{className:"text-xs text-blue-500 dark:text-blue-400 mt-0.5",children:t("orgSettings.billing.trialEnds","Trial ends {{date}}",{date:new Date(n.trialEnd).toLocaleDateString()})}),L.organization.billingSource==="MARKETPLACE"&&L.organization.marketplaceTermEndDate&&e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-0.5",children:L.organization.marketplaceAutoRenew===!1?t("orgSettings.billing.marketplaceExpiresOn","Expires on {{date}} · via Microsoft",{date:new Date(L.organization.marketplaceTermEndDate).toLocaleDateString()}):t("orgSettings.billing.marketplaceRenewsOn","Renews on {{date}} · via Microsoft",{date:new Date(L.organization.marketplaceTermEndDate).toLocaleDateString()})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v&&E&&be&&e.jsx("button",{onClick:()=>q.mutate(),disabled:q.isPending,className:"btn-secondary flex items-center gap-1.5 text-sm",title:t("orgSettings.billing.portalTooltip","Update payment method, download invoices, or cancel subscription"),children:q.isPending?t("orgSettings.billing.opening","Opening…"):e.jsxs(e.Fragment,{children:[e.jsx(ha,{className:"w-3.5 h-3.5"})," ",t("orgSettings.billing.managePaymentInvoices","Manage payment & invoices")]})}),e.jsx(Wr,{className:"w-8 h-8 text-indigo-400"})]})]}),K==="past_due"&&e.jsxs("div",{className:"mb-4 flex items-start gap-2 p-3 rounded-lg bg-red-50 dark:bg-red-900/10 border border-red-200 dark:border-red-700/40",children:[e.jsx(Vr,{className:"w-4 h-4 text-red-500 mt-0.5 shrink-0"}),e.jsxs("p",{className:"text-sm text-red-700 dark:text-red-400",children:[t("orgSettings.billing.pastDueWarning","Your last payment failed. Please update your payment method to avoid service interruption."),v&&be&&e.jsx("button",{onClick:()=>q.mutate(),className:"ms-1 underline hover:no-underline font-medium",children:t("orgSettings.billing.updatePayment","Update payment →")})]})]}),e.jsxs("div",{className:"mt-1 mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400",children:t("orgSettings.billing.usageThisPeriod","Usage this period")}),e.jsx("span",{className:"flex-1 h-px bg-gray-100 dark:bg-gray-700"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(js,{label:t("orgSettings.usage.members","Members"),used:L.usage.members.used,limit:L.usage.members.limit}),e.jsx(In,{freeGuests:L.usage.members.freeGuests})]}),e.jsx(js,{label:t("orgSettings.usage.projects","Projects"),used:L.usage.projects.used,limit:L.usage.projects.limit}),!L.usage.aiTokens.freeAiOneTime&&e.jsx(js,{label:t("orgSettings.usage.aiTokens","AI Tokens ({{month}})",{month:L.usage.aiTokens.month}),used:L.usage.aiTokens.used,limit:L.usage.aiTokens.limit}),L.usage.storage&&e.jsxs("div",{children:[e.jsx(js,{label:t("orgSettings.usage.storage","Storage"),used:L.usage.storage.usedBytes,limit:L.usage.storage.limitBytes,format:nr}),L.usage.storage.breakdown&&L.usage.storage.usedBytes>0?e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:t("orgSettings.usage.storageBreakdown","Workspace files: {{workspace}} · Task attachments: {{tasks}}",{workspace:nr(L.usage.storage.breakdown.workspaceBytes),tasks:nr(L.usage.storage.breakdown.taskBytes)})}):e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:t("orgSettings.usage.storageClarifier","Measures uploaded files only (workspace documents + task attachments). Task data, comments, and external file links don't count.")})]})]}),e.jsxs("div",{className:"mt-4 mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400",children:t("orgSettings.billing.balancesSection","Balances")}),e.jsx("span",{className:"flex-1 h-px bg-gray-100 dark:bg-gray-700"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(Co,{monthly:L.usage.aiTokens,canBuy:i.role==="OWNER"||i.role==="ADMIN"}),e.jsx(Po,{canBuy:i.role==="OWNER"||i.role==="ADMIN"})]}),e.jsxs("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-3",children:[t("orgSettings.billing.agentActionCapNote","AI agent actions are capped per month on Free and Starter and unlimited on Pro and up.")," ",e.jsx("a",{href:"https://docs.onplana.com/ai-agents/agent-action-limits/",target:"_blank",rel:"noopener noreferrer",className:"text-indigo-500 hover:text-indigo-600 underline",children:t("orgSettings.billing.agentActionCapLink","AI agent action limits")})]}),v&&Y&&!(n!=null&&n.cancelAtPeriodEnd)&&be&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-100 dark:border-gray-700 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:t("orgSettings.billing.cancelSubscription","Cancel subscription")}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:t("orgSettings.billing.cancelSubscriptionDesc","You'll retain access until the end of the current billing period.")})]}),e.jsx("button",{onClick:()=>q.mutate(),disabled:q.isPending,className:"text-xs text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 underline hover:no-underline transition-colors",children:q.isPending?t("orgSettings.billing.openingPortal","Opening portal…"):t("orgSettings.billing.cancelViaPortal","Cancel via Billing Portal →")})]}),!v&&L.plan.code!=="FREE"&&be&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-100 dark:border-gray-700 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:t("orgSettings.billing.switchToFree","Switch to Free")}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:t("orgSettings.billing.switchToFreeDesc","Demo mode - no Stripe configured. Reverts this org to the Free plan immediately.")})]}),e.jsx("button",{onClick:()=>{se({title:t("orgSettings.billing.switchToFreeConfirmTitle","Switch to Free plan"),message:t("orgSettings.billing.switchToFreeConfirmMessage","Switch this organization to the Free plan? This takes effect immediately."),confirmLabel:t("orgSettings.billing.switchToFree","Switch to Free"),variant:"warning",onOk:()=>Ee.mutate("FREE")})},disabled:Ee.isPending,className:"text-xs text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 underline hover:no-underline transition-colors",children:Ee.isPending?t("orgSettings.billing.switching","Switching…"):t("orgSettings.billing.switchToFreeArrow","Switch to Free →")})]})]})})():null,ga&&L&&e.jsx("div",{className:"card p-6",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-50 dark:bg-blue-900/30 flex items-center justify-center flex-shrink-0",children:e.jsx(Ha,{className:"w-5 h-5 text-blue-600 dar
35k:text-blue-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white",children:L.organization.marketplaceStatus==="Suspended"?t("orgSettings.marketplace.titleSuspended","Microsoft Marketplace subscription suspended"):L.organization.marketplaceStatus==="Unsubscribed"?t("orgSettings.marketplace.titleCancelled","Microsoft Marketplace subscription cancelled"):t("orgSettings.marketplace.titleActive","Billed through Microsoft Marketplace")}),e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 mt-1",children:L.organization.marketplaceStatus==="Unsubscribed"||L.organization.marketplaceStatus==="Suspended"?t("orgSettings.marketplace.inactiveDescription","This workspace's paid plan came from Microsoft Marketplace and is no longer active. To restore a paid plan, re-subscribe through Microsoft Marketplace. Direct billing here is intentionally disabled for Marketplace workspaces. Your data stays available to export during the grace window."):t("orgSettings.marketplace.activeDescription","This workspace's plan and seats are managed in Microsoft, not here. To upgrade, downgrade, change seats, or cancel, open this subscription in the Microsoft 365 admin center or the Azure portal. Changes sync back to Onplana automatically.")}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3",children:[e.jsx("a",{href:"https://admin.microsoft.com/Adminportal/Home#/subscriptions",target:"_blank",rel:"noopener noreferrer",className:"btn-secondary text-sm",children:t("orgSettings.marketplace.adminCenterLink","Microsoft 365 admin center →")}),e.jsx("a",{href:"https://portal.azure.com",target:"_blank",rel:"noopener noreferrer",className:"btn-secondary text-sm",children:t("orgSettings.marketplace.azurePortalLink","Azure portal →")})]}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-3",children:t("orgSettings.marketplace.aiCreditNote","AI credit purchases are separate and remain available here.")})]})]})}),!ga&&be&&L&&e.jsx(Ko,{orgName:L.organization.name,planCode:L.plan.code,hasActiveStripeSub:!!L.organization.stripeSubscriptionId}),!ga&&e.jsxs("div",{className:"card",children:[e.jsxs("div",{className:"p-4 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white",children:t("orgSettings.billing.allPlans","All Plans")}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:L!=null&&L.stripeEnabled?t("orgSettings.billing.poweredByStripe","Powered by Stripe. Click a plan to start checkout."):t("orgSettings.billing.demoModeNote","Demo mode - plan changes apply instantly without payment.")}),(L==null?void 0:L.stripeEnabled)&&e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:t("orgSettings.billing.taxNote","Taxes (VAT, GST, sales tax) are calculated automatically at checkout based on your billing address.")})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center bg-gray-100 dark:bg-gray-800 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>H("monthly"),className:`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${re==="monthly"?"bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"}`,children:t("orgSettings.billing.monthly","Monthly")}),e.jsxs("button",{onClick:()=>H("annual"),className:`px-3 py-1.5 rounded-md text-xs font-medium transition-colors flex items-center gap-1.5 ${re==="annual"?"bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"}`,children:[t("orgSettings.billing.annual","Annual"),e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400",children:"−20%"})]})]}),(L==null?void 0:L.stripeEnabled)&&L.organization.stripeCustomerId&&be&&e.jsxs("button",{onClick:()=>q.mutate(),disabled:q.isPending,className:"btn-secondary text-xs flex items-center gap-1.5",title:t("orgSettings.billing.portalTooltip","Update payment method, download invoices, or cancel subscription"),children:[e.jsx(ha,{className:"w-3.5 h-3.5"}),q.isPending?t("orgSettings.billing.opening","Opening…"):t("orgSettings.billing.paymentInvoices","Payment & invoices")]})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[760px] text-sm","aria-busy":!Me,children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-100 dark:border-gray-700",children:[e.jsx("th",{className:"sticky top-0 z-10 bg-white dark:bg-gray-800 text-start px-4 py-3 text-gray-500 dark:text-gray-400 font-medium w-48 shadow-[0_1px_0_0_rgba(0,0,0,0.05)] dark:shadow-[0_1px_0_0_rgba(255,255,255,0.05)]",children:t("orgSettings.billing.featureColumn","Feature")}),X.map(n=>{var Zt,bt;const v=n===_a,E=n==="ENTERPRISE_PLUS",Y=n==="FREE",K=!!(L!=null&&L.organization.stripeSubscriptionId),V=!!(L!=null&&L.stripeEnabled),ce=_r(i==null?void 0:i.product,n)??xt[n]??cs[n],Ct=re==="annual"?W(ce):ce;let xe;if(v)xe=e.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs bg-indigo-100 text-indigo-600 dark:bg-indigo-900/30 dark:text-indigo-400 font-medium",children:t("orgSettings.billing.current","Current")});else if(E)xe=e.jsxs("a",{href:"mailto:[email protected]",className:"flex items-center gap-1 justify-center text-xs text-indigo-600 hover:underline dark:text-indigo-400",children:[e.jsx(Wn,{className:"w-3 h-3"})," ",t("orgSettings.billing.contactSales","Contact Sales")]});else if(V&&K&&Y)xe=e.jsx("button",{disabled:!be||q.isPending,onClick:()=>be&&q.mutate(),className:`px-3 py-0.5 rounded-full text-xs font-medium transition-colors ${be?"bg-gray-200 text-gray-700 hover:bg-red-600 hover:text-white dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-red-600 dark:hover:text-white cursor-pointer":"bg-gray-100 text-gray-400 dark:bg-gray-700 dark:text-gray-500 cursor-not-allowed"}`,title:be?t("orgSettings.billing.cancelViaPortalTooltip","Cancel via Billing Portal"):t("orgSettings.billing.ownerOnlyPlanChange","Only the Owner can change plan"),children:t("orgSettings.billing.switchToFree","Switch to Free")});else if(V&&K&&!v){const ye=xt[n]??cs[n],It=ye>(xt[_a]??cs[_a]),ma=$a.indexOf(_a),xa=$a.indexOf(n),ti=ma>=0&&xa>=0&&xa<ma,ai=D.isPending&&((Zt=D.variables)==null?void 0:Zt.planCode)===n;xe=e.jsx("button",{disabled:!be||D.isPending,onClick:()=>{be&&(ti?mt({planCode:n,interval:re,label:lt(t,n,i==null?void 0:i.product),price:ye}):Ue({planCode:n,interval:re,label:lt(t,n,i==null?void 0:i.product),price:ye,isUpgrade:It}))},className:`px-3 py-0.5 rounded-full text-xs font-medium transition-colors ${be?"bg-indigo-600 text-white hover:bg-indigo-700 cursor-pointer":"bg-gray-100 text-gray-400 dark:bg-gray-700 dark:text-gray-500 cursor-not-allowed"}`,title:be?t("orgSettings.billing.switchToPlanTooltip","Switch to {{plan}} ({{interval}})",{plan:lt(t,n,i==null?void 0:i.product),interval:re==="annual"?t("orgSettings.billing.annual","Annual"):t("orgSettings.billing.monthly","Monthly")}):t("orgSettings.billing.ownerOnlyPlanChange","Only the Owner can change plan"),children:ai?"…":It?t("orgSettings.billing.upgrade","Upgrade"):t("orgSettings.billing.downgrade","Downgrade")})}else{const ye=$a.indexOf(_a),It=$a.indexOf(n),ma=ye>=0&&It>=0&&It<ye,xa=D.isPending&&((bt=D.variables)==null?void 0:bt.planCode)===n;xe=e.jsx("button",{disabled:!be||D.isPending,onClick:()=>{be&&(ma?mt({planCode:n,interval:re,label:lt(t,n,i==null?void 0:i.product),price:xt[n]??cs[n]}):D.mutate({planCode:n,interval:re}))},className:`px-3 py-0.5 rounded-full text-xs font-medium transition-colors ${be?"bg-indigo-600 text-white hover:bg-indigo-700 cursor-pointer":"bg-gray-100 text-gray-400 dark:bg-gray-700 dark:text-gray-500 cursor-not-allowed"}`,title:be?void 0:t("orgSettings.billing.ownerOnlyPlanChange","Only the Owner can change plan"),children:xa?t("orgSettings.billing.loading","Loading…"):Y?t("orgSettings.billing.downgrade","Downgrade"):V?t("orgSettings.billing.subscribe","Subscribe"):t("orgSettings.billing.select","Select")})}return e.jsx("th",{className:"sticky top-0 z-10 bg-white dark:bg-gray-800 px-3 py-3 text-center shadow-[0_1px_0_0_rgba(0,0,0,0.05)] dark:shadow-[0_1px_0_0_rgba(255,255,255,0.05)]",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:`font-semibold ${v?"text-indigo-600 dark:text-indigo-400":"text-gray-700 dark:text-gray-300"}`,children:lt(t,n,i==null?void 0:i.product)}),Y?e.jsx("span",{className:"text-xs text-gray-400",children:t("orgSettings.plan.free","Free")}):E?e.jsx("span",{className:"text-xs text-gray-400",children:t("orgSettings.billing.contactSalesLower","Contact sales")}):e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:t("orgSettings.billing.pricePerSeatMo","${{price}}/seat/mo",{price:Ct})}),re==="annual"&&e.jsx("span",{className:"text-[10px] text-gray-400 dark:text-gray-500",children:t("orgSettings.billing.billedAnnually","billed annually")})]}),be?xe:v?e.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs bg-indigo-100 text-indigo-600 dark:bg-indigo-900/30 dark:text-indigo-400 font-medium",children:t("orgSettings.billing.current","Current")}):null]})},n)})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-50 dark:divide-gray-800",children:[e.jsx("tr",{className:"bg-gray-50/50 dark:bg-gray-800/30",children:e.jsx("td",{className:"px-4 py-2 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide",colSpan:7,children:t("orgSettings.billing.limitsSection","
35Limits")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-gray-600 dark:text-gray-400",children:t("orgSettings.usage.members","Members")}),X.map(n=>{var E;const v=((E=Ve[n])==null?void 0:E.maxMembers)??-1;return ve(n,v===-1?"∞":v)})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-gray-600 dark:text-gray-400",children:t("orgSettings.usage.projects","Projects")}),X.map(n=>{var E;const v=((E=Ve[n])==null?void 0:E.maxProjects)??-1;return ve(n,v===-1?"∞":v)})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-gray-600 dark:text-gray-400",children:t("orgSettings.usage.storage","Storage")}),X.map(n=>{var Y;const v=((Y=Ve[n])==null?void 0:Y.storageGb)??-1,E=Fi(v);return ve(n,E)})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-gray-600 dark:text-gray-400",children:t("orgSettings.billing.aiTokensPerSeatRow","AI tokens / seat (one-time bonus)")}),X.map(n=>{var Y;const v=((Y=Ve[n])==null?void 0:Y.aiTokensPerSeat)??0,E=v===-1?"∞":v===0?"-":v<1e6?`${v/1e3}K`:`${v/1e6}M`;return ve(n,E)})]}),e.jsxs("tr",{children:[e.jsxs("td",{className:"px-4 py-2.5 text-gray-600 dark:text-gray-400 flex items-center gap-1.5",children:[e.jsx(Ba,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),t("orgSettings.billing.freeGuestSeatsRow","Free guest seats")]}),X.map(n=>{const v=w[n]??0;return ve(n,v===0?e.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"-"}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-medium text-green-700 dark:text-green-400 bg-green-50 dark:bg-green-900/20 px-2 py-0.5 rounded-full",children:[e.jsx(Ba,{className:"w-3 h-3"}),v]}))})]}),e.jsx("tr",{className:"bg-gray-50/50 dark:bg-gray-800/30",children:e.jsx("td",{className:"p-0",colSpan:7,children:e.jsxs("button",{type:"button",onClick:()=>_(n=>!n),"aria-expanded":ge,className:"w-full flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide hover:text-gray-700 dark:hover:text-gray-200 transition-colors",children:[e.jsx(gt,{className:`w-3.5 h-3.5 transition-transform ${ge?"rotate-180":""}`}),t("orgSettings.billing.featuresSection","Features"),e.jsx("span",{className:"ms-1 normal-case font-normal text-gray-400 dark:text-gray-500",children:ge?t("orgSettings.billing.featuresHide","(hide)"):t("orgSettings.billing.featuresCompareAll","(compare all {{amount}})",{amount:le.length})})]})})}),ge&&le.map(({key:n,label:v,tooltip:E,values:Y})=>e.jsxs("tr",{children:[e.jsxs("td",{className:"px-4 py-2 text-gray-600 dark:text-gray-400",children:[v,E&&e.jsx("span",{title:E,className:"ms-1 cursor-help text-gray-400",children:"*"})]}),X.map(K=>{const V=Y?Y[K]:pe(K,n);return e.jsx("td",{className:`px-3 py-2 text-center ${K===ds?"bg-indigo-50/50 dark:bg-indigo-900/10":""}`,children:typeof V=="string"?e.jsx("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:V}):V?e.jsx(ct,{className:"w-4 h-4 text-green-500 mx-auto"}):e.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"-"})},K)})]},n??v))]})]})})]}),!ga&&!be&&e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 text-center",children:t("orgSettings.billing.ownerOnlyPlanChangeNotice","Only the Owner can change the plan.")})]}),we&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md p-6",ref:Je,role:"dialog","aria-modal":"true","aria-labelledby":"plan-change-title",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-5",children:[e.jsx("div",{className:"w-10 h-10 bg-indigo-100 dark:bg-indigo-900/30 rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx(Ha,{className:"w-5 h-5 text-indigo-600 dark:text-indigo-400"})}),e.jsxs("div",{children:[e.jsx("h3",{id:"plan-change-title",className:"text-base font-semibold text-gray-900 dark:text-white",children:we.isUpgrade?t("orgSettings.planModal.titleUpgrade","Confirm plan upgrade"):t("orgSettings.planModal.titleDowngrade","Confirm plan downgrade")}),e.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:[t("orgSettings.planModal.switchingTo","Switching to")," ",e.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-300",children:we.label})]})]})]}),e.jsx(_o,{targetPlan:we.planCode,orgId:i==null?void 0:i.id}),e.jsxs("div",{className:"rounded-lg bg-gray-50 dark:bg-gray-700/50 border border-gray-200 dark:border-gray-600 p-4 mb-4 space-y-2.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:t("orgSettings.planModal.newPlan","New plan")}),e.jsx("span",{className:"font-semibold text-gray-900 dark:text-white",children:we.label})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:t("orgSettings.planModal.billingCycle","Billing cycle")}),e.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-300 capitalize",children:we.interval==="annual"?t("orgSettings.billing.annual","Annual"):t("orgSettings.billing.monthly","Monthly")})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:t("orgSettings.planModal.pricePerSeat","Price per seat")}),e.jsxs("span",{className:"font-medium text-gray-700 dark:text-gray-300",children:[t("orgSettings.planModal.pricePerMo","${{price}}/mo",{price:we.interval==="annual"?W(we.price):we.price}),we.interval==="annual"&&e.jsx("span",{className:"ms-1 text-xs text-gray-400",children:t("orgSettings.billing.billedAnnuallyParen","(billed annually)")})]})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-xs text-gray-500 dark:text-gray-400 mb-6",children:[e.jsx(je,{className:"w-3.5 h-3.5 mt-0.5 flex-shrink-0 text-amber-500"}),e.jsx("span",{children:we.isUpgrade?t("orgSettings.planModal.prorationUpgrade","A prorated charge for the remainder of the current billing period will be applied to your saved payment method immediately."):t("orgSettings.planModal.prorationDowngrade","A prorated credit will be applied to your next invoice. The change takes effect immediately.")})]}),e.jsxs("div",{className:"flex gap-3 justify-end",children:[e.jsx("button",{onClick:()=>Ue(null),disabled:D.isPending,className:"btn-secondary",children:t("common.cancel","Cancel")}),e.jsx("button",{onClick:()=>{D.mutate({planCode:we.planCode,interval:we.interval}),Ue(null)},disabled:D.isPending,className:"btn-primary flex items-center gap-2",children:D.isPending?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent roun
35ded-full animate-spin"}),t("orgSettings.planModal.processing","Processing…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ha,{className:"w-4 h-4"}),t("orgSettings.planModal.confirmCharge","Confirm & Charge")]})})]})]})}),Pe&&e.jsx(To,{targetPlan:Pe.planCode,targetLabel:Pe.label,targetPrice:Pe.price,interval:Pe.interval,orgName:(i==null?void 0:i.name)??t("orgSettings.thisOrganization","this organization"),onCancel:()=>mt(null),onComplete:n=>{if(mt(null),n.url){window.location.href=n.url;return}n.plan&&(k.success(t("orgSettings.billing.planDowngradedTo","Plan downgraded to {{plan}}",{plan:lt(t,n.plan.code,i==null?void 0:i.product)})),N.invalidateQueries({queryKey:["billing-subscription"]}),i&&o({...i,plan:n.plan.code}),B.list().then(v=>x(v.map(E=>({id:E.id,name:E.name,slug:E.slug,logo:E.logo,plan:E.plan,role:E.role,downgradeFromPlan:E.downgradeFromPlan??null,downgradeGraceUntil:E.downgradeGraceUntil??null})))))}}),z==="governance"&&e.jsx("div",{className:"space-y-6",children:P?e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:s.ref,style:s.style,className:"flex gap-1 border-b border-gray-200 dark:border-gray-700 max-md:overflow-x-auto max-md:[&>button]:shrink-0 max-md:[&>button]:whitespace-nowrap scrollbar-hide",children:[...Z?[{id:"classification",label:t("orgSettings.governance.subtab.classification","Classification")}]:[],...te?[{id:"ccb",label:Pt.length>0?t("orgSettings.governance.subtab.ccbCount","CCB ({{amount}})",{amount:Pt.length}):t("orgSettings.governance.subtab.ccb","CCB")}]:[],...A?[{id:"gate-reviewers",label:Qt.length>0?t("orgSettings.governance.subtab.gateReviewersCount","Gate Reviewers ({{amount}})",{amount:Qt.length}):t("orgSettings.governance.subtab.gateReviewers","Gate Reviewers")}]:[],...A?[{id:"criteria",label:t("orgSettings.governance.subtab.criteria","Evaluation Criteria")}]:[]].map(n=>e.jsx("button",{onClick:()=>as(n.id),className:`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${ht===n.id?"border-indigo-500 text-indigo-600 dark:text-indigo-400":"border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"}`,children:n.label},n.id))}),ht==="classification"&&Z&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"card p-5 border-s-4 border-s-indigo-500 flex gap-3",children:[e.jsx(mo,{className:"w-5 h-5 text-indigo-500 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900 dark:text-white text-sm",children:t("orgSettings.classification.bannerTitle","Project Classification Routing")}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:t("orgSettings.classification.bannerDescription","When enabled, new project creation shows a classification step. Strategic projects route through the full governance pipeline; operational projects are created directly.")})]})]}),Ie.isLoading?e.jsxs("div",{className:"card p-6 space-y-6",children:[e.jsx(oe,{className:"h-6 rounded w-1/4"}),e.jsx(oe,{className:"h-10 rounded-lg w-full",rows:3})]}):e.jsxs("div",{className:"card p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900 dark:text-white",children:t("orgSettings.classification.enableTitle","Enable project classification")}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-0.5",children:t("orgSettings.classification.enableDescription","Show Strategic / Operational picker when creating a new project")})]}),e.jsx("button",{onClick:()=>Fe(n=>({...n,enabled:!n.enabled})),role:"switch","aria-checked":!!fe.enabled,"aria-label":t("orgSettings.classification.enableTitle","Enable project classification"),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${fe.enabled?"bg-indigo-600":"bg-gray-200 dark:bg-gray-700"}`,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${fe.enabled?"translate-x-6 rtl:-translate-x-6":"translate-x-1 rtl:-translate-x-1"}`})})]}),fe.enabled&&e.jsxs(e.Fragment,{children:[e.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-1 uppercase tracking-wide",children:t("orgSettings.classification.thresholdsTitle","Strategic Project Thresholds")}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mb-4",children:t("orgSettings.classification.thresholdsDescription","Projects meeting any of these criteria will be recommended as Strategic.")}
35),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("orgSettings.classification.budgetThreshold","Budget threshold")}),e.jsxs("div",{className:"relative",children:[e.jsx(es,{className:"absolute start-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"number",min:0,className:"input ps-8",value:fe.strategicBudgetThreshold??"",onChange:n=>Fe(v=>({...v,strategicBudgetThreshold:Number(n.target.value)}))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("orgSettings.classification.durationThreshold","Duration threshold")}),e.jsxs("div",{className:"relative",children:[e.jsx(Ya,{className:"absolute start-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"number",min:1,className:"input ps-8 pe-16",value:fe.strategicDurationWeeks??"",onChange:n=>Fe(v=>({...v,strategicDurationWeeks:Number(n.target.value)}))}),e.jsx("span",{className:"absolute end-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs pointer-events-none",children:t("orgSettings.classification.weeksUnit","
35weeks")})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:t("orgSettings.classification.multiTeamRequired","Multi-team required")}),e.jsx("button",{onClick:()=>Fe(n=>({...n,requiresMultiTeam:!n.requiresMultiTeam})),role:"switch","aria-checked":!!fe.requiresMultiTeam,"aria-label":t("orgSettings.classification.multiTeamAria","Require multiple teams for strategic classification"),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${fe.requiresMultiTeam?"bg-indigo-600":"bg-gray-200 dark:bg-gray-700"}`,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${fe.requiresMultiTeam?"translate-x-6 rtl:-translate-x-6":"translate-x-1 rtl:-translate-x-1"}`})}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:t("orgSettings.classification.multiTeamHint","Requires multiple teams")})]})]})]}),e.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-4 uppercase tracking-wide",children:t("orgSettings.classification.customLabelsTitle","Custom Labels")}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("orgSettings.classification.strategicLabel","Strategic label")}),e.jsx("input",{className:"input",value:fe.strategicLabel??"",onChange:n=>Fe(v=>({...v,strategicLabel:n.target.value})),placeholder:t("orgSettings.classification.strategicPlaceholder","Strategic Project")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("orgSettings.classification.operationalLabel","Operational label")}),e.jsx("input",{className:"input",value:fe.operationalLabel??"",onChange:n=>Fe(v=>({...v,operationalLabel:n.target.value})),placeholder:t("orgSettings.classification.operationalPlaceholder","Operational Project")})]})]})]})]}),e.jsx("hr",{className:"border-gray-200 dark:border-gray-700"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-1 uppercase tracking-wide",children:t("orgSettings.creationGate.title","Project Creation Gate")}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mb-3",children:t("orgSettings.creationGate.description","Choose at which governance gate a project is automatically created when a proposal is approved. Earlier gates allow teams to start planning sooner; later gates enforce stricter governance.")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[{value:"PROPOSAL_REVIEW",label:qt(t,"PROPOSAL_REVIEW"),desc:t("orgSettings.creationGate.proposalReviewDesc","Project created after first gate (default)"),tradeoff:t("orgSettings.creationGate.proposalReviewTradeoff","Fastest start - work begins before the financial case is validated. Trade-off: proposals that later fail Business Case will have already consumed delivery capacity.")},{value:"BUSINESS_CASE_REVIEW",label:qt(t,"BUSINESS_CASE_REVIEW"),desc:t("orgSettings.creationGate.businessCaseReviewDesc","Project created after business case approval"),tradeoff:t("orgSettings.creationGate.businessCaseReviewTradeoff","Balanced - financial case approved before delivery starts, but the detailed plan is still being defined. Most teams pick this.")},{value:"PLAN_REVIEW",label:qt(t,"PLAN_REVIEW"),desc:t("orgSettings.creationGate.planReviewDesc","Project created after plan approval"),tradeoff:t("orgSettings.creationGate.planReviewTradeoff","Plan-validated - schedule, scope, and resourcing have all been reviewed before kickoff. Slower start, fewer rework loops downstream.")},{value:"APPROVED",label:t("orgSettings.creationGate.approvedLabel","Fully Approved"),desc:t("orgSettings.creationGate.approvedDesc","Project created only after all gates pass"),tradeoff:t("orgSettings.creationGate.approvedTradeoff","Strictest - every governance gate passed before any work begins. Best for high-stakes or regulated initiatives. Longest cycle time.")}].map(n=>{const v=(fe.projectCreationGate||"PROPOSAL_REVIEW")===n.value;return e.jsxs("button",{type:"button",title:n.tradeoff,"aria-label":t("orgSettings.creationGate.cardAria","{{label}}: {{tradeoff}}",{label:n.label,tradeoff:n.tradeoff}),onClick:()=>Fe(E=>({...E,projectCreationGate:n.value})),className:`flex flex-col items-start p-3 rounded-lg border-2 text-start transition-all ${v?"bg-indigo-50 dark:bg-indigo-900/20 border-indigo-400 dark:border-indigo-500":"border-gray-200 dark:border-gray-700 hover:border-indigo-300 dark:hover:border-indigo-600"}`,children:[e.jsx("span",{className:`text-xs font-semibold ${v?"text-indigo-700 dark:text-indigo-300":"text-gray-700 dark:text-gray-300"}`,children:n.label}),e.jsx("span",{className:"text-[10px] text-gray-500 dark:text-gray-400 mt-0.5 leading-tight",children:n.desc})]},n.value)})}),e.jsx("p",{className:"text-[11px] text-gray-400 dark:text-gray-500 mt-1.5 italic",children:t("orgSettings.creationGate.hoverHint","Hover any card for the cycle-time vs. governance-strictness trade-off.")})]}),e.jsxs("div",{className:"flex justify-end items-center pt-2 gap-3",children:[!Ze&&e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:t("orgSettings.classification.viewOnly","View-only - your role can't change classification config (requires org.governance.manage permission).")}
35),Ze&&vt&&e.jsx("span",{className:"text-xs text-amber-600 dark:text-amber-400",children:t("orgSettings.unsavedChanges","Unsaved changes")}),e.jsx("button",{onClick:()=>ut.mutate(fe),disabled:ut.isPending||!Ze||!vt,title:Ze?vt?void 0:t("orgSettings.noChangesToSave","No changes to save"):t("orgSettings.classification.needsPermissionTooltip","Requires org.governance.manage permission"),className:"btn-primary disabled:opacity-50 disabled:cursor-not-allowed",children:ut.isPending?t("orgSettings.saving","Saving…"):t("orgSettings.classification.saveButton","Save Governance Settings")})]})]})]}),ht==="ccb"&&te&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:t("orgSettings.ccb.description","CCB members can review and approve change requests across all projects in this org, regardless of project membership.")}),Ze&&!Ca&&e.jsxs("button",{onClick:()=>sa(!0),className:"btn-primary text-sm flex items-center gap-1.5",children:[e.jsx(st,{className:"w-3.5 h-3.5"}),t("orgSettings.ccb.addMember","Add member")]})]}),Ca&&Ze&&e.jsxs("div",{className:"card p-3 flex items-center gap-3",children:[e.jsx(ko,{members:Is.filter(n=>!n.user.isAgentPersona&&!ss.has(n.userId)).map(n=>({id:n.userId,name:n.user.name,avatar:n.user.avatar??null})),selected:Nt,onChange:ra,multiple:!0,orgId:O,placeholder:t("orgSettings.ccb.pickerPlaceholder","Select org members…"),className:"flex-1"}),e.jsx("button",{onClick:()=>Nt.length>0&&na.mutate(Nt),disabled:Nt.length===0||na.isPending,className:"btn-primary text-sm px-4 py-2",children:na.isPending?t("orgSettings.adding","Adding…"):Nt.length>1?t("orgSettings.addWithCount","Add ({{amount}})",{amount:Nt.length}):t("orgSettings.add","Add")}),e.jsx("button",{onClick:()=>{sa(!1),ra([])},className:"btn-secondary text-sm px-3 py-2",children:t("common.cancel","Cancel")})]}),Aa.isLoading?e.jsx("div",{className:"card p-4 space-y-3",children:e.jsx(oe,{className:"h-8 rounded w-full",rows:3})}):Pt.length===0?e.jsxs("div",{className:"card p-10 text-center",children:[e.jsx(zr,{className:"w-10 h-10 mx-auto mb-3 text-gray-300 dark:text-gray-600"}),e.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500",children:t("orgSettings.ccb.emptyState","No CCB members yet. Add org members to the board.")})]}):e.jsx("div",{className:"card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-gray-50 dark:bg-gray-800 text-start text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:[e.jsx("th",{className:"px-4 py-3",children:t("orgSettings.ccb.colMember","Member")}),e.jsx("th",{className:"px-4 py-3",children:t("orgSettings.ccb.colAddedBy","Added by")}),e.jsx("th",{className:"px-4 py-3",children:t("orgSettings.ccb.colAdded","Added")}),Ze&&e.jsx("th",{className:"px-4 py-3 w-16"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700",children:Pt.map(n=>{var v;return e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[n.user.avatar?e.jsx("img",{src:n.user.avatar,alt:n.user.name,className:"w-8 h-8 rounded-full object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 bg-indigo-500 rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx("span",{className:"text-xs font-semibold text-white",children:(v=n.user.name)==null?void 0:v.charAt(0).toUpperCase()})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:n.user.name}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:n.user.email})]}),e.jsxs("span",{className:"ms-1 inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",children:[e.jsx(zr,{className:"w-3 h-3"})," ",t("orgSettings.ccb.badge","CCB")]}),n.orgMembership&&!n.orgMembership.isActive&&e.jsx(_s,{deactivatedAt:n.orgMembership.deactivatedAt})]})}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-500 dark:text-gray-400",children:n.addedBy.name}),e.jsx("td",{className:"px-4 py-3 text-xs text-gray-400 whitespace-nowrap",children:new Date(n.createdAt).toLocaleDateString()}),Ze&&e.jsx("td",{className:"px-4 py-3",children:e.jsx("button",{onClick:()=>{se({title:t("orgSettings.ccb.removeConfirmTitle","Remove from CCB"),message:t("orgSettings.ccb.removeConfirmMessage","Remove {{name}}
35 from the CCB?",{name:n.user.name}),confirmLabel:t("orgSettings.remove","Remove"),variant:"danger",onOk:()=>Ta.mutate(n.userId)})},className:"p-1.5 hover:bg-red-50 dark:hover:bg-red-900/20 rounded text-red-400 hover:text-red-500 transition-colors",title:t("orgSettings.ccb.removeConfirmTitle","Remove from CCB"),children:e.jsx(dt,{className:"w-4 h-4"})})})]},n.id)})})]})}),e.jsxs("div",{className:"border-t border-gray-100 dark:border-gray-700 pt-6 mt-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-800 dark:text-gray-200",children:t("orgSettings.ccb.formFieldsTitle","Change Request Form Fields")}),zt.isPending&&e.jsx("span",{className:"text-xs text-gray-400",children:t("orgSettings.saving","Saving…")})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-4",children:t("orgSettings.ccb.formFieldsDescription","Control which fields appear when submitting a change request. Title is always required.")}),e.jsx("div",{className:"card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-gray-50 dark:bg-gray-800 text-start text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:[e.jsx("th",{className:"px-4 py-3 flex-1",children:t("orgSettings.ccb.colField","Field")}),e.jsx("th",{className:"px-4 py-3 text-center w-24",children:t("orgSettings.ccb.colVisible","Visible")}),e.jsx("th",{className:"px-4 py-3 text-center w-24",children:t("orgSettings.ccb.colRequired","Required")})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700",children:Ea.map(n=>{var K,V;const v=((K=nt[n.key])==null?void 0:K.visible)??!0,E=((V=nt[n.key])==null?void 0:V.required)??!1,Y=Zn;return e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[e.jsxs("td",{className:"px-4 py-3 font-medium text-gray-800 dark:text-gray-200",children:[n.label,n.alwaysRequired&&e.jsx("span",{className:"ms-2 text-xs text-gray-400 dark:text-gray-500 font-normal",children:t("orgSettings.ccb.alwaysOn","always on")})]}),e.jsx("td",{className:"px-4 py-3 text-center",children:n.alwaysRequired?e.jsx("span",{className:"inline-block w-4 h-4 rounded-full bg-indigo-500 mx-auto",title:t("orgSettings.ccb.alwaysVisible","Always visible")}):e.jsx("input",{type:"checkbox",checked:v,disabled:!Y||zt.isPending,onChange:ce=>Pa(n.key,"visible",ce.target.checked),className:"accent-indigo-500 w-4 h-4 cursor-pointer disabled:cursor-not-allowed"})}),e.jsx("td",{className:"px-4 py-3 text-center",children:n.alwaysRequired?e.jsx("span",{className:"inline-block w-4 h-4 rounded-full bg-red-400 mx-auto",title:t("orgSettings.ccb.alwaysRequired","Always required")}):e.jsx("input",{type:"checkbox",checked:E,disabled:!Y||!v||zt.isPending,onChange:ce=>Pa(n.key,"required",ce.target.checked),className:"accent-red-500 w-4 h-4 cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"})})]},n.key)})})]})})]})]}),ht==="gate-reviewers"&&A&&e.jsxs("div",{className:"card p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ba,{className:"w-5 h-5 text-purple-500"}),e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white text-sm",children:t("orgSettings.gateReviewers.title","Gate Reviewers")})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-4",children:t("orgSettings.gateReviewers.description","Assign designated reviewers for each governance gate. When reviewers are configured, ALL designated reviewers must submit their review before a proposal can advance.")}),["PROPOSAL_REVIEW","BUSINESS_CASE_REVIEW","PLAN_REVIEW"].map(n=>{var Y,K;const v=qt(t,n),E=Ma(n);return e.jsxs("div",{className:"mb-4 last:mb-0 border border-gray-200 dark:border-gray-700 rounded-lg p-4",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("h4",{className:"text-sm font-semibold text-gray-800 dark:text-white flex items-center gap-2",children:[e.jsx(kt,{className:"w-4 h-4 text-purple-500"}),v,E.length>0&&e.jsx("span",{className:"text-xs font-medium px-1.5 py-0.5 rounded-full bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300",children:E.length})]})}),Ze&&e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ya,{options:Is.filter(V=>!rs.has(`${n}:${V.userId}`)).filter(V=>V.role!=="GUEST"&&!V.user.isAgentPersona).map(V=>
35({id:V.userId,label:V.user.name,sublabel:`${V.user.email} · ${Dn(t,V.role)}`})),selected:St[n]??[],onChange:V=>Ra(ce=>({...ce,[n]:V})),placeholder:t("orgSettings.gateReviewers.pickerPlaceholder","Add reviewers…"),searchPlaceholder:t("orgSettings.gateReviewers.searchPlaceholder","Search team members…"),className:"flex-1"}),e.jsx("button",{onClick:()=>{var V;return(((V=St[n])==null?void 0:V.length)??0)>0&&ia.mutate({userIds:St[n],gate:n})},disabled:(((Y=St[n])==null?void 0:Y.length)??0)===0||ia.isPending,className:"btn-primary text-xs px-3 py-2",children:ia.isPending?t("orgSettings.adding","Adding…"):(((K=St[n])==null?void 0:K.length)??0)>1?t("orgSettings.addWithCount","Add ({{amount}})",{amount:St[n].length}):t("orgSettings.add","Add")})]}),E.length===0?e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 italic py-1",children:t("orgSettings.gateReviewers.emptyState","No designated reviewers - any Owner, Admin, or Portfolio Manager can approve (single-reviewer mode).")}):e.jsx("div",{className:"space-y-1.5",children:E.map(V=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-gray-50 dark:bg-gray-800/50 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 bg-purple-500 rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx("span",{className:"text-[10px] font-bold text-white",children:V.user.name.split(" ").map(ce=>ce[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-800 dark:text-gray-200",children:V.user.name}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:V.user.email})]}),V.orgMembership&&!V.orgMembership.isActive&&e.jsx(_s,{deactivatedAt:V.orgMembership.deactivatedAt})]}),Ze&&e.jsx("button",{onClick:()=>{se({title:t("orgSettings.gateReviewers.removeConfirmTitle","Remove reviewer"),message:t("orgSettings.gateReviewers.removeConfirmMessage","Remove {{name}} from {{gate}}?",{name:V.user.name,gate:v}),confirmLabel:t("orgSettings.remove","Remove"),variant:"danger",onOk:()=>Ms.mutate(V.id)})},className:"p-1.5 hover:bg-red-50 dark:hover:bg-red-900/20 rounded text-red-400 hover:text-red-500 transition-colors",title:t("orgSettings.gateReviewers.removeConfirmTitle","Remove reviewer"),children:e.jsx(dt,{className:"w-3.5 h-3.5"})})]},V.id))})]},n)})]}),ht==="criteria"&&A&&e.jsxs("div",{className:"card p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx($t,{className:"w-5 h-5 text-amber-500"}),e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white text-sm",children:t("orgSettings.criteria.title","Evaluation Criteria")})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-4",children:t("orgSettings.criteria.description","Define the scoring criteria for each governance gate review. Reviewers will score proposals against these criteria.")}),e.jsx("div",{className:"flex gap-1 mb-4 bg-gray-100 dark:bg-gray-700/50 rounded-lg p-1",children:[{key:"PROPOSAL_REVIEW",label:qt(t,"PROPOSAL_REVIEW")},{key:"BUSINESS_CASE_REVIEW",label:qt(t,"BUSINESS_CASE_REVIEW")},{key:"PLAN_REVIEW",label:qt(t,"PLAN_REVIEW")}].map(n=>e.jsx("button",{onClick:()=>{ns(n.key),Rt(!1),ze(null)},className:`flex-1 text-xs font-medium px-3 py-2 rounded-md transition-colors ${Tt===n.key?"bg-white dark:bg-gray-800 text-indigo-600 dark:text-indigo-400 shadow-sm":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"}`,children:n.label},n.key))}),oa.isLoading?e.jsx("div",{className:"py-4 space-y-3",children:e.jsx(oe,{className:"h-8 rounded w-full",rows:3})}):e.jsxs(e.Fragment,{children:[la&&e.jsxs("div",{className:"mb-3 px-3 py-2.5 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg flex items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-xs text-amber-700 dark:text-amber-300",children:[e.jsx(je,{className:"w-3.5 h-3.5 inline me-1 -mt-0.5"}),t("orgSettings.criteria.defaultBanner","Using default criteria. Customize to edit or remove individual criteria for this gate.")]}),Ze&&e.jsx("button",{onClick:()=>Da.mutate(Tt),disabled:Da.isPending,className:"btn-primary text-xs px-3 py-1.5 whitespace-nowrap flex-shrink-0",children:Da.isPending?t("orgSettings.criteria.copying","Copying…"):t("orgSettings.criteria.customize","Customize")})]}),Mt.length===0?e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 italic py-3",children:t("orgSettings.criteria.emptyState","No criteria configured for this gate. Add criteria below.")}):e.jsx("div",{className:"space-y-2 mb-4",children:Mt.map(n=>{const v=n.fieldType||"SCORE",Y={SCORE:{label:_t(t,"SCORE"),cls:"bg-blue-100 dar
35k:bg-blue-900/30 text-blue-600 dark:text-blue-400"},RATING:{label:_t(t,"RATING"),cls:"bg-amber-100 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400"},YES_NO:{label:_t(t,"YES_NO"),cls:"bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400"},SCALE:{label:_t(t,"SCALE"),cls:"bg-violet-100 dark:bg-violet-900/30 text-violet-600 dark:text-violet-400"},DROPDOWN:{label:_t(t,"DROPDOWN"),cls:"bg-pink-100 dark:bg-pink-900/30 text-pink-600 dark:text-pink-400"},TEXT:{label:_t(t,"TEXT"),cls:"bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400"}}[v];return e.jsx("div",{className:"flex items-start justify-between px-3 py-2.5 bg-gray-50 dark:bg-gray-800/50 rounded-lg group",children:(de==null?void 0:de.id)===n.id?e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("input",{className:"input text-sm",value:de.name,onChange:K=>ze({...de,name:K.target.value}),placeholder:t("orgSettings.criteria.namePlaceholder","Criterion name")}),e.jsx("input",{className:"input text-sm",value:de.description??"",onChange:K=>ze({...de,description:K.target.value}),placeholder:t("orgSettings.criteria.descriptionPlaceholder","Description (optional)")}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-gray-500 dark:text-gray-400 mb-1 block",children:t("orgSettings.criteria.inputType","Input Type")}),e.jsx("div",{className:"grid grid-cols-6 gap-1",children:["SCORE","RATING","YES_NO","SCALE","DROPDOWN","TEXT"].map(K=>{const ce={SCORE:Qr,RATING:$t,YES_NO:mr,SCALE:gs,DROPDOWN:Ns,TEXT:xr}[K],Ct=(de.fieldType||"SCORE")===K;return e.jsxs("button",{type:"button",onClick:()=>ze({...de,fieldType:K,...K==="RATING"?{maxScore:5}:K==="SCALE"?{maxScore:5}:{}}),className:`flex flex-col items-center gap-0.5 px-1 py-1.5 rounded text-[10px] font-medium border transition-all ${Ct?"bg-indigo-50 dark:bg-indigo-900/30 border-indigo-300 dark:border-indigo-600 text-indigo-700 dark:text-indigo-300":"border-transparent text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700/50"}`,children:[e.jsx(ce,{className:"w-3.5 h-3.5"}),_t(t,K)]},K)})})]}),(de.fieldType||"SCORE")==="DROPDOWN"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-gray-500 dark:text-gray-400",children:t("orgSettings.criteria.optionsLabel","Options (Label=Score, comma-separated)")}),e.jsx("input",{className:"input text-sm",placeholder:t("orgSettings.criteria.optionsPlaceholder","Excellent=10, Good=7, Fair=4, Poor=1"),value:(de.options||[]).join(", "),onChange:K=>ze({...de,options:K.target.value.split(",").map(V=>V.trim()).filter(Boolean)})}),(de.options||[]).length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:(de.options||[]).map((K,V)=>{const ce=K.lastIndexOf("="),Ct=ce>0?K.slice(0,ce).trim():K,xe=ce>0?K.slice(ce+1).trim():"?";return e.jsxs("span",{className:"text-[10px] bg-pink-50 dark:bg-pink-900/20 text-pink-700 dark:text-pink-300 px-1.5 py-0.5 rounded-full",children:[Ct," ",e.jsxs("span",{className:"opacity-60",children:["= ",xe]})]},V)})})]}),e.jsxs("div",{className:"flex gap-2",children:[(de.fieldType||"SCORE")!=="TEXT"&&(de.fieldType||"SCORE")!=="RATING"&&(de.fieldType||"SCORE")!=="SCALE"&&(de.fieldType||"SCORE")!=="DROPDOWN"&&e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[10px] text-gray-500 dark:text-gray-400",children:t("orgSettings.criteria.maxScore","Max Score")}),e.jsx("input",{type:"number",min:1,max:100,className:"input text-sm",value:de.maxScore,onChange:K=>ze({...de,maxScore:parseInt(K.target.value)||10})})]}),(de.fieldType||"SCORE")!=="TEXT"&&e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[10px] text-gray-500 dark:text-gray-400",children:t("orgSettings.criteria.weight","Weight")}),e.jsx("input",{type:"number",min:0,step:.1,className:"input text-sm",value:de.weight,onChange:K=>ze({...de,weight:parseFloat(K.target.value)||1})})]})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx("button",{onClick:()=>Fa.mutate({id:de.id,data:{name:de.name,description:de.description,fieldType:de.fieldType||"SCORE",options:de.options||[],maxScore:de.maxScore,weight:de.weight}}),disabled:!de.name||Fa.isPending,className:"btn-primary text-xs px-3 py-1.5",children:Fa.isPending?t("orgSettings.saving","Saving…"):t("orgSettings.save","Save")}),e.jsx("button",{onClick:()=>ze(null),className:"btn-secondary text-xs px-3 py-1.5",children:t("common.cancel","Cancel")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-gray-800 dark:text-gray-200",children:n.name}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${Y.cls}`,children:Y.label}),v!=="TEXT"&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400 font-medium",children:["0–",v==="RATING"||v==="SCALE"?5:n.maxScore]}),v!=="TEXT"&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 font-medium",children:["×",n.weight]})]}),n.description&&e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:n.description}),v==="DROPDOWN"&&(n.options||[]).length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:(n.options||[]).map((K,V)=>{const ce=K.lastIndexOf("="),Ct=ce>0?K.slice(0,ce).trim():K,xe=ce>0?K.slice(ce+1).trim():"";return e.jsxs("span",{className:"text-[10px] bg-pink-50 dark:bg-pink-900/20 text-pink-700 dark:text-pink-300 px-1.5 py-0.5 rounded-full",children:[Ct,xe&&e.jsxs("span",{className:"opacity-60",children:[" = ",xe]})]},V)})})]}),Ze&&!la&&e.jsxs("div",{className:"flex items-center gap-1 opacity-100 can-hover:opacity-0 can-hover:group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>ze(n),className:"p-1.5 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 rounded text-gray-400 hover:text-indigo-500 transition-colors",title:t("orgSettings.criteria.editTooltip","Edit criteria"),children:e.jsx(Ps,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>{var K;if((K=n._count)!=null&&K.scores&&n._count.scores>0){k.error(t("orgSettings.criteria.deleteBlocked","Cannot delete criteria that has been used in reviews"));return}se({title:t("orgSettings.criteria.deleteConfirmTitle","Delete criteria"),message:t("orgSettings.criteria.deleteConfirmMessage",'Delete "{{name}}"?',{name:n.name}),confirmLabel:t("common.delete","Delete"),variant:"danger",onOk:()=>is.mutate(n.id)})},className:"p-1.5 hover:bg-red-50 dark:hover:bg-red-900/20 rounded text-gray-400 hover:text-red-500 transition-colors",title:t("orgSettings.criteria.deleteTooltip","Delete criteria"),children:e.jsx(dt,{className:"w-3.5 h-3.5"})})]})]})},n.id)})}),Ze&&e.jsx(e.Fragment,{children:Fs?e.jsxs("div",{className:"border border-dashed border-indigo-300 dark:border-indigo-700 rounded-lg p-4 space-y-3",children:[e.jsx("input",{className:"input text-sm",value:Ne.name,onChange:n=>it(v=>({...v,name:n.target.value})),placeholder:t("orgSettings.criteria.nameRequiredPlaceholder","Criterion name *"),autoFocus:!0}),e.jsx("input",{className:"input text-sm",value:Ne.description,onChange:n=>it(v=>({...v,description:n.target.value})),placeholder:t("orgSettings.criteria.descriptionPlaceholder","Description (optional)")}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-gray-500 dark:text-gray-400 mb-1 block",children:t("orgSettings.criteria.inputType","Input Type")}),e.jsx("div",{className:"grid grid-cols-6 gap-1",children:["SCORE","RATING","YES_NO","SCALE","DROPDOWN","TEXT"].map(n=>{const E={SCORE:Qr,RATING:$t,YES_NO:mr,SCALE:gs,DROPDOWN:Ns,TEXT:xr}[n],Y=Ne.fieldType===n;return e.jsxs("button",{type:"button",onClick:()=>it(K=>({...K,fieldType:n,...n==="RATING"?{maxScore:5}:n==="SCALE"?{maxScore:5}:n==="TEXT"?{weight:0}:{}})),className:`flex flex-col items-center gap-0.5 px-1 py-1.5 rounded text-[10px] font-medium border transition-all ${Y?"bg-indigo-50 dark:bg-indigo-900/30 border-indigo-300 dark:border-indigo-600 text-indigo-700 dark:text-indigo-300":"border-transparent text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700/50"}`,children:[e.jsx(E,{className:"w-3.5 h-3.5"}),_t(t,n)]},n)})})]}),Ne.fieldType==="DROPDOWN"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-gray-500 dark:text-gray-400 mb-1 block",children:t("orgSettings.criteria.optionsLabel","Options (Label=Score, comma-separated)")}),e.jsx("input",{className:"input text-sm",placeholder:t("orgSettings.criteria.optionsPlaceholder","Excellent=10, Good=7, Fair=4, Poor=1"),value:Ne.options,onChange:n=>it(v=>({...v,options:n.target.value}))}),Ne.options&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Ne.options.split(",").map(n=>
35n.trim()).filter(Boolean).map((n,v)=>{const E=n.lastIndexOf("="),Y=E>0?n.slice(0,E).trim():n,K=E>0?n.slice(E+1).trim():"?";return e.jsxs("span",{className:"text-[10px] bg-pink-50 dark:bg-pink-900/20 text-pink-700 dark:text-pink-300 px-1.5 py-0.5 rounded-full",children:[Y," ",e.jsxs("span",{className:"opacity-60",children:["= ",K]})]},v)})})]}),e.jsxs("div",{className:"flex gap-2",children:[Ne.fieldType!=="TEXT"&&Ne.fieldType!=="RATING"&&Ne.fieldType!=="SCALE"&&Ne.fieldType!=="DROPDOWN"&&e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[10px] text-gray-500 dark:text-gray-400",children:t("orgSettings.criteria.maxScore","Max Score")}),e.jsx("input",{type:"number",min:1,max:100,className:"input text-sm",value:Ne.maxScore,onChange:n=>it(v=>({...v,maxScore:parseInt(n.target.value)||10}))})]}),Ne.fieldType!=="TEXT"&&e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-[10px] text-gray-500 dark:text-gray-400",children:t("orgSettings.criteria.weight","Weight")}),e.jsx("input",{type:"number",min:0,step:.1,className:"input text-sm",value:Ne.weight,onChange:n=>it(v=>({...v,weight:parseFloat(n.target.value)||1}))})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>Yt.mutate({...Ne,gate:Tt,options:Ne.fieldType==="DROPDOWN"?Ne.options.split(",").map(n=>n.trim()).filter(Boolean):[]}),disabled:!Ne.name||Yt.isPending||Ne.fieldType==="DROPDOWN"&&!Ne.options.trim(),className:"btn-primary text-xs px-3 py-1.5",children:Yt.isPending?t("orgSettings.adding","Adding…"):t("orgSettings.criteria.addButton","Add Criteria")}),e.jsx("button",{onClick:()=>{Rt(!1),it({name:"",description:"",fieldType:"SCORE",options:"",maxScore:10,weight:1})},className:"btn-secondary text-xs px-3 py-1.5",children:t("common.cancel","Cancel")})]})]}):e.jsxs("button",{onClick:()=>Rt(!0),className:"flex items-center gap-1.5 text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 font-medium transition-colors",children:[e.jsx(st,{className:"w-3.5 h-3.5"}),t("orgSettings.criteria.addForGate","Add Criteria for {{gate}}",{gate:qt(t,Tt)})]})})]})]})]}):e.jsx("div",{className:"card p-6",children:e.jsx(lr,{feature:t("orgSettings.governance.featureLockName","Governance Settings"),plan:"Enterprise",onUpgradeClick:()=>M("billing")})})}),z==="configuration"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{ref:l.ref,style:l.style,className:"flex gap-1 border-b border-gray-200 dark:border-gray-700 max-md:overflow-x-auto max-md:[&>button]:shrink-0 max-md:[&>button]:whitespace-nowrap scrollbar-hide",children:[e.jsxs("button",{onClick:()=>Ke("custom-fields"),className:`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors flex items-center gap-1.5 ${Be==="custom-fields"?"border-indigo-500 text-indigo-600 dark:text-indigo-400":"border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"}`,children:[e.jsx(gs,{className:"w-3.5 h-3.5"}),t("orgSettings.config.subtab.customFields","Custom Fields")]}),e.jsxs("button",{onClick:()=>Ke("calendars"),className:`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors flex items-center gap-1.5 ${Be==="calendars"?"border-indigo-500 text-indigo-600 dark:text-indigo-400":"border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"}`,children:[e.jsx(Nr,{className:"w-3.5 h-3.5"}),t("orgSettings.config.subtab.calendars","Calendars")]}),e.jsxs("button",{onClick:()=>Ke("timesheets"),className:`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors flex items-center gap-1.5 ${Be==="timesheets"?"border-indigo-500 text-indigo-600 dark:text-indigo-400":"border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"}`,children:[e.jsx(Ya,{className:"w-3.5 h-3.5"}),t("orgSettings.config.subtab.timesheets","Timesheets")]}),e.jsxs("button",{onClick:()=>Ke("currency"),className:`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors flex items-center gap-1.5 ${Be==="currency"?"border-indigo-500 text-indigo-600 dark:text-indigo-400":"border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"}`,children:[e.jsx(es,{className:"w-3.5 h-3.5"}),t("orgSettings.config.subtab.currency","Currency")]})]}),Be==="custom-fields"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"card p-6",children:e.jsx(ld,{orgId:O,canEdit:qe})}),e.jsx("div",{className:"card p-6",children:e.jsx(gd,{})})]}),Be==="calendars"&&e.jsx(Md,{orgId:O,canEdit:qe}),Be==="timesheets"&&!me&&e.jsx(lr,{feature:t("orgSettings.timesheets.featureLockName","Timesheet Settings"),plan:"PRO",description:t("orgSettings.timesheets.featureLockDescription","Timesheet approvals and configuration require the PRO plan or above."),onUpgradeClick:()=>M("billing"),compact:!0}),Be==="timesheets"&&me&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"card p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ya,{className:"w-4 h-4 text-indigo-500"}),e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white text-sm",children:t("orgSettings.timesheets.approvalTitle","Timesheet Approval")})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 leading-relaxed",children:t("orgSettings.timesheets.approvalDescription","When enabled, team members must submit their timesheet entries for review before they are locked. Approvers can a
35pprove or reject individual entries or entire weeks. This setting is optional - leave it off to allow timesheets without a formal approval step.")})]}),e.jsx("button",{onClick:()=>{const n=!ot,v=()=>{os(n),ca.mutate({enabled:n,mode:Jt})};se(n?{title:t("orgSettings.timesheets.enableConfirmTitle","Enable timesheet approval?"),message:e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("p",{children:[t("orgSettings.timesheets.enableConfirmP1Prefix","Once enabled, only")," ",e.jsx("strong",{children:t("orgSettings.timesheets.statusApproved","APPROVED")})," ",t("orgSettings.timesheets.enableConfirmP1Suffix","timesheet entries count toward project Actual Cost on Finance dashboards and EVM reports.")]}),e.jsxs("p",{children:[t("orgSettings.timesheets.enableConfirmP2Prefix","Any entries currently in")," ",e.jsx("strong",{children:t("orgSettings.timesheets.statusSubmitted","SUBMITTED")})," ",t("orgSettings.timesheets.enableConfirmP2Suffix","state will stop counting until they are approved. To preserve historical project costs across this change, you can auto-promote all currently-submitted entries to approved.")]})]}),variant:"warning",confirmLabel:t("orgSettings.timesheets.enableConfirmLabel","Enable + auto-promote existing entries"),cancelLabel:t("common.cancel","Cancel"),onOk:async()=>{try{const E=await jo.promoteSubmittedToApproved();E.promoted>0&&k.success(t("orgSettings.timesheets.autoApproved",{count:E.promoted,defaultValue_one:"Auto-approved {{count}} previously-submitted entry.",defaultValue_other:"Auto-approved {{count}} previously-submitted entries."}))}catch(E){k.error(U(E,"auto-promote entries"))}v()}}:{title:t("orgSettings.timesheets.disableConfirmTitle","Disable timesheet approval?"),message:e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("p",{children:[t("orgSettings.timesheets.disableConfirmP1Prefix","Once disabled, every timesheet entry (including")," ",e.jsx("strong",{children:t("orgSettings.timesheets.statusDraft","DRAFT")}),t("orgSettings.timesheets.disableConfirmP1Suffix",") immediately counts toward project Actual Cost on Finance dashboards and EVM reports.")]}),e.jsx("p",{children:t("orgSettings.timesheets.disableConfirmP2","This may change historical AC / CPI numbers without notice. Re-enable approval before logging hours for a new period if you want to keep the review workflow.")})]}),variant:"warning",confirmLabel:t("orgSettings.timesheets.disableConfirmLabel","Disable"),cancelLabel:t("common.cancel","Cancel"),onOk:v})},disabled:ca.isPending,role:"switch","aria-checked":ot,"aria-label":t("orgSettings.timesheets.approvalToggleAria","Enable timesheet approval"),className:`relative flex-shrink-0 inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 ${ot?"bg-indigo-600":"bg-gray-200 dark:bg-gray-700"}`,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${ot?"translate-x-6 rtl:-translate-x-6":"translate-x-1 rtl:-translate-x-1"}`})})]}),ot&&e.jsxs("div",{className:"mt-5 pt-4 border-t border-gray-100 dark:border-gray-700 space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide",children:t("orgSettings.timesheets.whoCanApprove","Who can approve timesheets?")}),e.jsx("div",{className:"space-y-2",children:[{value:"managers",label:t("orgSettings.timesheets.modeManagersLabel","Organization admins"),desc:t("orgSettings.timesheets.modeManagersDesc","Owners, Admins, and Portfolio Managers can approve timesheets for anyone in the org.")},{value:"approvers",label:t("orgSettings.timesheets.modeApproversLabel","Custom approvers"),desc:t("orgSettings.timesheets.modeApproversDesc","Only designated timesheet approvers (configured below) can approve. Useful for a dedicated finance or ops team.")}].map(n=>e.jsxs("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${Jt===n.value?"border-indigo-400 dark:border-indigo-600 bg-indigo-50 dark:bg-indigo-900/20":"border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600"}`,children:[e.jsx("input",{type:"radio",name:"tsMode",value:n.value,checked:Jt===n.value,onChange:()=>
35{he(n.value),ca.mutate({enabled:!0,mode:n.value})},className:"mt-0.5 accent-indigo-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:n.label}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:n.desc})]})]},n.value))})]})]}),ot&&Jt==="approvers"&&e.jsxs("div",{className:"card p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold text-gray-900 dark:text-white text-sm",children:[t("orgSettings.timesheets.approversTitle","Timesheet Approvers"),Dt.length>0&&e.jsx("span",{className:"ms-2 px-1.5 py-0.5 rounded-full bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300 text-xs font-bold",children:Dt.length})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:t("orgSettings.timesheets.approversDescription","These members can approve or reject timesheet entries across the organization.")})]}),qe&&e.jsxs("button",{onClick:()=>da(n=>!n),className:"btn-secondary text-xs flex items-center gap-1",children:[e.jsx(st,{className:"w-3.5 h-3.5"}),t("orgSettings.timesheets.addApprover","Add approver")]})]}),Ds&&e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(ya,{options:Is.filter(n=>!n.user.isAgentPersona&&!ls.has(n.userId)).map(n=>({id:n.userId,label:n.user.name,sublabel:n.user.email})),selected:Ft?[Ft]:[],onChange:n=>La(n[0]||""),placeholder:t("orgSettings.timesheets.approverPickerPlaceholder","- select member -"),searchPlaceholder:t("orgSettings.timesheets.approverSearchPlaceholder","Search by name or email…"),multiple:!1,className:"flex-1"}),e.jsx("button",{onClick:()=>Ft&&Ia.mutate(Ft),disabled:!Ft||Ia.isPending,className:"btn-primary text-xs px-3",children:t("orgSettings.add","Add")}),e.jsx("button",{onClick:()=>da(!1),className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",children:e.jsx(ft,{className:"w-4 h-4"})})]}),Oa.isLoading?e.jsx("div",{className:"py-2 space-y-2",children:e.jsx(oe,{className:"h-6 rounded w-full",rows:2})}):Dt.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(Ba,{className:"w-8 h-8 text-gray-300 dark:text-gray-600 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500",children:t("orgSettings.timesheets.approversEmpty","No approvers configured yet.")}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:t("orgSettings.timesheets.approversEmptyHint","Add members above to grant them approval authority.")})]}):e.jsx("ul",{className:"space-y-2",children:Dt.map(n=>e.jsxs("li",{className:"flex items-center justify-between py-2 px-3 rounded-lg bg-gray-50 dark:bg-gray-800/50",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-indigo-100 dark:bg-indigo-900/40 flex items-center justify-center text-xs font-bold text-indigo-700 dark:text-indigo-300",children:n.user.name.charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:n.user.name}),e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:n.user.email})]}),n.orgMembership&&!n.orgMembership.isActive&&e.jsx(_s,{deactivatedAt:n.orgMembership.deactivatedAt})]}),qe&&e.jsx("button",{onClick:()=>se({title:t("orgSettings.timesheets.removeApproverTitle","Remove approver"),message:t("orgSettings.timesheets.removeApproverMessage","Remove {{name}} as a timesheet approver? They will no longer be able to approve or reject timesheets.",{name:n.user.name}),confirmLabel:t("orgSettings.remove","Remove"),variant:"danger",onOk:()=>m.mutate(n.userId)}),disabled:m.isPending,className:"p-1 text-gray-400 hover:text-red-500 dark:hover:text-red-400 transition-colors",title:t("orgSettings.timesheets.removeApproverTitle","Remove approver"),children:e.jsx(dt,{className:"w-3.5 h-3.5"})})]},n.id))})]}),!ot&&e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-xl bg-gray-50 dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700/50",children:[e.jsx(Gt,{className:"w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0"}),e.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 leading-relaxed",children:[t("orgSettings.timesheets.disabledInfoPrefix","Timesheet approval is currently")," ",e.jsx("strong",{children:t("orgSettings.timesheets.disabledWord","disabled")}),t("orgSettings.timesheets.disabledInfoSuffix",". Team members can log time freely and entries are not reviewed. Enable approval above to introduce a submit → approve → lock workflow for c
35ompliance or invoicing.")]})]}),e.jsx($l,{orgId:O}),e.jsx(id,{}),e.jsx(td,{}),e.jsx(Ql,{})]}),Be==="currency"&&e.jsx(Rd,{orgId:O,canEdit:qe})]}),z==="security"&&e.jsx(bl,{orgId:i.id,orgSlug:i.slug,hasScimToken:Ae==null?void 0:Ae.hasScimToken,isOwner:be,subTab:rt,onSubTabChange:wa}),ne]})}const Td=[1,2,3,4,5,6,0];function Rd({orgId:t,canEdit:a}){var z;const{t:s}=Q(),l=_e(),{data:i,isLoading:c}=ee({queryKey:["currency-config",t],queryFn:()=>B.getCurrencyConfig(t),staleTime:3e4}),[r,o]=g.useState("USD"),[x,d]=g.useState({}),[u,h]=g.useState(!1),[f,j]=g.useState(""),[b,y]=g.useState(!1);g.useEffect(()=>{var M;i&&(o(i.defaultCurrency||"USD"),d(((M=i.exchangeRates)==null?void 0:M.rates)??{}),y(!1))},[i]);const N=$({mutationFn:M=>B.saveCurrencyConfig(t,M),onSuccess:M=>{(M==null?void 0:M.ratesRecomputedFrom)==="frankfurter"?k.success(s("orgSettings.currency.savedRefreshed","Currency saved. Exchange rates refreshed from frankfurter.app for the new base currency.")):(M==null?void 0:M.ratesRecomputedFrom)==="cross-rate"?k.success(s("orgSettings.currency.savedCrossRate","Currency saved. Exchange rates recomputed from the previous table (frankfurter unreachable).")):k.success(s("orgSettings.currency.saved","Currency configuration saved")),l.invalidateQueries({queryKey:["currency-config",t]}),y(!1)},onError:M=>k.error(U(M,"save currency settings"))}),p=()=>{const M=Object.entries(x).filter(([J,ae])=>J!==r&&(!Number.isFinite(ae)||ae<=0)).map(([J])=>J);if(M.length>0){k.error(s("orgSettings.currency.invalidRates","Exchange rates must be greater than zero. Check: {{codes}}",{codes:M.join(", ")}));return}N.mutate({defaultCurrency:r,exchangeRates:{baseCurrency:r,rates:x,updatedAt:new Date().toISOString()}})},S=(M,J)=>{const ae=parseFloat(J);d(re=>({...re,[M]:isNaN(ae)?0:ae})),y(!0)},C=M=>{d(J=>{const ae={...J};return delete ae[M],ae}),y(!0)},G=()=>{f&&!x[f]&&f!==r&&(d(M=>({...M,[f]:1})),j(""),h(!1),y(!0))},R=Object.entries(x).filter(([M])=>M!==r),Z=vo.filter(M=>M!==r&&!x[M]),te=(z=i==null?void 0:i.exchangeRates)==null?void 0:z.updatedAt,A=te?Math.floor((Date.now()-new Date(te).getTime())/864e5):1/0,P=A>14;return c?e.jsxs("div",{className:"space-y-4",children:[e.jsx(oe,{className:"h-24 rounded",rows:1}),e.jsx(oe,{className:"h-40 rounded",rows:1})]}):e.jsxs("div",{className:"space-y-6",children:[P&&e.jsx("div",{className:"bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3 text-sm text-amber-800 dark:text-amber-200",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(je,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("strong",{children:Number.isFinite(A)?s("orgSettings.currency.staleDays",{count:A,defaultValue_one:"Exchange rates haven't been updated in {{count}} day.",defaultValue_other:"Exchange rates haven't been updated in {{count}} days."}):s("orgSettings.currency.staleNever","Exchange rates have never been set.")})," ",s("orgSettings.currency.staleHint","Multi-currency totals may be inaccurate. Rates auto-refresh daily; if that isn't working, update them manually below.")]})]})}),e.jsxs("div",{className:"card p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(es,{className:"w-4 h-4 text-indigo-500"}),e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white text-sm",children:s("orgSettings.currency.defaultTitle","Default Currency")})]}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-3 leading-relaxed",children:s("orgSettings.currency.defaultDescription","The base currency used across budgets, rate cards, and financial reports. Changing this will also update the exchange rate base currency.")}),e.jsx("select",{value:r,onChange:M=>{o(M.target.value),d(J=>{const ae={...J};return delete ae[M.target.value],ae}),y(!0)},disabled:!a,className:"input w-48",children:No(i==null?void 0:i.defaultCurrency).map(M=>{var J;return e.jsxs("option",{value:M,children:[M," (",((J=$s[M])==null?void 0:J.trim())||M,")"]},M)})})]}),e.jsxs("div",{className:"card p-5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-indigo-500"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white text-sm",children:s("orgSettings.currency.ratesTitle","Exchange Rates")}),e.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:[s("orgSettings.currency.ratesExpressedPrefix","Rates are expressed as")," ",e.jsx("span",{className:"font-medium",children:s("orgSettings.currency.ratesExpressedFormula","1 {{currency}} = N target-currency",{currency:r})}),"."]})]})]}),e.jsxs("span",{className:`text-[11px] px-2 py-0.5 rounded-full font-medium ${(i==null?void 0:i.source)==="org"?"bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300":(i==null?void 0:i.source)==="global"?"bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300":"bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400"}`,children:[(i==null?void 0:i.source)==="org"&&s("orgSettings.currency.sourceOrg","Org overrides"),(i==null?void 0:i.source)==="global"&&s("orgSettings.currency.sourceGlobal","Auto-refreshed daily"),(i==null?void 0:i.source)==="none"&&s("orgSettings.currency.sourceNone","No rates set")]})]}),te&&e.jsxs("p",{className:"text-[11px] text-gray-400 dark:text-gray-500 mb-3",children:[s("orgSettings.currency.lastUpdated","Last updated {{when}}",{when:Number.isFinite(A)&&A===0?s("orgSettings.currency.today","today"):Number.isFinite(A)&&A<7?s("orgSettings.currency.daysAgo","{{amount}}d ago",{amount:A}):new Date(te).toLocaleDateString()}),(i==null?void 0:i.source)==="global"&&s("orgSettings.currency.sourcedFrom"," · sourced from frankfurter.app (ECB)")]}),R.length===0?e.jsxs("div",{className:"text-center py-6 border border-dashed border-gray-200 dark:border-gray-700 rounded-lg",children:[e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 mb-2",children:(i==null?void 0:i.source)==="global"?s("orgSettings.currency.emptyGlobal","Using daily-refreshed global rates. Add an override below to pin a 
35specific rate."):s("orgSettings.currency.emptyNone","No exchange rates configured yet.")}),a&&!u&&Z.length>0&&e.jsx("button",{onClick:()=>h(!0),className:"btn-secondary text-xs px-3 py-1.5",children:s("orgSettings.currency.addOverride","+ Add currency override")})]}):e.jsx("div",{className:"space-y-2 mb-3",children:R.map(([M,J])=>{var ae;return e.jsxs("div",{className:"flex items-center gap-2 py-1.5",children:[e.jsxs("div",{className:"w-20 flex-shrink-0",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-200",children:M}),e.jsxs("span",{className:"text-xs text-gray-400 dark:text-gray-500 ms-1",children:["(",((ae=$s[M])==null?void 0:ae.trim())||M,")"]})]}),e.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500 flex-shrink-0",children:s("orgSettings.currency.rateRowPrefix","1 {{currency}} =",{currency:r})}),e.jsx("input",{type:"number",step:"0.0001",min:0,value:J,disabled:!a,onChange:re=>S(M,re.target.value),className:"input text-sm py-1 w-32"}),e.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:M}),a&&e.jsx("button",{type:"button",onClick:()=>C(M),className:"ms-auto text-gray-300 hover:text-red-500 dark:text-gray-600 dark:hover:text-red-400 p-1",title:s("orgSettings.currency.removeOverrideTooltip","Remove {{code}} override",{code:M}),children:e.jsx(ft,{className:"w-3.5 h-3.5"})})]},M)})}),a&&R.length>0&&!u&&Z.length>0&&e.jsx("button",{onClick:()=>h(!0),className:"text-xs text-indigo-600 dark:text-indigo-400 hover:underline mb-2",children:s("orgSettings.currency.addOverride","+ Add currency override")}),a&&u&&e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-gray-50 dark:bg-gray-800/40 rounded-lg",children:[e.jsxs("select",{value:f,onChange:M=>j(M.target.value),className:"input text-sm py-1 flex-1",children:[e.jsx("option",{value:"",children:s("orgSettings.currency.pickPlaceholder","Pick a currency…")}),Z.map(M=>{var J;return e.jsxs("option",{value:M,children:[M," (",((J=$s[M])==null?void 0:J.trim())||M,")"]},M)})]}),e.jsx("button",{onClick:G,disabled:!f,className:"btn-primary text-xs px-3 py-1 disabled:opacity-50",children:s("orgSettings.add","Add")}),e.jsx("button",{onClick:()=>{h(!1),j("")},className:"text-xs text-gray-400 hover:text-gray-600 px-2",children:s("common.cancel","Cancel")})]}),a&&(i==null?void 0:i.source)==="org"&&R.length>0&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-gray-100 dark:border-gray-700",children:[e.jsx("button",{type:"button",onClick:()=>{d({}),y(!0)},className:"text-xs text-gray-500 dark:text-gray-400 hover:text-red-600 dark:hover:text-red-400",children:s("orgSettings.currency.clearOverrides","↺ Clear org overrides & revert to global rates")}),e.jsx("p",{className:"text-[11px] text-gray-400 dark:text-gray-500 mt-1",children:s("orgSettings.currency.clearOverridesHint","On next save, your org will fall back to the daily-refreshed global rates from frankfurter.app.")})]})]}),a&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:p,disabled:!b||N.isPending,className:"btn-primary text-sm px-5",children:N.isPending?s("orgSettings.saving","Saving…"):s("orgSettings.currency.saveButton","Save Currency Settings")}),b&&e.jsx("span",{className:"text-xs text-amber-600 dark:text-amber-400",children:s("orgSettings.unsavedChanges","Unsaved changes")})]})]})}function Md({orgId:t,canEdit:a}){const{t:s}=Q(),l=_e(),{data:i=Za,isLoading:c}=ee({queryKey:["working-calendars",t],queryFn:Ut.list,staleTime:3e4}),[r,o]=g.useState(!1),[x,d]=g.useState(""),[u,h]=g.useState([...Xr]),[f,j]=g.useState(8),[b,y]=g.useState(!1),[N,p]=g.useState(null),[S,C]=g.useState(null),G=$({mutationFn:()=>Ut.create({name:x.trim(),workDays:u,hoursPerDay:f,isDefault:b}),onSuccess:()=>{k.success(s("orgSettings.calendars.created","Calendar created")),l.invalidateQueries({queryKey:["working-calendars",t]}),o(!1),d(""),h([...Xr]),j(8),y(!1)},onError:P=>k.error(U(P,"create calendar"))}),R=$({mutationFn:P=>Ut.update(P,{isDefault:!0}),onSuccess:()=>{k.success(s("orgSettings.calendars.defaultUpdated","Default calendar updated")),l.invali
35dateQueries({queryKey:["working-calendars",t]})},onError:P=>k.error(U(P,"set default calendar"))}),Z=$({mutationFn:P=>Ut.delete(P),onSuccess:()=>{k.success(s("orgSettings.calendars.deleted","Calendar deleted")),l.invalidateQueries({queryKey:["working-calendars",t]})},onError:P=>k.error(U(P,"delete calendar"))}),te=$({mutationFn:Ut.create,onSuccess:P=>{k.success(s("orgSettings.calendars.createdNamed",'"{{name}}" calendar created',{name:P.name})),l.invalidateQueries({queryKey:["working-calendars",t]})},onError:P=>k.error(U(P,"create calendar"))});function A(P){h(z=>z.includes(P)?z.filter(M=>M!==P):[...z,P])}return c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(oe,{className:"h-5 w-48 rounded"}),e.jsx(oe,{className:"h-8 w-32 rounded"})]}),e.jsx(oe,{className:"h-20 rounded-lg",rows:3})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 dark:text-white",children:s("orgSettings.calendars.title","Working Calendars")}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-0.5",children:s("orgSettings.calendars.description","Define working days, hours per day, and holiday exceptions for scheduling calculations.")})]}),a&&e.jsxs("button",{onClick:()=>o(P=>!P),className:"btn-primary flex items-center gap-1.5 text-sm",children:[e.jsx(st,{className:"w-4 h-4"})," ",s("orgSettings.calendars.newCalendar","New Calendar")]})]}),r&&a&&e.jsxs("div",{className:"card p-5 border border-indigo-200 dark:border-indigo-700 space-y-4",children:[e.jsx("h4",{className:"font-medium text-gray-900 dark:text-white text-sm",children:s("orgSettings.calendars.newFormTitle","New Working Calendar")}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:s("orgSettings.calendars.nameLabel","Name")}),e.jsx("input",{type:"text",value:x,onChange:P=>d(P.target.value),placeholder:s("orgSettings.calendars.namePlaceholder","e.g. Standard Mon–Fri, US Eastern"),className:"input w-full text-sm",maxLength:100})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2",children:s("orgSettings.calendars.workingDays","Working Days")}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Td.map(P=>e.jsx("button",{type:"button",onClick:()=>A(P),className:`px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${u.includes(P)?"bg-indigo-50 dark:bg-indigo-900/40 border-indigo-300 dark:border-indigo-600 text-indigo-700 dark:text-indigo-300":"border-gray-200 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-gray-300"}`,children:Qn[P]},P))})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:s("orgSettings.calendars.hoursPerDay","Hours / day")}),e.jsx("input",{type:"number",value:f,onChange:P=>j(Math.min(24,Math.max(1,Number(P.target.value)))),className:"input w-24 text-sm",min:1,max:24,step:.5})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 cursor-pointer mt-4",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:P=>y(P.target.checked),className:"rounded border-gray-300 text-indigo-500 focus:ring-indigo-400"}),s("orgSettings.calendars.setAsDefault","Set as default calendar")]})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx("button",{onClick:()=>G.mutate(),disabled:G.isPending||!x.trim()||u.length===0,className:"btn-primary text-sm",children:G.isPending?s("orgSettings.calendars.creating","Creating…"):s("orgSettings.calendars.createButton","Create Calendar")}),e.jsx("button",{onClick:()=>o(!1),className:"btn-secondary text-sm",children:s("common.cancel","Cancel")})]})]}),i.length===0?e.jsxs("div",{className:"card p-8 text-center space-y-4",children:[e.jsx(Nr,{className:"w-10 h-10 text-gray-300 dark:text-gray-600 mx-auto"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:s("orgSettings.calendars.emptyTitle","No calendars yet")}),e.jsxs("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:[s("orgSettings.calendars.emptyHintPrefix","Start with a template below, or click")," ",e.jsx("strong",{children:s("orgSettings.calendars.newCalendar","New Calendar")})," ",s("orgSettings.calendars.emptyHintSuffix","above to build a custom one.")]})]}),a&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3 max-w-lg mx-auto pt-1",children:[{emoji:"🏢",name:"Standard Mon–Fri",label:s("orgSettings.calendars.tplStandardLabel","Standard Mon–Fri"),sub:s("orgSettings.calendars.tplStandardSub","8 h/day · 5 days/week"),workDays:[1,2,3,4,5],hours:8},{emoji:"🗓️",name:"Mon–Sat",label:s("orgSettings.calendars.tplMonSatLabel","Mon–Sat"),sub:s("orgSettings.calendars.tplMonSatSub","8 h/day · 6 days/week"),workDays:[1,2,3,4,5,6],hours:8},{emoji:"⏰",name:"7-Day Week",label:s("orgSettings.calendars.tpl7DayLabel","7-Day Week"),sub:s("orgSettings.calendars.tpl7DaySub","8 h/day · all days"),workDays:[0,1,2,3,4,5,6],hours:8}].map(P=>e.jsxs("button",{onClick:()=>te.mutate({name:P.name,workDays:[...P.workDays],hoursPerDay:P.hours,isDefault:!0}),disabled:te.isPending,className:`flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-dashed
36                             border-gray-200 dark:border-gray-700 hover:border-indigo-300
37                             dark:hover:border-indigo-600 hover:bg-indigo-50/40 dark:hover:bg-indigo-900/10
38                             transition-all text-center group disabled:opacity-50`,children:[e.jsx("span",{className:"text-3xl",children:P.emoji}),e.jsx("span",{className:"text-xs font-semibold text-gray-700 dark:text-gray-300 group-hover:text-indigo-700 dark:group-hover:text-indigo-300",children:P.label}),e.jsx("span",{className:"text-[10px] text-gray-400 dark:text-gray-500",children:P.sub})]},P.name))}),e.jsx("p",{className:"text-[10px] text-gray-400 dark:text-gray-500",children:s("orgSettings.calendars.importHint","After creating a calendar you can import public holidays for your country.")})]}):e.jsx("div",{className:"space-y-3",children:i.map(P=>e.jsx(Fd,{calendar:P,canEdit:a,expanded:N===P.id,onToggle:()=>p(z=>z===P.id?null:P.id),onSetDefault:()=>R.mutate(P.id),onDelete:()=>C({id:P.id,name:P.name}),orgId:t},P.id))}),e.jsx(Mi,{open:!!S,title:s("orgSettings.calendars.deleteConfirmTitle",'Delete "{{name}}"?',{name:(S==null?void 0:S.name)??""}),message:s("orgSettings.calendars.deleteConfirmMessage","This calendar and all its settings will be permanently removed. This cannot be undone."),confirmLabel:s("common.delete","Delete"),variant:"danger",onConfirm:()=>{S&&Z.mutate(S.id),C(null)},onCancel:()=>C(null)})]})}function Fd({calendar:t,canEdit:a,expanded:s,onToggle:l,onSetDefault:i,onDelete:c,orgId:r}){const{t:o}=Q(),x=_e(),{showConfirm:d,ConfirmUI:u}=As(),[h,f]=g.useState(""),[j,b]=g.useState(!1),[y,N]=g.useState(""),[p,S]=g.useState(""),[C,G]=g.useState(!1),[R,Z]=g.useState(!1),[te,A]=g.useState("US"),[P,z]=g.useState(new Date().getFullYear()),[M,J]=g.useState(new Set),[ae,re]=g.useState(!1),H=g.useMemo(()=>new Set(t.exceptions.map(T=>T.date.slice(0,10))),[t.exceptions]),ge=g.useMemo(()=>{const T=Mn.find(ie=>ie.code===te);return T?T.generate(P):[]},[te,P]);g.useEffect(()=>{J(new Set(ge.filter(T=>!H.has(T.date)).map(T=>T.date)))},[ge]);async function _(){const T=ge.filter(ie=>M.has(ie.date));if(T.length){re(!0);try{await Promise.all(T.map(ie=>Ut.addException(t.id,{date:ie.date,isWorking:!1,name:ie.name}))),k.success(o("orgSettings.calendars.holidaysImported",{count:T.length,defaultValue_one:"Imported {{count}} holiday",defaultValue_other:"Imported {{count}} holidays"})),Z(!1)}catch(ie){k.error(U(ie,"import holidays"))}finally{re(!1),x.invalidateQueries({queryKey:["working-calendars",r]})}}}const se=$({mutationFn:()=>Ut.addException(t.id,{date:h,isWorking:j,name:y||void 0,hoursAvail:p?parseFloat(p):void 0}),onSuccess:()=>{k.success(o("orgSettings.calendars.exceptionSaved","Exception saved")),x.invalidateQueries({queryKey:["working-calendars",r]}),f(""),N(""),S(""),b(!1),G(!1)},onError:T=>k.error(U(T,"save exception"))}),ne=$({mutationFn:T=>Ut.deleteException(t.id,T),onSuccess:()=>{k.success(o("orgSettings.calendars.exceptionRemoved","Exception removed")),x.invalidateQueries({queryKey:["working-calendars",r]})},onError:T=>k.error(U(T,"remove exception"))}),Ye=[1,2,3,4,5,6,0].filter(T=>t.workDays.includes(T)).map(T=>Qn[T]).join(", ");return e.jsxs("div",{className:"card overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:l,className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors text-start",children:[e.jsx(Nr,{className:"w-4 h-4 text-indigo-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm text-gray-900 dark:text-white truncate",children:t.name}),t.isDefault&&e.jsxs("span",{className:"flex items-center gap-1 text-[10px] font-semibold bg-indigo-100 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-400 px-1.5 py-0.5 rounded-full",children:[e.jsx($t,{className:"w-2.5 h-2.5"})," ",o("orgSettings.calendars.defaultBadge","Default")]})]}),e.jsxs("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-0.5",children:[o("orgSettings.calendars.summaryHours","{{days}} · {{hours}}h/day",{days:Ye,hours:t.hoursPerDay}),t.exceptions.length>0&&` · ${o("orgSettings.calendars.exceptionCount",{count:t.exceptions.length,defaultValue_one:"{{count}} exception",defaultValue_other:"{{count}} exceptions"})}`,t._count.projects>0&&` · ${o("orgSettings.calendars.projectCount",{count:t._count.projects,defaultValue_one:"{{count}} project",defaultValue_other:"{{count}} projects"})}`]})]}),e.jsx(gt,{className:`w-4 h-4 text-gray-400 transition-transform flex-shrink-0 ${s?"rotate-180":""}`})]}),s&&e.jsxs("div",{className:"border-t border-gray-100 dark:border-gray-700 px-4 py-4 space-y-4",children:[a&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[!t.isDefault&&e.jsxs("button",{onClick:i,className:"btn-secondary text-xs flex items-center gap-1.5",children:[e.jsx($t,{className:"w-3.5 h-3.5"})," ",o("orgSettings.calendars.setDefaultButton","Set as Default")]}),e.jsxs("button",{onClick:()=>G(T=>!T),className:"btn-secondary text-xs flex items-center gap-1.5",children:[e.jsx(st,{className:"w-3.5 h-3.5"})," ",o("orgSettings.calendars.addException","Add Exception")]}),e.jsxs("button",{onClick:()=>Z(T=>!T),className:`text-xs flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border transition-colors ${R?"bg-indigo-50 dark:bg-indigo-900/30 border-indigo-300 dark:border-indigo-700 text-indigo-600 dark:text-indigo-400":"btn-secondary"}`,children:[e.jsx(gr,{className:"w-3.5 h-3.5"})," ",o("orgSettings.calendars.importHolidays","Import Holidays")]}),t._count.projects===0&&!t.isDefault&&e.jsxs("button",{onClick:c,className:"btn-danger text-xs flex items-center gap-1.5 ms-auto",children:[e.jsx(dt,{className:"w-3.5 h-3.5"})," ",o("common.delete","Delete")]})]}),R&&a&&e.jsxs("div",{className:"bg-indigo-50/60 dark:bg-indigo-900/10 rounded-lg p-4 space-y-3 border border-indigo-100 dark:border-indigo-800",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-semibold text-indigo-700 dark:text-indigo-400 flex items-center gap-1.5",children:[e.jsx(gr,{className:"w-3.5 h-3.5"})," ",o("orgSettings.calendars.importPanelTitle","Import Public Holidays")]}),e.jsx("button",{onClick:()=>Z(!1),className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",children:e.jsx(ft,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("select",{value:te,onChange:T=>A(T.target.value),className:"input flex-1 text-sm",children:Mn.map(T=>e.jsxs("option",{value:T.code,children:[T.flag," ",T.name]},T.code))}),e.jsx("select",{value:P,onChange:T=>z(Number(T.target.value)),className:"input w-24 text-sm",children:Cd.map(T=>e.jsx("option",{value:T,children:T},T))})]}),e.jsx("div",{className:"space-y-0.5 max-h-52 overflow-y-auto rounded-lg border border-indigo-100 dark:border-indigo-800 bg-white dark:bg-gray-800/60 px-2 py-1.5",children:ge.map(T=>{const ie=H.has(T.date),Le=ie||M.has(T.date),we=Us(T.date,{month:"short",day:"numeric"});return e.jsxs("label",{className:`flex items-center gap-2.5 px-1.5 py-1.5 rounded cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors ${ie?"opacity-50 cursor-default":""}`,children:[e.jsx("input",{type:"checkbox",checked:Le,disabled:ie,onChange:Ue=>J(Je=>{const Pe=new Set(Je);return Ue.target.checked?Pe.add(T.date):Pe.delete(T.date),Pe}),className:"rounded border-gray-300 text-indigo-500 focus:ring-indigo-400 flex-shrink-0"}),e.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 w-14 flex-shrink-0 font-mono",children:we}),e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 truncate",children:T.name}),ie&&e.jsx("span",{className:"text-[10px] text-indigo-400 dark:text-indigo-500 ms-auto flex-shrink-0",children:o("orgSettings.calendars.holidayAdded","added")})]},T.date)})}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:[o("orgSettings.calendars.selectedCount","{{selected}} of {{total}} selected",{selected:M.size,total:ge.length}),ge.filter(T=>H.has(T.date)).length>0&&e.jsxs("span",{className:"ms-1 text-indigo-400",children:["· ",o("orgSettings.calendars.alreadyAdded",{count:ge.filter(T=>H.has(T.date)).length,defaultValue_one:"{{count}} already added",defaultValue_other:"{{count}} already added"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>J(new Set(ge.filter(T=>!H.has(T.date)).map(T=>T.date))),className:"text-xs text-indigo-500 hover:text-indigo-700 dark:hover:text-indigo-300",children:o("orgSettings.calendars.selectAllNew","Select all new")}),e.jsx("button",{onClick:_,disabled:ae||M.size===0,className:"btn-primary text-xs px-3 py-1.5 disabled:opacity-50",children:ae?o("orgSettings.calendars.importing","Importing…"):o("orgSettings.calendars.importCount",{count:M.size,defaultValue_one:"Import {{count}} holiday",defaultValue_other:"Import {{count}} holidays"})})]})]})]}),C&&a&&e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800/60 rounded-lg p-4 space-y-3 border border-gray-100 dark:border-gray-700",children:[e.jsx("p",{className:"text-xs font-medium text-gray-700 dark:text-gray-300",children:o("orgSettings.calendars.exceptionFormTitle","Add Holiday / Exception")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-gray-500 dark:text-gray-400 mb-1",children:o("orgSettings.calendars.exceptionDate","Date")}),e.jsx("input",{type:"date",value:h,onChange:T=>f(T.target.value),className:"input w-full text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-gray-500 dark:text-gray-400 mb-1",children:o("orgSettings.calendars.exceptionName","Name (optional)")}),e.jsx("input",{type:"text",value:y,onChange:T=>N(T.target.value),placeholder:o("orgSettings.calendars.exceptionNamePlaceholder","e.g. Christmas Day"),className:"input w-full text-sm",maxLength:100})]})]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:T=>b(T.target.checked),className:"rounded border-gray-300 text-indigo-500 focus:ring-indigo-400"}),o("orgSettings.calendars.overrideAsWorking","Override as working day")]}),j&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs text-gray-500 dark:text-gray-400",children:o("orgSettings.calendars.hoursAvailable","Hours available")}),e.jsx("input",{type:"number",value:p,onChange:T=>S(T.target.value),className:"input w-20 text-sm",min:0,max:24,
38step:.5,placeholder:"8"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>se.mutate(),disabled:se.isPending||!h,className:"btn-primary text-xs",children:se.isPending?o("orgSettings.saving","Saving…"):o("orgSettings.calendars.saveException","Save Exception")}),e.jsx("button",{onClick:()=>G(!1),className:"btn-secondary text-xs",children:o("common.cancel","Cancel")})]})]}),t.exceptions.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400 mb-2",children:o("orgSettings.calendars.exceptionsListTitle","Exceptions / Holidays")}),e.jsx("div",{className:"space-y-1",children:t.exceptions.map(T=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50 group",children:[e.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${T.isWorking?"bg-green-500":"bg-red-400"}`}),e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 font-medium w-28 flex-shrink-0",children:Us(T.date)}),e.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400 flex-1",children:[T.isWorking?T.hoursAvail!=null?o("orgSettings.calendars.workingDayHours","Working day ({{hours}}h)",{hours:T.hoursAvail}):o("orgSettings.calendars.workingDay","Working day"):o("orgSettings.calendars.nonWorkingDay","Non-working day"),T.name?` · ${T.name}`:""]}),a&&e.jsx("button",{onClick:()=>d({title:o("orgSettings.calendars.removeExceptionTitle","Remove exception"),message:o("orgSettings.calendars.removeExceptionMessage","Remove {{what}} ({{date}}) from the calendar?",{what:T.name?`"${T.name}"`:o("orgSettings.calendars.thisException","this exception"),date:Us(T.date)}),confirmLabel:o("orgSettings.remove","Remove"),variant:"danger",onOk:()=>ne.mutate(T.id)}),disabled:ne.isPending,title:o("orgSettings.calendars.removeExceptionTitle","Remove exception"),className:"opacity-100 can-hover:opacity-0 can-hover:group-hover:opacity-100 transition-opacity p-1 text-gray-400 hover:text-red-500 rounded",children:e.jsx(ft,{className:"w-3.5 h-3.5"})})]},T.id))})]}):e.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500 italic",children:o("orgSettings.calendars.noExceptions","No exceptions defined yet.")})]}),u]})}export{ks as canSeeTab,oc 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.