1import{j as e,l as Pi,k as U,s as It}from"./index-BSaWd9L_.js";import{u as Ei,r as b,R as Di,L as Ti}from"./react-router-6IwkzgbN.js";import{b as se,a as Oe,c as Z,R as Fi,d as Oi,e as $i,r as _i}from"./AuthenticatedApp-CCl0jXQV.js";import{r as zi}from"./requestService-CwJDay6v.js";import{a as Qe,g as Ra}from"./attestationService-DLZAMVrE.js";import{c as Pa}from"./certificationService-YW5MFxvP.js";import{c as Mi,s as Bi}from"./certificationPdfService-DJAiP4Zh.js";import{u as qi}from"./AuthBoundRoutes-DjP5sABm.js";import{g as Ui,a as Ea,i as Vi,b as Wi}from"./remediationIssues-zRJoODeK.js";import{b as Q,a as Yi,e as Rs,f as we}from"./dateUtils-BXjtmOLV.js";import{p as Da}from"./DashboardService-B00txz3S.js";import{g as Gi,b as Hi}from"./workspaceService-D0JmegHK.js";import{f as Ta}from"./flowchartService-DcV4ooxC.js";import{storage as hs}from"./firebase-BNIkhQ9j.js";import{d as fs,r as gs}from"./firebase-storage-C6V6HrQd.js";import{T as Ki,M as vs,a as Xi,b as Ji}from"./testingWorkpaperLimits-Cv6Bos1-.js";import{d as js,e as Zi,f as Qi,g as er,r as et,P as tr,c as sr,a as ye,h as ar}from"./customRcmFields-D-YcERf4.js";import{b as ir,c as rr}from"./rcmColumns-DxItQESu.js";import{p as Fa}from"./policyService-CFFJO8E1.js";import{C as nr}from"./CreateRequestModal-CgNOEDUM.js";import{az as lr,L as ee,b2 as or,aB as dr,X as ae,ah as Oa,b3 as Ns,af as $e,S as tt,F as Rt,w as ys,G as Pt,aZ as Ps,b4 as cr,a9 as mr,aH as $a,_ as Va,d as ze,at as Ue,J as ws,ao as Et,b as Me,b5 as Dt,aJ as pr,b6 as Cs,as as _a,C as Ds,z as Wa,aA as za,Q as xr,a as Be,B as ur,T as br,g as hr,aG as Ss,aW as fr,an as Ya}from"./ui-icons-DPTVeI4b.js";import"./react-dom-CBCeEX-5.js";import"./ocr-BeklWGL7.js";import"./firebase-core-DWzFmatk.js";import"./tokenService-CnhF7_3j.js";import"./firebase-functions-Co__ct4K.js";import"./firebase-firestore--QWOY731.js";import"./firebase-auth-Ci-ASzqO.js";import"./index-tXXNEbmK.js";import"./samplingEngine-D1Bxb3J7.js";import"./jspdf.es.min-Cs0E-PbN.js";import"./browser-Bnn2ysp0.js";import"./planningService-DOpJY0JT.js";import"./requestSampling-B1sbup1v.js";import"./AppSelect-B0Fu5Flc.js";const st=(s,p)=>({id:p.id,number:p.number,title:p.title,componentId:s,pointsOfFocus:p.points.map((h,u)=>({id:`${p.id}-${String(u+1).padStart(2,"0")}`,label:typeof h=="string"?h:h.label,...typeof h=="string"?{}:{category:h.category}}))}),gr=[{id:"P01",number:1,title:"Demonstrates commitment to integrity and ethical values",points:["Sets the Tone at the Top","Establishes Standards of Conduct","Evaluates Adherence to Standards of Conduct","Addresses Deviations in a Timely Manner"]},{id:"P02",number:2,title:"Exercises oversight responsibility",points:["Establishes Oversight Responsibilities","Applies Relevant Expertise","Operates Independently","Provides Oversight for the System of Internal Control"]},{id:"P03",number:3,title:"Establishes structure, authority, and responsibility",points:["Considers All Structures of the Entity","Establishes Reporting Lines","Defines, Assigns, and Limits Authorities and Responsibilities"]},{id:"P04",number:4,title:"Demonstrates commitment to competence",points:["Establishes Policies and Practices","Evaluates Competence and Addresses Shortcomings","Attracts, Develops, and Retains Individuals","Plans and Prepares for Succession"]},{id:"P05",number:5,title:"Enforces accountability",points:["Enforces Accountability through Structures, Authorities, and Responsibilities","Establishes Performance Measures, Incentives, and Rewards","Evaluates Performance Measures, Incentives, and Rewards for Ongoing Relevance","Considers Excessive Pressures","Evaluates Performance and Rewards or Disciplines Individuals"]}],vr=[{id:"P06",number:6,title:"Specifies suitable objectives",points:[{category:"Operations Objectives",label:"Reflects Managementâs Choices"},{category:"Operations Objectives",label:"Considers Tolerances for Risk"},{category:"Operations Objectives",label:"Includes Operations and Financial Performance Goals"},{category:"Operations Objectives",label:"Forms a Basis for Committing of Resources"},{category:"External Financial Reporting",label:"Complies with Applicable Accounting Standards"}
1,{category:"External Financial Reporting",label:"Considers Materiality"},{category:"External Financial Reporting",label:"Reflects Entity Activities"},{category:"External Non-Financial Reporting",label:"Complies with Externally Established Standards and Frameworks"},{category:"External Non-Financial Reporting",label:"Considers the Required Level of Precision"},{category:"External Non-Financial Reporting",label:"Reflects Entity Activities"},{category:"Internal Reporting Objectives",label:"Reflects Managementâs Choices"},{category:"Internal Reporting Objectives",label:"Considers the Required Level of Precision"},{category:"Internal Reporting Objectives",label:"Reflects Entity Activities"},{category:"Compliance Objectives",label:"Reflects External Laws and Regulations"},{category:"Compliance Objectives",label:"Considers Tolerances for Risk"}]},{id:"P07",number:7,title:"Identifies and analyzes risk",points:["Includes Entity, Subsidiary, Division, Operating Unit, and Functional Levels","Analyzes Internal and External Factors","Involves Appropriate Levels of Management","Estimates Significance of Risks Identified","Determines How to Respond to Risks"]},{id:"P08",number:8,title:"Assesses fraud risk",points:["Considers Various Types of Fraud","Assesses Incentive and Pressures","Assesses Opportunities","Assesses Attitudes and Rationalizations"]},{id:"P09",number:9,title:"Identifies and analyzes significant change",points:["Assesses Changes in the External Environment","Assesses Changes in the Business Model","Assesses Changes in Leadership"]}],jr=[{id:"P10",number:10,title:"Selects and develops control activities",points:["Integrates with Risk Assessment","Considers Entity-Specific Factors","Determines Relevant Business Processes","Evaluates a Mix of Control Activity Types","Considers at What Level Activities Are Applied","Addresses Segregation of Duties"]},{id:"P11",number:11,title:"Selects and develops general controls over technology",points:["Determines Dependency between the Use of Technology in Business Processes and Technology General Controls","Establishes Relevant Technology Infrastructure Control Activities","Establishes Relevant Security Management Process Control Activities","Establishes Relevant Technology Acquisition, Development, and Maintenance Process Control Activities"]},{id:"P12",number:12,title:"Deploys control activities through policies and procedures",points:["Establishes Policies and Procedures to Support Deployment of Managementâs Directives","Establishes Responsibility and Accountability for Executing Policies and Procedures","Performs in a Timely Manner","Takes Corrective Action","Performs Using Competent Personnel","Reassesses Policies and Procedures"]}],Nr=[{id:"P13",number:13,title:"Uses relevant information",points:["Identifies Information Requirements","Captures Internal and External Sources of Data","Processes Relevant Data into Information","Maintains Quality throughout Processing","Considers Costs and Benefits"]},{id:"P14",number:14,title:"Communicates internally",points:["Communicates Internal Control Information","Communicates with the Board of Directors","Provides Separate Communication Lines","Selects Relevant Method of Communication"]},{id:"P15",number:15,title:"Communicates externally",points:["Communicates to External Parties","Enables Inbound Communications","Communicates with the Board of Directors","Provides Separate Communication Lines","Selects Relevant Method of Communication"]}],yr=[{id:"P16",number:16,title:"Conducts ongoing and/or separate evaluations",points:["Considers a Mix of Ongoing and Separate Evaluations","Considers Rate of Change","Establishes Baseline Understanding","Uses Knowledgeable Personnel","Integrates with Business Processes","Adjusts Scope and Frequency","Objectively Evaluates"]},{id:"P17",number:17,title:"Evaluates and communicates deficiencies",points:["Assesses Results","Communicates Deficiencies","Monitors Corrective Actions"]}],Se=[{id:"CE",label:"Control Environment",principles:gr.map(s=>st("CE",s))},{id:"RA",label:"Risk Assessment",principles:vr.map(s=>st("RA",s))},{id:"CA",label:"Control Activities",principles:jr.map(s=>st("CA",s))},{id:"IC",label:"Information & Communication",principles:Nr.map(s=>st("IC",s))},{id:"MA",label:"Monitoring Activities",principles:yr.map(s=>st("MA",s))}],wr={"Existing Control Activities":"Control Activities","Information and Communication":"Information & Communication",Monitoring:"Monitoring Activities"},Cr={CE:"Control Environment",RA:"Risk Assessment",CA:"Existing Control Activities",IC:"Information and Communication",MA:"Monitoring Activities"},Sr=s=>Cr[s],Es=s=>Se.find(p=>p.id===s),Ga=s=>{const p=wr[String(s||"").trim()]||String(s||"").trim();return Se.find(h=>h.label===p)},Ha=s=>Se.flatMap(p=>p.principles).find(p=>p.id===s),Ka=s=>Se.flatMap(p=>p.principles).flatMap(p=>p.pointsOfFocus).find(p=>p.id===s),Ce=s=>`Principle ${s.number} â ${s.title}`,qe=s=>s.category?`${s.category} â ${s.label}`:s.label,Ar=(s,p)=>{var w,g;if(!s)return"Never";const h=s,u=s,A=(h.fiscalYear||((w=u.inputs)==null?void 0:w.fiscalYear)||"").trim(),k=(s.testPhase||((g=u.input
1s)==null?void 0:g.testPhase)||"").trim();return[A,k].filter(Boolean).join(" ")||(s.createdAt?p(s.createdAt):"Previously tested")},kr=(s,p)=>s?p?"Ineffective":s.reviewStatus!=="COMPLETE"?"Effective - pending review":"Effective":"Not Tested",Tt=s=>!s||s.includes(` 2`)?s:s.replace(/ (\d+\.)/g,` 3$1`),_t=s=>{let p=s+1,h="";for(;p>0;)p-=1,h=String.fromCharCode(65+p%26)+h,p=Math.floor(p/26);return h},Lr=s=>{const p=[];return se(s||"").split(` 4`).forEach(h=>{const u=h.trim();if(!u)return;const A=u.match(/^(?:[-*â¢]\s*)?([A-Za-z]+|\d+)\s*[.):-]\s*(.*)$/);if(A){p.push({name:A[1].toUpperCase(),description:A[2].trim()});return}const k=p[p.length-1];k?k.description=`${k.description} 5${u}`.trim():p.push({name:_t(p.length),description:u})}),p},As=s=>s.map((p,h)=>{const u=p.name.trim().toUpperCase()||_t(h),A=p.description.replace(/\s*\n+\s*/g," ").trim();return A?`${u}. ${A}`:`${u}.`}).join(` 6`),te=s=>({...s,description:se(s.description),controlObjective:se(s.controlObjective),riskDescription:se(s.riskDescription),testingAttributes:se(s.testingAttributes),pbcRequests:s.pbcRequests===void 0?void 0:se(s.pbcRequests),pbcPopulationRequests:s.pbcPopulationRequests===void 0?void 0:se(s.pbcPopulationRequests),pbcSampleRequests:s.pbcSampleRequests===void 0?void 0:se(s.pbcSampleRequests),controlNarrative:s.controlNarrative===void 0?void 0:se(s.controlNarrative),controlActivity:s.controlActivity===void 0?void 0:se(s.controlActivity)}),Ir=new Set(["policy","cosoComponents","cosoPrinciples","cosoPointsOfFocus","lastTested","testingConclusion","lastAttested","attestationStatus","isActive","openIssues","pastIssues","updatedAt"]),Rr=ir().filter(s=>!Ir.has(s.id)),Ma=s=>{if(!s)return"-";const p=String(s).trim(),h=/^\d{4}-\d{2}-\d{2}$/.test(p)?new Date(`${p}T00:00:00`):new Date(p);return Number.isNaN(h.getTime())?p:Rs(p)},Pr=s=>!Number.isFinite(s)||s<=0?"â":s<1024*1024?`${Math.max(1,Math.round(s/1024))} KB`:`${(s/(1024*1024)).toFixed(s>=10*1024*1024?0:1)} MB`,Er=()=>`FY${String((new Date().getFullYear()-1)%100).padStart(2,"0")}`,ks=s=>s.trim().replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"file",at=(s,p)=>`${s}::${p}`,Ba=s=>{const p=Array.isArray(s.coso_component_ids)&&s.coso_component_ids.length?s.coso_component_ids:s.coso_component_id?[s.coso_component_id]:[],h=[...Array.isArray(s.coso_components)?s.coso_components:[],s.coso_component,...Array.isArray(s.cosoComponents)?s.cosoComponents:[],...Array.isArray(s.cosoElements)?s.cosoElements:[]].filter(Boolean),u=Array.from(new Map([...p.map(m=>Es(m)),...h.map(m=>Ga(m))].filter(m=>!!m).map(m=>[m.id,m])).values()),A=new Set(u.map(m=>m.id)),k=Array.isArray(s.coso_principle_ids)&&s.coso_principle_ids.length?s.coso_principle_ids:s.coso_principle_id?[s.coso_principle_id]:[],j=[...Array.isArray(s.coso_principles)?s.coso_principles:[],s.coso_principle].filter(Boolean).map(m=>String(m).trim().toLocaleLowerCase()),w=Se.flatMap(m=>m.principles),g=Array.from(new Map([...k.map(m=>Ha(m)),...w.filter(m=>j.includes(m.title.toLocaleLowerCase())||j.includes(Ce(m).toLocaleLowerCase()))].filter(m=>!!(m&&A.has(m.componentId))).map(m=>[m.id,m])).values());new Set(g.map(m=>m.id));const N=g.flatMap(m=>m.pointsOfFocus),P=new Set(N.map(m=>m.id)),F=Array.isArray(s.coso_point_of_focus_ids)?s.coso_point_of_focus_ids:[],C=Array.isArray(s.coso_points_of_focus)?s.coso_points_of_focus.map(m=>String(m).trim().toLocaleLowerCase()):[],D=Array.from(new Map([...F.map(m=>Ka(m)),...N.filter(m=>C.includes(m.label.toLocaleLowerCase())||C.includes(qe(m).toLocaleLowerCase()))].filter(m=>!!(m&&P.has(m.id))).map(m=>[m.id,m])).values());return{components:u,principles:g,pointsOfFocus:D}},Ft=s=>s.replace(/([A-Z])/g," $1").replace(/^./,p=>p.toUpperCase()),Ot=(s,p,h=!1)=>{const u=p==="owner"?s.owners:s.preparers,k=((p==="owner"?s.owner:s.preparer)||"").split(",").map(N=>N.trim()).filter(Boolean),j=(u||[]).map(N=>(N.name||"").trim()).filter(Boolean),w=k.length>0&&k.join("|").toLocaleLowerCase()!==j.join("|").toLocaleLowerCase();return(!(u!=null&&u.length)||w?k.map((N,P)=>{var C;const F=u==null?void 0:u.find(D=>(D.name||"").trim().toLocaleLowerCase()===N.toLocaleLowerCase());return{name:N,email:(F==null?void 0:F.email)||((C=u==null?void 0:u[P])==null?void 0:C.email)||""}}):u).map(N=>({name:h?N.name||"":(N.name||"").trim(),email:h?N.email||"":(N.email||"").trim()})).filter(N=>h||N.name||N.email)},$t=s=>s.map(p=>
6(p.name||p.email||"").trim()).filter(Boolean).join(", "),Ls=()=>{if(typeof window>"u")return[];try{const s=JSON.parse(localStorage.getItem("controlLibraryCols")||"[]");return Array.isArray(s)?s.reduce((p,h)=>{const u=typeof h=="object"&&h!==null&&"customRcmField"in h?h.customRcmField:void 0,A=typeof u=="string"?u.trim():"";return A&&!p.some(k=>k.toLocaleLowerCase()===A.toLocaleLowerCase())&&p.push(A),p},[]):[]}catch{return[]}},Dr=s=>{if(typeof window>"u")return!1;try{const p=JSON.parse(localStorage.getItem("controlLibraryCols")||"[]");if(!Array.isArray(p))return!1;const h=p.filter(u=>{const A=typeof u=="object"&&u!==null&&"customRcmField"in u?u.customRcmField:void 0;return typeof A!="string"||A.trim().toLocaleLowerCase()!==s.trim().toLocaleLowerCase()});return h.length===p.length?!1:(localStorage.setItem("controlLibraryCols",JSON.stringify(h)),window.dispatchEvent(new Event("iabuddy:control-columns-updated")),!0)}catch{return!1}},qa=s=>{if(typeof window>"u"||!s.trim())return!1;try{const p=JSON.parse(localStorage.getItem("controlLibraryCols")||"[]");if(!Array.isArray(p)||p.some(w=>{const g=typeof w=="object"&&w!==null&&"customRcmField"in w?w.customRcmField:void 0;return typeof g=="string"&&g.trim().toLocaleLowerCase()===s.trim().toLocaleLowerCase()}))return!1;const h=`customRcm:${s.trim().toLocaleLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"field"}`,u=new Set(p.map(w=>typeof w=="object"&&w!==null&&"id"in w?w.id:void 0));let A=h,k=2;for(;u.has(A);)A=`${h}-${k}`,k+=1;const j=[...p,{id:A,label:s.trim(),customRcmField:s.trim(),width:180,minWidth:120,visible:!0}];return localStorage.setItem("controlLibraryCols",JSON.stringify(j)),window.dispatchEvent(new Event("iabuddy:control-columns-updated")),!0}catch{return!1}},Tr=(s,p)=>{if(typeof window>"u")return!1;try{const h=JSON.parse(localStorage.getItem("controlLibraryCols")||"[]");if(!Array.isArray(h))return!1;const u=s.trim().toLocaleLowerCase(),A=p.trim();if(h.some(g=>{const N=typeof g=="object"&&g!==null&&"customRcmField"in g?g.customRcmField:void 0;return typeof N=="string"&&N.trim().toLocaleLowerCase()!==u&&N.trim().toLocaleLowerCase()===A.toLocaleLowerCase()}))return!1;let j=!1;const w=h.map(g=>{const N=typeof g=="object"&&g!==null&&"customRcmField"in g?g.customRcmField:void 0;return typeof N!="string"||N.trim().toLocaleLowerCase()!==u?g:(j=!0,{...g,label:A,customRcmField:A})});return j?(localStorage.setItem("controlLibraryCols",JSON.stringify(w)),window.dispatchEvent(new Event("iabuddy:control-columns-updated")),!0):!1}catch{return!1}},Is=({ariaLabel:s,options:p,selectedIds:h,onChange:u,placeholder:A,disabledPlaceholder:k,searchPlaceholder:j="Search options...",disabled:w=!1})=>{const[g,N]=b.useState(!1),[P,F]=b.useState(""),C=b.useRef(null);b.useEffect(()=>{const v=T=>{C.current&&!C.current.contains(T.target)&&N(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),b.useEffect(()=>{w&&(N(!1),F(""))},[w]);const D=p.filter(v=>h.includes(v.id)),m=p.filter(v=>`${v.label} ${v.group||""}`.toLocaleLowerCase().includes(P.trim().toLocaleLowerCase())),L=v=>u(h.includes(v)?h.filter(T=>T!==v):[...h,v]);return e.jsxs("div",{ref:C,className:"relative space-y-2",children:[D.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:D.map(v=>e.jsxs("span",{className:"inline-flex max-w-full items-center gap-1.5 rounded-full border border-brand-200 bg-brand-50 px-2.5 py-1 text-[11px] font-semibold text-brand-800",children:[e.jsx("span",{className:"whitespace-normal break-words",children:v.label}),e.jsx("button",{type:"button","aria-label":`Remove ${v.label}`,onClick:()=>L(v.id),className:"shrink-0 rounded-full p-0.5 text-brand-600 transition hover:bg-brand-100 hover:text-brand-900",children:e.jsx(ae,{size:12})})]},v.id))}),e.jsxs("button",{type:"button",disabled:w,"aria-label":s,"aria-haspopup":"listbox","aria-expanded":g,onClick:()=>N(v=>!v),className:"flex min-h-11 w-full items-center justify-between rounded-xl border border-brand-200 bg-white px-3.5 py-2.5 text-left text-sm font-medium text-slate-700 shadow-sm outline-none transition hover:border-brand-300 hover:bg-brand-50/30 focus:border-brand-500 focus:ring-2 focus:ring-brand-100 disabled:cursor-not-allowed disabled:border-slate-200 disabled:bg-slate-50 disabled:text-slate-400 disabled:shadow-none",children:[e.jsx("span",{className:D.length?"text-slate-800":"text-slate-400",children:w?k:D.length?`${D.length} selected`:A}),e.jsx(Ds,{size:16,className:`shrink-0 text-brand-500 transition ${g?"rotate-180":""}`})]}),g&&!w&&e.jsxs("div",{role:"listbox","aria-label":`${s} options`,className:"absolute left-0 z-50 mt-1 w-full min-w-[280px] overflow-hidden rounded-xl border border-brand-100 bg-white shadow-xl ring-1 ring-slate-900/5",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-brand-100 bg-brand-50/40 px-3 py-2",children:[e.jsx("span",{className:"text-[10px] font-black uppercase tracking-widest text-brand-700",children:"Select one or more"}),D.length>0&&e.jsx("button",{type:"button",onClick:()=>u([]),className:"text-xs font-bold text-brand-700 hover:text-brand-900",children:"Clear all"})]}),e.jsxs("div",{className:"relative border-b border-slate-100 p-2",children:[e.jsx(Va,{size:15,className:"pointer-events-none absolute left-5 top-1/2 -translate-y-1/2 text-brand-400"}
6),e.jsx("input",{autoFocus:!0,type:"search",value:P,onChange:v=>F(v.target.value),placeholder:j,className:"w-full rounded-lg border border-slate-200 bg-slate-50 py-2 pl-9 pr-3 text-sm text-slate-700 outline-none placeholder:text-slate-400 focus:border-brand-400 focus:bg-white focus:ring-2 focus:ring-brand-100"})]}),e.jsx("div",{className:"max-h-72 overflow-y-auto py-1",children:m.length?m.map(v=>{const T=h.includes(v.id);return e.jsxs("label",{className:`flex cursor-pointer items-start gap-2.5 px-3 py-2.5 text-sm transition ${T?"bg-brand-50/70":"hover:bg-slate-50"}`,children:[e.jsx("input",{type:"checkbox",checked:T,onChange:()=>L(v.id),className:"mt-0.5 h-4 w-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[v.group&&e.jsx("span",{className:"mb-0.5 block text-[10px] font-bold uppercase tracking-wide text-brand-600/70",children:v.group}),e.jsx("span",{className:"font-medium text-slate-700",children:v.label})]}),T&&e.jsx(Be,{size:15,className:"mt-0.5 shrink-0 text-brand-600"})]},v.id)}):e.jsx("p",{className:"px-3 py-4 text-sm text-slate-500",children:"No matching options."})})]})]})},jn=({control:s,availableRisks:p=[],logs:h,workspaceId:u,onClose:A,onUseInTest:k,onUpdateControl:j,onControlRefreshed:w,onOpenPaywall:g,planTier:N,onNavigateToBilling:P,issues:F=[],userRole:C="Owner"})=>{var Ca,Sa,Aa,ka,La,Ia;const D=Ei(),[m,L]=b.useState(!1),[v,T]=b.useState(!1),[n,S]=b.useState(()=>te(s)),[Ae,ne]=b.useState(Ls),[ke,be]=b.useState({}),[Ve,We]=b.useState(!1),[x,it]=b.useState(null),[he,zt]=b.useState([]),[Ja,Ts]=b.useState([]),[Fs,Os]=b.useState(Er),[$s,_s]=b.useState(""),[fe,zs]=b.useState(!1),[Za,Mt]=b.useState({}),[ce,ge]=b.useState(null),[rt,Ms]=b.useState(!1),[Bt,qt]=b.useState([]),[Qa,nt]=b.useState(!1),[H,Ut]=b.useState([]),[ve,Bs]=b.useState([]),[K,qs]=b.useState(null),[Vt,Wt]=b.useState([]),[Us,Yt]=b.useState({}),[lt,Vs]=b.useState(!1),[ot,Gt]=b.useState(null),[dt,ei]=b.useState(null),[X,Ht]=b.useState("details"),[ct,Kt]=b.useState({open:!1,runId:null,displayName:""}),[Xt,Ws]=b.useState(!1),[Le,mt]=b.useState(!1),[Ie,Ys]=b.useState(()=>({frequency:{reviewed:!1,isAccurate:!0,suggestedValue:"",comments:""},owner:{reviewed:!1,isAccurate:!0,suggestedValue:"",comments:""},preparer:{reviewed:!1,isAccurate:!0,suggestedValue:"",comments:""},description:{reviewed:!1,isAccurate:!0,suggestedValue:"",comments:""},controlActivity:{reviewed:!1,isAccurate:!0,suggestedValue:"",comments:""},testingAttributes:{reviewed:!1,isAccurate:!0,suggestedValue:"",comments:""}})),[pt,Gs]=b.useState(""),[Jt,Hs]=b.useState(!1),[ti,Ks]=b.useState(null),[xt,Xs]=b.useState(null),[ut,Js]=b.useState([]),[le,bt]=b.useState(null),[Zt,je]=b.useState(null),[me,Ye]=b.useState(null),[Qt,ht]=b.useState(null),[es,ts]=b.useState([]),[Zs,Qs]=b.useState(!1),[pe,Re]=b.useState(""),[ea,Ge]=b.useState(!1),[ss,xe]=b.useState(!1),[as,He]=b.useState(""),[is,Ke]=b.useState(""),[rs,ta]=b.useState(!1),{currentUser:I}=qi(),[ft,sa]=b.useState([]),[aa,ns]=b.useState([]),ia=b.useRef(null),Ne=(t,a="info")=>je({message:t,tone:a}),ra=b.useMemo(()=>Ui(F,[s]),[F,s]),J=Oe(C,"testingMemoUI"),na=u||s.workspaceId,Xe=b.useMemo(()=>[...s.priorYearTestFiles||[]].sort((t,a)=>String(a.uploadedAt||"").localeCompare(String(t.uploadedAt||""))),[s.priorYearTestFiles]),si=b.useMemo(()=>Xe.reduce((t,a)=>{var c,o;const i=((c=a.fiscalYear)==null?void 0:c.trim())||"Unspecified fiscal year",r=((o=a.phase)==null?void 0:o.trim())||"Unspecified phase";return t[i]||(t[i]={}),t[i][r]||(t[i][r]=[]),t[i][r].push(a),t},{}),[Xe]),ai=b.useMemo(()=>Array.from(new Set(["Walkthrough","Interim","Year-End","Rollforward","Remediation",...he.map(t=>{var a;return t.testPhase||((a=t.inputs)==null?void 0:a.testPhase)||""}),...Xe.map(t=>t.phase||"")].map(t=>t.trim()).filter(Boolean))).sort((t,a)=>t.localeCompare(a)),[Xe,he]),Pe=Oe(C,"attestationUI"),ls=b.useMemo(()=>ra.filter(t=>Ea(t,s)&&Vi(t)),[ra,s]),la=b.useMemo(()=>F.filter(t=>Ea(t,s)&&Wi(t)),[F,s]),os=b.useMemo(()=>{const t=new Map(h.map(a=>[a.id,a]));return dt==null||dt.forEach(a=>t.set(a.id,a)),Array.from(t.values()).sort((a,i)=>String(i.timestamp||"").localeCompare(String(a.timestamp||"")))},[h,dt]),ii=b.useMemo(()=>{const t=[...H.flatMap(({campaign:o,request:d})=>{var de,W;if(d.status!=="COMPLETED")return[];const l=(de=d.responses)==null?void 0:de.find(_=>_.controlDocId===s.id),f=(l==null?void 0:l.respondedAt)||d.signedAt||d.updatedAt;if(!f)return[];const y=(W=d.controlSnapshots)==null?void 0:W.find(_=>_.controlDocId===s.id),M=_=>({frequency:y==null?void 0:y.frequency,owner:y==null?void 0:y.owner,description:y==null?void 0:y.description})[_]||"Value at attestation not retained",$={id:`legacy-attestation-${d.id}-${s.id}`,controlId:s.id,action:"ATTESTATION",performedBy:d.signedByName||d.ownerName||"Control owner",timestamp:f,details:`Legacy control attestation completed â ${o.name} (${o.period})`},re=((l==null?void 0:l.fieldResponses)||[]).filter(_=>!_.isAccurate&&_.reviewStatus==="ACCEPTED"&&_.suggestedValue).map(_=>({id:`legacy-attestation-suggestion-${d.id}-${s.id}-${_.field}`,controlId:s.id,action:"UPDATE",performedBy:d.signedByName||d.ownerName||"Control owner",timestamp:_.reviewedAt||d.updatedAt||f,details:`Legacy attestation suggestion applied for ${_.field}`,changes:[{field:_.field,oldValue:M(_.field),newValue:_.suggestedValue}]}));return[$,...re]}),...ve.flatMap(({campaign:o,request:d})=>{var l;return!d.signedAt||!((l=d.controlSnapshots)!=null&&l.some(f=>f.controlId===s.controlId))?[]:[{id:`certification-${d.id}-${s.id}`,controlId:s.id,action:"CERTIFICATION",performedBy:d.signedByName||d.signerName||"Certification signer",timestamp:d.signedAt,details:`${d.status==="SIGNED_WITH_EXCEPTIONS"?"SOX certification signed with exceptions":"SOX certification signed"} â ${o.name} (${o.period})`}]})],a=os.filter(o=>o.controlId===s.id),i=ut.filter(o=>o.controlId===s.id).flatMap(o=>{const d={id:`rcm-suggestion-submitted-${o.id}`,controlId:s.id,action:"SUGGESTION",performedBy:o.submittedByName||"Process/Control Owner",actorId:o.submittedBy,timestamp:o.submittedAt,details:Zi(o.fieldLabel),changes:[js(o)]};return o.status==="WITHDRAWN"&&o.withdrawnAt?[d,{id:`rcm-suggestion-withdrawn-${o.id}`,controlId:s.id,action:"SUGGESTION",performedBy:o.withdrawnByName||"Process/Control Owner",actorId:o.withdrawnBy,timestamp:o.withdrawnAt,details:Qi(o.fieldLabel),changes:[js(o)]}]:!o.reviewedAt||o.status!=="APPLIED"&&o.status!=="DISCARDED"?[d]:[d,{id:`rcm-suggestion-reviewed-${o.id}`,controlId:s.id,action:"SUGGESTION",performedBy:o.reviewedByName||"Workspace admin",actorId:o.reviewedBy,timestamp:o.reviewedAt,details:er(o.fieldLabel,o.status),changes:[js(o)]}]}),r=t.filter(o=>!a.some(d=>{var l,f,y,M,$;return d.timestamp===o.timestamp&&(o.action==="ATTESTATION"&&((l=d.details)==null?void 0:l.startsWith("Attestation submitted"))||o.action==="CERTIFICATION"&&((f=d.details)==null?void 0:f.startsWith("SOX certification signed"))||((y=o.details)==null?void 0:y.startsWith("Legacy attestation suggestion applied"))&&(((M=d.details)==null?void 0:M.startsWith("Legacy attestation suggestion applied"))||(($=d.details)==null?void 0:$.startsWith("Attestation suggestion accepted"))))})),c=i.filter(o=>!a.some(d=>d.action==="SUGGESTION"&&d.details===o.details&&d.timestamp===o.timestamp));return[...os,...r,...c].sort((o,d)=>String(d.timestamp||"").localeCompare(String(o.timestamp||"")))},[ve,s.id,s.controlId,H,os,ut]),ie=Oe(C,"controlLibraryUI"),gt=String(C||"").trim().toLocaleLowerCase()==="process/control owner",vt=String(C||"").trim().toLocaleLowerCase()==="process/control owner",oa=Oe(C,"testingUI"),ds=Oe(C,"requestUI")&&C!=="Process/Control Owner"&&!!(u&&I),da=ie&&Oe(C,"attestationUI"),ca=["owner","admin"].includes(String(C||"").trim().toLocaleLowerCase()),Ee=b.useMemo(()=>ft.filter(t=>{const a=t.linkedControlIds||[];
6return a.includes(s.id)||a.includes(s.controlId)}),[ft,s.id,s.controlId]);b.useEffect(()=>{m||ns(Ee.map(t=>t.id))},[m,Ee]),b.useEffect(()=>{const t=u||s.workspaceId,a=(I==null?void 0:I.uid)||"";if(!t||!a){sa([]);return}return Fa.subscribeAccessiblePolicies(t,a,sa,i=>console.info("Linked policies unavailable",i))},[s.workspaceId,I==null?void 0:I.uid,u]);const cs=b.useMemo(()=>ut.filter(t=>t.status==="PENDING"&&t.controlId===s.id).sort((t,a)=>a.submittedAt.localeCompare(t.submittedAt)),[s.id,ut]);b.useEffect(()=>{const t=u||s.workspaceId;if(!t){Js([]);return}return et.subscribe(t,Js)},[s.workspaceId,u]);const ma=async(t,a)=>{if(!ca||le||t.length===0)return;const i=`${a}:${t.map(r=>r.id).join(",")}`;bt(i),je(null);try{if(a==="APPLIED"){const c=await Z.getControlById(s.id);if(!c)throw new Error("The control is no longer available.");const o=t.filter(l=>ye(c,l)!==l.originalValue);if(o.length>0){const l=o.map(f=>f.fieldLabel).join(", ");throw new Error(`The live value changed for ${l} after these suggestions were submitted. Review the latest values before applying them.`)}const d=te({...c,...ar(c,t),updatedAt:new Date().toISOString()});await j(d),S(d),w==null||w(d)}await et.markReviewed(t.map(c=>c.id),a);const r=t.map(c=>c.fieldLabel).join(" and ");a==="DISCARDED"&&Ne(`${r} suggestions declined.`)}catch(r){console.error("Unable to review RCM suggestion from control detail",r),Ne(r instanceof Error?r.message:"Unable to review this suggestion.","error")}finally{bt(null)}},ri=async(t,a)=>{if(!vt||le||t.length===0)return;const i=t.map(r=>r.id);bt(`withdraw:${i.join(",")}`),je(null);try{await et.withdrawPendingSuggestions(i),Ne(`${a} suggestions canceled. The published control is unchanged.`)}catch(r){console.error("Unable to cancel RCM suggestion from control detail",r),Ne(r instanceof Error?r.message:"Unable to cancel this suggestion.","error")}finally{bt(null)}},ni=b.useMemo(()=>ve.flatMap(({campaign:t,request:a})=>(a.controlSuggestions||[]).map((i,r)=>({campaign:t,request:a,suggestion:i,suggestionIndex:r}))).filter(({suggestion:t})=>t.controlId===s.controlId&&(!t.reviewStatus||t.reviewStatus==="PENDING")).sort((t,a)=>String(a.request.signedAt||"").localeCompare(String(t.request.signedAt||""))),[ve,s.controlId]);b.useEffect(()=>()=>{K!=null&&K.url&&URL.revokeObjectURL(K.url)},[K==null?void 0:K.url]);const ms=async(t,a)=>{try{const i=await Mi(t,a),r=URL.createObjectURL(i);qs(c=>(c!=null&&c.url&&URL.revokeObjectURL(c.url),{url:r,filename:Bi(t,a)}))}catch(i){console.error("Unable to generate signed certification PDF",i),alert("Unable to generate the signed certification PDF. Please try again.")}};b.useEffect(()=>{const t=()=>ne(Ls());return t(),window.addEventListener("storage",t),window.addEventListener("iabuddy:control-columns-updated",t),()=>{window.removeEventListener("storage",t),window.removeEventListener("iabuddy:control-columns-updated",t)}},[]),b.useEffect(()=>{if(localStorage.getItem("controlLibraryCols")!==null)return;let t=!1;const a=r=>{t||ne(sr(r))},i=u||s.workspaceId;return i?(Z.getControls(i).then(a).catch(()=>a([s])),()=>{t=!0}):(a([s]),()=>{t=!0})},[s,u]),b.useEffect(()=>{if(X!=="logs")return;let t=!1;return Z.getLogs({controlId:s.id}).then(a=>{t||ei(a)}),()=>{t=!0}},[X,s.id]);const jt=b.useMemo(()=>{const t=n.customRcmData||{},a=Object.keys(t);return Ae.map(r=>{const c=a.find(o=>o.toLocaleLowerCase()===r.toLocaleLowerCase());return[r,c&&t[c]||""]})},[Ae,n.customRcmData]),ps=b.useMemo(()=>H.find(t=>{var i;return t.request.ownerUserId!==(I==null?void 0:I.uid)||t.request.status==="COMPLETED"?!1:!((i=t.request.responses)==null?void 0:i.some(r=>r.controlDocId===s.id))&&(t.request.status==="PENDING"||t.request.status==="OVERDUE")}),[H,I==null?void 0:I.uid,s.id]),Je=b.useMemo(()=>H.find(t=>{var i;if(t.request.status!=="COMPLETED")return!1;const a=(i=t.request.responses)==null?void 0:i.find(r=>r.controlDocId===s.id);return a!=null&&a.fieldResponses?a.fieldResponses.some(r=>!r.isAccurate&&r.reviewStatus==="PENDING"):!1}),[H,s.id]),Ze=[{field:"frequency",label:"Frequency"},{field:"owner",label:"Owner"},{field:"preparer",label:"Preparer"},{field:"description",label:"Control Description"},{field:"controlActivity",label:"Control Activity"},{field:"testingAttributes",label:"Attributes to Test"}],li=t=>{switch(t){case"frequency":return s.frequency||"";case"owner":return s.owner||"";case"preparer":return s.preparer||"";case"description":return s.description||"";case"controlActivity":return s.controlActivity||"";case"testingAttributes":return s.testingAttributes||"";default:return""}},xs=Object.values(Ie).filter(t=>t.reviewed).length,Nt=xs===Ze.length,pa=(t,a)=>{Pe&&Ys(i=>({...i,[t]:{...i[t],reviewed:!0,isAccurate:a,suggestedValue:a?"":i[t].suggestedValue}}))},oi=async()=>
6{if(!(!Pe||!ps||!Nt||!pt.trim()||Jt)){Hs(!0);try{const t=Ze.map(({field:i})=>({field:i,isAccurate:Ie[i].isAccurate,suggestedValue:Ie[i].suggestedValue,comments:Ie[i].comments,reviewStatus:Ie[i].isAccurate?"ACCEPTED":"PENDING",reviewedBy:null,reviewedAt:null})),a=[{controlId:s.controlId||s.id,controlDocId:s.id,fieldResponses:t,isAccurate:t.every(i=>i.isAccurate),comments:"",respondedAt:new Date().toISOString()}];if(await Qe.submitAttestation(ps.request.id,a,pt.trim()),u){const i=await Qe.getRequestsByControlId(u,s.id);Ut(i)}mt(!1),Gs("")}catch(t){console.error("Attestation submit failed:",t),alert("Failed to submit attestation: "+t.message)}finally{Hs(!1)}}},xa=async(t,a,i,r)=>{Ks(i);try{if(await Qe.reviewSuggestion(t,a,i,r),u){const c=await Qe.getRequestsByControlId(u,s.id);Ut(c)}if(r==="ACCEPT"){const c=await Z.getControlById(s.id);c&&(w?w(c):S(c))}}catch(c){console.error("Review suggestion failed:",c),alert("Failed: "+c.message)}finally{Ks(null)}},ua=async(t,a,i)=>{if(!da||xt)return;const r=`${t.id}-${a}`;Xs(r);try{if(await Pa.reviewControlSuggestion({requestId:t.id,suggestionIndex:a,controlDocId:s.id,action:i}),i==="APPLY"){const c=await Z.getControlById(s.id);c&&(S(c),w==null||w(c))}}catch(c){console.error("Certification suggestion review failed:",c),alert(c.message||"Unable to review this certification suggestion.")}finally{Xs(null)}},z=t=>{const a=ni.filter(({suggestion:i})=>i.field===t);return a.length===0?null:e.jsx("div",{className:"mt-2 space-y-2","aria-label":`Pending certification suggestions for ${Ft(t)}`,children:a.map(({campaign:i,request:r,suggestion:c,suggestionIndex:o})=>{const d=`${r.id}-${o}`,l=xt===d,f=r.signedByName||r.signerName||"Signer";return e.jsx("article",{className:`rounded-md border border-amber-200 bg-amber-50/80 px-2.5 py-2 ${l?"opacity-60":""}`,children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[10px] font-black uppercase tracking-wide text-amber-700",children:["Suggested by ",f]}),e.jsx("p",{className:"mt-0.5 whitespace-pre-wrap break-words text-xs font-medium leading-5 text-amber-950",children:c.suggestedValue||e.jsx("span",{className:"italic text-amber-700",children:"Clear this value"})}),e.jsxs("p",{className:"mt-1 text-[10px] font-semibold text-amber-700",children:[i.period," · awaiting review"]})]}),da&&e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsxs("button",{type:"button",onClick:()=>ua(r,o,"DISCARD"),disabled:l||!!xt,className:"inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] font-bold text-slate-600 transition hover:bg-white hover:text-slate-800 disabled:cursor-not-allowed disabled:opacity-50",title:"Discard suggested value","aria-label":`Discard suggested ${Ft(t)}`,children:[e.jsx(Ss,{size:13})," Discard"]}),e.jsxs("button",{type:"button",onClick:()=>ua(r,o,"APPLY"),disabled:l||!!xt,className:"inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] font-bold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-50",title:"Apply suggested value","aria-label":`Apply suggested ${Ft(t)}`,children:[l?e.jsx(ee,{size:13,className:"animate-spin"}):e.jsx(Be,{size:13}),"Apply"]})]})]})},d)})})},R=(t,a)=>{const i=Array.isArray(t)?t:[t],r=cs.filter(l=>i.includes(l.field)||a&&l.field.startsWith("custom:")&&l.fieldLabel.trim().toLocaleLowerCase()===a.trim().toLocaleLowerCase());if(r.length===0)return null;const c=i.includes("owner")&&i.includes("ownerEmail")?{role:"owner",label:"Control owner",nameField:"owner",emailField:"ownerEmail"}:i.includes("preparer")&&i.includes("preparerEmail")?{role:"preparer",label:"Preparer",nameField:"preparer",emailField:"preparerEmail"}:null,o=(l,f)=>{var _,V;if(!ca)return null;const y=l.map(ue=>ue.id).join(","),M=le===`DISCARDED:${y}`,$=le===`APPLIED:${y}`,de=l.length>1&&!!f?"both":(_=l[0])==null?void 0:_.fieldLabel,W=f||((V=l[0])==null?void 0:V.fieldLabel)||"suggested fields";return e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1 border-t border-amber-200/80 pt-2",children:[e.jsxs("button",{type:"button",onClick:()=>void ma(l,"DISCARDED"),disabled:!!le,className:"inline-flex min-h-8 items-center gap-1 rounded px-2 py-1 text-[10px] font-bold text-slate-600 transition hover:bg-white hover:text-slate-800 focus:outline-none focus:ring-2 focus:ring-amber-500 disabled:cursor-not-allowed disabled:opacity-50",title:`Decline suggested ${W}`,"aria-label":`Decline suggested ${W}`,children:[M?e.jsx(ee,{size:13,className:"animate-spin"}):e.jsx(Ss,{size:13}),"Decline ",de]}),e.jsxs("button",{type:"button",onClick:()=>void ma(l,"APPLIED"),disabled:!!le,className:"inline-flex min-h-8 items-center gap-1 rounded px-2 py-1 text-[10px] font-bold text-emerald-700 transition hover:bg-emerald-100 focus:outline-none focus:ring-2 focus:ring-emerald-500 disabled:cursor-not-allowed disabled:opacity-50",title:`Apply suggested ${W}`,"aria-label":`Apply suggested ${W}`,children:[$?e.jsx(ee,{size:13,className:"animate-spin"}):e.jsx(Be,{size:13}),"Apply ",de]})]})},d=(l,f)=>vt&&e.jsx("button",{type:"button",onClick:()=>void ri(l,f),disabled:!!le,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-amber-700 transition hover:bg-amber-100 hover:text-amber-900 focus:outline-none focus:ring-2 focus:ring-amber-500 disabled:cursor-not-allowed disabled:opacity-50",title:`Cancel pending ${f.toLocaleLowerCase()} suggestion`,"aria-label":`Cancel pending ${f.toLocaleLowerCase()} suggestion`,children:String(le||"").startsWith("withdraw:")?e.jsx(ee,{size:14,className:"animate-spin"}):e.jsx(ae,{size:15})});return e.jsx("div",{className:"mt-2 space-y-2",role:"group","aria-label":`Pending RCM suggestions for ${r.map(l=>l.fieldLabel).join(", ")}`,children:c?(()=>{const l=r.find(V=>V.field===c.nameField),f=r.find(V=>
6V.field===c.emailField),y=[l,f].filter(Boolean),M=ye(s,{field:c.nameField,fieldLabel:c.label}),$=ye(s,{field:c.emailField,fieldLabel:`${c.label} Email`}),re=(l==null?void 0:l.suggestedValue)??M,de=(f==null?void 0:f.suggestedValue)??$,W=y.reduce((V,ue)=>Date.parse(ue.editedAt||ue.submittedAt)>Date.parse(V.editedAt||V.submittedAt)?ue:V),_=(V,ue)=>e.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-2 text-amber-950",children:[e.jsx("span",{className:"truncate text-xs font-semibold",title:V,children:V||e.jsx("span",{className:"italic text-slate-400",children:"None"})}),e.jsx("span",{className:"truncate text-xs font-medium",title:ue,children:ue||e.jsx("span",{className:"italic text-slate-400",children:"No email on file"})})]});return e.jsxs("article",{className:"rounded-lg border border-amber-300 bg-amber-50/80 p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-wide text-amber-800",children:c.label}),d(y,c.label)]}),e.jsx("div",{className:"mt-2 rounded-md border border-amber-200 bg-white/55 px-2 py-2",children:_(re,de)}),e.jsx("div",{className:"mt-2 border-t border-amber-200 pt-2",children:e.jsx("p",{className:"text-[10px] font-semibold text-amber-800",children:W.editedAt?`Revised by ${W.editedByName||"Process/Control Owner"} · ${we(W.editedAt)}`:`Suggested by ${W.submittedByName||"Process/Control Owner"} · ${we(W.submittedAt)}`})}),o(y,`${c.role} name and email`)]},`${c.role}-suggestion`)})():r.map(l=>{const f=le===l.id,y=l.fieldLabel;return e.jsxs("article",{className:`rounded-lg border border-amber-300 bg-amber-50/80 p-3 ${f?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-wide text-amber-800",children:y}),d([l],l.fieldLabel)]}),e.jsx("div",{className:"mt-2 rounded-md border border-amber-200 bg-white/55 px-2 py-2",children:e.jsx("p",{className:"whitespace-pre-wrap break-words text-xs font-medium leading-5 text-amber-950",children:l.suggestedValue||e.jsx("span",{className:"italic text-amber-700",children:"Clear this value"})})}),e.jsx("div",{className:"mt-2 border-t border-amber-200 pt-2",children:e.jsxs("p",{className:"text-[10px] font-semibold text-amber-800",children:["Suggested by ",l.submittedByName," · ",we(l.submittedAt),l.editedAt&&e.jsxs(e.Fragment,{children:[" · Revised by ",l.editedByName||"Process/Control Owner"," · ",we(l.editedAt)]})]})}),o([l])]},l.id)})})},yt=t=>Array.isArray(t)?t.length>0:typeof t=="string"?t.trim().length>0:t!=null&&t!=="",di=t=>{const a=["controlObjective","testingAttributes","controlNarrative","controlActivity","pbcSampleRequests"],i=["assertions","classification","type","nature","process","subProcess","entity","relatedITSystems","keyReport","cosoComponents"],r=[...a.filter(c=>!yt(t[c])),...i];return!yt(t.riskId)&&!yt(t.riskDescription)&&r.unshift("riskId","riskDescription"),t.frequency==="As-Needed"&&!yt(t.pbcPopulationRequests)&&r.push("pbcPopulationRequests"),Array.from(new Set(r))},ci=(t,a)=>{const i=new Set(a);return Object.fromEntries(Object.entries(t).filter(([r])=>i.has(r)))};b.useEffect(()=>{S(te(s)),L(!1),T(!1),it(null),Re(""),Ge(!1),xe(!1),He(""),Ke(""),be({}),s.id&&(zt([]),Ts([]),gt?Z.getControlTestRuns(s.id,{metadataOnly:!0}).then(Ts).catch(t=>console.warn("Failed to fetch testing summary (likely plan restriction):",t)):Z.getControlTestRuns(s.id).then(zt).catch(t=>console.warn("Failed to fetch test history (likely plan restriction):",t)))},[s.id,gt]),b.useEffect(()=>{let t=!1;if(!u){ts([]);return}return Qs(!0),Gi(u).then(a=>a?Hi(a.members):[]).then(a=>{t||ts(a.filter(i=>!!i.email))}).catch(a=>{console.warn("Failed to load workspace members for control contacts:",a),t||ts([])}).finally(()=>{t||Qs(!1)}),()=>{t=!0}},[u]),b.useEffect(()=>{if(!u||!s.id){qt([]);return}return Qe.getRequestsByControlId(u,s.id).then(Ut).catch(t=>console.warn("Failed to load control attestations:",t)),zi.subscribeToRequests(u,t=>{const a=i=>{var r,c;return i.controlId===s.id||i.controlId===s.controlId||((r=i.additionalControlIds)==null?void 0:r.includes(s.id
6))||((c=i.additionalControlIds)==null?void 0:c.includes(s.controlId))};qt(t.filter(a))},t=>{console.warn("Failed to load linked requests:",t),qt([])})},[u,s.id,s.controlId]),b.useEffect(()=>{if(!u||!s.controlId){Bs([]);return}return Pa.subscribeToControlHistory(u,s.controlId,Bs)},[u,s.controlId]),b.useEffect(()=>{if(X!=="flowcharts")return;let t=!1;if(!u||!s.id){Wt([]),Yt({}),Gt(null);return}return Vs(!0),Gt(null),Ta.getFlowchartsForControl(u,{id:s.id,controlId:s.controlId}).then(async a=>{const i=await Promise.all(a.map(async r=>{const o=(await Ta.getValidations(r.id,u)).filter(d=>d.status==="approved"&&d.signedAt).map(d=>d.signedAt).sort((d,l)=>new Date(l).getTime()-new Date(d).getTime())[0];return[r.id,o]}));t||(Wt(a),Yt(Object.fromEntries(i.filter(r=>!!r[1]))))}).catch(a=>{console.warn("Failed to load linked flowcharts:",a),t||(Wt([]),Yt({}),Gt("Unable to load linked flowcharts. Please try again."))}).finally(()=>{t||Vs(!1)}),()=>{t=!0}},[X,u,s.id,s.controlId]);const[wt,Ct]=b.useState(!1),mi=async()=>{if(!vt||wt)return;const t=u||s.workspaceId;if(!t){Ne("Choose a workspace before submitting control suggestions.","error");return}const a=te(s),i=te(n),r=[...Rr,...Object.keys(a.customRcmData||{}).map(d=>({id:rr(d),label:d}))].flatMap(d=>{const l={field:d.id,fieldLabel:d.label},f=ye(a,l),y=ye(i,l);return f===y?[]:[{...l,originalValue:f,suggestedValue:y}]});if(r.length===0){Ne("No changes to submit. Update one or more fields first.");return}const c=r.flatMap(d=>{const l=cs.find(f=>f.field===d.field);return l?[{candidate:d,pendingSuggestion:l}]:[]}),o=r.filter(d=>!cs.some(l=>l.field===d.field));Ct(!0),je(null);try{const d=await Z.getControlById(s.id);if(!d)throw new Error("This control is no longer available.");const l=te(d),f=r.filter($=>ye(l,$)!==$.originalValue).map($=>$.fieldLabel);if(f.length>0)throw new Error(`The live control changed for ${f.join(", ")}. Refresh the page and review the latest values before suggesting edits.`);const y=c.map(({candidate:$,pendingSuggestion:re})=>({candidate:$,pendingSuggestion:re,latestValue:ye(l,$)})),M=y.filter(({candidate:$,latestValue:re})=>$.suggestedValue===re).map(({candidate:$})=>$.fieldLabel);if(M.length>0)throw new Error(`The latest value already matches the proposed change for ${M.join(", ")}. Refresh the control and review the pending suggestion before revising it.`);await Promise.all([...y.map(({candidate:$,pendingSuggestion:re,latestValue:de})=>et.revisePendingSuggestion(re.id,{originalValue:de,suggestedValue:$.suggestedValue})),...o.map($=>et.submit({workspaceId:t,controlId:s.id,controlReference:d.controlId||s.controlId,...$}))]),S(l),L(!1),T(!1)}
6catch(d){console.error("Unable to submit control detail RCM suggestions",d),Ne(d instanceof Error?d.message:"Unable to submit these suggestions. Please try again.","error")}finally{Ct(!1)}},pi=async()=>{if(v){await mi();return}if(!ie)return;if(Object.values(ke).some(f=>f.trim().length===0)){await U({title:"Custom field name required",message:"Enter a name for each custom field or remove the blank field before saving.",confirmLabel:"Done",variant:"warning",hideCancel:!0});return}const a=Ba(n),i=Array.isArray(n.coso_principle_ids)&&n.coso_principle_ids.length?n.coso_principle_ids.filter(Boolean):n.coso_principle_id?[n.coso_principle_id]:[],r=Array.isArray(n.coso_principles)&&n.coso_principles.length?n.coso_principles.filter(Boolean):n.coso_principle?[n.coso_principle]:[],c=i.length||r.length,o=Array.isArray(n.coso_point_of_focus_ids)?n.coso_point_of_focus_ids.filter(Boolean):[],d=Array.isArray(n.coso_points_of_focus)?n.coso_points_of_focus.filter(Boolean):[],l=o.length||d.length;if(c>0&&a.principles.length!==c||l>0&&a.pointsOfFocus.length!==l){await U({title:"Review COSO mapping",message:"The selected COSO Principle or Point of Focus does not belong to the current COSO Component. Choose a valid hierarchy before saving.",confirmLabel:"Done",variant:"warning",hideCancel:!0});return}Ct(!0);try{const f=Ot(n,"owner"),y=Ot(n,"preparer");await j(te({...n,owners:f,preparers:y,owner:$t(f),preparer:$t(y),updatedAt:new Date().toISOString()})),I!=null&&I.uid&&await Fa.setControlPolicyLinks(ft,{id:s.id,controlId:n.controlId||s.controlId},aa,I.uid),L(!1)}catch(f){console.error("Save failed in component",f)}finally{Ct(!1)}},xi=async t=>{const a=Array.from(t.target.files||[]);if(t.target.value="",!J||a.length===0)return;if(!na){await U({title:"Workspace required",message:"Choose a workspace before uploading archived testing files.",confirmLabel:"Done",variant:"warning",hideCancel:!0});return}const i=Fs.trim();if(!i){await U({title:"Fiscal year required",message:"Enter the fiscal year for these archived testing files.",confirmLabel:"Done",variant:"warning",hideCancel:!0});return}const r=$s.trim();if(!r){await U({title:"Test phase required",message:"Enter the prior-year test phase for these archived testing files.",confirmLabel:"Done",variant:"warning",hideCancel:!0});return}if((s.priorYearTestFiles||[]).filter(l=>(l.fiscalYear||"").trim().toLocaleLowerCase()===i.toLocaleLowerCase()&&(l.phase||"").trim().toLocaleLowerCase()===r.toLocaleLowerCase()).length+a.length>vs){await U({title:"Archive file limit reached",message:`Each prior-year phase can contain up to ${vs} files, matching testing workpapers. Remove a file or upload fewer files to ${i} ${r}.`,confirmLabel:"Done",variant:"warning",hideCancel:!0});return}const o=a.find(l=>l.size>Xi);if(o){await U({title:"File exceeds testing workpaper limit",message:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:o.name})," is larger than the ",Ji," per-file limit used for testing workpapers and archive files."]}),confirmLabel:"Done",variant:"warning",hideCancel:!0});return}zs(!0);const d=[];try{for(const l of a){const f=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,y=["workspaces",na,"controls",s.id,"prior-year-test-archive",ks(i),ks(r),`${f}_${ks(l.name)}`].join("/"),M=await Z.uploadWorkpaper(l,y,{controlId:s.id,fiscalYear:i,phase:r,uploadedBy:(I==null?void 0:I.uid)||"unknown",archive:"prior-year-testing"});d.push({id:f,fileName:l.name,fileUrl:M,storagePath:y,fiscalYear:i,phase:r,fileSize:l.size,...l.type?{contentType:l.type}:{},uploadedAt:new Date().toISOString(),uploadedBy:(I==null?void 0:I.displayName)||(I==null?void 0:I.email)||"Current Auditor"})}await j({...s,priorYearTestFiles:[...s.priorYearTestFiles||[],...d],updatedAt:new Date().toISOString()}),await It(d.length===1?"Archived testing file uploaded":"Archived testing files uploaded",`${d.length} file${d.length===1?"":"s"} added to the ${i} ${r} archive.`)}catch(l){console.error("Failed to upload prior-year testing files:",l),await Promise.all(d.map(f=>fs(gs(hs,f.storagePath)).catch(()=>{}))),await U({title:"Unable to upload archived files",message:"The archived testing files could not be uploaded. Please try again.",confirmLabel:"Done",variant:"warning",hideCancel:!0})}finally{zs(!1)}},ui=async t=>{if(!(!J||!await U({title:"Remove archived testing file?",message:e.jsxs(e.Fragment,{children:["This permanently removes ",e.jsx("span",{className:"font-semibold",children:t.fileName})," from the prior-year archive."]}),confirmLabel:"Remove file",variant:"danger"})))try{t.storagePath&&await fs(gs(hs,t.storagePath)),await j({...s,priorYearTestFiles:(s.priorYearTestFiles||[]).filter(i=>i.id!==t.id),updatedAt:new Date().toISOString()}),await It("Archived testing file removed",`${t.fileName} was removed from the prior-year archive.`)}catch(i){console.error("Failed to remove prior-year testing file:",i),await U({title:"Unable to remove archived file",message:"The archived testing file could not be removed. Please try again.",confirmLabel:"Done",variant:"warning",hideCancel:!0})}},bi=(t,a)=>{const i=at(t,a);Mt(r=>({...r,[i]:!r[i]}))},hi=(t,a)=>{!J||fe||(Os(t),_s(a==="Unspecified phase"?"":a),window.requestAnimationFrame(()=>{var i;return(i=ia.current)==null?void 0:i.click()}))},ba=async()=>
6{if(!ce||!J)return;const{fiscalYear:t,phase:a}=ce,i=ce.value.trim();if(!i){await U({title:"Phase name required",message:"Enter a name for this prior-year archive phase.",confirmLabel:"Done",variant:"warning",hideCancel:!0});return}const r=i.localeCompare(a,void 0,{sensitivity:"accent"})===0,c=(s.priorYearTestFiles||[]).some(d=>(d.fiscalYear||"").trim().toLocaleLowerCase()===t.toLocaleLowerCase()&&(d.phase||"Unspecified phase").trim().toLocaleLowerCase()===i.toLocaleLowerCase()&&(d.phase||"Unspecified phase").trim().toLocaleLowerCase()!==a.toLocaleLowerCase());if(!r&&c){await U({title:"Phase already exists",message:`${t} already has an archive phase named â${i}â. Choose a different name.`,confirmLabel:"Done",variant:"warning",hideCancel:!0});return}const o=(s.priorYearTestFiles||[]).filter(d=>(d.fiscalYear||"").trim().toLocaleLowerCase()===t.toLocaleLowerCase()&&(d.phase||"Unspecified phase").trim().toLocaleLowerCase()===a.toLocaleLowerCase());if(o.length===0){ge(null);return}Ms(!0);try{await j({...s,priorYearTestFiles:(s.priorYearTestFiles||[]).map(d=>o.some(l=>l.id===d.id)?{...d,phase:i}:d),updatedAt:new Date().toISOString()}),Mt(d=>({...d,[at(t,a)]:!1,[at(t,i)]:!0})),ge(null),await It("Archive phase renamed",`${t} ${a} is now named ${i}.`)}catch(d){console.error("Failed to rename archive phase:",d),await U({title:"Unable to rename archive phase",message:"The archive phase could not be renamed. Please try again.",confirmLabel:"Done",variant:"warning",hideCancel:!0})}finally{Ms(!1)}},fi=async(t,a,i)=>{if(!(!J||i.length===0||!await U({title:"Delete archive phase?",message:e.jsxs(e.Fragment,{children:["This permanently removes the ",e.jsxs("span",{className:"font-semibold",children:[t," ",a]})," phase and its ",i.length," archived file",i.length===1?"":"s","."]}),confirmLabel:"Delete phase",variant:"danger"})))try{await Promise.all(i.map(o=>o.storagePath?fs(gs(hs,o.storagePath)):Promise.resolve()));const c=new Set(i.map(o=>o.id));await j({...s,priorYearTestFiles:(s.priorYearTestFiles||[]).filter(o=>!c.has(o.id)),updatedAt:new Date().toISOString()}),Mt(o=>{const d={...o};return delete d[at(t,a)],d}),ge(o=>(o==null?void 0:o.fiscalYear)===t&&o.phase===a?null:o),await It("Archive phase deleted",`${t} ${a} and its archived files were removed.`)}catch(c){console.error("Failed to delete archive phase:",c),await U({title:"Unable to delete archive phase",message:"The phase and its archived files could not be removed. Please try again.",confirmLabel:"Done",variant:"warning",hideCancel:!0})}},ha=(t,a)=>{const i=a.map(r=>({name:r.name||"",email:r.email||""}));S(r=>t==="owner"?{...r,owners:i,owner:$t(i)}:{...r,preparers:i,preparer:$t(i)})},gi=()=>{const t=n.customRcmData||{};let a=1,i="Custom Field";for(;Object.prototype.hasOwnProperty.call(t,i);)a+=1,i=`Custom Field ${a}`;qa(i)&&ne(Ls()),S(r=>({...r,customRcmData:{...r.customRcmData||{},[i]:""}}))},fa=(t,a,i=!1)=>{if(!i){S(l=>({...l,customRcmData:{...l.customRcmData||{},[t]:a}}));return}const r=n.customRcmData||{},c=a.trim(),o=Object.keys(r).some(l=>l.toLocaleLowerCase()!==t.toLocaleLowerCase()&&l.toLocaleLowerCase()===c.toLocaleLowerCase());if(!c||o)return;const d=Ae.some(l=>l.toLocaleLowerCase()===t.toLocaleLowerCase());if(d&&c!==t){if(!Tr(t,c))return;ne(l=>l.map(f=>f.toLocaleLowerCase()===t.toLocaleLowerCase()?c:f))}else!d&&qa(c)&&ne(l=>[...l,c]);S(l=>{const f={};return Object.entries(l.customRcmData||{}).forEach(([y,M])=>{f[y.toLocaleLowerCase()===t.toLocaleLowerCase()?c:y]=M}),{...l,customRcmData:f}})},vi=t=>{const a=ke[t];if(a===void 0||a===t)return;const i=a.trim();i&&(fa(t,i,!0),be(r=>{const c={...r};return delete c[t],c}))},ji=t=>{Dr(t)&&ne(i=>i.filter(r=>r.toLocaleLowerCase()!==t.toLocaleLowerCase())),S(i=>{const r={...i.customRcmData||{}};return Object.keys(r).forEach(c=>{c.toLocaleLowerCase()===t.toLocaleLowerCase()&&delete r[c]}),{...i,customRcmData:r}}),be(i=>{const r={...i};return delete r[t],r})},Ni=async()=>{var a,i;if(!ie)return;if(!n.name||!n.description){alert("Please provide a Control Name and Description before requesting AI suggestions.");return}const t=di(n);We(!0);try{const r=await Oi(n.name,n.description,n.controlObjective,n.riskDescription,n.assertions,n.riskLevel,I==null?void 0:I.uid,n.workspaceId,n.testingAttributes,n.pbcRequests,n.controlNarrative,n.controlActivity,n.pbcPopulationRequests,n.pbcSampleRequests,t,n.controlId,{classification:n.classification,type:n.type,nature:n.nature,process:n.process,subProcess:n.subProcess,entity:n.entity,relatedITSystems:n.relatedITSystems,keyReport:n.keyReport,cosoComponents:(a=n.coso_components)!=null&&a.length?n.coso_components:n.cosoComponents});it(ci(r,t))}catch(r){(i=r.message)!=null&&i.includes("402 Payment Required")?g():alert(`AI suggestion failed: ${r.message}`)}finally{We(!1)}},q=t=>{x&&S(a=>({...a,[t]:t==="assertions"?$i(x.assertions):x[t]}))},yi=()=>{var i;const t=(i=x==null?void 0:x.riskId)==null?void 0:i.trim();if(!t)return;const a=kt.get(t.toLocaleLowerCase());if(a){Lt([...oe,a.riskId]);return}Re(t),He(t),Ke((x==null?void 0:x.riskDescription)||""),Ge(!0),xe(!0)},O="w-full bg-slate-50 border border-slate-200 rounded-lg p-2 text-sm focus:ring-2 focus:ring-brand-500 outline-none transition font-medium text-slate-900",E="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-1",De=t=>{if(!Le||!Pe)return null;const a=Ie[t];return e.jsxs("div",{className:"mt-2 animate-in fade-in slide-in-from-top-1 duration-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>pa(t,!0),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-all border ${a.reviewed&&a.isAccurate?"bg-emerald-50 text-emerald-700 border-emerald-300 shadow-sm ring-2 ring-emerald-200":"bg-white text-slate-500 border-slate-200 hover:border-emerald-300 hover:text-emerald-600"}`,children:[e.jsx(Be,{size:14}),"Accurate"]}),e.jsxs("button",{onClick:()=>pa(t,!1),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-all border ${a.reviewed&&!a.isAccurate?"bg-amber-50 text-amber-700 border-amber-300 shadow-sm ring-2 ring-amber-200":"bg-white text-slate-500 border-slate-200 hover:border-amber-300 hover:text-amber-600"}`,children:[e.jsx(Ss,{size:14}),"Suggest Update"]}),a.reviewed&&e.jsx("span",{className:"text-[10px] text-slate-400 font-medium ml-auto",children:"â Reviewed"})]}),a.reviewed&&!a.isAccurate&&e.jsxs("div",{className:"mt-2 space-y-2 animate-in fade-in slide-in-from-top-2 duration-200",children:[e.jsx("label",{className:"text-[10px] font-bold text-amber-700 uppercase tracking-wider",children:"Suggested Value"}),e.jsx("textarea",{className:"w-full bg-amber-50/50 border border-amber-200 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-amber-400 outline-none transition font-medium text-slate-900 min-h-[60
6px]",placeholder:"Suggest a new value for this field...",value:a.suggestedValue,onChange:i=>Ys(r=>({...r,[t]:{...r[t],suggestedValue:i.target.value}}))})]})]})},Te=t=>{var c;if(!Je||!ie)return null;const a=(c=Je.request.responses)==null?void 0:c.find(o=>o.controlDocId===s.id);if(!(a!=null&&a.fieldResponses))return null;const i=a.fieldResponses.find(o=>o.field===t&&!o.isAccurate&&o.reviewStatus==="PENDING");if(!i)return null;const r=ti===t;return e.jsx("div",{className:"mt-2 bg-amber-50 border border-amber-200 rounded-lg p-3 animate-in fade-in slide-in-from-top-2 duration-300",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(fr,{size:14,className:"text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-[10px] font-bold text-amber-700 uppercase tracking-wider mb-1",children:["Change Suggested by ",Je.request.ownerName]}),e.jsx("div",{className:"text-sm font-medium text-slate-900 bg-white rounded-md p-2 border border-amber-100 whitespace-pre-wrap",children:i.suggestedValue||e.jsx("span",{className:"text-slate-400 italic",children:"No value provided"})}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs("button",{onClick:()=>xa(Je.request.id,s.id,t,"ACCEPT"),disabled:r,className:"flex items-center gap-1.5 px-3 py-1.5 bg-emerald-600 text-white rounded-lg text-xs font-bold hover:bg-emerald-700 transition disabled:opacity-50",children:[r?e.jsx(ee,{size:12,className:"animate-spin"}):e.jsx(ze,{size:12}),"Accept & Update Control"]}),e.jsxs("button",{onClick:()=>xa(Je.request.id,s.id,t,"REJECT"),disabled:r,className:"flex items-center gap-1.5 px-3 py-1.5 bg-white text-slate-600 border border-slate-200 rounded-lg text-xs font-bold hover:bg-slate-50 transition disabled:opacity-50",children:[e.jsx(ae,{size:12}),"Reject"]})]})]})]})})},Y=Ba(n),Fe=Y.components.map(t=>t.id),us=Y.principles.map(t=>t.id),wi=Y.pointsOfFocus.map(t=>t.id),bs=Se.filter(t=>Fe.includes(t.id)).flatMap(t=>t.principles),ga=bs.filter(t=>us.includes(t.id)).flatMap(t=>t.pointsOfFocus),va=Array.from(new Map(((x==null?void 0:x.cosoComponents)||[]).map(t=>Ga(t)).filter(t=>!!t).map(t=>[t.id,t])).values()),St=va.map(t=>t.id),Ci=St.length>0&&(St.length!==Fe.length||St.some(t=>!Fe.includes(t))),ja=t=>{const a=t.map(f=>Es(f)).filter(f=>!!f),i=new Set(a.map(f=>f.id)),r=Y.principles.filter(f=>i.has(f.componentId)),c=new Set(r.map(f=>f.id)),o=Y.pointsOfFocus.filter(f=>r.some(y=>y.pointsOfFocus.some(M=>M.id===f.id))),d=a[0],l=r[0];S(f=>({...f,coso_component_ids:a.map(y=>y.id),coso_components:a.map(y=>y.label),cosoComponents:a.map(y=>Sr(y.id)),coso_component_id:(d==null?void 0:d.id)||"",coso_component:(d==null?void 0:d.label)||"",coso_principle_ids:r.map(y=>y.id),coso_principles:r.map(y=>Ce(y)),coso_principle_id:(l==null?void 0:l.id)||"",coso_principle:l?Ce(l):"",coso_point_of_focus_ids:o.filter(y=>c.size>0).map(y=>y.id),coso_points_of_focus:o.filter(y=>c.size>0).map(y=>qe(y))}))},Si=t=>{const a=new Set(Fe),i=t.map(d=>Ha(d)).filter(d=>!!(d&&a.has(d.componentId))),r=new Set(i.map(d=>d.id)),c=Y.pointsOfFocus.filter(d=>i.some(l=>l.pointsOfFocus.some(f=>f.id===d.id))),o=i[0];S(d=>({...d,coso_principle_ids:i.map(l=>l.id),coso_principles:i.map(l=>Ce(l)),coso_principle_id:(o==null?void 0:o.id)||"",coso_principle:o?Ce(o):"",coso_point_of_focus_ids:c.filter(l=>r.size>0).map(l=>l.id),coso_points_of_focus:c.filter(l=>r.size>0).map(l=>qe(l))}))},Ai=t=>{const a=new Set(ga.map(r=>r.id)),i=t.filter(r=>a.has(r)).map(r=>Ka(r)).filter(r=>!!r);S(r=>({...r,coso_point_of_focus_ids:i.map(c=>c.id),coso_points_of_focus:i.map(c=>qe(c))}))},At=Array.from(new Set(n.assertions||[])),ki=t=>{S({...n,assertions:At.includes(t)?At.filter(a=>a!==t):[...At,t]})},oe=(n.riskId||"").split(",").map(t=>t.trim()).filter(Boolean),kt=b.useMemo(()=>{const t=new Map;return p.forEach(a=>{var i;(i=a.riskId)!=null&&i.trim()&&t.set(a.riskId.trim().toLocaleLowerCase(),a)}),t},[p]),Na=b.useMemo(()=>{const t=pe.trim().toLocaleLowerCase();return p.filter(a=>a.isActive!==!1).filter(a=>!t||a.riskId.toLocaleLowerCase().includes(t)||a.riskDescription.toLocaleLowerCase().includes(t)).slice(0,8)},[p,pe]),Li=(t,a=[])=>{const i=new Map(kt);return a.forEach(r=>i.set(r.riskId.trim().toLocaleLowerCase(),r)),t.map(r=>{var o;const c=i.get(r.toLocaleLowerCase());return(o=c==null?void 0:c.riskDescription)!=null&&o.trim()?t.length>1?`${c.riskId} â ${c.riskDescription.trim()}`:c.riskDescription.trim():""}
6).filter(Boolean).join(` 7 8`)},Lt=(t,a=[])=>{const i=Array.from(new Map(t.map(r=>[r.toLocaleLowerCase(),r.trim()])).values()).filter(Boolean);S(r=>({...r,riskId:i.join(", "),riskDescription:Li(i,a)}))},ya=t=>{oe.some(a=>a.toLocaleLowerCase()===t.riskId.toLocaleLowerCase())||(Lt([...oe,t.riskId]),Re(""))},wa=t=>{Lt(oe.filter(a=>a.toLocaleLowerCase()!==t.toLocaleLowerCase()))},Ii=()=>{He(pe.trim()),Ke(""),xe(!0)},Ri=async()=>{if(!ie)return;const t=as.trim(),a=is.trim();if(!u||!t||!a||rs)return;const i=kt.get(t.toLocaleLowerCase());if(i){ya(i),xe(!1);return}ta(!0);try{const r=await _i.createRisk({riskId:t,riskDescription:a,riskLevel:n.riskLevel,assertions:n.assertions||[]},u);Lt([...oe,r.riskId],[r]),Re(""),He(""),Ke(""),xe(!1)}catch(r){console.error("Failed to create risk:",r),alert("Unable to create this risk. Please try again.")}finally{ta(!1)}};return e.jsxs("div",{className:"animate-in slide-in-from-right duration-300 bg-white rounded-xl shadow-xl border border-slate-200 flex flex-col h-full overflow-hidden",children:[e.jsxs("div",{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 gap-y-3 border-b border-slate-100 bg-slate-50/50 px-4 py-3 sm:px-6 sm:py-4 md:flex md:justify-between",children:[e.jsx("button",{onClick:A,className:"col-start-1 row-start-1 shrink-0 rounded-lg p-1.5 text-slate-500 transition hover:bg-slate-200",children:e.jsx(lr,{size:18})}),e.jsxs("div",{className:"col-start-2 row-start-1 min-w-0 self-center md:order-none md:flex-1",children:[e.jsxs("h3",{className:"break-words text-base font-black leading-6 tracking-tight text-slate-900 italic",children:[m?e.jsx("input",{className:"bg-white border border-slate-300 px-2 py-1 rounded text-sm outline-none",value:n.controlId,onChange:t=>S({...n,controlId:t.target.value}),placeholder:"ID"}):n.controlId,e.jsx("span",{className:"text-slate-300 mx-1 font-thin",children:"|"}),m?e.jsx("input",{className:"bg-white border border-slate-300 px-2 py-1 rounded text-sm outline-none",value:n.name,onChange:t=>S({...n,name:t.target.value}),placeholder:"Control Name"}):n.name]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:[e.jsxs("div",{children:[z("controlId"),R("controlId")]}),e.jsxs("div",{children:[z("name"),R("name")]})]})]}),e.jsx("div",{className:"col-span-3 row-start-2 flex min-w-0 items-center justify-self-start gap-2 overflow-x-auto whitespace-nowrap scrollbar-hide md:order-none md:overflow-visible",children:m?e.jsxs(e.Fragment,{children:[!v&&e.jsxs("div",{className:"relative group/suggest",children:[e.jsxs("button",{onClick:Ni,disabled:Ve,className:"flex items-center gap-2 px-3 py-1.5 border rounded-lg text-xs font-bold transition shadow-sm disabled:opacity-50 bg-brand-50 text-brand-700 border-brand-200 hover:bg-brand-100",children:[Ve?e.jsx(ee,{size:14,className:"animate-spin"}):e.jsx(or,{size:14}),"Suggest (Unlimited)"]}),!1]}),e.jsxs("button",{onClick:pi,disabled:wt,className:"flex items-center gap-2 px-4 py-1.5 bg-green-600 text-white rounded-lg text-xs font-bold hover:bg-green-700 transition shadow-sm disabled:cursor-not-allowed disabled:opacity-50",children:[wt?e.jsx(ee,{size:14,className:"animate-spin"}):e.jsx(dr,{size:14}),v?"Submit Suggestions":"Save Changes"]}),v&&e.jsxs("button",{type:"button",disabled:wt,onClick:()=>{S(te(s)),L(!1),T(!1),je(null)},className:"flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-bold text-slate-600 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx(ae,{size:14})," Cancel"]})]}):e.jsxs(e.Fragment,{children:[ie&&oa&&e.jsxs("button",{onClick:()=>k(te(s)),className:"flex items-center gap-2 px-4 py-1.5 bg-brand-900 text-white rounded-lg text-xs font-bold hover:bg-black transition shadow-sm",children:[e.jsx(Oa,{size:14}),"Test"]}),ie&&e.jsxs("button",{onClick:()=>{ns(Ee.map(t=>t.id)),L(!0)},className:"flex items-center gap-2 px-4 py-1.5 bg-slate-100 text-slate-700 rounded-lg text-xs font-bold hover:bg-slate-200 transition border border-slate-200",children:[e.jsx(Ns,{size:14}),"Edit"]}),vt&&!Le&&e.jsxs("button",{type:"button",onClick:()=>{S(te(s)),Re(""),Ge(!1),xe(!1),mt(!1),je(null),Ht("details"),T(!0),L(!0)},className:"flex items-center gap-2 rounded-lg border border-brand-200 bg-brand-50 px-3 py-1.5 text-xs font-bold text-brand-700 shadow-sm transition hover:bg-brand-100",children:[e.jsx(Ns,{size:14})," Suggest edits"]}),Pe&&ps&&!Le&&e.jsxs("button",{onClick:()=>{mt(!0),Ht("details")},className:"flex items-center gap-2 px-4 py-1.5 bg-gradient-to-r from-teal-600 to-emerald-600 text-white rounded-lg text-xs font-bold hover:from-teal-700 hover:to-emerald-700 transition shadow-md shadow-emerald-500/20 animate-in fade-in",children:[e.jsx($e,{size:14}),"Attest"]}),Pe&&Le&&e.jsxs("button",{onClick:()=>mt(!1),className:"flex items-center gap-2 px-4 py-1.5 bg-slate-100 text-slate-600 rounded-lg text-xs font-bold hover:bg-slate-200 transition border border-slate-200",children:[e.jsx(ae,{size:14}),"Cancel Attestation"]})]})}),e.jsx("button",{onClick:A,className:"col-start-3 row-start-1 justify-self-end rounded-lg p-1.5 text-slate-400 transition hover:bg-slate-200 md:order-none",children:e.jsx(ae,{size:18})})]}),e.jsx("div",{className:"sticky top-0 z-10 flex min-w-0 overflow-x-auto border-b border-slate-200 bg-white scrollbar-hide transition-colors",children:[{id:"details",label:"Overview",icon:tt},{id:"history",label:"Test History",icon:Rt,count:he.length},{id:"requests",label:"PBC Requests",icon:ys,count:Bt.length},{id:"flowcharts",label:"Flowcharts",icon:Pt,count:Vt.length},{id:"attestations",label:"Attestations",icon:$e,count:H.length},{id:"logs",label:"Audit Log",icon:Ps}].map(t=>e.jsxs("button",{onClick:()=>Ht(t.id),className:`flex min-w-max shrink-0 items-center justify-center gap-2 whitespace-nowrap border-b-2 px-4 py-3 text-xs font-bold uppercase tracking-wider transition-all md:flex-1 ${X===t.id?"border-brand-600 text-brand-700 bg-brand-50/50":"border-transparent text-slate-400 hover:text-slate-600 hover:bg-slate-50"}`,children:[e.jsx(t.icon,{size:14}),t.label,t.count!==void 0&&t.count>0&&e.jsx("span",{className:"bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded-full text-[10px] group-hover:bg-white",children:t.count})]},t.id))}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain p-8 space-y-10 bg-slate-50/30",children:[X==="details"&&e.jsxs("div",{className:"space-y-10 animate-in fade-in slide-in-from-bottom-2 duration-300",children:[Le&&e.jsxs("div",{className:"bg-gradient-to-r from-teal-50 to-emerald-50 border border-teal-200 rounded-xl p-4 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{size:16,className:"text-teal-600"}),e.jsx("span",{className:"text-sm font-bold text-teal-900",children:"Attestation in Progress"})]}),e.jsxs("span",{className:"text-xs font-bold text-teal-700",children:[xs," of ",Ze.length," fields reviewed"]})]}),e.jsx("div",{className:"w-full bg-teal-100 rounded-full h-2",children:e.jsx("div",{className:"bg-gradient-to-r from-teal-500 to-emerald-500 h-2 rounded-full transition-all duration-500",style:{width:`${xs/Ze.length*100}%`}})}),e.jsx("p",{className:"text-[11px] text-teal-700 mt-2 font-medium",children:"Review each field below by clicking â (Accurate) or â (Suggest Update). You must review all fields before signing off."})]}),Zt&&e.jsxs("div",{className:`flex items-start justify-between gap-3 rounded-md border px-3 py-2 text-xs font-semibold ${Zt.tone==="error"?"border-rose-200 bg-rose-50 text-rose-800":"border-slate-200 bg-slate-50 text-slate-700"}`,role:"status","aria-live":"polite",children:[e.jsx("span",{className:"min-w-0 flex-1 sm:whitespace-nowrap",children:Zt.message}),e.jsx("button",{type:"button",onClick:()=>je(null),className:"inline-flex h-8 w-8 shrink-0 cursor-pointer items-center justify-center rounded-md text-current transition-colors duration-200 hover:bg-black/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-current focus-visible:ring-offset-2","aria-label":"Dismiss confirmation message",title:"Dismiss message",children:e.jsx(ae,{size:16})})]}),v&&e.jsxs("div",{className:"rounded-lg border border-brand-200 bg-brand-50/70 px-4 py-3 text-sm text-brand-900",role:"status",children:[e.jsx("p",{className:"font-bold",children:"Youâre suggesting changes to this control."}),e.jsx("p",{className:"mt-0.5 text-xs leading-5 text-brand-800",children:"Your edits will be submitted for owner or admin review. The published control stays unchanged until a reviewer applies them."})]}),(()=>{const t=gt?Ja[0]:[...he].sort((o,d)=>new Date(d.createdAt).getTime()-new Date(o.createdAt).getTime())[0],a=t?"memo"in t?t.memo||"":`| Conclusion Summary | ${t.conclusion||""} |`:"",i=!!t&&Da(a)==="fail",r=i?ls[0]:void 0,c=kr(t,i);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(_e,{isEditing:m,label:"Frequency",value:n.frequency,icon:e.jsx(cr,{size:14}),onChange:o=>S({...n,frequency:o}),options:["Daily","Weekly","Bi-weekly","Monthly","Quarterly","Semi-Annual","Annual","As-Needed"]}),De("frequency"),Te("frequency"),z("frequency"),R("frequency")]}),e.jsxs("div",{children:[e.jsx(_e,{isEditing:m,label:"Risk Level",value:n.riskLevel,icon:e.jsx(mr,{size:14}),onChange:o=>S({...n,riskLevel:o}),options:["Low","Medium","High"]}),z("riskLevel"),R("riskLevel")]}),e.jsxs("div",{children:[e.jsx(_e,{isEditing:m,label:"EA Reliance",value:n.eaReliance?"Yes":"No",icon:e.jsx(tt,{size:14}),onChange:o=>S({...n,eaReliance:o==="Yes"}),options:["Yes","No"],color:n.eaReliance?"text-green-600":"text-slate-500"}),R("eaReliance")]}),e.jsxs("div",{children:[e.jsx(_e,{isEditing:m,label:"Type",value:n.isKeyControl?"Key":"Non-Key",icon:e.jsx(tt,{size:14}),onChange:o=>S({...n,isKeyControl:o==="Key"}),options:["Key","Non-Key"],color:n.isKeyControl?"text-brand-700":"text-slate-500"}),R("isKeyControl")]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(Ua,{isEditing:m,label:"Control Owner",contacts:Ot(m?n:s,"owner",m),icon:e.jsx($a,{size:14}),onChange:o=>ha("owner",o),onViewContacts:o=>ht({role:"owner",contacts:o}
8),workspaceMembers:es,isLoadingWorkspaceMembers:Zs}),De("owner"),Te("owner"),z("owner"),R(["owner","ownerEmail"])]}),e.jsxs("div",{children:[e.jsx(Ua,{isEditing:m,label:"Preparer",contacts:Ot(m?n:s,"preparer",m),icon:e.jsx($a,{size:14}),onChange:o=>ha("preparer",o),onViewContacts:o=>ht({role:"preparer",contacts:o}),workspaceMembers:es,isLoadingWorkspaceMembers:Zs}),De("preparer"),Te("preparer"),z("preparer"),R(["preparer","preparerEmail"])]}),e.jsx(_e,{isEditing:!1,label:"Last Tested",value:Ar(t,Q),icon:e.jsx(Ps,{size:14}),onChange:()=>{},color:t?"text-slate-900 group-hover:text-brand-600 transition-colors":"text-slate-400",onClick:t&&!gt?()=>window.location.href=`/memo/${t.id}`:void 0}),e.jsx(_e,{isEditing:!1,label:"Status",value:c,icon:e.jsx(tt,{size:14}),onChange:()=>{},options:[],color:t?i?"text-red-600 font-bold group-hover:text-red-800":t.reviewStatus!=="COMPLETE"?"text-blue-600 font-bold":"text-green-600 font-bold":"text-slate-400",onClick:r?()=>D(`/issue-detail/${r.id}`):void 0,onClickLabel:r?`Open linked issue ${r.issueId}`:void 0})]})]})})(),e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Control Description"}),m?e.jsx("textarea",{className:`${O} h-32`,value:n.description,onChange:t=>S({...n,description:t.target.value}),placeholder:"Detailed activity..."}):e.jsx("div",{className:"bg-slate-50 p-4 rounded-xl text-sm font-medium leading-relaxed text-slate-900 border border-slate-200 whitespace-pre-wrap",children:se(n.description)||e.jsx("span",{className:"text-slate-400 italic",children:"No description provided."})}),De("description"),Te("description"),z("description"),R("description")]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Control Objective"}),e.jsx("div",{className:"relative",children:m?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:`${O} h-24 pr-10`,value:n.controlObjective,onChange:t=>S({...n,controlObjective:t.target.value}),placeholder:"Formal objective (e.g. To ensure...)"}),(x==null?void 0:x.controlObjective)&&x.controlObjective!==n.controlObjective&&e.jsx(B,{fieldName:"Control Objective",text:x.controlObjective,onApply:()=>q("controlObjective")})]}):e.jsx("div",{className:"bg-brand-50/30 p-4 rounded-xl text-sm font-medium text-slate-900 border border-brand-100 whitespace-pre-wrap",children:n.controlObjective||e.jsx("span",{className:"text-slate-400",children:"Objective not defined."})})}),R("controlObjective")]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Control Narrative"}),e.jsx("div",{className:"relative",children:m?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:`${O} h-32`,value:n.controlNarrative||"",onChange:t=>S({...n,controlNarrative:t.target.value}),placeholder:"Narrative describing how the control operates..."}),(x==null?void 0:x.controlNarrative)&&x.controlNarrative!==n.controlNarrative&&e.jsx(B,{fieldName:"Control Narrative",text:x.controlNarrative,onApply:()=>q("controlNarrative")})]}):e.jsx("div",{className:"bg-slate-50 p-4 rounded-xl text-sm font-medium leading-relaxed text-slate-900 border border-slate-200 whitespace-pre-wrap",children:n.controlNarrative||e.jsx("span",{className:"text-slate-400 italic",children:"No narrative defined."})})}),z("controlNarrative"),R("controlNarrative")]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Control Activity"}),e.jsx("div",{className:"relative",children:m?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:`${O} h-28`,value:n.controlActivity||"",onChange:t=>S({...n,controlActivity:t.target.value}),placeholder:"Specific activity performed by the control owner..."}),(x==null?void 0:x.controlActivity)&&x.controlActivity!==n.controlActivity&&e.jsx(B,{fieldName:"Control Activity",text:x.controlActivity,onApply:()=>q("controlActivity")})]}):e.jsx("div",{className:"bg-slate-50 p-4 rounded-xl text-sm font-medium leading-relaxed text-slate-900 border border-slate-200 whitespace-pre-wrap",children:n.controlActivity||e.jsx("span",{className:"text-slate-400 italic",children:"No activity defined."})})}),De("controlActivity"),Te("controlActivity"),z("controlActivity"),R("c
8ontrolActivity")]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Attributes to Test"}),e.jsx(Xa,{value:n.testingAttributes,isEditing:m,onChange:t=>S(a=>({...a,testingAttributes:t}))}),m&&(x==null?void 0:x.testingAttributes)&&x.testingAttributes!==n.testingAttributes&&e.jsx(Or,{value:x.testingAttributes,onApply:()=>q("testingAttributes")}),De("testingAttributes"),Te("testingAttributes"),z("testingAttributes"),R("testingAttributes")]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"PBC Requests"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Population Request"}),m?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:`${O} h-32`,placeholder:"For the selected sample period, please provide...",value:n.pbcPopulationRequests||"",onChange:t=>S({...n,pbcPopulationRequests:t.target.value})}),(x==null?void 0:x.pbcPopulationRequests)&&x.pbcPopulationRequests!==n.pbcPopulationRequests&&e.jsx(B,{fieldName:"Population Request",text:Tt(x.pbcPopulationRequests),onApply:()=>q("pbcPopulationRequests")})]}):e.jsx("div",{className:"bg-slate-50 p-4 rounded-xl text-sm font-medium leading-relaxed text-slate-900 border border-slate-200 whitespace-pre-wrap",children:Tt(n.pbcPopulationRequests||n.pbcRequests||"")||"No population request defined."}),R("pbcPopulationRequests")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Sample Request"}),m?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:`${O} h-32`,placeholder:"For the selected samples, please provide...",value:n.pbcSampleRequests||"",onChange:t=>S({...n,pbcSampleRequests:t.target.value})}),(x==null?void 0:x.pbcSampleRequests)&&x.pbcSampleRequests!==n.pbcSampleRequests&&e.jsx(B,{fieldName:"Sample Request",text:Tt(x.pbcSampleRequests),onApply:()=>q("pbcSampleRequests")})]}):e.jsx("div",{className:"bg-slate-50 p-4 rounded-xl text-sm font-medium leading-relaxed text-slate-900 border border-slate-200 whitespace-pre-wrap",children:Tt(n.pbcSampleRequests||n.pbcRequests||"")||"No sample request defined."}),R("pbcSampleRequests")]}),m&&n.pbcRequests&&!n.pbcPopulationRequests&&!n.pbcSampleRequests&&e.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs font-medium text-amber-800",children:"Existing legacy PBC request text will remain available until you save separate population and sample requests."})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Metadata"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Risk ID"}),m?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"rounded-lg border border-slate-200 bg-slate-50/70 p-2",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[oe.map(t=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-brand-200 bg-brand-50 px-2 py-1 text-xs font-bold text-brand-800",children:[t,e.jsx("button",{type:"button","aria-label":`Remove ${t}`,onClick:()=>wa(t),className:"rounded p-0.5 text-brand-600 hover:bg-brand-100 hover:text-brand-800",children:e.jsx(ae,{size:12,strokeWidth:2.5})})]},t)),e.jsxs("div",{className:"relative min-w-[11rem] flex-1",children:[e.jsx(Va,{size:14,className:"pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{className:"w-full bg-transparent py-1.5 pl-8 pr-2 text-sm text-slate-800 outline-none placeholder:text-slate-400",value:pe,onFocus:()=>Ge(!0),onChange:t=>{Re(t.target.value),Ge(!0),xe(!1)},placeholder:oe.length?"Add another risk ID...":"Search risk IDs...","aria-label":"Search risk IDs","aria-expanded":ea})]})]})}),ea&&e.jsxs("div",{className:"overflow-hidden rounded-lg border border-slate-200 bg-white shadow-sm",children:[e.jsxs("div",{className:"max-h-48 overflow-y-auto p-1.5",children:[Na.map(t=>{const a=oe.some(i=>i.toLocaleLowerCase()===t.riskId.toLocaleLowerCase());return e.jsxs("button",{type:"button",onClick:()=>
8a?wa(t.riskId):ya(t),className:`flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left transition ${a?"bg-brand-50 text-brand-800":"hover:bg-slate-50 text-slate-700"}`,children:[e.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border ${a?"border-brand-600 bg-brand-600 text-white":"border-slate-300 bg-white"}`,children:a&&e.jsx(ze,{size:11,strokeWidth:3})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-xs font-bold",children:t.riskId}),e.jsx("span",{className:"block truncate text-[11px] font-medium text-slate-500",children:t.riskDescription||"No description added"})]})]},t.id)}),Na.length===0&&!ss&&e.jsx("p",{className:"px-2.5 py-3 text-xs font-medium text-slate-500",children:"No matching risks found."})]}),!ss&&ie&&e.jsx("div",{className:"border-t border-slate-100 p-1.5",children:p.some(t=>t.riskId.toLocaleLowerCase()===pe.trim().toLocaleLowerCase())&&pe.trim()?e.jsx("p",{className:"px-2.5 py-2 text-xs font-medium text-slate-500",children:"Select the matching workspace risk above to link it."}):e.jsxs("button",{type:"button",onClick:Ii,className:"flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-xs font-bold text-brand-700 hover:bg-brand-50",children:[e.jsx(Ue,{size:14}),pe.trim()?`Create risk "${pe.trim()}"`:"Create a new risk"]})}),ss&&ie&&e.jsxs("div",{className:"space-y-2 border-t border-slate-100 bg-slate-50/70 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-[11px] font-black uppercase tracking-wide text-slate-500",children:"New risk"}),e.jsx("button",{type:"button",onClick:()=>xe(!1),className:"text-xs font-semibold text-slate-500 hover:text-slate-700",children:"Cancel"})]}),e.jsx("input",{className:O,value:as,onChange:t=>He(t.target.value),placeholder:"Risk ID"}),e.jsx("textarea",{className:`${O} h-20 resize-none`,value:is,onChange:t=>Ke(t.target.value),placeholder:"Risk description"}),e.jsxs("button",{type:"button",onClick:Ri,disabled:!u||!as.trim()||!is.trim()||rs,className:"flex w-full items-center justify-center gap-2 rounded-md bg-brand-600 px-3 py-2 text-xs font-bold text-white transition hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-50",children:[rs&&e.jsx(ee,{size:13,className:"animate-spin"}),"Create and link risk"]})]})]}),(x==null?void 0:x.riskId)&&!n.riskId&&!n.riskDescription&&e.jsx(B,{fieldName:"Linked Risk",text:`${kt.has(x.riskId.trim().toLocaleLowerCase())?"Workspace risk match":"New risk recommendation"}: ${x.riskId}${x.riskDescription?` â ${x.riskDescription}`:""}`,onApply:yi}),e.jsx("p",{className:"text-[11px] font-medium text-slate-500",children:"Search the workspace risk library to link one or more risks."})]}):e.jsx("p",{className:"text-sm font-medium leading-relaxed flex flex-wrap gap-1",children:n.riskId?n.riskId.split(",").map(t=>t.trim()).filter(Boolean).map((t,a,i)=>e.jsxs(Di.Fragment,{children:[e.jsx("span",{className:"text-brand-600 hover:text-brand-800 cursor-pointer underline underline-offset-2",onClick:()=>D(`/risk-detail/${t}`),children:t}),a<i.length-1&&e.jsx("span",{className:"text-slate-400",children:","})]},t)):e.jsx("span",{className:"text-slate-400",children:"-"})}),z("riskId"),R("riskId")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Risk Description"}),m?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:`${O} h-32 resize-none bg-slate-50 text-slate-700`,value:n.riskDescription||"",readOnly:!0,placeholder:"Link a risk ID to populate its description."}),e.jsxs("p",{className:"text-[11px] font-medium text-slate-500",children:["Updated automatically from the linked risk ID",oe.length===1?"":"s","."]})]}):e.jsx("p",{className:"text-sm font-medium text-slate-900 leading-relaxed",children:n.riskDescription||e.jsx("span",{className:"text-slate-400 italic",children:"No risk specified."})}),z("riskDescription"),R("riskDescription")]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,
8children:"Risk Assertion"}),m?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 rounded-lg border border-slate-200 bg-slate-50/70 p-2",children:Fi.map(t=>{const a=At.includes(t);return e.jsxs("button",{type:"button",role:"checkbox","aria-checked":a,onClick:()=>ki(t),className:`flex items-center gap-2 rounded-md px-2.5 py-2 text-left text-xs font-semibold transition ${a?"bg-emerald-50 text-emerald-800 ring-1 ring-emerald-300":"bg-white text-slate-600 hover:bg-slate-100 ring-1 ring-transparent"}`,children:[e.jsx("span",{className:`flex h-4 w-4 shrink-0 items-center justify-center rounded border ${a?"border-emerald-600 bg-emerald-600 text-white":"border-slate-300 bg-white"}`,children:a&&e.jsx(ze,{size:11,strokeWidth:3})}),t]},t)})}),(x==null?void 0:x.assertions)&&x.assertions.join(", ")!==n.assertions.join(", ")&&e.jsx(B,{fieldName:"Risk Assertions",text:x.assertions.join(", "),onApply:()=>q("assertions")})]}):e.jsx("div",{className:"flex flex-wrap gap-2",children:((Ca=n.assertions)==null?void 0:Ca.length)>0?n.assertions.map(t=>e.jsx("span",{className:"px-2 py-1 bg-brand-50 text-brand-700 rounded text-[10px] font-bold border border-brand-100",children:t},t)):e.jsx("span",{className:"text-slate-400 text-xs italic",children:"-"})}),R("assertions")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Classification"}),m?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("select",{className:O,value:n.classification||"Business Process",onChange:t=>S({...n,classification:t.target.value}),children:[e.jsx("option",{value:"Business Process",children:"Business Process"}),e.jsx("option",{value:"ELC",children:"ELC"}),e.jsx("option",{value:"ITGC",children:"ITGC"})]}),(x==null?void 0:x.classification)&&x.classification!==n.classification&&e.jsx(B,{fieldName:"Classification",text:x.classification,onApply:()=>q("classification")})]}):e.jsx("p",{className:"text-sm font-medium text-slate-900 leading-relaxed",children:n.classification||"-"}),R("classification")]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Control Type"}),m?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("select",{className:O,value:n.type||"Manual",onChange:t=>S({...n,type:t.target.value}),children:[e.jsx("option",{value:"Manual",children:"Manual"}),e.jsx("option",{value:"Automated",children:"Automated"}),e.jsx("option",{value:"ITDM",children:"ITDM"})]}),(x==null?void 0:x.type)&&x.type!==n.type&&e.jsx(B,{fieldName:"Control Type",text:x.type,onApply:()=>q("type")})]}):e.jsx("p",{className:"text-sm font-medium text-slate-900 leading-relaxed",children:n.type||"-"}),R("type")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Nature"}),m?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("select",{className:O,value:n.nature||"Preventive",onChange:t=>S({...n,nature:t.target.value}),children:[e.jsx("option",{value:"Preventive",children:"Preventive"}),e.jsx("option",{value:"Detective",children:"Detective"}),e.jsx("option",{value:"Corrective",children:"Corrective"})]}),(x==null?void 0:x.nature)&&x.nature!==n.nature&&e.jsx(B,{fieldName:"Control Nature",text:x.nature,onApply:()=>q("nature")})]}):e.jsx("p",{className:"text-sm font-medium text-slate-900 leading-relaxed",children:n.nature||"-"}),R("nature")]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Process"}),m?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("input",{className:O,value:n.process||"",onChange:t=>S({...n,process:t.target.value})}),(x==null?void 0:x.process)&&x.process!==n.process&&e.jsx(B,{fieldName:"Process",text:x.process,onApply:()=>q("process")})]}):e.jsx("p",{className:"text-sm font-medium text-slate-900 leading-relaxed",children:n.process||"-"}),z("process"),R("process")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,
8children:"Sub-Process"}),m?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("input",{className:O,value:n.subProcess||"",onChange:t=>S({...n,subProcess:t.target.value})}),(x==null?void 0:x.subProcess)&&x.subProcess!==n.subProcess&&e.jsx(B,{fieldName:"Sub-process",text:x.subProcess,onApply:()=>q("subProcess")})]}):e.jsx("p",{className:"text-sm font-medium text-slate-900 leading-relaxed",children:n.subProcess||"-"}),z("subProcess"),R("subProcess")]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Related IT System"}),m?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("input",{className:O,value:((Sa=n.relatedITSystems)==null?void 0:Sa.join(", "))||"",placeholder:"Comma separated",onChange:t=>S({...n,relatedITSystems:t.target.value.split(",").map(a=>a.trim()).filter(Boolean)})}),(x==null?void 0:x.relatedITSystems)&&x.relatedITSystems.join(", ")!==(((Aa=n.relatedITSystems)==null?void 0:Aa.join(", "))||"")&&e.jsx(B,{fieldName:"Related IT Systems",text:x.relatedITSystems.join(", "),onApply:()=>q("relatedITSystems")})]}):e.jsx("div",{className:"flex flex-wrap gap-2",children:((ka=n.relatedITSystems)==null?void 0:ka.length)>0?n.relatedITSystems.map(t=>e.jsx("span",{className:"px-2 py-1 bg-slate-100 text-slate-700 rounded text-[10px] font-bold border border-slate-200",children:t},t)):e.jsx("span",{className:"text-slate-400 text-xs italic",children:"-"})}),z("relatedITSystems"),R("relatedITSystems")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Key Report"}),m?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("input",{className:O,value:n.keyReport||"",onChange:t=>S({...n,keyReport:t.target.value})}),(x==null?void 0:x.keyReport)&&x.keyReport!==n.keyReport&&e.jsx(B,{fieldName:"Key Report",text:x.keyReport,onApply:()=>q("keyReport")})]}):e.jsx("p",{className:"text-sm font-medium text-slate-900 leading-relaxed",children:n.keyReport||"-"}),z("keyReport"),R("keyReport")]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Entity / BU"}),m?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("input",{className:O,value:n.entity||"",onChange:t=>S({...n,entity:t.target.value})}),(x==null?void 0:x.entity)&&x.entity!==n.entity&&e.jsx(B,{fieldName:"Entity / BU",text:x.entity,onApply:()=>q("entity")})]}):e.jsx("p",{className:"text-sm font-medium text-slate-900 leading-relaxed",children:n.entity||"-"}),z("entity"),R("entity")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Policy"}),m&&!v?e.jsx(tr,{manualValue:n.policy||"",onManualValueChange:t=>S({...n,policy:t}),policies:ft,selectedPolicyIds:aa,onSelectedPolicyIdsChange:ns}):e.jsxs("div",{className:"space-y-2",children:[((La=n.policy)==null?void 0:La.trim())&&e.jsx("p",{className:"text-sm font-medium leading-relaxed text-slate-900",children:n.policy}),Ee.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:Ee.map(t=>e.jsxs(Ti,{to:`/policies/${t.id}`,className:"rounded border border-brand-100 bg-brand-50 px-2 py-1 text-xs font-bold text-brand-700 hover:bg-brand-100 hover:underline",children:[t.policyId," â ",t.title]},t.id))}),!((Ia=n.policy)!=null&&Ia.trim())&&!Ee.length&&e.jsx("p",{className:"text-sm font-medium leading-relaxed text-slate-900",children:"-"})]})]})]}),e.jsxs("section",{className:"rounded-xl border border-brand-100 bg-brand-50/30 p-4 sm:p-5",children:[e.jsxs("div",{className:"mb-4 flex items-start gap-3",children:[e.jsx("div",{className:"rounded-lg bg-brand-100 p-2 text-brand-700",children:e.jsx(tt,{size:18})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-black text-slate-900",children:"COSO Framework Mapping"}),e.jsx("p",{className:"mt-0.5 text-xs text-slate-500",children:"Components â Principles â Points of Focus"})]})]}),m&&!v?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,
8children:"COSO Components"}),e.jsx(Is,{ariaLabel:"COSO Components",options:Se.map(t=>({id:t.id,label:t.label})),selectedIds:Fe,onChange:ja,placeholder:"Select COSO components",disabledPlaceholder:"Select COSO components",searchPlaceholder:"Search components..."}),Ci&&e.jsx(B,{fieldName:"COSO Components",text:va.map(t=>t.label).join(", "),onApply:()=>ja(St)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"COSO Principles"}),e.jsx(Is,{ariaLabel:"COSO Principles",options:bs.map(t=>{var a;return{id:t.id,label:Ce(t),group:(a=Es(t.componentId))==null?void 0:a.label}}),selectedIds:us,onChange:Si,placeholder:"Select COSO principles",disabledPlaceholder:"Select a component first",searchPlaceholder:"Search principles...",disabled:Fe.length===0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"COSO Points of Focus"}),e.jsx(Is,{ariaLabel:"COSO Points of Focus",options:ga.map(t=>{const a=bs.find(i=>i.pointsOfFocus.some(r=>r.id===t.id));return{id:t.id,label:qe(t),group:a?`Principle ${a.number}`:void 0}}),selectedIds:wi,onChange:Ai,placeholder:"Select COSO points of focus",disabledPlaceholder:"Select a principle first",searchPlaceholder:"Search points of focus...",disabled:us.length===0})]})]}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-5 lg:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:E,children:"Components"}),Y.components.length>0?e.jsx("div",{className:"flex flex-wrap gap-2",children:Y.components.map(t=>e.jsx("span",{className:"rounded-full border border-brand-200 bg-brand-50 px-2.5 py-1 text-xs font-semibold text-brand-800",children:t.label},t.id))}):e.jsx("span",{className:"text-xs italic text-slate-400",children:"-"})]}),e.jsxs("div",{children:[e.jsx("p",{className:E,children:"Principles"}),Y.principles.length>0?e.jsx("ul",{className:"space-y-2",children:Y.principles.map(t=>e.jsx("li",{className:"text-sm font-semibold leading-6 text-slate-900",children:Ce(t)},t.id))}):e.jsx("span",{className:"text-xs italic text-slate-400",children:"-"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:E,children:"Points of Focus"}),Y.pointsOfFocus.length>0?e.jsx("ul",{className:"space-y-2",children:Y.pointsOfFocus.map(t=>e.jsxs("li",{className:"flex items-start gap-2 text-sm leading-6 text-slate-700",children:[e.jsx("span",{className:"mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-brand-500"}),e.jsx("span",{children:qe(t)})]},t.id))}):e.jsx("span",{className:"text-xs italic text-slate-400",children:"-"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Fraud Control"}),m?e.jsxs("select",{className:O,value:n.fraudControl?"Yes":"No",onChange:t=>S({...n,fraudControl:t.target.value==="Yes"}),children:[e.jsx("option",{value:"Yes",children:"Yes"}),e.jsx("option",{value:"No",children:"No"})]}):e.jsx("p",{className:`text-sm font-medium ${n.fraudControl?"text-amber-600":"text-slate-900 leading-relaxed"}`,children:n.fraudControl?"Yes":"No"}),R("fraudControl")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"MRC"}),m?e.jsxs("select",{className:O,value:n.mrc?"Yes":"No",onChange:t=>S({...n,mrc:t.target.value==="Yes"}),children:[e.jsx("option",{value:"Yes",children:"Yes"}),e.jsx("option",{value:"No",children:"No"})]}):e.jsx("p",{className:`text-sm font-medium ${n.mrc?"text-blue-600":"text-slate-900 leading-relaxed"}`,children:n.mrc?"Yes":"No"}),R("mrc")]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Date Effective"}),m?e.jsx("input",{type:"date",className:O,value:n.dateEffective||"",onChange:t=>S({...n,dateEffective:t.target.value})}):e.jsx("p",{className:"text-sm text-slate-900 font-medium leading-relaxed",children:Ma(n.dateEffective)}),z("dateEffective"),R("dateEffective")]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,
8children:"Date Decommissioned"}),m?e.jsx("input",{type:"date",className:O,value:n.dateDecommissioned||"",onChange:t=>S({...n,dateDecommissioned:t.target.value||null})}):e.jsx("p",{className:"text-sm text-slate-900 font-medium leading-relaxed",children:Ma(n.dateDecommissioned)}),R("dateDecommissioned")]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Control Status"}),e.jsx("p",{className:`text-sm font-medium ${n.isActive!==!1?"text-emerald-700":"text-slate-500"}`,children:n.isActive!==!1?"Active":"Inactive"}),R("isActive")]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:E,children:[e.jsx(ws,{size:10,className:"inline mr-1 text-red-400"}),"Open Issues"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:ls.length>0?ls.map(t=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-bold text-red-700 bg-red-50 px-2.5 py-1 rounded-lg border border-red-200 cursor-pointer hover:bg-red-100 hover:shadow-sm transition",onClick:()=>D(`/issue-detail/${t.id}`),children:[e.jsx(ws,{size:11}),t.issueId]},t.id)):e.jsx("span",{className:"text-xs text-slate-400 italic",children:"None"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:E,children:[e.jsx(ze,{size:10,className:"inline mr-1 text-emerald-400"}),"Past Issues"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:la.length>0?la.map(t=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-bold text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded-lg border border-emerald-200 cursor-pointer hover:bg-emerald-100 hover:shadow-sm transition",onClick:()=>D(`/issue-detail/${t.id}`),children:[e.jsx(ze,{size:11}),t.issueId]},t.id)):e.jsx("span",{className:"text-xs text-slate-400 italic",children:"None"})})]})]}),(()=>{const t=l=>Ra(l,s.id),a=H.find(l=>t(l.request)==="COMPLETED"),i=ve[0],r=(a==null?void 0:a.request.signedAt)||(a==null?void 0:a.request.updatedAt)||"",c=(i==null?void 0:i.request.signedAt)||"",o=!!(i&&(!a||c>=r)),d=H.find(l=>t(l.request)!=="COMPLETED");return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 pt-4 border-t border-slate-100",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Last Attested Date"}),o&&i?e.jsxs("button",{onClick:()=>ms(i.campaign,i.request),className:"text-sm font-medium text-brand-600 hover:text-brand-800 hover:underline flex items-center gap-1.5 transition",children:[Q(i.request.signedAt)," (",i.campaign.period,")",e.jsx(Et,{size:12})]}):a?e.jsxs("button",{onClick:()=>Ye({request:a.request,campaign:a.campaign}),className:"text-sm font-medium text-brand-600 hover:text-brand-800 hover:underline flex items-center gap-1.5 transition",children:[Q(a.request.signedAt||a.request.updatedAt)," (",a.campaign.period,")",e.jsx(Et,{size:12})]}):e.jsx("span",{className:"text-sm text-slate-400 italic",children:"Never"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:E,children:"Current Attestation Status"}),d?e.jsxs("button",{onClick:()=>Ye({request:d.request,campaign:d.campaign}),className:"flex items-center gap-2 group w-fit",children:[e.jsx("span",{className:`inline-flex items-center rounded-full px-2.5 py-1 text-xs font-bold transition group-hover:shadow-sm ${t(d.request)==="OVERDUE"?"bg-red-50 text-red-700 border border-red-200":"bg-amber-50 text-amber-700 border border-amber-200"}`,children:t(d.request).replace("_"," ")}),e.jsxs("span",{className:"text-xs font-medium text-slate-500 group-hover:text-brand-600 transition",children:["(",d.campaign.period,")"]})]}):i?e.jsxs("button",{onClick:()=>ms(i.campaign,i.request),className:"flex items-center gap-2 group w-fit",children:[e.jsx("span",{className:"inline-flex items-center rounded-full border border-emerald-200 bg-emerald-50 px-2.5 py-1 text-xs font-bold text-emerald-700 transition group-hover:shadow-sm",children:"SIGNED"}),e.jsxs("span",{className:"text-xs font-medium text-slate-500 group-hover:text-brand-600 transition",children:["(",i.campaign.period,")"]})]}):a?e.jsxs("button",{onClick:()=>Ye({request:a.request,campaign:a.campaign}),className:"flex items-center gap-2 group w-fit",children:[e.jsx("span",{className:"inline-flex items-center rounded-full border border-emerald-200 bg-emerald-50 px-2.5 py-1 text-xs font-bold text-emerald-700 transition group-hover:shadow-sm",children:"COMPLETED"}),e.jsxs("span",{className:"text-xs font-medium text-slate-500 group-hover:text-brand-600 transition",children:["(",a.campaign.period,")"]})]}):e.jsx("span",{className:"text-sm text-slate-400 italic",children:"-"})]})]})})(),e.jsxs("div",{className:"space-y-3 pt-4 border-t border-slate-100",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:E,
8children:"Custom RCM Data"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Add workspace-specific metadata. Each label is included as its own export column."})]}),m&&!v&&e.jsxs("button",{type:"button",onClick:gi,className:"shrink-0 inline-flex items-center gap-1.5 rounded-lg border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-bold text-brand-700 transition hover:bg-brand-100",children:[e.jsx(Ue,{size:14})," Add field"]})]}),m?jt.length>0?e.jsx("div",{className:"space-y-2",children:jt.map(([t,a])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:`grid grid-cols-1 gap-2 ${v?"sm:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]":"sm:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto]"}`,children:[v?e.jsx("div",{className:`${O} flex items-center text-slate-500`,"aria-label":"Custom RCM column name",children:t}):e.jsx("input",{className:O,value:ke[t]??t,"aria-label":"Custom RCM column name",onChange:i=>be(r=>({...r,[t]:i.target.value})),onBlur:()=>vi(t)}),e.jsx("input",{className:O,value:a,"aria-label":`${t} value`,placeholder:"Value",onChange:i=>fa(t,i.target.value)}),!v&&e.jsx("button",{type:"button","aria-label":`Remove ${t}`,onClick:()=>ji(t),className:"inline-flex h-10 w-10 items-center justify-center self-center rounded-lg text-slate-400 transition hover:bg-red-50 hover:text-red-600",children:e.jsx(Me,{size:15})})]}),R([],t)]},t.toLocaleLowerCase()))}):null:jt.length>0?e.jsx("dl",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:jt.map(([t,a])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"rounded-lg border border-slate-100 bg-slate-50 px-3 py-2.5",children:[e.jsx("dt",{className:"text-[10px] font-black uppercase tracking-widest text-slate-400",children:t}),e.jsx("dd",{className:"mt-1 break-words text-sm font-medium leading-relaxed text-slate-900",children:a||"-"})]}),R([],t)]},t))}):null]})]})]}),Pe&&Le&&Nt&&e.jsx("section",{className:"sticky bottom-0 bg-white border-t-2 border-teal-200 rounded-xl shadow-xl p-6 animate-in slide-in-from-bottom-4 duration-500",children:e.jsxs("div",{className:"max-w-xl mx-auto space-y-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-lg font-black text-slate-900",children:"Sign & Complete Attestation"}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 font-medium",children:"By signing below, I attest that I have reviewed the control details above and the responses provided are accurate to the best of my knowledge."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-bold text-slate-700 uppercase",children:"Electronic Signature (Full Name)"}),e.jsx("input",{value:pt,onChange:t=>Gs(t.target.value),placeholder:"e.g. Jane Doe",disabled:!Nt,className:"w-full px-4 py-3 bg-slate-50 border-2 border-slate-200 rounded-xl text-base font-bold focus:ring-4 focus:ring-teal-500/20 focus:border-teal-500 focus:bg-white outline-none transition-all text-center disabled:opacity-50 disabled:cursor-not-allowed"})]}),e.jsxs("button",{onClick:oi,disabled:Jt||!Nt||!pt.trim(),className:"w-full flex items-center justify-center gap-2 px-6 py-4 bg-gradient-to-r from-teal-600 to-emerald-600 text-white font-black rounded-xl hover:from-teal-700 hover:to-emerald-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-lg shadow-teal-500/20",children:[Jt&&e.jsx(ee,{size:20,className:"animate-spin"}),e.jsx($e,{size:18}),"Submit Attestation"]})]})})]}),X==="history"&&e.jsxs("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Testing Results",icon:e.jsx(Rt,{size:16})}),e.jsxs("div",{className:"space-y-3",children:[he.length===0&&e.jsxs("div",{className:"rounded-xl border border-dashed border-slate-300 bg-white px-6 py-12 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 flex h-11 w-11 items-center justify-center rounded-xl bg-slate-100 text-slate-400",children:e.jsx(Oa,{size:21})}),e.jsx("h5",{className:"text-sm font-bold text-slate-700",children:"No tests run yet"}),e.jsx("p",{className:"mx-auto mt-1 max-w-sm text-xs leading-relaxed text-slate-500",children:"Run automated testing for this control to create a documented testing result."}),ie&&oa&&e.jsxs("button",{type:"button",onClick:()=>k(te(s)),className:"mt-4 inline-flex items-center gap-1.5 text-xs font-bold text-brand-700 transition hover:text-brand-900",children:["Run Testing ",e.jsx(Dt,{size:14})]})]}),Object.entries(he.reduce((t,a)=>{var o,d;const i=((o=a.inputs)==null?void 0:o.fiscalYear)||"FY26",r=a.testPhase||((d=a.inputs)==null?void 0:d.testPhase)||"Walkthrough",c=`${i} ${r}`;return t[c]||(t[c]=[]),t[c].push(a),t},{})).map(([t,a])=>e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider mt-4 mb-2 border-b border-slate-100 pb-1",children:t}),a.map(i=>{var l;(l=i.memo)!=null&&l.toLowerCase();const r=Da(i.memo||"")==="fail",c=i.memo?i.memo.match(/\|\s*\*\*Sample Period\*\*\s*\|\s*([^|]+)\s*\|/i):null,o=c?c[1].trim():null,d=o?`${o} Result`:`${Q(i.createdAt)} Result`;return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg p-3 hover:shadow-md transition group cursor-pointer",onClick:()=>D(`/memo/${i.id}${u?`?ws=${encodeURIComponent(u)}`:""}`),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${r?"bg-red-500":i.reviewStatus!=="COMPLETE"?"bg-blue-500":"bg-green-500"}`}),e.jsx("h5",{className:"text-xs font-bold text-slate-900",children:d})]}),e.jsx("div",{className:"flex items-center gap-2",children:J&&e.jsx("button",{onClick:f=>{f.stopPropagation(),Kt({open:!0,runId:i.id,displayName:d})},className:"text-[10px] font-bold text-red-600 hover:text-red-700 p-1",title:"Delete test result",children:e.jsx(Me,{size:12})})})]}),e.jsxs("div",{className:"mt-2 text-[10px] text-slate-500 flex items-center gap-3",children:[e.jsx("span",{children:Q(i.createdAt)}),e.jsx("span",{children:"â¢"}),e.jsx("span",{children:Yi(i.createdAt)}),e.jsx("span",{children:"â¢"}),e.jsx("span",{className:`uppercase tracking-wider ${r?"text-red-600 font-bold":i.reviewStatus!=="COMPLETE"?"text-blue-600 font-bold":"text-green-600 font-bold"}`,children:r?"INEFFECTIVE":i.reviewStatus!=="COMPLETE"?"EFFECTIVE - PENDING REVIEW":"EFFECTIVE"})]})]},i.id)})]},t))]}),he.length===0&&!Pi(N)&&e.jsxs("div",{className:"bg-gradient-to-br from-amber-50 to-orange-50 border-2 border-amber-200 rounded-xl p-6 text-center mt-4",children:[e.jsx("div",{className:"bg-white p-3 rounded-full w-12 h-12 flex items-center justify-center mx-auto mb-3 shadow-sm",children:e.jsx(pr,{className:"text-amber-500",size:24})}),e.jsx("h4",{className:"text-sm font-bold text-slate-900 mb-2",children:"Save Your Testing History"}),e.jsxs("p",{className:"text-xs text-slate-600 mb-4 leading-relaxed",children:["Upgrade to the ",e.jsx("span",{className:"font-bold text-brand-700",children:"Plus Plan"})," to automatically save and access testing history, reviewer workflow, and shared workspace collaboration."]}),e.jsx("button",{onClick:P,className:"px-4 py-2 bg-gradient-to-r from-amber-500 to-orange-500 text-white text-xs font-bold rounded-lg shadow-lg shadow-amber-500/20 hover:scale-105 transition",children:"Upgrade to Plus"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsx("div",{className:"flex-1 min-w-[180px]",children:e.jsx(G,{title:"Prior-Year Archive",icon:e.jsx(Cs,{size:16})})}),J&&e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"mb-1 block text-[10px] font-bold uppercase tracking-wider text-slate-500",children:"Fiscal year"}),e.jsx("input",{value:Fs,onChange:t=>Os(t.target.value),placeholder:"e.g. FY25",maxLength:24,className:"h-9 w-24 rounded-lg border border-slate-200 bg-white px-2.5 text-xs font-semibold text-slate-700 outline-none transition focus:border-brand-500 focus:ring-2 focus:ring-brand-100","aria-label":"Archive fiscal year",disabled:fe})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"mb-1 block text-[10px] font-bold uppercase tracking-wider text-slate-500",children:"Test phase"}),e.jsx("input",{value:$s,onChange:t=>_s(t.target.value),placeholder:"e.g. Interim",list:`archive-phase-options-${s.id}`,maxLength:80,className:"h-9 w-32 rounded-lg border border-slate-200 bg-white px-2.5 text-xs font-semibold text-slate-700 outline-none transition focus:border-brand-500 focus:ring-2 focus:ring-brand-100","aria-label":"Archive test phase",disabled:fe}),e.jsx("datalist",{id:`archive-phase-options-${s.id}`,children:ai.map(t=>e.jsx("option",{value:t},t))})]}),e.jsxs("label",{className:`inline-flex h-9 cursor-pointer items-center gap-1.5 rounded-lg bg-brand-600 px-3 text-xs font-bold text-white shadow-sm transition hover:bg-brand-700 ${fe?"pointer-events-none opacity-60":""}`,children:[fe?e.jsx(ee,{size:14,className:"animate-spin"}):e.jsx(_a,{size:14}),fe?"Uploading...":"Upload files",e.jsx("input",{ref:ia,type:"file",multiple:!0,accept:Ki,className:"sr-only",onChange:xi,disabled:fe})]})]})]}),Xe.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center rounded-xl border border-dashed border-slate-200 bg-white px-6 py-10 text-center",children:[e.jsx(Cs,{size:22,className:"mb-2 text-slate-300"}),e.jsx("p",{className:"text-xs font-semibold text-slate-500",children:"No prior-year testing phases archived."}),J&&e.jsx("p",{className:"mt-1 text-[11px] text-slate-400",children:"Choose a fiscal year and phase, then upload files to create a phase card."})]}):e.jsx("div",{className:"space-y-5",children:Object.entries(si).sort(([t],[a])=>a.localeCompare(t)).map(([t,a])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("span",{className:"rounded-md bg-brand-50 px-2 py-1 text-[10px] font-black uppercase tracking-wider text-brand-700",children:t}),e.jsxs("span",{className:"text-[10px] text-slate-400",children:[Object.keys(a).length," phase",Object.keys(a).length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:Object.entries(a).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>{const c=at(t,i),o=!!Za[c],d=(ce==null?void 0:ce.fiscalYear)===t&&ce.phase===i;return e.jsxs("div",{className:`overflow-hidden rounded-xl border bg-white transition ${o?"border-brand-200 shadow-sm":"border-slate-200 hover:border-brand-200 hover:shadow-sm"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 p-3",children:[e.jsxs("button",{type:"button",onClick:()=>bi(t,i),className:"flex min-w-0 flex-1 items-center gap-3 text-left","aria-expanded":o,children:[e.jsx("div",{className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${o?"bg-brand-600 text-white":"bg-brand-50 text-brand-700"}`,children:e.jsx(Cs,{size:17})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-xs font-bold text-slate-900",children:i}),e.jsxs("p",{className:"mt-0.5 text-[10px] text-slate-500",children:[r.length," / ",vs," files"]})]}),o?e.jsx(Ds,{size:16,className:"shrink-0 text-brand-600"}):e.jsx(Wa,{size:16,className:"shrink-0 text-slate-400"})]}),J&&!d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("button",{type:"button",onClick:()=>hi(t,i),className:"rounded-md p-1.5 text-slate-400 transition hover:bg-brand-50 hover:text-brand-700",title:`Add f
8iles to ${i}`,"aria-label":`Add files to ${i}`,children:e.jsx(_a,{size:14})}),e.jsx("button",{type:"button",onClick:()=>ge({fiscalYear:t,phase:i,value:i==="Unspecified phase"?"":i}),className:"rounded-md p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-slate-700",title:`Rename ${i}`,"aria-label":`Rename ${i}`,children:e.jsx(Ns,{size:14})}),e.jsx("button",{type:"button",onClick:()=>void fi(t,i,r),className:"rounded-md p-1.5 text-slate-400 transition hover:bg-red-50 hover:text-red-600",title:`Delete ${i}`,"aria-label":`Delete ${i}`,children:e.jsx(Me,{size:14})})]})]}),d&&e.jsxs("div",{className:"flex items-center gap-2 border-t border-slate-100 bg-slate-50 px-3 py-2",children:[e.jsx("input",{value:ce.value,onChange:l=>ge(f=>f&&{...f,value:l.target.value}),placeholder:"Phase name",autoFocus:!0,className:"h-8 min-w-0 flex-1 rounded-md border border-slate-200 bg-white px-2 text-xs font-semibold text-slate-700 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100",onKeyDown:l=>{l.key==="Enter"&&ba(),l.key==="Escape"&&ge(null)},disabled:rt}),e.jsx("button",{type:"button",onClick:()=>void ba(),disabled:rt,className:"rounded-md bg-brand-600 px-2.5 py-1.5 text-[10px] font-bold text-white transition hover:bg-brand-700 disabled:opacity-60",children:rt?"Saving...":"Save"}),e.jsx("button",{type:"button",onClick:()=>ge(null),disabled:rt,className:"rounded-md px-2 py-1.5 text-[10px] font-bold text-slate-500 transition hover:bg-white hover:text-slate-700",children:"Cancel"})]}),o&&e.jsx("div",{className:"border-t border-slate-100 bg-slate-50/40 p-2 animate-in fade-in slide-in-from-top-1 duration-200",children:e.jsx("div",{className:"space-y-1",children:r.map(l=>e.jsxs("div",{className:"flex items-center gap-3 rounded-lg px-2 py-2 transition hover:bg-white",children:[e.jsx(Rt,{size:16,className:"shrink-0 text-slate-400"}),e.jsxs("button",{type:"button",onClick:()=>window.open(l.fileUrl,"_blank","noopener,noreferrer"),className:"min-w-0 flex-1 text-left",title:`Open ${l.fileName}`,children:[e.jsx("p",{className:"truncate text-xs font-semibold text-slate-800 hover:text-brand-700",children:l.fileName}),e.jsxs("p",{className:"mt-0.5 text-[10px] text-slate-400",children:[Pr(l.fileSize)," · Uploaded ",Q(l.uploadedAt),l.uploadedBy?` by ${l.uploadedBy}`:""]})]}),e.jsx("a",{href:l.fileUrl,target:"_blank",rel:"noreferrer",download:l.fileName,className:"rounded-md p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-brand-700",title:`Download ${l.fileName}`,"aria-label":`Download ${l.fileName}`,children:e.jsx(za,{size:15})}),J&&e.jsx("button",{type:"button",onClick:()=>void ui(l),className:"rounded-md p-1.5 text-slate-400 transition hover:bg-red-50 hover:text-red-600",title:`Remove ${l.fileName}`,"aria-label":`Remove ${l.fileName}`,children:e.jsx(Me,{size:15})})]},l.id))})})]},i)})})]},t))})]})]}),X==="requests"&&e.jsx("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-slate-100 pb-2",children:[e.jsxs("h4",{className:"flex min-w-0 items-center gap-2 text-xs font-black uppercase tracking-widest text-slate-900",children:[e.jsx(ys,{size:16}),"Linked PBC Requests"]}),ds&&e.jsxs("button",{type:"button",onClick:()=>nt(!0),className:"inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-bold text-white shadow-sm transition hover:bg-brand-700 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2",children:[e.jsx(Ue,{size:14})," Add request"]})]}),e.jsxs("div",{className:"space-y-3",children:[Bt.length===0&&e.jsxs("div",{className:"rounded-xl border border-dashed border-slate-300 bg-white px-6 py-12 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 flex h-11 w-11 items-center justify-center rounded-xl bg-slate-100 text-slate-400",children:e.jsx(ys,{size:21})}),e.jsx("h5",{className:"text-sm font-bold text-slate-700",children:"No linked PBC requests yet"}),e.jsx("p",{className:"mx-auto mt-1 max-w-sm text-xs leading-relaxed text-slate-500",children:"Add a PBC request to collect evidence for this control."}),ds&&e.jsxs("button",{type:"button",onClick:()=>nt(!0),className:"mt-4 inline-flex items-center gap-1.5 text-xs font-bold text-brand-700 transition hover:text-brand-900",children:["Add request ",e.jsx(Ue,{size:14})]})]}),Bt.map(t=>e.jsxs("button",{type:"button",onClick:()=>D(`/request-detail/${t.id}`),className:"w-full rounded-lg border border-slate-200 bg-white p-4 text-left transition hover:border-brand-200 hover:shadow-md",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h5",{className:"truncate text-sm font-bold text-slate-900",children:t.title}),e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold ${t.status==="COMPLETED"?"bg-emerald-50 text-emerald-700":t.status==="IN_REVIEW"?"bg-indigo-50 text-indigo-700":t.status==="SENT"?"bg-blue-50 text-blue-700":t.status==="RETURNED"?"bg-
8orange-50 text-orange-700":"bg-slate-100 text-slate-600"}`,children:t.status.replace("_"," ")})]}),e.jsxs("div",{className:"mt-1 text-xs font-medium text-slate-500",children:[t.requestType==="SAMPLE"?"Sample":t.requestType==="POPULATION"?"Population":"General",t.testPhase?` ⢠${t.testPhase}`:""]})]}),e.jsx(Et,{size:14,className:"mt-0.5 flex-shrink-0 text-slate-400"})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-[11px] text-slate-500",children:[e.jsxs("span",{children:[t.filesCount," file",t.filesCount===1?"":"s"]}),e.jsx("span",{children:"â¢"}),e.jsxs("span",{children:["Created ",Q(t.createdAt)]}),t.dueDate&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"â¢"}),e.jsxs("span",{children:["Due ",Rs(t.dueDate)]})]})]})]},t.id))]})]})}),X==="flowcharts"&&e.jsx("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Linked process flowcharts",icon:e.jsx(Pt,{size:16})}),lt&&e.jsx("div",{className:"space-y-3","aria-label":"Loading linked flowcharts",children:[0,1].map(t=>e.jsx("div",{className:"h-28 animate-pulse rounded-xl border border-slate-200 bg-slate-100"},t))}),!lt&&ot&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-5 text-center",children:[e.jsx(ws,{className:"mx-auto mb-2 text-red-500",size:22}),e.jsx("p",{className:"text-sm font-bold text-red-800",children:ot})]}),!lt&&!ot&&Vt.length===0&&e.jsxs("div",{className:"rounded-xl border border-dashed border-slate-300 bg-white px-6 py-12 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 flex h-11 w-11 items-center justify-center rounded-xl bg-slate-100 text-slate-400",children:e.jsx(Pt,{size:21})}),e.jsx("h5",{className:"text-sm font-bold text-slate-700",children:"No linked flowcharts yet"}),e.jsx("p",{className:"mx-auto mt-1 max-w-sm text-xs leading-relaxed text-slate-500",children:"Link this control to a process step in Flowcharts to see its process context here."}),e.jsxs("button",{type:"button",onClick:()=>D("/flowcharts"),className:"mt-4 inline-flex items-center gap-1.5 text-xs font-bold text-brand-700 transition hover:text-brand-900",children:["Open Flowcharts ",e.jsx(Dt,{size:14})]})]}),!lt&&!ot&&Vt.map(t=>e.jsxs("article",{className:"group overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm transition hover:border-brand-200 hover:shadow-md",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-5 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 gap-3",children:[e.jsx("span",{className:"mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-slate-900 text-white shadow-sm",children:e.jsx(Pt,{size:18})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h5",{className:"truncate text-sm font-black text-slate-900",children:t.name}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[10px] font-black uppercase tracking-wide ${t.status==="validated"?"bg-emerald-50 text-emerald-700":t.status==="in_review"?"bg-amber-50 text-amber-700":t.status==="archived"?"bg-slate-100 text-slate-500":"bg-brand-50 text-brand-700"}`,children:t.status.replace("_"," ")})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-3 gap-y-1 text-[11px] font-medium text-slate-500",children:e.jsx("span",{children:Us[t.id]?`Last validated ${Q(Us[t.id])}`:`Updated ${Q(t.updatedAt)}`})})]})]}),e.jsxs("button",{type:"button",onClick:()=>D(`/flowcharts/${t.id}`),className:"inline-flex shrink-0 items-center justify-center gap-1.5 rounded-lg bg-brand-700 px-3 py-2 text-xs font-bold text-white transition hover:bg-brand-800",children:["View flowchart ",e.jsx(Dt,{size:14})]})]}),e.jsx("div",{className:"border-t border-slate-100 bg-slate-50 px-5 py-2.5 text-[11px] font-medium text-slate-500",children:"This control is linked to a process node in this flowchart."})]},t.id))]})}),X==="attestations"&&e.jsx("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Attestation History",icon:e.jsx($e,{size:16})}),e.jsxs("div",{className:"space-y-3",children:[H.length===0&&ve.length===0&&e.jsxs("div",{className:"rounded-xl border border-dashed border-slate-300 bg-white px-6 py-12 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 flex h-11 w-11 items-center justify-center rounded-xl bg-slate-100 text-slate-400",children:e.jsx($e,{size:21})}),e.jsx("h5",{className:"text-sm font-bold text-slate-700",children:"No attestation history yet"}),e.jsx("p",{className:"mx-auto mt-1 max-w-sm text-xs leading-relaxed text-slate-500",children:"No signed control attestations or SOX sub-certifications have been recorded for this control."}),e.jsxs("button",{type:"button",onClick:()=>D("/attestation"),className:"mt-4 inline-flex items-center gap-1.5 text-xs font-bold text-brand-700 transition hover:text-brand-900",children:["Open Control Attestation ",e.jsx(Dt,{size:14})]})]}),ve.map(({campaign:t,request:a})=>{const i=(a.controlSuggestions||[]).filter(c=>c.controlId===s.controlId),r=a.status==="SIGNED_WITH_EXCEPTIONS";return e.jsxs("div",{className:"rounded-xl border border-teal-200 bg-teal-50/30 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h5",{className:"truncate text-sm font-bold text-slate-900",children:t.name}),e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold ${r?"bg-rose-100 text-rose-700":"bg-emerald-100 text-emerald-700"}`,children:r?"SIGNED WITH EXCEPTIONS":"SIGNED"}),e.jsx("span",{className:"inline-flex items-center rounded-full bg-teal-100 px-2 py-0.5 text-[10px] font-bold text-teal-700",children:"SOX certification"})]}),e.jsxs("p",{className:"mt-1 text-xs text-slate-500",children:[t.period," · signed by ",a.signedByName||a.signerName,a.signedAt?` on ${Q(a.signedAt)}`:""]})]}),e.jsxs("button",{type:"button",onClick:()=>ms(t,a),className:"inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-teal-600 px-3 py-1.5 text-[10px] font-bold text-white transition hover:bg-teal-700",children:[e.jsx(Rt,{size:13})," View signed PDF"]})]}),i.length>0?e.jsxs("div",{className:"mt-4 rounded-lg border border-amber-200 bg-white p-3",children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-[0.12em] text-amber-700",children:"Proposed RCM updates from this certification"}),e.jsx("div",{className:"mt-3 space-y-3",children:i.map((c,o)=>e.jsxs("div",{className:"grid gap-2 rounded-md border border-slate-100 bg-slate-50 p-3 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-[10px] font-bold uppercase tracking-wide text-slate-400",children:[Ft(c.field)," · frozen value"]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-xs text-slate-700",children:c.originalValue||"â"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-wide text-teal-700",children:"Suggested value"}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-xs font-medium text-teal-800",children:c.suggestedValue})]})]},`${c.field}-${o}`))})]}):e.jsx("p",{className:"mt-3 text-xs text-slate-500",children:"No RCM updates were proposed for this control."})]},`certification-${a.id}`)}),H.map(({campaign:t,request:a})=>{var d;const i=Ra(a,s.id),r=(d=a.responses)==null?void 0:d.find(l=>l.controlDocId===s.id),c=(r==null?void 0:r.respondedAt)||a.signedAt,o=a.signedByName;return e.jsxs("div",{className:"w-full rounded-lg border border-slate-200 bg-white p-4 text-left shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h5",{className:"truncate text-sm font-bold text-slate-900",children:t.name}),e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold ${i==="COMPLETED"?"bg-emerald-50 text-emerald-700":i==="OVERDUE"?"bg-red-50 text-red-700":"bg-amber-50 text-amber-700"}`,children:i.replace("_"," ")})]}),e.jsxs("div",{className:"mt-1 text-xs font-medium text-slate-500 flex gap-2",children:[e.jsxs("span",{children:["Period: ",t.period]}),e.jsx("span",{children:"â¢"}),e.jsxs("span",{children:["Assigned to: ",a.ownerName]})]})]}),e.jsxs("button",{onClick:()=>Ye({request:a,campaign:t}),className:"flex items-center gap-1.5 px-3 py-1.5 bg-brand-50 text-brand-700 rounded-lg text-[10px] font-bold hover:bg-brand-100 transition whitespace-nowrap",children:["View Form ",e.jsx(Et,{size:12})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-4 text-[11px] text-slate-600 bg-slate-50/50 p-2 rounded-lg border border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xr,{size:12,className:"text-slate-400"}),e.jsxs("span",{children:["Due: ",Rs(a.dueDate)]})]}),i==="COMPLETED"&&c?e.jsxs("div",{className:"flex items-center gap-1 text-emerald-600",children:[e.jsx(Be,{size:12}),e.jsxs("span",{children:["Signed: ",Q(c)," by ",o]})]}):e.jsxs("div",{className:"flex items-center gap-1 text-amber-600",children:[e.jsx(ur,{size:12}),e.jsx("span",{children:"Pending Signature"})]})]})]},a.id)})]})]})}),X==="logs"&&e.jsx(Fr,{logs:ii,controlId:s.id})]}),ct.open&&J&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 backdrop-blur-sm animate-in fade-in",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl w-full max-w-md p-6 m-4",onClick:t=>t.stopPropagation(),children:[e.jsx("div",{className:"bg-red-50 w-12 h-12 rounded-full flex items-center justify-center mb-4",children:e.jsx(Me,{className:"text-red-600",size:24})}),e.jsx("h3",{className:"text-lg font-bold text-slate-900 mb-2",children:"Delete test result?"}),e.jsxs("p",{className:"text-sm text-slate-600 mb-6",children:["This will permanently remove ",e.jsxs("span",{className:"font-semibold",children:['"',ct.displayName,'"']})," from your test history. This cannot be undone."]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>Kt({open:!1,runId:null,displayName:""}),className:"px-4 py-2 text-slate-600 font-bold hover:bg-slate-100 rounded-lg transition",disabled:Xt,children:"Cancel"}),e.jsxs("button",{onClick:async()=>
8{if(ct.runId){Ws(!0);try{await Z.deleteTestRun(ct.runId);const t=await Z.getControlTestRuns(s.id);zt(t),Kt({open:!1,runId:null,displayName:""})}catch{alert("Failed to delete test result. Please try again.")}finally{Ws(!1)}}},className:"px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-bold rounded-lg transition flex items-center gap-2",disabled:Xt,children:[Xt&&e.jsx(ee,{size:16,className:"animate-spin"}),"Delete"]})]})]})}),me&&e.jsx("div",{className:"fixed inset-0 z-[100] bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden animate-in fade-in zoom-in-95 duration-200",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/50",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-black text-slate-900",children:"Attestation Record"}),e.jsxs("p",{className:"text-[10px] text-slate-500 font-medium",children:["Period: ",me.campaign.period]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:()=>{var i;const t=(i=document.getElementById("attestation-print-view"))==null?void 0:i.innerHTML;if(!t)return;const a=document.body.innerHTML;document.body.innerHTML=t,window.print(),document.body.innerHTML=a,window.location.reload()},className:"flex items-center gap-1.5 px-3 py-1.5 bg-slate-100 text-slate-600 rounded-lg text-xs font-bold hover:bg-slate-200 transition",children:"Print"}),e.jsx("button",{onClick:()=>Ye(null),className:"p-1.5 hover:bg-slate-200 rounded-lg text-slate-400 transition",children:e.jsx(ae,{size:18})})]})]}),e.jsx("div",{id:"attestation-print-view",className:"p-8 overflow-y-auto bg-slate-50/30 flex-1 space-y-8",children:(()=>{var a,i;const t=(a=me.request.responses)==null?void 0:a.find(r=>r.controlDocId===s.id);return t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-center space-y-2 mb-8",children:[e.jsx("h2",{className:"text-xl font-black text-slate-900 uppercase tracking-tight",children:"Control Attestation Record"}),e.jsxs("div",{className:"text-sm text-slate-600 font-medium",children:["Control: ",s.controlId," - ",s.name]}),e.jsxs("div",{className:"text-xs text-slate-500",children:["Signed: ",we(me.request.signedAt)," by ",me.request.signedByName]})]}),e.jsx("div",{className:"space-y-6",children:(i=t.fieldResponses)==null?void 0:i.map(r=>{var c;return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 border-b border-slate-100 pb-2",children:[e.jsx("span",{className:"text-xs font-black text-slate-700 uppercase tracking-wider",children:((c=Ze.find(o=>o.field===r.field))==null?void 0:c.label)||r.field}),r.isAccurate?e.jsxs("span",{className:"flex items-center gap-1 text-[10px] font-bold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full",children:[e.jsx(Be,{size:10})," Attested Accurate"]}):e.jsxs("span",{className:"flex items-center gap-1 text-[10px] font-bold text-amber-600 bg-amber-50 px-2 py-0.5 rounded-full",children:[e.jsx(br,{size:10})," Suggested Change"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[9px] font-bold text-slate-400 uppercase mb-1",children:"Value at Attestation"}),e.jsx("div",{className:"text-sm text-slate-900 font-medium whitespace-pre-wrap",children:li(r.field)||e.jsx("span",{className:"text-slate-400 italic",children:"No value"})})]}),!r.isAccurate&&e.jsxs("div",{className:"bg-amber-50/50 p-3 rounded-lg border border-amber-100",children:[e.jsx("div",{className:"text-[9px] font-bold text-amber-600 uppercase mb-1",children:"Suggested Update"}),e.jsx("div",{className:"text-sm text-amber-900 font-medium whitespace-pre-wrap",children:r.suggestedValue||e.jsx("span",{className:"text-amber-700/50 italic",children:"No suggested value"})})]})]})]},r.field)})}),e.jsx("div",{className:"mt-12 pt-8 border-t-2 border-slate-200",children:e.jsxs("div",{className:"max-w-md
8space-y-1",children:[e.jsx("div",{className:"text-[10px] font-black text-slate-400 uppercase tracking-widest",children:"Electronic Signature"}),e.jsx("div",{className:"text-xl font-signature text-slate-900 border-b border-slate-300 pb-2 mb-2",children:me.request.signedByName}),e.jsxs("div",{className:"flex justify-between text-[10px] text-slate-500 font-medium",children:[e.jsxs("span",{children:["IP: ",me.request.signedFromIp||"Unknown"]}),e.jsx("span",{children:we(me.request.signedAt)})]})]})})]}):e.jsx("div",{className:"text-center py-8 text-slate-500",children:"No response data found for this control."})})()})]})}),K&&e.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center bg-slate-950/65 p-4 backdrop-blur-sm",children:e.jsxs("div",{className:"flex h-[88vh] w-full max-w-6xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-slate-200 px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-black text-slate-900",children:"Signed certification"}),e.jsx("p",{className:"mt-1 text-[11px] text-slate-500",children:"Frozen letter, acknowledgements, control register, and electronic-signature audit trail."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("a",{href:K.url,download:K.filename,className:"inline-flex items-center gap-1.5 rounded-lg bg-teal-600 px-3 py-2 text-xs font-bold text-white hover:bg-teal-700",children:[e.jsx(za,{size:14})," Download PDF"]}),e.jsx("button",{type:"button",onClick:()=>qs(null),className:"rounded-lg border border-slate-200 px-3 py-2 text-xs font-bold text-slate-600 hover:bg-slate-50",children:"Close"})]})]}),e.jsx("iframe",{title:"Signed certification PDF",src:K.url,className:"min-h-0 flex-1 bg-slate-100"})]})}),Qt&&e.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center bg-slate-900/45 p-4 backdrop-blur-sm",role:"dialog","aria-modal":"true","aria-labelledby":"control-contact-dialog-title",onClick:()=>ht(null),children:e.jsxs("div",{className:"w-full max-w-md overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl animate-in fade-in zoom-in-95 duration-200",onClick:t=>t.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between border-b border-slate-100 bg-teal-50/70 px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-black uppercase tracking-[0.16em] text-teal-700",children:"Control contact"}),e.jsxs("h3",{id:"control-contact-dialog-title",className:"mt-1 text-base font-black text-slate-900",children:[Qt.role==="owner"?"Control owner":"Preparer"," details"]})]}),e.jsx("button",{onClick:()=>ht(null),className:"rounded-lg p-1.5 text-slate-400 transition hover:bg-white hover:text-slate-700","aria-label":"Close contact details",children:e.jsx(ae,{size:18})})]}),e.jsx("div",{className:"max-h-[55vh] space-y-3 overflow-y-auto p-5",children:Qt.contacts.map((t,a)=>e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50/70 p-4",children:[e.jsx("p",{className:"text-sm font-bold text-slate-900",children:t.name||"Unnamed contact"}),t.email?e.jsxs("a",{href:`mailto:${t.email}`,className:"mt-1.5 inline-flex items-center gap-1.5 text-xs font-bold text-teal-700 transition hover:text-teal-900 hover:underline",children:[e.jsx(hr,{size:13}),t.email]}):e.jsx("p",{className:"mt-1.5 text-xs font-medium text-slate-400",children:"No email address on file"})]},`${t.name}-${t.email}-${a}`))})]})}),Qa&&ds&&u&&I&&e.jsx(nr,{workspaceId:u,currentUserId:I.uid,currentUserName:I.displayName||I.email||void 0,controls:[s],workspaceMembers:es,prefillControlId:s.id,onClose:()=>nt(!1),onCreated:()=>nt(!1)})]})},Ua=({isEditing:s,label:p,contacts:h,icon:u,onChange:A,onViewContacts:k,workspaceMembers:j,isLoadingWorkspaceMembers:w})=>{const g=p==="Control Owner"?"owner":"preparer",[N,P]=b.useState(null),F=b.useMemo(()=>[...j].sort((m,L)=>(m.displayName||m.email).localeCompare(L.displayName||L.email)),[j]),C=(m,L,v)=>{A(h.map((T,n)=>n===m?{...T,[L]:v}:T))},D=(m,L)=>{const v=F.find(T=>T.uid===L);v&&(A(h.map((T,n)=>n===m?{...T,name:v.displayName||v.email,email:v.email}:T)),P(null))};return e.jsxs("div",{className:"min-h-[84px] rounded-xl border border-slate-100 bg-white p-3 shadow-sm",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1.5 text-slate-400",children:[u,e.jsx("span",{className:"text-[10px] font-black uppercase tracking-widest",children:p})]}),s?e.jsxs("div",{className:"space-y-2",children:[h.map((m,L)=>e.jsx("div",{className:"space-y-1.5",children:e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_24px] items-center gap-1.5",children:[e.jsxs("div",{className:"relative min-w-0",children:[e.jsx("input",{className:"w-full min-w-0 rounded border border-slate-200 bg-slate-50 px-2 py-1 text-xs font-bold outline-none focus:border-teal-400 focus:ring-2 focus:ring-teal-100",value:m.name,onFocus:()=>P(L),onBlur:()=>window.setTimeout(()=>P(null),120),onChange:v=>{C(L,"name",v.target.value),P(L)},onKeyDown:v=>{v.key==="Escape"&&P(null)},placeholder:"Search or enter name","aria-label":`${p} ${L+1} name`,"aria-autocomplete":"list","aria-expanded":N===L}),N===L&&e.jsx("div",{className:"absolute left-0 top-full z-30 mt-1 w-[min(18rem,calc(100vw-3rem))] overflow-hidden rounded-lg border border-slate-200 bg-white py-1 shadow-lg shadow-slate-900/10",children:w?e.jsx("p",{className:"px-3 py-2 text-xs font-medium text-slate-500",children:"Loading workspace membersâ¦"}):(()=>{const v=m.name.trim().toLowerCase(),T=v?F.filter(n=>`${n.displayName} ${n.email}`.toLowerCase().includes(v)).slice(0,6):[];return v?T.length===0?e.jsx("p",{className:"px-3 py-2 text-xs font-medium text-slate-500",children:"No workspace member matches. You can keep this as a manual contact."}):T.map(n=>e.jsxs("button",{type:"button",onMouseDown:S=>{S.preventDefault(),D(L,n.uid)},className:"flex w-full flex-col px-3 py-2 text-left transition hover:bg-teal-50 focus:bg-teal-50 focus:outline-none",children:[e.jsx("span",{className:"truncate text-xs font-bold text-slate-800",children:n.displayName||n.email}),e.jsx("span",{className:"truncate text-[11px] font-medium text-teal-700",children:n.email})]},n.uid)):e.jsx("p",{className:"px-3 py-2 text-xs font-medium text-slate-500",children:"Type to search workspace members."})})()})]}),e.jsx("input",{className:"min-w-0 rounded border border-slate-200 bg-slate-50 px-2 py-1 text-xs font-medium outline-none focus:border-teal-400 focus:ring-2 focus:ring-teal-100",type:"email",value:m.email||"",onChange:v=>C(L,"email",v.target.value),placeholder:"[email protected]","aria-label":`${p} ${L+1} email`}),e.jsx("button",{type:"button",onClick:()=>A(h.filter((v,T)=>T!==L)),className:"rounded p-1 text-slate-400 transition hover:bg-red-50 hover:text-red-600","aria-label":`Remove ${g} ${L+1}`,children:e.jsx(ae,{size:14})})]})},`${g}-${L}`)),e.jsxs("button",{type:"button",onClick:()=>A([...h,{name:"",email:""}]),className:"inline-flex items-center gap-1 text-[11px] font-bold text-teal-700 transition hover:text-teal-900",children:[e.jsx(Ue,{size:13})," Add ",g]}
8)]}):h.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:h.map((m,L)=>e.jsx("button",{type:"button",onClick:()=>k([m]),className:"max-w-full truncate rounded-md bg-teal-50 px-2 py-1 text-left text-xs font-bold text-teal-800 transition hover:bg-teal-100 hover:text-teal-950 focus:outline-none focus:ring-2 focus:ring-teal-300",title:`View ${m.name||"contact"} email`,children:m.name||m.email},`${m.name}-${m.email}-${L}`))}):e.jsx("div",{className:"text-sm font-bold text-slate-400",children:"Not assigned"})]})},_e=({isEditing:s,label:p,value:h,icon:u,onChange:A,options:k,color:j="text-slate-900",onClick:w,onClickLabel:g})=>{const N=!s&&!!w,P="bg-white border border-slate-100 p-3 rounded-xl shadow-sm",F=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-400 mb-1",children:[u,e.jsx("span",{className:"text-[10px] font-black uppercase tracking-widest",children:p})]}),s?k?e.jsx("select",{className:"w-full text-xs font-bold bg-slate-50 border border-slate-200 rounded p-1 outline-none",value:h,onChange:C=>A(C.target.value),children:k.map(C=>e.jsx("option",{value:C,children:C},C))}):e.jsx("input",{className:"w-full text-xs font-bold bg-slate-50 border border-slate-200 rounded p-1 outline-none",value:h,onChange:C=>A(C.target.value)}):e.jsx("div",{className:`text-sm font-bold ${j}`,children:h})]});return N?e.jsx("button",{type:"button",onClick:w,"aria-label":g||`${p}: ${h}`,title:g,className:`group w-full text-left ${P} cursor-pointer transition-shadow hover:shadow-md hover:border-brand-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 focus-visible:ring-offset-2`,children:F}):e.jsx("div",{className:P,children:F})},Fr=({logs:s,controlId:p})=>{const[h,u]=b.useState(new Set),A=j=>{u(w=>{const g=new Set(w);return g.has(j)?g.delete(j):g.add(j),g})},k=s.filter(j=>j.controlId===p);return e.jsx("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300",children:e.jsxs("section",{className:"space-y-4",children:[e.jsx(G,{title:"Audit History",icon:e.jsx(Ps,{size:16})}),e.jsxs("div",{className:"space-y-2",children:[k.map(j=>{var n,S,Ae,ne,ke,be,Ve,We;const w=h.has(j.id),g=j.changes&&j.changes.length>0,N=j.action==="ATTESTATION"||((n=j.details)==null?void 0:n.startsWith("Attestation submitted")),P=j.action==="CERTIFICATION"||((S=j.details)==null?void 0:S.startsWith("SOX certification signed")),F=((Ae=j.details)==null?void 0:Ae.startsWith("Attestation suggestion accepted"))||((ne=j.details)==null?void 0:ne.startsWith("Legacy attestation suggestion applied"));j.action==="SUGGESTION"||((ke=j.details)==null||ke.startsWith("RCM suggestion "));const C=(be=j.details)!=null&&be.startsWith("RCM suggestion submitted")?"submitted":(Ve=j.details)!=null&&Ve.startsWith("RCM suggestion applied")?"applied":(We=j.details)!=null&&We.startsWith("RCM suggestion declined")?"declined":null,D=j.action==="FLOWCHART_VALIDATED",m=N||P||F,L=C==="submitted"?w?"bg-amber-500":"bg-amber-200 group-hover:bg-amber-400":C==="applied"?w?"bg-emerald-500":"bg-emerald-200 group-hover:bg-emerald-400":C==="declined"?w?"bg-rose-500":"bg-rose-200 group-hover:bg-rose-400":D?w?"bg-emerald-500":"bg-emerald-200 group-hover:bg-emerald-400":P?w?"bg-teal-500":"bg-teal-200 group-hover:bg-teal-400":N?w?"bg-violet-500":"bg-violet-200 group-hover:bg-violet-400":F?w?"bg-amber-500":"bg-amber-200 group-hover:bg-amber-400":w?"bg-brand-500":"bg-slate-200 group-hover:bg-brand-400",v=C==="submitted"?"RCM SUGGESTION":C==="applied"?"SUGGESTION APPLIED":C==="declined"?"SUGGESTION DECLINED":D?"FLOWCHART VALIDATED":P?"SOX CERTIFICATION":N?"ATTESTATION":F?"SUGGESTION APPLIED":j.action,T=C==="submitted"?"text-amber-700":C==="applied"?"text-emerald-700":C==="declined"?"text-rose-700":D?"text-emerald-700":P?"text-teal-700":N?"text-violet-700":F?"text-amber-700":"text-slate-800";return e.jsxs("div",{className:"rounded-lg border border-slate-100 overflow-hidden transition-all",children:[e.jsxs("button",{onClick:()=>g&&A(j.id),className:`w-full flex gap-3 p-3 text-left transition group ${g?"hover:bg-slate-50 cursor-pointer":"cursor-default"}`,children:[e.jsx("div",{className:`w-1 rounded-full flex-shrink-0 transition-colors ${L}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-black uppercase tracking-tighter ${T}`,children:v}),g&&e.jsxs("span",{className:"text-[9px] text-slate-400 font-medium bg-slate-100 px-1.5 py-0.5 rounded",children:[j.changes.length," ",j.changes.length===1?"change":"changes"]}),m&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded ${P?"bg-teal-50 text-teal-700":N?"bg-vi
8olet-50 text-violet-600":"bg-amber-50 text-amber-600"}`,children:P||N?"âï¸ Signed":"â
Applied"}),C&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded ${C==="submitted"?"bg-amber-50 text-amber-700":C==="applied"?"bg-emerald-50 text-emerald-700":"bg-rose-50 text-rose-700"}`,children:C==="submitted"?"Proposed":C==="applied"?"â Applied":"Declined"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-medium",children:we(j.timestamp)}),g&&(w?e.jsx(Ds,{size:12,className:"text-slate-400"}):e.jsx(Wa,{size:12,className:"text-slate-400"}))]})]}),e.jsx("p",{className:"text-xs text-slate-500 mt-1 truncate",children:j.details}),e.jsxs("p",{className:"text-[9px] text-brand-600 font-bold uppercase mt-1",children:["By: ",j.performedBy]})]})]}),w&&g&&e.jsx("div",{className:"border-t border-slate-100 bg-slate-50/50 px-4 py-3 space-y-2 animate-in fade-in slide-in-from-top-1 duration-200",children:j.changes.map((x,it)=>e.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[e.jsx("span",{className:"text-[10px] font-black text-slate-700 uppercase tracking-wider",children:x.field}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-1 ml-2",children:[e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx("span",{className:"text-[9px] font-bold text-red-400 mt-0.5 flex-shrink-0 w-8",children:"OLD"}),e.jsx("span",{className:"text-[11px] text-red-600 bg-red-50 px-2 py-1 rounded break-words line-clamp-3",children:x.oldValue||"(empty)"})]}),e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx("span",{className:"text-[9px] font-bold text-emerald-400 mt-0.5 flex-shrink-0 w-8",children:"NEW"}),e.jsx("span",{className:"text-[11px] text-emerald-700 bg-emerald-50 px-2 py-1 rounded break-words line-clamp-3",children:x.newValue||"(empty)"})]})]})]},it))})]},j.id)}),k.length===0&&e.jsx("p",{className:"text-xs text-slate-400 text-center py-8",children:"No audit history for this control."})]})]})})},G=({title:s,icon:p})=>e.jsxs("h4",{className:"flex items-center gap-2 text-xs font-black text-slate-900 uppercase tracking-widest border-b border-slate-100 pb-2",children:[p,s]}),Xa=({value:s,isEditing:p,onChange:h})=>{const u=Lr(s),A=u.length>0?u:p?[{name:"A",description:""}]:[],k=(g,N,P)=>{const F=A.map((C,D)=>D===g?{...C,[N]:P}:C);h==null||h(As(F))},j=g=>{h==null||h(As(A.filter((N,P)=>P!==g)))},w=()=>{const g=u.length>0?u:A;h==null||h(As([...g,{name:_t(g.length),description:""}]))};return e.jsxs("div",{className:"overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[640px] table-fixed border-collapse text-left",children:[e.jsx("thead",{className:"bg-brand-50/70",children:e.jsxs("tr",{className:"border-b border-brand-100",children:[e.jsx("th",{className:"w-40 px-4 py-3 text-[10px] font-black uppercase tracking-widest text-brand-900",children:"Attribute"}),e.jsx("th",{className:"px-4 py-3 text-[10px] font-black uppercase tracking-widest text-brand-900",children:"Attribute Description"}),p&&e.jsx("th",{className:"w-14 px-2 py-3",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{className:"divide-y divide-slate-200",children:A.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:2,className:"px-4 py-8 text-center text-sm italic text-slate-400",children:"No attributes defined."})}):A.map((g,N)=>e.jsxs("tr",{className:"group align-top transition-colors hover:bg-slate-50/70",children:[e.jsx("td",{className:"border-r border-slate-200 p-0",children:p?e.jsx("input",{value:g.name,onChange:P=>k(N,"name",P.target.value),"aria-label":`Attribute name ${N+1}`,className:"h-full min-h-16 w-full bg-transparent px-4 py-3 text-sm font-black uppercase text-slate-900 outline-none transition focus:bg-white focus:ring-2 focus:ring-inset focus:ring-brand-500",placeholder:_t(N)}):e.jsx("div",{className:"px-4 py-3 text-sm font-black text-slate-900",children:g.name})}),e.jsx("td",{className:"p-0",children:p?e.jsx("textarea",{value:g.de
8scription,onChange:P=>k(N,"description",P.target.value),"aria-label":`Attribute description ${g.name||N+1}`,className:"min-h-16 w-full resize-y bg-transparent px-4 py-3 text-sm font-medium leading-6 text-slate-900 outline-none transition focus:bg-white focus:ring-2 focus:ring-inset focus:ring-brand-500",placeholder:"Describe the test procedure..."}):e.jsx("div",{className:"whitespace-pre-wrap px-4 py-3 text-sm font-medium leading-6 text-slate-800",children:g.description||"â"})}),p&&e.jsx("td",{className:"px-2 py-3 text-center",children:e.jsx("button",{type:"button",onClick:()=>j(N),className:"rounded-md p-2 text-slate-300 transition hover:bg-red-50 hover:text-red-600 focus:outline-none focus:ring-2 focus:ring-red-300",title:`Delete attribute ${g.name||N+1}`,"aria-label":`Delete attribute ${g.name||N+1}`,children:e.jsx(Me,{size:15})})})]},N))})]})}),p&&e.jsxs("button",{type:"button",onClick:w,className:"flex w-full items-center gap-2 border-t border-slate-200 bg-slate-50 px-4 py-3 text-xs font-bold text-brand-700 transition hover:bg-brand-50 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-brand-500",children:[e.jsx(Ue,{size:14})," Add attribute"]})]})},Or=({value:s,onApply:p})=>e.jsxs("div",{className:"rounded-lg border border-brand-100 bg-brand-50 p-3 animate-in fade-in slide-in-from-top-1",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ya,{className:"mt-0.5 shrink-0 text-brand-500",size:14}),e.jsx("p",{className:"mb-1 flex-1 text-xs font-medium text-brand-700",children:"AI Suggestion for Testing Attributes"}),e.jsx("button",{type:"button",onClick:p,className:"shrink-0 rounded border border-brand-200 bg-white px-3 py-1 text-xs font-bold text-brand-600 shadow-sm hover:bg-brand-50",children:"Apply table"})]}),e.jsx("div",{className:"mt-2",children:e.jsx(Xa,{value:s,isEditing:!1})})]}),B=({fieldName:s,text:p,onApply:h})=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-brand-100 bg-brand-50 p-3 animate-in fade-in slide-in-from-top-1",children:[e.jsx(Ya,{className:"mt-0.5 shrink-0 text-brand-500",size:14}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"mb-1 text-xs font-medium text-brand-700",children:["AI Suggestion for ",s]}),e.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-slate-800",children:p})]}),e.jsx("button",{type:"button",onClick:h,className:"shrink-0 rounded border border-brand-200 bg-white px-3 py-1 text-xs font-bold text-brand-600 shadow-sm hover:bg-brand-50",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ze,{size:12})," Apply"]})})]});export{jn as ControlDetail};
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.