PageSourceSearch

https://iabuddy.ai/assets/WorkpaperView-Qpb9Eqr5.js

js iabuddy.ai collected 2026-10-05 15:22:47 UTC 75,496 bytes, 28 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CIStryfq.css"])))=>i.map(i=>d[i]);
2import{j as e,_ as ee,r as rs,s as as,k as ns,l as os}from"./index-BSaWd9L_.js";import{r as i,R as ft}from"./react-router-6IwkzgbN.js";import{a as Ft}from"./react-dom-CBCeEX-5.js";import{D as is,P as ls,g as cs,v as ds,G as us}from"./index-DqoObOmM.js";import{s as ms}from"./ocr-BeklWGL7.js";import{bg as fs,bh as xs,bi as zt,b as St,bj as At,L as le,a1 as qt,z as Ge,X as Gt,_ as ps,b4 as hs,F as Zt,bk as Rt,J as Mt,T as Jt,f as bs,az as gs,d as It,aW as ws,as as Lt,aA as vs,aB as ys,j as $t,ax as js,aC as Ns,an as Ps,a4 as Ss,R as Bt,bl as Ts,bm as _s,bn as ks,a as Es,aG as Ds,bo as Cs}from"./ui-icons-DPTVeI4b.js";import{P as Yt}from"./pdf-lib-C72b0oxm.js";import{p as Fs,c as Be,q as zs,u as As}from"./AuthenticatedApp-CCl0jXQV.js";import{p as Rs}from"./planningService-DOpJY0JT.js";import{b as Ms,a as Is}from"./dateUtils-BXjtmOLV.js";import{storage as Ht,functions as Ls}from"./firebase-BNIkhQ9j.js";import{httpsCallable as $s}from"./firebase-functions-Co__ct4K.js";import{r as Wt,c as Bs,d as Hs,b as Ws}from"./firebase-storage-C6V6HrQd.js";import{u as Us,S as Vs}from"./useUndoRedo-B2zDMr3M.js";import{u as Os}from"./useDocumentTitle-WXljKUO9.js";import{read as Xs,utils as Ut}from"./xlsx-Bb_VIWOD.js";import"./firebase-core-DWzFmatk.js";import"./firebase-firestore--QWOY731.js";import"./clsx-B-dksMZM.js";import"./AuthBoundRoutes-DjP5sABm.js";import"./firebase-auth-Ci-ASzqO.js";import"./tokenService-CnhF7_3j.js";import"./workspaceService-D0JmegHK.js";import"./index-tXXNEbmK.js";import"./samplingEngine-D1Bxb3J7.js";us.workerSrc=`https://unpkg.com/pdfjs-dist@${ds}/legacy/build/pdf.worker.min.mjs`;const qs=({content:a,isEditing:t,style:c,onInput:o,onBlur:s,onMouseDown:v,onDoubleClick:d})=>{const g=i.useRef(null);return i.useEffect(()=>{g.current&&g.current.innerHTML!==a&&(t?g.current.innerHTML===""&&(g.current.innerHTML=a||""):g.current.innerHTML=a||"")},[a,t]),e.jsx("div",{ref:g,contentEditable:t,suppressContentEditableWarning:!0,className:`w-full h-full outline-none leading-tight ${t?"cursor-text ":"cursor-default"}`,style:{...c,minHeight:"1em"},onInput:o,onBlur:s,onMouseDown:v,onDoubleClick:d})},Vt=a=>{switch(a){case"Courier":return'"Courier New", Courier, monospace';case"Times-Roman":return'"Times New Roman", Times, serif';case"Arial":return"Arial, Helvetica, sans-serif";case"Verdana":return"Verdana, Geneva, sans-serif";case"Georgia":return"Georgia, serif";case"Garamond":return"Garamond, serif";case"Trebuchet MS":return'"Trebuchet MS", sans-serif';case"Helvetica":default:return"Helvetica, Arial, sans-serif"}},Gs=({pdfUrl:a,selectedTool:t,annotations:c,setAnnotations:o,scale:s,attributeStatuses:v={},searchQuery:d,currentMatchIndex:g,onSearchResults:y,readOnly:m=!1,onEditingChange:u,pageControlsContainer:w=null,textStyleControlsContainer:j=null,navigationTarget:k=null,onNavigationStateChange:N})=>{const[C,T]=i.useState(null),[F,z]=i.useState(1),[Z,ae]=i.useState(null),te=i.useRef(null),H=i.useRef(new Map),se=i.useRef({pageNumber:1,offsetWithinPage:0}),ne=i.useRef(!1),[I,G]=i.useState(!1),[fe,ce]=i.useState(null),[xe,ge]=i.useState(null),[W,oe]=i.useState(null),[p,q]=i.useState([]),[de,we]=i.useState([]),[pt,h]=i.useState(!1);i.useEffect(()=>{if(!a){q([]);return}let r=!1,f=null,x=null;return(async()=>{try{f=cs(a);const n=await f.promise;if(r)return;const S=n.numPages,$=[];let L=!1;for(let X=1;X<=S;X++){const U=await n.getPage(X),Y=U.getViewport({scale:1}),B=await U.getTextContent();B.items.length>5&&(L=!0),B.items.forEach(Q=>{$.push({...Q,pageIndex:X,pageWidth:Y.width,pageHeight:Y.height})})}if(!L&&S>0){if(console.log("Low text content detected, initiating OCR..."),r)return;if(h(!0),q([]),x=await ms.createWorker("eng"),r){await x.terminate(),x=null;return}const X=[];for(let U=1;U<=S;U++){const Y=await n.getPage(U),B=2,Q=Y.getViewport({scale:B}),_=document.createElement("canvas"),ie=_.getContext("2d");if(ie){_.height=Q.height,_.width=Q.width,await Y.render({canvasContext:ie,viewport:Q}).promise;const K=_.toDataURL("image/png"),ue=await x.recognize(K);if(r)return;const Oe=ue.data.words||[],Xe=Y.getViewport({scale:1});Oe.forEach(pe=>
2{const ot=pe.bbox.x0/B,qe=pe.bbox.y0/B,wt=pe.bbox.x1/B,it=pe.bbox.y1/B,vt=wt-ot,lt=it-qe,yt=Xe.height-qe-lt;X.push({str:pe.text,width:vt,height:lt,transform:[1,0,0,1,ot,yt],pageIndex:U,pageWidth:Xe.width,pageHeight:Xe.height})})}}await x.terminate(),x=null,r||(q(X),h(!1))}else r||q($)}catch(n){if(r)return;console.error("Failed to extract PDF text:",n),h(!1)}})(),()=>{r=!0,f==null||f.destroy(),x&&x.terminate()}},[a]),i.useEffect(()=>{if(!d||d.trim()===""){y([]),we([]);return}const r=d.toLowerCase(),f=p.filter(x=>x.str.toLowerCase().includes(r));we(f),y(f)},[d,p,y]),i.useEffect(()=>{if(g>=0&&g<de.length){const r=de[g];r.pageIndex!==F&&z(r.pageIndex)}},[g,de]);const[O,V]=i.useState(null),[je,Ze]=i.useState(!1),[ve,Re]=i.useState({x:0,y:0}),[Pe,He]=i.useState(null),[J,Me]=i.useState(null),We=i.useRef("");i.useEffect(()=>{u==null||u(!!J)},[J,u]);const[Ne,Ue]=i.useState("1");i.useEffect(()=>{Ue(F.toString())},[F]),i.useEffect(()=>{N==null||N({activePageNumber:F,selectedAnnotationId:O})},[N,F,O]),i.useEffect(()=>{if(!k||!C)return;const r=c.find(n=>n.id===k.annotationId&&n.type==="badge");if(!r)return;V(r.id),z(r.pageNumber);let f=0,x=0;const R=()=>{const n=te.current,S=H.current.get(r.pageNumber);if(!n||!S){x<8&&(x+=1,f=requestAnimationFrame(R));return}const $=r.y*s+15*s,L=S.offsetTop+$-n.clientHeight/2;n.scrollTo({top:Math.max(0,L),behavior:"smooth"})};return f=requestAnimationFrame(R),()=>cancelAnimationFrame(f)},[c,k==null?void 0:k.requestId,C,s]);const Je=()=>{const r=te.current;if(!r||ne.current)return;let f=F,x=H.current.get(f);const R=Array.from(H.current.entries()).filter(([,n])=>n.offsetTop<=r.scrollTop+1).sort(([,n],[,S])=>S.offsetTop-n.offsetTop)[0];R&&(f=R[0],x=R[1]),se.current={pageNumber:f,offsetWithinPage:Math.max(0,r.scrollTop-((x==null?void 0:x.offsetTop)||0))}},Ve=()=>{const r=se.current;let f=0;ne.current=!0;const x=()=>{const R=te.current,n=H.current.get(r.pageNumber);if(R&&n&&(R.scrollTop=n.offsetTop+r.offsetWithinPage,z(r.pageNumber)),f>=6){ne.current=!1;return}f+=1,requestAnimationFrame(x)};requestAnimationFrame(x)},ht=({numPages:r})=>{T(r),se.current.pageNumber>r&&(se.current={pageNumber:1,offsetWithinPage:0}),Ve()},bt=r=>{Z||ae({width:r.width,height:r.height})},Se=r=>{const f=H.current.get(r);f&&(f.scrollIntoView({behavior:"smooth"}),z(r))},Ye=r=>{const f=F+r;C&&f>=1&&f<=C&&Se(f)};i.useEffect(()=>{const r=te.current;if(!r||!C)return;const f=new IntersectionObserver(x=>{let R=0,n=-1;x.forEach(S=>{S.isIntersecting&&S.intersectionRatio>R&&(R=S.intersectionRatio,n=parseInt(S.target.getAttribute("data-page-number")||"1",10))}),n!==-1&&z(n)},{root:r,threshold:[.1,.5,.9]});return H.current.forEach(x=>{x&&f.observe(x)}),()=>f.disconnect()},[C,p,a]);const Ie=(r,f)=>{const x=f.getBoundingClientRect();return{x:(r.clientX-x.left)/s,y:(r.clientY-x.top)/s}},Ke=(r,f)=>{if(m)return;const x=r.currentTarget,R=Ie(r.nativeEvent,x),n=r.target.closest("[data-annotation-id]"),S=n==null?void 0:n.getAttribute("data-annotation-id");if(!(J&&S===J)){if(J&&S!==J&&tt(),S){if(V(S),t==="select"){const $=c.find(L=>L.id===S);$&&(Ze(!0),Re({x:R.x-$.x,y:R.y-$.y}),ge(f))}return}V(null),(t==="box"||t==="text")&&(G(!0),ce(R),ge(f),oe({x:R.x,y:R.y,width:0,height:0,type:t,pageNumber:f}))}},ye=(r,f,x)=>{if(m)return;r.stopPropagation(),r.preventDefault();const R=r.target.closest(".page-interaction-layer");if(!R)return;const n=Ie(r.nativeEvent,R);He({handle:x,startPoint:n,originalRect:{...f}}),V(f.id),ge(f.pageNumber)},Qe=(r,f)=>{if(m||!xe&&!je&&!Pe)return;const x=xe||f,R=H.current.get(x);if(!R)return;const n=Ie(r,R);if(Pe){const{handle:S,startPoint:$,originalRect:L}=Pe,X=n.x-$.x,U=n.y-$.y;let Y=L.x,B=L.y,Q=L.width,_=L.height;const ie=10;if(S.includes("e")&&(Q=Math.max(ie,L.width+X)),S.includes("w")){const K=L.width-X;K>ie&&(Y=L.x+X,Q=K)}if(S.includes("s")&&(_=Math.max(ie,L.height+U)),S.includes("n")){const K=L.height-U;K>ie&&(B=L.y+U,_=K)}o(K=>K.map(ue=>ue.id===L.id?{...ue,x:Y,y:B,width:Q,height:_}:ue));return}if(je&&O&&!J){o(S=>S.map($=>$.id===O?{...$,x:n.x-ve.x,y:n.y-ve.y}:$));return}if(I&&fe&&W){const S=Math.max(0,n.x-fe.x),$=Math.max(0,n.y-fe.y);oe({...W,width:S,height:$,x:fe.x,y:fe.y})}},re=()=>{if(!m){if(Pe){He(null),ge(null);return}if(je){Ze(!1),ge(null);return}if(I&&W&&xe){if(W.width&&W.width>5&&W.height&&W.height>
25){const r=Date.now().toString(),f={id:r,x:W.x,y:W.y,width:W.width,height:W.height,type:W.type,pageNumber:xe,content:W.type==="text"?"New Note":void 0,style:W.type==="text"?{fontFamily:"Helvetica",fontSize:14,fontWeight:"normal",fontStyle:"normal",color:"#dc2626",backgroundColor:"#ffffff"}:void 0};o(x=>[...x,f]),f.type==="text"&&(V(r),et(f))}G(!1),ce(null),oe(null),ge(null)}}},Te=(r,f)=>{m||(f&&f.stopPropagation(),o(x=>x.filter(R=>R.id!==r)),O===r&&V(null),J===r&&Me(null))},et=r=>{m||r.type==="text"&&(Me(r.id),We.current=r.content||"")},tt=()=>{m||J&&(o(r=>r.map(f=>f.id===J?{...f,content:We.current}:f)),Me(null))},gt=r=>{We.current=r.currentTarget.innerHTML},Le=(r,f)=>{document.execCommand(r,!1,f)},st=()=>Le("bold"),$e=()=>Le("italic"),_e=r=>Le("foreColor",r),rt=r=>{O&&o(f=>f.map(x=>x.id!==O?x:{...x,style:{...x.style||{},fontSize:r}}))},at=r=>Le("fontName",Vt(r)),ke=r=>{O&&o(f=>f.map(x=>x.id!==O?x:{...x,style:{...x.style||{},backgroundColor:r}}))},Ee=c.find(r=>r.id===O),Ce=800*s,nt=!m&&J&&Ee&&Ee.type==="text"&&e.jsxs("div",{className:`${j?"flex":"absolute bottom-5 left-1/2 z-[60] -translate-x-1/2"} items-center gap-3 rounded-lg border border-gray-200 bg-white px-3 py-2 shadow-xl`,children:[e.jsxs("select",{onChange:r=>at(r.target.value),className:"cursor-pointer border-none bg-transparent text-sm text-gray-700 outline-none",defaultValue:"Helvetica",children:[e.jsx("option",{value:"Helvetica",children:"Helvetica"}),e.jsx("option",{value:"Arial",children:"Arial"}),e.jsx("option",{value:"Times-Roman",children:"Times New Roman"}),e.jsx("option",{value:"Courier",children:"Courier New"}),e.jsx("option",{value:"Georgia",children:"Georgia"})]}),e.jsx("input",{type:"number",defaultValue:"14",min:"8",max:"72",onChange:r=>rt(parseInt(r.target.value)||14),className:"w-10 border-none bg-transparent text-sm text-gray-700 outline-none"}),e.jsx("div",{className:"h-5 w-px bg-gray-300"}),e.jsx("button",{onMouseDown:r=>{r.preventDefault(),st()},className:"rounded p-1 text-gray-700 hover:bg-gray-100",children:e.jsx(fs,{size:16})}),e.jsx("button",{onMouseDown:r=>{r.preventDefault(),$e()},className:"rounded p-1 text-gray-700 hover:bg-gray-100",children:e.jsx(xs,{size:16})}),e.jsx("div",{className:"h-5 w-px bg-gray-300"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"Text"}),e.jsxs("div",{className:"flex gap-1",children:[["#EF4444","#1F2937","#3B82F6","#10B981"].map(r=>e.jsx("button",{onMouseDown:f=>{f.preventDefault(),_e(r)},className:"h-5 w-5 rounded-full border border-gray-300 transition hover:scale-110",style:{backgroundColor:r}},r)),e.jsxs("div",{className:"relative flex h-5 w-5 cursor-pointer items-center justify-center overflow-hidden rounded-full border border-gray-300 transition-colors hover:bg-gray-50",children:[e.jsx(zt,{size:10,className:"text-gray-500"}),e.jsx("input",{type:"color",onInput:r=>_e(r.target.value),className:"absolute inset-0 h-full w-full cursor-pointer border-0 p-0 opacity-0"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"Fill"}),e.jsxs("div",{className:"flex gap-1",children:[["#FEF08A","#FED7AA","#E0E0E0","#FFFFFF"].map(r=>e.jsx("button",{onMouseDown:f=>{f.preventDefault(),ke(r)},className:"h-5 w-5 rounded-full border border-gray-300 transition hover:scale-110",style:{backgroundColor:r}},r)),e.jsxs("div",{className:"relative flex h-5 w-5 cursor-pointer items-center justify-center overflow-hidden rounded-full border border-gray-300 transition-colors hover:bg-gray-50",children:[e.jsx(zt,{size:10,className:"text-gray-500"}),e.jsx("input",{type:"color",onInput:r=>ke(r.target.value),className:"absolute inset-0 h-full w-full cursor-pointer border-0 p-0 opacity-0"})]})]})]})]}),Fe=C&&e.jsxs("div",{className:w?"flex min-h-8 items-center gap-1 rounded-xl border border-slate-200/80 bg-white/90 p-0.5 shadow-sm":"fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 roun
2ded-full border border-gray-200 bg-white/90 px-4 py-2 shadow-xl backdrop-blur-sm transition-all hover:bg-white",children:[e.jsx("button",{onClick:()=>Ye(-1),disabled:F<=1,className:"rounded-lg p-1 text-gray-700 transition-colors hover:bg-gray-100 disabled:opacity-30 disabled:hover:bg-transparent",title:"Previous page",children:e.jsx(qt,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[11px] font-medium text-gray-600",children:"Page"}),e.jsx("input",{type:"text",value:Ne,onChange:r=>Ue(r.target.value),onBlur:()=>{const r=parseInt(Ne);!isNaN(r)&&r>=1&&r<=C?Se(r):Ue(F.toString())},onKeyDown:r=>{r.key==="Enter"&&r.currentTarget.blur()},className:"w-7 border-b border-gray-300 bg-transparent text-center text-[11px] font-medium text-gray-800 outline-none focus:border-brand-500","aria-label":"Current page"}),e.jsxs("span",{className:"text-[11px] text-gray-500",children:["/ ",C]})]}),e.jsx("button",{onClick:()=>Ye(1),disabled:F>=C,className:"rounded-lg p-1 text-gray-700 transition-colors hover:bg-gray-100 disabled:opacity-30 disabled:hover:bg-transparent",title:"Next page",children:e.jsx(Ge,{className:"h-4 w-4"})})]});return e.jsxs("div",{className:"relative flex justify-center bg-gray-100 min-h-full transition-all duration-200 ease-in-out",children:[j?Ft.createPortal(nt,j):nt,e.jsx("div",{ref:te,onScroll:Je,className:"flex h-full w-full flex-col items-center gap-8 overflow-y-auto pb-0 pt-0",children:e.jsx(is,{file:a,onLoadSuccess:ht,className:"flex flex-col items-center gap-8",loading:e.jsx("div",{className:"p-10 text-gray-500",children:"Loading PDF..."}),children:C&&Array.from({length:C}).map((r,f)=>{const x=f+1,R=c.filter(n=>n.pageNumber===x);return e.jsxs("div",{ref:n=>{n?H.current.set(x,n):H.current.delete(x)},"data-page-number":x,className:"relative shadow-xl border border-gray-300 bg-white select-none origin-top transition-transform",style:{width:Ce},children:[e.jsx(ls,{pageNumber:x,width:Ce,onLoadSuccess:bt,renderTextLayer:!1,renderAnnotationLayer:!1}),Z&&e.jsxs("div",{className:`absolute top-0 left-0 z-10 page-interaction-layer ${!m&&t!=="select"?"cursor-crosshair":"cursor-default"}`,style:{width:"100%",height:"100%"},onMouseDown:m?void 0:n=>Ke(n,x),onMouseMove:m?void 0:n=>Qe(n.nativeEvent,x),onMouseUp:m?void 0:re,onMouseLeave:m?void 0:re,onDragOver:n=>{m||(n.preventDefault(),n.dataTransfer.dropEffect="copy")},onDrop:n=>{if(m)return;n.preventDefault();const S=n.dataTransfer.getData("attributeId");if(S){const $=n.currentTarget,L=Ie(n.nativeEvent,$),X=Date.now().toString(),U={id:X,x:L.x-15,y:L.y-15,width:30,height:30,type:"badge",pageNumber:x,content:S};o(Y=>[...Y,U]),V(X)}},children:[R.map(n=>{var L,X,U,Y,B,Q;const S=J===n.id,$=O===n.id;return n.style,e.jsxs("div",{"data-annotation-id":n.id,className:`absolute group ${$||S?"z-40":"z-30"}`,style:{left:n.x*s,top:n.y*s,width:n.type==="badge"?30*s:n.width*s,height:n.type==="badge"?30*s:n.height*s},children:[!m&&$&&!S&&n.type!=="badge"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-1.5 -left-1.5 w-3 h-3 bg-white border border-blue-500 rounded-full cursor-nw-resize z-50 hover:bg-blue-100",onMouseDown:_=>ye(_,n,"nw")}),e.jsx("div",{className:"absolute -top-1.5 -right-1.5 w-3 h-3 bg-white border border-blue-500 rounded-full cursor-ne-resize z-50 hover:bg-blue-100",onMouseDown:_=>ye(_,n,"ne")}),e.jsx("div",{className:"absolute -bottom-1.5 -left-1.5 w-3 h-3 bg-white border border-blue-500 rounded-full cursor-sw-resize z-50 hover:bg-blue-100",onMouseDown:_=>ye(_,n,"sw")}),e.jsx("div",{className:"absolute -bottom-1.5 -right-1.5 w-3 h-3 bg-white border border-blue-500 rounded-full cursor-se-resize z-50 hover:bg-blue-100",onMouseDown:_=>ye(_,n,"se")}),e.jsx("div",{className:"absolute top-1/2 -right-1.5 w-2 h-4 -mt-2 bg-white border border-blue-500 rounded-full cursor-e-resize z-50",onMouseDown:_=>ye(_,n,"e")}),e.jsx("div",{className:"absolute top-1/2 -left-1.5 w-2 h-4 -mt-2 bg-white border border-blue-500 rounded-full cursor-w-resize z-50",onMouseDown:_=>ye(_,n,"w")}),e.jsx("div",{className:"absolute -bottom-1.5 left-1/2 w-4 h-2 -ml-2 bg-white border border-blue-500 rounded-full cursor-s-resize z-50",onMouseDown:_=>ye(_,n,"s")})]}),n.type==="box"?e.jsxs("div",{className:`w-full h-full border-[3px] border-red-500 hover:bg-red-500/10 transition-colors ${O===n.id?"ring-2 ring-blue-500 shadow-lg":""}`,style:{borderWidth:3*s},children:[!m&&e.jsx("div",{className:"absolute -top-3 -right-3 flex gap-1 opacity-100 transition-opacity",style:{transform:`scale(${s})`,transformOrigin:"bottom left"},children:e.jsx("button",{onClick:_=>Te(n.id,_.nativeEvent),className:"bg-red-600 text-white p-1 rounded-full shadow-sm hover:bg-red-700",children:e.jsx(St,{size:12})})}),!m&&t==="select"&&e.jsx("div",{className:"absolute top-0 left-0 bg-blue-500 text-white p-0.5 opacity-0 group-hover:opacity-100 cursor-move roun
2ded-br",style:{transform:`scale(${s})`,transformOrigin:"top left"},children:e.jsx(At,{size:10})})]}):n.type==="badge"?(()=>{const _=n.content?v[n.content]:void 0,ie=_==null?void 0:_.status;let K="bg-white border-brand-600 text-brand-600";return ie==="Pass"?K="bg-emerald-600 border-emerald-700 text-white":ie==="Fail"?K="bg-red-600 border-red-700 text-white":ie==="N/A"&&(K="bg-blue-600 border-blue-700 text-white"),e.jsxs("div",{className:`w-full h-full rounded-full border-2 flex items-center justify-center shadow-sm hover:shadow-md transition-shadow ${m?"cursor-default":"cursor-grab active:cursor-grabbing"} ${O===n.id?"ring-2 ring-blue-500 ring-offset-1":""} ${K}`,style:{fontSize:14*s,borderWidth:2*s},children:[e.jsx("span",{className:"font-bold leading-none select-none",children:n.content}),!m&&e.jsx("div",{className:"absolute -top-1 -right-1 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-50",style:{transform:`scale(${s})`,transformOrigin:"bottom left"},children:e.jsx("button",{onClick:ue=>Te(n.id,ue.nativeEvent),className:"bg-red-600 text-white p-0.5 rounded-full shadow-sm hover:bg-red-700",children:e.jsx(St,{size:10})})})]})})():e.jsxs("div",{className:`border shadow-sm flex-1 w-full h-full relative flex flex-col ${O===n.id?"ring-2 ring-blue-500 shadow-md":""}`,style:{padding:8*s,borderWidth:1*s,borderColor:"#dc2626",fontSize:(((L=n.style)==null?void 0:L.fontSize)||14)*s,fontFamily:Vt((X=n.style)==null?void 0:X.fontFamily),color:((U=n.style)==null?void 0:U.color)||"#dc2626",backgroundColor:((Y=n.style)==null?void 0:Y.backgroundColor)||"#ffffff",fontWeight:(B=n.style)==null?void 0:B.fontWeight,fontStyle:(Q=n.style)==null?void 0:Q.fontStyle},onDoubleClick:_=>{m||(_.stopPropagation(),et(n))},children:[e.jsx(qs,{content:n.content||"",isEditing:S,style:{},onInput:gt,onBlur:tt,onMouseDown:_=>{S&&_.stopPropagation()},onDoubleClick:_=>{S&&_.stopPropagation()}}),!m&&!S&&e.jsx("div",{className:"absolute -top-3 -right-3 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",style:{transform:`scale(${s})`,transformOrigin:"bottom left"},children:e.jsx("button",{onClick:_=>Te(n.id,_.nativeEvent),className:"bg-red-600 text-white p-1 rounded-full shadow-sm hover:bg-red-700",children:e.jsx(St,{size:12})})}),!m&&!S&&t==="select"&&e.jsx("div",{className:"absolute top-0 left-0 bg-blue-500 text-white p-0.5 opacity-0 group-hover:opacity-100 cursor-move rounded-br",style:{transform:`scale(${s})`,transformOrigin:"top left"},children:e.jsx(At,{size:10})})]})]},n.id)}),!m&&I&&W&&xe===x&&e.jsx("div",{className:"absolute border-[3px] border-red-500 bg-red-500/10 pointer-events-none z-50 dashed-border",style:{left:W.x*s,top:W.y*s,width:W.width*s,height:W.height*s,borderWidth:3*s},children:W.type==="text"&&e.jsx("div",{className:"absolute top-0 left-0 bg-red-600 text-white px-1",style:{fontSize:10*s},children:"Text Area"})})]}),pt&&e.jsxs("div",{className:"absolute top-4 right-4 z-50 bg-white/90 backdrop-blur shadow-md rounded-md px-3 py-2 flex items-center gap-2 text-xs font-medium text-brand-600 border border-brand-100 animate-in fade-in slide-in-from-top-2",children:[e.jsx(le,{className:"w-3 h-3 animate-spin"}),e.jsx("span",{children:"OCR Scanning..."})]}),de.filter(n=>n.pageIndex===x).map((n,S)=>{const $=de.indexOf(n)===g,L=n.pageWidth,X=n.pageHeight,U=(Z&&Z.width?Z.width:800*s)/L,Y=n.transform[4],B=n.transform[5],Q=n.width,_=n.height;return e.jsx("div",{className:`absolute z-20 pointer-events-none mix-blend-multiply transition-colors ${$?"bg-orange-400/60 ring-2 ring-orange-500":"bg-yellow-300/40"}`,style:{left:Y*U,top:(X-B-_)*U,width:Q*U,height:_*1.2*U}},`match-${x}-${S}`)})]},`page-${x}`)})},a)}),w?Ft.createPortal(Fe,w):Fe]})},Ot=(a,t)=>{const c=(a||"").trim(),o=(t||"").trim();return c&&o&&c!==o?`${c} <${o}>`:o||c},Zs=a=>{if(!a)return"";const t=new Date(a);return Number.isNaN(t.getTime())?String(a):t.toLocaleString()},Js=a=>{const t=document.createElement("div");return t.innerHTML=a.replace(/<br\s*\/?>/gi,`
3`).replace(/<\/(p|div|li|tr|h[1-6])>/gi,`
4`).replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<script[\s\S]*?<\/script>/gi,""),(t.textContent||t.innerText||"").replace(/\n{3,}/g,`
5
6`).trim()},_t=async(a,t)=>{var k;const{jsPDF:c}=await ee(async()=>{const{jsPDF:N}=await import("./jspdf.es.min-Cs0E-PbN.js");return{jsPDF:N}},__vite__mapDeps([0])),o=new c({unit:"pt",format:"letter",orientation:"portrait"}),s=54,v=o.internal.pageSize.getWidth(),d=o.internal.pageSize.getHeight(),g=v-s*2;let y=s;const m=(N=18)=>{y+N>
6d-s&&(o.addPage(),y=s)},u=(N,C=10,T=C*1.35,F="helvetica",z="normal",Z=8)=>{o.setFont(F,z),o.setFontSize(C);const te=(N||"").replace(/\r\n/g,`
7`).replace(/\r/g,`
8`).split(`
9`);for(const H of te){const se=H.trim()?o.splitTextToSize(H,g):[""];for(const ne of se)m(T),ne&&o.text(ne,s,y),y+=T}y+=Z};t.title&&u(t.title,16,21,"helvetica","bold",16);const w=(t.headerRows||[]).filter(([,N])=>N&&N.trim());if(w.length>0){o.setFontSize(9.5);for(const[N,C]of w){const F=o.splitTextToSize(C||"",g-52);m(Math.max(14,F.length*13)),o.setFont("helvetica","bold"),o.text(`${N}:`,s,y),o.setFont("helvetica","normal"),o.text(F,s+52,y),y+=Math.max(14,F.length*13)}y+=10}(k=t.attachments)!=null&&k.length&&u(`Attachments: ${t.attachments.join("; ")}`,9.5,13,"helvetica","normal",12),o.setDrawColor(209,213,219),m(18),o.line(s,y,v-s,y),y+=24,u(t.bodyText||"No message body found.",10,14,t.monospaceBody?"courier":"helvetica","normal",0);const j=o.output("blob");return new File([j],a,{type:"application/pdf"})};async function Ys(a){const t=await Yt.create(),c=t.addPage(),{width:o,height:s}=c.getSize(),v=await a.arrayBuffer();let d;try{if(a.type==="image/jpeg"||a.type==="image/jpg")d=await t.embedJpg(v);else if(a.type==="image/png")d=await t.embedPng(v);else throw new Error("Unsupported image type. Only PNG and JPEG are supported.")}catch(C){throw console.error("Error embedding image:",C),new Error("Failed to embed image. Ensure it is a valid PNG or JPEG.")}const g=50,y=o-2*g,m=s-2*g,u=Math.min(y/d.width,m/d.height,1),w=d.width*u,j=d.height*u;c.drawImage(d,{x:(o-w)/2,y:(s-j)/2,width:w,height:j});const k=await t.save(),N=a.name.replace(/\.[^/.]+$/,"")+".pdf";return new File([k],N,{type:"application/pdf"})}const xt=a=>a.name.replace(/\.[^/.]+$/,"")+".pdf",Kt=async a=>{const[{auth:t,appCheck:c},{getToken:o}]=await Promise.all([ee(()=>import("./firebase-BNIkhQ9j.js"),[]),ee(()=>import("./firebase-core-DWzFmatk.js").then(g=>g.Z),[])]),s=t.currentUser;if(!s)throw new Error("Sign in is required for native Office rendering.");if(!c)throw new Error("App Check is not available for native Office rendering.");const v=new AbortController,d=window.setTimeout(()=>v.abort(),12e4);try{const[g,y]=await Promise.all([s.getIdToken(),o(c,!1)]),u=await fetch("/api/docx/convert",{method:"POST",headers:{Authorization:`Bearer ${g}`,"X-Firebase-AppCheck":y.token,"X-File-Name":encodeURIComponent(a.name),"Content-Type":a.type||"application/octet-stream"},body:a,signal:v.signal});if(!u.ok){const k=(await u.text()).trim();throw new Error(k||`Native Office renderer returned ${u.status}.`)}const w=await u.arrayBuffer();if(!new TextDecoder("latin1").decode(w.slice(0,5)).startsWith("%PDF-"))throw new Error("Native Office renderer did not return a PDF.");return new File([w],xt(a),{type:"application/pdf"})}finally{window.clearTimeout(d)}},Ks=async a=>{var y;const[{renderAsync:t},c,o]=await Promise.all([ee(()=>import("./docx-preview-BWHwJIIq.js"),[]),ee(()=>import("./html2canvas.esm-QH1iLAAe.js"),[]),ee(()=>import("./jspdf.es.min-Cs0E-PbN.js"),__vite__mapDeps([0]))]),s=c.default,{jsPDF:v}=o,d=document.createElement("iframe");d.setAttribute("aria-hidden","true"),d.style.cssText=["position:fixed","left:-100000px","top:0","width:1200px","height:1600px","border:0","pointer-events:none","background:#fff"].join(";"),d.srcdoc='<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>';const g=new Promise((m,u)=>{d.addEventListener("load",()=>m(),{once:!0}),d.addEventListener("error",()=>u(new Error("Could not initialize DOCX preview frame.")),{once:!0})});document.body.appendChild(d);try{await g;const m=d.contentDocument;if(!m)throw new Error("DOCX preview frame is unavailable.");m.body.style.margin="0",m.body.style.background="#fff",await t(await a.arrayBuffer(),m.body,m.head,{breakPages:!0,ignoreLastRenderedPageBreak:!1,experimental:!0,renderHeaders:!0,renderFooters:!0,renderFootnotes:!0,useBase64URL:!0,inWrapper:!0});const u=Array.from(m.images);await Promise.all(u.map(async k=>{k.complete||await new Promise(N=>{k.addEventListener("load",()=>N(),{once:!0}),k.addEventListener("error",()=>N(),{once:!0})})})),await((y=m.fonts)==null?void 0:y.ready),await new Promise(k=>requestAnimationFrame(()=>requestAnimationFrame(()=>k())));const w=Array.from(m.querySelectorAll("section.docx"));if(w.length===0)throw new Error("The DOCX renderer produced no pages.");let j=null;for(const[k,N]of w.entries()){const C=N.getBoundingClientRect(),T=Math.ceil(C.width||N.scrollWidth),F=Math.ceil(C.height||N.scrollHeight);if(T<10||F<10)throw new Error("The DOCX renderer produced an empty page.");const z=await s(N,{backgroundColor:"#ffffff",scale:2,useCORS:!0,logging:!1,imageTimeout:15e3,width:T,height:F,windowWidth:Math.max(1200,T),windowHeight:Math.max(1600,F)}),Z=T*.75,ae=F*.75,te=Z>ae?"landscape":"portrait";j?j.addPage([Z,ae],te):j=new v({unit:"pt",format:[Z,ae],orientation:te,compress:!0});const H=j.internal.pageSize.getWidth(),se=j.internal.pageSize.getHeight();j.addImage(z.toDataURL("image/jpeg",.98),"JPEG",0,0,H,se,`docx-page-${k}`,"FAST")}if(!j)throw new Error("The DOCX renderer did not create a PDF.");return new File([j.output("arraybuffer")],xt(a),{type:"application/pdf"})}finally{d.remove()}};async function Qs(a){try{return await Kt(a)}catch(t){console.warn("Native DOCX rendering unavailable; using browser renderer.",t)}try{return await Ks(a)}catch(t){console.warn("Browser DOCX rendering unavailable; using text fallback.",t)}try{const c=await(await ee(async()=>{const{default:o}=await import("./index-yKy4l5oB.js").then(s=>s.i);return{default:o}},[])).default.extractRawText({arrayBuffer:await a.arrayBuffer()});return _t(xt(a),{bodyText:(c.value||"").trim()||"No document content found."})}catch(t){throw console.error("Error converting DOCX:",t),new Error("Failed to convert Word document.")}}async function er(a){try{const t=await ee(()=>import("./xlsx-Bb_VIWOD.js"),[]),c=t.default||t,o=(await ee(async()=>{const{default:k}
9=await import("./html2pdf--62a008u.js").then(N=>N.h);return{default:k}},__vite__mapDeps([0]))).default,s=await a.arrayBuffer(),v=c.read(s,{type:"array"}),d=v.SheetNames[0],g=v.Sheets[d],y=c.utils.sheet_to_html(g),m=document.createElement("div");m.innerHTML=y;const u=document.createElement("style");u.innerHTML=`
10            table { border-collapse: collapse; width: 100%; font-family: sans-serif; font-size: 10pt; }
11            td, th { border: 1px solid #ddd; padding: 4px; }
12            th { background-color: #f2f2f2; font-weight: bold; }
13        `,m.appendChild(u);const w={margin:10,filename:a.name.replace(/\.[^/.]+$/,"")+".pdf",image:{type:"jpeg",quality:.98},html2canvas:{scale:2,useCORS:!0},jsPDF:{unit:"mm",format:"a4",orientation:"landscape"}},j=await o().set(w).from(m).output("blob");return new File([j],w.filename,{type:"application/pdf"})}catch(t){throw console.error("Error converting XLSX:",t),new Error("Failed to convert Excel spreadsheet.")}}async function tr(a){try{const{jsPDF:t}=await ee(async()=>{const{jsPDF:m}=await import("./jspdf.es.min-Cs0E-PbN.js");return{jsPDF:m}},__vite__mapDeps([0])),c=await a.text(),o=new t;o.setFont("courier"),o.setFontSize(10);const s=15,v=o.internal.pageSize.getHeight(),d=o.splitTextToSize(c,o.internal.pageSize.getWidth()-2*s);let g=s;for(let m=0;m<d.length;m++)g>v-s&&(o.addPage(),g=s),o.text(d[m],s,g),g+=5;const y=o.output("blob");return new File([y],a.name.replace(/\.[^/.]+$/,"")+".pdf",{type:"application/pdf"})}catch(t){throw console.error("Error converting TXT:",t),new Error("Failed to convert text file.")}}async function sr(a){try{return await Kt(a)}catch(t){console.warn("Native PowerPoint rendering unavailable; using text fallback.",t)}try{const c=await(await ee(async()=>{const{default:v}=await import("./jszip.min-DAspU9g4.js").then(d=>d.j);return{default:v}},[])).default.loadAsync(await a.arrayBuffer()),o=Object.keys(c.files).filter(v=>v.match(/ppt\/slides\/slide\d+\.xml/)).sort((v,d)=>{var m,u;const g=parseInt(((m=v.match(/slide(\d+)/))==null?void 0:m[1])||"0"),y=parseInt(((u=d.match(/slide(\d+)/))==null?void 0:u[1])||"0");return g-y});if(o.length===0)throw new Error("No slides were found in the PowerPoint package.");const s=await Promise.all(o.map(async v=>{var u,w;const d=await((u=c.file(v))==null?void 0:u.async("string")),y=((d==null?void 0:d.match(/<a:t>([^<]*)<\/a:t>/g))||[]).map(j=>j.replace(/<\/?a:t>/g,"")).join(" ").trim();return`Slide ${((w=v.match(/slide(\d+)/))==null?void 0:w[1])||"?"}
14${y||"No extractable slide text."}`}));return _t(xt(a),{title:`${a.name} (text-only fallback)`,bodyText:s.join(`
15
16`)})}catch(t){throw console.error("Error converting PPTX:",t),new Error("Failed to convert PowerPoint file.")}}async function rr(a){try{const{extract:t}=await ee(async()=>{const{extract:T}=await import("./index-CQGjF6Dm.js");return{extract:T}},[]),c=(await ee(async()=>{const{default:T}=await import("./html2pdf--62a008u.js").then(F=>F.h);return{default:T}},__vite__mapDeps([0]))).default,o=await a.text(),s=t(o);let v="";s.subject&&(v+=`Subject: ${s.subject}
17`);const d=T=>{if(!T)return"";if(typeof T=="string")return T;let F=T.name||"",z=T.address?`<${T.address}>`:"";return F&&z?`${F} ${z}`:z||F||""},g=T=>T?Array.isArray(T)?T.map(d).join(", "):d(T):"";s.from&&(v+=`From: ${g(s.from)}
18`),s.to&&(v+=`To: ${g(s.to)}
19`),s.cc&&(v+=`Cc: ${g(s.cc)}
20`),s.date&&(v+=`Date: ${new Date(s.date).toLocaleString()}
21`),v+=`
22----------------------------------------
23
24`;let y=s.text;if(!y&&s.html){const T=document.createElement("div");T.innerHTML=s.html,y=T.textContent||T.innerText||""}y?v+=y:v+="No message body found.";const{jsPDF:m}=await ee(async()=>{const{jsPDF:T}=await import("./jspdf.es.min-Cs0E-PbN.js");return{jsPDF:T}},__vite__mapDeps([0])),u=new m;u.setFont("courier"),u.setFontSize(10);const w=15,j=u.internal.pageSize.getHeight(),k=u.splitTextToSize(v,u.internal.pageSize.getWidth()-2*w);let N=w;for(let T=0;T<k.length;T++)N>j-w&&(u.addPage(),N=w),u.text(k[T],w,N),N+=5;const C=u.output("blob");return new File([C],a.name.replace(/\.[^/.]+$/,"")+".pdf",{type:"application/pdf"})}catch(t){throw console.error("Error converting EML:",t),new Error("Failed to convert .eml file.")}}async function ar(a){try{const t=(await ee(async()=>{const{default:w}=await import("./index-BH46o-VE.js").then(j=>j.i);return{default:w}},[])).default,c=await a.arrayBuffer(),s=new t(c).getFileData(),v=s.recipients||[],d=w=>v.filter(j=>j.recipType===w||!j.recipType&&w==="to").map(j=>
24Ot(j.name,j.smtpAddress||j.email)).filter(Boolean).join("; "),g=s.bodyHtml||s.html||"",y=(s.body||"").trim()||Js(g)||(s.preview||"").trim(),m=(s.attachments||[]).filter(w=>!w.attachmentHidden).map(w=>w.fileName||w.fileNameShort).filter(Boolean),u=a.name.replace(/\.[^/.]+$/,"")+".pdf";return _t(u,{title:s.subject||a.name,headerRows:[["From",Ot(s.senderName,s.senderSmtpAddress||s.senderEmail)],["Sent",Zs(s.clientSubmitTime||s.messageDeliveryTime||s.creationTime)],["To",d("to")],["Cc",d("cc")],["Bcc",d("bcc")],["Subject",s.subject]],attachments:m,bodyText:y||"No message body found."})}catch(t){throw console.error("Error converting MSG:",t),new Error("Failed to convert Outlook .msg file.")}}async function Xt(a){const t=Fs(a),c=t.type.toLowerCase(),o=t.name.toLowerCase();if(c==="application/pdf")return t;if(c.startsWith("image/"))return Ys(t);if(c==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||o.endsWith(".docx"))return Qs(t);if(c==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||/\.(xlsx|xls|xlsm)$/i.test(o))return er(t);if(o.endsWith(".txt")||c==="text/plain"||o.endsWith(".csv")||c==="text/csv")return tr(t);if(o.endsWith(".eml")||c==="message/rfc822")return rr(t);if(o.endsWith(".msg")||c==="application/vnd.ms-outlook")return ar(t);if(o.endsWith(".pptx")||o.endsWith(".ppt")||c.includes("presentation")){if(o.endsWith(".ppt"))throw new Error("Legacy .ppt files cannot be converted to preview. Please save as .pptx or .pdf.");return sr(t)}else throw new Error(`Unsupported file type: ${c}. Please upload a PDF, Image, Word, Excel, PowerPoint (.pptx), Message (.msg/.eml), or Text file.`)}const nr=["Walkthrough","Interim","Year-End","Rollforward","Remediation"],or=a=>{var c;const t=(c=a==null?void 0:a.phases)==null?void 0:c.map(o=>{var s;return(s=o.phase)==null?void 0:s.trim()}).filter(o=>!!o);return t!=null&&t.length?Array.from(new Set(t)):nr},ir=a=>{const t=(a.fiscalYear||a.name||"").trim();return/^\d{4}$/.test(t)?`FY${t.slice(-2)}`:t},lr=(a,t,c)=>{var o,s,v,d;return{controlId:a.controlId,controlName:a.name,controlDescription:a.description||"",controlObjective:a.controlObjective||"",riskDescription:a.riskDescription||"",riskAssertion:((o=a.assertions)==null?void 0:o.join(", "))||"",attributes:((s=a.testingAttributes)==null?void 0:s.trim())||`Accuracy
25Completeness
26Validity`,testPhase:c,fiscalYear:ir(t),classification:a.classification,metadata:{owner:a.owner||"",preparer:a.preparer||"",frequency:a.frequency||"Monthly",riskLevel:a.riskLevel||"Low",populationSize:"",sampleSize:"1",controlType:a.type||"Manual",nature:a.nature||"Preventive",process:a.process||"",subProcess:a.subProcess||"",riskId:a.riskId||"",relatedITSystem:((v=a.relatedITSystems)==null?void 0:v.join(", "))||"",cosoComponents:((d=a.cosoComponents)==null?void 0:d.join(", "))||""},files:[],auditPlanId:t.id,auditPlanName:t.name}},cr=({controls:a,workspaceId:t,onSelect:c,onClose:o})=>{const[s,v]=i.useState(""),[d,g]=i.useState(null),[y,m]=i.useState([]),[u,w]=i.useState(!1),[j,k]=i.useState([]),[N,C]=i.useState(!!t),[T,F]=i.useState(""),[z,Z]=i.useState(""),[ae,te]=i.useState(!1),[H,se]=i.useState(null),[ne,I]=i.useState(null),G=i.useMemo(()=>j.find(p=>p.id===T)||null,[j,T]),fe=i.useMemo(()=>or(G),[G]),ce=a.filter(p=>p.name.toLowerCase().includes(s.toLowerCase())||p.controlId.toLowerCase().includes(s.toLowerCase()));i.useEffect(()=>{if(!t){k([]),C(!1);return}C(!0);const p=Rs.subscribeToPlans(t,q=>{k(q),C(!1)});return()=>p()},[t]),i.useEffect(()=>{(async()=>{if(!d){m([]);return}w(!0);try{const q=await Be.getControlTestRuns(d.id);m(q)}catch(q){console.error("Failed to fetch runs",q),m([])}finally{w(!1)}})()},[d]);const xe=p=>{g(p),F(""),Z(""),I(null)},ge=p=>{F(p),Z(""),I(null)},W=async p=>{se(p),I(null);try{await c(p)===!1&&I("The workpaper could not be linked. Please try again.")}catch(q){console.error("Failed to link workpaper to testing",q),I("The workpaper could not be linked. Please try again.")}finally{se(null)}},oe=async()=>{if(!t||!d||!G||!z)return;te(!0),I(null);let p=null,q=!1;try{const de=lr(d,G,z),we=zs(de);if(p=(await Be.createTestRun(t,d.controlId,d.name,de,z,"manual")).testRunId,await Be.linkTestRunToControl(p,d.id),await Be.saveTestRunOutput(p,we,de,z),q=!0,await c(p)===!1){const O=await Be.getControlTestRuns(d.id);m(O),I("The manual testing memo was created, but the workpaper could not be linked. Select the new testing memo to try again.")}}catch(de){if(console.error("Failed to create manual testing memo",de),p&&q){try{const we=await Be.getControlTestRuns(d.id);m(we)}catch(we){console.error("Failed to refresh testing after partial creation",we)}I("The manual testing memo was created, but the workpaper could not be linked. Select the new testing memo to try again.")}else I("The manual testing memo could not be created. Please try again.")}finally{te(!1)}};return e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-2xl w-full max-w-2xl flex flex-col max-h-[80vh]",children:[e.jsxs("div",{className:"p-4 border-b border-slate-200 flex justify-between items-center bg-slate-50 rounded-t-xl",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-slate-800",children:"Save to Testing"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select a testing memo to link this workpaper to"})]}),e.jsx("button",{onClick:o,className:"p-2 hover:bg-slate-200 rounded-lg text-slate-500 transition",children:e.jsx(Gt,{size:20})})]}),e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col md:flex-row h-full",children:[e.jsxs("div",{className:`w-full md:w-1/2 border-r border-slate-200 flex flex-col ${d?"hidden md:flex":"flex"}`,children:[e.jsx("div",{className:"p-3 border-b border-slate-200",children:e.jsxs("div",{className:"relative",children:[e.jsx(ps,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:14}),e.jsx("input",{type:"text",placeholder:"Search controls...",className:"w-full pl-9 pr-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-brand-500 outline-none",value:s,onChange:p=>v(p.target.value)})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1",children:ce.map(p=>e.jsxs("button",{onClick:()=>xe(p),className:`w-full text-left p-3 rounded-lg text-sm transition flex items-center justify-between group ${(d==null?void 0:d.id)===p.id?"bg-brand-50 text-brand-700 font-medium":"hover:bg-slate-50 text-slate-700"}`,children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-slate-500 font-mono mb-0.5",children:p.controlId}),e.jsx("div",{className:"line-clamp-1",children:p.name})]}),e.jsx(Ge,{size:16,className:`opacity-0 group-hover:opacity-100 ${(d==null?void 0:d.id)===p.id?"opacity-100 text-brand-500":"text-slate-400"}`})]}
26,p.id))})]}),e.jsx("div",{className:`w-full md:w-1/2 flex flex-col bg-slate-50/50 ${d?"flex":"hidden md:flex"}`,children:d?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-3 border-b border-slate-200 bg-white md:bg-transparent flex items-center gap-2",children:[e.jsx("button",{onClick:()=>g(null),className:"md:hidden p-1 -ml-1 hover:bg-slate-100 rounded text-slate-500",children:e.jsx(Ge,{size:20,className:"rotate-180"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-bold text-slate-800 text-sm truncate",children:d.name}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select a testing below"})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:[u?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(le,{className:"animate-spin text-slate-400",size:24})}):y.length>0?y.map(p=>{const q=new Date(p.createdAt);return e.jsxs("button",{onClick:()=>W(p.id),disabled:!!H,className:"w-full bg-white p-3 rounded-lg border border-slate-200 shadow-sm hover:border-brand-300 hover:shadow-md transition text-left group",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-500 mb-1",children:[e.jsx(hs,{size:12}),e.jsxs("span",{children:[Ms(q)," ",Is(q)]})]}),e.jsxs("div",{className:"flex items-center gap-2 font-medium text-slate-700",children:[H===p.id?e.jsx(le,{size:14,className:"animate-spin text-brand-500"}):e.jsx(Zt,{size:14,className:"text-slate-400 group-hover:text-brand-500"}),H===p.id?"Linking workpaper...":"Memo Output"]}),p.workpaperUrl&&e.jsx("div",{className:"mt-1.5 inline-block px-1.5 py-0.5 bg-blue-50 text-blue-600 text-[10px] rounded border border-blue-100",children:"Has Workpaper"})]},p.id)}):e.jsxs("div",{className:"mx-auto flex w-full max-w-sm flex-col items-center px-1 py-5 text-center",children:[e.jsx("div",{className:"mb-3 flex h-11 w-11 items-center justify-center rounded-full bg-brand-50 text-brand-600",children:e.jsx(Rt,{size:20})}),e.jsx("p",{className:"text-sm font-semibold text-slate-700",children:"No testing found"}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-slate-500",children:"Create a manual testing memo for this control and link the current workpaper."}),e.jsxs("div",{className:"mt-5 w-full space-y-3 text-left",children:[e.jsxs("label",{className:"block",children:[e.jsxs("span",{className:"mb-1 block text-xs font-semibold text-slate-700",children:["Audit Plan ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("select",{"aria-label":"Audit Plan",value:T,onChange:p=>ge(p.target.value),disabled:N||ae,className:"w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-brand-400 focus:ring-2 focus:ring-brand-100 disabled:cursor-not-allowed disabled:bg-slate-100",children:[e.jsx("option",{value:"",children:N?"Loading audit plans...":"Select audit plan..."}),j.map(p=>e.jsx("option",{value:p.id,children:p.name},p.id))]})]}),e.jsxs("label",{className:"block",children:[e.jsxs("span",{className:"mb-1 block text-xs font-semibold text-slate-700",children:["Test Phase ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("select",{"aria-label":"Test Phase",value:z,onChange:p=>{Z(p.target.value),I(null)},disabled:!G||ae,className:"w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-brand-400 focus:ring-2 focus:ring-brand-100 disabled:cursor-not-allowed disabled:bg-slate-100",children:[e.jsx("option",{value:"",children:"Select test phase..."}),fe.map(p=>e.jsx("option",{value:p,children:p},p))]})]}),!N&&j.length===0&&e.jsx("p",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs leading-relaxed text-amber-700",children:"No audit plans are available. Create an audit plan in Planning before creating manual testing."}),ne&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs leading-relaxed text-red-700",role:"alert",children:[e.jsx(Mt,{size:14,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:ne})]}),e.jsxs("button",{type:"button",onClick:oe,disabled:!t||!G||!z||ae,className:"flex w-full items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-brand-700 disabled:cursor-not-allowed disabled:bg-slate-300",children:[ae?e.jsx(le,{size:16,className:"animate-spin"}):e.jsx(Rt,{size:16}),ae?"Creating and linking...":"Create manual testing memo and link"]})]})]}),y.length>0&&ne&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs leading-relaxed text-red-700",role:"alert",children:[e.jsx(Mt,{size:14,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:ne})]})]})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-slate-400 p-8 text-center",children:[e.jsx("div",{className:"w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center mb-3",children:e.jsx(Ge,{size:24,className:"opacity-50"})}),e.jsx("p",{className:"text-sm",children:"Select a control to view available testing"})]})})]})]})})},dr=({file:a})=>{const[t,c]=i.useState(null),[o,s]=i.useState(""),[v,d]=i.useState(null);i.useEffect(()=>{let u=!1;return c(null),s(""),d(null),a.arrayBuffer().then(w=>
26{if(u)return;const j=Xs(w,{type:"array",cellFormula:!0});if(!j.SheetNames.length)throw new Error("No worksheets were found in this file.");c(j),s(j.SheetNames[0])}).catch(w=>{u||(console.error("Unable to create spreadsheet preview:",w),d("This spreadsheet could not be previewed in the browser. Download the original evidence to review it."))}),()=>{u=!0}},[a]);const g=i.useMemo(()=>{const u=t==null?void 0:t.Sheets[o];return u?Ut.sheet_to_json(u,{header:1,defval:"",raw:!1}).slice(0,250).map(j=>j.slice(0,50).map(k=>String(k??""))):[]},[o,t]),y=i.useMemo(()=>Math.max(1,...g.map(u=>u.length)),[g]);if(v)return e.jsxs("div",{className:"flex h-full min-h-[28rem] flex-col items-center justify-center gap-3 px-6 text-center text-slate-500",role:"alert",children:[e.jsx(Jt,{className:"text-amber-500",size:30}),e.jsx("p",{className:"font-semibold text-slate-700",children:"Spreadsheet preview unavailable"}),e.jsx("p",{className:"max-w-md text-sm leading-relaxed",children:v})]});if(!t||!o)return e.jsxs("div",{className:"flex h-full min-h-[28rem] items-center justify-center gap-3 text-slate-500",role:"status","aria-live":"polite",children:[e.jsx(le,{className:"animate-spin text-brand-600",size:28}),e.jsx("span",{className:"text-sm font-medium",children:"Loading spreadsheet preview…"})]});const m=g.length>=250||g.some(u=>u.length>=50);return e.jsxs("section",{className:"flex h-full min-h-0 flex-col bg-white","aria-label":`Spreadsheet preview: ${a.name}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 bg-slate-50 px-4 py-2.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-sm text-slate-600",children:[e.jsx(bs,{size:18,className:"shrink-0 text-brand-600","aria-hidden":"true"}),e.jsx("span",{className:"truncate font-semibold",title:a.name,children:a.name}),e.jsx("span",{className:"shrink-0 rounded-full bg-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-800",children:"Read-only preview"})]}),t.SheetNames.length>1&&e.jsxs("label",{className:"flex items-center gap-2 text-xs font-medium text-slate-600",children:["Sheet",e.jsx("select",{value:o,onChange:u=>s(u.target.value),className:"rounded-md border border-slate-300 bg-white px-2 py-1 text-sm text-slate-700",children:t.SheetNames.map(u=>e.jsx("option",{value:u,children:u},u))})]})]}),m&&e.jsx("p",{className:"border-b border-amber-100 bg-amber-50 px-4 py-2 text-xs text-amber-800",children:"Preview is limited to the first 250 rows and 50 columns. Download the original file to review all evidence."}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsxs("table",{className:"min-w-full border-collapse text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 z-10 bg-slate-100 text-xs font-semibold text-slate-600",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"sticky left-0 z-20 w-12 border-b border-r border-slate-200 bg-slate-100 px-3 py-2 text-right",children:"#"}),Array.from({length:y},(u,w)=>e.jsx("th",{scope:"col",className:"min-w-32 border-b border-r border-slate-200 px-3 py-2",children:Ut.encode_col(w)},w))]})}),e.jsx("tbody",{children:g.map((u,w)=>e.jsxs("tr",{className:"hover:bg-brand-50/40",children:[e.jsx("th",{scope:"row",className:"sticky left-0 z-10 border-b border-r border-slate-200 bg-slate-50 px-3 py-1.5 text-right text-xs font-medium text-slate-500",children:w+1}),Array.from({length:y},(j,k)=>e.jsx("td",{className:"max-w-96 whitespace-pre-wrap break-words border-b border-r border-slate-200 px-3 py-1.5 align-top text-slate-700",children:u[k]||""},k))]},w))})]})})]})},ur=a=>Array.isArray(a)?a.flatMap(t=>{const c=Number(t.pageNumber),o=Number(t.x),s=Number(t.y);return t.type!=="badge"||!t.id||!t.content||!Number.isInteger(c)||c<1||!Number.isFinite(o)||!Number.isFinite(s)?[]:[{annotationId:t.id,attributeId:t.content,pageNumber:c,x:o,y:s}]}).sort((t,c)=>t.pageNumber-c.pageNumber||t.y-c.y||t.x-c.x||t.attributeId.localeCompare(c.attributeId)||t.annotationId.localeCompare(c.annotationId)):[],mr=(a,t,c)=>{if(!a.length)return;const o=t?a.findIndex(s=>s.annotationId===t):-1;return o>=0?a[(o+1)%a.length]:a.find(s=>s.pageNumber===c)||a[0]},fr=ft.lazy(()=>ee(()=>import("./ExcelPage-khtpsZ0m.js"),__vite__mapDeps([0])).then(a=>({default:a.ExcelPage}))),Br=({initialFiles:a=[],onSave:t,readOnly:c=!1,testRunId:o,onSaveToCloud:s,controls:v=[],externalFile:d,initialAnnotations:g=[],isAlreadyLinked:y=!1,onSelectControl:m,selectedControl:u,planTier:w,onOpenPaywall:j,attributes:k,attributeStatuses:N={},userId:C,controlId:T,controlName:F,excelWorkbookId:z,onExcelUpload:Z,onReplaceExcelWorkpaper:ae,onCloseExcel:te,workspaceId:H,onBack:se,backLabel:ne="Return to testing memo",activeWorkpaperId:I,workpaperNavigation:G,onSelectWorkpaper:fe,onBeforeWorkpaperChange:ce,onUpdateAttributeStatus:xe,onExcelNavigationChange:ge,onRegisterExcelNavigation:W,onPdfNavigationChange:oe,onRegisterPdfNavigation:p})=>{Os("Workpaper");const[q,de]=i.useState(!1),[we,pt]=i.useState(""),[h,O]=i.useState(a[0]||null),[V,je]=i.useState(""),[Ze,ve]=i.useState(!1),[Re,Pe]=i.useState(null),[He,J]=i.useState(null),[Me,We]=i.useState(""),[Ne,Ue]=i.useState([]),[Je,Ve]=i.useState(0),[ht,bt]=i.useState(null),[Se,Ye]=i.useState(!1),[Ie,Ke]=i.useState(null),[ye,Qe]=i.useState(null),{state:re,set:Te,undo:et,redo:tt,canUndo:gt,canRedo:Le,reset:st}=Us(g||[]),[$e,_e]=i.useState("select"),[rt,at]=i.useState(!1),[ke,Ee]=i.useState(!1),[De,Ce]=i.useState(!1),[nt,Fe]=i.useState(!1),[r,f]=i.useState(y),[x,R]=i.useState(!1),n=!!(h&&/\.(xlsx|xls|xlsm|csv)$/i.test(h.name)),[S,$]=i.useState(1),[L,X]=i.useState(null),[U,Y]=i.useState(null),[B,Q]=i.useState({activePageNumber:1,selectedAnnotationId:null}),[_,ie]=i.useState(null),K=i.useRef(0),ue=i.useRef(null),Oe=i.useRef(null),Xe=async(l,b)=>{if(!(c||!xe)){Qe(l);try{await xe(l,b),Ke(null)}catch(P){console.error("Failed to update tickmark conclusion",P),alert("Unable to update the tickmark conclusion. Please try again.")}finally{Qe(null)}}};i.useEffect(()=>{if(!d){Oe.current=null;return}Oe.current!==d&&(Oe.current=d,O(d),st(g||[]),pe.current=JSON.stringify(g||[]))},[d,st]),i.useEffect(()=>{f(y)},[y]),i.useEffect(()=>{c&&(_e("select"),ve(!1),Fe(!1))},[c]);const pe=i.useRef(JSON.stringify(g));i.useEffect(()=>{if(!o||!r||c||JSON.stringify(re)===pe.current)return;const b=setTimeout(()=>{ct(o,!0)},5e3);return()=>clearTimeout(b)},[re,o,r,c,I]),i.useEffect(()=>{if(h&&h.type!=="application/pdf"){if(/\.(xlsx|xls|xlsm|csv)$/i.test(h.name))return;let l=!1;return Ce(!0),J(null),Xt(h).then(b=>{l||O(b)}).catch(b=>{l||(console.error("Auto-conversion failed:",b),!rs(b)&&J(b.message||"Preview not supported for this file type."))}).finally(()=>{l||Ce(!1)}),()=>{l=!0}}else J(null)},[h]),i.useEffect(()=>{if(je((h==null?void 0:h.name)||""),h&&h.type==="application/pdf"){const l=URL.createObjectURL(h);return Pe(l),()=>URL.revokeObjectURL(l)}else Pe(null)},[h]);const ot=async l=>{if(!c&&l.target.files&&l.target.files[0]){const b=l.target.files[0],P=b.name.toLowerCase();if(/\.(xlsx|xls|xlsm|csv)$/i.test(P)){Z?await Z(b):alert("Excel upload not supported in this context.");return}Ce(!0),J(null);try{const A=await Xt(b);if(O(A),Te([]),f(!1),o&&I&&s){Ee(!0);try{await s(b,A,[],o,b.name,I),pe.current=JSON.stringify([]),f(!0)}catch(D){console.error("Failed to save replacement workpaper:",D),alert("The replacement could not be saved. It is still open locally; use Save to Testing to retry.")}finally{Ee(!1)}}}catch(A){console.error("File conversion failed:",A),O(b),J(A.message||"Failed to process file. Please ensure it is a valid PDF, Image, or Word document.")}finally{Ce(!1)}}},qe=l=>{$(b=>{const P=Math.max(.5,Math.min(3,b+l));return Math.round(P*10)/10})},wt=async()=>{var A,D;if(!h)throw new Error("No workpaper is loaded.");const l=$s(Ls,"generateAnnotatedPdf"),b={annotations:re,attributeStatuses:N};if(H&&C){const M=(V||h.name||"workpaper.pdf").replace(/[^a-zA-Z0-9._-]/g,"_"),E=((D=(A=globalThis.crypto)==null?void 0:A.randomUUID)==null?void 0:D.call(A))||`${Date.now()}-${Math.random().toString(36).slice(2)}
26`,me=`workspaces/${H}/temp_pdf_exports/${C}/${E}_${M}`;return await Ws(Wt(Ht,me),h,{contentType:"application/pdf"}),l({...b,storagePath:me})}const P=await new Promise((M,E)=>{const me=new FileReader;me.readAsDataURL(h),me.onload=()=>M(me.result.split(",")[1]),me.onerror=E});return l({...b,fileBase64:P})},it=async()=>{const l=await wt(),b=l.data.storagePath;if(b){const M=Wt(Ht,b);try{return new Uint8Array(await Bs(M))}finally{await Hs(M).catch(E=>{console.warn("Unable to remove temporary exported PDF.",E)})}}const P=l.data.pdfBase64,A=atob(P),D=new Array(A.length);for(let M=0;M<A.length;M++)D[M]=A.charCodeAt(M);return new Uint8Array(D)},vt=async()=>{if(h){at(!0);try{if(n){const M=document.createElement("a"),E=URL.createObjectURL(h);M.href=E,M.download=V||h.name,document.body.appendChild(M),M.click(),document.body.removeChild(M),window.setTimeout(()=>URL.revokeObjectURL(E),0);return}const l=re.length>0,b=l?new Blob([await it()],{type:"application/pdf"}):new Blob([h],{type:"application/pdf"}),P=document.createElement("a"),A=URL.createObjectURL(b);P.href=A;const D=V.endsWith(".pdf")?V:`${V}.pdf`;P.download=l&&!D.startsWith("annotated_")?`annotated_${D}`:D,document.body.appendChild(P),P.click(),document.body.removeChild(P),window.setTimeout(()=>URL.revokeObjectURL(A),0)}catch(l){console.error("Failed to export PDF",l),await ns({title:"PDF export failed",message:"We could not generate the annotated PDF. Please try again.",confirmLabel:"Close",variant:"warning",hideCancel:!0})}finally{at(!1)}}},lt=()=>{if(!c){if(!os(w)&&j){j();return}!h||re.length===0&&r||(o?ct():Fe(!0))}},yt=async l=>{const b=await ct(l);return b&&Fe(!1),b},ct=async(l,b=!1,P)=>{if(c)return!0;const A=l||o;if(!h||h.type!=="application/pdf"||!s||!A)return!b&&h&&h.type!=="application/pdf"&&alert("Please wait for the file to finish converting to PDF before saving."),!1;Ee(!0);try{const D=V.endsWith(".pdf")?V:`${V}.pdf`;let M=new File([h],D,{type:"application/pdf"});try{const E=await it(),me=new Blob([E],{type:"application/pdf"});M=new File([me],D,{type:"application/pdf"})}catch(E){console.warn("Could not bake annotations into this PDF; saving the original with structured annotations.",E)}return await s(h,M,re,A,V,P||I),f(!0),b||await as("Workpaper saved","The workpaper was saved to testing successfully."),pe.current=JSON.stringify(re),!0}catch(D){return console.error("Cloud save failed",D),alert("Failed to save workpaper to cloud (Server-Side)."),!1}finally{Ee(!1)}},dt=I?(G==null?void 0:G.orderedFiles.findIndex(l=>l.id===I))??-1:-1,he=dt>0?G==null?void 0:G.orderedFiles[dt-1]:void 0,be=dt>=0?G==null?void 0:G.orderedFiles[dt+1]:void 0,jt=i.useCallback(async()=>JSON.stringify(re)!==pe.current?ct(o||void 0,!0,I):!0,[I,re,o]);i.useEffect(()=>(ce==null||ce(jt),()=>ce==null?void 0:ce(null)),[ce,jt]);const Nt=async l=>{if(!(!l||!fe||l===I||x)){R(!0);try{if(!await jt())return;fe(l,{skipSave:!0})}finally{R(!1)}}},[ut,kt]=i.useState(!1),Qt=async()=>{if(!c){if(!h||!N||Object.keys(N).length===0){alert("No attributes or file to annotate.");return}kt(!0);try{const l=await h.arrayBuffer();let b=[];try{b=(await Yt.load(l,{ignoreEncryption:!0})).getPages().map(M=>M.getSize())}catch(D){console.warn("Could not read PDF dimensions for auto-annotation; using letter-page dimensions.",D)}if(!C){alert("You must be logged in to use AI features.");return}console.log("Calling suggestAnnotations",{controlName:F||(u==null?void 0:u.name),controlId:T||(u==null?void 0:u.controlId),selectedControlFull:u});const P=await As(C,h,N,F||(u==null?void 0:u.name),T||(u==null?void 0:u.controlId),H);if(P.length===0){alert("AI could not determine placement for annotations. Please check your notes and try again.");return}const A=P.flatMap(D=>{const M=Number.isFinite(D.page)&&D.page>0?Math.floor(D.page):1,E=Number(D.x),me=Number(D.y);if(!Number.isFinite(E)||!Number.isFinite(me))return console.warn("Skipping auto-annotation with invalid coordinates.",D),[];const Pt=b[M-1]||b[0],Ct=800*(Pt?Pt.height/Pt.width:11/8.5),ts=Math.max(0,Math.min(800,E/100*800)),ss=Math.max(0,Math.min(Ct,me/100*Ct));return[{id:Date.now()+Math.random().toString(),type:"badge",content:D.code,x:ts,y:ss,width:0,height:0,pageNumber:M}]});if(A.length===0){alert("AI could not determine valid placements for annotations. Please check your notes and try again.");return}Te(D=>[...D,...A])}catch(l){console.error("Auto-Annotation Failed:",l),alert("Failed to auto-annotate. Please try again.")}finally{kt(!1)}}},ze=ft.useMemo(()=>k?k.split(`
27`).filter(l=>l.trim()).map((l,b)=>{const P=l.match(/^(?:[-*•]\s*)?([A-Z]+|\d+)\s*[.):-]\s*(.*)$/i);return P?{id:P[1].toUpperCase(),description:P[2]||l}:{id:String.fromCharCode(65+b),description:l}}):[],[k]),Ae=ft.useMemo(()=>ur(re),[re]),mt=i.useCallback(l=>{Ae.some(b=>b.annotationId===l)&&(K.current+=1,ie({annotationId:l,requestId:K.current}))},[Ae]),Et=i.useCallback(()=>{const l=mr(Ae,B.selectedAnnotationId,B.activePageNumber);l&&mt(l.annotationId)},[mt,B.activePageNumber,B.selectedAnnotationId,Ae]);i.useEffect(()=>{if(!oe||z||!I)return;const l=new Map(ze.map(P=>[P.id,P.description])),b=Array.from(new Set(Ae.map(P=>P.pageNumber))).sort((P,A)=>P-A).map(P=>({pageNumber:P,label:`Page ${P}`}));
27oe({workpaperId:I,filename:V||(h==null?void 0:h.name)||"PDF workpaper",pages:b,tickmarks:Ae.map(P=>{var A;return{...P,description:l.get(P.attributeId),status:((A=N[P.attributeId])==null?void 0:A.status)||"Not Reviewed"}}),activePageNumber:B.activePageNumber,selectedAnnotationId:B.selectedAnnotationId})},[I,N,z,h==null?void 0:h.name,V,oe,ze,B.activePageNumber,B.selectedAnnotationId,Ae]),i.useEffect(()=>!p||z?void 0:(p({selectTickmark:mt,nextTickmark:Et}),()=>p(null)),[z,Et,mt,p]),i.useEffect(()=>()=>oe==null?void 0:oe(null),[oe]);const es=i.useCallback(l=>{Ue(l),l.length>0?Ve(0):Ve(-1)},[]),Dt=l=>{Ne.length!==0&&Ve(b=>l==="next"?(b+1)%Ne.length:(b-1+Ne.length)%Ne.length)};return e.jsxs("div",{className:"relative flex h-full min-h-0 w-full min-w-0 flex-col overflow-visible bg-[radial-gradient(circle_at_72%_8%,rgba(204,251,241,0.58),transparent_25%),radial-gradient(circle_at_20%_92%,rgba(219,234,254,0.52),transparent_30%),#f8fafc] text-slate-700",children:[!z&&e.jsxs("div",{className:"z-20 flex flex-col",children:[e.jsxs("div",{className:"flex h-[72px] shrink-0 items-center gap-3 rounded-t-2xl border-x border-t border-slate-200 bg-white px-4 sm:px-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2.5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[se&&e.jsx("button",{type:"button",onClick:se,className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-700",title:ne,"aria-label":ne,children:e.jsx(gs,{size:20})}),e.jsx("span",{className:"hidden h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-brand-50 to-cyan-100 text-brand-700 shadow-inner sm:flex",children:e.jsx(Zt,{size:20})}),Ze?e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:[e.jsx("input",{type:"text",value:V,onChange:l=>je(l.target.value),className:"min-w-0 flex-1 rounded-lg border border-brand-300 bg-white px-2.5 py-1.5 text-sm font-bold text-slate-700 shadow-sm focus:outline-none focus:ring-2 focus:ring-brand-200",autoFocus:!0,onKeyDown:l=>{l.key==="Enter"&&ve(!1),l.key==="Escape"&&(je((h==null?void 0:h.name)||""),ve(!1))}}),e.jsx("button",{onClick:()=>ve(!1),className:"p-1 hover:bg-green-100 text-green-600 rounded",children:e.jsx(It,{size:16})}),e.jsx("button",{onClick:()=>{je((h==null?void 0:h.name)||""),ve(!1)},className:"p-1 hover:bg-red-100 text-red-600 rounded",children:e.jsx(Gt,{size:16})})]}):e.jsxs("div",{className:"group flex min-w-0 flex-1 items-center gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"hidden text-[10px] font-bold uppercase tracking-[0.16em] text-slate-400 sm:block",children:"Workpaper"}),e.jsx("h2",{className:"truncate text-sm font-bold text-slate-800 sm:text-base",title:V,children:V||"No Document Loaded"})]}),h&&!c&&e.jsx("button",{onClick:()=>ve(!0),className:"p-1 text-slate-400 hover:text-brand-600 hover:bg-slate-100 rounded opacity-0 group-hover:opacity-100 transition",children:e.jsx(ws,{size:14})})]}),fe&&I&&e.jsxs("div",{className:"flex shrink-0 items-center rounded-lg border border-slate-200 bg-slate-50 p-0.5","aria-label":"Workpaper navigation controls",children:[e.jsx("button",{type:"button",onClick:()=>void Nt(he==null?void 0:he.id),disabled:!he||x||ke,title:he?`Previous file: ${he.name}`:"No previous file","aria-label":he?`Previous file: ${he.name}`:"No previous file",className:"flex min-h-8 min-w-8 items-center justify-center rounded-md text-slate-600 transition hover:bg-white hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-35",children:e.jsx(qt,{size:17})}),e.jsx("button",{type:"button",onClick:()=>void Nt(be==null?void 0:be.id),disabled:!be||x||ke,title:be?`Next file: ${be.name}`:"No next file","aria-label":be?`Next file: ${be.name}`:"No next file",className:"flex min-h-8 min-w-8 items-center justify-center rounded-md text-slate-600 transition hover:bg-white hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-35",children:x?e.jsx(le,{size:16,className:"animate-spin"}):e.jsx(Ge,{size:17})})]})]}),e.jsx("input",{ref:ue,type:"file",onClick:l=>{l.target.value=""},onChange:ot,accept:".pdf,.docx,.doc,image/png,image/jpeg,image/jpg,.xlsx,.csv,.ppt,.pptx,.txt,.msg,.eml",className:"hidden"})]}),h&&e.jsx("div",{className:"w-full max-w-48 shrink-0",children:e.jsx(Vs,{query:Me,setQuery:We,resultCount:Ne.length,currentResultIndex:Je,onNext:()=>Dt("next"),onPrev:()=>Dt("prev")})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[!c&&e.jsx("button",{onClick:()=>{var l;return(l=ue.current)==null?void 0:l.click()},disabled:De,className:"flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 bg-white/80 text-slate-700 shadow-sm transition-all hover:-translate-y-0.5 hover:border-brand-200 hover:bg-brand-50 disabled:opacity-50",title:"Replace workpaper","aria-label":"Replace workpaper",children:De?e.jsx(le,{size:17,className:"animate-spin"}):e.jsx(Lt,{size:17})}),e.jsx("button",{onClick:vt,disabled:!h||rt,className:"flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 bg-white/80 text-slate-700 shadow-sm transition-all hover:-translate-y-0.5 hover:border-brand-200 hover:bg-brand-50 disabled:opacity-50",title:n?"Download original file":"Download PDF","aria-label":n?"Download original file":"Download PDF",children:rt?e.jsx(le,{size:17,className:"animate-spin"}):e.jsx(vs,{size:17})}),s&&!c&&e.jsx("button",{onClick:lt,disabled:!h||ke,className:`${r?"bg-emerald-600 hover:bg-emerald-700":"bg-brand-600 hover:bg-brand-700"} flex h-10 w-10 items-center justify-center rounded-xl text-white shadow-[0_12px_22px_-14px_rgba(13,148,136,0.9)] transition-all hover:-translate-y-0.5 disabled:opacity-50`,title:"Save to Testing","aria-label":"Save to Testing",children:ke?e.jsx(le,{size:17,className:"animate-spin"}):e.jsx(ys,{size:17})})]})]}),e.jsxs("div",{className:"mt-0 flex w-full min-w-0 shrink-0 flex-nowrap items-center justify-center gap-1.5 overflow-x-auto border-x border-t border-slate-200 bg-white px-2 py-1.5 [scrollbar-width:thin]",children:[!c&&e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 rounded-xl border border-slate-200/80 bg-white/90 p-0.5 shadow-sm",children:[e.jsx(Tt,{active:$e==="select",onClick:()=>_e("select"),icon:e.jsx($t,{size:15}),label:"Select"}),e.jsx("div",{className:"mx-0.5 h-5 w-px bg-slate-200"}),e.jsx(Tt,{active:$e==="box",onClick:()=>_e("box"),icon:e.jsx(js,{size:15}),label:"Box"}),e.jsx(Tt,{active:$e==="text",onClick:()=>_e("text"),icon:e.jsx(Ns,{size:15}),label:"Text"}),e.jsx("div",{className:"mx-0.5 h-5 w-px bg-slate-200"}),e.jsxs("button",{onClick:Qt,disabled:ut||!h,className:`flex min-h-8 items-center gap-1 rounded-lg px-2 py-1 text-[11px] font-bold transition-all
28                                    ${ut?"bg-brand-50 text-brand-400 cursor-not-allowed":"bg-gradient-to-r from-brand-600 to-teal-500 text-white shadow-[0_8px_16px_
28-10px_rgba(13,148,136,0.9)] hover:-translate-y-0.5 hover:shadow-md"}`,children:[ut?e.jsx(le,{size:14,className:"animate-spin"}):e.jsx(Ps,{size:14}),ut?"Analyzing...":"Auto-Annotate"]})]}),!c&&ze.length>0&&!z&&e.jsx("div",{className:"flex shrink-0 items-center",children:e.jsxs("button",{onClick:()=>Ye(!Se),className:`flex min-h-8 items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-bold transition ${Se?"bg-brand-50 text-brand-600 border-brand-200":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:[e.jsx(Ss,{size:14,className:Se?"text-brand-500":"text-slate-400"}),"Attributes",e.jsx("span",{className:"ml-0.5 rounded-full bg-brand-500 px-1.5 py-0.5 text-[9px] font-bold text-white",children:ze.length})]})}),!c&&e.jsxs("div",{className:"flex shrink-0 items-center rounded-xl border border-slate-200/80 bg-white/90 p-0.5 shadow-sm",children:[e.jsx("button",{onClick:et,disabled:!gt,className:"rounded-lg p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-slate-900 disabled:cursor-not-allowed disabled:opacity-30",title:"Undo (Ctrl+Z)",children:e.jsx(Bt,{size:15})}),e.jsx("button",{onClick:tt,disabled:!Le,className:"ml-0.5 rounded-lg border-l border-slate-200 p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-slate-900 disabled:cursor-not-allowed disabled:opacity-30",title:"Redo (Ctrl+Y)",children:e.jsx(Ts,{size:15})})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("div",{className:"flex items-center rounded-xl border border-slate-200/80 bg-white/90 p-0.5 shadow-sm",children:[e.jsx("button",{onClick:()=>qe(-.1),className:"rounded-lg p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-slate-900",title:"Zoom Out",children:e.jsx(_s,{size:14})}),e.jsxs("span",{className:"w-10 select-none text-center text-[11px] font-bold text-slate-700",children:[Math.round(S*100),"%"]}),e.jsx("button",{onClick:()=>qe(.1),className:"rounded-lg p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-slate-900",title:"Zoom In",children:e.jsx(ks,{size:14})}),e.jsx("button",{onClick:()=>$(1),className:"ml-1 rounded-lg border-l border-slate-200 p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-slate-900",title:"Reset Zoom",children:e.jsx(Bt,{size:13})})]}),e.jsx("div",{ref:X,className:"empty:hidden"})]})]})]}),e.jsxs("div",{className:`mt-0 flex min-h-0 flex-1 overflow-hidden bg-white ${z?"rounded-2xl border border-white/80 shadow-[0_20px_46px_-34px_rgba(15,23,42,0.45)] backdrop-blur-xl":"rounded-b-2xl border-x border-b border-slate-200 shadow-[0_18px_40px_-30px_rgba(15,23,42,0.38)]"}`,children:[e.jsx("div",{className:`relative flex-1 ${z?"h-full w-full overflow-hidden bg-white":"flex justify-center overflow-auto bg-white"}`,children:z?e.jsx(ft.Suspense,{fallback:e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(le,{className:"animate-spin text-brand-600"})}),children:e.jsx(fr,{workbookId:z,onBack:se||te||(()=>{}),attributeStatuses:N,testRunId:o,onSaveToCloud:s,workspaceId:H,parsedAttributes:ze,readOnly:c,previousWorkpaper:he?{id:he.id,name:he.name}:void 0,nextWorkpaper:be?{id:be.id,name:be.name}:void 0,onNavigateWorkpaper:l=>{Nt(l)},isSwitchingWorkpaper:x,onReplaceWorkbook:ae,onUpdateAttributeStatus:xe,onWorkbookNavigationChange:ge,onRegisterWorkbookNavigation:W},z)}):He?e.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-4 text-slate-500",children:[e.jsx("div",{className:"flex h-20 w-20 items-center justify-center rounded-3xl border border-amber-100 bg-amber-50 text-amber-500 shadow-inner",children:e.jsx(Jt,{size:32})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-bold text-lg text-slate-700",children:"Preview Not Supported"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-md mx-auto",children:He})]}),!c&&e.jsx("button",{onClick:()=>{var l;return(l=ue.current)==null?void 0:l.click()},disabled:De,className:"bg-white border border-slate-300 text-slate-700 px-6 py-2 rounded-full font-bold hover:bg-slate-50 transition shadow-sm disabled:opacity-50 flex items-center gap-2 mt-4",children:De?e.jsxs(e.Fragment,{children:[e.jsx(le,{size:20,className:"animate-spin"})," Processing..."]}):"Select Different Document"})]}):n&&h?e.jsx(dr,{file:h}):Re?e.jsx(Gs,{pdfUrl:Re,selectedTool:$e,annotations:re,setAnnotations:Te,scale:S,attributeStatuses:N,searchQuery:Me,currentMatchIndex:Je,onSearchResults:es,readOnly:c,pageControlsContainer:L,textStyleControlsContainer:U,navigationTarget:_,onNavigationStateChange:Q},I||Re):e.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-5 px-6 text-slate-400",children:[e.jsx("div",{className:"flex h-20 w-20 items-center justify-center rounded-3xl border border-brand-100 bg-gradient-to-br from-brand-50 to-cyan-100 text-brand-500 shadow-[inset_0_1px_0_rgba(255,255,255,0.9),0_14px_28px_-20px_rgba(13,148,136,0.65)]",children:e.jsx(Lt,{size:30})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-bold text-slate-700",children:"Your workpaper canvas is ready"}),e.jsx("p",{className:"mt-1 max-w-sm text-sm leading-relaxed text-slate-400",children:"Upload a PDF, Word, Excel, or image to start reviewing, annotating, and documenting evidence."})]}),!c&&e.jsx("button",{onClick:()=>{var l;return(l=ue.current)==null?void 0:l.click()},disabled:De,className:"flex items-center gap-2 rounded-xl bg-brand-600 px-5 py-2.5 text-sm font-bold text-white shadow-[0_14px_25px_-16px_rgba(13,148,136,0.9)] transition-all hover:-translate-y-0.5 hover:bg-brand-700 disabled:opacity-50",children:De?e.jsxs(e.Fragment,{children:[e.jsx(le,{size:20,className:"animate-spin"})," Processing..."]}):"Select Document"})]})}),!c&&Se&&ze.length>0&&Re&&!z&&e.jsxs("div",{className:"z-20 flex w-80 flex-col border-l border-white/80 bg-white/80 shadow-[-18px_0_38px_-30px_rgba(15,23,42,0.45)] backdrop-blur-xl",children:[e.jsx("div",{className:"border-b border-slate-100 bg-white/45 p-4",children:e.jsxs("h3",{className:"text-xs font-black text-slate-500 uppercase tracking-wider flex items-center gap-2",children:[e.jsx($t,{size:12}),"Tickmark Attributes"]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3",children:[e.jsx("p",{className:"mb-4 text-xs italic text-slate-400",children:"Drag attributes onto the workpaper to annotate."}),ze.map(l=>{const b=N[l.id],P=(b==null?void 0:b.status)||"Not Reviewed",A=Ie===l.id;let D="bg-slate-500 border-slate-600 text-white";P==="Pass"?D="bg-emerald-600 border-emerald-700 text-white":P==="Fail"?D="bg-red-600 border-red-700 text-white":P==="N/A"&&(D="bg-blue-600 border-blue-700 text-white");const M=ht===l.id;return e.jsx("div",{draggable:!0,onDragStart:E=>{E.dataTransfer.setData("attributeId",l.id),E.dataTransfer.setData("attributeDesc",l.description),E.dataTransfer.effectAllowed="copy"},onClick:()=>bt(M?null:l.id),className:`bg-white border rounded-lg p-3 shadow-sm hover:shadow-md transition cursor-pointer group mb-2 ${M?"border-brand-500 ring-1 ring-brand-500":"border-slate-200 hover:border-brand-300"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx("button",{type:"button",onClick:E=>{E.stopPropagation(),Ke(A?null:l.id)},onPointerDown:E=>E.stopPropagation(),"aria-label":`Change conclusion for tickmark ${l.id}; currently ${P}`,"aria-haspopup":"menu","aria-expanded":A,title:`Tickmark conclusion: ${P}`,className:`flex h-8 w-8 items-center justify-center rounded-full border font-bold text-sm shadow-sm transition hover:scale-105 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 focus-visible:ring-offset-2 ${D}`,children:l.id}),A&&e.jsx("div",{role:"menu","aria-label":`Tickmark ${l.id} conclusion options`,onClick:E=>E.stopPropagation(),onPointerDown:E=>E.stopPropagation(),className:"absolute left-0 top-10 z-50 w-52 overflow-hidden rounded-lg border border-slate-300 bg-white py-1 shadow-xl",children:[{value:"Pass",label:"Pass",icon:e.jsx(Es,{size:18}),className:"text-lime-600"},{value:"Fail",label:"Fail",icon:e.jsx(Ds,{size:18}),className:"text-red-600"},{value:"N/A",label:"Not Applicable",icon:e.jsx("span",{className:"inline-flex h-[18px] w-[18px] items-center justify-center rounded-full bg-blue-500 text-[9px] font-black text-white",children:"NA"}),className:"text-blue-600"},{value:"Not Reviewed",label:"Not Reviewed",icon:e.jsx(Cs,{size:18}),className:"text-slate-600"}].map(E=>e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":P===E.value,disabled:ye===l.id,onClick:()=>
28void Xe(l.id,E.value),className:"flex w-full items-center gap-2 px-3 py-2 text-left text-sm font-semibold text-slate-700 transition hover:bg-slate-50 disabled:cursor-wait disabled:opacity-60",children:[e.jsx("span",{className:E.className,children:E.icon}),E.label,P===E.value&&e.jsx(It,{size:15,className:"ml-auto text-brand-600"})]},E.value))})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-xs text-slate-600 leading-relaxed ${M?"":"line-clamp-2"}`,children:l.description}),M&&b&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-slate-100 space-y-2 animate-in slide-in-from-top-2 fade-in duration-200",children:[b.testingNotes&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wide",children:"Testing Notes"}),e.jsx("p",{className:"text-xs text-slate-700 mt-0.5",children:b.testingNotes})]}),b.reference&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wide",children:"Reference"}),e.jsx("p",{className:"text-xs text-slate-700 mt-0.5 font-mono bg-slate-50 px-1 py-0.5 bg-slate-50 rounded inline-block",children:b.reference})]}),!b.testingNotes&&!b.reference&&e.jsx("p",{className:"text-xs text-slate-400 italic",children:"No additional details in memo."})]})]})]})},l.id)})]})]})]}),e.jsx("div",{ref:Y,className:"empty:hidden absolute left-1/2 top-full z-30 mt-3 flex -translate-x-1/2 justify-center"}),nt&&e.jsx(cr,{controls:v,workspaceId:H,onSelect:yt,onClose:()=>Fe(!1)})]})},Tt=({active:a,onClick:t,icon:c,label:o})=>e.jsxs("button",{onClick:t,title:o,className:`group relative flex min-h-8 min-w-8 items-center justify-center rounded-lg p-1.5 transition-all ${a?"bg-brand-50 text-brand-700 shadow-sm ring-1 ring-brand-100":"text-slate-500 hover:bg-slate-100 hover:text-slate-800"}`,children:[c,e.jsx("span",{className:"absolute -bottom-8 left-1/2 -translate-x-1/2 bg-slate-800 text-white text-[10px] px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition pointer-events-none whitespace-nowrap z-50",children:o})]});export{Br as WorkpaperView};

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.