From da1dd79ef200f224dd230da8410a7c34f7eb2883 Mon Sep 17 00:00:00 2001 From: Ross Date: Wed, 20 May 2026 21:13:08 +0100 Subject: [PATCH] up dv3d --- rad/static/dv3d/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rad/static/dv3d/index.js b/rad/static/dv3d/index.js index 2390a154..14daf298 100644 --- a/rad/static/dv3d/index.js +++ b/rad/static/dv3d/index.js @@ -3857,4 +3857,4 @@ throwBindingError('function `+$+" called with ' + arguments.length + ' arguments `,kt.push(_n+"_dtor"),In.push(K[Re].destructorFunction))}Fe&&(It+=`var ret = retType.fromWireType(rv); return ret; `),It+=`} -`,kt.push(It);var rr=Vi(Function,kt).apply(null,In);return rr}function bi($,K,R,U,X,ge){T(K>0);var xe=ki(K,R);X=vr(U,X),Hr([],[$],function(be){be=be[0];var Re="constructor "+be.name;if(be.registeredClass.constructor_body===void 0&&(be.registeredClass.constructor_body=[]),be.registeredClass.constructor_body[K-1]!==void 0)throw new Bo("Cannot register multiple constructors with identical number of parameters ("+(K-1)+") for class '"+be.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return be.registeredClass.constructor_body[K-1]=()=>{yr("Cannot construct "+be.name+" due to unbound types",xe)},Hr([],xe,function(Fe){return Fe.splice(1,0,null),be.registeredClass.constructor_body[K-1]=di(Re,Fe,null,X,ge),[]}),[]})}function Za($,K,R,U,X,ge,xe,be){var Re=ki(R,U);K=Vr(K),ge=vr(X,ge),Hr([],[$],function(Fe){Fe=Fe[0];var Xe=Fe.name+"."+K;K.startsWith("@@")&&(K=Symbol[K.substring(2)]),be&&Fe.registeredClass.pureVirtualFunctions.push(K);function ht(){yr("Cannot call "+Xe+" due to unbound types",Re)}var It=Fe.registeredClass.instancePrototype,jt=It[K];return jt===void 0||jt.overloadTable===void 0&&jt.className!==Fe.name&&jt.argCount===R-2?(ht.argCount=R-2,ht.className=Fe.name,It[K]=ht):(ji(It,K,Xe),It[K].overloadTable[R-2]=ht),Hr([],Re,function(kt){var In=di(Xe,kt,Fe,ge,xe);return It[K].overloadTable===void 0?(In.argCount=R-2,It[K]=In):It[K].overloadTable[R-2]=In,[]}),[]})}var Qa=[],Hi=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function Uc($){$>4&&--Hi[$].refcount===0&&(Hi[$]=void 0,Qa.push($))}function Al(){for(var $=0,K=5;K($||kn("Cannot use deleted val. handle = "+$),Hi[$].value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var K=Qa.length?Qa.pop():Hi.length;return Hi[K]={refcount:1,value:$},K}}}};function Es($,K){K=Vr(K),ni($,{name:K,fromWireType:function(R){var U=Ia.toValue(R);return Uc(R),U},toWireType:function(R,U){return Ia.toHandle(U)},argPackAdvance:8,readValueFromPointer:sr,destructorFunction:null})}function Zs($){if($===null)return"null";var K=typeof $;return K==="object"||K==="array"||K==="function"?$.toString():""+$}function Nl($,K){switch(K){case 2:return function(R){return this.fromWireType(J[R>>2])};case 3:return function(R){return this.fromWireType(oe[R>>3])};default:throw new TypeError("Unknown float type: "+$)}}function Gc($,K,R){var U=Ai(R);K=Vr(K),ni($,{name:K,fromWireType:function(X){return X},toWireType:function(X,ge){return ge},argPackAdvance:8,readValueFromPointer:Nl(K,U),destructorFunction:null})}function Qs($,K,R,U,X,ge){var xe=ki(K,R);$=Vr($),X=vr(U,X),qr($,function(){yr("Cannot call "+$+" due to unbound types",xe)},K-1),Hr([],xe,function(be){var Re=[be[0],null].concat(be.slice(1));return Ya($,di($,Re,null,X,ge),K-1),[]})}function Wc($,K,R){switch(K){case 0:return R?function(X){return V[X]}:function(X){return W[X]};case 1:return R?function(X){return A[X>>1]}:function(X){return k[X>>1]};case 2:return R?function(X){return F[X>>2]}:function(X){return H[X>>2]};default:throw new TypeError("Unknown integer type: "+$)}}function ec($,K,R,U,X){K=Vr(K);var ge=Ai(R),xe=ht=>ht;if(U===0){var be=32-8*R;xe=ht=>ht<>>be}var Re=K.includes("unsigned"),Fe=(ht,It)=>{},Xe;Re?Xe=function(ht,It){return Fe(It,this.name),It>>>0}:Xe=function(ht,It){return Fe(It,this.name),It},ni($,{name:K,fromWireType:xe,toWireType:Xe,argPackAdvance:8,readValueFromPointer:Wc(K,ge,U!==0),destructorFunction:null})}function tc($,K,R){var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],X=U[K];function ge(xe){xe=xe>>2;var be=H,Re=be[xe],Fe=be[xe+1];return new X(L,Fe,Re)}R=Vr(R),ni($,{name:R,fromWireType:ge,argPackAdvance:8,readValueFromPointer:ge},{ignoreDuplicateRegistrations:!0})}function zc($,K){K=Vr(K);var R=K==="std::string";ni($,{name:K,fromWireType:function(U){var X=H[U>>2],ge=U+4,xe;if(R)for(var be=ge,Re=0;Re<=X;++Re){var Fe=ge+Re;if(Re==X||W[Fe]==0){var Xe=Fe-be,ht=D(be,Xe);xe===void 0?xe=ht:(xe+="\0",xe+=ht),be=Fe+1}}else{for(var It=new Array(X),Re=0;Re>2]=ge,R&&xe)P(X,Re,ge+1);else if(xe)for(var Fe=0;Fe255&&(Ee(Re),kn("String has UTF-16 code units that do not fit in 8 bits")),W[Re+Fe]=Xe}else for(var Fe=0;Fe>1,X=U+K/2;!(U>=X)&&k[U];)++U;if(R=U<<1,R-$>32&&bs)return bs.decode(W.subarray($,R));for(var ge="",xe=0;!(xe>=K/2);++xe){var be=A[$+xe*2>>1];if(be==0)break;ge+=String.fromCharCode(be)}return ge}function rc($,K,R){if(R===void 0&&(R=2147483647),R<2)return 0;R-=2;for(var U=K,X=R<$.length*2?R/2:$.length,ge=0;ge>1]=xe,K+=2}return A[K>>1]=0,K-U}function sa($){return $.length*2}function kl($,K){for(var R=0,U="";!(R>=K/4);){var X=F[$+R*4>>2];if(X==0)break;if(++R,X>=65536){var ge=X-65536;U+=String.fromCharCode(55296|ge>>10,56320|ge&1023)}else U+=String.fromCharCode(X)}return U}function ic($,K,R){if(R===void 0&&(R=2147483647),R<4)return 0;for(var U=K,X=U+R-4,ge=0;ge<$.length;++ge){var xe=$.charCodeAt(ge);if(xe>=55296&&xe<=57343){var be=$.charCodeAt(++ge);xe=65536+((xe&1023)<<10)|be&1023}if(F[K>>2]=xe,K+=4,K+4>X)break}return F[K>>2]=0,K-U}function oc($){for(var K=0,R=0;R<$.length;++R){var U=$.charCodeAt(R);U>=55296&&U<=57343&&++R,K+=4}return K}function $c($,K,R){R=Vr(R);var U,X,ge,xe,be;K===2?(U=nc,X=rc,xe=sa,ge=()=>k,be=1):K===4&&(U=kl,X=ic,xe=oc,ge=()=>H,be=2),ni($,{name:R,fromWireType:function(Re){for(var Fe=H[Re>>2],Xe=ge(),ht,It=Re+4,jt=0;jt<=Fe;++jt){var kt=Re+4+jt*K;if(jt==Fe||Xe[kt>>be]==0){var In=kt-It,_n=U(It,In);ht===void 0?ht=_n:(ht+="\0",ht+=_n),It=kt+K}}return Ee(Re),ht},toWireType:function(Re,Fe){typeof Fe!="string"&&kn("Cannot pass non-string to C++ string type "+R);var Xe=xe(Fe),ht=te(4+Xe+K);return H[ht>>2]=Xe>>be,X(Fe,ht+4,Xe+K),Re!==null&&Re.push(Ee,ht),ht},argPackAdvance:8,readValueFromPointer:sr,destructorFunction:function(Re){Ee(Re)}})}function Oa($,K,R,U,X,ge){Cn[$]={name:Vr(K),rawConstructor:vr(R,U),rawDestructor:vr(X,ge),fields:[]}}function Ds($,K,R,U,X,ge,xe,be,Re,Fe){Cn[$].fields.push({fieldName:Vr(K),getterReturnType:R,getter:vr(U,X),getterContext:ge,setterArgumentType:xe,setter:vr(be,Re),setterContext:Fe})}function jc($,K){K=Vr(K),ni($,{isVoid:!0,name:K,argPackAdvance:0,fromWireType:function(){},toWireType:function(R,U){}})}function _r($){$>4&&(Hi[$].refcount+=1)}function Is($,K){var R=xt[$];return R===void 0&&kn(K+" has unknown type "+sn($)),R}function ac($,K){$=Is($,"_emval_take_value");var R=$.readValueFromPointer(K);return Ia.toHandle(R)}function Os(){Ye("")}function Vl($,K,R){W.copyWithin($,K,K+R)}function Fl(){return 2147483648}function Ms($){try{return S.grow($-L.byteLength+65535>>>16),ve(S.buffer),1}catch{}}function Wo($){var K=W.length;$=$>>>0;var R=Fl();if($>R)return!1;let U=(Re,Fe)=>Re+(Fe-Re%Fe)%Fe;for(var X=1;X<=4;X*=2){var ge=K*(1+.2/X);ge=Math.min(ge,$+100663296);var xe=Math.min(R,U(Math.max($,ge),65536)),be=Ms(xe);if(be)return!0}return!1}function zo($){return 52}function io($,K,R,U,X){return 70}var Mo=[null,[],[]];function Hc($,K){var R=Mo[$];K===0||K===10?(($===1?w:x)(b(R,0)),R.length=0):R.push(K)}function sc($,K,R,U){for(var X=0,ge=0;ge>2],be=H[K+4>>2];K+=8;for(var Re=0;Re>2]=X,0}function cc($){return $}function Kc($){var K=o["_"+$];return K}function Ps($,K){V.set($,K)}function qc($,K,R,U,X){var ge={string:kt=>{var In=0;if(kt!=null&&kt!==0){var _n=(kt.length<<2)+1;In=ft(_n),P(kt,In,_n)}return In},array:kt=>{var In=ft(kt.length);return Ps(kt,In),In}};function xe(kt){return K==="string"?D(kt):K==="boolean"?!!kt:kt}var be=Kc($),Re=[],Fe=0;if(U)for(var Xe=0;Xe0||(Pe(),Q>0))return;function K(){pt||(pt=!0,o.calledRun=!0,!_&&(B(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),O()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),K()},1)):K()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return dt(),o.ready}})();t.exports=r})(DW);var Z3e=DW.exports;const Q3e=Ml(Z3e),eSe=new URL("/static/dv3d/openjphjs.wasm",import.meta.url),dp={codec:void 0,decoder:void 0,decodeConfig:{}};function tSe(t,e,r){const n={width:e,height:r};for(;t>0;)n.width=Math.ceil(n.width/2),n.height=Math.ceil(n.height/2),t--;return n}function nSe(t){if(dp.decodeConfig=t,dp.codec)return Promise.resolve();const e=Q3e({locateFile:r=>r.endsWith(".wasm")?eSe.toString():r});return new Promise((r,n)=>{e.then(i=>{dp.codec=i,dp.decoder=new i.HTJ2KDecoder,r()},n)})}async function rSe(t,e){await nSe();const r=new dp.codec.HTJ2KDecoder,n=r.getEncodedBuffer(t.length);n.set(t);const i=e.decodeLevel||0;r.decodeSubResolution(i);const o=r.getFrameInfo();if(e.decodeLevel>0){const{width:E,height:b}=tSe(e.decodeLevel,o.width,o.height);o.width=E,o.height=b}const a=r.getDecodedBuffer();new Uint8Array(a.length).set(a);const c=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,l=r.getNumDecompositions(),f=r.getNumLayers(),u=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],d=r.getIsReversible(),h=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,g=`${r.getTileSize().width} x ${r.getTileSize().height}`,p=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,v=`${a.length.toLocaleString()} bytes`,y=`${(a.length/n.length).toFixed(2)}:1`,m={columns:o.width,rows:o.height,bitsPerPixel:o.bitsPerSample,signed:o.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:o.componentCount};let w=iSe(o,a);const{buffer:x,byteOffset:C,byteLength:S}=w,_=x.slice(C,C+S);w=new w.constructor(_);const T={imageOffset:c,numDecompositions:l,numLayers:f,progessionOrder:u,reversible:d,blockDimensions:h,tileSize:g,tileOffset:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:T,...T,...m}}function iSe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function oSe(t,e){const r=t.length,{rescaleSlope:n,rescaleIntercept:i,suvbw:o,doseGridScaling:a}=e;if(e.modality==="PT"&&typeof o=="number"&&!isNaN(o))for(let s=0;s>o;let a=t.pixelData;t.pixelDataLength=t.pixelData.length;const{min:s,max:c}=jw(t.pixelData),l=typeof e.allowFloatRendering<"u"?e.allowFloatRendering:!0;let f=d8(t.photometricInterpretation)&&((m=e.targetBuffer)==null?void 0:m.offset)===void 0;const d=((w=e.preScale)==null?void 0:w.enabled)&&Object.values(e.preScale.scalingParameters).some(C=>typeof C=="number"&&!Number.isInteger(C)),h=!e.preScale.enabled||!l&&d,g=(x=e.targetBuffer)==null?void 0:x.type;if(g&&e.preScale.enabled&&!h){const C=e.preScale.scalingParameters,S=o_(s,c,C);f=!UCe(S.min,S.max,WI[g])}g&&!f?a=lSe(e,t,WI,a):e.preScale.enabled&&!h?a=uSe(e,s,c,t):a=IW(s,c,t);let p=s,v=c;if(e.preScale.enabled&&!h){const C=e.preScale.scalingParameters;if(OW(C),cSe(C)){oSe(a,C),t.preScale={...e.preScale,scaled:!0};const _=o_(s,c,C);p=_.min,v=_.max}}else h&&(t.preScale={enabled:!0,scaled:!1},p=s,v=c);t.pixelData=a,t.smallestPixelValue=p,t.largestPixelValue=v;const y=new Date().getTime();return t.decodeTimeInMS=y-r,t}function cSe(t){const{rescaleSlope:e,rescaleIntercept:r,modality:n,doseGridScaling:i,suvbw:o}=t;return typeof e=="number"&&typeof r=="number"||n==="RTDOSE"&&typeof i=="number"||n==="PT"&&typeof o=="number"}function lSe(t,e,r,n){const{arrayBuffer:i,type:o,offset:a=0,length:s,rows:c}=t.targetBuffer,l=r[o];if(!l)throw new Error(`target array ${o} is not supported, or doesn't exist.`);c&&c!=e.rows&&dSe(e,t.targetBuffer,l);const f=e.pixelDataLength,u=a,d=s??f-u,h=e.pixelData;if(d!==h.length)throw new Error(`target array for image does not have the same length (${d}) as the decoded image length (${h.length}).`);const g=i?new l(i,u,d):new l(d);return g.set(h,0),n=g,n}function uSe(t,e,r,n){const i=t.preScale.scalingParameters;OW(i);const o=o_(e,r,i);return IW(o.min,o.max,n)}function IW(t,e,r){const n=h8(t,e),i=new n(r.pixelData.length);return i.set(r.pixelData,0),i}function o_(t,e,r){const{rescaleSlope:n,rescaleIntercept:i,modality:o,doseGridScaling:a,suvbw:s}=r;return o==="PT"&&typeof s=="number"&&!isNaN(s)?{min:s*(t*n+i),max:s*(e*n+i)}:o==="RTDOSE"&&typeof a=="number"&&!isNaN(a)?{min:t*a,max:e*a}:typeof n=="number"&&typeof i=="number"?{min:n*t+i,max:n*e+i}:{min:t,max:e}}function OW(t){if(!t)throw new Error("options.preScale.scalingParameters must be defined if preScale.enabled is true, and scalingParameters cannot be derived from the metadata providers.")}function fSe(t,e,r){const{samplesPerPixel:n}=t,{rows:i,columns:o}=e,a=i*o*n,s=new r(a),c=s.byteLength/a;return{pixelData:s,rows:i,columns:o,frameInfo:{...t.frameInfo,rows:i,columns:o},imageInfo:{...t.imageInfo,rows:i,columns:o,bytesPerPixel:c}}}function dSe(t,e,r){const n=fSe(t,e,r),{scalingType:i="replicate"}=e;return aSe[i](t,n),Object.assign(t,n),t.pixelDataLength=t.pixelData.length,t}async function MW(t,e,r,n,i,o){const a=new Date().getTime();let s=null,c;switch(e){case"1.2.840.10008.1.2":case"1.2.840.10008.1.2.1":s=VI(t,r);break;case"1.2.840.10008.1.2.2":s=E3e(t,r);break;case"1.2.840.10008.1.2.1.99":s=VI(t,r);break;case"1.2.840.10008.1.2.5":s=b3e(t,r);break;case"1.2.840.10008.1.2.4.50":c={...t},s=A3e(r,c);break;case"1.2.840.10008.1.2.4.51":s=U3e(t,r);break;case"1.2.840.10008.1.2.4.57":s=UI(t,r);break;case"1.2.840.10008.1.2.4.70":s=UI(t,r);break;case"1.2.840.10008.1.2.4.80":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=BI(r,c);break;case"1.2.840.10008.1.2.4.81":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=BI(r,c);break;case"1.2.840.10008.1.2.4.90":c={...t},s=GI(r,c);break;case"1.2.840.10008.1.2.4.91":c={...t},s=GI(r,c);break;case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":c={...t},s=rSe(r,c);break;default:throw new Error(`no decoder for transfer syntax ${e}`)}if(!s)throw new Error("decodePromise not defined");const l=await s,f=sSe(l,i,a);return o==null||o(f),f}const hSe={decodeTask({imageFrame:t,transferSyntax:e,decodeConfig:r,options:n,pixelData:i,callbackFn:o}){return MW(t,e,i,r,n,o)}};i4(hSe);const Uu={constants:C3e,convertRGBColorByPixel:UG,convertRGBColorByPlane:BG,convertYBRFullByPixel:GG,convertYBRFullByPlane:WG,convertPALETTECOLOR:zG,wadouri:$Ce,wadors:p3e,init:SW,convertColorSpace:cW,createImage:Hw,decodeJPEGBaseline8BitColor:lW,getImageFrame:uW,getPixelData:v8,getMinMax:jw,isColorImage:d8,isJPEGBaseline8BitColor:w3e,internal:oCe,decodeImageFrame:MW},zI={debug:0,info:1,warn:2,error:3,silent:4},y8={minLevel:"warn",format:"compact",namespace:"dv3d",dedupeWindowMs:1200};let $s={...y8};const $I=new Map;function PW(){return new Date().toISOString()}function jI(t){return t==="debug"?console.debug.bind(console):t==="info"?console.info.bind(console):t==="warn"?console.warn.bind(console):console.error.bind(console)}function RW(t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t}function gSe(t){return zI[t]>=zI[$s.minLevel]}function pSe(t){return t==="debug"||t==="info"}function mSe(t,e,r){const n=(r==null?void 0:r.dedupeKey)||`${(r==null?void 0:r.namespace)||$s.namespace}:${t}`,i=e.map(o=>{if(typeof o=="string")return o;try{return JSON.stringify(RW(o))}catch{return String(o)}}).join("|");return`${n}:${i}`}function vSe(t,e,r){if(!pSe(t)||$s.dedupeWindowMs<=0)return!1;const n=mSe(t,e,r),i=Date.now(),o=$I.get(n);return $I.set(n,i),o===void 0?!1:i-o<$s.dedupeWindowMs}function ySe(t,e){const r=e||$s.namespace;return $s.format==="compact"?`[${r}] ${t.toUpperCase()}`:$s.format==="verbose"?`[${PW()}] [${r}] [${t.toUpperCase()}]`:""}function Bu(t,e,r){if(!gSe(t)||vSe(t,e,r))return;if($s.format==="json"){jI(t)({ts:PW(),namespace:(r==null?void 0:r.namespace)||$s.namespace,level:t,message:e.map(RW)});return}const n=ySe(t,r==null?void 0:r.namespace);jI(t)(n,...e)}function w8(t){return $s={...$s,...t},m5()}function m5(){return{...$s}}function Wp(t){return t==="compact"||t==="verbose"||t==="json"?t:y8.format}function v5(t){return t==="debug"||t==="info"||t==="warn"||t==="error"||t==="silent"?t:y8.minLevel}function a_(t){if(typeof t=="boolean")return t?"debug":"warn";if(typeof t=="string"){const e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"?"debug":"warn"}return typeof t=="number"&&t!==0?"debug":"warn"}const LW={debug:(...t)=>Bu("debug",t),info:(...t)=>Bu("info",t),warn:(...t)=>Bu("warn",t),error:(...t)=>Bu("error",t),child:t=>({debug:(...e)=>Bu("debug",e,{namespace:t}),info:(...e)=>Bu("info",e,{namespace:t}),warn:(...e)=>Bu("warn",e,{namespace:t}),error:(...e)=>Bu("error",e,{namespace:t})})};class Gh extends Uf{}j8(Gh,"toolName","NoLabelArrowAnnotate");function HI(t,e){const r=Ct("imagePlaneModule",t);if(!r)return;const{rowCosines:n,columnCosines:i,imagePositionPatient:o,rowPixelSpacing:a,columnPixelSpacing:s}=r;if(!n||!i||!o)return;const c=s||1,l=a||1;return{x:o[0]+n[0]*e.y*l+i[0]*e.x*c,y:o[1]+n[1]*e.y*l+i[1]*e.x*c,z:o[2]+n[2]*e.y*l+i[2]*e.x*c}}const{MouseBindings:jg,KeyboardBindings:KI}=Ck,{IMAGE_RENDERED:Hg}=lt,wSe=[{name:"Soft Tissue",center:40,width:400},{name:"Lung",center:-600,width:1500},{name:"Bone",center:300,width:1500},{name:"Brain",center:40,width:80},{name:"Abdomen",center:60,width:400}],qI=t=>{const e=(t||"").toUpperCase(),r=[{name:"Reset to default",action:"reset"},{name:"Auto level",action:"autolevel"}];return e!=="CT"?r:[...r,...wSe.map(n=>({name:n.name,action:"preset",center:n.center,width:n.width}))]},dd=[{label:"Window/Level",value:Yd.toolName,icon:"🌓"},{label:"Pan",value:Cc.toolName,icon:"✋"},{label:"Zoom",value:ll.toolName,icon:"🔍"},{label:"Stack Scroll",value:_f.toolName,icon:"📚"},{label:"Rotate",value:Vh.toolName,icon:"↺"},{label:"Length",value:Ff.toolName,icon:"📏"},{label:"Probe",value:_u.toolName,icon:"🔎"},{label:"Arrow (No Label)",value:Gh.toolName,icon:"➡️"},{label:"Arrow Annotate",value:Uf.toolName,icon:"✈️"},{label:"Rectangle ROI",value:Su.toolName,icon:"▭"},{label:"Ellipse ROI",value:Jd.toolName,icon:"◯"},{label:"Freehand ROI",value:Vf.toolName,icon:"✏️"},{label:"Freehand Contour Segmentation",value:Il.toolName,icon:"🖊️"},{label:"Sculptor",value:Fh.toolName,icon:"🔧"},{label:"Reference Cursors",value:os.toolName,icon:"⦿"}],xSe=3,CSe=220,XI="dv3d_logging",SSe=[{label:"Compact",value:"compact"},{label:"Verbose",value:"verbose"},{label:"JSON",value:"json"}],_Se=[{label:"Off",value:"silent"},{label:"Error",value:"error"},{label:"Warn",value:"warn"},{label:"Info",value:"info"},{label:"Debug",value:"debug"}],YI="dv3d_grouping",hp=[{id:"dwiBValue",label:"DWI b-value",description:"DiffusionBValue (0018,9087) + known private fallbacks",defaultEnabled:!0},{id:"dwiDirection",label:"DWI direction",description:"Diffusion Gradient Direction (0018,9089)",defaultEnabled:!0},{id:"temporalPosition",label:"Temporal position",description:"Temporal Position Identifier (0020,0100)",defaultEnabled:!0},{id:"triggerTime",label:"Trigger time",description:"Trigger Time (0018,1060)",defaultEnabled:!0},{id:"contentTime",label:"Content/Acquisition time",description:"Content Time (0008,0033) / Acquisition Time (0008,0032)",defaultEnabled:!1},{id:"echoTime",label:"Echo time",description:"Echo Time (0018,0081)",defaultEnabled:!0},{id:"echoNumber",label:"Echo number",description:"Echo Number (0018,0086)",defaultEnabled:!0}];function JI(){return hp.reduce((t,e)=>(t[e.id]=e.defaultEnabled,t),{})}const Nt=LW.child("app");function ZI(t){if(!t)return"🔖";const e=dd.find(r=>r.value===t||r.label===t);return(e==null?void 0:e.icon)||"🔖"}function Qc(t){return t?t.startsWith("wadouri:")?t.replace(/^wadouri:+/,"").replace(/^:+/,""):t:""}function s_(t){return/([?&])frame=\d+/i.test(t)}function QI(t,e){const r=Math.max(1,Math.floor(e));return s_(t)?t.replace(/([?&])frame=\d+/i,`$1frame=${r}`):`${t}&frame=${r}`}function e7(t){const e=t.match(/[?&]frame=(\d+)/i);if(!e)return null;const r=Number(e[1]);return Number.isFinite(r)&&r>0?Math.floor(r):null}function y5(t){return t?t.split(/\\|,/).map(e=>Number(e.trim())).filter(e=>Number.isFinite(e)):[]}function OC(t){if(!t||typeof t!="object")return[];const e=o=>{if(typeof t.string=="function"){const a=t.string(o);if(a!=null&&a!==""){const s=y5(a);if(s.length>0&&Number.isFinite(s[0])&&s[0]>=0)return s[0]}}if(typeof t.double=="function")try{const a=t.double(o);if(Number.isFinite(a)&&a>=0)return a}catch{}if(typeof t.float=="function")try{const a=t.float(o);if(Number.isFinite(a)&&a>=0)return a}catch{}return null},r=e("x00189087");if(r!==null)return[r];const n=e("x0019100c");if(n!==null)return[n];if(typeof t.string=="function"){const o=t.string("x00431039");if(o){const a=y5(o);if(a.length>0&&Number.isFinite(a[0])&&a[0]>=0)return[a[0]]}}const i=e("x20011003");return i!==null?[i]:[]}function Gu(t){return t.startsWith("wadouri:")||t.startsWith("external:")?t:`wadouri:${t}`}function Wu(t){const e=new Set,r=[];for(const n of t)!n||e.has(n)||(e.add(n),r.push(n));return r}function TSe(t){try{const e=t.getContext("2d",{willReadFrequently:!0});if(!e)return!0;const r=t.width||160,n=t.height||160,o=e.getImageData(0,0,r,n).data;let a=255,s=0,c=0,l=0;for(let d=0;d0&&w>12&&(c+=1),a=Math.min(a,w),s=Math.max(s,w),l+=1}if(l===0)return!0;const f=c/l,u=s-a;return f>.015||u>8}catch{return!0}}const t7=[{label:"Left",value:"Primary"},{label:"Middle",value:"Auxiliary"},{label:"Right",value:"Secondary"}],z2=[{label:"Left",value:"Primary",mask:1},{label:"Middle",value:"Auxiliary",mask:4},{label:"Right",value:"Secondary",mask:2},{label:"Left + Right",value:"Primary_and_Secondary",mask:3},{label:"Left + Middle",value:"Primary_and_Auxiliary",mask:5},{label:"Right + Middle",value:"Secondary_and_Auxiliary",mask:6},{label:"Left + Right + Middle",value:"Primary_and_Secondary_and_Auxiliary",mask:7},{label:"Fourth Button",value:"Fourth_Button",mask:8},{label:"Fifth Button",value:"Fifth_Button",mask:16},{label:"Mouse Wheel",value:"Wheel",mask:524288},{label:"Mouse Wheel + Left",value:"Wheel_Primary",mask:524289}];function ESe({container_id:t,imageStacks:e,autoCacheStack:r,annotationJson:n,viewerState:i,initialLoggerConfig:o}){var Mt,Yt,rn,cn,Z,Y,we,We,et,St,pt,dt,$,K,R,U,X,ge,xe,be,Re,Fe,Xe,ht,It,jt,kt,In,_n,rr,ii,hi,Xc,ca,Xf,Ou,vg,yg,F8,U8,B8,G8,W8,z8;const a=at.useRef(null),s=at.useRef(null),c=at.useRef(!1),l="dv3d_mouseToolBindings",f="dv3d_ctrlMouseToolBindings",u=(o==null?void 0:o.minLevel)??((o==null?void 0:o.debug)!==void 0?o.debug?"debug":"warn":void 0)??m5().minLevel,d=Wp((o==null?void 0:o.format)??m5().format),[h,g]=at.useState(u),[p,v]=at.useState(d),[y,m]=at.useState(!0),[w,x]=at.useState(()=>JI()),[C,S]=at.useState(!1),[_,T]=at.useState(!1),[E,b]=at.useState(320),D=`dv3d_stackPanelWidth_${t||"default"}`,I=at.useRef({resizing:!1,startX:0,startWidth:320}),P=240,M=720,L=220,V=40,W=14,A=at.useRef(null),[k,F]=at.useState(null),[H,J]=at.useState(null),[oe,ve]=at.useState(!1),[de,_e]=at.useState(!1),[Le,Be]=at.useState(!1),[Pe,B]=at.useState(null),[O,j]=at.useState(!0),[z,q]=at.useState(null),[Q,re]=at.useState("center"),[Ie,Ve]=at.useState(null),Ye=at.useRef(0),Ue=9,ie="renderingEngine_"+t,se="TOOL_GROUP_"+t,ye=at.useRef(null),le=at.useRef(!1),[Se,nt]=at.useState(!0),[ce,Ot]=at.useState(!1),[bt,Tt]=at.useState([]),[Ae,tt]=at.useState(0),[wt,yt]=at.useState(null),[Dt,qt]=at.useState(!1),[At,$t]=at.useState(null),[Lt,Yn]=at.useState(()=>Array(Ue).fill(null).map(()=>[])),fn=G=>{typeof G=="function"?Yn(ue=>{const Te=G(ue);return Nt.debug("setViewportImageIds (fn):",Te),Te}):(Nt.debug("setViewportImageIds:",G),Yn(G))},[an,Cn]=at.useState(()=>Array(Ue).fill(0)),[kr,sr]=at.useState(()=>Array(Ue).fill(null).map(()=>[])),[Ze,xt]=at.useState(()=>Array(Ue).fill(0)),[tn,Fn]=at.useState(()=>Array(Ue).fill(!1)),[Ei,on]=at.useState(()=>Array(Ue).fill(12)),[Un,Dn]=at.useState(()=>Array(Ue).fill(!1)),vn=at.useRef({}),ti=at.useRef({}),[Hr,xs]=at.useState({}),Fo=at.useRef({}),Ai=at.useRef({}),li=at.useCallback((G,ue)=>{xs(Te=>{const Ce=Te[G];if(Ce&&Ce!==ue&&Ce.startsWith("blob:"))try{URL.revokeObjectURL(Ce)}catch{}const he={...Te,[G]:ue};return Fo.current=he,he})},[]);at.useEffect(()=>{Fo.current=Hr},[Hr]),at.useEffect(()=>()=>{Object.values(Fo.current).forEach(G=>{if(typeof G=="string"&&G.startsWith("blob:"))try{URL.revokeObjectURL(G)}catch{}})},[]),at.useEffect(()=>{try{const G=localStorage.getItem(D);if(G){const ue=Number(G);Number.isNaN(ue)||b(Math.max(P,Math.min(M,Math.round(ue))))}}catch{}},[D]),at.useEffect(()=>{try{localStorage.setItem(D,String(Math.round(E)))}catch{}},[D,E]);function Uo(G){if(!G)return null;try{if(G.tagName&&G.tagName.toLowerCase()==="canvas")return G}catch{}try{const ue=G.querySelector&&G.querySelector("canvas");if(ue)return ue}catch{}try{const ue=G.children||[];for(let Te=0;TeMath.min(pn,Math.max(Gt,Et)),Ge=()=>{ue.style.transform=`translate(${ae}px, ${De}px) scale(${fe})`};let Ke=!0,$e=!0;const rt=Et=>{if(!$e)return;Et.preventDefault();const Gt=ue.getBoundingClientRect(),pn=Et.clientX-Gt.left,pr=Et.clientY-Gt.top,Di=-Et.deltaY,es=1+(Di>0?.1:-.1)*Math.min(4,Math.abs(Di)/100),Ki=Me(fe*es,.1,10);ae=(ae-pn)*(Ki/fe)+pn,De=(De-pr)*(Ki/fe)+pr,fe=Ki,Ge()},ct=Et=>{Et.button===0&&Ke&&(pe=!0,me=Et.clientX,ke=Et.clientY,ue.style.cursor="grabbing",Et.preventDefault())},ut=Et=>{if(!pe)return;const Gt=Et.clientX-me,pn=Et.clientY-ke;ae+=Gt,De+=pn,me=Et.clientX,ke=Et.clientY,Ge()},mt=Et=>{pe&&(pe=!1,ue.style.cursor="grab")},Rt=Et=>{fe=1,ae=0,De=0,Ge()};let Zt=0;const gr=(Et,Gt)=>Math.hypot(Gt.clientX-Et.clientX,Gt.clientY-Et.clientY),ln=Et=>{Et.touches.length===1?Ke&&(pe=!0,me=Et.touches[0].clientX,ke=Et.touches[0].clientY):Et.touches.length===2&&(Zt=gr(Et.touches[0],Et.touches[1]))},Bt=Et=>{if(Et.touches.length===1&&pe){const Gt=Et.touches[0].clientX-me,pn=Et.touches[0].clientY-ke;ae+=Gt,De+=pn,me=Et.touches[0].clientX,ke=Et.touches[0].clientY,Ge()}else if(Et.touches.length===2&&$e){const Gt=gr(Et.touches[0],Et.touches[1]);if(Zt>0){const pn=Gt/Zt,pr=ue.getBoundingClientRect(),Di=(Et.touches[0].clientX+Et.touches[1].clientX)/2-pr.left,es=(Et.touches[0].clientY+Et.touches[1].clientY)/2-pr.top,Ki=Me(fe*pn,.1,10);ae=(ae-Di)*(Ki/fe)+Di,De=(De-es)*(Ki/fe)+es,fe=Ki,Ge()}Zt=Gt}Et.preventDefault()},Qt=Et=>{Et.touches.length===0&&(pe=!1,Zt=0)};return G.addEventListener("wheel",rt,{passive:!1}),G.addEventListener("mousedown",ct),window.addEventListener("mousemove",ut),window.addEventListener("mouseup",mt),ue.addEventListener("dblclick",Rt),G.addEventListener("touchstart",ln,{passive:!1}),G.addEventListener("touchmove",Bt,{passive:!1}),G.addEventListener("touchend",Qt),{cleanup:()=>{G.removeEventListener("wheel",rt),G.removeEventListener("mousedown",ct),window.removeEventListener("mousemove",ut),window.removeEventListener("mouseup",mt),ue.removeEventListener("dblclick",Rt),G.removeEventListener("touchstart",ln),G.removeEventListener("touchmove",Bt),G.removeEventListener("touchend",Qt),ue.style.transform="",ue.style.cursor="",ue.style.willChange=""},setAllowPan:Et=>{Ke=Et},setAllowZoom:Et=>{$e=Et}}}const[kn,ni]=at.useState(!1),[ja,Sr]=at.useState(null),[oa,no]=at.useState(!1),[zi,qs]=at.useState(null);at.useEffect(()=>{const G=Te=>{try{const Ce=Te&&Te.message?String(Te.message):"";(Ce.includes("releaseGraphicsResources")||Ce.includes("openGLTexture")||Ce.includes("getDefaultActor")||Ce.includes("setColormapGPU")||Ce.includes(`can't access property "actor"`)||Ce.toLowerCase().includes("webgl")||Ce.toLowerCase().includes("colormap"))&&(Nt.error("Detected graphics/rendering error:",Te),qs(Ce||null),no(!0))}catch{}},ue=Te=>{try{const Ce=Te&&Te.reason||"",he=typeof Ce=="string"?Ce:Ce&&Ce.message?Ce.message:String(Ce);(he.includes("releaseGraphicsResources")||he.includes("openGLTexture")||he.includes("getDefaultActor")||he.includes("setColormapGPU")||he.includes(`can't access property "actor"`)||he.toLowerCase().includes("webgl")||he.toLowerCase().includes("colormap"))&&(Nt.error("Detected graphics/rendering rejection:",Te),qs(he||null),no(!0))}catch{}};return window.addEventListener("error",G),window.addEventListener("unhandledrejection",ue),()=>{window.removeEventListener("error",G),window.removeEventListener("unhandledrejection",ue)}},[]),at.useEffect(()=>{let G=!1;if(n||i){Sr(n?"annotations":"viewerState");const ue=setTimeout(()=>{if(G)return;const Te=t||"default";if(n)try{const Ce=window[`importAnnotations_${Te}`]||window.importAnnotations;typeof Ce=="function"&&Ce(n)}catch(Ce){Nt.error("Failed to import annotations from prop:",Ce)}if(i)try{const Ce=window[`importViewerState_${Te}`]||window.importViewerState;typeof Ce=="function"&&Ce(i)}catch(Ce){Nt.error("Failed to import viewer state from prop:",Ce)}Sr(null)},2e3);return()=>{G=!0,clearTimeout(ue),Sr(null)}}},[n,i,t]),at.useEffect(()=>{let G=!0;return e().then(async ue=>{var he;if(!G)return;const Te=Array.isArray(ue)?ue:[],Ce=[];for(const fe of Te){const ae=Array.isArray(fe),De=ae?fe:Array.isArray(fe.imageIds)?fe.imageIds:Array.isArray(fe.i)?fe.i:[],pe=ae?{}:{studyId:fe.studyId,name:fe.name,caseId:fe.caseId,studyInstanceUID:fe.studyInstanceUID};if(!ae&&Array.isArray(fe.series)){const ke=fe.series.map((Me,Ge)=>{const Ke=Array.isArray(Me==null?void 0:Me.imageIds)?Me.imageIds:Array.isArray(Me==null?void 0:Me.i)?Me.i:[],$e=Wu(Ke.map(Gu)),ct=(typeof(Me==null?void 0:Me.name)=="string"?Me.name:"").trim()||`Series ${Ge+1}`;return{key:String((Me==null?void 0:Me.seriesInstanceUID)||(Me==null?void 0:Me.seriesId)||`SERIES_${Ge}`),label:ct,imageIds:$e,seriesInstanceUID:Me==null?void 0:Me.seriesInstanceUID,bValue:Number.isFinite(Number(Me==null?void 0:Me.bValue))?Number(Me.bValue):null}}).filter(Me=>Me.imageIds.length>0);if(ke.length>0){Ce.push({imageIds:Wu(ke.flatMap(Me=>Me.imageIds)),seriesGroups:ke,...pe});continue}}const me=Wu(De.map(Gu));me.length>0&&Ce.push({imageIds:me,seriesGroups:[],...pe})}if(Tt(Ce),Ce[0]){const fe=Ce[0];let ae=fe.seriesGroups||[],De=fe.imageIds;ae.length===0&&(De=await vo(fe.imageIds),await Bn(De,{force:!!r}),ae=await ui(De),Ce[0]={...fe,imageIds:De,seriesGroups:ae},Tt([...Ce]));const pe=((he=ae[0])==null?void 0:he.imageIds)||De;await Bn(pe),fn(Array(Ue).fill(null).map((me,ke)=>ke===0?pe||[]:[])),sr(Array(Ue).fill(null).map(()=>ae)),xt(Array(Ue).fill(0))}else fn(Array(Ue).fill(null).map(()=>[])),sr(Array(Ue).fill(null).map(()=>[])),xt(Array(Ue).fill(0))}).catch(ue=>{Nt.error("Failed to load imageStacks:",ue),Tt([]),fn(Array(Ue).fill(null).map(()=>[]))}),()=>{G=!1}},[]);const bo=async(G,ue)=>{var ae,De,pe,me;const Te=bt[ue];if(!Te)return;const Ce=await vo(Te.imageIds||[]);Nt.debug("[handleLoadStack] Loading stack:",Ce.length,"ids. First:",(ae=Ce[0])==null?void 0:ae.slice(0,80)),await Bn(Ce,{force:!0});const he=await ui(Ce);Nt.debug("[handleLoadStack] Derived series groups:",he.length,"groups. First group has",(De=he[0])==null?void 0:De.imageIds.length,"images"),Tt(ke=>{const Me=[...ke];return Me[ue]?(Me[ue]={...Me[ue],seriesGroups:he,imageIds:Ce},Me):ke});const fe=((pe=he[0])==null?void 0:pe.imageIds)||Ce;Nt.debug("[handleLoadStack] Setting viewport to primarySeries with",fe.length,"ids. First:",(me=fe[0])==null?void 0:me.slice(0,80)),Sr("displayset");try{yr(ke=>{const Me=[...ke];return Me[G]="stack",Me}),fn(ke=>{const Me=[...ke];return Me[G]=fe,Me}),Cn(ke=>{const Me=[...ke];return Me[G]=ue,Me}),sr(ke=>{const Me=[...ke];return Me[G]=he||[],Me}),xt(ke=>{const Me=[...ke];return Me[G]=0,Me}),await Bn(fe)}finally{Sr(null)}},[$i,Fc]=at.useState(!1),[Ni,Cs]=at.useState(!0),[Sa,Do]=at.useState(!1),[Ss,Ha]=at.useState(!1),Io=()=>{Nt.debug("Sorting viewport imageIds by slice location"),fn(G=>{const ue=G.map((Te,Ce)=>{if(!Te||Te.length===0)return Te;const ae=[...Te.map(De=>{const pe=Ct("imagePlaneModule",De);let me=null;return pe&&(pe.sliceLocation!==void 0?me=Number(pe.sliceLocation):pe.imagePositionPatient&&Array.isArray(pe.imagePositionPatient)&&pe.imagePositionPatient.length===3&&(me=Number(pe.imagePositionPatient[2]))),{imageId:De,sortKey:me}})].sort((De,pe)=>De.sortKey!==null&&pe.sortKey!==null?De.sortKey-pe.sortKey:De.imageId.localeCompare(pe.imageId)).map(De=>De.imageId);return JSON.stringify(ae)===JSON.stringify(Te)?Te:ae});return ni(!0),ue})},_a=at.useCallback(async(G,ue,Te=0)=>{if(!ue||Hr[G]||Ai.current[G])return;if(Vr(ue)){try{const ae=new Image;ae.crossOrigin="anonymous";const De=ue.replace(/^external:/,"");ae.src=De,await new Promise((Me,Ge)=>{ae.onload=()=>Me(!0),ae.onerror=Ke=>Ge(Ke)});const pe=document.createElement("canvas"),me=160;pe.width=me,pe.height=me;const ke=pe.getContext("2d");if(ke){const Me=Math.min(me/ae.width,me/ae.height),Ge=ae.width*Me,Ke=ae.height*Me,$e=(me-Ge)/2,rt=(me-Ke)/2;ke.fillStyle="#000",ke.fillRect(0,0,me,me),ke.drawImage(ae,$e,rt,Ge,Ke),li(G,pe.toDataURL("image/png"))}else li(G,"BROKEN")}catch{li(G,"BROKEN")}return}const Ce=ye.current;if(!Ce)return;Ai.current[G]=!0;const he=`THUMB_${t||"main"}_${G}`,fe=document.createElement("div");fe.style.width="160px",fe.style.height="160px",fe.style.position="absolute",fe.style.left="-9999px",fe.style.top="0",document.body.appendChild(fe);try{Ce.enableElement({viewportId:he,type:Mr.STACK,element:fe});const ae=Ce.getViewport(he);if(!ae)return;try{ae.setStack([ue])}catch{}await new Promise(pe=>{let me=!1;const ke=setTimeout(()=>{me||(me=!0,pe(!1))},2e3),Me=()=>{me||(me=!0,clearTimeout(ke),pe(!0))};try{if(ae&&ae.element&&ae.element.addEventListener(Hg,Me,{once:!0}),typeof ae.render=="function")try{const Ge=ae.render();Ge&&typeof Ge.then=="function"&&Ge.catch(()=>{})}catch{}}catch{clearTimeout(ke),pe(!1)}});let De=Uo(fe)||(ae&&ae.element?Uo(ae.element):null);if(De||(await new Promise(pe=>setTimeout(pe,150)),De=Uo(fe)||(ae&&ae.element?Uo(ae.element):null)),De){if(!TSe(De)&&Te{_a(G,ue,Te+1)},me);return}try{if(typeof De.toBlob=="function"){const me=await new Promise(ke=>{De.toBlob(Me=>{if(!Me){ke(null);return}ke(URL.createObjectURL(Me))},"image/png")});me?li(G,me):li(G,De.toDataURL("image/png"))}else li(G,De.toDataURL("image/png"))}catch{li(G,"BROKEN")}}else li(G,"BROKEN")}catch{try{li(G,"BROKEN")}catch{}}finally{try{Ce.disableElement(he)}catch{}fe&&fe.parentNode&&fe.parentNode.removeChild(fe)}},[t,Hr,li]);at.useEffect(()=>{!_||!bt||bt.length===0||!ye.current||bt.slice(0,12).forEach((ue,Te)=>{const Ce=Array.isArray(ue.imageIds)?ue.imageIds:[],he=Math.floor(Ce.length/2),fe=Ce[he]||Ce[0]||null;!Hr[Te]&&!Ai.current[Te]&&_a(Te,fe)})},[bt,_a,_,Hr]);const Bn=async(G,ue)=>{Nt.debug("Setting loaded imageIds:",G),Nt.debug("autoCacheStack:",r);const Te=[];if(!!(r||ue!=null&&ue.force)){const he=new Set;for(const fe of G)if(fe.startsWith("wadouri:"))try{const ae=Qc(fe).replace(/[?&]frame=\d+/gi,"");ae&&he.add(ae)}catch(ae){Nt.warn(`Failed to cache metadata for ${fe}:`,ae)}for(const fe of he)if(Uu.wadouri.dataSetCacheManager){const ae=Uu.wadouri.dataSetCacheManager.load(fe);ae&&typeof ae.then=="function"&&Te.push(ae)}else Nt.warn("MetaDataManager not found. Unable to cache metadata.");await Promise.all(Te),qr&&(Nt.debug("Sorting viewport imageIds by slice location"),Io())}},mo=at.useCallback(async G=>{var De;if(!G.startsWith("wadouri:")||s_(G))return 1;const ue=Gu(G),Te=Qc(ue),Ce=`wadouri:${Te}`,he=vn.current[Ce];if(he!==void 0)return he;const fe=pe=>{if(!pe||typeof pe.intString!="function")return 1;const me=Number(pe.intString("x00280008"));return Number.isFinite(me)&&me>1?Math.floor(me):1},ae=pe=>{try{const me=Lr.parseDicom(pe);return fe(me)}catch(me){if(me!=null&&me.dataSet){const ke=fe(me.dataSet);if(ke>1)return ke}return 1}};try{const pe=Ct("multiframeModule",ue),me=Number(pe==null?void 0:pe.numberOfFrames);if(Number.isFinite(me)&&me>1)return vn.current[Ce]=Math.floor(me),Math.floor(me)}catch{}try{const pe=(De=Uu==null?void 0:Uu.wadouri)==null?void 0:De.dataSetCacheManager;if(pe!=null&&pe.get){const me=pe.get(Te);if(me){const ke=fe(me);return vn.current[Ce]=ke,ke}}}catch{}try{const pe=await fetch(Te,{headers:{Range:"bytes=0-262143"}});if(pe.ok||pe.status===206){const me=await pe.arrayBuffer(),ke=ae(new Uint8Array(me));return vn.current[Ce]=ke,ke}}catch{}return vn.current[Ce]=1,1},[]),Ka=at.useCallback(async G=>{var Ce;const ue=[],Te=[];for(const he of G||[]){const fe=Gu(he);if(!fe.startsWith("wadouri:")||s_(fe)){ue.push(fe);continue}const ae=await mo(fe);if(ae<=1)ue.push(fe);else{const De=Array.from({length:ae},(pe,me)=>QI(fe,me+1));Te.push({baseImageId:fe,frameIds:De}),Nt.debug("[splitMultiframeToStacks]",((Ce=Qc(fe).split("/").pop())==null?void 0:Ce.split("?")[0])??fe,"->",ae,"frames (separate stack)")}}return{singleFrameIds:Wu(ue),multiframeGroups:Te}},[mo]),vo=at.useCallback(async G=>{Nt.debug("[expandMultiframeImageIds] Input:",G.length,"imageIds");const{singleFrameIds:ue,multiframeGroups:Te}=await Ka(G),Ce=Wu([...ue,...Te.flatMap(he=>he.frameIds)]);return Nt.debug("[expandMultiframeImageIds] Output:",Ce.length,"total imageIds"),Ce},[Ka]),_s=at.useCallback(async G=>{var fe;if(!G.startsWith("wadouri:"))return[];const ue=Gu(G),Te=Qc(ue).replace(/[?&]frame=\d+/i,""),Ce=ti.current[Te];if(Ce)return Ce;try{const ae=(fe=Uu==null?void 0:Uu.wadouri)==null?void 0:fe.dataSetCacheManager;if(ae!=null&&ae.get){const De=ae.get(Te),pe=OC(De);if(pe.length>0)return ti.current[Te]=pe,pe}}catch{}const he=ae=>{try{return OC(Lr.parseDicom(ae))}catch(De){if(De!=null&&De.dataSet){const pe=OC(De.dataSet);if(pe.length>0)return pe}return[]}};try{const ae=await fetch(Te,{headers:{Range:"bytes=0-65535"}});if(ae.ok||ae.status===206){const De=await ae.arrayBuffer(),pe=he(new Uint8Array(De));if(pe.length>0||ae.status===200)return ti.current[Te]=pe,pe}}catch{}try{const De=await(await fetch(Te)).arrayBuffer(),pe=he(new Uint8Array(De));return ti.current[Te]=pe,pe}catch{return ti.current[Te]=[],[]}},[]),ui=at.useCallback(async G=>{if(!Array.isArray(G)||G.length===0)return[];const ue=Ge=>!Array.isArray(Ge)||Ge.length===0?"":Ge.map(Ke=>{const $e=Number(Ke);return Number.isFinite($e)?$e.toFixed(3):"0.000"}).join(","),Te=Ge=>{if(Array.isArray(Ge)&&Ge.length>0){const Ke=Ge.map($e=>Number($e)).filter($e=>Number.isFinite($e));if(Ke.length>=3)return ue(Ke.slice(0,3))}if(typeof Ge=="string"){const Ke=y5(Ge);if(Ke.length>=3)return ue(Ke.slice(0,3));const $e=Ge.trim();if($e)return $e}if(Ge&&typeof Ge=="object"){const Ke=[Ge.x,Ge.y,Ge.z].map($e=>Number($e)).filter($e=>Number.isFinite($e));if(Ke.length>=3)return ue(Ke.slice(0,3))}return""},Ce=Ge=>{if(Ge==null)return"";const Ke=String(Ge).trim();if(!Ke)return"";const $e=Number(Ke);return Number.isFinite($e)?$e.toFixed(1):Ke},he=Ge=>{const Ke=Ct("imagePlaneModule",Ge)||{},$e=Ct("generalImageModule",Ge)||{},rt=Array.isArray(Ke==null?void 0:Ke.rowCosines)?Ke.rowCosines:null,ct=Array.isArray(Ke==null?void 0:Ke.columnCosines)?Ke.columnCosines:null,ut=rt&&ct?`${ue(rt)}|${ue(ct)}`:"";if(ut)return ut;const mt=$e==null?void 0:$e.imageOrientationPatient;if(Array.isArray(mt)&&mt.length>=6)return`${ue(mt.slice(0,3))}|${ue(mt.slice(3,6))}`;if(typeof mt=="string"){const Rt=y5(mt);if(Rt.length>=6)return`${ue(Rt.slice(0,3))}|${ue(Rt.slice(3,6))}`}return"ORI_UNKNOWN"},fe=new Map;G.forEach(Ge=>{const Ke=Qc(Gu(Ge)).replace(/[?&]frame=\d+/i,""),$e=fe.get(Ke)||[];$e.push(Ge),fe.set(Ke,$e)}),fe.forEach((Ge,Ke)=>{Ge.sort(($e,rt)=>{const ct=e7($e)||1,ut=e7(rt)||1;return ct-ut}),fe.set(Ke,Ge)});const ae=new Map;await Promise.all(Array.from(fe.keys()).map(async Ge=>{const Ke=`wadouri:${Ge}`,$e=await _s(Ke);ae.set(Ge,$e)}));const De=Ge=>{const Ke=Ct("imagePlaneModule",Ge)||{},$e=Array.isArray(Ke==null?void 0:Ke.imagePositionPatient)?Ke.imagePositionPatient:null;if($e&&$e.length>=3){const ct=$e.slice(0,3).map(ut=>Number(ut));if(ct.every(ut=>Number.isFinite(ut)))return`IPP:${ct.map(ut=>ut.toFixed(3)).join(",")}`}const rt=Number(Ke==null?void 0:Ke.sliceLocation);return Number.isFinite(rt)?`SL:${rt.toFixed(3)}`:""},pe=G.map(Ge=>{const Ke=Ct("generalSeriesModule",Ge)||{},$e=Ct("generalImageModule",Ge)||{},rt=Ct("mrImageModule",Ge)||{},ct=(Ke.seriesInstanceUID||"").trim()||void 0,ut=(Ke.seriesDescription||"").trim()||void 0,mt=Number(Ke.seriesNumber),Rt=Number($e.instanceNumber),Zt=he(Ge),gr=De(Ge);let ln=Number(rt.diffusionBValue??rt.diffusionbValue??rt.bValue),Bt=Number.isFinite(ln)?ln:null;if(Bt===null){const es=Qc(Gu(Ge)).replace(/[?&]frame=\d+/i,""),Ki=ae.get(es)||[];if(Ki.length>0){const $8=fe.get(es)||[Ge],qw=Math.max(0,$8.indexOf(Ge)),A1=Math.max(1,$8.length);if(Ki.length===1)Bt=Ki[0];else if(Ki.length===A1)Bt=Ki[Math.min(Ki.length-1,qw)];else if(Ki.length===2&&A1%2===0)Bt=qww[Ge.id]).map(Ge=>Ge.id).filter(Ge=>{const Ke=pe.map(ct=>ct.ruleValues[Ge]).filter(ct=>!!ct),$e=new Set(Ke),rt=Ke.length/pe.length;return $e.size>1&&$e.size=.7}):[],ke=new Map;if(pe.forEach(Ge=>{const Ke=[Ge.seriesInstanceUID||"NO_UID",Ge.orientationKey].join("|"),$e=me.map(ct=>{const ut=Ge.ruleValues[ct];return ut?`${ct}:${ut}`:""}).filter(Boolean).join("|"),rt=$e?`${Ke}|${$e}`:Ke;if(!ke.has(rt)){const ct={};me.forEach(ut=>{const mt=Ge.ruleValues[ut];mt&&(ct[ut]=mt)}),ke.set(rt,{imageIds:[],seriesInstanceUID:Ge.seriesInstanceUID,seriesDescription:Ge.seriesDescription,seriesNumber:Ge.seriesNumber,bValue:Ge.bValue,groupValues:ct})}ke.get(rt).imageIds.push(Ge.id)}),ke.size<=1){if(me.length===0&&pe.length>=4){const Ge=new Map;pe.forEach($e=>{$e.sliceKey&&Ge.set($e.sliceKey,(Ge.get($e.sliceKey)||0)+1)});const Ke=Ge.size;if(Ke>=2&&Ke=2&&rt<=8&&Array.from(Ge.values()).every(mt=>mt===rt)){const mt=Array.from({length:rt},()=>[]),Rt=new Map;[...pe].map((ln,Bt)=>({c:ln,idx:Bt})).sort((ln,Bt)=>{const Qt=ln.c.instanceNumber,lr=Bt.c.instanceNumber;return Number.isFinite(Qt)&&Number.isFinite(lr)?Qt-lr:ln.idx-Bt.idx}).forEach(({c:ln})=>{if(!ln.sliceKey)return;const Bt=Rt.get(ln.sliceKey)||0,Qt=Math.min(rt-1,Bt);mt[Qt].push(ln.id),Rt.set(ln.sliceKey,Bt+1)});const gr=mt.filter(ln=>ln.length>0);if(gr.length>1)return gr.map((ln,Bt)=>({key:`SERIES_FALLBACK_${Bt}`,label:`Series ${Bt+1}`,imageIds:Wu(ln)}))}}}return[{key:"SERIES_0",label:"Series 1",imageIds:Wu(G)}]}return Array.from(ke.entries()).map(([Ge,Ke],$e)=>{const rt=[];Ke.seriesDescription&&rt.push(Ke.seriesDescription),Ke.seriesNumber!==void 0&&rt.push(`#${Ke.seriesNumber}`),Ke.groupValues&&hp.forEach(ut=>{var Rt;const mt=(Rt=Ke.groupValues)==null?void 0:Rt[ut.id];mt&&(ut.id==="dwiBValue"?rt.push(`b=${mt}`):ut.id==="dwiDirection"?rt.push(`dir=${mt}`):ut.id==="temporalPosition"?rt.push(`tp=${mt}`):ut.id==="triggerTime"?rt.push(`tr=${mt}`):ut.id==="contentTime"?rt.push(`t=${mt}`):ut.id==="echoTime"?rt.push(`TE=${mt}`):ut.id==="echoNumber"&&rt.push(`echo=${mt}`))}),rt.length===0&&Ke.bValue!==null&&Ke.bValue!==void 0&&rt.push(`b=${Math.round(Ke.bValue)}`);const ct=rt.length>0?rt.join(" • "):`Series ${$e+1}`;return{key:Ge,label:ct,imageIds:Wu(Ke.imageIds),seriesInstanceUID:Ke.seriesInstanceUID,bValue:Ke.bValue,groupValues:Ke.groupValues}})},[y,_s,w]),[Xt,Ta]=at.useState({rows:1,cols:1}),[Ea,qa]=at.useState(!1),Kr=at.useRef([]),yo=at.useRef({}),ji=at.useRef({}),[qr,Xs]=at.useState(!1),[Oo,Xa]=at.useState(!0),Ir=at.useCallback(G=>{const ue=G.currentTarget.getBoundingClientRect(),Te=G.clientX-ue.left,Ce=G.clientY-ue.top,he=ue.width,fe=ue.height,ae=Math.min(he,fe)*.24,De=[{zone:"left",distance:Te},{zone:"right",distance:he-Te},{zone:"top",distance:Ce},{zone:"bottom",distance:fe-Ce}];return De.sort((pe,me)=>pe.distance-me.distance),De[0].distance<=ae?De[0].zone:"center"},[]),Ys=at.useCallback((G,ue,Te)=>{const Ce=ue-G.left,he=Te-G.top,fe=G.width,ae=G.height,De=Math.min(fe,ae)*.24,pe=[{zone:"left",distance:Ce},{zone:"right",distance:fe-Ce},{zone:"top",distance:he},{zone:"bottom",distance:ae-he}];return pe.sort((me,ke)=>me.distance-ke.distance),pe[0].distance<=De?pe[0].zone:"center"},[]),ri=at.useCallback(G=>G==="left"||G==="right"?Xt.cols<3?G:"center":(G==="top"||G==="bottom")&&Xt.rows<3?G:"center",[Xt]),fi=[];for(let G=1;G<=3;G++)for(let ue=1;ue<=3;ue++)fi.push({rows:G,cols:ue});const[gn,aa]=at.useState(()=>Array(Xt.rows*Xt.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:"",modality:"",orientation:"",resolution:"",spacing:"",focalPoint:""})),[ro,Ya]=at.useState({}),Js=at.useRef(Array(Ue).fill("")),Go=at.useRef(Array(Ue).fill(null)),Ja=at.useRef(Array(Ue).fill(null)),vr=at.useRef(Array(Ue).fill(null)),ba=at.useRef(Array(Ue).fill(0)),[sn,yr]=at.useState(()=>Array(Ue).fill("stack")),[Da,ki]=at.useState(()=>Array(Xt.rows*Xt.cols).fill(!1)),[Vi,di]=at.useState({Primary:_f.toolName,Auxiliary:Cc.toolName,Secondary:Yd.toolName,Primary_and_Secondary:ll.toolName,Fourth_Button:Vh.toolName,Wheel:_f.toolName}),[bi,Za]=at.useState({Primary:Ff.toolName,Auxiliary:_u.toolName,Secondary:Gh.toolName}),[Qa,Hi]=at.useState(!1);at.useEffect(()=>{const G=Te=>{Te.ctrlKey&&Hi(!0)},ue=Te=>{Te.ctrlKey||Hi(!1)};return window.addEventListener("keydown",G),window.addEventListener("keyup",ue),()=>{window.removeEventListener("keydown",G),window.removeEventListener("keyup",ue)}},[]),at.useEffect(()=>{const G=window.matchMedia("(max-width: 768px), (pointer: coarse)"),ue=()=>{const Te=G.matches;_e(Te),Te||(Be(!1),B(null))};return ue(),typeof G.addEventListener=="function"?(G.addEventListener("change",ue),()=>G.removeEventListener("change",ue)):(G.addListener(ue),()=>G.removeListener(ue))},[]);const Uc=at.useCallback(G=>{if(!de)return;tt(G),B(G),Be(!0),j(!0),T(!1);const ue=a.current;if(ue&&document.fullscreenElement!==ue){const Te=ue.requestFullscreen||ue.webkitRequestFullscreen||ue.msRequestFullscreen;if(Te)try{const Ce=Te.call(ue);Ce&&typeof Ce.catch=="function"&&Ce.catch(()=>{})}catch{}}},[de]);at.useEffect(()=>{!de||!Le||!O||Ae!==null&&B(Ae)},[Ae,de,Le,O]);const[Al,Ts]=at.useState(!1),[Bc,Ia]=at.useState(null),Es=(G,ue)=>{pa&&pa(ue),He(Te=>{const Ce=[...Te];return Ce[G]=ue,Ce})},Zs=(G,ue,Te)=>{const Ce=Or.getAllAnnotations()||[];Ce.forEach(fe=>{fe.annotationUID===ue&&(fe.isSelected=!1)}),Or.removeAnnotation(ue),ye.current.render();const he=Te.filter(fe=>fe.annotationUID!==ue);He(fe=>{const ae=[...fe],De=he.length>0?he[0].annotationUID:null;return ae[G]=De,Ce.forEach(pe=>{pe.isSelected=pe.annotationUID===De}),pa(De),ye.current.render(),ae})},Nl=()=>{const G=Lt.findIndex(he=>he&&he.length>0);if(G===-1){Ia("No images loaded."),Ts(!0);return}const ue=Lt[G][0],Te=["imagePlaneModule","generalSeriesModule","generalStudyModule","patientModule","imagePixelModule","voiLutModule","modalityLutModule","sopCommonModule","petIsotopeModule","multiframeModule","cineModule","overlayPlaneModule","generalImageModule","stackModule","voiLutModule","modalityLutModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule"],Ce={};Te.forEach(he=>{const fe=Ct(he,ue);fe!==void 0&&(Ce[he]=fe)}),Ia(Ne.jsx("pre",{style:{maxHeight:600,overflow:"auto",fontSize:13,color:"#fff"},children:JSON.stringify(Ce,null,2)})),Ts(!0)};at.useEffect(()=>{try{const G=localStorage.getItem(l),ue=localStorage.getItem(f);G&&di(JSON.parse(G)),ue&&Za(JSON.parse(ue));const Te=localStorage.getItem(XI);if(Te){const he=JSON.parse(Te);typeof(he==null?void 0:he.minLevel)=="string"?g(v5(he.minLevel)):typeof(he==null?void 0:he.debug)=="boolean"&&g(he.debug?"debug":"warn"),typeof(he==null?void 0:he.format)=="string"&&v(Wp(he.format))}const Ce=localStorage.getItem(YI);if(Ce){const he=JSON.parse(Ce);if(typeof(he==null?void 0:he.advancedGroupingEnabled)=="boolean"&&m(he.advancedGroupingEnabled),he!=null&&he.groupingRuleEnabled&&typeof he.groupingRuleEnabled=="object"){const fe=JI();hp.forEach(ae=>{typeof he.groupingRuleEnabled[ae.id]=="boolean"&&(fe[ae.id]=he.groupingRuleEnabled[ae.id])}),x(fe)}}}catch{}},[]),at.useEffect(()=>{try{localStorage.setItem(l,JSON.stringify(Vi))}catch{}},[Vi]),at.useEffect(()=>{try{localStorage.setItem(f,JSON.stringify(bi))}catch{}},[bi]),at.useEffect(()=>{w8({minLevel:h,format:p});try{localStorage.setItem(XI,JSON.stringify({minLevel:h,format:p}))}catch{}},[h,p]),at.useEffect(()=>{try{localStorage.setItem(YI,JSON.stringify({advancedGroupingEnabled:y,groupingRuleEnabled:w}))}catch{}},[y,w]),at.useEffect(()=>{if(bt.length===0)return;let G=!1;return(async()=>{const Te=await Promise.all(bt.map(async Ce=>{const he=await ui(Ce.imageIds);return{...Ce,seriesGroups:he}}));G||(Tt(Te),sr(Ce=>{var fe;const he=[...Ce];for(let ae=0;ae{var fe;const he=[...Ce];for(let ae=0;ae{var fe,ae,De;const he=[...Ce];for(let pe=0;pe{G=!0}},[y,w]),at.useEffect(()=>(window.loadDicomStackFromFiles=G=>{const ue=Array.from(G);Ds({target:{files:ue}})},()=>{window.loadDicomStackFromFiles=void 0}),[]),at.useEffect(()=>{const G=()=>{qt(!1),$t(null),yt(null)};return document.addEventListener("dragend",G),()=>document.removeEventListener("dragend",G)},[]);const[Gc,Qs]=at.useState(!1),[Wc,ec]=at.useState(!1);at.useEffect(()=>{const G=wi(se);G&&["ArrowAnnotate","NoLabelArrowAnnotate","Length","RectangleROI","EllipticalROI","PlanarFreehandROI","PlanarFreehandContourSegmentation"].forEach(ue=>{G.setToolConfiguration(ue,{color:"#00e676",selectedColor:"#ffeb3b"})})},[se]),at.useEffect(()=>{const G=Ce=>{Ce.altKey&&Qs(!0),Ce.shiftKey&&ec(!0)},ue=Ce=>{Ce.altKey||Qs(!1),Ce.shiftKey||ec(!1)},Te=()=>{Qs(!1),ec(!1)};return window.addEventListener("keydown",G),window.addEventListener("keyup",ue),window.addEventListener("blur",Te),()=>{window.removeEventListener("keydown",G),window.removeEventListener("keyup",ue),window.removeEventListener("blur",Te)}},[]),at.useEffect(()=>{const G=wi(se);if(!G)return;if(Wc||Oo&&Gc){const Te=Xt.rows*Xt.cols;Lt.slice(0,Te).filter((he,fe)=>sn[fe]==="stack"&&Array.isArray(he)&&he.length>0).forEach(he=>{Bn(he,{force:!0}).catch(fe=>{Nt.warn("Reference cursor metadata warm-up failed:",fe)})}),G.hasTool(os.toolName)||G.addTool(os.toolName),G.setToolEnabled(os.toolName),G.setToolActive(os.toolName)}else G.hasTool(os.toolName)&&G.setToolDisabled(os.toolName)},[Gc,Wc,Oo,Xt.rows,Xt.cols,Lt,sn,Bn]);const tc=at.useCallback(()=>{[wi(se)].forEach(ue=>{if(ue){dd.forEach(fe=>{ue.setToolPassive(fe.value,{removeAllBindings:!0})}),ue.setToolDisabled(os.toolName);const Te={};Object.entries(Vi).forEach(([fe,ae])=>{Te[ae]||(Te[ae]=[]);const De=z2.find(pe=>pe.value===fe);De?Te[ae].push({mouseButton:De.mask}):jg[fe]&&Te[ae].push({mouseButton:jg[fe]})}),Object.entries(bi).forEach(([fe,ae])=>{if(!ae)return;Te[ae]||(Te[ae]=[]);const De=z2.find(pe=>pe.value===fe);De?Te[ae].push({mouseButton:De.mask,modifierKey:KI.Ctrl}):jg[fe]&&Te[ae].push({mouseButton:jg[fe],modifierKey:KI.Ctrl})}),Object.entries(Te).forEach(([fe,ae])=>{ue.setToolActive(fe,{bindings:ae})});const Ce=Vi.Primary;if(Ce){const fe=[...Te[Ce]||[],{numTouchPoints:1}];ue.setToolActive(Ce,{bindings:fe})}const he=[...Te[Cc.toolName]||[],{numTouchPoints:2}];ue.setToolActive(Cc.toolName,{bindings:he});try{const fe=Vi.Primary,ae=Vi.Wheel,De=Vi.Auxiliary,pe=fe===Cc.toolName||De===Cc.toolName,me=fe===ll.toolName||ae===ll.toolName||Vi.Primary_and_Secondary===ll.toolName;Kr.current.forEach(ke=>{if(!ke)return;const Me=ke._externalPanZoom;Me&&(typeof Me.setAllowPan=="function"&&Me.setAllowPan(!!pe),typeof Me.setAllowZoom=="function"&&Me.setAllowZoom(!!me))})}catch{}}})},[Vi,bi]),[zc,bs]=at.useState(!1),[nc,rc]=at.useState("add"),sa=at.useRef(null),kl=at.useCallback(G=>{_&&(G.preventDefault(),G.stopPropagation(),I.current={resizing:!0,startX:G.clientX,startWidth:E},document.body.style.cursor="col-resize",document.body.style.userSelect="none")},[_,E]);at.useEffect(()=>{const G=Te=>{if(!I.current.resizing)return;const Ce=I.current.startX-Te.clientX,he=Math.max(P,Math.min(M,I.current.startWidth+Ce));b(he)},ue=()=>{I.current.resizing&&(I.current.resizing=!1,document.body.style.cursor="",document.body.style.userSelect="")};return window.addEventListener("mousemove",G),window.addEventListener("mouseup",ue),()=>{window.removeEventListener("mousemove",G),window.removeEventListener("mouseup",ue),document.body.style.cursor="",document.body.style.userSelect=""}},[]);const ic=zc?L-V/2:-V+W;at.useEffect(()=>{try{sa.current&&(sa.current.setAttribute("webkitdirectory","true"),sa.current.setAttribute("directory",""),sa.current.setAttribute("mozdirectory",""))}catch{}},[]);async function oc(G,ue=""){const Te=[],Ce=G.entries?G.entries():G.values();for await(const he of Ce)try{let fe,ae;if(Array.isArray(he)&&he.length>=2?(ae=he[0],fe=he[1]):(fe=he,ae=fe.name),!fe)continue;if(fe.kind==="file"){const De=await fe.getFile();try{Object.defineProperty(De,"webkitRelativePath",{value:ue+(ae||fe.name),configurable:!0})}catch{}Te.push(De)}else if(fe.kind==="directory"){const De=await oc(fe,ue+(ae||fe.name)+"/");Te.push(...De)}}catch(fe){Nt.debug("collectFilesFromDirectoryHandle: skipping entry due to error",fe)}return Te}const $c=async()=>{var G;if(window.showDirectoryPicker)try{const ue=await window.showDirectoryPicker(),Te=await oc(ue);Te&&Te.length>0?await Ds({target:{files:Te}}):alert("No files found in selected folder.");return}catch(ue){Nt.warn("showDirectoryPicker failed or cancelled",ue)}(G=sa.current)==null||G.click()},Oa=at.useRef(null),Ds=async G=>{const ue=G.target.files;if(!ue||ue.length===0)return;Xs(!1);const Te=Array.from(ue).sort((ae,De)=>ae.name.localeCompare(De.name)),Ce=await Promise.all(Te.map(async ae=>{const De=ae.type&&ae.type.startsWith("image/");let pe,me,ke,Me,Ge=1,Ke=!1;if(!De)try{const rt=await ae.arrayBuffer(),ct=Lr.parseDicom(new Uint8Array(rt));pe=ct.string("x0020000d"),me=ct.string("x0020000e");const ut=ct.string("x00200013");ut!=null&&ut!==""&&(ke=parseInt(ut,10));const mt=ct.string("x00201041")||ct.string("x00201040");mt!=null&&mt!==""&&(Me=parseFloat(mt));const Rt=ct.string("x00280008");if(Rt!=null&&Rt!==""){const Zt=Number(Rt);Number.isFinite(Zt)&&Zt>1&&(Ge=Math.floor(Zt))}Ke=!0}catch{Ke=!1}const $e=De?`external:${URL.createObjectURL(ae)}`:`wadouri:${URL.createObjectURL(ae)}`;return{file:ae,imageId:$e,studyInstanceUID:pe,seriesInstanceUID:me,instanceNumber:ke,sliceLocation:Me,numberOfFrames:Ge,isImage:De,parsedSuccessfully:Ke}})),he=new Map;for(const ae of Ce){if(!ae.isImage&&!ae.parsedSuccessfully){Nt.debug("Skipping non-DICOM/non-image file:",ae.file.name);continue}const De=ae.seriesInstanceUID||ae.studyInstanceUID||(ae.file.webkitRelativePath?ae.file.webkitRelativePath.split("/")[0]:ae.file.name);he.has(De)||he.set(De,{entries:[],studyInstanceUID:ae.studyInstanceUID,seriesInstanceUID:ae.seriesInstanceUID}),he.get(De).entries.push(ae)}const fe=[];for(const[ae,De]of he.entries()){const pe=De.entries;pe.sort((Me,Ge)=>qr&&Me.sliceLocation!==void 0&&Ge.sliceLocation!==void 0?Me.sliceLocation-Ge.sliceLocation:Me.instanceNumber!==void 0&&Ge.instanceNumber!==void 0?Me.instanceNumber-Ge.instanceNumber:(Me.file.webkitRelativePath||Me.file.name).localeCompare(Ge.file.webkitRelativePath||Ge.file.name));const me=pe.flatMap(Me=>{if(Me.isImage||!Number.isFinite(Me.numberOfFrames)||Me.numberOfFrames<=1)return[Me.imageId];const Ge=[];for(let Ke=1;Ke<=Me.numberOfFrames;Ke++)Ge.push(QI(Me.imageId,Ke));return Ge}),ke=await ui(me);fe.push({imageIds:me,studyInstanceUID:De.studyInstanceUID,seriesInstanceUID:De.seriesInstanceUID,seriesGroups:ke})}if(fe.length!==0)if(nc==="replace"){try{const ae=ye.current;if(ae)for(let De=0;De{var De,pe;const ae=Array(Ue).fill([]);for(let me=0;me{const ae=Array(Ue).fill(null).map(()=>[]);for(let De=0;De{const De=[...ae,...fe];fn(pe=>{var Me,Ge;const me=[...pe],ke=fe[fe.length-1];return me[0]=((Ge=(Me=ke.seriesGroups)==null?void 0:Me[0])==null?void 0:Ge.imageIds)||ke.imageIds,me}),Cn(pe=>{const me=[...pe];return me[0]=De.length-1,me}),sr(pe=>{var ke;const me=[...pe];return me[0]=((ke=fe[fe.length-1])==null?void 0:ke.seriesGroups)||[],me}),xt(pe=>{const me=[...pe];return me[0]=0,me});for(const pe of fe)Bn(pe.imageIds);return De})},jc=(G,ue)=>{di(Te=>({...Te,[G]:ue}))},_r=at.useCallback((G,ue)=>{var $e,rt;if(!ue)return;let Te=0,Ce=0,he="",fe="",ae="",De="",pe="",me="",ke="",Me="",Ge,Ke;if(sn[G]==="stack"){Te=typeof ue.getCurrentImageIdIndex=="function"?ue.getCurrentImageIdIndex():0;const ct=typeof ue.getImageIds=="function"?ue.getImageIds():[];Ce=ct.length;const ut=ct[Te];if(ut){if(Nt.debug("[updateOverlay] Current image:",ut.slice(0,80),"frameIndex status:",Ge,"totalFrames:",Ke),ut.includes("&frame=")){const ln=ut.match(/&frame=(\d+)/);if(ln){Ge=parseInt(ln[1],10),Nt.debug("[updateOverlay] Frame detected:",Ge);const Bt=ut.split("&frame=")[0],Qt=Ct("multiframeModule",Bt);if(Qt!=null&&Qt.numberOfFrames)Ke=Qt.numberOfFrames,Nt.debug("[updateOverlay] Total frames from metadata:",Ke);else{const lr=ct.map(Et=>{const Gt=Et.match(/&frame=(\d+)/);return Gt?parseInt(Gt[1],10):null}).filter(Et=>Et!==null&&typeof Et=="number");lr.length>0&&(Ke=Math.max(...lr),Nt.debug("[updateOverlay] Total frames from imageIds:",Ke))}}}else Nt.debug("[updateOverlay] No frame query in imageId. imageIds.length:",ct.length);const mt=Ct("generalSeriesModule",ut),Rt=Ct("imagePlaneModule",ut),Zt=Ct("imagePixelModule",ut);De=(mt==null?void 0:mt.modality)||"",Zt!=null&&Zt.rows&&(Zt!=null&&Zt.columns)&&(me=`${Zt.columns} x ${Zt.rows}`);const gr=[Rt==null?void 0:Rt.columnPixelSpacing,Rt==null?void 0:Rt.rowPixelSpacing,Rt==null?void 0:Rt.sliceThickness].filter(ln=>ln!=null&&ln!=="");gr.length>0&&(ke=gr.join(" x "))}if(typeof ue.getCamera=="function"){const mt=ue.getCamera();mt!=null&&mt.focalPoint&&Array.isArray(mt.focalPoint)&&(Me=mt.focalPoint.map(Rt=>Rt.toFixed(1)).join(", "))}if(ut&&Ya(mt=>mt[ut]?mt:{...mt,[ut]:!0}),typeof ue.getProperties=="function"){const mt=ue.getProperties();if(mt.voiRange){const{lower:Rt,upper:Zt}=mt.voiRange;he=((Zt+Rt)/2).toFixed(0),fe=(Zt-Rt).toFixed(0),Go.current[G]===null&&(Go.current[G]={lower:Rt,upper:Zt})}}}else if(sn[G]==="volume"){if(typeof ue.getSliceIndex=="function"&&(Te=ue.getSliceIndex()),typeof ue.getNumberOfSlices=="function"&&(Ce=ue.getNumberOfSlices()),typeof ue.getProperties=="function"){let ut;if(ue.volumeIds&&ue.volumeIds.size>0){const mt=Array.from(ue.volumeIds)[0];ut=ue.getProperties(mt)}else ut=ue.getProperties();if(ut&&ut.voiRange){const{lower:mt,upper:Rt}=ut.voiRange;he=((Rt+mt)/2).toFixed(0),fe=(Rt-mt).toFixed(0),Go.current[G]===null&&(Go.current[G]={lower:mt,upper:Rt})}}if(typeof ue.getSlicePlaneCoordinates=="function"){const ut=ue.getSlicePlaneCoordinates();ut&&typeof ut.position=="number"&&(ae=ut.position.toFixed(2)+" mm")}const ct=($e=Lt[G])==null?void 0:$e[0];if(ct){const ut=Ct("generalSeriesModule",ct),mt=Ct("imagePlaneModule",ct),Rt=Ct("imagePixelModule",ct);De=(ut==null?void 0:ut.modality)||"",pe=String(((rt=ue.viewportProperties)==null?void 0:rt.orientation)||"").toUpperCase(),Rt!=null&&Rt.rows&&(Rt!=null&&Rt.columns)&&(me=`${Rt.columns} x ${Rt.rows}`);const Zt=[mt==null?void 0:mt.columnPixelSpacing,mt==null?void 0:mt.rowPixelSpacing,mt==null?void 0:mt.sliceThickness].filter(gr=>gr!=null&&gr!=="");Zt.length>0&&(ke=Zt.join(" x "))}if(typeof ue.getCamera=="function"){const ut=ue.getCamera();ut!=null&&ut.focalPoint&&Array.isArray(ut.focalPoint)&&(Me=ut.focalPoint.map(mt=>mt.toFixed(1)).join(", "))}}aa(ct=>{const ut=[...ct];return ut[G]={index:Te+1,total:Ce,windowCenter:he,windowWidth:fe,slicePosition:ae,modality:De,orientation:pe,resolution:me,spacing:ke,focalPoint:Me,frameIndex:Ge,totalFrames:Ke},ut})},[sn,Lt]);at.useEffect(()=>{for(let G=0;G{var lr;const he=await vo(ue.map(Gu));if(he.length===0)return;await Bn(he,{force:!0});const fe=await ui(he),ae=((lr=fe[0])==null?void 0:lr.imageIds)||he;let De=-1,pe=-1;Tt(Et=>(De=Et.findIndex(Gt=>Gt.imageIds.length===he.length&&Gt.imageIds.every((pn,pr)=>pn===he[pr])),De!==-1?Et:(pe=Et.length,[...Et,{imageIds:he,name:Te,seriesGroups:fe}])));const me=De!==-1?De:pe,ke=ri(Ce);if(ke==="center"){Sr("displayset");try{yr(Et=>{const Gt=[...Et];return Gt[G]="stack",Gt}),fn(Et=>{const Gt=[...Et];return Gt[G]=ae,Gt}),Cn(Et=>{const Gt=[...Et];return Gt[G]=me,Gt}),sr(Et=>{const Gt=[...Et];return Gt[G]=fe,Gt}),xt(Et=>{const Gt=[...Et];return Gt[G]=0,Gt}),tt(G),await Bn(ae)}finally{Sr(null)}return}const Me=Xt.rows,Ge=Xt.cols,Ke=Math.floor(G/Ge),$e=G%Ge,rt=ke==="top"||ke==="bottom"?Me+1:Me,ct=ke==="left"||ke==="right"?Ge+1:Ge;if(rt>3||ct>3||rt*ct>Ue){Sr("displayset");try{yr(Et=>{const Gt=[...Et];return Gt[G]="stack",Gt}),fn(Et=>{const Gt=[...Et];return Gt[G]=he,Gt}),Cn(Et=>{const Gt=[...Et];return Gt[G]=me,Gt}),tt(G),await Bn(he)}finally{Sr(null)}return}const ut=ke==="top"?Ke:ke==="bottom"?Ke+1:Ke,mt=ke==="left"?$e:ke==="right"?$e+1:$e,Rt=ut*ct+mt,Zt=Array(Ue).fill([]),gr=Array(Ue).fill("stack"),ln=Array(Ue).fill(0),Bt=Array(Ue).fill(null).map(()=>[]),Qt=Array(Ue).fill(0);for(let Et=0;Et$e||ke==="left"?pn+1:pn),(ke==="top"||ke==="bottom")&&pn===$e&&(pr=GtKe||ke==="top"?Gt+1:Gt);const es=pr*ct+Di;Zt[es]=Lt[Et]||[],gr[es]=sn[Et]||"stack",ln[es]=an[Et]??0,Bt[es]=kr[Et]||[],Qt[es]=Ze[Et]??0}Zt[Rt]=ae,gr[Rt]="stack",ln[Rt]=pe,Bt[Rt]=fe,Qt[Rt]=0,Sr("displayset");try{Is(),Ta({rows:rt,cols:ct}),fn(Zt),yr(gr),Cn(ln),sr(Bt),xt(Qt),tt(Rt),await Bn(ae)}finally{Sr(null)}},Os=async(G,ue,Te)=>{var Bt;const Ce=bt[ue];if(!Ce)return;let he=Ce.imageIds||[];he=await vo(he),await Bn(he,{force:!0});const ae=await ui(he);Tt(Qt=>{const lr=[...Qt];return lr[ue]?(lr[ue]={...lr[ue],seriesGroups:ae,imageIds:he},lr):Qt});const De=((Bt=ae[0])==null?void 0:Bt.imageIds)||he,pe=ri(Te);if(pe==="center"){await bo(G,ue),tt(G);return}const me=Xt.rows,ke=Xt.cols,Me=Math.floor(G/ke),Ge=G%ke,Ke=pe==="top"||pe==="bottom"?me+1:me,$e=pe==="left"||pe==="right"?ke+1:ke;if(Ke>3||$e>3||Ke*$e>Ue){await bo(G,ue),tt(G);return}const rt=Array(Ue).fill([]),ct=Array(Ue).fill("stack"),ut=Array(Ue).fill(0),mt=Array(Ue).fill(null).map(()=>[]),Rt=Array(Ue).fill(0),Zt=pe==="top"?Me:pe==="bottom"?Me+1:Me,gr=pe==="left"?Ge:pe==="right"?Ge+1:Ge,ln=Zt*$e+gr;for(let Qt=0;QtGe?pn=Et+1:pn=pe==="left"?Et+1:Et),(pe==="top"||pe==="bottom")&&Et===Ge&&(lrMe?Gt=lr+1:Gt=pe==="top"?lr+1:lr);const pr=Gt*$e+pn;rt[pr]=Lt[Qt]||[],ct[pr]=sn[Qt]||"stack",ut[pr]=an[Qt]??0,mt[pr]=kr[Qt]||[],Rt[pr]=Ze[Qt]??0}rt[ln]=De,ct[ln]="stack",ut[ln]=ue,mt[ln]=ae||[],Rt[ln]=0,Sr("displayset");try{Is(),Ta({rows:Ke,cols:$e}),fn(rt),yr(ct),Cn(ut),sr(mt),xt(Rt),tt(ln),await Bn(De)}finally{Sr(null)}},Vl=at.useCallback((G,ue)=>{if(!(de&&Le)||(ue.pointerType||"").toLowerCase()==="mouse")return;ue.preventDefault(),ue.stopPropagation(),Ye.current=Date.now()+400;const Te=Xt.rows*Xt.cols;let Ce=null,he="center";Ve({stackIdx:G,x:ue.clientX,y:ue.clientY,targetViewportIdx:null,zone:"center"});const fe=me=>{let ke=null,Me="center";for(let Ge=0;Ge$e.right||me.clientY<$e.top||me.clientY>$e.bottom)){ke=Ge,Me=ri(Ys($e,me.clientX,me.clientY));break}}Ce=ke,he=Me,Ve(Ge=>Ge&&{...Ge,x:me.clientX,y:me.clientY,targetViewportIdx:ke,zone:Me}),$t(ke!==null?{viewportIdx:ke,zone:Me}:null)},ae=async()=>{if(window.removeEventListener("pointermove",fe),window.removeEventListener("pointerup",De),window.removeEventListener("pointercancel",pe),$t(null),Ve(null),Ce!==null)try{await Os(Ce,G,he),T(!1),tt(Ce),B(Ce)}catch(me){Nt.error("Failed mobile pointer stack drop:",me)}Ye.current=Date.now()+400},De=()=>{ae()},pe=()=>{ae()};window.addEventListener("pointermove",fe,{passive:!0}),window.addEventListener("pointerup",De,{passive:!0}),window.addEventListener("pointercancel",pe,{passive:!0})},[Os,Ys,de,Le,ri,Xt]);at.useEffect(()=>{const G=async()=>{var fe;if(Nt.debug("setup"),!c.current){c.current=!0,await uee(),await _U(),SW();try{Mp("external",ae=>({promise:(async()=>{const pe=ae.replace(/^external:/,""),me=new Image;me.crossOrigin="anonymous",me.src=pe,await new Promise((ct,ut)=>{me.onload=()=>ct(!0),me.onerror=mt=>ut(mt)});const ke=me.naturalWidth||me.width,Me=me.naturalHeight||me.height,Ge=document.createElement("canvas");Ge.width=ke,Ge.height=Me;const Ke=Ge.getContext("2d");if(!Ke)throw new Error("Unable to create canvas context");Ke.drawImage(me,0,0,ke,Me);const $e=Ke.getImageData(0,0,ke,Me);return{imageId:ae,minPixelValue:0,maxPixelValue:255,slope:1,intercept:0,rows:Me,columns:ke,height:Me,width:ke,color:!0,rgba:!0,sizeInBytes:$e.data.length,getPixelData:()=>$e.data,getImageData:()=>$e,getCanvas:()=>Ge}})()}))}catch(ae){Nt.warn("Failed to register external image loader",ae)}}let Te=ye.current;Te||(Te=new BN(ie),ye.current=Te);let Ce=wi(se);Ce||(Ce=bSe(se)),sn.slice(0,Xt.rows*Xt.cols).filter(ae=>ae==="volume").length,sc(Ce);for(let ae=0;ae{if(me.offsetWidth>0&&me.offsetHeight>0){Te.resize();const $e=Te.getViewport(pe);$e&&typeof $e.resize=="function"&&$e.resize(),$e&&typeof $e.render=="function"&&$e.render()}});Ke.observe(me),me._resizeObserver=Ke}if(sn[ae]==="stack"){if(De&&De.length>0){const Ke=De[0];if(Vr(Ke))try{try{const ct=me._externalPanZoom;ct&&typeof ct.cleanup=="function"&&ct.cleanup()}catch{}me.innerHTML="";const $e=document.createElement("img");$e.style.width="100%",$e.style.height="100%",$e.style.objectFit="contain",$e.style.display="block",$e.src=Ke.replace(/^external:/,""),$e.setAttribute("draggable","false"),me.appendChild($e);const rt=Bo(me,$e);me._externalPanZoom=rt,Ce.removeViewports(ie,pe)}catch($e){Nt.warn("Failed to render external image in viewport",$e)}else try{Me.setStack(De)}catch($e){Nt.warn("viewport.setStack failed",$e)}}$i?Ce.removeViewports(ie,pe):Ce.addViewport(pe,ie)}else if(sn[ae]==="volume"){Ce.addViewport(pe,ie);const Ke=`myVolumeId_${ae}`;if((await My(Ke,{imageIds:De})).load(),Me.setVolumes([{volumeId:Ke}]),typeof Me.getNumberOfSlices=="function"){const ct=Me.getNumberOfSlices(),ut=ba.current[ae]||0,mt=Math.max(0,Math.min(Math.max(0,ct-1),ut));xo(Me.element,{imageIndex:mt})}Me.render(),me._overlayListener&&Me.element.removeEventListener(Hg,me._overlayListener);const rt=()=>_r(ae,Me);Me.element.addEventListener(Hg,rt),me._overlayListener=rt,_r(ae,Me);continue}if(Me.render(),!le.current){ji.current[ae]!==void 0&&typeof Me.setImageIdIndex=="function"&&xo(Me.element,{imageIndex:ji.current[ae]});const Ke=yo.current[ae];if(Ke&&typeof Me.setProperties=="function"){const{voiRange:$e,invert:rt,interpolationType:ct,VOILUTFunction:ut,colormap:mt}=Ke,Rt={};$e&&$e.lower!==void 0&&$e.upper!==void 0&&(Rt.voiRange=$e),rt!==void 0&&(Rt.invert=rt),ct!==void 0&&(Rt.interpolationType=ct),ut&&(Rt.VOILUTFunction=ut),mt!=null&&(typeof mt=="string"||typeof mt=="object"&&!("actor"in mt))&&(Rt.colormap=mt),setTimeout(()=>{Nt.debug("Restoring properties (timeout) for viewport",ae,Rt),Me.setProperties(Rt),Me.render()},100)}}me._overlayListener&&Me.element.removeEventListener(Hg,me._overlayListener);const Ge=()=>_r(ae,Me);Me.element.addEventListener(Hg,Ge),me._overlayListener=Ge,_r(ae,Me)}for(let ae=0;ae=2?(Ce.hasTool(al.toolName)||Ce.addTool(al.toolName),Ce.setToolEnabled(al.toolName),Ce.setToolConfiguration(al.toolName,{}),Ce.setToolActive(al.toolName,{bindings:[{mouseButton:jg.Primary}]})):Ce.hasTool(al.toolName)&&Ce.setToolDisabled(al.toolName)),tc()},ue=requestAnimationFrame(()=>{G()});return()=>{Kr.current.forEach(Te=>{Te&&Te._resizeObserver&&(Te._resizeObserver.disconnect(),delete Te._resizeObserver)}),cancelAnimationFrame(ue)}},[s,_r,Xt,sn,Lt]);const Fl=at.useCallback(G=>{const ue=`CT_${G}`,Ce=ye.current.getViewport(ue);Ce&&typeof Ce.resetCamera=="function"&&(Ce.resetCamera(),Nt.debug("Restoring viewport properties for viewport",G),Ce.resetProperties(),Ce.render())},[]),Ms=at.useCallback((G,ue,Te)=>{const Ce=`CT_${G}`;try{const he=ye.current;if(he){const fe=he.getViewport(Ce);fe&&typeof fe.setProperties=="function"&&(Nt.debug(`Applying preset to viewport ${G}: center=${ue}, width=${Te}`),fe.setProperties({voiRange:{lower:ue-Te/2,upper:ue+Te/2}}),fe.render(),_r(G,fe))}}catch{}},[_r]),Wo=at.useCallback((G,ue=!1)=>{const Te=`CT_${G}`;try{const Ce=ye.current,he=Ce==null?void 0:Ce.getViewport(Te);if(!he)return!1;const fe=typeof he.getImageIds=="function"?he.getImageIds():Lt[G]||[],ae=typeof he.getCurrentImageIdIndex=="function"?he.getCurrentImageIdIndex():0,De=fe[ae]||fe[0],pe=Go.current[G],me=De?Ct("voiLutModule",De)||{}:{},ke=De?Ct("imagePixelModule",De)||{}:{},Me=De?Ct("modalityLutModule",De)||{}:{},Ge=Array.isArray(me.windowCenter)?me.windowCenter[0]:me.windowCenter,Ke=Array.isArray(me.windowWidth)?me.windowWidth[0]:me.windowWidth,$e=Number(ke.smallestPixelValue??ke.smallestImagePixelValue),rt=Number(ke.largestPixelValue??ke.largestImagePixelValue),ct=Number(Me.rescaleSlope??1),ut=Number(Me.rescaleIntercept??0);if(pe)he.setProperties({voiRange:pe});else if(Number.isFinite(Number(Ge))&&Number.isFinite(Number(Ke))&&Number(Ke)>0){const mt=Number(Ge),Rt=Number(Ke);he.setProperties({voiRange:{lower:mt-Rt/2,upper:mt+Rt/2}})}else Number.isFinite($e)&&Number.isFinite(rt)&&rt>$e?he.setProperties({voiRange:{lower:$e*ct+ut,upper:rt*ct+ut}}):typeof he.resetProperties=="function"&&he.resetProperties();return ue&&typeof he.resetCamera=="function"&&he.resetCamera(),he.render(),_r(G,he),!0}catch(Ce){return Nt.warn("Failed to apply default window level",Ce),!1}},[_r,Lt]),zo=at.useCallback(G=>{const ue=`CT_${G}`;(async()=>{const Te=ye.current;if(!Te)return;const Ce=Te.getViewport(ue);if(!Ce)return;const he=typeof Ce.getImageIds=="function"?Ce.getImageIds():Lt[G]||[],fe=typeof Ce.getCurrentImageIdIndex=="function"?Ce.getCurrentImageIdIndex():0,ae=he[fe]||he[0];if(!ae){Wo(G);return}const De=Ct("imagePixelModule",ae)||{},pe=Ct("modalityLutModule",ae)||{},me=Ct("voiLutModule",ae)||{},ke=Go.current[G];let Me=Number(De.smallestPixelValue??De.smallestImagePixelValue),Ge=Number(De.largestPixelValue??De.largestImagePixelValue),Ke=Number(pe.rescaleSlope??1),$e=Number(pe.rescaleIntercept??0);if(!Number.isFinite(Me)||!Number.isFinite(Ge)||Ge<=Me)try{const ut=await El(ae);Me=Number(ut==null?void 0:ut.minPixelValue),Ge=Number(ut==null?void 0:ut.maxPixelValue),Ke=Number((ut==null?void 0:ut.slope)??Ke),$e=Number((ut==null?void 0:ut.intercept)??$e)}catch{const mt=he.filter(Rt=>!!Rt).slice(0,6);for(const Rt of mt)try{const Zt=await El(Rt);if(Me=Number(Zt==null?void 0:Zt.minPixelValue),Ge=Number(Zt==null?void 0:Zt.maxPixelValue),Ke=Number((Zt==null?void 0:Zt.slope)??Ke),$e=Number((Zt==null?void 0:Zt.intercept)??$e),Number.isFinite(Me)&&Number.isFinite(Ge)&&Ge>Me)break}catch{}}const rt=Array.isArray(me.windowCenter)?me.windowCenter[0]:me.windowCenter,ct=Array.isArray(me.windowWidth)?me.windowWidth[0]:me.windowWidth;if(Number.isFinite(Me)&&Number.isFinite(Ge)&&Ge>Me)Ce.setProperties({voiRange:{lower:Me*Ke+$e,upper:Ge*Ke+$e}});else if(Number.isFinite(Number(rt))&&Number.isFinite(Number(ct))&&Number(ct)>0){const ut=Number(rt),mt=Number(ct);Ce.setProperties({voiRange:{lower:ut-mt/2,upper:ut+mt/2}})}else if(ke)Ce.setProperties({voiRange:ke});else{Wo(G);return}Ce.render(),_r(G,Ce)})().catch(()=>{Wo(G)})},[Wo,_r,Lt]),io=at.useCallback((G,ue,Te=!0,Ce=!0)=>{if(Te&&(Ja.current[G]=ue),ue.action==="reset"){Wo(G,Ce);return}if(ue.action==="autolevel"){zo(G);return}const he=ue;Ms(G,he.center,he.width)},[Wo,Ms,zo]);at.useEffect(()=>{const G=()=>{const Te=ye.current;if(!Te)return;const Ce=Xt.rows*Xt.cols;for(let he=0;hewindow.clearTimeout(ue)},[io,gn,Xt,sn]),at.useEffect(()=>{const G=ue=>{var De,pe;const Te=ue.target;if(Te){const me=(De=Te.tagName)==null?void 0:De.toLowerCase(),ke=Te.getAttribute("contenteditable")==="true";if(me==="input"||me==="textarea"||me==="select"||ke)return}if(ue.ctrlKey||ue.altKey||ue.metaKey||Ae===null)return;const Ce=(pe=gn[Ae])==null?void 0:pe.modality,he=qI(Ce);if(ue.key==="0"){const me=he.find(ke=>ke.action==="reset");me&&(io(Ae,me),ue.preventDefault());return}if(!/^[1-9]$/.test(ue.key))return;const fe=Number(ue.key)-1,ae=he.filter(me=>me.action==="preset");fe>=ae.length||(io(Ae,ae[fe]),ue.preventDefault())};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[Ae,io,gn]);const Mo=at.useCallback((G,ue)=>{const Te=kr[G]||[];if(Te.length<=1)return;const Ce=Math.max(0,Math.min(Te.length-1,ue)),he=Te[Ce];if(!he||he.imageIds.length===0)return;const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`),De=sn[G]==="volume",pe=ke=>{if(!ke)return null;const Me=Ct("imagePlaneModule",ke)||{},Ge=Array.isArray(Me==null?void 0:Me.imagePositionPatient)?Me.imagePositionPatient:null,Ke=Array.isArray(Me==null?void 0:Me.rowCosines)?Me.rowCosines:null,$e=Array.isArray(Me==null?void 0:Me.columnCosines)?Me.columnCosines:null;if(Ge&&Ke&&$e&&Ke.length>=3&&$e.length>=3){const ct=[Ke[1]*$e[2]-Ke[2]*$e[1],Ke[2]*$e[0]-Ke[0]*$e[2],Ke[0]*$e[1]-Ke[1]*$e[0]],ut=Math.hypot(ct[0],ct[1],ct[2]);if(ut>1e-6){const mt=[ct[0]/ut,ct[1]/ut,ct[2]/ut];return Ge[0]*mt[0]+Ge[1]*mt[1]+Ge[2]*mt[2]}}const rt=Number(Me==null?void 0:Me.sliceLocation);return Number.isFinite(rt)?rt:null};let me=0;if(ae&&typeof ae.getCurrentImageIdIndex=="function"){const ke=Lt[G]||[],Me=ke.length,Ge=ae.getCurrentImageIdIndex(),Ke=ke[Ge]||ke[0],$e=pe(Ke);if($e!==null&&he.imageIds.length>0){let rt=0,ct=Number.POSITIVE_INFINITY;he.imageIds.forEach((ut,mt)=>{const Rt=pe(ut);if(Rt===null)return;const Zt=Math.abs(Rt-$e);Zt1?Ge/(Me-1):0;me=Math.max(0,Math.min(he.imageIds.length-1,Math.round(rt*Math.max(0,he.imageIds.length-1))))}}else if(De&&ae&&typeof ae.getSliceIndex=="function"&&typeof ae.getNumberOfSlices=="function"){const ke=ae.getNumberOfSlices(),Me=ae.getSliceIndex(),Ge=ke>1?Me/(ke-1):0;me=Math.max(0,Math.min(he.imageIds.length-1,Math.round(Ge*Math.max(0,he.imageIds.length-1))))}ba.current[G]=me,xt(ke=>{const Me=[...ke];return Me[G]=Ce,Me}),fn(ke=>{const Me=[...ke];return Me[G]=he.imageIds,Me}),Bn(he.imageIds,{force:!0}),window.setTimeout(()=>{var Me;const ke=(Me=ye.current)==null?void 0:Me.getViewport(`CT_${G}`);if(ke){if(sn[G]==="stack"&&typeof ke.setImageIdIndex=="function"){xo(ke.element,{imageIndex:me}),ke.render(),_r(G,ke);return}if(sn[G]==="volume"&&typeof ke.getNumberOfSlices=="function"){const Ge=ke.getNumberOfSlices(),Ke=Math.max(0,Math.min(Math.max(0,Ge-1),me));xo(ke.element,{imageIndex:Ke}),ke.render(),_r(G,ke)}}},25)},[kr,Bn,_r,Lt,sn]);at.useEffect(()=>{const G=[],ue=Xt.rows*Xt.cols;for(let Te=0;Te{var Ge,Ke;const De=(Ge=ye.current)==null?void 0:Ge.getViewport(`CT_${Te}`);if(!De||typeof De.getCurrentImageIdIndex!="function"||typeof De.setImageIdIndex!="function")return;const me=(((Ke=De.getImageIds)==null?void 0:Ke.call(De))||Ce).length;if(me<2)return;const Me=(De.getCurrentImageIdIndex()+1)%me;xo(De.element,{imageIndex:Me}),De.render()},fe);G.push(ae)}return()=>{G.forEach(Te=>window.clearInterval(Te))}},[Ei,tn,Xt,Lt,sn]);const Hc=at.useCallback(()=>{const G=a.current;G&&(document.fullscreenElement===G?document.exitFullscreen():G.requestFullscreen?G.requestFullscreen():G.webkitRequestFullscreen?G.webkitRequestFullscreen():G.msRequestFullscreen&&G.msRequestFullscreen())},[]);at.useEffect(()=>{aa(Array(Xt.rows*Xt.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:"",modality:"",orientation:"",resolution:"",spacing:"",focalPoint:""})),ki(Array(Xt.rows*Xt.cols).fill(!1)),Dn(Array(Ue).fill(!1))},[Xt]),at.useEffect(()=>{tc()},[Vi,bi,Qa,tc]),at.useEffect(()=>{if(!Da.some(Boolean))return;const G=ue=>{const Te=document.querySelector(".preset-menu");Te&&!Te.contains(ue.target)&&ki(Ce=>Ce.map(()=>!1))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Da]),at.useEffect(()=>{if(!Ea)return;const G=ue=>{const Te=A.current;Te&&!Te.contains(ue.target)&&(qa(!1),ve(!1))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Ea]),at.useEffect(()=>{const G=ue=>{if(ue.button===3||ue.button===4)return ue.preventDefault(),!1};return window.addEventListener("mousedown",G,!0),window.addEventListener("mouseup",G,!0),window.addEventListener("auxclick",G,!0),()=>{window.removeEventListener("mousedown",G,!0),window.removeEventListener("mouseup",G,!0),window.removeEventListener("auxclick",G,!0)}},[]),at.useEffect(()=>{const G=a.current;if(!G)return;const ue=Te=>{Te.preventDefault()};return G.addEventListener("contextmenu",ue),()=>{G.removeEventListener("contextmenu",ue)}},[]),at.useEffect(()=>{if(!Ni)return;const G=wi(se);sc(G)},[Ae,Ni]),at.useEffect(()=>{Oa.current&&(Oa.current.setAttribute("webkitdirectory","true"),Oa.current.setAttribute("directory","true"))},[]),at.useEffect(()=>(window.loadDicomStackFromWadouriList=async G=>{var fe;if(!G||G.length===0)return;const ue=await vo(G);await Bn(ue,{force:!!r});const Te=await ui(ue),Ce=((fe=Te[0])==null?void 0:fe.imageIds)||ue;let he;try{const ae=ue[0];if(ae&&ae.startsWith("wadouri:")){const De=Qc(ae),me=await(await fetch(De)).arrayBuffer();he=Lr.parseDicom(new Uint8Array(me)).string("x0020000d")}}catch{}Tt(ae=>{const De=[...ae,{imageIds:ue,studyInstanceUID:he,seriesGroups:Te}];return fn(pe=>{const me=[...pe];return me[0]=Ce,me}),Cn(pe=>{const me=[...pe];return me[0]=De.length-1,me}),sr(pe=>{const me=[...pe];return me[0]=Te,me}),xt(pe=>{const me=[...pe];return me[0]=0,me}),Bn(Ce),De})},()=>{window.loadDicomStackFromWadouriList=void 0}),[ui,vo,Tt,Bn,Cn,fn]),at.useEffect(()=>{!qr||!Lt.every(ue=>!ue||ue.length===0||ue.every(Te=>!!Ct("imagePlaneModule",Te)))||fn(ue=>{let Te=!1;const Ce=ue.map(he=>{if(!he||he.length===0)return he;const De=[...he.map(pe=>({imageId:pe,sliceLoc:(()=>{const me=Ct("imagePlaneModule",pe);return me&&me.sliceLocation!==void 0?Number(me.sliceLocation):null})()}))].sort((pe,me)=>pe.sliceLoc!==null&&me.sliceLoc!==null?pe.sliceLoc-me.sliceLoc:pe.imageId.localeCompare(me.imageId)).map(pe=>pe.imageId);return JSON.stringify(De)!==JSON.stringify(he)?(Te=!0,De):he});return Te&&ni(!0),Ce})},[qr,bt]);function sc(G){if(!G)return;const ue=`CT_${Ae}`;Ni?(G.setToolEnabled(Ld.toolName),G.setToolConfiguration(Ld.toolName,{sourceViewportId:ue})):G.setToolDisabled(Ld.toolName)}function cc(){var ue,Te,Ce;const G=ye.current;if(G)for(let he=0;he[])),Cn(Array(Ue).fill(0)),sr(Array(Ue).fill(null).map(()=>[])),xt(Array(Ue).fill(0)),Fn(Array(Ue).fill(!1)),Dn(Array(Ue).fill(!1)),yr(Array(Ue).fill("stack")),Object.values(Fo.current).forEach(ue=>{if(typeof ue=="string"&&ue.startsWith("blob:"))try{URL.revokeObjectURL(ue)}catch{}}),Fo.current={},xs({}),Ai.current={},ni(!1),tt(0)}function Ps(G,ue){var ae,De;if(Nt.debug("Truncating stack from",G,"to",ue),Nt.debug(kn),Xt.rows!==1||Xt.cols!==1||bt.length!==1||!Lt[0]||Lt[0].length===0||kn)return alert("Truncation is only allowed when a single stack is loaded in a single viewport (and the order has not been modified in the viewer)."),!1;const Te=bt[0],Ce=Te.imageIds;if(G<0||ue>=Ce.length||G>=ue)return alert("Invalid truncation bounds."),!1;const he=Ce.slice(G,ue+1);Tt([{...Te,imageIds:he}]),fn([he]),Cn([0]);const fe=ye.current;if(fe){const pe=fe.getViewport("CT_0");pe&&typeof pe.setStack=="function"&&(pe.setStack(he),(ae=pe.setImageIdIndex)==null||ae.call(pe,0),(De=pe.render)==null||De.call(pe))}return!0}function qc(G=0){const ue=ye.current;if(!ue)return null;const Te=ue.getViewport(`CT_${G}`);return!Te||typeof Te.getCurrentImageIdIndex!="function"?null:Te.getCurrentImageIdIndex()}at.useEffect(()=>{const G=t||"default";function ue(Ce,he){const fe=ye.current;if(!fe)return;const ae=fe.getViewport(`CT_${Ce}`);if(!ae||typeof ae.getImageIds!="function")return;const pe=ae.getImageIds().map(Me=>Qc(Me)),me=Qc(he),ke=pe.indexOf(me);ke!==-1&&typeof ae.setImageIdIndex=="function"&&(xo(ae.element,{imageIndex:ke}),_r(Ce,ae))}window[`getViewport_${G}`]=Ce=>{const he=ye.current;if(he)return he.getViewport(`CT_${Ce}`)},window[`getAllViewports_${G}`]=()=>{const Ce=ye.current;return Ce?Array.from({length:Ue},(he,fe)=>Ce.getViewport(`CT_${fe}`)).filter(Boolean):[]},window[`jumpToSliceByImageId_${G}`]=ue,window[`resetViewer_${G}`]=cc,window[`clearViewer_${G}`]=Kc,window[`truncateStack_${G}`]=Ps,window[`getCurrentStackPosition_${G}`]=qc,window[`loadAdditionalStack_${G}`]=async(Ce,he)=>{var me,ke;if(!Array.isArray(Ce)||Ce.length===0)return;const fe=await vo(Ce);await Bn(fe,{force:!!r});const ae=await ui(fe),De=((me=ae[0])==null?void 0:me.imageIds)||fe;let pe=he;if(!pe&&((ke=fe[0])!=null&&ke.startsWith("wadouri:")))try{const Me=Qc(fe[0]),Ke=await(await fetch(Me)).arrayBuffer();pe=Lr.parseDicom(new Uint8Array(Ke)).string("x0020000d")}catch{}Tt(Me=>[...Me,{imageIds:fe,studyInstanceUID:pe,seriesGroups:ae}]),fn(Me=>{const Ge=[...Me],Ke=Ge.findIndex($e=>!$e||$e.length===0);return Ke!==-1&&(Ge[Ke]=De,sr($e=>{const rt=[...$e];return rt[Ke]=ae,rt}),xt($e=>{const rt=[...$e];return rt[Ke]=0,rt})),Ge}),Bn(De)},window[`loadExternalStack_${G}`]=async(Ce,he)=>{!Array.isArray(Ce)||Ce.length===0||await ac(Ae??0,Ce,he||"Series","center")},window[`loadExternalStackNewViewport_${G}`]=async(Ce,he)=>{if(!Array.isArray(Ce)||Ce.length===0)return;await ac(Ae??0,Ce,he||"Series","right")},window[`exportViewerState_${G}`]=()=>{var $e;const Ce=Xt.rows*Xt.cols,he=sn.slice(0,Ce),fe=an.slice(0,Ce),ae=bt.map(rt=>({i:rt.imageIds,u:rt.studyInstanceUID,g:rt.seriesGroups}));Nt.debug("Exporting viewer state with",Ce,"active viewports"),Nt.debug("modes",he);const De=ye.current,pe=[],me=[],ke=[],Me=[],Ge=[];for(let rt=0;rt{try{le.current=!0;const he=typeof Ce=="string"?JSON.parse(Ce):Ce;if(he.grid&&Ta(he.grid),he.modes&&yr(he.modes),he.stacks&&Tt(he.stacks.map(pe=>({imageIds:pe.i,studyInstanceUID:pe.u,seriesGroups:Array.isArray(pe.g)?pe.g:void 0}))),he.stackIdx&&he.stacks){const pe=he.stackIdx.map(me=>{var ke;return((ke=he.stacks[me])==null?void 0:ke.i)||[]});fn(pe),Cn(he.stackIdx),sr(()=>{const me=Array(Ue).fill(null).map(()=>[]);for(let ke=0;kepr===Gt[Di])){Nt.warn(`Viewport ${Bt}: importedImageIds do not match viewportImageIds`,{importedImageIds:Gt,viewportImageIds:pn}),ke=!1;break}}catch{ke=!1}}if(!ke&&ae{De()},500);return}for(let Bt=0;Bt{try{xo(Qt.element,{imageIndex:he.volumeSliceIndices[Bt]})}catch{}},100)}else{try{Qt.setStack&&(Qt.setStack(Gt),Qt.render())}catch(pn){Nt.warn("Failed to set stack for viewport",Bt,pn)}if(he.stackPos&&typeof he.stackPos[Bt]=="number"&&typeof Qt.setImageIdIndex=="function")try{Kn&&xo?xo(Qt.element,{imageIndex:he.stackPos[Bt]}):Qt.setImageIdIndex(he.stackPos[Bt])}catch{}}}const Me=1500;Nt.debug(`Waiting ${Me}ms before applying properties/camera to viewports`),await new Promise(Bt=>setTimeout(Bt,Me));for(let Bt=0;Bt{De()},100)}catch(he){le.current=!1,alert("Failed to import viewer state: "+he)}},window[`exportAnnotations_${G}`]=()=>{try{let Ce=Or.getAllAnnotations();if(Nt.debug("Exporting annotations:",Ce),Array.isArray(Ce)){const he=[Ff.toolName,Gh.toolName,Uf.toolName,Su.toolName,Jd.toolName,Vf.toolName,Il.toolName,_u.toolName,Fh.toolName];Ce=Ce.filter(fe=>he.includes(fe.metadata.toolName))}else return"{}";return JSON.stringify(Ce,null,2)}catch(Ce){return alert("Failed to export annotations: "+Ce),"{}"}},window.__pendingImportAnnotations=window.__pendingImportAnnotations||{};const Te=Ce=>{try{const he=window.__pendingImportAnnotations&&window.__pendingImportAnnotations[Ce];if(!he||!he.length)return;const fe=Or;if(!fe||typeof fe.addAnnotation!="function")return;for(;(window.__pendingImportAnnotations[Ce]||[]).length;){const ae=(window.__pendingImportAnnotations[Ce]||[]).shift();ae&&Array.isArray(ae)&&ae.forEach(De=>{try{fe.addAnnotation(De,De.annotationUID)}catch(pe){Nt.error("Failed to add queued annotation",pe,De)}})}ye.current&&ye.current.render()}catch(he){Nt.error("Error flushing pending annotations:",he)}};return window[`importAnnotations_${G}`]=Ce=>{try{const he=typeof Ce=="string"?JSON.parse(Ce):Ce,fe=Or;if(!fe||typeof fe.addAnnotation!="function"){window.__pendingImportAnnotations[G]=window.__pendingImportAnnotations[G]||[],window.__pendingImportAnnotations[G].push(he),Nt.warn("importAnnotations: annotation state not ready, queued import",G),setTimeout(()=>Te(G),500);return}if(fe.removeAllAnnotations)try{fe.removeAllAnnotations()}catch(ae){Nt.warn("removeAllAnnotations failed",ae)}Array.isArray(he)&&he.forEach(ae=>{try{fe.addAnnotation(ae,ae.annotationUID)}catch(De){Nt.error("Failed to add annotation",De,ae)}}),ye.current&&ye.current.render()}catch(he){Nt.error("Failed to import annotations:",he,{apiKey:G,cornerstoneTools:!!Hxe,renderingEngine:!!ye.current});try{alert("Failed to import annotations: "+he)}catch{}}try{Te(G)}catch{}},window[`importLegacyAnnotations_${G}`]=Ce=>{Or.removeAllAnnotations&&Or.removeAllAnnotations();let he;try{he=typeof Ce=="string"?JSON.parse(Ce):Ce}catch{alert("Invalid legacy annotation JSON");return}const fe={ArrowAnnotate:"ArrowAnnotate"};Object.entries(he).forEach(([ae,De])=>{Nt.debug("Importing legacy annotations for imageId:",ae),Object.entries(De).forEach(([pe,me])=>{const ke=fe[pe]||pe;me.data&&Array.isArray(me.data)&&me.data.forEach(Me=>{const Ge=HI(ae,{x:Me.handles.start.y,y:Me.handles.start.x}),Ke=HI(ae,{x:Me.handles.end.y,y:Me.handles.end.x});Nt.debug("Importing legacy annotation:"),Nt.debug(" Image ID:",ae),Nt.debug(" Start World:",Ge),Nt.debug(" End World:",Ke);const $e=Ct("imagePlaneModule",ae);Nt.debug(SA);let rt=Ct("frameOfReferenceUID",ae);!rt&&$e&&$e.frameOfReferenceUID&&(rt=$e.frameOfReferenceUID);const ct=$e!=null&&$e.rowCosines&&($e!=null&&$e.columnCosines)?[$e.rowCosines[1]*$e.columnCosines[2]-$e.rowCosines[2]*$e.columnCosines[1],$e.rowCosines[2]*$e.columnCosines[0]-$e.rowCosines[0]*$e.columnCosines[2],$e.rowCosines[0]*$e.columnCosines[1]-$e.rowCosines[1]*$e.columnCosines[0]]:void 0;Array.isArray(ct)&&ct.length,typeof Me.rotation=="number"&&Me.rotation;const ut={annotationUID:Me.uuid,metadata:{toolName:ke,referencedImageId:ae,FrameOfReferenceUID:rt,viewPlaneNormal:ct},data:{handles:{points:[Ge,Ke],textBox:Me.handles.textBox},text:Me.text||""},visibility:Me.visible!==!1,active:Me.active||!1};Or.addAnnotation(ut,ut.annotationUID)})})}),ye.current&&ye.current.render()},window[`importLegacyViewport_${G}`]=Ce=>{let he;try{he=typeof Ce=="string"?JSON.parse(Ce):Ce}catch{alert("Invalid legacy viewport JSON");return}const fe=ye.current;if(!fe)return;const ae=`CT_${Ae??0}`,De=fe.getViewport(ae);if(!De)return;const pe={};if(he.voi&&(pe.voiRange={lower:he.voi.windowCenter-he.voi.windowWidth/2,upper:he.voi.windowCenter+he.voi.windowWidth/2}),typeof he.invert=="boolean"&&(pe.invert=he.invert),typeof he.pixelReplication=="boolean"&&(pe.interpolationType=he.pixelReplication?0:1),typeof he.hflip=="boolean"&&(pe.hflip=he.hflip),typeof he.vflip=="boolean"&&(pe.vflip=he.vflip),typeof De.setProperties=="function"&&De.setProperties(pe),he.translation||he.scale){const me=De.getCamera?De.getCamera():{};he.translation&&(me.translation={...me.translation,...he.translation}),he.scale&&(me.parallelScale=200/he.scale),Nt.debug("Applying legacy camera properties:",me),typeof De.setCamera=="function"&&De.setCamera(me)}typeof he.rotation=="number"&&De.setRotation(he.rotation),De.render(),_r(Ae??0,De)},()=>{window[`exportViewerState_${G}`]=void 0,window[`importViewerState_${G}`]=void 0,window[`exportAnnotations_${G}`]=void 0,window[`importAnnotations_${G}`]=void 0,window[`importLegacyAnnotations_${G}`]=void 0,window[`importLegacyViewport_${G}`]=void 0,window[`jumpToSliceByImageId_${G}`]=void 0,window[`resetViewer_${G}`]=void 0,window[`clearViewer_${G}`]=void 0,window[`truncateStack_${G}`]=void 0,window[`getCurrentStackPosition_${G}`]=void 0,window[`loadAdditionalStack_${G}`]=void 0,window[`loadExternalStack_${G}`]=void 0,window[`loadExternalStackNewViewport_${G}`]=void 0,window[`getViewport_${G}`]=void 0,window[`getAllViewports_${G}`]=void 0}},[Xt,sn,an,bt,Lt,Ta,yr,Cn,Tt,fn,Tt,fn,Bn]),at.useEffect(()=>{const G=a.current;if(!G)return;function ue(Te){if(Nt.debug("Handling arrow key navigation",Te.key),Nt.debug("activeViewport",Ae),Ae===null)return;const Ce=ye.current;if(!Ce)return;const he=Ce.getViewport(`CT_${Ae}`);if(he){if(Nt.debug(he),sn[Ae]==="stack"){if(typeof he.getCurrentImageIdIndex!="function"||typeof he.setImageIdIndex!="function")return;const fe=Lt[Ae];if(!fe||fe.length===0)return;Te.key==="ArrowUp"||Te.key==="ArrowRight"?(bc(he,{delta:-1}),Te.preventDefault()):(Te.key==="ArrowDown"||Te.key==="ArrowLeft")&&(bc(he,{delta:1}),Te.preventDefault())}sn[Ae]==="volume"&&typeof he.getSliceIndex=="function"&&typeof he.getNumberOfSlices=="function"&&he.getNumberOfSlices()>1&&(Te.key==="ArrowUp"||Te.key==="ArrowRight"?(bc(he,{delta:-1}),Te.preventDefault()):(Te.key==="ArrowDown"||Te.key==="ArrowLeft")&&(bc(he,{delta:1}),Te.preventDefault()))}}return G.addEventListener("keydown",ue),()=>{G.removeEventListener("keydown",ue)}},[Ae,sn,Lt,_r]);const ee=Ae!==null?an[Ae]:0,te=bt[ee];te==null||te.studyInstanceUID;const[Ee,He]=at.useState(()=>Array(Ue).fill(null)),ot=Xt.rows*Xt.cols,gt=[];for(let G=0;GKr.current[G]=fe,style:{flex:1,display:ue&&Te?"flex":"none",border:ue?"1px solid #222":"none",background:"#000",minWidth:0,minHeight:0,position:"relative",overflow:"hidden",flexDirection:"column",gridRow:Math.floor(G/Xt.cols)+1,gridColumn:G%Xt.cols+1,height:"100%",touchAction:de&&Le?"none":"pan-y",boxShadow:Ae===G?"0 0 0 4px #1976d2, 0 0 16px 4px #1976d2cc":void 0,zIndex:Ae===G?10:1},onClick:()=>{if(!Ie){if(de&&!Le){Uc(G),qa(!1),ve(!1),bs(!1);return}if(de&&Le&&z!==null){Os(G,z,Q).catch(fe=>{Nt.error("Failed to apply mobile stack drop:",fe)}),q(null),T(!1);return}tt(G),qa(!1)}},onDoubleClick:()=>Fl(G),onDragEnter:fe=>{const ae=fe.dataTransfer.types,De=ae.includes("text/stack-idx"),pe=ae.includes("text/dv3d-imageids");if(!De&&!pe)return;fe.preventDefault(),pe&&qt(!0);const me=Ir(fe);$t({viewportIdx:G,zone:me})},onDragOver:fe=>{const ae=fe.dataTransfer.types,De=ae.includes("text/stack-idx"),pe=ae.includes("text/dv3d-imageids");if(!De&&!pe)return;fe.preventDefault();const me=Ir(fe),ke=ri(me);$t({viewportIdx:G,zone:me}),fe.dataTransfer.dropEffect=ke===me?"copy":"move"},onDragLeave:fe=>{if((At==null?void 0:At.viewportIdx)!==G)return;const ae=fe.relatedTarget;ae&&fe.currentTarget.contains(ae)||$t(null)},onDrop:fe=>{fe.preventDefault();const ae=fe.dataTransfer.getData("text/dv3d-imageids");if(ae){const me=fe.dataTransfer.getData("text/dv3d-stack-name")||"Series";try{const ke=JSON.parse(ae),Me=Ir(fe);ac(G,ke,me,Me).catch(Ge=>{Nt.error("Failed to apply external drop:",Ge)})}catch(ke){Nt.error("Invalid text/dv3d-imageids payload:",ke)}$t(null),qt(!1);return}const De=fe.dataTransfer.getData("text/stack-idx"),pe=parseInt(De,10);if(!isNaN(pe)){const me=Ir(fe);Os(G,pe,me).catch(ke=>{Nt.error("Failed to apply dropped stack:",ke)})}$t(null),yt(null),qt(!1)},children:[de&&!Le&&Ne.jsx("div",{style:{position:"absolute",inset:0,zIndex:60,pointerEvents:"none",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(to top, rgba(0,0,0,0.55), rgba(0,0,0,0.2))",color:"#fff",fontSize:14,fontWeight:700,letterSpacing:.2,textAlign:"center",padding:"18px"},children:"Tap to activate fullscreen interaction"}),de&&Le&&z!==null&&Ne.jsxs("div",{style:{position:"absolute",top:8,right:8,zIndex:62,background:"rgba(25, 118, 210, 0.92)",color:"#fff",borderRadius:6,padding:"6px 8px",fontSize:11,fontWeight:700,pointerEvents:"none"},children:["Tap to drop stack (",Q,")"]}),(wt!==null||Dt)&&Ce&&Ne.jsx("div",{style:{position:"absolute",inset:0,zIndex:19,pointerEvents:"none",background:"rgba(0,0,0,0.08)"},children:Ne.jsx("div",{style:{position:"absolute",left:he==="left"?0:he==="right"?"50%":"20%",top:he==="top"?0:he==="bottom"?"50%":"20%",width:he==="left"||he==="right"?"50%":"60%",height:he==="top"||he==="bottom"?"50%":"60%",border:"2px solid #90caf9",boxShadow:"0 0 0 9999px rgba(17, 29, 45, 0.22)",background:"rgba(25, 118, 210, 0.28)",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:.4},children:he==="center"?"Load Here":`Split ${he}`})}),Ne.jsx("button",{style:{position:"absolute",top:8,left:8,zIndex:20,background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"12px",opacity:.85},onClick:()=>{yr(fe=>{const ae=[...fe];return ae[G]=fe[G]==="stack"?"volume":"stack",ae})},children:sn[G]==="stack"?"Volume":"Stack"}),sn[G]==="volume"&&Ne.jsxs("div",{style:{position:"absolute",top:8,left:70,zIndex:21,display:"flex",gap:"6px",background:"rgba(34,34,34,0.85)",borderRadius:"4px",padding:"2px 6px",alignItems:"center"},children:[Ne.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`);ae&&ae.setOrientation&&(ae.setOrientation("axial"),ae.render())},children:"Axial"}),Ne.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`);ae&&ae.setOrientation&&(ae.setOrientation("sagittal"),ae.render())},children:"Sagittal"}),Ne.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px"},onClick:()=>{const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`);ae&&ae.setOrientation&&(ae.setOrientation("coronal"),ae.render())},children:"Coronal"})]}),Ne.jsxs("button",{style:{position:"absolute",top:40,left:8,zIndex:20,background:"#111",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"13px",opacity:.85,marginTop:"4px",display:"flex",alignItems:"center",gap:"6px"},title:"Toggle Fullscreen",onClick:fe=>{fe.stopPropagation();const ae=Kr.current[G];document.fullscreenElement===ae?document.exitFullscreen():ae!=null&&ae.requestFullscreen?ae.requestFullscreen():ae!=null&&ae.webkitRequestFullscreen?ae.webkitRequestFullscreen():ae!=null&&ae.msRequestFullscreen&&ae.msRequestFullscreen()},onMouseEnter:()=>F(G),onMouseLeave:()=>F(null),children:[Ne.jsx("span",{style:{fontSize:"18px",lineHeight:1},children:"⛶"}),k===G&&Ne.jsx("span",{style:{marginLeft:6},children:document.fullscreenElement===Kr.current[G]?"Exit Fullscreen":"Fullscreen"})]}),sn[G]==="stack"&&Se&&(()=>{var $e;const fe=Lt[G],De=(Or.getAllAnnotations()||[]).filter(rt=>rt.metadata&&rt.metadata.referencedImageId&&fe.includes(rt.metadata.referencedImageId)&&rt.metadata.toolName!==os.toolName);if(!De.length)return null;const pe=ye.current,me=pe==null?void 0:pe.getViewport(`CT_${G}`),ke=(($e=me==null?void 0:me.getCurrentImageIdIndex)==null?void 0:$e.call(me))??0,Me=fe[ke],Ge=De.filter(rt=>rt.metadata.referencedImageId===Me),Ke=Ee[G];return Ne.jsxs("div",{style:{position:"absolute",left:"50%",bottom:60,transform:"translateX(-50%)",zIndex:30,display:"flex",gap:4,pointerEvents:"auto",alignItems:"center"},children:[Ne.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Previous Annotation","aria-label":"Previous Annotation",onClick:()=>{const rt=ye.current,ct=rt==null?void 0:rt.getViewport(`CT_${G}`);if(!ct||typeof ct.getCurrentImageIdIndex!="function")return;const ut=ct.getCurrentImageIdIndex(),mt=n7(ut,fe,De,-1);if(mt!==null&&typeof ct.setImageIdIndex=="function"){xo(ct.element,{imageIndex:mt}),_r(G,ct);const Rt=fe[mt],Zt=De.filter(gr=>gr.metadata.referencedImageId===Rt);Es(G,Zt.length>0?Zt[0].annotationUID:null)}},children:Ne.jsx("span",{"aria-hidden":"true",children:"◀"})}),Ne.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Next Annotation","aria-label":"Next Annotation",onClick:()=>{const rt=ye.current,ct=rt==null?void 0:rt.getViewport(`CT_${G}`);if(!ct||typeof ct.getCurrentImageIdIndex!="function")return;const ut=ct.getCurrentImageIdIndex(),mt=n7(ut,fe,De,1);if(mt!==null&&typeof ct.setImageIdIndex=="function"){xo(ct.element,{imageIndex:mt}),_r(G,ct);const Rt=fe[mt],Zt=De.filter(gr=>gr.metadata.referencedImageId===Rt);Es(G,Zt.length>0?Zt[0].annotationUID:null)}},children:Ne.jsx("span",{"aria-hidden":"true",children:"▶"})}),Ge.length>0&&Ne.jsx("div",{style:{display:"flex",gap:2,alignItems:"center"},children:Ge.map(rt=>Ne.jsxs("div",{style:{display:"flex",alignItems:"center",background:Ke===rt.annotationUID?"rgb(4, 225, 0)":"#444",color:Ke===rt.annotationUID?"#222":"#fff",borderRadius:"4px",padding:"2px 6px",marginRight:2,cursor:"pointer",border:Ke===rt.annotationUID?"2px solid #1976d2":"none",fontWeight:Ke===rt.annotationUID?"bold":"normal"},onClick:()=>Es(G,rt.annotationUID),children:[Ne.jsxs("span",{style:{marginRight:4},title:rt.metadata.toolName||"Annotation",children:[Ke===rt.annotationUID?"★ ":"",Ne.jsx("span",{style:{fontSize:14,lineHeight:1},children:ZI(rt.metadata.toolName)})]}),Ne.jsx("button",{style:{background:"transparent",color:"#f44336",border:"1px solid #f44336",borderRadius:3,width:16,height:16,fontSize:10,lineHeight:1,cursor:"pointer",marginLeft:4,display:"flex",alignItems:"center",justifyContent:"center",opacity:.95,padding:0},title:"Delete this annotation","aria-label":"Delete annotation",onClick:ct=>{ct.stopPropagation(),Zs(G,rt.annotationUID,Ge)},children:Ne.jsx("span",{"aria-hidden":"true",children:"✖"})})]},rt.annotationUID))})]})})(),Ne.jsx("div",{style:{position:"absolute",left:8,bottom:8,background:"rgba(0,0,0,0.7)",color:"#fff",padding:"6px 12px",borderRadius:"4px",fontSize:"14px",zIndex:10,pointerEvents:"none",minWidth:"120px",userSelect:"none"},children:sn[G]==="stack"?Ne.jsxs(Ne.Fragment,{children:[Ne.jsxs("div",{children:["Image: ",(Mt=gn[G])==null?void 0:Mt.index," / ",(Yt=gn[G])==null?void 0:Yt.total,(rn=gn[G])!=null&&rn.frameIndex&&((cn=gn[G])!=null&&cn.totalFrames)?Ne.jsxs(Ne.Fragment,{children:["   [Frame: ",(Z=gn[G])==null?void 0:Z.frameIndex," / ",(Y=gn[G])==null?void 0:Y.totalFrames,"]"]}):null]}),Ne.jsxs("div",{children:["WC: ",(we=gn[G])==null?void 0:we.windowCenter,"   WW: ",(We=gn[G])==null?void 0:We.windowWidth]}),ce&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsxs("div",{children:["Ori: ",((et=gn[G])==null?void 0:et.orientation)||"N/A"]}),((St=gn[G])==null?void 0:St.resolution)&&Ne.jsxs("div",{children:["Res: ",(pt=gn[G])==null?void 0:pt.resolution]}),((dt=gn[G])==null?void 0:dt.spacing)&&Ne.jsxs("div",{children:["Spacing: ",($=gn[G])==null?void 0:$.spacing]}),((K=gn[G])==null?void 0:K.focalPoint)&&Ne.jsxs("div",{children:["Pos: ",(R=gn[G])==null?void 0:R.focalPoint]})]})]}):Ne.jsxs("div",{children:["Slice: ",(U=gn[G])==null?void 0:U.index," / ",(X=gn[G])==null?void 0:X.total,((ge=gn[G])==null?void 0:ge.slicePosition)&&Ne.jsxs("span",{children:["   (",(xe=gn[G])==null?void 0:xe.slicePosition,")"]}),Ne.jsx("br",{}),"WC: ",(be=gn[G])==null?void 0:be.windowCenter,"   WW: ",(Re=gn[G])==null?void 0:Re.windowWidth,ce&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("br",{}),"Ori: ",((Fe=gn[G])==null?void 0:Fe.orientation)||"N/A",((Xe=gn[G])==null?void 0:Xe.resolution)&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("br",{}),"Res: ",(ht=gn[G])==null?void 0:ht.resolution]}),((It=gn[G])==null?void 0:It.spacing)&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("br",{}),"Spacing: ",(jt=gn[G])==null?void 0:jt.spacing]}),((kt=gn[G])==null?void 0:kt.focalPoint)&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("br",{}),"Pos: ",(In=gn[G])==null?void 0:In.focalPoint]})]})]})}),Ne.jsxs("div",{style:{position:"absolute",right:8,bottom:8,zIndex:110,pointerEvents:"auto",display:"flex",alignItems:"flex-end",gap:6},children:[Ne.jsx("button",{style:{background:Un[G]?"rgba(30,120,200,0.95)":"rgba(0,0,0,0.7)",color:"#fff",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"4px",fontSize:"12px",fontWeight:700,padding:"6px 9px",cursor:"pointer",minHeight:30},title:Un[G]?"Hide cine controls":"Show cine controls",onClick:fe=>{fe.stopPropagation(),Dn(ae=>{const De=[...ae],pe=!De[G];return De[G]=pe,pe||Fn(me=>{const ke=[...me];return ke[G]=!1,ke}),De})},children:"Cine"}),Ne.jsxs("div",{className:"preset-menu",style:{background:"rgba(0,0,0,0.7)",color:"#fff",borderRadius:"4px",fontSize:"14px",minWidth:"120px",overflow:"hidden",cursor:"pointer",position:"relative",boxShadow:Da[G]?"0 2px 8px rgba(0,0,0,0.3)":void 0,pointerEvents:"auto"},onClick:fe=>fe.stopPropagation(),children:[Ne.jsxs("div",{style:{padding:"6px 12px",fontWeight:"bold",userSelect:"none"},onClick:fe=>{fe.stopPropagation(),ki(ae=>{const De=[...ae];return De[G]=!De[G],De})},children:["Presets (",((_n=gn[G])==null?void 0:_n.modality)||"Unknown",")",Ne.jsx("span",{style:{float:"right",fontWeight:"normal"},children:Da[G]?"▲":"▼"})]}),Da[G]&&Ne.jsx("div",{className:"preset-menu-content",style:{background:"rgba(0,0,0,0.95)",borderRadius:"0 0 4px 4px",padding:"6px 0 6px 0",display:"flex",flexDirection:"column",zIndex:111,pointerEvents:"auto"},onClick:fe=>fe.stopPropagation(),children:(()=>{var De;const fe=qI((De=gn[G])==null?void 0:De.modality);let ae=0;return fe.map(pe=>{let me="";return pe.action==="reset"?me="0":pe.action==="preset"&&(ae+=1,me=String(ae)),Ne.jsxs("button",{title:me?`Shortcut: ${me}`:void 0,style:{display:"block",width:"100%",margin:"2px 0",background:pe.action==="preset"?"#333":"#444",color:"#fff",border:"none",borderRadius:"3px",cursor:"pointer",padding:pe.action==="preset"?"4px 0":"6px 0",fontSize:"13px",opacity:.9,fontWeight:pe.action==="preset"?"normal":"600"},onClick:ke=>{ke.stopPropagation(),io(G,pe),ki(Me=>{const Ge=[...Me];return Ge[G]=!1,Ge})},children:[pe.name,me?` (${me})`:""]},pe.name)})})()})]})]}),sn[G]==="stack"&&(Un[G]||(kr[G]||[]).length>1||((rr=gn[G])==null?void 0:rr.frameIndex)&&((ii=gn[G])==null?void 0:ii.totalFrames))&&Ne.jsxs("div",{style:{position:"absolute",left:"50%",bottom:8,transform:"translateX(-50%)",zIndex:36,background:"rgba(15,15,15,0.82)",border:"1px solid rgba(255,255,255,0.18)",borderRadius:8,padding:"6px 10px",display:"flex",alignItems:"center",gap:8,pointerEvents:"auto",minWidth:200,maxWidth:"72%"},onClick:fe=>fe.stopPropagation(),children:[Un[G]&&((hi=gn[G])==null?void 0:hi.total)>1&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("button",{style:{background:tn[G]?"#d32f2f":"#2e7d32",color:"#fff",border:"none",borderRadius:4,fontSize:12,padding:"4px 8px",cursor:"pointer"},title:tn[G]?"Pause cine":"Play cine",onClick:()=>{Fn(fe=>{const ae=[...fe];return ae[G]=!ae[G],ae})},children:tn[G]?"Pause":"Play"}),Ne.jsxs("label",{style:{color:"#ddd",fontSize:11,display:"flex",alignItems:"center",gap:4},children:["FPS",Ne.jsx("input",{type:"range",min:1,max:30,step:1,value:Math.max(1,Math.min(30,Math.round(Ei[G]||12))),onChange:fe=>{const ae=Number(fe.target.value);on(De=>{const pe=[...De];return pe[G]=ae,pe})}}),Ne.jsx("span",{style:{minWidth:22,textAlign:"right"},children:Math.round(Ei[G]||12)})]})]}),((Xc=gn[G])==null?void 0:Xc.frameIndex)&&((ca=gn[G])==null?void 0:ca.totalFrames)&&((Xf=gn[G])==null?void 0:Xf.totalFrames)>1&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("span",{style:{color:"#fff",fontSize:12,whiteSpace:"nowrap"},children:"Frame"}),Ne.jsx("input",{type:"range",min:1,max:((Ou=gn[G])==null?void 0:Ou.totalFrames)||1,step:1,value:Math.max(1,Math.min(((vg=gn[G])==null?void 0:vg.totalFrames)||1,((yg=gn[G])==null?void 0:yg.frameIndex)||1)),onChange:fe=>{var me;const ae=Number(fe.target.value),pe=(Lt[G]||[]).findIndex(ke=>{const Me=ke.match(/&frame=(\d+)/);return Me&&parseInt(Me[1],10)===ae});if(pe>=0){const ke=(me=ye.current)==null?void 0:me.getViewport(`CT_${G}`);ke&&typeof xo=="function"&&xo(ke.element,{imageIndex:pe})}},style:{width:100}}),Ne.jsxs("span",{style:{color:"#e0e0e0",fontSize:11,minWidth:50,textAlign:"right"},children:[(F8=gn[G])==null?void 0:F8.frameIndex," / ",(U8=gn[G])==null?void 0:U8.totalFrames]})]}),(kr[G]||[]).length>1&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("span",{style:{color:"#fff",fontSize:12,whiteSpace:"nowrap"},children:"Group"}),Ne.jsx("input",{type:"range",min:0,max:Math.max(0,(kr[G]||[]).length-1),step:1,value:Math.max(0,Math.min((kr[G]||[]).length-1,Ze[G]||0)),onChange:fe=>{Mo(G,Number(fe.target.value))},style:{width:140}}),Ne.jsx("span",{style:{color:"#e0e0e0",fontSize:11,maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:((G8=(B8=kr[G])==null?void 0:B8[Ze[G]||0])==null?void 0:G8.label)||"Group",children:((z8=(W8=kr[G])==null?void 0:W8[Ze[G]||0])==null?void 0:z8.label)||"Group"})]})]}),sn[G]==="stack"&&Lt[G]&&Ne.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"14px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:35,display:Lt[G].length>0?"flex":"none",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:(()=>{const fe=Lt[G]||[],ae=fe.length;if(ae===0)return null;const De=ye.current,pe=De==null?void 0:De.getViewport(`CT_${G}`),me=pe&&typeof pe.getCurrentImageIdIndex=="function"?pe.getCurrentImageIdIndex():-1,ke=new Set(fe.map((ct,ut)=>ro[ct]?ut:-1).filter(ct=>ct>=0)),Me=fe.map(ct=>ct.startsWith("external:")?!0:!!Ct("imagePlaneModule",ct)||!!Ct("generalSeriesModule",ct)),Ge=Me.reduce((ct,ut)=>ct+(ut?1:0),0),Ke=fe.reduce((ct,ut,mt)=>ct+(ke.has(mt)?1:0),0),$e=Math.min(ae,180),rt=Array.from({length:$e},()=>({loaded:!1,viewed:!1,current:!1}));for(let ct=0;ct{var Bt;const mt=ct.currentTarget.getBoundingClientRect(),Rt=Math.min(mt.height,Math.max(0,ct.clientY-mt.top)),Zt=mt.height>0?Rt/mt.height:0,gr=Math.min(ae-1,Math.max(0,Math.round(Zt*(ae-1)))),ln=(Bt=ye.current)==null?void 0:Bt.getViewport(`CT_${G}`);ln&&typeof ln.setImageIdIndex=="function"&&sn[G]==="stack"&&(xo(ln.element,{imageIndex:gr}),_r(G,ln))},children:[rt.map((ct,ut)=>{let mt="#3f3f3f";return ct.loaded&&(mt="#2e7d32"),ct.viewed&&(mt="#1565c0"),ct.current&&(mt="#fbc02d"),Ne.jsx("div",{style:{width:"100%",height:`${100/$e}%`,minHeight:1,background:mt,opacity:ct.loaded||ct.viewed||ct.current?.95:.45,borderBottom:ut<$e-1?"1px solid #222":"none",pointerEvents:"none"}},ut)}),me>=0&&ae>$e&&Ne.jsx("div",{style:{position:"absolute",left:0,right:0,top:`${me/Math.max(1,ae-1)*100}%`,height:2,background:"#ffeb3b",boxShadow:"0 0 4px #ffeb3b",transform:"translateY(-1px)",pointerEvents:"none"}})]})})()}),sn[G]==="volume"&&(()=>{const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`);let De=0,pe=0;return ae&&typeof ae.getNumberOfSlices=="function"&&typeof ae.getSliceIndex=="function"&&(De=ae.getNumberOfSlices(),pe=ae.getSliceIndex()),De>1?Ne.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"12px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:30,display:"flex",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:Ne.jsx("div",{style:{width:"8px",height:"100%",maxHeight:"100%",minHeight:0,borderRadius:"6px",background:"#222",position:"relative",display:"flex",flexDirection:"column",justifyContent:"flex-start",boxShadow:"0 0 8px #2196f3cc",overflow:"hidden",cursor:"pointer"},onClick:me=>{const Me=me.currentTarget.getBoundingClientRect(),Ge=me.clientY-Me.top,Ke=Math.floor(Ge/Me.height*De),$e=ye.current,rt=$e==null?void 0:$e.getViewport(`CT_${G}`);rt&&(xo(rt.element,{imageIndex:Ke}),rt.render(),_r(G,rt))},children:Array.from({length:De}).map((me,ke)=>{const Me=ke===pe;return Ne.jsx("div",{style:{width:"100%",height:`${100/De}%`,minHeight:Me?1:0,background:Me?"linear-gradient(to right, #ffeb3b 60%, #ff9800 100%)":"#444",opacity:Me?.95:.4,transition:"background 0.3s, opacity 0.3s",borderBottom:ke1||!Lt[G]||Lt[G].length===0)&&Ne.jsx("div",{style:{position:"absolute",left:0,right:0,bottom:sn[G]==="stack"&&(Un[G]||(kr[G]||[]).length>1)?56:8,zIndex:20,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",width:"100%",background:"none",borderRadius:"0",padding:0},children:Ne.jsxs("div",{style:{position:"relative"},children:[Ne.jsxs("button",{onClick:fe=>{fe.stopPropagation(),J(ae=>ae===G?null:G)},style:{padding:"6px 12px",background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",cursor:"pointer",pointerEvents:"auto",fontSize:13},title:"Choose stack",children:[(()=>{const fe=Array.isArray(an)?an[G]:void 0,ae=typeof fe=="number"&&bt[fe]?bt[fe]:void 0,De=ae&&Array.isArray(ae.imageIds)?ae.imageIds:[],pe=ae?ae.name||(ae.caseId?`Case: ${ae.caseId}`:void 0):void 0;if(pe)return pe;if(De.length>0)return`Stack ${typeof fe=="number"?fe+1:"1"}`;const me=Lt[G]||[];return me.length>0?`Stack (${me.length} images)`:"No stack"})(),Ne.jsx("span",{style:{marginLeft:8,opacity:.8},children:H===G?"▲":"▼"})]}),H===G&&Ne.jsx("div",{ref:fe=>{fe&&fe.focus()},tabIndex:0,style:{position:"absolute",left:0,bottom:"110%",background:"#222",border:"1px solid #444",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",zIndex:100,minWidth:220,maxHeight:260,overflowY:"auto",overscrollBehavior:"contain",scrollbarWidth:"thin",padding:6},role:"listbox",onMouseDown:fe=>fe.stopPropagation(),onWheel:fe=>{var De;try{fe.stopPropagation()}catch{}try{fe.preventDefault()}catch{}const ae=fe.currentTarget;if(ae){const pe=fe.deltaY??((De=fe.nativeEvent)==null?void 0:De.deltaY)??0;ae.scrollTop+=pe}},onBlur:fe=>{const ae=fe.currentTarget;setTimeout(()=>{if(!ae){J(null);return}ae.contains(document.activeElement)||J(null)},0)},children:(()=>{const fe={};return bt.forEach((ae,De)=>{const pe=ae.studyId||ae.studyInstanceUID||"Unspecified";fe[pe]||(fe[pe]=[]),fe[pe].push({idx:De,stack:ae})}),Object.keys(fe).map(ae=>Ne.jsxs("div",{style:{marginBottom:6},children:[Ne.jsx("div",{style:{fontSize:12,color:"#aaa",padding:"4px 8px",fontWeight:700},children:ae==="Unspecified"?"Unspecified study":`Study: ${ae}`}),Ne.jsx("div",{children:fe[ae].map(({idx:De,stack:pe})=>{const me=Array.isArray(pe.imageIds)?pe.imageIds:[],ke=pe&&(pe.name||pe.caseId)?pe.name||`Case: ${pe.caseId}`:`Stack ${De+1}`,Me=me.length,Ge=!Array.isArray(me)||Me===0;return Ne.jsxs("button",{role:"option","aria-selected":!1,title:Ge?"Invalid stack descriptor":`${ke} — ${Me} image${Me===1?"":"s"}${pe!=null&&pe.caseId?` — case ${pe.caseId}`:""}`,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",width:"100%",padding:"8px 12px",background:"transparent",color:"#fff",border:"none",textAlign:"left",cursor:Ge?"not-allowed":"pointer"},onClick:Ke=>{if(Ke.stopPropagation(),Ge){Nt.warn(`Attempted to select invalid stack at index ${De}`,pe);return}bo(G,De).catch($e=>Nt.error("Failed to load stack:",$e)),J(null)},children:[Ne.jsx("div",{style:{fontWeight:"600",fontSize:13},children:ke}),Ne.jsxs("div",{style:{fontSize:12,opacity:.7},children:[Me," image",Me===1?"":"s",pe!=null&&pe.caseId?` • case ${pe.caseId}`:""]})]},De)})})]},ae))})()})]})})]},G))}const vt=[_f.toolName,Yd.toolName,Cc.toolName,ll.toolName],it=[{rows:1,cols:1},{rows:1,cols:2},{rows:2,cols:2}],ft=de&&Le;return Ne.jsxs("div",{ref:a,style:{position:"relative",inset:0,width:"100%",height:"100%",boxSizing:"border-box",background:ft?"#000":"#222",padding:ft?"0px":de?"6px":"12px",overflow:"hidden"},children:[ja&&Ne.jsx("div",{style:{position:"absolute",zIndex:3e3,top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.7)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontSize:28,fontWeight:"bold",letterSpacing:1},children:ja==="annotations"?"Loading Annotations...":ja==="displayset"?"Loading Display Set...":"Loading Viewer State..."}),oa&&Ne.jsxs("div",{style:{position:"fixed",top:12,left:12,right:12,zIndex:1e4,background:"#fff3cd",color:"#856404",border:"1px solid #ffeeba",padding:"10px 14px",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[Ne.jsxs("div",{style:{flex:1,fontSize:14},children:[Ne.jsx("strong",{children:"Graphics error:"})," The viewer encountered a WebGL/graphics error and may be unstable. Please reload the page.",zi?Ne.jsx("div",{style:{marginTop:6,fontSize:12,color:"#6b4f00"},children:zi}):null]}),Ne.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[Ne.jsx("button",{onClick:()=>window.location.reload(),style:{padding:"6px 10px"},children:"Reload"}),Ne.jsx("button",{onClick:()=>no(!1),style:{padding:"6px 10px"},children:"Dismiss"})]})]}),!_&&!ft&&Ne.jsx("button",{onClick:()=>T(!0),"aria-pressed":!1,title:"Open stacks",style:{position:"absolute",right:8,top:76,zIndex:120,width:24,height:42,background:"#1976d2",color:"#fff",border:"none",borderRadius:5,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",pointerEvents:"auto"},children:"▶"}),ft&&Ne.jsx("button",{onClick:()=>{Be(!1),B(null),j(!1),T(!1),q(null);const G=a.current;G&&document.fullscreenElement===G&&document.exitFullscreen&&document.exitFullscreen().catch(()=>{})},style:{position:"absolute",top:10,left:10,zIndex:3500,background:"rgba(0,0,0,0.78)",color:"#fff",border:"1px solid rgba(255,255,255,0.25)",borderRadius:8,padding:"8px 10px",fontSize:13,fontWeight:700},children:"Exit Viewer"}),ft&&Ne.jsxs("div",{style:{position:"absolute",top:10,right:10,zIndex:3500,display:"flex",gap:8},children:[Ne.jsx("button",{onClick:()=>T(G=>!G),style:{background:"rgba(0,0,0,0.78)",color:"#fff",border:"1px solid rgba(255,255,255,0.25)",borderRadius:8,padding:"8px 10px",fontSize:13,fontWeight:700},children:"Stacks"}),Ne.jsx("button",{onClick:()=>{O?j(!1):(j(!0),B(Ae??0))},style:{background:"rgba(0,0,0,0.78)",color:"#fff",border:"1px solid rgba(255,255,255,0.25)",borderRadius:8,padding:"8px 10px",fontSize:13,fontWeight:700},children:O?"Grid":"Focus"}),Ne.jsx("button",{onClick:()=>{Ta(G=>{const ue=it.findIndex(Ce=>Ce.rows===G.rows&&Ce.cols===G.cols);return it[(ue+1+it.length)%it.length]})},style:{background:"rgba(0,0,0,0.78)",color:"#fff",border:"1px solid rgba(255,255,255,0.25)",borderRadius:8,padding:"8px 10px",fontSize:13,fontWeight:700},children:"Layout"})]}),Ie&&Ne.jsxs("div",{style:{position:"fixed",left:Ie.x+14,top:Ie.y-18,zIndex:5e3,background:"rgba(21,101,192,0.92)",color:"#fff",border:"1px solid rgba(255,255,255,0.35)",borderRadius:8,padding:"5px 8px",fontSize:11,fontWeight:700,pointerEvents:"none",whiteSpace:"nowrap"},children:["Drop on viewport ",Ie.targetViewportIdx!==null?Ie.targetViewportIdx+1:"-"," (",Ie.zone,")"]}),!ft&&Ne.jsxs("div",{children:[Ne.jsx("button",{style:{position:"absolute",top:"50%",transform:"translateY(-50%)",left:ic,zIndex:200,width:V,height:V,background:"#222",color:"#fff",border:"none",borderRadius:"50%",fontWeight:"bold",cursor:"pointer",fontSize:"22px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",transition:"left 0.25s cubic-bezier(.4,2,.6,1), background 0.2s"},onClick:()=>bs(G=>!G),"aria-label":"Open menu",children:"☰"}),zc&&Ne.jsx("div",{style:{position:"absolute",top:0,left:0,width:L,height:"100%",background:"#222",color:"#fff",zIndex:199,boxShadow:"2px 0 12px rgba(0,0,0,0.3)",flexDirection:"column",padding:"24px 16px 16px 16px",display:"flex",overflow:"hidden"},children:Ne.jsxs("div",{style:{flex:1,minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column"},children:[Ne.jsxs("div",{style:{fontWeight:"bold",fontSize:18,marginBottom:24},children:["Menu",Ne.jsx("button",{style:{float:"right",background:"transparent",color:"#fff",border:"none",fontSize:"22px",cursor:"pointer"},onClick:()=>bs(!1),"aria-label":"Close menu",children:"×"})]}),Ne.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[Ne.jsxs("label",{style:{fontSize:13},children:[Ne.jsx("input",{type:"radio",name:"folderLoadMode",value:"add",checked:nc==="add",onChange:()=>rc("add")})," Add (append)"]}),Ne.jsxs("label",{style:{fontSize:13},children:[Ne.jsx("input",{type:"radio",name:"folderLoadMode",value:"replace",checked:nc==="replace",onChange:()=>rc("replace")})," Replace all"]})]}),Ne.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:$c,children:"Load DICOM Folder"}),Ne.jsx("input",{ref:sa,type:"file",style:{display:"none"},multiple:!0,onChange:Ds}),Ne.jsx("input",{ref:Oa,type:"file",style:{display:"none"},multiple:!0,onChange:Ds,accept:".dcm,application/dicom"}),Ne.jsxs("div",{style:{marginBottom:"18px",display:"flex",alignItems:"center",gap:"8px"},children:[Ne.jsx("input",{type:"checkbox",id:"orderBySliceLocation",checked:qr,onChange:G=>Xs(G.target.checked),style:{accentColor:"#666"}}),Ne.jsx("label",{htmlFor:"orderBySliceLocation",style:{fontSize:"15px",cursor:"pointer"},children:"Order by Slice Location"})]}),Ne.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:Nl,children:"Show DICOM Metadata"}),Ne.jsxs("button",{style:{padding:"10px 18px",background:$i?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Fc(G=>!G),children:[$i?"Disable":"Enable"," Cross Reference Lines"]}),Ne.jsxs("button",{style:{padding:"10px 18px",background:Ni?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Cs(G=>!G),children:[Ni?"Disable":"Enable"," Reference Lines"]}),Ne.jsx("button",{onClick:Io,style:{margin:8,padding:8},children:"Sort All Viewports by Slice Location"}),Ne.jsx("button",{style:{padding:"10px 18px",background:Oo?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Xa(G=>!G),children:Oo?"Disable Alt Key for Reference Cursors (Shift always works)":"Enable Alt Key for Reference Cursors (Shift always works)"}),Ne.jsxs("button",{style:{padding:"10px 18px",background:Se?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>nt(G=>!G),children:[Se?"Hide":"Show"," Annotation Navigation"]}),Ne.jsxs("button",{style:{padding:"10px 18px",background:ce?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Ot(G=>!G),children:[ce?"Disable":"Enable"," Volume Diagnostics"]})]})})]}),!ft&&Ne.jsxs("div",{ref:A,className:"grid-menu-hover-container",style:{position:"absolute",top:Ea||oe?8:-18,left:"50%",transform:"translateX(-50%)",zIndex:100,display:"flex",flexDirection:"row",alignItems:"flex-start",gap:8,width:"auto",pointerEvents:"auto",transition:"top 180ms ease",paddingTop:28,marginTop:-28,paddingBottom:12},onMouseEnter:()=>ve(!0),onMouseLeave:()=>{Ea||ve(!1)},children:[Ne.jsxs("button",{style:{height:40,padding:"6px 12px 6px 10px",background:"#222",color:"#fff",border:"none",borderRadius:"0 0 4px 4px",fontWeight:"bold",cursor:"pointer",fontSize:"14px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",display:"inline-flex",alignItems:"center",gap:8},title:"Toggle viewer fullscreen",onFocus:()=>ve(!0),onClick:()=>{ve(!0),Hc()},children:[Ne.jsx("span",{style:{fontSize:16,lineHeight:1},children:"⛶"}),Ne.jsx("span",{children:"Fullscreen"})]}),Ne.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"stretch"},children:[Ne.jsxs("button",{className:"grid-menu-btn",style:{height:40,padding:"6px 14px 6px 10px",background:"#222",color:"#fff",border:"none",borderRadius:"0 0 4px 4px",fontWeight:"bold",cursor:"pointer",fontSize:"14px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",display:"inline-flex",alignItems:"center",gap:10,justifyContent:"space-between",minWidth:136},onFocus:()=>ve(!0),onClick:()=>{ve(!0),qa(G=>!G)},tabIndex:0,children:[Ne.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[Ne.jsx("span",{style:{display:"grid",gridTemplateColumns:`repeat(${Xt.cols}, 5px)`,gridTemplateRows:`repeat(${Xt.rows}, 5px)`,gap:2,padding:1},children:Array.from({length:Xt.rows*Xt.cols}).map((G,ue)=>Ne.jsx("span",{style:{width:5,height:5,borderRadius:1,background:"#90caf9",display:"block"}},ue))}),Ne.jsxs("span",{children:[Xt.rows,"x",Xt.cols]})]}),Ne.jsx("span",{style:{opacity:.8},children:Ea?"▲":"▼"})]}),Ea&&Ne.jsx("div",{style:{position:"absolute",top:"calc(100% + 8px)",right:0,background:"#222",color:"#fff",borderRadius:"6px",boxShadow:"0 2px 12px rgba(0,0,0,0.4)",padding:"12px",display:"grid",gridTemplateColumns:"repeat(3, minmax(68px, 1fr))",gap:"8px",zIndex:200,pointerEvents:"auto"},onMouseDown:G=>G.stopPropagation(),children:fi.map(G=>Ne.jsxs("button",{style:{minWidth:"68px",height:"54px",background:G.rows===Xt.rows&&G.cols===Xt.cols?"#444":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"13px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6},onClick:()=>{Is(),Ta({rows:G.rows,cols:G.cols}),qa(!1),ve(!1)},children:[Ne.jsx("span",{style:{display:"grid",gridTemplateColumns:`repeat(${G.cols}, 6px)`,gridTemplateRows:`repeat(${G.rows}, 6px)`,gap:2},children:Array.from({length:G.rows*G.cols}).map((ue,Te)=>Ne.jsx("span",{style:{width:6,height:6,borderRadius:1,background:"#90caf9",display:"block"}},Te))}),Ne.jsxs("span",{children:[G.rows,"x",G.cols]})]},`${G.rows}x${G.cols}`))})]})]}),Ne.jsxs("div",{style:{display:"flex",flexDirection:"row",height:ft?"100%":"calc(100% - 48px)",gap:ft?0:8},children:[Ne.jsxs("div",{style:{flex:1,display:"grid",margin:ft?0:3,gridTemplateRows:`repeat(${Xt.rows}, 1fr)`,gridTemplateColumns:`repeat(${Xt.cols}, 1fr)`,gap:"5px",minHeight:0,minWidth:0,zIndex:1,position:"relative"},children:[gt,!ft&&Ne.jsx("button",{style:{position:"absolute",top:8,right:8,zIndex:2600,padding:"6px 12px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer",opacity:.85,userSelect:"none"},onClick:()=>S(!0),children:"Settings"}),ft&&Ne.jsx("div",{style:{position:"absolute",left:0,right:0,bottom:10,zIndex:3200,display:"flex",justifyContent:"center",pointerEvents:"none"},children:Ne.jsx("div",{style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:6,background:"rgba(0,0,0,0.74)",border:"1px solid rgba(255,255,255,0.2)",borderRadius:10,padding:"8px 8px",maxWidth:"95%",overflowX:"auto"},children:vt.map(G=>{var Ce;const ue=Vi.Primary===G,Te=((Ce=dd.find(he=>he.value===G))==null?void 0:Ce.label)||G;return Ne.jsx("button",{title:Te,onClick:()=>jc("Primary",G),style:{minWidth:46,height:42,borderRadius:8,border:ue?"1px solid #90caf9":"1px solid rgba(255,255,255,0.22)",background:ue?"#1565c0":"#1f1f1f",color:"#fff",fontSize:18,fontWeight:700,padding:"0 8px"},children:ZI(G)},G)})})})]}),Ne.jsxs("div",{style:ft?{position:"absolute",left:8,right:8,bottom:_?62:-420,height:"min(48vh, 420px)",transition:"bottom 220ms ease",display:"flex",flexDirection:"column",pointerEvents:_?"auto":"none",overflow:"hidden",zIndex:3450,borderRadius:12,border:"1px solid #2f3336",boxShadow:"0 6px 24px rgba(0,0,0,0.45)",background:"#1f2428"}:{width:_?E:0,transition:"width 220ms ease",display:"flex",flexDirection:"column",pointerEvents:_?"auto":"none",overflow:"hidden",position:"relative"},children:[_&&!ft&&Ne.jsx("div",{onMouseDown:kl,title:"Resize stacks panel",style:{position:"absolute",left:0,top:0,width:8,height:"100%",cursor:"col-resize",zIndex:2800,background:"linear-gradient(to right, rgba(100,181,246,0.25), rgba(100,181,246,0))"}}),Ne.jsx("div",{style:{pointerEvents:"auto",width:"100%",height:"100%"},children:Ne.jsxs("div",{style:{height:"100%",width:"100%",background:"#1f2428",color:"#fff",boxShadow:"0 2px 14px rgba(0,0,0,0.45)",borderLeft:"1px solid #2f3336",transform:"translateX(0)",transition:"transform 220ms ease",display:"flex",flexDirection:"column",overflow:"hidden"},children:[Ne.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid #2b2f31"},children:[Ne.jsx("div",{style:{fontWeight:700},children:"Stacks"}),Ne.jsxs("div",{style:{fontSize:12,color:"#9bb4c8"},children:["Active VP: ",Ae!==null?Ae+1:"-"]}),Ne.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[ft&&Ne.jsxs("button",{title:"Toggle stack drop mode",onClick:()=>{re(G=>G==="center"?"right":G==="right"?"bottom":"center")},style:{background:"transparent",color:"#90caf9",border:"1px solid #335",borderRadius:6,padding:"4px 8px",cursor:"pointer",fontSize:12},children:["Drop: ",Q]}),Ne.jsx("button",{title:"Close",onClick:()=>{T(!1)},style:{background:"transparent",color:"#fff",border:"none",cursor:"pointer",fontSize:16},children:"×"})]})]}),Ne.jsx("div",{style:{overflowY:"auto",padding:8,flex:1},children:bt.length===0?Ne.jsx("div",{style:{color:"#999",padding:12},children:"No stacks available"}):Ne.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:bt.map((G,ue)=>{const Te=Array.isArray(G.imageIds)?G.imageIds:[],Ce=G.name||(G.caseId?`Case: ${G.caseId}`:`Stack ${ue+1}`),he=Te.length,fe=!Array.isArray(Te)||he===0,ae=an.includes(ue),De=Ae!==null&&an[Ae]===ue,pe=Math.floor(Te.length/2);return Te[pe]||Te[0],Ne.jsxs("div",{draggable:!fe,onDragStart:me=>{fe||(yt(ue),$t(null),me.dataTransfer.setData("text/stack-idx",String(ue)),me.dataTransfer.effectAllowed="copy")},onDragEnd:()=>{yt(null),$t(null)},onClick:()=>{if(Date.now(){if(fe||Hr[ue]||Ai.current[ue])return;const me=Math.floor(Te.length/2),ke=Te[me]||Te[0]||null;ke&&_a(ue,ke)},onMouseEnter:()=>{if(fe||Hr[ue]||Ai.current[ue])return;const me=Math.floor(Te.length/2),ke=Te[me]||Te[0]||null;ke&&_a(ue,ke)},style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 10px",background:De?"#0d47a1":ae?"#1976d2":"transparent",color:ae?"#fff":"#ddd",border:De?"1px solid #64b5f6":"1px solid transparent",borderRadius:6,cursor:fe?"not-allowed":"pointer"},children:[Ne.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(()=>{const me=Hr[ue],Me=(me&&me!=="BROKEN"?me:null)||null;return Me?Ne.jsx("img",{"data-thumb-stack":ue,src:Me,alt:Ce,style:{width:56,height:56,objectFit:"cover",borderRadius:4,background:"#111"},onError:()=>{Nt.warn("Thumbnail failed to load for stack",ue,Me),li(ue,"BROKEN")}}):Ne.jsx("div",{style:{width:56,height:56,borderRadius:4,background:"#111",display:"flex",alignItems:"center",justifyContent:"center",color:"#777"},children:"No Img"})})(),Ne.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[Ne.jsx("div",{style:{fontWeight:600},children:Ce}),Ne.jsxs("div",{style:{fontSize:12,opacity:.7},children:[he," img",he===1?"":"s"]})]})]}),Ne.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:4},children:[Ne.jsx("div",{style:{fontSize:12,opacity:.8},children:G.studyId||""}),De&&Ne.jsx("div",{style:{fontSize:11,color:"#bbdefb",fontWeight:700},children:"ACTIVE"}),ft&&!fe&&Ne.jsxs("div",{style:{display:"flex",gap:6},children:[Ne.jsx("button",{onClick:me=>{me.stopPropagation(),bo(Ae??0,ue),T(!1)},style:{background:"#1565c0",color:"#fff",border:"none",borderRadius:4,padding:"3px 7px",fontSize:11,cursor:"pointer"},children:"Load"}),Ne.jsx("button",{onClick:me=>{me.stopPropagation(),!(Date.now(){Vl(ue,me)},style:{background:z===ue?"#2e7d32":"#444",color:"#fff",border:"none",borderRadius:4,padding:"3px 7px",fontSize:11,cursor:"pointer"},children:z===ue?"Armed":"Drag"})]})]})]},ue)})})})]})})]})]}),C&&Ne.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.4)",zIndex:1e3,display:"flex",alignItems:"flex-start",justifyContent:"center",overflowY:"auto",padding:"16px 12px"},onClick:()=>S(!1),children:Ne.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",minHeight:"180px",maxWidth:"min(960px, 96vw)",maxHeight:"calc(100vh - 32px)",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative",overflowY:"auto",margin:"0 auto"},onClick:G=>G.stopPropagation(),children:[Ne.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"Settings"}),Ne.jsxs("div",{style:{marginBottom:"24px"},children:[Ne.jsx("div",{style:{marginBottom:12,fontWeight:"bold"},children:"Mouse Button Tool Bindings"}),t7.map(G=>Ne.jsxs("div",{style:{marginBottom:10},children:[Ne.jsxs("label",{style:{marginRight:8},children:[G.label," Button:"]}),Ne.jsx("select",{value:Vi[G.value],onChange:ue=>di(Te=>({...Te,[G.value]:ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:dd.map(ue=>Ne.jsx("option",{value:ue.value,title:ue.label,children:`${ue.icon?`${ue.icon} `:""}${ue.label}`},ue.value))})]},G.value)),Ne.jsxs("div",{style:{margin:"12px 0"},children:[Ne.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>Do(G=>!G),children:[Sa?"Hide":"Show"," Advanced Mouse Bindings"]}),Sa&&Ne.jsx("div",{style:{marginTop:8},children:z2.slice(3).map(G=>Ne.jsxs("div",{style:{marginBottom:10},children:[Ne.jsxs("label",{style:{marginRight:8},children:[G.label,":"]}),Ne.jsxs("select",{value:Vi[G.value]||"",onChange:ue=>di(Te=>({...Te,[G.value]:ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[Ne.jsx("option",{value:"",children:"(None)"}),dd.map(ue=>Ne.jsx("option",{value:ue.value,title:ue.label,children:`${ue.icon?`${ue.icon} `:""}${ue.label}`},ue.value))]})]},G.value))})]}),Ne.jsx("div",{style:{margin:"18px 0 8px 0",fontWeight:"bold"},children:"Ctrl + Mouse Button Tool Bindings"}),t7.map(G=>Ne.jsxs("div",{style:{marginBottom:10},children:[Ne.jsxs("label",{style:{marginRight:8},children:[G.label," + Ctrl:"]}),Ne.jsxs("select",{value:bi[G.value]||"",onChange:ue=>Za(Te=>({...Te,[G.value]:ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[Ne.jsx("option",{value:"",children:"(None)"}),dd.map(ue=>Ne.jsx("option",{value:ue.value,title:ue.label,children:`${ue.icon?`${ue.icon} `:""}${ue.label}`},ue.value))]})]},G.value+"_ctrl")),Ne.jsxs("div",{style:{margin:"12px 0"},children:[Ne.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>Ha(G=>!G),children:[Ss?"Hide":"Show"," Advanced Ctrl + Mouse Bindings"]}),Ss&&Ne.jsx("div",{style:{marginTop:8},children:z2.slice(3).map(G=>Ne.jsxs("div",{style:{marginBottom:10},children:[Ne.jsxs("label",{style:{marginRight:8},children:[G.label," + Ctrl:"]}),Ne.jsxs("select",{value:bi[G.value]||"",onChange:ue=>Za(Te=>({...Te,[G.value]:ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[Ne.jsx("option",{value:"",children:"(None)"}),dd.map(ue=>Ne.jsx("option",{value:ue.value,title:ue.label,children:`${ue.icon?`${ue.icon} `:""}${ue.label}`},ue.value))]})]},G.value+"_ctrl"))})]})]}),Ne.jsxs("div",{style:{marginTop:8,paddingTop:16,borderTop:"1px solid #333"},children:[Ne.jsx("div",{style:{marginBottom:10,fontWeight:"bold"},children:"Stack Grouping"}),Ne.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",marginBottom:10},children:[Ne.jsx("input",{type:"checkbox",checked:y,onChange:G=>m(G.target.checked)}),"Enable advanced DWI/time/echo grouping"]}),Ne.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,opacity:y?1:.6},children:hp.map(G=>Ne.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:y?"pointer":"default"},title:G.description,children:[Ne.jsx("input",{type:"checkbox",disabled:!y,checked:!!w[G.id],onChange:ue=>{const Te=ue.target.checked;x(Ce=>({...Ce,[G.id]:Te}))}}),G.label]},G.id))})]}),Ne.jsxs("div",{style:{marginTop:8,paddingTop:16,borderTop:"1px solid #333"},children:[Ne.jsx("div",{style:{marginBottom:10,fontWeight:"bold"},children:"Logging"}),Ne.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,marginBottom:10,flexWrap:"wrap"},children:[Ne.jsxs("div",{children:[Ne.jsx("label",{style:{marginRight:8},children:"Level:"}),Ne.jsx("select",{value:h,onChange:G=>g(v5(G.target.value)),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:_Se.map(G=>Ne.jsx("option",{value:G.value,children:G.label},G.value))})]}),Ne.jsxs("div",{children:[Ne.jsx("label",{style:{marginRight:8},children:"Format:"}),Ne.jsx("select",{value:p,onChange:G=>v(Wp(G.target.value)),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:SSe.map(G=>Ne.jsx("option",{value:G.value,children:G.label},G.value))})]})]})]}),Ne.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>S(!1),"aria-label":"Close",children:"×"})]})}),Al&&Ne.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"rgba(0,0,0,0.5)",zIndex:2e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>Ts(!1),children:Ne.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",maxWidth:"80vw",maxHeight:"80vh",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative",overflow:"auto"},onClick:G=>G.stopPropagation(),children:[Ne.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"DICOM Metadata"}),Bc,Ne.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>Ts(!1),"aria-label":"Close",children:"×"})]})})]})}function bSe(t){Nt.debug("Setting up tools...",t),Yi(Cc),Yi(Yd),Yi(_f),Yi(ll),Yi(Vh),Yi(Ff),Yi(_u),Yi(Uf),Yi(Su),Yi(Jd),Yi(Vf),Yi(Il),Yi(Fh),Yi(os),Yi(al),Yi(Ld),Yi(Gh);let e=wi(t);return e||(e=Rk(t),e.addTool(Yd.toolName),e.addTool(Cc.toolName),e.addTool(ll.toolName),e.addTool(_f.toolName,{loop:!1}),e.addTool(Vh.toolName),e.addTool(Ff.toolName),e.addTool(Gh.toolName,{getTextCallback:()=>""}),e.addTool(Uf.toolName),e.addTool(_u.toolName,{statsCalculator:()=>null}),e.addTool(Su.toolName,{calculateStats:!1,getTextCallback:()=>""}),e.addTool(Jd.toolName,{getTextCallback:()=>""}),e.addTool(Vf.toolName,{calculateStats:!1}),e.addTool(Il.toolName,{}),e.addTool(Fh.toolName,{}),e.addTool(Ld.toolName),e.addTool(os.toolName)),e}function n7(t,e,r,n){if(!r.length||!e.length)return null;const i=r.map(o=>e.findIndex(a=>a===o.metadata.referencedImageId)).filter(o=>o!==-1).sort((o,a)=>o-a);if(!i.length)return null;if(n===1){for(let o of i)if(o>t)return o;return i[0]}else{for(let o=i.length-1;o>=0;o--)if(i[o]`wadouri:/test_images/stack2/IMG${r+1}.dcm`),Array.from({length:25},(e,r)=>`wadouri:/test_images/stack5/IMG${r+1}.dcm`),Array.from({length:26},(e,r)=>`wadouri:/test_images/stack3/IMG${r+1}.dcm`)]}const MC=new WeakMap,zp=LW.child("main"),ISe=t=>{const e=t.trim();return!e||e.startsWith("external:")||e.startsWith("wadors:")?e:e.startsWith("wadouri:")?`wadouri:${e.slice(8).replace(/^:+/,"")}`:`wadouri:${e.replace(/^:+/,"")}`},Km=t=>t.map(ISe),r7=t=>t?{imageIds:Km(t)}:{imageIds:[]},OSe=t=>{if(!t)return[];if(Array.isArray(t)&&t.length>0&&typeof t[0]=="string")return[r7(t)];if(!Array.isArray(t))return[];const e=[];return t.forEach((r,n)=>{if(r&&typeof r=="object"&&Array.isArray(r.stacks)){const i=r.caseId||r.caseUID||r.case||void 0,o=r.studyId||r.studyUID||r.studyInstanceUID||void 0;r.stacks.forEach((a,s)=>{let c=[];if(Array.isArray(a)?c=a:Array.isArray(a.imageIds)?c=a.imageIds:Array.isArray(a.i)&&(c=a.i),!Array.isArray(c)||c.length===0||!c.every(l=>typeof l=="string")){zp.warn(`data-named-stacks: skipping invalid nested stack at parsed[${n}].stacks[${s}]`,a);return}e.push({imageIds:Km(c),name:a.name||a.label||void 0,caseId:i,studyId:a.studyId||o})});return}if(r&&typeof r=="object"&&(Array.isArray(r.imageIds)||Array.isArray(r.i))){const i=Array.isArray(r.imageIds)?r.imageIds:r.i;if(!Array.isArray(i)||i.length===0||!i.every(o=>typeof o=="string")){zp.warn(`data-named-stacks: skipping invalid stack object at parsed[${n}]`,r);return}e.push({imageIds:Km(i),name:r.name||r.label||void 0,caseId:r.caseId||r.caseUID||void 0,studyId:r.studyId||r.studyUID||r.studyInstanceUID||void 0});return}if(Array.isArray(r)&&r.length>0&&typeof r[0]=="string"){e.push(r7(r));return}zp.warn(`data-named-stacks: unknown or invalid entry at parsed[${n}] - skipping`,r)}),e},MSe=t=>JSON.stringify({id:t.id||"",empty:t.getAttribute("data-empty")||"",namedStacks:t.getAttribute("data-named-stacks")||"",images:t.getAttribute("data-images")||"",autoCache:t.getAttribute("data-auto-cache-stack")||"",annotation:t.getAttribute("data-annotationjson")||"",viewerState:t.getAttribute("data-viewerstate")||""}),i7=(t,e)=>!(e!=null&&e.containerIds)||e.containerIds.length===0?!0:e.containerIds.includes(t.id||""),PSe=(t,e)=>{var s,c,l;const r=t.getAttribute("data-log-level"),n=t.getAttribute("data-log-debug"),i=t.getAttribute("data-log-format");let o;r!==null?o=v5(r):(s=e==null?void 0:e.logging)!=null&&s.minLevel?o=e.logging.minLevel:n!==null?o=a_(n):((c=e==null?void 0:e.logging)==null?void 0:c.debug)!==void 0?o=a_(e.logging.debug):o="warn";const a=Wp(i??((l=e==null?void 0:e.logging)==null?void 0:l.format));return{minLevel:o,format:a}},o7=(t,e,r)=>{const n=MSe(t),i=MC.get(t),o=PSe(t,r);if(i&&!(r!=null&&r.force)&&i.signature===n)return;i&&(i.root.unmount(),MC.delete(t)),w8(o);const a=yM(t);a.render(Ne.jsx(ESe,{container_id:t.id||"",imageStacks:e,autoCacheStack:t.getAttribute("data-auto-cache-stack")==="true"||t.getAttribute("data-auto-cache-stack")==="1",annotationJson:t.getAttribute("data-annotationjson")||void 0,viewerState:t.getAttribute("data-viewerstate")||void 0,initialLoggerConfig:o})),MC.set(t,{root:a,signature:n})};function x8(t){document.querySelectorAll(".dicom-viewer-test-root").forEach(n=>{if(!i7(n,t))return;o7(n,()=>DSe(),t)}),document.querySelectorAll(".dicom-viewer-root").forEach(n=>{if(!i7(n,t))return;let i;const o=n.getAttribute("data-empty")==="true",a=n.getAttribute("data-named-stacks"),s=n.getAttribute("data-images");if(o)i=()=>Promise.resolve([]);else if(a){let c;try{c=JSON.parse(a)}catch(f){zp.error("Invalid data-named-stacks JSON:",f),c=[]}const l=OSe(c);i=()=>Promise.resolve(l)}else if(s){let c;try{c=JSON.parse(s)}catch(l){zp.error("Invalid data-images JSON:",l),c=[]}Array.isArray(c)&&c.length>0&&typeof c[0]=="string"?i=()=>Promise.resolve([Km(c)]):Array.isArray(c)?i=()=>Promise.resolve(c.map(l=>Array.isArray(l)?Km(l):[])):i=()=>Promise.resolve([[]])}else i=()=>Promise.resolve([]);o7(n,i,t)})}x8();window.mountDicomViewers=x8;window.remountDicomViewer=t=>{x8({force:!0,containerIds:[t]})};window.setDicomViewerLogging=t=>{const e=t.minLevel?v5(t.minLevel):t.debug!==void 0?a_(t.debug):void 0;w8({minLevel:e,format:t.format?Wp(t.format):void 0})};window.getDicomViewerLogging=()=>m5(); +`,kt.push(It);var rr=Vi(Function,kt).apply(null,In);return rr}function bi($,K,R,U,X,ge){T(K>0);var xe=ki(K,R);X=vr(U,X),Hr([],[$],function(be){be=be[0];var Re="constructor "+be.name;if(be.registeredClass.constructor_body===void 0&&(be.registeredClass.constructor_body=[]),be.registeredClass.constructor_body[K-1]!==void 0)throw new Bo("Cannot register multiple constructors with identical number of parameters ("+(K-1)+") for class '"+be.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return be.registeredClass.constructor_body[K-1]=()=>{yr("Cannot construct "+be.name+" due to unbound types",xe)},Hr([],xe,function(Fe){return Fe.splice(1,0,null),be.registeredClass.constructor_body[K-1]=di(Re,Fe,null,X,ge),[]}),[]})}function Za($,K,R,U,X,ge,xe,be){var Re=ki(R,U);K=Vr(K),ge=vr(X,ge),Hr([],[$],function(Fe){Fe=Fe[0];var Xe=Fe.name+"."+K;K.startsWith("@@")&&(K=Symbol[K.substring(2)]),be&&Fe.registeredClass.pureVirtualFunctions.push(K);function ht(){yr("Cannot call "+Xe+" due to unbound types",Re)}var It=Fe.registeredClass.instancePrototype,jt=It[K];return jt===void 0||jt.overloadTable===void 0&&jt.className!==Fe.name&&jt.argCount===R-2?(ht.argCount=R-2,ht.className=Fe.name,It[K]=ht):(ji(It,K,Xe),It[K].overloadTable[R-2]=ht),Hr([],Re,function(kt){var In=di(Xe,kt,Fe,ge,xe);return It[K].overloadTable===void 0?(In.argCount=R-2,It[K]=In):It[K].overloadTable[R-2]=In,[]}),[]})}var Qa=[],Hi=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function Uc($){$>4&&--Hi[$].refcount===0&&(Hi[$]=void 0,Qa.push($))}function Al(){for(var $=0,K=5;K($||kn("Cannot use deleted val. handle = "+$),Hi[$].value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var K=Qa.length?Qa.pop():Hi.length;return Hi[K]={refcount:1,value:$},K}}}};function Es($,K){K=Vr(K),ni($,{name:K,fromWireType:function(R){var U=Ia.toValue(R);return Uc(R),U},toWireType:function(R,U){return Ia.toHandle(U)},argPackAdvance:8,readValueFromPointer:sr,destructorFunction:null})}function Zs($){if($===null)return"null";var K=typeof $;return K==="object"||K==="array"||K==="function"?$.toString():""+$}function Nl($,K){switch(K){case 2:return function(R){return this.fromWireType(J[R>>2])};case 3:return function(R){return this.fromWireType(oe[R>>3])};default:throw new TypeError("Unknown float type: "+$)}}function Gc($,K,R){var U=Ai(R);K=Vr(K),ni($,{name:K,fromWireType:function(X){return X},toWireType:function(X,ge){return ge},argPackAdvance:8,readValueFromPointer:Nl(K,U),destructorFunction:null})}function Qs($,K,R,U,X,ge){var xe=ki(K,R);$=Vr($),X=vr(U,X),qr($,function(){yr("Cannot call "+$+" due to unbound types",xe)},K-1),Hr([],xe,function(be){var Re=[be[0],null].concat(be.slice(1));return Ya($,di($,Re,null,X,ge),K-1),[]})}function Wc($,K,R){switch(K){case 0:return R?function(X){return V[X]}:function(X){return W[X]};case 1:return R?function(X){return A[X>>1]}:function(X){return k[X>>1]};case 2:return R?function(X){return F[X>>2]}:function(X){return H[X>>2]};default:throw new TypeError("Unknown integer type: "+$)}}function ec($,K,R,U,X){K=Vr(K);var ge=Ai(R),xe=ht=>ht;if(U===0){var be=32-8*R;xe=ht=>ht<>>be}var Re=K.includes("unsigned"),Fe=(ht,It)=>{},Xe;Re?Xe=function(ht,It){return Fe(It,this.name),It>>>0}:Xe=function(ht,It){return Fe(It,this.name),It},ni($,{name:K,fromWireType:xe,toWireType:Xe,argPackAdvance:8,readValueFromPointer:Wc(K,ge,U!==0),destructorFunction:null})}function tc($,K,R){var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],X=U[K];function ge(xe){xe=xe>>2;var be=H,Re=be[xe],Fe=be[xe+1];return new X(L,Fe,Re)}R=Vr(R),ni($,{name:R,fromWireType:ge,argPackAdvance:8,readValueFromPointer:ge},{ignoreDuplicateRegistrations:!0})}function zc($,K){K=Vr(K);var R=K==="std::string";ni($,{name:K,fromWireType:function(U){var X=H[U>>2],ge=U+4,xe;if(R)for(var be=ge,Re=0;Re<=X;++Re){var Fe=ge+Re;if(Re==X||W[Fe]==0){var Xe=Fe-be,ht=D(be,Xe);xe===void 0?xe=ht:(xe+="\0",xe+=ht),be=Fe+1}}else{for(var It=new Array(X),Re=0;Re>2]=ge,R&&xe)P(X,Re,ge+1);else if(xe)for(var Fe=0;Fe255&&(Ee(Re),kn("String has UTF-16 code units that do not fit in 8 bits")),W[Re+Fe]=Xe}else for(var Fe=0;Fe>1,X=U+K/2;!(U>=X)&&k[U];)++U;if(R=U<<1,R-$>32&&bs)return bs.decode(W.subarray($,R));for(var ge="",xe=0;!(xe>=K/2);++xe){var be=A[$+xe*2>>1];if(be==0)break;ge+=String.fromCharCode(be)}return ge}function rc($,K,R){if(R===void 0&&(R=2147483647),R<2)return 0;R-=2;for(var U=K,X=R<$.length*2?R/2:$.length,ge=0;ge>1]=xe,K+=2}return A[K>>1]=0,K-U}function sa($){return $.length*2}function kl($,K){for(var R=0,U="";!(R>=K/4);){var X=F[$+R*4>>2];if(X==0)break;if(++R,X>=65536){var ge=X-65536;U+=String.fromCharCode(55296|ge>>10,56320|ge&1023)}else U+=String.fromCharCode(X)}return U}function ic($,K,R){if(R===void 0&&(R=2147483647),R<4)return 0;for(var U=K,X=U+R-4,ge=0;ge<$.length;++ge){var xe=$.charCodeAt(ge);if(xe>=55296&&xe<=57343){var be=$.charCodeAt(++ge);xe=65536+((xe&1023)<<10)|be&1023}if(F[K>>2]=xe,K+=4,K+4>X)break}return F[K>>2]=0,K-U}function oc($){for(var K=0,R=0;R<$.length;++R){var U=$.charCodeAt(R);U>=55296&&U<=57343&&++R,K+=4}return K}function $c($,K,R){R=Vr(R);var U,X,ge,xe,be;K===2?(U=nc,X=rc,xe=sa,ge=()=>k,be=1):K===4&&(U=kl,X=ic,xe=oc,ge=()=>H,be=2),ni($,{name:R,fromWireType:function(Re){for(var Fe=H[Re>>2],Xe=ge(),ht,It=Re+4,jt=0;jt<=Fe;++jt){var kt=Re+4+jt*K;if(jt==Fe||Xe[kt>>be]==0){var In=kt-It,_n=U(It,In);ht===void 0?ht=_n:(ht+="\0",ht+=_n),It=kt+K}}return Ee(Re),ht},toWireType:function(Re,Fe){typeof Fe!="string"&&kn("Cannot pass non-string to C++ string type "+R);var Xe=xe(Fe),ht=te(4+Xe+K);return H[ht>>2]=Xe>>be,X(Fe,ht+4,Xe+K),Re!==null&&Re.push(Ee,ht),ht},argPackAdvance:8,readValueFromPointer:sr,destructorFunction:function(Re){Ee(Re)}})}function Oa($,K,R,U,X,ge){Cn[$]={name:Vr(K),rawConstructor:vr(R,U),rawDestructor:vr(X,ge),fields:[]}}function Ds($,K,R,U,X,ge,xe,be,Re,Fe){Cn[$].fields.push({fieldName:Vr(K),getterReturnType:R,getter:vr(U,X),getterContext:ge,setterArgumentType:xe,setter:vr(be,Re),setterContext:Fe})}function jc($,K){K=Vr(K),ni($,{isVoid:!0,name:K,argPackAdvance:0,fromWireType:function(){},toWireType:function(R,U){}})}function _r($){$>4&&(Hi[$].refcount+=1)}function Is($,K){var R=xt[$];return R===void 0&&kn(K+" has unknown type "+sn($)),R}function ac($,K){$=Is($,"_emval_take_value");var R=$.readValueFromPointer(K);return Ia.toHandle(R)}function Os(){Ye("")}function Vl($,K,R){W.copyWithin($,K,K+R)}function Fl(){return 2147483648}function Ms($){try{return S.grow($-L.byteLength+65535>>>16),ve(S.buffer),1}catch{}}function Wo($){var K=W.length;$=$>>>0;var R=Fl();if($>R)return!1;let U=(Re,Fe)=>Re+(Fe-Re%Fe)%Fe;for(var X=1;X<=4;X*=2){var ge=K*(1+.2/X);ge=Math.min(ge,$+100663296);var xe=Math.min(R,U(Math.max($,ge),65536)),be=Ms(xe);if(be)return!0}return!1}function zo($){return 52}function io($,K,R,U,X){return 70}var Mo=[null,[],[]];function Hc($,K){var R=Mo[$];K===0||K===10?(($===1?w:x)(b(R,0)),R.length=0):R.push(K)}function sc($,K,R,U){for(var X=0,ge=0;ge>2],be=H[K+4>>2];K+=8;for(var Re=0;Re>2]=X,0}function cc($){return $}function Kc($){var K=o["_"+$];return K}function Ps($,K){V.set($,K)}function qc($,K,R,U,X){var ge={string:kt=>{var In=0;if(kt!=null&&kt!==0){var _n=(kt.length<<2)+1;In=ft(_n),P(kt,In,_n)}return In},array:kt=>{var In=ft(kt.length);return Ps(kt,In),In}};function xe(kt){return K==="string"?D(kt):K==="boolean"?!!kt:kt}var be=Kc($),Re=[],Fe=0;if(U)for(var Xe=0;Xe0||(Pe(),Q>0))return;function K(){pt||(pt=!0,o.calledRun=!0,!_&&(B(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),O()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),K()},1)):K()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return dt(),o.ready}})();t.exports=r})(DW);var Z3e=DW.exports;const Q3e=Ml(Z3e),eSe=new URL("/static/dv3d/openjphjs.wasm",import.meta.url),dp={codec:void 0,decoder:void 0,decodeConfig:{}};function tSe(t,e,r){const n={width:e,height:r};for(;t>0;)n.width=Math.ceil(n.width/2),n.height=Math.ceil(n.height/2),t--;return n}function nSe(t){if(dp.decodeConfig=t,dp.codec)return Promise.resolve();const e=Q3e({locateFile:r=>r.endsWith(".wasm")?eSe.toString():r});return new Promise((r,n)=>{e.then(i=>{dp.codec=i,dp.decoder=new i.HTJ2KDecoder,r()},n)})}async function rSe(t,e){await nSe();const r=new dp.codec.HTJ2KDecoder,n=r.getEncodedBuffer(t.length);n.set(t);const i=e.decodeLevel||0;r.decodeSubResolution(i);const o=r.getFrameInfo();if(e.decodeLevel>0){const{width:E,height:b}=tSe(e.decodeLevel,o.width,o.height);o.width=E,o.height=b}const a=r.getDecodedBuffer();new Uint8Array(a.length).set(a);const c=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,l=r.getNumDecompositions(),f=r.getNumLayers(),u=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],d=r.getIsReversible(),h=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,g=`${r.getTileSize().width} x ${r.getTileSize().height}`,p=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,v=`${a.length.toLocaleString()} bytes`,y=`${(a.length/n.length).toFixed(2)}:1`,m={columns:o.width,rows:o.height,bitsPerPixel:o.bitsPerSample,signed:o.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:o.componentCount};let w=iSe(o,a);const{buffer:x,byteOffset:C,byteLength:S}=w,_=x.slice(C,C+S);w=new w.constructor(_);const T={imageOffset:c,numDecompositions:l,numLayers:f,progessionOrder:u,reversible:d,blockDimensions:h,tileSize:g,tileOffset:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:T,...T,...m}}function iSe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function oSe(t,e){const r=t.length,{rescaleSlope:n,rescaleIntercept:i,suvbw:o,doseGridScaling:a}=e;if(e.modality==="PT"&&typeof o=="number"&&!isNaN(o))for(let s=0;s>o;let a=t.pixelData;t.pixelDataLength=t.pixelData.length;const{min:s,max:c}=jw(t.pixelData),l=typeof e.allowFloatRendering<"u"?e.allowFloatRendering:!0;let f=d8(t.photometricInterpretation)&&((m=e.targetBuffer)==null?void 0:m.offset)===void 0;const d=((w=e.preScale)==null?void 0:w.enabled)&&Object.values(e.preScale.scalingParameters).some(C=>typeof C=="number"&&!Number.isInteger(C)),h=!e.preScale.enabled||!l&&d,g=(x=e.targetBuffer)==null?void 0:x.type;if(g&&e.preScale.enabled&&!h){const C=e.preScale.scalingParameters,S=o_(s,c,C);f=!UCe(S.min,S.max,WI[g])}g&&!f?a=lSe(e,t,WI,a):e.preScale.enabled&&!h?a=uSe(e,s,c,t):a=IW(s,c,t);let p=s,v=c;if(e.preScale.enabled&&!h){const C=e.preScale.scalingParameters;if(OW(C),cSe(C)){oSe(a,C),t.preScale={...e.preScale,scaled:!0};const _=o_(s,c,C);p=_.min,v=_.max}}else h&&(t.preScale={enabled:!0,scaled:!1},p=s,v=c);t.pixelData=a,t.smallestPixelValue=p,t.largestPixelValue=v;const y=new Date().getTime();return t.decodeTimeInMS=y-r,t}function cSe(t){const{rescaleSlope:e,rescaleIntercept:r,modality:n,doseGridScaling:i,suvbw:o}=t;return typeof e=="number"&&typeof r=="number"||n==="RTDOSE"&&typeof i=="number"||n==="PT"&&typeof o=="number"}function lSe(t,e,r,n){const{arrayBuffer:i,type:o,offset:a=0,length:s,rows:c}=t.targetBuffer,l=r[o];if(!l)throw new Error(`target array ${o} is not supported, or doesn't exist.`);c&&c!=e.rows&&dSe(e,t.targetBuffer,l);const f=e.pixelDataLength,u=a,d=s??f-u,h=e.pixelData;if(d!==h.length)throw new Error(`target array for image does not have the same length (${d}) as the decoded image length (${h.length}).`);const g=i?new l(i,u,d):new l(d);return g.set(h,0),n=g,n}function uSe(t,e,r,n){const i=t.preScale.scalingParameters;OW(i);const o=o_(e,r,i);return IW(o.min,o.max,n)}function IW(t,e,r){const n=h8(t,e),i=new n(r.pixelData.length);return i.set(r.pixelData,0),i}function o_(t,e,r){const{rescaleSlope:n,rescaleIntercept:i,modality:o,doseGridScaling:a,suvbw:s}=r;return o==="PT"&&typeof s=="number"&&!isNaN(s)?{min:s*(t*n+i),max:s*(e*n+i)}:o==="RTDOSE"&&typeof a=="number"&&!isNaN(a)?{min:t*a,max:e*a}:typeof n=="number"&&typeof i=="number"?{min:n*t+i,max:n*e+i}:{min:t,max:e}}function OW(t){if(!t)throw new Error("options.preScale.scalingParameters must be defined if preScale.enabled is true, and scalingParameters cannot be derived from the metadata providers.")}function fSe(t,e,r){const{samplesPerPixel:n}=t,{rows:i,columns:o}=e,a=i*o*n,s=new r(a),c=s.byteLength/a;return{pixelData:s,rows:i,columns:o,frameInfo:{...t.frameInfo,rows:i,columns:o},imageInfo:{...t.imageInfo,rows:i,columns:o,bytesPerPixel:c}}}function dSe(t,e,r){const n=fSe(t,e,r),{scalingType:i="replicate"}=e;return aSe[i](t,n),Object.assign(t,n),t.pixelDataLength=t.pixelData.length,t}async function MW(t,e,r,n,i,o){const a=new Date().getTime();let s=null,c;switch(e){case"1.2.840.10008.1.2":case"1.2.840.10008.1.2.1":s=VI(t,r);break;case"1.2.840.10008.1.2.2":s=E3e(t,r);break;case"1.2.840.10008.1.2.1.99":s=VI(t,r);break;case"1.2.840.10008.1.2.5":s=b3e(t,r);break;case"1.2.840.10008.1.2.4.50":c={...t},s=A3e(r,c);break;case"1.2.840.10008.1.2.4.51":s=U3e(t,r);break;case"1.2.840.10008.1.2.4.57":s=UI(t,r);break;case"1.2.840.10008.1.2.4.70":s=UI(t,r);break;case"1.2.840.10008.1.2.4.80":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=BI(r,c);break;case"1.2.840.10008.1.2.4.81":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=BI(r,c);break;case"1.2.840.10008.1.2.4.90":c={...t},s=GI(r,c);break;case"1.2.840.10008.1.2.4.91":c={...t},s=GI(r,c);break;case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":c={...t},s=rSe(r,c);break;default:throw new Error(`no decoder for transfer syntax ${e}`)}if(!s)throw new Error("decodePromise not defined");const l=await s,f=sSe(l,i,a);return o==null||o(f),f}const hSe={decodeTask({imageFrame:t,transferSyntax:e,decodeConfig:r,options:n,pixelData:i,callbackFn:o}){return MW(t,e,i,r,n,o)}};i4(hSe);const Uu={constants:C3e,convertRGBColorByPixel:UG,convertRGBColorByPlane:BG,convertYBRFullByPixel:GG,convertYBRFullByPlane:WG,convertPALETTECOLOR:zG,wadouri:$Ce,wadors:p3e,init:SW,convertColorSpace:cW,createImage:Hw,decodeJPEGBaseline8BitColor:lW,getImageFrame:uW,getPixelData:v8,getMinMax:jw,isColorImage:d8,isJPEGBaseline8BitColor:w3e,internal:oCe,decodeImageFrame:MW},zI={debug:0,info:1,warn:2,error:3,silent:4},y8={minLevel:"warn",format:"compact",namespace:"dv3d",dedupeWindowMs:1200};let $s={...y8};const $I=new Map;function PW(){return new Date().toISOString()}function jI(t){return t==="debug"?console.debug.bind(console):t==="info"?console.info.bind(console):t==="warn"?console.warn.bind(console):console.error.bind(console)}function RW(t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t}function gSe(t){return zI[t]>=zI[$s.minLevel]}function pSe(t){return t==="debug"||t==="info"}function mSe(t,e,r){const n=(r==null?void 0:r.dedupeKey)||`${(r==null?void 0:r.namespace)||$s.namespace}:${t}`,i=e.map(o=>{if(typeof o=="string")return o;try{return JSON.stringify(RW(o))}catch{return String(o)}}).join("|");return`${n}:${i}`}function vSe(t,e,r){if(!pSe(t)||$s.dedupeWindowMs<=0)return!1;const n=mSe(t,e,r),i=Date.now(),o=$I.get(n);return $I.set(n,i),o===void 0?!1:i-o<$s.dedupeWindowMs}function ySe(t,e){const r=e||$s.namespace;return $s.format==="compact"?`[${r}] ${t.toUpperCase()}`:$s.format==="verbose"?`[${PW()}] [${r}] [${t.toUpperCase()}]`:""}function Bu(t,e,r){if(!gSe(t)||vSe(t,e,r))return;if($s.format==="json"){jI(t)({ts:PW(),namespace:(r==null?void 0:r.namespace)||$s.namespace,level:t,message:e.map(RW)});return}const n=ySe(t,r==null?void 0:r.namespace);jI(t)(n,...e)}function w8(t){return $s={...$s,...t},m5()}function m5(){return{...$s}}function Wp(t){return t==="compact"||t==="verbose"||t==="json"?t:y8.format}function v5(t){return t==="debug"||t==="info"||t==="warn"||t==="error"||t==="silent"?t:y8.minLevel}function a_(t){if(typeof t=="boolean")return t?"debug":"warn";if(typeof t=="string"){const e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"?"debug":"warn"}return typeof t=="number"&&t!==0?"debug":"warn"}const LW={debug:(...t)=>Bu("debug",t),info:(...t)=>Bu("info",t),warn:(...t)=>Bu("warn",t),error:(...t)=>Bu("error",t),child:t=>({debug:(...e)=>Bu("debug",e,{namespace:t}),info:(...e)=>Bu("info",e,{namespace:t}),warn:(...e)=>Bu("warn",e,{namespace:t}),error:(...e)=>Bu("error",e,{namespace:t})})};class Gh extends Uf{}j8(Gh,"toolName","NoLabelArrowAnnotate");function HI(t,e){const r=Ct("imagePlaneModule",t);if(!r)return;const{rowCosines:n,columnCosines:i,imagePositionPatient:o,rowPixelSpacing:a,columnPixelSpacing:s}=r;if(!n||!i||!o)return;const c=s||1,l=a||1;return{x:o[0]+n[0]*e.y*l+i[0]*e.x*c,y:o[1]+n[1]*e.y*l+i[1]*e.x*c,z:o[2]+n[2]*e.y*l+i[2]*e.x*c}}const{MouseBindings:jg,KeyboardBindings:KI}=Ck,{IMAGE_RENDERED:Hg}=lt,wSe=[{name:"Soft Tissue",center:40,width:400},{name:"Lung",center:-600,width:1500},{name:"Bone",center:300,width:1500},{name:"Brain",center:40,width:80},{name:"Abdomen",center:60,width:400}],qI=t=>{const e=(t||"").toUpperCase(),r=[{name:"Reset to default",action:"reset"},{name:"Auto level",action:"autolevel"}];return e!=="CT"?r:[...r,...wSe.map(n=>({name:n.name,action:"preset",center:n.center,width:n.width}))]},dd=[{label:"Window/Level",value:Yd.toolName,icon:"🌓"},{label:"Pan",value:Cc.toolName,icon:"✋"},{label:"Zoom",value:ll.toolName,icon:"🔍"},{label:"Stack Scroll",value:_f.toolName,icon:"📚"},{label:"Rotate",value:Vh.toolName,icon:"↺"},{label:"Length",value:Ff.toolName,icon:"📏"},{label:"Probe",value:_u.toolName,icon:"🔎"},{label:"Arrow (No Label)",value:Gh.toolName,icon:"➡️"},{label:"Arrow Annotate",value:Uf.toolName,icon:"✈️"},{label:"Rectangle ROI",value:Su.toolName,icon:"▭"},{label:"Ellipse ROI",value:Jd.toolName,icon:"◯"},{label:"Freehand ROI",value:Vf.toolName,icon:"✏️"},{label:"Freehand Contour Segmentation",value:Il.toolName,icon:"🖊️"},{label:"Sculptor",value:Fh.toolName,icon:"🔧"},{label:"Reference Cursors",value:os.toolName,icon:"⦿"}],xSe=3,CSe=220,XI="dv3d_logging",SSe=[{label:"Compact",value:"compact"},{label:"Verbose",value:"verbose"},{label:"JSON",value:"json"}],_Se=[{label:"Off",value:"silent"},{label:"Error",value:"error"},{label:"Warn",value:"warn"},{label:"Info",value:"info"},{label:"Debug",value:"debug"}],YI="dv3d_grouping",hp=[{id:"dwiBValue",label:"DWI b-value",description:"DiffusionBValue (0018,9087) + known private fallbacks",defaultEnabled:!0},{id:"dwiDirection",label:"DWI direction",description:"Diffusion Gradient Direction (0018,9089)",defaultEnabled:!0},{id:"temporalPosition",label:"Temporal position",description:"Temporal Position Identifier (0020,0100)",defaultEnabled:!0},{id:"triggerTime",label:"Trigger time",description:"Trigger Time (0018,1060)",defaultEnabled:!0},{id:"contentTime",label:"Content/Acquisition time",description:"Content Time (0008,0033) / Acquisition Time (0008,0032)",defaultEnabled:!1},{id:"echoTime",label:"Echo time",description:"Echo Time (0018,0081)",defaultEnabled:!0},{id:"echoNumber",label:"Echo number",description:"Echo Number (0018,0086)",defaultEnabled:!0}];function JI(){return hp.reduce((t,e)=>(t[e.id]=e.defaultEnabled,t),{})}const Nt=LW.child("app");function ZI(t){if(!t)return"🔖";const e=dd.find(r=>r.value===t||r.label===t);return(e==null?void 0:e.icon)||"🔖"}function Qc(t){return t?t.startsWith("wadouri:")?t.replace(/^wadouri:+/,"").replace(/^:+/,""):t:""}function s_(t){return/([?&])frame=\d+/i.test(t)}function QI(t,e){const r=Math.max(1,Math.floor(e));return s_(t)?t.replace(/([?&])frame=\d+/i,`$1frame=${r}`):`${t}&frame=${r}`}function e7(t){const e=t.match(/[?&]frame=(\d+)/i);if(!e)return null;const r=Number(e[1]);return Number.isFinite(r)&&r>0?Math.floor(r):null}function y5(t){return t?t.split(/\\|,/).map(e=>Number(e.trim())).filter(e=>Number.isFinite(e)):[]}function OC(t){if(!t||typeof t!="object")return[];const e=o=>{if(typeof t.string=="function"){const a=t.string(o);if(a!=null&&a!==""){const s=y5(a);if(s.length>0&&Number.isFinite(s[0])&&s[0]>=0)return s[0]}}if(typeof t.double=="function")try{const a=t.double(o);if(Number.isFinite(a)&&a>=0)return a}catch{}if(typeof t.float=="function")try{const a=t.float(o);if(Number.isFinite(a)&&a>=0)return a}catch{}return null},r=e("x00189087");if(r!==null)return[r];const n=e("x0019100c");if(n!==null)return[n];if(typeof t.string=="function"){const o=t.string("x00431039");if(o){const a=y5(o);if(a.length>0&&Number.isFinite(a[0])&&a[0]>=0)return[a[0]]}}const i=e("x20011003");return i!==null?[i]:[]}function Gu(t){return t.startsWith("wadouri:")||t.startsWith("external:")?t:`wadouri:${t}`}function Wu(t){const e=new Set,r=[];for(const n of t)!n||e.has(n)||(e.add(n),r.push(n));return r}function TSe(t){try{const e=t.getContext("2d",{willReadFrequently:!0});if(!e)return!0;const r=t.width||160,n=t.height||160,o=e.getImageData(0,0,r,n).data;let a=255,s=0,c=0,l=0;for(let d=0;d0&&w>12&&(c+=1),a=Math.min(a,w),s=Math.max(s,w),l+=1}if(l===0)return!0;const f=c/l,u=s-a;return f>.015||u>8}catch{return!0}}const t7=[{label:"Left",value:"Primary"},{label:"Middle",value:"Auxiliary"},{label:"Right",value:"Secondary"}],z2=[{label:"Left",value:"Primary",mask:1},{label:"Middle",value:"Auxiliary",mask:4},{label:"Right",value:"Secondary",mask:2},{label:"Left + Right",value:"Primary_and_Secondary",mask:3},{label:"Left + Middle",value:"Primary_and_Auxiliary",mask:5},{label:"Right + Middle",value:"Secondary_and_Auxiliary",mask:6},{label:"Left + Right + Middle",value:"Primary_and_Secondary_and_Auxiliary",mask:7},{label:"Fourth Button",value:"Fourth_Button",mask:8},{label:"Fifth Button",value:"Fifth_Button",mask:16},{label:"Mouse Wheel",value:"Wheel",mask:524288},{label:"Mouse Wheel + Left",value:"Wheel_Primary",mask:524289}];function ESe({container_id:t,imageStacks:e,autoCacheStack:r,annotationJson:n,viewerState:i,initialLoggerConfig:o}){var Mt,Yt,rn,cn,Z,Y,we,We,et,St,pt,dt,$,K,R,U,X,ge,xe,be,Re,Fe,Xe,ht,It,jt,kt,In,_n,rr,ii,hi,Xc,ca,Xf,Ou,vg,yg,F8,U8,B8,G8,W8,z8;const a=at.useRef(null),s=at.useRef(null),c=at.useRef(!1),l="dv3d_mouseToolBindings",f="dv3d_ctrlMouseToolBindings",u=(o==null?void 0:o.minLevel)??((o==null?void 0:o.debug)!==void 0?o.debug?"debug":"warn":void 0)??m5().minLevel,d=Wp((o==null?void 0:o.format)??m5().format),[h,g]=at.useState(u),[p,v]=at.useState(d),[y,m]=at.useState(!0),[w,x]=at.useState(()=>JI()),[C,S]=at.useState(!1),[_,T]=at.useState(!1),[E,b]=at.useState(320),D=`dv3d_stackPanelWidth_${t||"default"}`,I=at.useRef({resizing:!1,startX:0,startWidth:320}),P=240,M=720,L=220,V=40,W=14,A=at.useRef(null),[k,F]=at.useState(null),[H,J]=at.useState(null),[oe,ve]=at.useState(!1),[de,_e]=at.useState(!1),[Le,Be]=at.useState(!1),[Pe,B]=at.useState(null),[O,j]=at.useState(!0),[z,q]=at.useState(null),[Q,re]=at.useState("center"),[Ie,Ve]=at.useState(null),Ye=at.useRef(0),Ue=9,ie="renderingEngine_"+t,se="TOOL_GROUP_"+t,ye=at.useRef(null),le=at.useRef(!1),[Se,nt]=at.useState(!0),[ce,Ot]=at.useState(!1),[bt,Tt]=at.useState([]),[Ae,tt]=at.useState(0),[wt,yt]=at.useState(null),[Dt,qt]=at.useState(!1),[At,$t]=at.useState(null),[Lt,Yn]=at.useState(()=>Array(Ue).fill(null).map(()=>[])),fn=G=>{typeof G=="function"?Yn(ue=>{const Te=G(ue);return Nt.debug("setViewportImageIds (fn):",Te),Te}):(Nt.debug("setViewportImageIds:",G),Yn(G))},[an,Cn]=at.useState(()=>Array(Ue).fill(0)),[kr,sr]=at.useState(()=>Array(Ue).fill(null).map(()=>[])),[Ze,xt]=at.useState(()=>Array(Ue).fill(0)),[tn,Fn]=at.useState(()=>Array(Ue).fill(!1)),[Ei,on]=at.useState(()=>Array(Ue).fill(12)),[Un,Dn]=at.useState(()=>Array(Ue).fill(!1)),vn=at.useRef({}),ti=at.useRef({}),[Hr,xs]=at.useState({}),Fo=at.useRef({}),Ai=at.useRef({}),li=at.useCallback((G,ue)=>{xs(Te=>{const Ce=Te[G];if(Ce&&Ce!==ue&&Ce.startsWith("blob:"))try{URL.revokeObjectURL(Ce)}catch{}const he={...Te,[G]:ue};return Fo.current=he,he})},[]);at.useEffect(()=>{Fo.current=Hr},[Hr]),at.useEffect(()=>()=>{Object.values(Fo.current).forEach(G=>{if(typeof G=="string"&&G.startsWith("blob:"))try{URL.revokeObjectURL(G)}catch{}})},[]),at.useEffect(()=>{try{const G=localStorage.getItem(D);if(G){const ue=Number(G);Number.isNaN(ue)||b(Math.max(P,Math.min(M,Math.round(ue))))}}catch{}},[D]),at.useEffect(()=>{try{localStorage.setItem(D,String(Math.round(E)))}catch{}},[D,E]);function Uo(G){if(!G)return null;try{if(G.tagName&&G.tagName.toLowerCase()==="canvas")return G}catch{}try{const ue=G.querySelector&&G.querySelector("canvas");if(ue)return ue}catch{}try{const ue=G.children||[];for(let Te=0;TeMath.min(pn,Math.max(Gt,Et)),Ge=()=>{ue.style.transform=`translate(${ae}px, ${De}px) scale(${fe})`};let Ke=!0,$e=!0;const rt=Et=>{if(!$e)return;Et.preventDefault();const Gt=ue.getBoundingClientRect(),pn=Et.clientX-Gt.left,pr=Et.clientY-Gt.top,Di=-Et.deltaY,es=1+(Di>0?.1:-.1)*Math.min(4,Math.abs(Di)/100),Ki=Me(fe*es,.1,10);ae=(ae-pn)*(Ki/fe)+pn,De=(De-pr)*(Ki/fe)+pr,fe=Ki,Ge()},ct=Et=>{Et.button===0&&Ke&&(pe=!0,me=Et.clientX,ke=Et.clientY,ue.style.cursor="grabbing",Et.preventDefault())},ut=Et=>{if(!pe)return;const Gt=Et.clientX-me,pn=Et.clientY-ke;ae+=Gt,De+=pn,me=Et.clientX,ke=Et.clientY,Ge()},mt=Et=>{pe&&(pe=!1,ue.style.cursor="grab")},Rt=Et=>{fe=1,ae=0,De=0,Ge()};let Zt=0;const gr=(Et,Gt)=>Math.hypot(Gt.clientX-Et.clientX,Gt.clientY-Et.clientY),ln=Et=>{Et.touches.length===1?Ke&&(pe=!0,me=Et.touches[0].clientX,ke=Et.touches[0].clientY):Et.touches.length===2&&(Zt=gr(Et.touches[0],Et.touches[1]))},Bt=Et=>{if(Et.touches.length===1&&pe){const Gt=Et.touches[0].clientX-me,pn=Et.touches[0].clientY-ke;ae+=Gt,De+=pn,me=Et.touches[0].clientX,ke=Et.touches[0].clientY,Ge()}else if(Et.touches.length===2&&$e){const Gt=gr(Et.touches[0],Et.touches[1]);if(Zt>0){const pn=Gt/Zt,pr=ue.getBoundingClientRect(),Di=(Et.touches[0].clientX+Et.touches[1].clientX)/2-pr.left,es=(Et.touches[0].clientY+Et.touches[1].clientY)/2-pr.top,Ki=Me(fe*pn,.1,10);ae=(ae-Di)*(Ki/fe)+Di,De=(De-es)*(Ki/fe)+es,fe=Ki,Ge()}Zt=Gt}Et.preventDefault()},Qt=Et=>{Et.touches.length===0&&(pe=!1,Zt=0)};return G.addEventListener("wheel",rt,{passive:!1}),G.addEventListener("mousedown",ct),window.addEventListener("mousemove",ut),window.addEventListener("mouseup",mt),ue.addEventListener("dblclick",Rt),G.addEventListener("touchstart",ln,{passive:!1}),G.addEventListener("touchmove",Bt,{passive:!1}),G.addEventListener("touchend",Qt),{cleanup:()=>{G.removeEventListener("wheel",rt),G.removeEventListener("mousedown",ct),window.removeEventListener("mousemove",ut),window.removeEventListener("mouseup",mt),ue.removeEventListener("dblclick",Rt),G.removeEventListener("touchstart",ln),G.removeEventListener("touchmove",Bt),G.removeEventListener("touchend",Qt),ue.style.transform="",ue.style.cursor="",ue.style.willChange=""},setAllowPan:Et=>{Ke=Et},setAllowZoom:Et=>{$e=Et}}}const[kn,ni]=at.useState(!1),[ja,Sr]=at.useState(null),[oa,no]=at.useState(!1),[zi,qs]=at.useState(null);at.useEffect(()=>{const G=Te=>{try{const Ce=Te&&Te.message?String(Te.message):"";(Ce.includes("releaseGraphicsResources")||Ce.includes("openGLTexture")||Ce.includes("getDefaultActor")||Ce.includes("setColormapGPU")||Ce.includes(`can't access property "actor"`)||Ce.toLowerCase().includes("webgl")||Ce.toLowerCase().includes("colormap"))&&(Nt.error("Detected graphics/rendering error:",Te),qs(Ce||null),no(!0))}catch{}},ue=Te=>{try{const Ce=Te&&Te.reason||"",he=typeof Ce=="string"?Ce:Ce&&Ce.message?Ce.message:String(Ce);(he.includes("releaseGraphicsResources")||he.includes("openGLTexture")||he.includes("getDefaultActor")||he.includes("setColormapGPU")||he.includes(`can't access property "actor"`)||he.toLowerCase().includes("webgl")||he.toLowerCase().includes("colormap"))&&(Nt.error("Detected graphics/rendering rejection:",Te),qs(he||null),no(!0))}catch{}};return window.addEventListener("error",G),window.addEventListener("unhandledrejection",ue),()=>{window.removeEventListener("error",G),window.removeEventListener("unhandledrejection",ue)}},[]),at.useEffect(()=>{let G=!1;if(n||i){Sr(n?"annotations":"viewerState");const ue=setTimeout(()=>{if(G)return;const Te=t||"default";if(n)try{const Ce=window[`importAnnotations_${Te}`]||window.importAnnotations;typeof Ce=="function"&&Ce(n)}catch(Ce){Nt.error("Failed to import annotations from prop:",Ce)}if(i)try{const Ce=window[`importViewerState_${Te}`]||window.importViewerState;typeof Ce=="function"&&Ce(i)}catch(Ce){Nt.error("Failed to import viewer state from prop:",Ce)}Sr(null)},2e3);return()=>{G=!0,clearTimeout(ue),Sr(null)}}},[n,i,t]),at.useEffect(()=>{let G=!0;return e().then(async ue=>{var he;if(!G)return;const Te=Array.isArray(ue)?ue:[],Ce=[];for(const fe of Te){const ae=Array.isArray(fe),De=ae?fe:Array.isArray(fe.imageIds)?fe.imageIds:Array.isArray(fe.i)?fe.i:[],pe=ae?{}:{studyId:fe.studyId,name:fe.name,caseId:fe.caseId,studyInstanceUID:fe.studyInstanceUID};if(!ae&&Array.isArray(fe.series)){const ke=fe.series.map((Me,Ge)=>{const Ke=Array.isArray(Me==null?void 0:Me.imageIds)?Me.imageIds:Array.isArray(Me==null?void 0:Me.i)?Me.i:[],$e=Wu(Ke.map(Gu)),ct=(typeof(Me==null?void 0:Me.name)=="string"?Me.name:"").trim()||`Series ${Ge+1}`;return{key:String((Me==null?void 0:Me.seriesInstanceUID)||(Me==null?void 0:Me.seriesId)||`SERIES_${Ge}`),label:ct,imageIds:$e,seriesInstanceUID:Me==null?void 0:Me.seriesInstanceUID,bValue:Number.isFinite(Number(Me==null?void 0:Me.bValue))?Number(Me.bValue):null}}).filter(Me=>Me.imageIds.length>0);if(ke.length>0){Ce.push({imageIds:Wu(ke.flatMap(Me=>Me.imageIds)),seriesGroups:ke,...pe});continue}}const me=Wu(De.map(Gu));me.length>0&&Ce.push({imageIds:me,seriesGroups:[],...pe})}if(Tt(Ce),Ce[0]){const fe=Ce[0];let ae=fe.seriesGroups||[],De=fe.imageIds;ae.length===0&&(De=await vo(fe.imageIds),await Bn(De,{force:!!r}),ae=await ui(De),Ce[0]={...fe,imageIds:De,seriesGroups:ae},Tt([...Ce]));const pe=((he=ae[0])==null?void 0:he.imageIds)||De;await Bn(pe),fn(Array(Ue).fill(null).map((me,ke)=>ke===0?pe||[]:[])),sr(Array(Ue).fill(null).map(()=>ae)),xt(Array(Ue).fill(0))}else fn(Array(Ue).fill(null).map(()=>[])),sr(Array(Ue).fill(null).map(()=>[])),xt(Array(Ue).fill(0))}).catch(ue=>{Nt.error("Failed to load imageStacks:",ue),Tt([]),fn(Array(Ue).fill(null).map(()=>[]))}),()=>{G=!1}},[]);const bo=async(G,ue)=>{var ae,De,pe,me;const Te=bt[ue];if(!Te)return;const Ce=await vo(Te.imageIds||[]);Nt.debug("[handleLoadStack] Loading stack:",Ce.length,"ids. First:",(ae=Ce[0])==null?void 0:ae.slice(0,80)),await Bn(Ce,{force:!!r});const he=await ui(Ce);Nt.debug("[handleLoadStack] Derived series groups:",he.length,"groups. First group has",(De=he[0])==null?void 0:De.imageIds.length,"images"),Tt(ke=>{const Me=[...ke];return Me[ue]?(Me[ue]={...Me[ue],seriesGroups:he,imageIds:Ce},Me):ke});const fe=((pe=he[0])==null?void 0:pe.imageIds)||Ce;Nt.debug("[handleLoadStack] Setting viewport to primarySeries with",fe.length,"ids. First:",(me=fe[0])==null?void 0:me.slice(0,80)),Sr("displayset");try{yr(ke=>{const Me=[...ke];return Me[G]="stack",Me}),fn(ke=>{const Me=[...ke];return Me[G]=fe,Me}),Cn(ke=>{const Me=[...ke];return Me[G]=ue,Me}),sr(ke=>{const Me=[...ke];return Me[G]=he||[],Me}),xt(ke=>{const Me=[...ke];return Me[G]=0,Me}),await Bn(fe)}finally{Sr(null)}},[$i,Fc]=at.useState(!1),[Ni,Cs]=at.useState(!0),[Sa,Do]=at.useState(!1),[Ss,Ha]=at.useState(!1),Io=()=>{Nt.debug("Sorting viewport imageIds by slice location"),fn(G=>{const ue=G.map((Te,Ce)=>{if(!Te||Te.length===0)return Te;const ae=[...Te.map(De=>{const pe=Ct("imagePlaneModule",De);let me=null;return pe&&(pe.sliceLocation!==void 0?me=Number(pe.sliceLocation):pe.imagePositionPatient&&Array.isArray(pe.imagePositionPatient)&&pe.imagePositionPatient.length===3&&(me=Number(pe.imagePositionPatient[2]))),{imageId:De,sortKey:me}})].sort((De,pe)=>De.sortKey!==null&&pe.sortKey!==null?De.sortKey-pe.sortKey:De.imageId.localeCompare(pe.imageId)).map(De=>De.imageId);return JSON.stringify(ae)===JSON.stringify(Te)?Te:ae});return ni(!0),ue})},_a=at.useCallback(async(G,ue,Te=0)=>{if(!ue||Hr[G]||Ai.current[G])return;if(Vr(ue)){try{const ae=new Image;ae.crossOrigin="anonymous";const De=ue.replace(/^external:/,"");ae.src=De,await new Promise((Me,Ge)=>{ae.onload=()=>Me(!0),ae.onerror=Ke=>Ge(Ke)});const pe=document.createElement("canvas"),me=160;pe.width=me,pe.height=me;const ke=pe.getContext("2d");if(ke){const Me=Math.min(me/ae.width,me/ae.height),Ge=ae.width*Me,Ke=ae.height*Me,$e=(me-Ge)/2,rt=(me-Ke)/2;ke.fillStyle="#000",ke.fillRect(0,0,me,me),ke.drawImage(ae,$e,rt,Ge,Ke),li(G,pe.toDataURL("image/png"))}else li(G,"BROKEN")}catch{li(G,"BROKEN")}return}const Ce=ye.current;if(!Ce)return;Ai.current[G]=!0;const he=`THUMB_${t||"main"}_${G}`,fe=document.createElement("div");fe.style.width="160px",fe.style.height="160px",fe.style.position="absolute",fe.style.left="-9999px",fe.style.top="0",document.body.appendChild(fe);try{Ce.enableElement({viewportId:he,type:Mr.STACK,element:fe});const ae=Ce.getViewport(he);if(!ae)return;try{ae.setStack([ue])}catch{}await new Promise(pe=>{let me=!1;const ke=setTimeout(()=>{me||(me=!0,pe(!1))},2e3),Me=()=>{me||(me=!0,clearTimeout(ke),pe(!0))};try{if(ae&&ae.element&&ae.element.addEventListener(Hg,Me,{once:!0}),typeof ae.render=="function")try{const Ge=ae.render();Ge&&typeof Ge.then=="function"&&Ge.catch(()=>{})}catch{}}catch{clearTimeout(ke),pe(!1)}});let De=Uo(fe)||(ae&&ae.element?Uo(ae.element):null);if(De||(await new Promise(pe=>setTimeout(pe,150)),De=Uo(fe)||(ae&&ae.element?Uo(ae.element):null)),De){if(!TSe(De)&&Te{_a(G,ue,Te+1)},me);return}try{if(typeof De.toBlob=="function"){const me=await new Promise(ke=>{De.toBlob(Me=>{if(!Me){ke(null);return}ke(URL.createObjectURL(Me))},"image/png")});me?li(G,me):li(G,De.toDataURL("image/png"))}else li(G,De.toDataURL("image/png"))}catch{li(G,"BROKEN")}}else li(G,"BROKEN")}catch{try{li(G,"BROKEN")}catch{}}finally{try{Ce.disableElement(he)}catch{}fe&&fe.parentNode&&fe.parentNode.removeChild(fe)}},[t,Hr,li]);at.useEffect(()=>{!_||!bt||bt.length===0||!ye.current||bt.slice(0,12).forEach((ue,Te)=>{const Ce=Array.isArray(ue.imageIds)?ue.imageIds:[],he=Math.floor(Ce.length/2),fe=Ce[he]||Ce[0]||null;!Hr[Te]&&!Ai.current[Te]&&_a(Te,fe)})},[bt,_a,_,Hr]);const Bn=async(G,ue)=>{Nt.debug("Setting loaded imageIds:",G),Nt.debug("autoCacheStack:",r);const Te=[];if(!!(r||ue!=null&&ue.force)){const he=new Set;for(const fe of G)if(fe.startsWith("wadouri:"))try{const ae=Qc(fe).replace(/[?&]frame=\d+/gi,"");ae&&he.add(ae)}catch(ae){Nt.warn(`Failed to cache metadata for ${fe}:`,ae)}for(const fe of he)if(Uu.wadouri.dataSetCacheManager){const ae=Uu.wadouri.dataSetCacheManager.load(fe);ae&&typeof ae.then=="function"&&Te.push(ae)}else Nt.warn("MetaDataManager not found. Unable to cache metadata.");await Promise.all(Te),qr&&(Nt.debug("Sorting viewport imageIds by slice location"),Io())}},mo=at.useCallback(async G=>{var De;if(!G.startsWith("wadouri:")||s_(G))return 1;const ue=Gu(G),Te=Qc(ue),Ce=`wadouri:${Te}`,he=vn.current[Ce];if(he!==void 0)return he;const fe=pe=>{if(!pe||typeof pe.intString!="function")return 1;const me=Number(pe.intString("x00280008"));return Number.isFinite(me)&&me>1?Math.floor(me):1},ae=pe=>{try{const me=Lr.parseDicom(pe);return fe(me)}catch(me){if(me!=null&&me.dataSet){const ke=fe(me.dataSet);if(ke>1)return ke}return 1}};try{const pe=Ct("multiframeModule",ue),me=Number(pe==null?void 0:pe.numberOfFrames);if(Number.isFinite(me)&&me>1)return vn.current[Ce]=Math.floor(me),Math.floor(me)}catch{}try{const pe=(De=Uu==null?void 0:Uu.wadouri)==null?void 0:De.dataSetCacheManager;if(pe!=null&&pe.get){const me=pe.get(Te);if(me){const ke=fe(me);return vn.current[Ce]=ke,ke}}}catch{}try{const pe=await fetch(Te,{headers:{Range:"bytes=0-262143"}});if(pe.ok||pe.status===206){const me=await pe.arrayBuffer(),ke=ae(new Uint8Array(me));return vn.current[Ce]=ke,ke}}catch{}return vn.current[Ce]=1,1},[]),Ka=at.useCallback(async G=>{var Ce;const ue=[],Te=[];for(const he of G||[]){const fe=Gu(he);if(!fe.startsWith("wadouri:")||s_(fe)){ue.push(fe);continue}const ae=await mo(fe);if(ae<=1)ue.push(fe);else{const De=Array.from({length:ae},(pe,me)=>QI(fe,me+1));Te.push({baseImageId:fe,frameIds:De}),Nt.debug("[splitMultiframeToStacks]",((Ce=Qc(fe).split("/").pop())==null?void 0:Ce.split("?")[0])??fe,"->",ae,"frames (separate stack)")}}return{singleFrameIds:Wu(ue),multiframeGroups:Te}},[mo]),vo=at.useCallback(async G=>{Nt.debug("[expandMultiframeImageIds] Input:",G.length,"imageIds");const{singleFrameIds:ue,multiframeGroups:Te}=await Ka(G),Ce=Wu([...ue,...Te.flatMap(he=>he.frameIds)]);return Nt.debug("[expandMultiframeImageIds] Output:",Ce.length,"total imageIds"),Ce},[Ka]),_s=at.useCallback(async G=>{var fe;if(!G.startsWith("wadouri:"))return[];const ue=Gu(G),Te=Qc(ue).replace(/[?&]frame=\d+/i,""),Ce=ti.current[Te];if(Ce)return Ce;try{const ae=(fe=Uu==null?void 0:Uu.wadouri)==null?void 0:fe.dataSetCacheManager;if(ae!=null&&ae.get){const De=ae.get(Te),pe=OC(De);if(pe.length>0)return ti.current[Te]=pe,pe}}catch{}const he=ae=>{try{return OC(Lr.parseDicom(ae))}catch(De){if(De!=null&&De.dataSet){const pe=OC(De.dataSet);if(pe.length>0)return pe}return[]}};try{const ae=await fetch(Te,{headers:{Range:"bytes=0-65535"}});if(ae.ok||ae.status===206){const De=await ae.arrayBuffer(),pe=he(new Uint8Array(De));if(pe.length>0||ae.status===200)return ti.current[Te]=pe,pe}}catch{}try{const De=await(await fetch(Te)).arrayBuffer(),pe=he(new Uint8Array(De));return ti.current[Te]=pe,pe}catch{return ti.current[Te]=[],[]}},[]),ui=at.useCallback(async G=>{if(!Array.isArray(G)||G.length===0)return[];const ue=Ge=>!Array.isArray(Ge)||Ge.length===0?"":Ge.map(Ke=>{const $e=Number(Ke);return Number.isFinite($e)?$e.toFixed(3):"0.000"}).join(","),Te=Ge=>{if(Array.isArray(Ge)&&Ge.length>0){const Ke=Ge.map($e=>Number($e)).filter($e=>Number.isFinite($e));if(Ke.length>=3)return ue(Ke.slice(0,3))}if(typeof Ge=="string"){const Ke=y5(Ge);if(Ke.length>=3)return ue(Ke.slice(0,3));const $e=Ge.trim();if($e)return $e}if(Ge&&typeof Ge=="object"){const Ke=[Ge.x,Ge.y,Ge.z].map($e=>Number($e)).filter($e=>Number.isFinite($e));if(Ke.length>=3)return ue(Ke.slice(0,3))}return""},Ce=Ge=>{if(Ge==null)return"";const Ke=String(Ge).trim();if(!Ke)return"";const $e=Number(Ke);return Number.isFinite($e)?$e.toFixed(1):Ke},he=Ge=>{const Ke=Ct("imagePlaneModule",Ge)||{},$e=Ct("generalImageModule",Ge)||{},rt=Array.isArray(Ke==null?void 0:Ke.rowCosines)?Ke.rowCosines:null,ct=Array.isArray(Ke==null?void 0:Ke.columnCosines)?Ke.columnCosines:null,ut=rt&&ct?`${ue(rt)}|${ue(ct)}`:"";if(ut)return ut;const mt=$e==null?void 0:$e.imageOrientationPatient;if(Array.isArray(mt)&&mt.length>=6)return`${ue(mt.slice(0,3))}|${ue(mt.slice(3,6))}`;if(typeof mt=="string"){const Rt=y5(mt);if(Rt.length>=6)return`${ue(Rt.slice(0,3))}|${ue(Rt.slice(3,6))}`}return"ORI_UNKNOWN"},fe=new Map;G.forEach(Ge=>{const Ke=Qc(Gu(Ge)).replace(/[?&]frame=\d+/i,""),$e=fe.get(Ke)||[];$e.push(Ge),fe.set(Ke,$e)}),fe.forEach((Ge,Ke)=>{Ge.sort(($e,rt)=>{const ct=e7($e)||1,ut=e7(rt)||1;return ct-ut}),fe.set(Ke,Ge)});const ae=new Map;await Promise.all(Array.from(fe.keys()).map(async Ge=>{const Ke=`wadouri:${Ge}`,$e=await _s(Ke);ae.set(Ge,$e)}));const De=Ge=>{const Ke=Ct("imagePlaneModule",Ge)||{},$e=Array.isArray(Ke==null?void 0:Ke.imagePositionPatient)?Ke.imagePositionPatient:null;if($e&&$e.length>=3){const ct=$e.slice(0,3).map(ut=>Number(ut));if(ct.every(ut=>Number.isFinite(ut)))return`IPP:${ct.map(ut=>ut.toFixed(3)).join(",")}`}const rt=Number(Ke==null?void 0:Ke.sliceLocation);return Number.isFinite(rt)?`SL:${rt.toFixed(3)}`:""},pe=G.map(Ge=>{const Ke=Ct("generalSeriesModule",Ge)||{},$e=Ct("generalImageModule",Ge)||{},rt=Ct("mrImageModule",Ge)||{},ct=(Ke.seriesInstanceUID||"").trim()||void 0,ut=(Ke.seriesDescription||"").trim()||void 0,mt=Number(Ke.seriesNumber),Rt=Number($e.instanceNumber),Zt=he(Ge),gr=De(Ge);let ln=Number(rt.diffusionBValue??rt.diffusionbValue??rt.bValue),Bt=Number.isFinite(ln)?ln:null;if(Bt===null){const es=Qc(Gu(Ge)).replace(/[?&]frame=\d+/i,""),Ki=ae.get(es)||[];if(Ki.length>0){const $8=fe.get(es)||[Ge],qw=Math.max(0,$8.indexOf(Ge)),A1=Math.max(1,$8.length);if(Ki.length===1)Bt=Ki[0];else if(Ki.length===A1)Bt=Ki[Math.min(Ki.length-1,qw)];else if(Ki.length===2&&A1%2===0)Bt=qww[Ge.id]).map(Ge=>Ge.id).filter(Ge=>{const Ke=pe.map(ct=>ct.ruleValues[Ge]).filter(ct=>!!ct),$e=new Set(Ke),rt=Ke.length/pe.length;return $e.size>1&&$e.size=.7}):[],ke=new Map;if(pe.forEach(Ge=>{const Ke=[Ge.seriesInstanceUID||"NO_UID",Ge.orientationKey].join("|"),$e=me.map(ct=>{const ut=Ge.ruleValues[ct];return ut?`${ct}:${ut}`:""}).filter(Boolean).join("|"),rt=$e?`${Ke}|${$e}`:Ke;if(!ke.has(rt)){const ct={};me.forEach(ut=>{const mt=Ge.ruleValues[ut];mt&&(ct[ut]=mt)}),ke.set(rt,{imageIds:[],seriesInstanceUID:Ge.seriesInstanceUID,seriesDescription:Ge.seriesDescription,seriesNumber:Ge.seriesNumber,bValue:Ge.bValue,groupValues:ct})}ke.get(rt).imageIds.push(Ge.id)}),ke.size<=1){if(me.length===0&&pe.length>=4){const Ge=new Map;pe.forEach($e=>{$e.sliceKey&&Ge.set($e.sliceKey,(Ge.get($e.sliceKey)||0)+1)});const Ke=Ge.size;if(Ke>=2&&Ke=2&&rt<=8&&Array.from(Ge.values()).every(mt=>mt===rt)){const mt=Array.from({length:rt},()=>[]),Rt=new Map;[...pe].map((ln,Bt)=>({c:ln,idx:Bt})).sort((ln,Bt)=>{const Qt=ln.c.instanceNumber,lr=Bt.c.instanceNumber;return Number.isFinite(Qt)&&Number.isFinite(lr)?Qt-lr:ln.idx-Bt.idx}).forEach(({c:ln})=>{if(!ln.sliceKey)return;const Bt=Rt.get(ln.sliceKey)||0,Qt=Math.min(rt-1,Bt);mt[Qt].push(ln.id),Rt.set(ln.sliceKey,Bt+1)});const gr=mt.filter(ln=>ln.length>0);if(gr.length>1)return gr.map((ln,Bt)=>({key:`SERIES_FALLBACK_${Bt}`,label:`Series ${Bt+1}`,imageIds:Wu(ln)}))}}}return[{key:"SERIES_0",label:"Series 1",imageIds:Wu(G)}]}return Array.from(ke.entries()).map(([Ge,Ke],$e)=>{const rt=[];Ke.seriesDescription&&rt.push(Ke.seriesDescription),Ke.seriesNumber!==void 0&&rt.push(`#${Ke.seriesNumber}`),Ke.groupValues&&hp.forEach(ut=>{var Rt;const mt=(Rt=Ke.groupValues)==null?void 0:Rt[ut.id];mt&&(ut.id==="dwiBValue"?rt.push(`b=${mt}`):ut.id==="dwiDirection"?rt.push(`dir=${mt}`):ut.id==="temporalPosition"?rt.push(`tp=${mt}`):ut.id==="triggerTime"?rt.push(`tr=${mt}`):ut.id==="contentTime"?rt.push(`t=${mt}`):ut.id==="echoTime"?rt.push(`TE=${mt}`):ut.id==="echoNumber"&&rt.push(`echo=${mt}`))}),rt.length===0&&Ke.bValue!==null&&Ke.bValue!==void 0&&rt.push(`b=${Math.round(Ke.bValue)}`);const ct=rt.length>0?rt.join(" • "):`Series ${$e+1}`;return{key:Ge,label:ct,imageIds:Wu(Ke.imageIds),seriesInstanceUID:Ke.seriesInstanceUID,bValue:Ke.bValue,groupValues:Ke.groupValues}})},[y,_s,w]),[Xt,Ta]=at.useState({rows:1,cols:1}),[Ea,qa]=at.useState(!1),Kr=at.useRef([]),yo=at.useRef({}),ji=at.useRef({}),[qr,Xs]=at.useState(!1),[Oo,Xa]=at.useState(!0),Ir=at.useCallback(G=>{const ue=G.currentTarget.getBoundingClientRect(),Te=G.clientX-ue.left,Ce=G.clientY-ue.top,he=ue.width,fe=ue.height,ae=Math.min(he,fe)*.24,De=[{zone:"left",distance:Te},{zone:"right",distance:he-Te},{zone:"top",distance:Ce},{zone:"bottom",distance:fe-Ce}];return De.sort((pe,me)=>pe.distance-me.distance),De[0].distance<=ae?De[0].zone:"center"},[]),Ys=at.useCallback((G,ue,Te)=>{const Ce=ue-G.left,he=Te-G.top,fe=G.width,ae=G.height,De=Math.min(fe,ae)*.24,pe=[{zone:"left",distance:Ce},{zone:"right",distance:fe-Ce},{zone:"top",distance:he},{zone:"bottom",distance:ae-he}];return pe.sort((me,ke)=>me.distance-ke.distance),pe[0].distance<=De?pe[0].zone:"center"},[]),ri=at.useCallback(G=>G==="left"||G==="right"?Xt.cols<3?G:"center":(G==="top"||G==="bottom")&&Xt.rows<3?G:"center",[Xt]),fi=[];for(let G=1;G<=3;G++)for(let ue=1;ue<=3;ue++)fi.push({rows:G,cols:ue});const[gn,aa]=at.useState(()=>Array(Xt.rows*Xt.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:"",modality:"",orientation:"",resolution:"",spacing:"",focalPoint:""})),[ro,Ya]=at.useState({}),Js=at.useRef(Array(Ue).fill("")),Go=at.useRef(Array(Ue).fill(null)),Ja=at.useRef(Array(Ue).fill(null)),vr=at.useRef(Array(Ue).fill(null)),ba=at.useRef(Array(Ue).fill(0)),[sn,yr]=at.useState(()=>Array(Ue).fill("stack")),[Da,ki]=at.useState(()=>Array(Xt.rows*Xt.cols).fill(!1)),[Vi,di]=at.useState({Primary:_f.toolName,Auxiliary:Cc.toolName,Secondary:Yd.toolName,Primary_and_Secondary:ll.toolName,Fourth_Button:Vh.toolName,Wheel:_f.toolName}),[bi,Za]=at.useState({Primary:Ff.toolName,Auxiliary:_u.toolName,Secondary:Gh.toolName}),[Qa,Hi]=at.useState(!1);at.useEffect(()=>{const G=Te=>{Te.ctrlKey&&Hi(!0)},ue=Te=>{Te.ctrlKey||Hi(!1)};return window.addEventListener("keydown",G),window.addEventListener("keyup",ue),()=>{window.removeEventListener("keydown",G),window.removeEventListener("keyup",ue)}},[]),at.useEffect(()=>{const G=window.matchMedia("(max-width: 768px), (pointer: coarse)"),ue=()=>{const Te=G.matches;_e(Te),Te||(Be(!1),B(null))};return ue(),typeof G.addEventListener=="function"?(G.addEventListener("change",ue),()=>G.removeEventListener("change",ue)):(G.addListener(ue),()=>G.removeListener(ue))},[]);const Uc=at.useCallback(G=>{if(!de)return;tt(G),B(G),Be(!0),j(!0),T(!1);const ue=a.current;if(ue&&document.fullscreenElement!==ue){const Te=ue.requestFullscreen||ue.webkitRequestFullscreen||ue.msRequestFullscreen;if(Te)try{const Ce=Te.call(ue);Ce&&typeof Ce.catch=="function"&&Ce.catch(()=>{})}catch{}}},[de]);at.useEffect(()=>{!de||!Le||!O||Ae!==null&&B(Ae)},[Ae,de,Le,O]);const[Al,Ts]=at.useState(!1),[Bc,Ia]=at.useState(null),Es=(G,ue)=>{pa&&pa(ue),He(Te=>{const Ce=[...Te];return Ce[G]=ue,Ce})},Zs=(G,ue,Te)=>{const Ce=Or.getAllAnnotations()||[];Ce.forEach(fe=>{fe.annotationUID===ue&&(fe.isSelected=!1)}),Or.removeAnnotation(ue),ye.current.render();const he=Te.filter(fe=>fe.annotationUID!==ue);He(fe=>{const ae=[...fe],De=he.length>0?he[0].annotationUID:null;return ae[G]=De,Ce.forEach(pe=>{pe.isSelected=pe.annotationUID===De}),pa(De),ye.current.render(),ae})},Nl=()=>{const G=Lt.findIndex(he=>he&&he.length>0);if(G===-1){Ia("No images loaded."),Ts(!0);return}const ue=Lt[G][0],Te=["imagePlaneModule","generalSeriesModule","generalStudyModule","patientModule","imagePixelModule","voiLutModule","modalityLutModule","sopCommonModule","petIsotopeModule","multiframeModule","cineModule","overlayPlaneModule","generalImageModule","stackModule","voiLutModule","modalityLutModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule"],Ce={};Te.forEach(he=>{const fe=Ct(he,ue);fe!==void 0&&(Ce[he]=fe)}),Ia(Ne.jsx("pre",{style:{maxHeight:600,overflow:"auto",fontSize:13,color:"#fff"},children:JSON.stringify(Ce,null,2)})),Ts(!0)};at.useEffect(()=>{try{const G=localStorage.getItem(l),ue=localStorage.getItem(f);G&&di(JSON.parse(G)),ue&&Za(JSON.parse(ue));const Te=localStorage.getItem(XI);if(Te){const he=JSON.parse(Te);typeof(he==null?void 0:he.minLevel)=="string"?g(v5(he.minLevel)):typeof(he==null?void 0:he.debug)=="boolean"&&g(he.debug?"debug":"warn"),typeof(he==null?void 0:he.format)=="string"&&v(Wp(he.format))}const Ce=localStorage.getItem(YI);if(Ce){const he=JSON.parse(Ce);if(typeof(he==null?void 0:he.advancedGroupingEnabled)=="boolean"&&m(he.advancedGroupingEnabled),he!=null&&he.groupingRuleEnabled&&typeof he.groupingRuleEnabled=="object"){const fe=JI();hp.forEach(ae=>{typeof he.groupingRuleEnabled[ae.id]=="boolean"&&(fe[ae.id]=he.groupingRuleEnabled[ae.id])}),x(fe)}}}catch{}},[]),at.useEffect(()=>{try{localStorage.setItem(l,JSON.stringify(Vi))}catch{}},[Vi]),at.useEffect(()=>{try{localStorage.setItem(f,JSON.stringify(bi))}catch{}},[bi]),at.useEffect(()=>{w8({minLevel:h,format:p});try{localStorage.setItem(XI,JSON.stringify({minLevel:h,format:p}))}catch{}},[h,p]),at.useEffect(()=>{try{localStorage.setItem(YI,JSON.stringify({advancedGroupingEnabled:y,groupingRuleEnabled:w}))}catch{}},[y,w]),at.useEffect(()=>{if(bt.length===0)return;let G=!1;return(async()=>{const Te=await Promise.all(bt.map(async Ce=>{const he=await ui(Ce.imageIds);return{...Ce,seriesGroups:he}}));G||(Tt(Te),sr(Ce=>{var fe;const he=[...Ce];for(let ae=0;ae{var fe;const he=[...Ce];for(let ae=0;ae{var fe,ae,De;const he=[...Ce];for(let pe=0;pe{G=!0}},[y,w]),at.useEffect(()=>(window.loadDicomStackFromFiles=G=>{const ue=Array.from(G);Ds({target:{files:ue}})},()=>{window.loadDicomStackFromFiles=void 0}),[]),at.useEffect(()=>{const G=()=>{qt(!1),$t(null),yt(null)};return document.addEventListener("dragend",G),()=>document.removeEventListener("dragend",G)},[]);const[Gc,Qs]=at.useState(!1),[Wc,ec]=at.useState(!1);at.useEffect(()=>{const G=wi(se);G&&["ArrowAnnotate","NoLabelArrowAnnotate","Length","RectangleROI","EllipticalROI","PlanarFreehandROI","PlanarFreehandContourSegmentation"].forEach(ue=>{G.setToolConfiguration(ue,{color:"#00e676",selectedColor:"#ffeb3b"})})},[se]),at.useEffect(()=>{const G=Ce=>{Ce.altKey&&Qs(!0),Ce.shiftKey&&ec(!0)},ue=Ce=>{Ce.altKey||Qs(!1),Ce.shiftKey||ec(!1)},Te=()=>{Qs(!1),ec(!1)};return window.addEventListener("keydown",G),window.addEventListener("keyup",ue),window.addEventListener("blur",Te),()=>{window.removeEventListener("keydown",G),window.removeEventListener("keyup",ue),window.removeEventListener("blur",Te)}},[]),at.useEffect(()=>{const G=wi(se);if(!G)return;if(Wc||Oo&&Gc){const Te=Xt.rows*Xt.cols;Lt.slice(0,Te).filter((he,fe)=>sn[fe]==="stack"&&Array.isArray(he)&&he.length>0).forEach(he=>{Bn(he,{force:!0}).catch(fe=>{Nt.warn("Reference cursor metadata warm-up failed:",fe)})}),G.hasTool(os.toolName)||G.addTool(os.toolName),G.setToolEnabled(os.toolName),G.setToolActive(os.toolName)}else G.hasTool(os.toolName)&&G.setToolDisabled(os.toolName)},[Gc,Wc,Oo,Xt.rows,Xt.cols,Lt,sn,Bn]);const tc=at.useCallback(()=>{[wi(se)].forEach(ue=>{if(ue){dd.forEach(fe=>{ue.setToolPassive(fe.value,{removeAllBindings:!0})}),ue.setToolDisabled(os.toolName);const Te={};Object.entries(Vi).forEach(([fe,ae])=>{Te[ae]||(Te[ae]=[]);const De=z2.find(pe=>pe.value===fe);De?Te[ae].push({mouseButton:De.mask}):jg[fe]&&Te[ae].push({mouseButton:jg[fe]})}),Object.entries(bi).forEach(([fe,ae])=>{if(!ae)return;Te[ae]||(Te[ae]=[]);const De=z2.find(pe=>pe.value===fe);De?Te[ae].push({mouseButton:De.mask,modifierKey:KI.Ctrl}):jg[fe]&&Te[ae].push({mouseButton:jg[fe],modifierKey:KI.Ctrl})}),Object.entries(Te).forEach(([fe,ae])=>{ue.setToolActive(fe,{bindings:ae})});const Ce=Vi.Primary;if(Ce){const fe=[...Te[Ce]||[],{numTouchPoints:1}];ue.setToolActive(Ce,{bindings:fe})}const he=[...Te[Cc.toolName]||[],{numTouchPoints:2}];ue.setToolActive(Cc.toolName,{bindings:he});try{const fe=Vi.Primary,ae=Vi.Wheel,De=Vi.Auxiliary,pe=fe===Cc.toolName||De===Cc.toolName,me=fe===ll.toolName||ae===ll.toolName||Vi.Primary_and_Secondary===ll.toolName;Kr.current.forEach(ke=>{if(!ke)return;const Me=ke._externalPanZoom;Me&&(typeof Me.setAllowPan=="function"&&Me.setAllowPan(!!pe),typeof Me.setAllowZoom=="function"&&Me.setAllowZoom(!!me))})}catch{}}})},[Vi,bi]),[zc,bs]=at.useState(!1),[nc,rc]=at.useState("add"),sa=at.useRef(null),kl=at.useCallback(G=>{_&&(G.preventDefault(),G.stopPropagation(),I.current={resizing:!0,startX:G.clientX,startWidth:E},document.body.style.cursor="col-resize",document.body.style.userSelect="none")},[_,E]);at.useEffect(()=>{const G=Te=>{if(!I.current.resizing)return;const Ce=I.current.startX-Te.clientX,he=Math.max(P,Math.min(M,I.current.startWidth+Ce));b(he)},ue=()=>{I.current.resizing&&(I.current.resizing=!1,document.body.style.cursor="",document.body.style.userSelect="")};return window.addEventListener("mousemove",G),window.addEventListener("mouseup",ue),()=>{window.removeEventListener("mousemove",G),window.removeEventListener("mouseup",ue),document.body.style.cursor="",document.body.style.userSelect=""}},[]);const ic=zc?L-V/2:-V+W;at.useEffect(()=>{try{sa.current&&(sa.current.setAttribute("webkitdirectory","true"),sa.current.setAttribute("directory",""),sa.current.setAttribute("mozdirectory",""))}catch{}},[]);async function oc(G,ue=""){const Te=[],Ce=G.entries?G.entries():G.values();for await(const he of Ce)try{let fe,ae;if(Array.isArray(he)&&he.length>=2?(ae=he[0],fe=he[1]):(fe=he,ae=fe.name),!fe)continue;if(fe.kind==="file"){const De=await fe.getFile();try{Object.defineProperty(De,"webkitRelativePath",{value:ue+(ae||fe.name),configurable:!0})}catch{}Te.push(De)}else if(fe.kind==="directory"){const De=await oc(fe,ue+(ae||fe.name)+"/");Te.push(...De)}}catch(fe){Nt.debug("collectFilesFromDirectoryHandle: skipping entry due to error",fe)}return Te}const $c=async()=>{var G;if(window.showDirectoryPicker)try{const ue=await window.showDirectoryPicker(),Te=await oc(ue);Te&&Te.length>0?await Ds({target:{files:Te}}):alert("No files found in selected folder.");return}catch(ue){Nt.warn("showDirectoryPicker failed or cancelled",ue)}(G=sa.current)==null||G.click()},Oa=at.useRef(null),Ds=async G=>{const ue=G.target.files;if(!ue||ue.length===0)return;Xs(!1);const Te=Array.from(ue).sort((ae,De)=>ae.name.localeCompare(De.name)),Ce=await Promise.all(Te.map(async ae=>{const De=ae.type&&ae.type.startsWith("image/");let pe,me,ke,Me,Ge=1,Ke=!1;if(!De)try{const rt=await ae.arrayBuffer(),ct=Lr.parseDicom(new Uint8Array(rt));pe=ct.string("x0020000d"),me=ct.string("x0020000e");const ut=ct.string("x00200013");ut!=null&&ut!==""&&(ke=parseInt(ut,10));const mt=ct.string("x00201041")||ct.string("x00201040");mt!=null&&mt!==""&&(Me=parseFloat(mt));const Rt=ct.string("x00280008");if(Rt!=null&&Rt!==""){const Zt=Number(Rt);Number.isFinite(Zt)&&Zt>1&&(Ge=Math.floor(Zt))}Ke=!0}catch{Ke=!1}const $e=De?`external:${URL.createObjectURL(ae)}`:`wadouri:${URL.createObjectURL(ae)}`;return{file:ae,imageId:$e,studyInstanceUID:pe,seriesInstanceUID:me,instanceNumber:ke,sliceLocation:Me,numberOfFrames:Ge,isImage:De,parsedSuccessfully:Ke}})),he=new Map;for(const ae of Ce){if(!ae.isImage&&!ae.parsedSuccessfully){Nt.debug("Skipping non-DICOM/non-image file:",ae.file.name);continue}const De=ae.seriesInstanceUID||ae.studyInstanceUID||(ae.file.webkitRelativePath?ae.file.webkitRelativePath.split("/")[0]:ae.file.name);he.has(De)||he.set(De,{entries:[],studyInstanceUID:ae.studyInstanceUID,seriesInstanceUID:ae.seriesInstanceUID}),he.get(De).entries.push(ae)}const fe=[];for(const[ae,De]of he.entries()){const pe=De.entries;pe.sort((Me,Ge)=>qr&&Me.sliceLocation!==void 0&&Ge.sliceLocation!==void 0?Me.sliceLocation-Ge.sliceLocation:Me.instanceNumber!==void 0&&Ge.instanceNumber!==void 0?Me.instanceNumber-Ge.instanceNumber:(Me.file.webkitRelativePath||Me.file.name).localeCompare(Ge.file.webkitRelativePath||Ge.file.name));const me=pe.flatMap(Me=>{if(Me.isImage||!Number.isFinite(Me.numberOfFrames)||Me.numberOfFrames<=1)return[Me.imageId];const Ge=[];for(let Ke=1;Ke<=Me.numberOfFrames;Ke++)Ge.push(QI(Me.imageId,Ke));return Ge}),ke=await ui(me);fe.push({imageIds:me,studyInstanceUID:De.studyInstanceUID,seriesInstanceUID:De.seriesInstanceUID,seriesGroups:ke})}if(fe.length!==0)if(nc==="replace"){try{const ae=ye.current;if(ae)for(let De=0;De{var De,pe;const ae=Array(Ue).fill([]);for(let me=0;me{const ae=Array(Ue).fill(null).map(()=>[]);for(let De=0;De{const De=[...ae,...fe];fn(pe=>{var Me,Ge;const me=[...pe],ke=fe[fe.length-1];return me[0]=((Ge=(Me=ke.seriesGroups)==null?void 0:Me[0])==null?void 0:Ge.imageIds)||ke.imageIds,me}),Cn(pe=>{const me=[...pe];return me[0]=De.length-1,me}),sr(pe=>{var ke;const me=[...pe];return me[0]=((ke=fe[fe.length-1])==null?void 0:ke.seriesGroups)||[],me}),xt(pe=>{const me=[...pe];return me[0]=0,me});for(const pe of fe)Bn(pe.imageIds);return De})},jc=(G,ue)=>{di(Te=>({...Te,[G]:ue}))},_r=at.useCallback((G,ue)=>{var $e,rt;if(!ue)return;let Te=0,Ce=0,he="",fe="",ae="",De="",pe="",me="",ke="",Me="",Ge,Ke;if(sn[G]==="stack"){Te=typeof ue.getCurrentImageIdIndex=="function"?ue.getCurrentImageIdIndex():0;const ct=typeof ue.getImageIds=="function"?ue.getImageIds():[];Ce=ct.length;const ut=ct[Te];if(ut){if(Nt.debug("[updateOverlay] Current image:",ut.slice(0,80),"frameIndex status:",Ge,"totalFrames:",Ke),ut.includes("&frame=")){const ln=ut.match(/&frame=(\d+)/);if(ln){Ge=parseInt(ln[1],10),Nt.debug("[updateOverlay] Frame detected:",Ge);const Bt=ut.split("&frame=")[0],Qt=Ct("multiframeModule",Bt);if(Qt!=null&&Qt.numberOfFrames)Ke=Qt.numberOfFrames,Nt.debug("[updateOverlay] Total frames from metadata:",Ke);else{const lr=ct.map(Et=>{const Gt=Et.match(/&frame=(\d+)/);return Gt?parseInt(Gt[1],10):null}).filter(Et=>Et!==null&&typeof Et=="number");lr.length>0&&(Ke=Math.max(...lr),Nt.debug("[updateOverlay] Total frames from imageIds:",Ke))}}}else Nt.debug("[updateOverlay] No frame query in imageId. imageIds.length:",ct.length);const mt=Ct("generalSeriesModule",ut),Rt=Ct("imagePlaneModule",ut),Zt=Ct("imagePixelModule",ut);De=(mt==null?void 0:mt.modality)||"",Zt!=null&&Zt.rows&&(Zt!=null&&Zt.columns)&&(me=`${Zt.columns} x ${Zt.rows}`);const gr=[Rt==null?void 0:Rt.columnPixelSpacing,Rt==null?void 0:Rt.rowPixelSpacing,Rt==null?void 0:Rt.sliceThickness].filter(ln=>ln!=null&&ln!=="");gr.length>0&&(ke=gr.join(" x "))}if(typeof ue.getCamera=="function"){const mt=ue.getCamera();mt!=null&&mt.focalPoint&&Array.isArray(mt.focalPoint)&&(Me=mt.focalPoint.map(Rt=>Rt.toFixed(1)).join(", "))}if(ut&&Ya(mt=>mt[ut]?mt:{...mt,[ut]:!0}),typeof ue.getProperties=="function"){const mt=ue.getProperties();if(mt.voiRange){const{lower:Rt,upper:Zt}=mt.voiRange;he=((Zt+Rt)/2).toFixed(0),fe=(Zt-Rt).toFixed(0),Go.current[G]===null&&(Go.current[G]={lower:Rt,upper:Zt})}}}else if(sn[G]==="volume"){if(typeof ue.getSliceIndex=="function"&&(Te=ue.getSliceIndex()),typeof ue.getNumberOfSlices=="function"&&(Ce=ue.getNumberOfSlices()),typeof ue.getProperties=="function"){let ut;if(ue.volumeIds&&ue.volumeIds.size>0){const mt=Array.from(ue.volumeIds)[0];ut=ue.getProperties(mt)}else ut=ue.getProperties();if(ut&&ut.voiRange){const{lower:mt,upper:Rt}=ut.voiRange;he=((Rt+mt)/2).toFixed(0),fe=(Rt-mt).toFixed(0),Go.current[G]===null&&(Go.current[G]={lower:mt,upper:Rt})}}if(typeof ue.getSlicePlaneCoordinates=="function"){const ut=ue.getSlicePlaneCoordinates();ut&&typeof ut.position=="number"&&(ae=ut.position.toFixed(2)+" mm")}const ct=($e=Lt[G])==null?void 0:$e[0];if(ct){const ut=Ct("generalSeriesModule",ct),mt=Ct("imagePlaneModule",ct),Rt=Ct("imagePixelModule",ct);De=(ut==null?void 0:ut.modality)||"",pe=String(((rt=ue.viewportProperties)==null?void 0:rt.orientation)||"").toUpperCase(),Rt!=null&&Rt.rows&&(Rt!=null&&Rt.columns)&&(me=`${Rt.columns} x ${Rt.rows}`);const Zt=[mt==null?void 0:mt.columnPixelSpacing,mt==null?void 0:mt.rowPixelSpacing,mt==null?void 0:mt.sliceThickness].filter(gr=>gr!=null&&gr!=="");Zt.length>0&&(ke=Zt.join(" x "))}if(typeof ue.getCamera=="function"){const ut=ue.getCamera();ut!=null&&ut.focalPoint&&Array.isArray(ut.focalPoint)&&(Me=ut.focalPoint.map(mt=>mt.toFixed(1)).join(", "))}}aa(ct=>{const ut=[...ct];return ut[G]={index:Te+1,total:Ce,windowCenter:he,windowWidth:fe,slicePosition:ae,modality:De,orientation:pe,resolution:me,spacing:ke,focalPoint:Me,frameIndex:Ge,totalFrames:Ke},ut})},[sn,Lt]);at.useEffect(()=>{for(let G=0;G{var lr;const he=await vo(ue.map(Gu));if(he.length===0)return;await Bn(he,{force:!!r});const fe=await ui(he),ae=((lr=fe[0])==null?void 0:lr.imageIds)||he;let De=-1,pe=-1;Tt(Et=>(De=Et.findIndex(Gt=>Gt.imageIds.length===he.length&&Gt.imageIds.every((pn,pr)=>pn===he[pr])),De!==-1?Et:(pe=Et.length,[...Et,{imageIds:he,name:Te,seriesGroups:fe}])));const me=De!==-1?De:pe,ke=ri(Ce);if(ke==="center"){Sr("displayset");try{yr(Et=>{const Gt=[...Et];return Gt[G]="stack",Gt}),fn(Et=>{const Gt=[...Et];return Gt[G]=ae,Gt}),Cn(Et=>{const Gt=[...Et];return Gt[G]=me,Gt}),sr(Et=>{const Gt=[...Et];return Gt[G]=fe,Gt}),xt(Et=>{const Gt=[...Et];return Gt[G]=0,Gt}),tt(G),await Bn(ae)}finally{Sr(null)}return}const Me=Xt.rows,Ge=Xt.cols,Ke=Math.floor(G/Ge),$e=G%Ge,rt=ke==="top"||ke==="bottom"?Me+1:Me,ct=ke==="left"||ke==="right"?Ge+1:Ge;if(rt>3||ct>3||rt*ct>Ue){Sr("displayset");try{yr(Et=>{const Gt=[...Et];return Gt[G]="stack",Gt}),fn(Et=>{const Gt=[...Et];return Gt[G]=he,Gt}),Cn(Et=>{const Gt=[...Et];return Gt[G]=me,Gt}),tt(G),await Bn(he)}finally{Sr(null)}return}const ut=ke==="top"?Ke:ke==="bottom"?Ke+1:Ke,mt=ke==="left"?$e:ke==="right"?$e+1:$e,Rt=ut*ct+mt,Zt=Array(Ue).fill([]),gr=Array(Ue).fill("stack"),ln=Array(Ue).fill(0),Bt=Array(Ue).fill(null).map(()=>[]),Qt=Array(Ue).fill(0);for(let Et=0;Et$e||ke==="left"?pn+1:pn),(ke==="top"||ke==="bottom")&&pn===$e&&(pr=GtKe||ke==="top"?Gt+1:Gt);const es=pr*ct+Di;Zt[es]=Lt[Et]||[],gr[es]=sn[Et]||"stack",ln[es]=an[Et]??0,Bt[es]=kr[Et]||[],Qt[es]=Ze[Et]??0}Zt[Rt]=ae,gr[Rt]="stack",ln[Rt]=pe,Bt[Rt]=fe,Qt[Rt]=0,Sr("displayset");try{Is(),Ta({rows:rt,cols:ct}),fn(Zt),yr(gr),Cn(ln),sr(Bt),xt(Qt),tt(Rt),await Bn(ae)}finally{Sr(null)}},Os=async(G,ue,Te)=>{var Bt;const Ce=bt[ue];if(!Ce)return;let he=Ce.imageIds||[];he=await vo(he),await Bn(he,{force:!!r});const ae=await ui(he);Tt(Qt=>{const lr=[...Qt];return lr[ue]?(lr[ue]={...lr[ue],seriesGroups:ae,imageIds:he},lr):Qt});const De=((Bt=ae[0])==null?void 0:Bt.imageIds)||he,pe=ri(Te);if(pe==="center"){await bo(G,ue),tt(G);return}const me=Xt.rows,ke=Xt.cols,Me=Math.floor(G/ke),Ge=G%ke,Ke=pe==="top"||pe==="bottom"?me+1:me,$e=pe==="left"||pe==="right"?ke+1:ke;if(Ke>3||$e>3||Ke*$e>Ue){await bo(G,ue),tt(G);return}const rt=Array(Ue).fill([]),ct=Array(Ue).fill("stack"),ut=Array(Ue).fill(0),mt=Array(Ue).fill(null).map(()=>[]),Rt=Array(Ue).fill(0),Zt=pe==="top"?Me:pe==="bottom"?Me+1:Me,gr=pe==="left"?Ge:pe==="right"?Ge+1:Ge,ln=Zt*$e+gr;for(let Qt=0;QtGe?pn=Et+1:pn=pe==="left"?Et+1:Et),(pe==="top"||pe==="bottom")&&Et===Ge&&(lrMe?Gt=lr+1:Gt=pe==="top"?lr+1:lr);const pr=Gt*$e+pn;rt[pr]=Lt[Qt]||[],ct[pr]=sn[Qt]||"stack",ut[pr]=an[Qt]??0,mt[pr]=kr[Qt]||[],Rt[pr]=Ze[Qt]??0}rt[ln]=De,ct[ln]="stack",ut[ln]=ue,mt[ln]=ae||[],Rt[ln]=0,Sr("displayset");try{Is(),Ta({rows:Ke,cols:$e}),fn(rt),yr(ct),Cn(ut),sr(mt),xt(Rt),tt(ln),await Bn(De)}finally{Sr(null)}},Vl=at.useCallback((G,ue)=>{if(!(de&&Le)||(ue.pointerType||"").toLowerCase()==="mouse")return;ue.preventDefault(),ue.stopPropagation(),Ye.current=Date.now()+400;const Te=Xt.rows*Xt.cols;let Ce=null,he="center";Ve({stackIdx:G,x:ue.clientX,y:ue.clientY,targetViewportIdx:null,zone:"center"});const fe=me=>{let ke=null,Me="center";for(let Ge=0;Ge$e.right||me.clientY<$e.top||me.clientY>$e.bottom)){ke=Ge,Me=ri(Ys($e,me.clientX,me.clientY));break}}Ce=ke,he=Me,Ve(Ge=>Ge&&{...Ge,x:me.clientX,y:me.clientY,targetViewportIdx:ke,zone:Me}),$t(ke!==null?{viewportIdx:ke,zone:Me}:null)},ae=async()=>{if(window.removeEventListener("pointermove",fe),window.removeEventListener("pointerup",De),window.removeEventListener("pointercancel",pe),$t(null),Ve(null),Ce!==null)try{await Os(Ce,G,he),T(!1),tt(Ce),B(Ce)}catch(me){Nt.error("Failed mobile pointer stack drop:",me)}Ye.current=Date.now()+400},De=()=>{ae()},pe=()=>{ae()};window.addEventListener("pointermove",fe,{passive:!0}),window.addEventListener("pointerup",De,{passive:!0}),window.addEventListener("pointercancel",pe,{passive:!0})},[Os,Ys,de,Le,ri,Xt]);at.useEffect(()=>{const G=async()=>{var fe;if(Nt.debug("setup"),!c.current){c.current=!0,await uee(),await _U(),SW();try{Mp("external",ae=>({promise:(async()=>{const pe=ae.replace(/^external:/,""),me=new Image;me.crossOrigin="anonymous",me.src=pe,await new Promise((ct,ut)=>{me.onload=()=>ct(!0),me.onerror=mt=>ut(mt)});const ke=me.naturalWidth||me.width,Me=me.naturalHeight||me.height,Ge=document.createElement("canvas");Ge.width=ke,Ge.height=Me;const Ke=Ge.getContext("2d");if(!Ke)throw new Error("Unable to create canvas context");Ke.drawImage(me,0,0,ke,Me);const $e=Ke.getImageData(0,0,ke,Me);return{imageId:ae,minPixelValue:0,maxPixelValue:255,slope:1,intercept:0,rows:Me,columns:ke,height:Me,width:ke,color:!0,rgba:!0,sizeInBytes:$e.data.length,getPixelData:()=>$e.data,getImageData:()=>$e,getCanvas:()=>Ge}})()}))}catch(ae){Nt.warn("Failed to register external image loader",ae)}}let Te=ye.current;Te||(Te=new BN(ie),ye.current=Te);let Ce=wi(se);Ce||(Ce=bSe(se)),sn.slice(0,Xt.rows*Xt.cols).filter(ae=>ae==="volume").length,sc(Ce);for(let ae=0;ae{if(me.offsetWidth>0&&me.offsetHeight>0){Te.resize();const $e=Te.getViewport(pe);$e&&typeof $e.resize=="function"&&$e.resize(),$e&&typeof $e.render=="function"&&$e.render()}});Ke.observe(me),me._resizeObserver=Ke}if(sn[ae]==="stack"){if(De&&De.length>0){const Ke=De[0];if(Vr(Ke))try{try{const ct=me._externalPanZoom;ct&&typeof ct.cleanup=="function"&&ct.cleanup()}catch{}me.innerHTML="";const $e=document.createElement("img");$e.style.width="100%",$e.style.height="100%",$e.style.objectFit="contain",$e.style.display="block",$e.src=Ke.replace(/^external:/,""),$e.setAttribute("draggable","false"),me.appendChild($e);const rt=Bo(me,$e);me._externalPanZoom=rt,Ce.removeViewports(ie,pe)}catch($e){Nt.warn("Failed to render external image in viewport",$e)}else try{Me.setStack(De)}catch($e){Nt.warn("viewport.setStack failed",$e)}}$i?Ce.removeViewports(ie,pe):Ce.addViewport(pe,ie)}else if(sn[ae]==="volume"){Ce.addViewport(pe,ie);const Ke=`myVolumeId_${ae}`;if((await My(Ke,{imageIds:De})).load(),Me.setVolumes([{volumeId:Ke}]),typeof Me.getNumberOfSlices=="function"){const ct=Me.getNumberOfSlices(),ut=ba.current[ae]||0,mt=Math.max(0,Math.min(Math.max(0,ct-1),ut));xo(Me.element,{imageIndex:mt})}Me.render(),me._overlayListener&&Me.element.removeEventListener(Hg,me._overlayListener);const rt=()=>_r(ae,Me);Me.element.addEventListener(Hg,rt),me._overlayListener=rt,_r(ae,Me);continue}if(Me.render(),!le.current){ji.current[ae]!==void 0&&typeof Me.setImageIdIndex=="function"&&xo(Me.element,{imageIndex:ji.current[ae]});const Ke=yo.current[ae];if(Ke&&typeof Me.setProperties=="function"){const{voiRange:$e,invert:rt,interpolationType:ct,VOILUTFunction:ut,colormap:mt}=Ke,Rt={};$e&&$e.lower!==void 0&&$e.upper!==void 0&&(Rt.voiRange=$e),rt!==void 0&&(Rt.invert=rt),ct!==void 0&&(Rt.interpolationType=ct),ut&&(Rt.VOILUTFunction=ut),mt!=null&&(typeof mt=="string"||typeof mt=="object"&&!("actor"in mt))&&(Rt.colormap=mt),setTimeout(()=>{Nt.debug("Restoring properties (timeout) for viewport",ae,Rt),Me.setProperties(Rt),Me.render()},100)}}me._overlayListener&&Me.element.removeEventListener(Hg,me._overlayListener);const Ge=()=>_r(ae,Me);Me.element.addEventListener(Hg,Ge),me._overlayListener=Ge,_r(ae,Me)}for(let ae=0;ae=2?(Ce.hasTool(al.toolName)||Ce.addTool(al.toolName),Ce.setToolEnabled(al.toolName),Ce.setToolConfiguration(al.toolName,{}),Ce.setToolActive(al.toolName,{bindings:[{mouseButton:jg.Primary}]})):Ce.hasTool(al.toolName)&&Ce.setToolDisabled(al.toolName)),tc()},ue=requestAnimationFrame(()=>{G()});return()=>{Kr.current.forEach(Te=>{Te&&Te._resizeObserver&&(Te._resizeObserver.disconnect(),delete Te._resizeObserver)}),cancelAnimationFrame(ue)}},[s,_r,Xt,sn,Lt]);const Fl=at.useCallback(G=>{const ue=`CT_${G}`,Ce=ye.current.getViewport(ue);Ce&&typeof Ce.resetCamera=="function"&&(Ce.resetCamera(),Nt.debug("Restoring viewport properties for viewport",G),Ce.resetProperties(),Ce.render())},[]),Ms=at.useCallback((G,ue,Te)=>{const Ce=`CT_${G}`;try{const he=ye.current;if(he){const fe=he.getViewport(Ce);fe&&typeof fe.setProperties=="function"&&(Nt.debug(`Applying preset to viewport ${G}: center=${ue}, width=${Te}`),fe.setProperties({voiRange:{lower:ue-Te/2,upper:ue+Te/2}}),fe.render(),_r(G,fe))}}catch{}},[_r]),Wo=at.useCallback((G,ue=!1)=>{const Te=`CT_${G}`;try{const Ce=ye.current,he=Ce==null?void 0:Ce.getViewport(Te);if(!he)return!1;const fe=typeof he.getImageIds=="function"?he.getImageIds():Lt[G]||[],ae=typeof he.getCurrentImageIdIndex=="function"?he.getCurrentImageIdIndex():0,De=fe[ae]||fe[0],pe=Go.current[G],me=De?Ct("voiLutModule",De)||{}:{},ke=De?Ct("imagePixelModule",De)||{}:{},Me=De?Ct("modalityLutModule",De)||{}:{},Ge=Array.isArray(me.windowCenter)?me.windowCenter[0]:me.windowCenter,Ke=Array.isArray(me.windowWidth)?me.windowWidth[0]:me.windowWidth,$e=Number(ke.smallestPixelValue??ke.smallestImagePixelValue),rt=Number(ke.largestPixelValue??ke.largestImagePixelValue),ct=Number(Me.rescaleSlope??1),ut=Number(Me.rescaleIntercept??0);if(pe)he.setProperties({voiRange:pe});else if(Number.isFinite(Number(Ge))&&Number.isFinite(Number(Ke))&&Number(Ke)>0){const mt=Number(Ge),Rt=Number(Ke);he.setProperties({voiRange:{lower:mt-Rt/2,upper:mt+Rt/2}})}else Number.isFinite($e)&&Number.isFinite(rt)&&rt>$e?he.setProperties({voiRange:{lower:$e*ct+ut,upper:rt*ct+ut}}):typeof he.resetProperties=="function"&&he.resetProperties();return ue&&typeof he.resetCamera=="function"&&he.resetCamera(),he.render(),_r(G,he),!0}catch(Ce){return Nt.warn("Failed to apply default window level",Ce),!1}},[_r,Lt]),zo=at.useCallback(G=>{const ue=`CT_${G}`;(async()=>{const Te=ye.current;if(!Te)return;const Ce=Te.getViewport(ue);if(!Ce)return;const he=typeof Ce.getImageIds=="function"?Ce.getImageIds():Lt[G]||[],fe=typeof Ce.getCurrentImageIdIndex=="function"?Ce.getCurrentImageIdIndex():0,ae=he[fe]||he[0];if(!ae){Wo(G);return}const De=Ct("imagePixelModule",ae)||{},pe=Ct("modalityLutModule",ae)||{},me=Ct("voiLutModule",ae)||{},ke=Go.current[G];let Me=Number(De.smallestPixelValue??De.smallestImagePixelValue),Ge=Number(De.largestPixelValue??De.largestImagePixelValue),Ke=Number(pe.rescaleSlope??1),$e=Number(pe.rescaleIntercept??0);if(!Number.isFinite(Me)||!Number.isFinite(Ge)||Ge<=Me)try{const ut=await El(ae);Me=Number(ut==null?void 0:ut.minPixelValue),Ge=Number(ut==null?void 0:ut.maxPixelValue),Ke=Number((ut==null?void 0:ut.slope)??Ke),$e=Number((ut==null?void 0:ut.intercept)??$e)}catch{const mt=he.filter(Rt=>!!Rt).slice(0,6);for(const Rt of mt)try{const Zt=await El(Rt);if(Me=Number(Zt==null?void 0:Zt.minPixelValue),Ge=Number(Zt==null?void 0:Zt.maxPixelValue),Ke=Number((Zt==null?void 0:Zt.slope)??Ke),$e=Number((Zt==null?void 0:Zt.intercept)??$e),Number.isFinite(Me)&&Number.isFinite(Ge)&&Ge>Me)break}catch{}}const rt=Array.isArray(me.windowCenter)?me.windowCenter[0]:me.windowCenter,ct=Array.isArray(me.windowWidth)?me.windowWidth[0]:me.windowWidth;if(Number.isFinite(Me)&&Number.isFinite(Ge)&&Ge>Me)Ce.setProperties({voiRange:{lower:Me*Ke+$e,upper:Ge*Ke+$e}});else if(Number.isFinite(Number(rt))&&Number.isFinite(Number(ct))&&Number(ct)>0){const ut=Number(rt),mt=Number(ct);Ce.setProperties({voiRange:{lower:ut-mt/2,upper:ut+mt/2}})}else if(ke)Ce.setProperties({voiRange:ke});else{Wo(G);return}Ce.render(),_r(G,Ce)})().catch(()=>{Wo(G)})},[Wo,_r,Lt]),io=at.useCallback((G,ue,Te=!0,Ce=!0)=>{if(Te&&(Ja.current[G]=ue),ue.action==="reset"){Wo(G,Ce);return}if(ue.action==="autolevel"){zo(G);return}const he=ue;Ms(G,he.center,he.width)},[Wo,Ms,zo]);at.useEffect(()=>{const G=()=>{const Te=ye.current;if(!Te)return;const Ce=Xt.rows*Xt.cols;for(let he=0;hewindow.clearTimeout(ue)},[io,gn,Xt,sn]),at.useEffect(()=>{const G=ue=>{var De,pe;const Te=ue.target;if(Te){const me=(De=Te.tagName)==null?void 0:De.toLowerCase(),ke=Te.getAttribute("contenteditable")==="true";if(me==="input"||me==="textarea"||me==="select"||ke)return}if(ue.ctrlKey||ue.altKey||ue.metaKey||Ae===null)return;const Ce=(pe=gn[Ae])==null?void 0:pe.modality,he=qI(Ce);if(ue.key==="0"){const me=he.find(ke=>ke.action==="reset");me&&(io(Ae,me),ue.preventDefault());return}if(!/^[1-9]$/.test(ue.key))return;const fe=Number(ue.key)-1,ae=he.filter(me=>me.action==="preset");fe>=ae.length||(io(Ae,ae[fe]),ue.preventDefault())};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[Ae,io,gn]);const Mo=at.useCallback((G,ue)=>{const Te=kr[G]||[];if(Te.length<=1)return;const Ce=Math.max(0,Math.min(Te.length-1,ue)),he=Te[Ce];if(!he||he.imageIds.length===0)return;const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`),De=sn[G]==="volume",pe=ke=>{if(!ke)return null;const Me=Ct("imagePlaneModule",ke)||{},Ge=Array.isArray(Me==null?void 0:Me.imagePositionPatient)?Me.imagePositionPatient:null,Ke=Array.isArray(Me==null?void 0:Me.rowCosines)?Me.rowCosines:null,$e=Array.isArray(Me==null?void 0:Me.columnCosines)?Me.columnCosines:null;if(Ge&&Ke&&$e&&Ke.length>=3&&$e.length>=3){const ct=[Ke[1]*$e[2]-Ke[2]*$e[1],Ke[2]*$e[0]-Ke[0]*$e[2],Ke[0]*$e[1]-Ke[1]*$e[0]],ut=Math.hypot(ct[0],ct[1],ct[2]);if(ut>1e-6){const mt=[ct[0]/ut,ct[1]/ut,ct[2]/ut];return Ge[0]*mt[0]+Ge[1]*mt[1]+Ge[2]*mt[2]}}const rt=Number(Me==null?void 0:Me.sliceLocation);return Number.isFinite(rt)?rt:null};let me=0;if(ae&&typeof ae.getCurrentImageIdIndex=="function"){const ke=Lt[G]||[],Me=ke.length,Ge=ae.getCurrentImageIdIndex(),Ke=ke[Ge]||ke[0],$e=pe(Ke);if($e!==null&&he.imageIds.length>0){let rt=0,ct=Number.POSITIVE_INFINITY;he.imageIds.forEach((ut,mt)=>{const Rt=pe(ut);if(Rt===null)return;const Zt=Math.abs(Rt-$e);Zt1?Ge/(Me-1):0;me=Math.max(0,Math.min(he.imageIds.length-1,Math.round(rt*Math.max(0,he.imageIds.length-1))))}}else if(De&&ae&&typeof ae.getSliceIndex=="function"&&typeof ae.getNumberOfSlices=="function"){const ke=ae.getNumberOfSlices(),Me=ae.getSliceIndex(),Ge=ke>1?Me/(ke-1):0;me=Math.max(0,Math.min(he.imageIds.length-1,Math.round(Ge*Math.max(0,he.imageIds.length-1))))}ba.current[G]=me,xt(ke=>{const Me=[...ke];return Me[G]=Ce,Me}),fn(ke=>{const Me=[...ke];return Me[G]=he.imageIds,Me}),Bn(he.imageIds,{force:!!r}),window.setTimeout(()=>{var Me;const ke=(Me=ye.current)==null?void 0:Me.getViewport(`CT_${G}`);if(ke){if(sn[G]==="stack"&&typeof ke.setImageIdIndex=="function"){xo(ke.element,{imageIndex:me}),ke.render(),_r(G,ke);return}if(sn[G]==="volume"&&typeof ke.getNumberOfSlices=="function"){const Ge=ke.getNumberOfSlices(),Ke=Math.max(0,Math.min(Math.max(0,Ge-1),me));xo(ke.element,{imageIndex:Ke}),ke.render(),_r(G,ke)}}},25)},[kr,Bn,_r,Lt,sn]);at.useEffect(()=>{const G=[],ue=Xt.rows*Xt.cols;for(let Te=0;Te{var Ge,Ke;const De=(Ge=ye.current)==null?void 0:Ge.getViewport(`CT_${Te}`);if(!De||typeof De.getCurrentImageIdIndex!="function"||typeof De.setImageIdIndex!="function")return;const me=(((Ke=De.getImageIds)==null?void 0:Ke.call(De))||Ce).length;if(me<2)return;const Me=(De.getCurrentImageIdIndex()+1)%me;xo(De.element,{imageIndex:Me}),De.render()},fe);G.push(ae)}return()=>{G.forEach(Te=>window.clearInterval(Te))}},[Ei,tn,Xt,Lt,sn]);const Hc=at.useCallback(()=>{const G=a.current;G&&(document.fullscreenElement===G?document.exitFullscreen():G.requestFullscreen?G.requestFullscreen():G.webkitRequestFullscreen?G.webkitRequestFullscreen():G.msRequestFullscreen&&G.msRequestFullscreen())},[]);at.useEffect(()=>{aa(Array(Xt.rows*Xt.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:"",modality:"",orientation:"",resolution:"",spacing:"",focalPoint:""})),ki(Array(Xt.rows*Xt.cols).fill(!1)),Dn(Array(Ue).fill(!1))},[Xt]),at.useEffect(()=>{tc()},[Vi,bi,Qa,tc]),at.useEffect(()=>{if(!Da.some(Boolean))return;const G=ue=>{const Te=document.querySelector(".preset-menu");Te&&!Te.contains(ue.target)&&ki(Ce=>Ce.map(()=>!1))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Da]),at.useEffect(()=>{if(!Ea)return;const G=ue=>{const Te=A.current;Te&&!Te.contains(ue.target)&&(qa(!1),ve(!1))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Ea]),at.useEffect(()=>{const G=ue=>{if(ue.button===3||ue.button===4)return ue.preventDefault(),!1};return window.addEventListener("mousedown",G,!0),window.addEventListener("mouseup",G,!0),window.addEventListener("auxclick",G,!0),()=>{window.removeEventListener("mousedown",G,!0),window.removeEventListener("mouseup",G,!0),window.removeEventListener("auxclick",G,!0)}},[]),at.useEffect(()=>{const G=a.current;if(!G)return;const ue=Te=>{Te.preventDefault()};return G.addEventListener("contextmenu",ue),()=>{G.removeEventListener("contextmenu",ue)}},[]),at.useEffect(()=>{if(!Ni)return;const G=wi(se);sc(G)},[Ae,Ni]),at.useEffect(()=>{Oa.current&&(Oa.current.setAttribute("webkitdirectory","true"),Oa.current.setAttribute("directory","true"))},[]),at.useEffect(()=>(window.loadDicomStackFromWadouriList=async G=>{var fe;if(!G||G.length===0)return;const ue=await vo(G);await Bn(ue,{force:!!r});const Te=await ui(ue),Ce=((fe=Te[0])==null?void 0:fe.imageIds)||ue;let he;try{const ae=ue[0];if(ae&&ae.startsWith("wadouri:")){const De=Qc(ae),me=await(await fetch(De)).arrayBuffer();he=Lr.parseDicom(new Uint8Array(me)).string("x0020000d")}}catch{}Tt(ae=>{const De=[...ae,{imageIds:ue,studyInstanceUID:he,seriesGroups:Te}];return fn(pe=>{const me=[...pe];return me[0]=Ce,me}),Cn(pe=>{const me=[...pe];return me[0]=De.length-1,me}),sr(pe=>{const me=[...pe];return me[0]=Te,me}),xt(pe=>{const me=[...pe];return me[0]=0,me}),Bn(Ce),De})},()=>{window.loadDicomStackFromWadouriList=void 0}),[ui,vo,Tt,Bn,Cn,fn]),at.useEffect(()=>{!qr||!Lt.every(ue=>!ue||ue.length===0||ue.every(Te=>!!Ct("imagePlaneModule",Te)))||fn(ue=>{let Te=!1;const Ce=ue.map(he=>{if(!he||he.length===0)return he;const De=[...he.map(pe=>({imageId:pe,sliceLoc:(()=>{const me=Ct("imagePlaneModule",pe);return me&&me.sliceLocation!==void 0?Number(me.sliceLocation):null})()}))].sort((pe,me)=>pe.sliceLoc!==null&&me.sliceLoc!==null?pe.sliceLoc-me.sliceLoc:pe.imageId.localeCompare(me.imageId)).map(pe=>pe.imageId);return JSON.stringify(De)!==JSON.stringify(he)?(Te=!0,De):he});return Te&&ni(!0),Ce})},[qr,bt]);function sc(G){if(!G)return;const ue=`CT_${Ae}`;Ni?(G.setToolEnabled(Ld.toolName),G.setToolConfiguration(Ld.toolName,{sourceViewportId:ue})):G.setToolDisabled(Ld.toolName)}function cc(){var ue,Te,Ce;const G=ye.current;if(G)for(let he=0;he[])),Cn(Array(Ue).fill(0)),sr(Array(Ue).fill(null).map(()=>[])),xt(Array(Ue).fill(0)),Fn(Array(Ue).fill(!1)),Dn(Array(Ue).fill(!1)),yr(Array(Ue).fill("stack")),Object.values(Fo.current).forEach(ue=>{if(typeof ue=="string"&&ue.startsWith("blob:"))try{URL.revokeObjectURL(ue)}catch{}}),Fo.current={},xs({}),Ai.current={},ni(!1),tt(0)}function Ps(G,ue){var ae,De;if(Nt.debug("Truncating stack from",G,"to",ue),Nt.debug(kn),Xt.rows!==1||Xt.cols!==1||bt.length!==1||!Lt[0]||Lt[0].length===0||kn)return alert("Truncation is only allowed when a single stack is loaded in a single viewport (and the order has not been modified in the viewer)."),!1;const Te=bt[0],Ce=Te.imageIds;if(G<0||ue>=Ce.length||G>=ue)return alert("Invalid truncation bounds."),!1;const he=Ce.slice(G,ue+1);Tt([{...Te,imageIds:he}]),fn([he]),Cn([0]);const fe=ye.current;if(fe){const pe=fe.getViewport("CT_0");pe&&typeof pe.setStack=="function"&&(pe.setStack(he),(ae=pe.setImageIdIndex)==null||ae.call(pe,0),(De=pe.render)==null||De.call(pe))}return!0}function qc(G=0){const ue=ye.current;if(!ue)return null;const Te=ue.getViewport(`CT_${G}`);return!Te||typeof Te.getCurrentImageIdIndex!="function"?null:Te.getCurrentImageIdIndex()}at.useEffect(()=>{const G=t||"default";function ue(Ce,he){const fe=ye.current;if(!fe)return;const ae=fe.getViewport(`CT_${Ce}`);if(!ae||typeof ae.getImageIds!="function")return;const pe=ae.getImageIds().map(Me=>Qc(Me)),me=Qc(he),ke=pe.indexOf(me);ke!==-1&&typeof ae.setImageIdIndex=="function"&&(xo(ae.element,{imageIndex:ke}),_r(Ce,ae))}window[`getViewport_${G}`]=Ce=>{const he=ye.current;if(he)return he.getViewport(`CT_${Ce}`)},window[`getAllViewports_${G}`]=()=>{const Ce=ye.current;return Ce?Array.from({length:Ue},(he,fe)=>Ce.getViewport(`CT_${fe}`)).filter(Boolean):[]},window[`jumpToSliceByImageId_${G}`]=ue,window[`resetViewer_${G}`]=cc,window[`clearViewer_${G}`]=Kc,window[`truncateStack_${G}`]=Ps,window[`getCurrentStackPosition_${G}`]=qc,window[`loadAdditionalStack_${G}`]=async(Ce,he)=>{var me,ke;if(!Array.isArray(Ce)||Ce.length===0)return;const fe=await vo(Ce);await Bn(fe,{force:!!r});const ae=await ui(fe),De=((me=ae[0])==null?void 0:me.imageIds)||fe;let pe=he;if(!pe&&((ke=fe[0])!=null&&ke.startsWith("wadouri:")))try{const Me=Qc(fe[0]),Ke=await(await fetch(Me)).arrayBuffer();pe=Lr.parseDicom(new Uint8Array(Ke)).string("x0020000d")}catch{}Tt(Me=>[...Me,{imageIds:fe,studyInstanceUID:pe,seriesGroups:ae}]),fn(Me=>{const Ge=[...Me],Ke=Ge.findIndex($e=>!$e||$e.length===0);return Ke!==-1&&(Ge[Ke]=De,sr($e=>{const rt=[...$e];return rt[Ke]=ae,rt}),xt($e=>{const rt=[...$e];return rt[Ke]=0,rt})),Ge}),Bn(De)},window[`loadExternalStack_${G}`]=async(Ce,he)=>{!Array.isArray(Ce)||Ce.length===0||await ac(Ae??0,Ce,he||"Series","center")},window[`loadExternalStackNewViewport_${G}`]=async(Ce,he)=>{if(!Array.isArray(Ce)||Ce.length===0)return;await ac(Ae??0,Ce,he||"Series","right")},window[`exportViewerState_${G}`]=()=>{var $e;const Ce=Xt.rows*Xt.cols,he=sn.slice(0,Ce),fe=an.slice(0,Ce),ae=bt.map(rt=>({i:rt.imageIds,u:rt.studyInstanceUID,g:rt.seriesGroups}));Nt.debug("Exporting viewer state with",Ce,"active viewports"),Nt.debug("modes",he);const De=ye.current,pe=[],me=[],ke=[],Me=[],Ge=[];for(let rt=0;rt{try{le.current=!0;const he=typeof Ce=="string"?JSON.parse(Ce):Ce;if(he.grid&&Ta(he.grid),he.modes&&yr(he.modes),he.stacks&&Tt(he.stacks.map(pe=>({imageIds:pe.i,studyInstanceUID:pe.u,seriesGroups:Array.isArray(pe.g)?pe.g:void 0}))),he.stackIdx&&he.stacks){const pe=he.stackIdx.map(me=>{var ke;return((ke=he.stacks[me])==null?void 0:ke.i)||[]});fn(pe),Cn(he.stackIdx),sr(()=>{const me=Array(Ue).fill(null).map(()=>[]);for(let ke=0;kepr===Gt[Di])){Nt.warn(`Viewport ${Bt}: importedImageIds do not match viewportImageIds`,{importedImageIds:Gt,viewportImageIds:pn}),ke=!1;break}}catch{ke=!1}}if(!ke&&ae{De()},500);return}for(let Bt=0;Bt{try{xo(Qt.element,{imageIndex:he.volumeSliceIndices[Bt]})}catch{}},100)}else{try{Qt.setStack&&(Qt.setStack(Gt),Qt.render())}catch(pn){Nt.warn("Failed to set stack for viewport",Bt,pn)}if(he.stackPos&&typeof he.stackPos[Bt]=="number"&&typeof Qt.setImageIdIndex=="function")try{Kn&&xo?xo(Qt.element,{imageIndex:he.stackPos[Bt]}):Qt.setImageIdIndex(he.stackPos[Bt])}catch{}}}const Me=1500;Nt.debug(`Waiting ${Me}ms before applying properties/camera to viewports`),await new Promise(Bt=>setTimeout(Bt,Me));for(let Bt=0;Bt{De()},100)}catch(he){le.current=!1,alert("Failed to import viewer state: "+he)}},window[`exportAnnotations_${G}`]=()=>{try{let Ce=Or.getAllAnnotations();if(Nt.debug("Exporting annotations:",Ce),Array.isArray(Ce)){const he=[Ff.toolName,Gh.toolName,Uf.toolName,Su.toolName,Jd.toolName,Vf.toolName,Il.toolName,_u.toolName,Fh.toolName];Ce=Ce.filter(fe=>he.includes(fe.metadata.toolName))}else return"{}";return JSON.stringify(Ce,null,2)}catch(Ce){return alert("Failed to export annotations: "+Ce),"{}"}},window.__pendingImportAnnotations=window.__pendingImportAnnotations||{};const Te=Ce=>{try{const he=window.__pendingImportAnnotations&&window.__pendingImportAnnotations[Ce];if(!he||!he.length)return;const fe=Or;if(!fe||typeof fe.addAnnotation!="function")return;for(;(window.__pendingImportAnnotations[Ce]||[]).length;){const ae=(window.__pendingImportAnnotations[Ce]||[]).shift();ae&&Array.isArray(ae)&&ae.forEach(De=>{try{fe.addAnnotation(De,De.annotationUID)}catch(pe){Nt.error("Failed to add queued annotation",pe,De)}})}ye.current&&ye.current.render()}catch(he){Nt.error("Error flushing pending annotations:",he)}};return window[`importAnnotations_${G}`]=Ce=>{try{const he=typeof Ce=="string"?JSON.parse(Ce):Ce,fe=Or;if(!fe||typeof fe.addAnnotation!="function"){window.__pendingImportAnnotations[G]=window.__pendingImportAnnotations[G]||[],window.__pendingImportAnnotations[G].push(he),Nt.warn("importAnnotations: annotation state not ready, queued import",G),setTimeout(()=>Te(G),500);return}if(fe.removeAllAnnotations)try{fe.removeAllAnnotations()}catch(ae){Nt.warn("removeAllAnnotations failed",ae)}Array.isArray(he)&&he.forEach(ae=>{try{fe.addAnnotation(ae,ae.annotationUID)}catch(De){Nt.error("Failed to add annotation",De,ae)}}),ye.current&&ye.current.render()}catch(he){Nt.error("Failed to import annotations:",he,{apiKey:G,cornerstoneTools:!!Hxe,renderingEngine:!!ye.current});try{alert("Failed to import annotations: "+he)}catch{}}try{Te(G)}catch{}},window[`importLegacyAnnotations_${G}`]=Ce=>{Or.removeAllAnnotations&&Or.removeAllAnnotations();let he;try{he=typeof Ce=="string"?JSON.parse(Ce):Ce}catch{alert("Invalid legacy annotation JSON");return}const fe={ArrowAnnotate:"ArrowAnnotate"};Object.entries(he).forEach(([ae,De])=>{Nt.debug("Importing legacy annotations for imageId:",ae),Object.entries(De).forEach(([pe,me])=>{const ke=fe[pe]||pe;me.data&&Array.isArray(me.data)&&me.data.forEach(Me=>{const Ge=HI(ae,{x:Me.handles.start.y,y:Me.handles.start.x}),Ke=HI(ae,{x:Me.handles.end.y,y:Me.handles.end.x});Nt.debug("Importing legacy annotation:"),Nt.debug(" Image ID:",ae),Nt.debug(" Start World:",Ge),Nt.debug(" End World:",Ke);const $e=Ct("imagePlaneModule",ae);Nt.debug(SA);let rt=Ct("frameOfReferenceUID",ae);!rt&&$e&&$e.frameOfReferenceUID&&(rt=$e.frameOfReferenceUID);const ct=$e!=null&&$e.rowCosines&&($e!=null&&$e.columnCosines)?[$e.rowCosines[1]*$e.columnCosines[2]-$e.rowCosines[2]*$e.columnCosines[1],$e.rowCosines[2]*$e.columnCosines[0]-$e.rowCosines[0]*$e.columnCosines[2],$e.rowCosines[0]*$e.columnCosines[1]-$e.rowCosines[1]*$e.columnCosines[0]]:void 0;Array.isArray(ct)&&ct.length,typeof Me.rotation=="number"&&Me.rotation;const ut={annotationUID:Me.uuid,metadata:{toolName:ke,referencedImageId:ae,FrameOfReferenceUID:rt,viewPlaneNormal:ct},data:{handles:{points:[Ge,Ke],textBox:Me.handles.textBox},text:Me.text||""},visibility:Me.visible!==!1,active:Me.active||!1};Or.addAnnotation(ut,ut.annotationUID)})})}),ye.current&&ye.current.render()},window[`importLegacyViewport_${G}`]=Ce=>{let he;try{he=typeof Ce=="string"?JSON.parse(Ce):Ce}catch{alert("Invalid legacy viewport JSON");return}const fe=ye.current;if(!fe)return;const ae=`CT_${Ae??0}`,De=fe.getViewport(ae);if(!De)return;const pe={};if(he.voi&&(pe.voiRange={lower:he.voi.windowCenter-he.voi.windowWidth/2,upper:he.voi.windowCenter+he.voi.windowWidth/2}),typeof he.invert=="boolean"&&(pe.invert=he.invert),typeof he.pixelReplication=="boolean"&&(pe.interpolationType=he.pixelReplication?0:1),typeof he.hflip=="boolean"&&(pe.hflip=he.hflip),typeof he.vflip=="boolean"&&(pe.vflip=he.vflip),typeof De.setProperties=="function"&&De.setProperties(pe),he.translation||he.scale){const me=De.getCamera?De.getCamera():{};he.translation&&(me.translation={...me.translation,...he.translation}),he.scale&&(me.parallelScale=200/he.scale),Nt.debug("Applying legacy camera properties:",me),typeof De.setCamera=="function"&&De.setCamera(me)}typeof he.rotation=="number"&&De.setRotation(he.rotation),De.render(),_r(Ae??0,De)},()=>{window[`exportViewerState_${G}`]=void 0,window[`importViewerState_${G}`]=void 0,window[`exportAnnotations_${G}`]=void 0,window[`importAnnotations_${G}`]=void 0,window[`importLegacyAnnotations_${G}`]=void 0,window[`importLegacyViewport_${G}`]=void 0,window[`jumpToSliceByImageId_${G}`]=void 0,window[`resetViewer_${G}`]=void 0,window[`clearViewer_${G}`]=void 0,window[`truncateStack_${G}`]=void 0,window[`getCurrentStackPosition_${G}`]=void 0,window[`loadAdditionalStack_${G}`]=void 0,window[`loadExternalStack_${G}`]=void 0,window[`loadExternalStackNewViewport_${G}`]=void 0,window[`getViewport_${G}`]=void 0,window[`getAllViewports_${G}`]=void 0}},[Xt,sn,an,bt,Lt,Ta,yr,Cn,Tt,fn,Tt,fn,Bn]),at.useEffect(()=>{const G=a.current;if(!G)return;function ue(Te){if(Nt.debug("Handling arrow key navigation",Te.key),Nt.debug("activeViewport",Ae),Ae===null)return;const Ce=ye.current;if(!Ce)return;const he=Ce.getViewport(`CT_${Ae}`);if(he){if(Nt.debug(he),sn[Ae]==="stack"){if(typeof he.getCurrentImageIdIndex!="function"||typeof he.setImageIdIndex!="function")return;const fe=Lt[Ae];if(!fe||fe.length===0)return;Te.key==="ArrowUp"||Te.key==="ArrowRight"?(bc(he,{delta:-1}),Te.preventDefault()):(Te.key==="ArrowDown"||Te.key==="ArrowLeft")&&(bc(he,{delta:1}),Te.preventDefault())}sn[Ae]==="volume"&&typeof he.getSliceIndex=="function"&&typeof he.getNumberOfSlices=="function"&&he.getNumberOfSlices()>1&&(Te.key==="ArrowUp"||Te.key==="ArrowRight"?(bc(he,{delta:-1}),Te.preventDefault()):(Te.key==="ArrowDown"||Te.key==="ArrowLeft")&&(bc(he,{delta:1}),Te.preventDefault()))}}return G.addEventListener("keydown",ue),()=>{G.removeEventListener("keydown",ue)}},[Ae,sn,Lt,_r]);const ee=Ae!==null?an[Ae]:0,te=bt[ee];te==null||te.studyInstanceUID;const[Ee,He]=at.useState(()=>Array(Ue).fill(null)),ot=Xt.rows*Xt.cols,gt=[];for(let G=0;GKr.current[G]=fe,style:{flex:1,display:ue&&Te?"flex":"none",border:ue?"1px solid #222":"none",background:"#000",minWidth:0,minHeight:0,position:"relative",overflow:"hidden",flexDirection:"column",gridRow:Math.floor(G/Xt.cols)+1,gridColumn:G%Xt.cols+1,height:"100%",touchAction:de&&Le?"none":"pan-y",boxShadow:Ae===G?"0 0 0 4px #1976d2, 0 0 16px 4px #1976d2cc":void 0,zIndex:Ae===G?10:1},onClick:()=>{if(!Ie){if(de&&!Le){Uc(G),qa(!1),ve(!1),bs(!1);return}if(de&&Le&&z!==null){Os(G,z,Q).catch(fe=>{Nt.error("Failed to apply mobile stack drop:",fe)}),q(null),T(!1);return}tt(G),qa(!1)}},onDoubleClick:()=>Fl(G),onDragEnter:fe=>{const ae=fe.dataTransfer.types,De=ae.includes("text/stack-idx"),pe=ae.includes("text/dv3d-imageids");if(!De&&!pe)return;fe.preventDefault(),pe&&qt(!0);const me=Ir(fe);$t({viewportIdx:G,zone:me})},onDragOver:fe=>{const ae=fe.dataTransfer.types,De=ae.includes("text/stack-idx"),pe=ae.includes("text/dv3d-imageids");if(!De&&!pe)return;fe.preventDefault();const me=Ir(fe),ke=ri(me);$t({viewportIdx:G,zone:me}),fe.dataTransfer.dropEffect=ke===me?"copy":"move"},onDragLeave:fe=>{if((At==null?void 0:At.viewportIdx)!==G)return;const ae=fe.relatedTarget;ae&&fe.currentTarget.contains(ae)||$t(null)},onDrop:fe=>{fe.preventDefault();const ae=fe.dataTransfer.getData("text/dv3d-imageids");if(ae){const me=fe.dataTransfer.getData("text/dv3d-stack-name")||"Series";try{const ke=JSON.parse(ae),Me=Ir(fe);ac(G,ke,me,Me).catch(Ge=>{Nt.error("Failed to apply external drop:",Ge)})}catch(ke){Nt.error("Invalid text/dv3d-imageids payload:",ke)}$t(null),qt(!1);return}const De=fe.dataTransfer.getData("text/stack-idx"),pe=parseInt(De,10);if(!isNaN(pe)){const me=Ir(fe);Os(G,pe,me).catch(ke=>{Nt.error("Failed to apply dropped stack:",ke)})}$t(null),yt(null),qt(!1)},children:[de&&!Le&&Ne.jsx("div",{style:{position:"absolute",inset:0,zIndex:60,pointerEvents:"none",display:"flex",alignItems:"center",justifyContent:"center",background:"linear-gradient(to top, rgba(0,0,0,0.55), rgba(0,0,0,0.2))",color:"#fff",fontSize:14,fontWeight:700,letterSpacing:.2,textAlign:"center",padding:"18px"},children:"Tap to activate fullscreen interaction"}),de&&Le&&z!==null&&Ne.jsxs("div",{style:{position:"absolute",top:8,right:8,zIndex:62,background:"rgba(25, 118, 210, 0.92)",color:"#fff",borderRadius:6,padding:"6px 8px",fontSize:11,fontWeight:700,pointerEvents:"none"},children:["Tap to drop stack (",Q,")"]}),(wt!==null||Dt)&&Ce&&Ne.jsx("div",{style:{position:"absolute",inset:0,zIndex:19,pointerEvents:"none",background:"rgba(0,0,0,0.08)"},children:Ne.jsx("div",{style:{position:"absolute",left:he==="left"?0:he==="right"?"50%":"20%",top:he==="top"?0:he==="bottom"?"50%":"20%",width:he==="left"||he==="right"?"50%":"60%",height:he==="top"||he==="bottom"?"50%":"60%",border:"2px solid #90caf9",boxShadow:"0 0 0 9999px rgba(17, 29, 45, 0.22)",background:"rgba(25, 118, 210, 0.28)",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:.4},children:he==="center"?"Load Here":`Split ${he}`})}),Ne.jsx("button",{style:{position:"absolute",top:8,left:8,zIndex:20,background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"12px",opacity:.85},onClick:()=>{yr(fe=>{const ae=[...fe];return ae[G]=fe[G]==="stack"?"volume":"stack",ae})},children:sn[G]==="stack"?"Volume":"Stack"}),sn[G]==="volume"&&Ne.jsxs("div",{style:{position:"absolute",top:8,left:70,zIndex:21,display:"flex",gap:"6px",background:"rgba(34,34,34,0.85)",borderRadius:"4px",padding:"2px 6px",alignItems:"center"},children:[Ne.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`);ae&&ae.setOrientation&&(ae.setOrientation("axial"),ae.render())},children:"Axial"}),Ne.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`);ae&&ae.setOrientation&&(ae.setOrientation("sagittal"),ae.render())},children:"Sagittal"}),Ne.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px"},onClick:()=>{const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`);ae&&ae.setOrientation&&(ae.setOrientation("coronal"),ae.render())},children:"Coronal"})]}),Ne.jsxs("button",{style:{position:"absolute",top:40,left:8,zIndex:20,background:"#111",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"13px",opacity:.85,marginTop:"4px",display:"flex",alignItems:"center",gap:"6px"},title:"Toggle Fullscreen",onClick:fe=>{fe.stopPropagation();const ae=Kr.current[G];document.fullscreenElement===ae?document.exitFullscreen():ae!=null&&ae.requestFullscreen?ae.requestFullscreen():ae!=null&&ae.webkitRequestFullscreen?ae.webkitRequestFullscreen():ae!=null&&ae.msRequestFullscreen&&ae.msRequestFullscreen()},onMouseEnter:()=>F(G),onMouseLeave:()=>F(null),children:[Ne.jsx("span",{style:{fontSize:"18px",lineHeight:1},children:"⛶"}),k===G&&Ne.jsx("span",{style:{marginLeft:6},children:document.fullscreenElement===Kr.current[G]?"Exit Fullscreen":"Fullscreen"})]}),sn[G]==="stack"&&Se&&(()=>{var $e;const fe=Lt[G],De=(Or.getAllAnnotations()||[]).filter(rt=>rt.metadata&&rt.metadata.referencedImageId&&fe.includes(rt.metadata.referencedImageId)&&rt.metadata.toolName!==os.toolName);if(!De.length)return null;const pe=ye.current,me=pe==null?void 0:pe.getViewport(`CT_${G}`),ke=(($e=me==null?void 0:me.getCurrentImageIdIndex)==null?void 0:$e.call(me))??0,Me=fe[ke],Ge=De.filter(rt=>rt.metadata.referencedImageId===Me),Ke=Ee[G];return Ne.jsxs("div",{style:{position:"absolute",left:"50%",bottom:60,transform:"translateX(-50%)",zIndex:30,display:"flex",gap:4,pointerEvents:"auto",alignItems:"center"},children:[Ne.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Previous Annotation","aria-label":"Previous Annotation",onClick:()=>{const rt=ye.current,ct=rt==null?void 0:rt.getViewport(`CT_${G}`);if(!ct||typeof ct.getCurrentImageIdIndex!="function")return;const ut=ct.getCurrentImageIdIndex(),mt=n7(ut,fe,De,-1);if(mt!==null&&typeof ct.setImageIdIndex=="function"){xo(ct.element,{imageIndex:mt}),_r(G,ct);const Rt=fe[mt],Zt=De.filter(gr=>gr.metadata.referencedImageId===Rt);Es(G,Zt.length>0?Zt[0].annotationUID:null)}},children:Ne.jsx("span",{"aria-hidden":"true",children:"◀"})}),Ne.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Next Annotation","aria-label":"Next Annotation",onClick:()=>{const rt=ye.current,ct=rt==null?void 0:rt.getViewport(`CT_${G}`);if(!ct||typeof ct.getCurrentImageIdIndex!="function")return;const ut=ct.getCurrentImageIdIndex(),mt=n7(ut,fe,De,1);if(mt!==null&&typeof ct.setImageIdIndex=="function"){xo(ct.element,{imageIndex:mt}),_r(G,ct);const Rt=fe[mt],Zt=De.filter(gr=>gr.metadata.referencedImageId===Rt);Es(G,Zt.length>0?Zt[0].annotationUID:null)}},children:Ne.jsx("span",{"aria-hidden":"true",children:"▶"})}),Ge.length>0&&Ne.jsx("div",{style:{display:"flex",gap:2,alignItems:"center"},children:Ge.map(rt=>Ne.jsxs("div",{style:{display:"flex",alignItems:"center",background:Ke===rt.annotationUID?"rgb(4, 225, 0)":"#444",color:Ke===rt.annotationUID?"#222":"#fff",borderRadius:"4px",padding:"2px 6px",marginRight:2,cursor:"pointer",border:Ke===rt.annotationUID?"2px solid #1976d2":"none",fontWeight:Ke===rt.annotationUID?"bold":"normal"},onClick:()=>Es(G,rt.annotationUID),children:[Ne.jsxs("span",{style:{marginRight:4},title:rt.metadata.toolName||"Annotation",children:[Ke===rt.annotationUID?"★ ":"",Ne.jsx("span",{style:{fontSize:14,lineHeight:1},children:ZI(rt.metadata.toolName)})]}),Ne.jsx("button",{style:{background:"transparent",color:"#f44336",border:"1px solid #f44336",borderRadius:3,width:16,height:16,fontSize:10,lineHeight:1,cursor:"pointer",marginLeft:4,display:"flex",alignItems:"center",justifyContent:"center",opacity:.95,padding:0},title:"Delete this annotation","aria-label":"Delete annotation",onClick:ct=>{ct.stopPropagation(),Zs(G,rt.annotationUID,Ge)},children:Ne.jsx("span",{"aria-hidden":"true",children:"✖"})})]},rt.annotationUID))})]})})(),Ne.jsx("div",{style:{position:"absolute",left:8,bottom:8,background:"rgba(0,0,0,0.7)",color:"#fff",padding:"6px 12px",borderRadius:"4px",fontSize:"14px",zIndex:10,pointerEvents:"none",minWidth:"120px",userSelect:"none"},children:sn[G]==="stack"?Ne.jsxs(Ne.Fragment,{children:[Ne.jsxs("div",{children:["Image: ",(Mt=gn[G])==null?void 0:Mt.index," / ",(Yt=gn[G])==null?void 0:Yt.total,(rn=gn[G])!=null&&rn.frameIndex&&((cn=gn[G])!=null&&cn.totalFrames)?Ne.jsxs(Ne.Fragment,{children:["   [Frame: ",(Z=gn[G])==null?void 0:Z.frameIndex," / ",(Y=gn[G])==null?void 0:Y.totalFrames,"]"]}):null]}),Ne.jsxs("div",{children:["WC: ",(we=gn[G])==null?void 0:we.windowCenter,"   WW: ",(We=gn[G])==null?void 0:We.windowWidth]}),ce&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsxs("div",{children:["Ori: ",((et=gn[G])==null?void 0:et.orientation)||"N/A"]}),((St=gn[G])==null?void 0:St.resolution)&&Ne.jsxs("div",{children:["Res: ",(pt=gn[G])==null?void 0:pt.resolution]}),((dt=gn[G])==null?void 0:dt.spacing)&&Ne.jsxs("div",{children:["Spacing: ",($=gn[G])==null?void 0:$.spacing]}),((K=gn[G])==null?void 0:K.focalPoint)&&Ne.jsxs("div",{children:["Pos: ",(R=gn[G])==null?void 0:R.focalPoint]})]})]}):Ne.jsxs("div",{children:["Slice: ",(U=gn[G])==null?void 0:U.index," / ",(X=gn[G])==null?void 0:X.total,((ge=gn[G])==null?void 0:ge.slicePosition)&&Ne.jsxs("span",{children:["   (",(xe=gn[G])==null?void 0:xe.slicePosition,")"]}),Ne.jsx("br",{}),"WC: ",(be=gn[G])==null?void 0:be.windowCenter,"   WW: ",(Re=gn[G])==null?void 0:Re.windowWidth,ce&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("br",{}),"Ori: ",((Fe=gn[G])==null?void 0:Fe.orientation)||"N/A",((Xe=gn[G])==null?void 0:Xe.resolution)&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("br",{}),"Res: ",(ht=gn[G])==null?void 0:ht.resolution]}),((It=gn[G])==null?void 0:It.spacing)&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("br",{}),"Spacing: ",(jt=gn[G])==null?void 0:jt.spacing]}),((kt=gn[G])==null?void 0:kt.focalPoint)&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("br",{}),"Pos: ",(In=gn[G])==null?void 0:In.focalPoint]})]})]})}),Ne.jsxs("div",{style:{position:"absolute",right:8,bottom:8,zIndex:110,pointerEvents:"auto",display:"flex",alignItems:"flex-end",gap:6},children:[Ne.jsx("button",{style:{background:Un[G]?"rgba(30,120,200,0.95)":"rgba(0,0,0,0.7)",color:"#fff",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"4px",fontSize:"12px",fontWeight:700,padding:"6px 9px",cursor:"pointer",minHeight:30},title:Un[G]?"Hide cine controls":"Show cine controls",onClick:fe=>{fe.stopPropagation(),Dn(ae=>{const De=[...ae],pe=!De[G];return De[G]=pe,pe||Fn(me=>{const ke=[...me];return ke[G]=!1,ke}),De})},children:"Cine"}),Ne.jsxs("div",{className:"preset-menu",style:{background:"rgba(0,0,0,0.7)",color:"#fff",borderRadius:"4px",fontSize:"14px",minWidth:"120px",overflow:"hidden",cursor:"pointer",position:"relative",boxShadow:Da[G]?"0 2px 8px rgba(0,0,0,0.3)":void 0,pointerEvents:"auto"},onClick:fe=>fe.stopPropagation(),children:[Ne.jsxs("div",{style:{padding:"6px 12px",fontWeight:"bold",userSelect:"none"},onClick:fe=>{fe.stopPropagation(),ki(ae=>{const De=[...ae];return De[G]=!De[G],De})},children:["Presets (",((_n=gn[G])==null?void 0:_n.modality)||"Unknown",")",Ne.jsx("span",{style:{float:"right",fontWeight:"normal"},children:Da[G]?"▲":"▼"})]}),Da[G]&&Ne.jsx("div",{className:"preset-menu-content",style:{background:"rgba(0,0,0,0.95)",borderRadius:"0 0 4px 4px",padding:"6px 0 6px 0",display:"flex",flexDirection:"column",zIndex:111,pointerEvents:"auto"},onClick:fe=>fe.stopPropagation(),children:(()=>{var De;const fe=qI((De=gn[G])==null?void 0:De.modality);let ae=0;return fe.map(pe=>{let me="";return pe.action==="reset"?me="0":pe.action==="preset"&&(ae+=1,me=String(ae)),Ne.jsxs("button",{title:me?`Shortcut: ${me}`:void 0,style:{display:"block",width:"100%",margin:"2px 0",background:pe.action==="preset"?"#333":"#444",color:"#fff",border:"none",borderRadius:"3px",cursor:"pointer",padding:pe.action==="preset"?"4px 0":"6px 0",fontSize:"13px",opacity:.9,fontWeight:pe.action==="preset"?"normal":"600"},onClick:ke=>{ke.stopPropagation(),io(G,pe),ki(Me=>{const Ge=[...Me];return Ge[G]=!1,Ge})},children:[pe.name,me?` (${me})`:""]},pe.name)})})()})]})]}),sn[G]==="stack"&&(Un[G]||(kr[G]||[]).length>1||((rr=gn[G])==null?void 0:rr.frameIndex)&&((ii=gn[G])==null?void 0:ii.totalFrames))&&Ne.jsxs("div",{style:{position:"absolute",left:"50%",bottom:8,transform:"translateX(-50%)",zIndex:36,background:"rgba(15,15,15,0.82)",border:"1px solid rgba(255,255,255,0.18)",borderRadius:8,padding:"6px 10px",display:"flex",alignItems:"center",gap:8,pointerEvents:"auto",minWidth:200,maxWidth:"72%"},onClick:fe=>fe.stopPropagation(),children:[Un[G]&&((hi=gn[G])==null?void 0:hi.total)>1&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("button",{style:{background:tn[G]?"#d32f2f":"#2e7d32",color:"#fff",border:"none",borderRadius:4,fontSize:12,padding:"4px 8px",cursor:"pointer"},title:tn[G]?"Pause cine":"Play cine",onClick:()=>{Fn(fe=>{const ae=[...fe];return ae[G]=!ae[G],ae})},children:tn[G]?"Pause":"Play"}),Ne.jsxs("label",{style:{color:"#ddd",fontSize:11,display:"flex",alignItems:"center",gap:4},children:["FPS",Ne.jsx("input",{type:"range",min:1,max:30,step:1,value:Math.max(1,Math.min(30,Math.round(Ei[G]||12))),onChange:fe=>{const ae=Number(fe.target.value);on(De=>{const pe=[...De];return pe[G]=ae,pe})}}),Ne.jsx("span",{style:{minWidth:22,textAlign:"right"},children:Math.round(Ei[G]||12)})]})]}),((Xc=gn[G])==null?void 0:Xc.frameIndex)&&((ca=gn[G])==null?void 0:ca.totalFrames)&&((Xf=gn[G])==null?void 0:Xf.totalFrames)>1&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("span",{style:{color:"#fff",fontSize:12,whiteSpace:"nowrap"},children:"Frame"}),Ne.jsx("input",{type:"range",min:1,max:((Ou=gn[G])==null?void 0:Ou.totalFrames)||1,step:1,value:Math.max(1,Math.min(((vg=gn[G])==null?void 0:vg.totalFrames)||1,((yg=gn[G])==null?void 0:yg.frameIndex)||1)),onChange:fe=>{var me;const ae=Number(fe.target.value),pe=(Lt[G]||[]).findIndex(ke=>{const Me=ke.match(/&frame=(\d+)/);return Me&&parseInt(Me[1],10)===ae});if(pe>=0){const ke=(me=ye.current)==null?void 0:me.getViewport(`CT_${G}`);ke&&typeof xo=="function"&&xo(ke.element,{imageIndex:pe})}},style:{width:100}}),Ne.jsxs("span",{style:{color:"#e0e0e0",fontSize:11,minWidth:50,textAlign:"right"},children:[(F8=gn[G])==null?void 0:F8.frameIndex," / ",(U8=gn[G])==null?void 0:U8.totalFrames]})]}),(kr[G]||[]).length>1&&Ne.jsxs(Ne.Fragment,{children:[Ne.jsx("span",{style:{color:"#fff",fontSize:12,whiteSpace:"nowrap"},children:"Group"}),Ne.jsx("input",{type:"range",min:0,max:Math.max(0,(kr[G]||[]).length-1),step:1,value:Math.max(0,Math.min((kr[G]||[]).length-1,Ze[G]||0)),onChange:fe=>{Mo(G,Number(fe.target.value))},style:{width:140}}),Ne.jsx("span",{style:{color:"#e0e0e0",fontSize:11,maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:((G8=(B8=kr[G])==null?void 0:B8[Ze[G]||0])==null?void 0:G8.label)||"Group",children:((z8=(W8=kr[G])==null?void 0:W8[Ze[G]||0])==null?void 0:z8.label)||"Group"})]})]}),sn[G]==="stack"&&Lt[G]&&Ne.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"14px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:35,display:Lt[G].length>0?"flex":"none",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:(()=>{const fe=Lt[G]||[],ae=fe.length;if(ae===0)return null;const De=ye.current,pe=De==null?void 0:De.getViewport(`CT_${G}`),me=pe&&typeof pe.getCurrentImageIdIndex=="function"?pe.getCurrentImageIdIndex():-1,ke=new Set(fe.map((ct,ut)=>ro[ct]?ut:-1).filter(ct=>ct>=0)),Me=fe.map(ct=>ct.startsWith("external:")?!0:!!Ct("imagePlaneModule",ct)||!!Ct("generalSeriesModule",ct)),Ge=Me.reduce((ct,ut)=>ct+(ut?1:0),0),Ke=fe.reduce((ct,ut,mt)=>ct+(ke.has(mt)?1:0),0),$e=Math.min(ae,180),rt=Array.from({length:$e},()=>({loaded:!1,viewed:!1,current:!1}));for(let ct=0;ct{var Bt;const mt=ct.currentTarget.getBoundingClientRect(),Rt=Math.min(mt.height,Math.max(0,ct.clientY-mt.top)),Zt=mt.height>0?Rt/mt.height:0,gr=Math.min(ae-1,Math.max(0,Math.round(Zt*(ae-1)))),ln=(Bt=ye.current)==null?void 0:Bt.getViewport(`CT_${G}`);ln&&typeof ln.setImageIdIndex=="function"&&sn[G]==="stack"&&(xo(ln.element,{imageIndex:gr}),_r(G,ln))},children:[rt.map((ct,ut)=>{let mt="#3f3f3f";return ct.loaded&&(mt="#2e7d32"),ct.viewed&&(mt="#1565c0"),ct.current&&(mt="#fbc02d"),Ne.jsx("div",{style:{width:"100%",height:`${100/$e}%`,minHeight:1,background:mt,opacity:ct.loaded||ct.viewed||ct.current?.95:.45,borderBottom:ut<$e-1?"1px solid #222":"none",pointerEvents:"none"}},ut)}),me>=0&&ae>$e&&Ne.jsx("div",{style:{position:"absolute",left:0,right:0,top:`${me/Math.max(1,ae-1)*100}%`,height:2,background:"#ffeb3b",boxShadow:"0 0 4px #ffeb3b",transform:"translateY(-1px)",pointerEvents:"none"}})]})})()}),sn[G]==="volume"&&(()=>{const fe=ye.current,ae=fe==null?void 0:fe.getViewport(`CT_${G}`);let De=0,pe=0;return ae&&typeof ae.getNumberOfSlices=="function"&&typeof ae.getSliceIndex=="function"&&(De=ae.getNumberOfSlices(),pe=ae.getSliceIndex()),De>1?Ne.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"12px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:30,display:"flex",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:Ne.jsx("div",{style:{width:"8px",height:"100%",maxHeight:"100%",minHeight:0,borderRadius:"6px",background:"#222",position:"relative",display:"flex",flexDirection:"column",justifyContent:"flex-start",boxShadow:"0 0 8px #2196f3cc",overflow:"hidden",cursor:"pointer"},onClick:me=>{const Me=me.currentTarget.getBoundingClientRect(),Ge=me.clientY-Me.top,Ke=Math.floor(Ge/Me.height*De),$e=ye.current,rt=$e==null?void 0:$e.getViewport(`CT_${G}`);rt&&(xo(rt.element,{imageIndex:Ke}),rt.render(),_r(G,rt))},children:Array.from({length:De}).map((me,ke)=>{const Me=ke===pe;return Ne.jsx("div",{style:{width:"100%",height:`${100/De}%`,minHeight:Me?1:0,background:Me?"linear-gradient(to right, #ffeb3b 60%, #ff9800 100%)":"#444",opacity:Me?.95:.4,transition:"background 0.3s, opacity 0.3s",borderBottom:ke1||!Lt[G]||Lt[G].length===0)&&Ne.jsx("div",{style:{position:"absolute",left:0,right:0,bottom:sn[G]==="stack"&&(Un[G]||(kr[G]||[]).length>1)?56:8,zIndex:20,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",width:"100%",background:"none",borderRadius:"0",padding:0},children:Ne.jsxs("div",{style:{position:"relative"},children:[Ne.jsxs("button",{onClick:fe=>{fe.stopPropagation(),J(ae=>ae===G?null:G)},style:{padding:"6px 12px",background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",cursor:"pointer",pointerEvents:"auto",fontSize:13},title:"Choose stack",children:[(()=>{const fe=Array.isArray(an)?an[G]:void 0,ae=typeof fe=="number"&&bt[fe]?bt[fe]:void 0,De=ae&&Array.isArray(ae.imageIds)?ae.imageIds:[],pe=ae?ae.name||(ae.caseId?`Case: ${ae.caseId}`:void 0):void 0;if(pe)return pe;if(De.length>0)return`Stack ${typeof fe=="number"?fe+1:"1"}`;const me=Lt[G]||[];return me.length>0?`Stack (${me.length} images)`:"No stack"})(),Ne.jsx("span",{style:{marginLeft:8,opacity:.8},children:H===G?"▲":"▼"})]}),H===G&&Ne.jsx("div",{ref:fe=>{fe&&fe.focus()},tabIndex:0,style:{position:"absolute",left:0,bottom:"110%",background:"#222",border:"1px solid #444",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",zIndex:100,minWidth:220,maxHeight:260,overflowY:"auto",overscrollBehavior:"contain",scrollbarWidth:"thin",padding:6},role:"listbox",onMouseDown:fe=>fe.stopPropagation(),onWheel:fe=>{var De;try{fe.stopPropagation()}catch{}try{fe.preventDefault()}catch{}const ae=fe.currentTarget;if(ae){const pe=fe.deltaY??((De=fe.nativeEvent)==null?void 0:De.deltaY)??0;ae.scrollTop+=pe}},onBlur:fe=>{const ae=fe.currentTarget;setTimeout(()=>{if(!ae){J(null);return}ae.contains(document.activeElement)||J(null)},0)},children:(()=>{const fe={};return bt.forEach((ae,De)=>{const pe=ae.studyId||ae.studyInstanceUID||"Unspecified";fe[pe]||(fe[pe]=[]),fe[pe].push({idx:De,stack:ae})}),Object.keys(fe).map(ae=>Ne.jsxs("div",{style:{marginBottom:6},children:[Ne.jsx("div",{style:{fontSize:12,color:"#aaa",padding:"4px 8px",fontWeight:700},children:ae==="Unspecified"?"Unspecified study":`Study: ${ae}`}),Ne.jsx("div",{children:fe[ae].map(({idx:De,stack:pe})=>{const me=Array.isArray(pe.imageIds)?pe.imageIds:[],ke=pe&&(pe.name||pe.caseId)?pe.name||`Case: ${pe.caseId}`:`Stack ${De+1}`,Me=me.length,Ge=!Array.isArray(me)||Me===0;return Ne.jsxs("button",{role:"option","aria-selected":!1,title:Ge?"Invalid stack descriptor":`${ke} — ${Me} image${Me===1?"":"s"}${pe!=null&&pe.caseId?` — case ${pe.caseId}`:""}`,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",width:"100%",padding:"8px 12px",background:"transparent",color:"#fff",border:"none",textAlign:"left",cursor:Ge?"not-allowed":"pointer"},onClick:Ke=>{if(Ke.stopPropagation(),Ge){Nt.warn(`Attempted to select invalid stack at index ${De}`,pe);return}bo(G,De).catch($e=>Nt.error("Failed to load stack:",$e)),J(null)},children:[Ne.jsx("div",{style:{fontWeight:"600",fontSize:13},children:ke}),Ne.jsxs("div",{style:{fontSize:12,opacity:.7},children:[Me," image",Me===1?"":"s",pe!=null&&pe.caseId?` • case ${pe.caseId}`:""]})]},De)})})]},ae))})()})]})})]},G))}const vt=[_f.toolName,Yd.toolName,Cc.toolName,ll.toolName],it=[{rows:1,cols:1},{rows:1,cols:2},{rows:2,cols:2}],ft=de&&Le;return Ne.jsxs("div",{ref:a,style:{position:"relative",inset:0,width:"100%",height:"100%",boxSizing:"border-box",background:ft?"#000":"#222",padding:ft?"0px":de?"6px":"12px",overflow:"hidden"},children:[ja&&Ne.jsx("div",{style:{position:"absolute",zIndex:3e3,top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.7)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontSize:28,fontWeight:"bold",letterSpacing:1},children:ja==="annotations"?"Loading Annotations...":ja==="displayset"?"Loading Display Set...":"Loading Viewer State..."}),oa&&Ne.jsxs("div",{style:{position:"fixed",top:12,left:12,right:12,zIndex:1e4,background:"#fff3cd",color:"#856404",border:"1px solid #ffeeba",padding:"10px 14px",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[Ne.jsxs("div",{style:{flex:1,fontSize:14},children:[Ne.jsx("strong",{children:"Graphics error:"})," The viewer encountered a WebGL/graphics error and may be unstable. Please reload the page.",zi?Ne.jsx("div",{style:{marginTop:6,fontSize:12,color:"#6b4f00"},children:zi}):null]}),Ne.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[Ne.jsx("button",{onClick:()=>window.location.reload(),style:{padding:"6px 10px"},children:"Reload"}),Ne.jsx("button",{onClick:()=>no(!1),style:{padding:"6px 10px"},children:"Dismiss"})]})]}),!_&&!ft&&Ne.jsx("button",{onClick:()=>T(!0),"aria-pressed":!1,title:"Open stacks",style:{position:"absolute",right:8,top:76,zIndex:120,width:24,height:42,background:"#1976d2",color:"#fff",border:"none",borderRadius:5,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",pointerEvents:"auto"},children:"▶"}),ft&&Ne.jsx("button",{onClick:()=>{Be(!1),B(null),j(!1),T(!1),q(null);const G=a.current;G&&document.fullscreenElement===G&&document.exitFullscreen&&document.exitFullscreen().catch(()=>{})},style:{position:"absolute",top:10,left:10,zIndex:3500,background:"rgba(0,0,0,0.78)",color:"#fff",border:"1px solid rgba(255,255,255,0.25)",borderRadius:8,padding:"8px 10px",fontSize:13,fontWeight:700},children:"Exit Viewer"}),ft&&Ne.jsxs("div",{style:{position:"absolute",top:10,right:10,zIndex:3500,display:"flex",gap:8},children:[Ne.jsx("button",{onClick:()=>T(G=>!G),style:{background:"rgba(0,0,0,0.78)",color:"#fff",border:"1px solid rgba(255,255,255,0.25)",borderRadius:8,padding:"8px 10px",fontSize:13,fontWeight:700},children:"Stacks"}),Ne.jsx("button",{onClick:()=>{O?j(!1):(j(!0),B(Ae??0))},style:{background:"rgba(0,0,0,0.78)",color:"#fff",border:"1px solid rgba(255,255,255,0.25)",borderRadius:8,padding:"8px 10px",fontSize:13,fontWeight:700},children:O?"Grid":"Focus"}),Ne.jsx("button",{onClick:()=>{Ta(G=>{const ue=it.findIndex(Ce=>Ce.rows===G.rows&&Ce.cols===G.cols);return it[(ue+1+it.length)%it.length]})},style:{background:"rgba(0,0,0,0.78)",color:"#fff",border:"1px solid rgba(255,255,255,0.25)",borderRadius:8,padding:"8px 10px",fontSize:13,fontWeight:700},children:"Layout"})]}),Ie&&Ne.jsxs("div",{style:{position:"fixed",left:Ie.x+14,top:Ie.y-18,zIndex:5e3,background:"rgba(21,101,192,0.92)",color:"#fff",border:"1px solid rgba(255,255,255,0.35)",borderRadius:8,padding:"5px 8px",fontSize:11,fontWeight:700,pointerEvents:"none",whiteSpace:"nowrap"},children:["Drop on viewport ",Ie.targetViewportIdx!==null?Ie.targetViewportIdx+1:"-"," (",Ie.zone,")"]}),!ft&&Ne.jsxs("div",{children:[Ne.jsx("button",{style:{position:"absolute",top:"50%",transform:"translateY(-50%)",left:ic,zIndex:200,width:V,height:V,background:"#222",color:"#fff",border:"none",borderRadius:"50%",fontWeight:"bold",cursor:"pointer",fontSize:"22px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",transition:"left 0.25s cubic-bezier(.4,2,.6,1), background 0.2s"},onClick:()=>bs(G=>!G),"aria-label":"Open menu",children:"☰"}),zc&&Ne.jsx("div",{style:{position:"absolute",top:0,left:0,width:L,height:"100%",background:"#222",color:"#fff",zIndex:199,boxShadow:"2px 0 12px rgba(0,0,0,0.3)",flexDirection:"column",padding:"24px 16px 16px 16px",display:"flex",overflow:"hidden"},children:Ne.jsxs("div",{style:{flex:1,minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column"},children:[Ne.jsxs("div",{style:{fontWeight:"bold",fontSize:18,marginBottom:24},children:["Menu",Ne.jsx("button",{style:{float:"right",background:"transparent",color:"#fff",border:"none",fontSize:"22px",cursor:"pointer"},onClick:()=>bs(!1),"aria-label":"Close menu",children:"×"})]}),Ne.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[Ne.jsxs("label",{style:{fontSize:13},children:[Ne.jsx("input",{type:"radio",name:"folderLoadMode",value:"add",checked:nc==="add",onChange:()=>rc("add")})," Add (append)"]}),Ne.jsxs("label",{style:{fontSize:13},children:[Ne.jsx("input",{type:"radio",name:"folderLoadMode",value:"replace",checked:nc==="replace",onChange:()=>rc("replace")})," Replace all"]})]}),Ne.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:$c,children:"Load DICOM Folder"}),Ne.jsx("input",{ref:sa,type:"file",style:{display:"none"},multiple:!0,onChange:Ds}),Ne.jsx("input",{ref:Oa,type:"file",style:{display:"none"},multiple:!0,onChange:Ds,accept:".dcm,application/dicom"}),Ne.jsxs("div",{style:{marginBottom:"18px",display:"flex",alignItems:"center",gap:"8px"},children:[Ne.jsx("input",{type:"checkbox",id:"orderBySliceLocation",checked:qr,onChange:G=>Xs(G.target.checked),style:{accentColor:"#666"}}),Ne.jsx("label",{htmlFor:"orderBySliceLocation",style:{fontSize:"15px",cursor:"pointer"},children:"Order by Slice Location"})]}),Ne.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:Nl,children:"Show DICOM Metadata"}),Ne.jsxs("button",{style:{padding:"10px 18px",background:$i?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Fc(G=>!G),children:[$i?"Disable":"Enable"," Cross Reference Lines"]}),Ne.jsxs("button",{style:{padding:"10px 18px",background:Ni?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Cs(G=>!G),children:[Ni?"Disable":"Enable"," Reference Lines"]}),Ne.jsx("button",{onClick:Io,style:{margin:8,padding:8},children:"Sort All Viewports by Slice Location"}),Ne.jsx("button",{style:{padding:"10px 18px",background:Oo?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Xa(G=>!G),children:Oo?"Disable Alt Key for Reference Cursors (Shift always works)":"Enable Alt Key for Reference Cursors (Shift always works)"}),Ne.jsxs("button",{style:{padding:"10px 18px",background:Se?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>nt(G=>!G),children:[Se?"Hide":"Show"," Annotation Navigation"]}),Ne.jsxs("button",{style:{padding:"10px 18px",background:ce?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>Ot(G=>!G),children:[ce?"Disable":"Enable"," Volume Diagnostics"]})]})})]}),!ft&&Ne.jsxs("div",{ref:A,className:"grid-menu-hover-container",style:{position:"absolute",top:Ea||oe?8:-18,left:"50%",transform:"translateX(-50%)",zIndex:100,display:"flex",flexDirection:"row",alignItems:"flex-start",gap:8,width:"auto",pointerEvents:"auto",transition:"top 180ms ease",paddingTop:28,marginTop:-28,paddingBottom:12},onMouseEnter:()=>ve(!0),onMouseLeave:()=>{Ea||ve(!1)},children:[Ne.jsxs("button",{style:{height:40,padding:"6px 12px 6px 10px",background:"#222",color:"#fff",border:"none",borderRadius:"0 0 4px 4px",fontWeight:"bold",cursor:"pointer",fontSize:"14px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",display:"inline-flex",alignItems:"center",gap:8},title:"Toggle viewer fullscreen",onFocus:()=>ve(!0),onClick:()=>{ve(!0),Hc()},children:[Ne.jsx("span",{style:{fontSize:16,lineHeight:1},children:"⛶"}),Ne.jsx("span",{children:"Fullscreen"})]}),Ne.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"stretch"},children:[Ne.jsxs("button",{className:"grid-menu-btn",style:{height:40,padding:"6px 14px 6px 10px",background:"#222",color:"#fff",border:"none",borderRadius:"0 0 4px 4px",fontWeight:"bold",cursor:"pointer",fontSize:"14px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",display:"inline-flex",alignItems:"center",gap:10,justifyContent:"space-between",minWidth:136},onFocus:()=>ve(!0),onClick:()=>{ve(!0),qa(G=>!G)},tabIndex:0,children:[Ne.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[Ne.jsx("span",{style:{display:"grid",gridTemplateColumns:`repeat(${Xt.cols}, 5px)`,gridTemplateRows:`repeat(${Xt.rows}, 5px)`,gap:2,padding:1},children:Array.from({length:Xt.rows*Xt.cols}).map((G,ue)=>Ne.jsx("span",{style:{width:5,height:5,borderRadius:1,background:"#90caf9",display:"block"}},ue))}),Ne.jsxs("span",{children:[Xt.rows,"x",Xt.cols]})]}),Ne.jsx("span",{style:{opacity:.8},children:Ea?"▲":"▼"})]}),Ea&&Ne.jsx("div",{style:{position:"absolute",top:"calc(100% + 8px)",right:0,background:"#222",color:"#fff",borderRadius:"6px",boxShadow:"0 2px 12px rgba(0,0,0,0.4)",padding:"12px",display:"grid",gridTemplateColumns:"repeat(3, minmax(68px, 1fr))",gap:"8px",zIndex:200,pointerEvents:"auto"},onMouseDown:G=>G.stopPropagation(),children:fi.map(G=>Ne.jsxs("button",{style:{minWidth:"68px",height:"54px",background:G.rows===Xt.rows&&G.cols===Xt.cols?"#444":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"13px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6},onClick:()=>{Is(),Ta({rows:G.rows,cols:G.cols}),qa(!1),ve(!1)},children:[Ne.jsx("span",{style:{display:"grid",gridTemplateColumns:`repeat(${G.cols}, 6px)`,gridTemplateRows:`repeat(${G.rows}, 6px)`,gap:2},children:Array.from({length:G.rows*G.cols}).map((ue,Te)=>Ne.jsx("span",{style:{width:6,height:6,borderRadius:1,background:"#90caf9",display:"block"}},Te))}),Ne.jsxs("span",{children:[G.rows,"x",G.cols]})]},`${G.rows}x${G.cols}`))})]})]}),Ne.jsxs("div",{style:{display:"flex",flexDirection:"row",height:ft?"100%":"calc(100% - 48px)",gap:ft?0:8},children:[Ne.jsxs("div",{style:{flex:1,display:"grid",margin:ft?0:3,gridTemplateRows:`repeat(${Xt.rows}, 1fr)`,gridTemplateColumns:`repeat(${Xt.cols}, 1fr)`,gap:"5px",minHeight:0,minWidth:0,zIndex:1,position:"relative"},children:[gt,!ft&&Ne.jsx("button",{style:{position:"absolute",top:8,right:8,zIndex:2600,padding:"6px 12px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer",opacity:.85,userSelect:"none"},onClick:()=>S(!0),children:"Settings"}),ft&&Ne.jsx("div",{style:{position:"absolute",left:0,right:0,bottom:10,zIndex:3200,display:"flex",justifyContent:"center",pointerEvents:"none"},children:Ne.jsx("div",{style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:6,background:"rgba(0,0,0,0.74)",border:"1px solid rgba(255,255,255,0.2)",borderRadius:10,padding:"8px 8px",maxWidth:"95%",overflowX:"auto"},children:vt.map(G=>{var Ce;const ue=Vi.Primary===G,Te=((Ce=dd.find(he=>he.value===G))==null?void 0:Ce.label)||G;return Ne.jsx("button",{title:Te,onClick:()=>jc("Primary",G),style:{minWidth:46,height:42,borderRadius:8,border:ue?"1px solid #90caf9":"1px solid rgba(255,255,255,0.22)",background:ue?"#1565c0":"#1f1f1f",color:"#fff",fontSize:18,fontWeight:700,padding:"0 8px"},children:ZI(G)},G)})})})]}),Ne.jsxs("div",{style:ft?{position:"absolute",left:8,right:8,bottom:_?62:-420,height:"min(48vh, 420px)",transition:"bottom 220ms ease",display:"flex",flexDirection:"column",pointerEvents:_?"auto":"none",overflow:"hidden",zIndex:3450,borderRadius:12,border:"1px solid #2f3336",boxShadow:"0 6px 24px rgba(0,0,0,0.45)",background:"#1f2428"}:{width:_?E:0,transition:"width 220ms ease",display:"flex",flexDirection:"column",pointerEvents:_?"auto":"none",overflow:"hidden",position:"relative"},children:[_&&!ft&&Ne.jsx("div",{onMouseDown:kl,title:"Resize stacks panel",style:{position:"absolute",left:0,top:0,width:8,height:"100%",cursor:"col-resize",zIndex:2800,background:"linear-gradient(to right, rgba(100,181,246,0.25), rgba(100,181,246,0))"}}),Ne.jsx("div",{style:{pointerEvents:"auto",width:"100%",height:"100%"},children:Ne.jsxs("div",{style:{height:"100%",width:"100%",background:"#1f2428",color:"#fff",boxShadow:"0 2px 14px rgba(0,0,0,0.45)",borderLeft:"1px solid #2f3336",transform:"translateX(0)",transition:"transform 220ms ease",display:"flex",flexDirection:"column",overflow:"hidden"},children:[Ne.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",borderBottom:"1px solid #2b2f31"},children:[Ne.jsx("div",{style:{fontWeight:700},children:"Stacks"}),Ne.jsxs("div",{style:{fontSize:12,color:"#9bb4c8"},children:["Active VP: ",Ae!==null?Ae+1:"-"]}),Ne.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[ft&&Ne.jsxs("button",{title:"Toggle stack drop mode",onClick:()=>{re(G=>G==="center"?"right":G==="right"?"bottom":"center")},style:{background:"transparent",color:"#90caf9",border:"1px solid #335",borderRadius:6,padding:"4px 8px",cursor:"pointer",fontSize:12},children:["Drop: ",Q]}),Ne.jsx("button",{title:"Close",onClick:()=>{T(!1)},style:{background:"transparent",color:"#fff",border:"none",cursor:"pointer",fontSize:16},children:"×"})]})]}),Ne.jsx("div",{style:{overflowY:"auto",padding:8,flex:1},children:bt.length===0?Ne.jsx("div",{style:{color:"#999",padding:12},children:"No stacks available"}):Ne.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:bt.map((G,ue)=>{const Te=Array.isArray(G.imageIds)?G.imageIds:[],Ce=G.name||(G.caseId?`Case: ${G.caseId}`:`Stack ${ue+1}`),he=Te.length,fe=!Array.isArray(Te)||he===0,ae=an.includes(ue),De=Ae!==null&&an[Ae]===ue,pe=Math.floor(Te.length/2);return Te[pe]||Te[0],Ne.jsxs("div",{draggable:!fe,onDragStart:me=>{fe||(yt(ue),$t(null),me.dataTransfer.setData("text/stack-idx",String(ue)),me.dataTransfer.effectAllowed="copy")},onDragEnd:()=>{yt(null),$t(null)},onClick:()=>{if(Date.now(){if(fe||Hr[ue]||Ai.current[ue])return;const me=Math.floor(Te.length/2),ke=Te[me]||Te[0]||null;ke&&_a(ue,ke)},onMouseEnter:()=>{if(fe||Hr[ue]||Ai.current[ue])return;const me=Math.floor(Te.length/2),ke=Te[me]||Te[0]||null;ke&&_a(ue,ke)},style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 10px",background:De?"#0d47a1":ae?"#1976d2":"transparent",color:ae?"#fff":"#ddd",border:De?"1px solid #64b5f6":"1px solid transparent",borderRadius:6,cursor:fe?"not-allowed":"pointer"},children:[Ne.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(()=>{const me=Hr[ue],Me=(me&&me!=="BROKEN"?me:null)||null;return Me?Ne.jsx("img",{"data-thumb-stack":ue,src:Me,alt:Ce,style:{width:56,height:56,objectFit:"cover",borderRadius:4,background:"#111"},onError:()=>{Nt.warn("Thumbnail failed to load for stack",ue,Me),li(ue,"BROKEN")}}):Ne.jsx("div",{style:{width:56,height:56,borderRadius:4,background:"#111",display:"flex",alignItems:"center",justifyContent:"center",color:"#777"},children:"No Img"})})(),Ne.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[Ne.jsx("div",{style:{fontWeight:600},children:Ce}),Ne.jsxs("div",{style:{fontSize:12,opacity:.7},children:[he," img",he===1?"":"s"]})]})]}),Ne.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:4},children:[Ne.jsx("div",{style:{fontSize:12,opacity:.8},children:G.studyId||""}),De&&Ne.jsx("div",{style:{fontSize:11,color:"#bbdefb",fontWeight:700},children:"ACTIVE"}),ft&&!fe&&Ne.jsxs("div",{style:{display:"flex",gap:6},children:[Ne.jsx("button",{onClick:me=>{me.stopPropagation(),bo(Ae??0,ue),T(!1)},style:{background:"#1565c0",color:"#fff",border:"none",borderRadius:4,padding:"3px 7px",fontSize:11,cursor:"pointer"},children:"Load"}),Ne.jsx("button",{onClick:me=>{me.stopPropagation(),!(Date.now(){Vl(ue,me)},style:{background:z===ue?"#2e7d32":"#444",color:"#fff",border:"none",borderRadius:4,padding:"3px 7px",fontSize:11,cursor:"pointer"},children:z===ue?"Armed":"Drag"})]})]})]},ue)})})})]})})]})]}),C&&Ne.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.4)",zIndex:1e3,display:"flex",alignItems:"flex-start",justifyContent:"center",overflowY:"auto",padding:"16px 12px"},onClick:()=>S(!1),children:Ne.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",minHeight:"180px",maxWidth:"min(960px, 96vw)",maxHeight:"calc(100vh - 32px)",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative",overflowY:"auto",margin:"0 auto"},onClick:G=>G.stopPropagation(),children:[Ne.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"Settings"}),Ne.jsxs("div",{style:{marginBottom:"24px"},children:[Ne.jsx("div",{style:{marginBottom:12,fontWeight:"bold"},children:"Mouse Button Tool Bindings"}),t7.map(G=>Ne.jsxs("div",{style:{marginBottom:10},children:[Ne.jsxs("label",{style:{marginRight:8},children:[G.label," Button:"]}),Ne.jsx("select",{value:Vi[G.value],onChange:ue=>di(Te=>({...Te,[G.value]:ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:dd.map(ue=>Ne.jsx("option",{value:ue.value,title:ue.label,children:`${ue.icon?`${ue.icon} `:""}${ue.label}`},ue.value))})]},G.value)),Ne.jsxs("div",{style:{margin:"12px 0"},children:[Ne.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>Do(G=>!G),children:[Sa?"Hide":"Show"," Advanced Mouse Bindings"]}),Sa&&Ne.jsx("div",{style:{marginTop:8},children:z2.slice(3).map(G=>Ne.jsxs("div",{style:{marginBottom:10},children:[Ne.jsxs("label",{style:{marginRight:8},children:[G.label,":"]}),Ne.jsxs("select",{value:Vi[G.value]||"",onChange:ue=>di(Te=>({...Te,[G.value]:ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[Ne.jsx("option",{value:"",children:"(None)"}),dd.map(ue=>Ne.jsx("option",{value:ue.value,title:ue.label,children:`${ue.icon?`${ue.icon} `:""}${ue.label}`},ue.value))]})]},G.value))})]}),Ne.jsx("div",{style:{margin:"18px 0 8px 0",fontWeight:"bold"},children:"Ctrl + Mouse Button Tool Bindings"}),t7.map(G=>Ne.jsxs("div",{style:{marginBottom:10},children:[Ne.jsxs("label",{style:{marginRight:8},children:[G.label," + Ctrl:"]}),Ne.jsxs("select",{value:bi[G.value]||"",onChange:ue=>Za(Te=>({...Te,[G.value]:ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[Ne.jsx("option",{value:"",children:"(None)"}),dd.map(ue=>Ne.jsx("option",{value:ue.value,title:ue.label,children:`${ue.icon?`${ue.icon} `:""}${ue.label}`},ue.value))]})]},G.value+"_ctrl")),Ne.jsxs("div",{style:{margin:"12px 0"},children:[Ne.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>Ha(G=>!G),children:[Ss?"Hide":"Show"," Advanced Ctrl + Mouse Bindings"]}),Ss&&Ne.jsx("div",{style:{marginTop:8},children:z2.slice(3).map(G=>Ne.jsxs("div",{style:{marginBottom:10},children:[Ne.jsxs("label",{style:{marginRight:8},children:[G.label," + Ctrl:"]}),Ne.jsxs("select",{value:bi[G.value]||"",onChange:ue=>Za(Te=>({...Te,[G.value]:ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[Ne.jsx("option",{value:"",children:"(None)"}),dd.map(ue=>Ne.jsx("option",{value:ue.value,title:ue.label,children:`${ue.icon?`${ue.icon} `:""}${ue.label}`},ue.value))]})]},G.value+"_ctrl"))})]})]}),Ne.jsxs("div",{style:{marginTop:8,paddingTop:16,borderTop:"1px solid #333"},children:[Ne.jsx("div",{style:{marginBottom:10,fontWeight:"bold"},children:"Stack Grouping"}),Ne.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",marginBottom:10},children:[Ne.jsx("input",{type:"checkbox",checked:y,onChange:G=>m(G.target.checked)}),"Enable advanced DWI/time/echo grouping"]}),Ne.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,opacity:y?1:.6},children:hp.map(G=>Ne.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:y?"pointer":"default"},title:G.description,children:[Ne.jsx("input",{type:"checkbox",disabled:!y,checked:!!w[G.id],onChange:ue=>{const Te=ue.target.checked;x(Ce=>({...Ce,[G.id]:Te}))}}),G.label]},G.id))})]}),Ne.jsxs("div",{style:{marginTop:8,paddingTop:16,borderTop:"1px solid #333"},children:[Ne.jsx("div",{style:{marginBottom:10,fontWeight:"bold"},children:"Logging"}),Ne.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,marginBottom:10,flexWrap:"wrap"},children:[Ne.jsxs("div",{children:[Ne.jsx("label",{style:{marginRight:8},children:"Level:"}),Ne.jsx("select",{value:h,onChange:G=>g(v5(G.target.value)),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:_Se.map(G=>Ne.jsx("option",{value:G.value,children:G.label},G.value))})]}),Ne.jsxs("div",{children:[Ne.jsx("label",{style:{marginRight:8},children:"Format:"}),Ne.jsx("select",{value:p,onChange:G=>v(Wp(G.target.value)),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:SSe.map(G=>Ne.jsx("option",{value:G.value,children:G.label},G.value))})]})]})]}),Ne.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>S(!1),"aria-label":"Close",children:"×"})]})}),Al&&Ne.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"rgba(0,0,0,0.5)",zIndex:2e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>Ts(!1),children:Ne.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",maxWidth:"80vw",maxHeight:"80vh",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative",overflow:"auto"},onClick:G=>G.stopPropagation(),children:[Ne.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"DICOM Metadata"}),Bc,Ne.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>Ts(!1),"aria-label":"Close",children:"×"})]})})]})}function bSe(t){Nt.debug("Setting up tools...",t),Yi(Cc),Yi(Yd),Yi(_f),Yi(ll),Yi(Vh),Yi(Ff),Yi(_u),Yi(Uf),Yi(Su),Yi(Jd),Yi(Vf),Yi(Il),Yi(Fh),Yi(os),Yi(al),Yi(Ld),Yi(Gh);let e=wi(t);return e||(e=Rk(t),e.addTool(Yd.toolName),e.addTool(Cc.toolName),e.addTool(ll.toolName),e.addTool(_f.toolName,{loop:!1}),e.addTool(Vh.toolName),e.addTool(Ff.toolName),e.addTool(Gh.toolName,{getTextCallback:()=>""}),e.addTool(Uf.toolName),e.addTool(_u.toolName,{statsCalculator:()=>null}),e.addTool(Su.toolName,{calculateStats:!1,getTextCallback:()=>""}),e.addTool(Jd.toolName,{getTextCallback:()=>""}),e.addTool(Vf.toolName,{calculateStats:!1}),e.addTool(Il.toolName,{}),e.addTool(Fh.toolName,{}),e.addTool(Ld.toolName),e.addTool(os.toolName)),e}function n7(t,e,r,n){if(!r.length||!e.length)return null;const i=r.map(o=>e.findIndex(a=>a===o.metadata.referencedImageId)).filter(o=>o!==-1).sort((o,a)=>o-a);if(!i.length)return null;if(n===1){for(let o of i)if(o>t)return o;return i[0]}else{for(let o=i.length-1;o>=0;o--)if(i[o]`wadouri:/test_images/stack2/IMG${r+1}.dcm`),Array.from({length:25},(e,r)=>`wadouri:/test_images/stack5/IMG${r+1}.dcm`),Array.from({length:26},(e,r)=>`wadouri:/test_images/stack3/IMG${r+1}.dcm`)]}const MC=new WeakMap,zp=LW.child("main"),ISe=t=>{const e=t.trim();return!e||e.startsWith("external:")||e.startsWith("wadors:")?e:e.startsWith("wadouri:")?`wadouri:${e.slice(8).replace(/^:+/,"")}`:`wadouri:${e.replace(/^:+/,"")}`},Km=t=>t.map(ISe),r7=t=>t?{imageIds:Km(t)}:{imageIds:[]},OSe=t=>{if(!t)return[];if(Array.isArray(t)&&t.length>0&&typeof t[0]=="string")return[r7(t)];if(!Array.isArray(t))return[];const e=[];return t.forEach((r,n)=>{if(r&&typeof r=="object"&&Array.isArray(r.stacks)){const i=r.caseId||r.caseUID||r.case||void 0,o=r.studyId||r.studyUID||r.studyInstanceUID||void 0;r.stacks.forEach((a,s)=>{let c=[];if(Array.isArray(a)?c=a:Array.isArray(a.imageIds)?c=a.imageIds:Array.isArray(a.i)&&(c=a.i),!Array.isArray(c)||c.length===0||!c.every(l=>typeof l=="string")){zp.warn(`data-named-stacks: skipping invalid nested stack at parsed[${n}].stacks[${s}]`,a);return}e.push({imageIds:Km(c),name:a.name||a.label||void 0,caseId:i,studyId:a.studyId||o})});return}if(r&&typeof r=="object"&&(Array.isArray(r.imageIds)||Array.isArray(r.i))){const i=Array.isArray(r.imageIds)?r.imageIds:r.i;if(!Array.isArray(i)||i.length===0||!i.every(o=>typeof o=="string")){zp.warn(`data-named-stacks: skipping invalid stack object at parsed[${n}]`,r);return}e.push({imageIds:Km(i),name:r.name||r.label||void 0,caseId:r.caseId||r.caseUID||void 0,studyId:r.studyId||r.studyUID||r.studyInstanceUID||void 0});return}if(Array.isArray(r)&&r.length>0&&typeof r[0]=="string"){e.push(r7(r));return}zp.warn(`data-named-stacks: unknown or invalid entry at parsed[${n}] - skipping`,r)}),e},MSe=t=>JSON.stringify({id:t.id||"",empty:t.getAttribute("data-empty")||"",namedStacks:t.getAttribute("data-named-stacks")||"",images:t.getAttribute("data-images")||"",autoCache:t.getAttribute("data-auto-cache-stack")||"",annotation:t.getAttribute("data-annotationjson")||"",viewerState:t.getAttribute("data-viewerstate")||""}),i7=(t,e)=>!(e!=null&&e.containerIds)||e.containerIds.length===0?!0:e.containerIds.includes(t.id||""),PSe=(t,e)=>{var s,c,l;const r=t.getAttribute("data-log-level"),n=t.getAttribute("data-log-debug"),i=t.getAttribute("data-log-format");let o;r!==null?o=v5(r):(s=e==null?void 0:e.logging)!=null&&s.minLevel?o=e.logging.minLevel:n!==null?o=a_(n):((c=e==null?void 0:e.logging)==null?void 0:c.debug)!==void 0?o=a_(e.logging.debug):o="warn";const a=Wp(i??((l=e==null?void 0:e.logging)==null?void 0:l.format));return{minLevel:o,format:a}},o7=(t,e,r)=>{const n=MSe(t),i=MC.get(t),o=PSe(t,r);if(i&&!(r!=null&&r.force)&&i.signature===n)return;i&&(i.root.unmount(),MC.delete(t)),w8(o);const a=yM(t);a.render(Ne.jsx(ESe,{container_id:t.id||"",imageStacks:e,autoCacheStack:t.getAttribute("data-auto-cache-stack")==="true"||t.getAttribute("data-auto-cache-stack")==="1",annotationJson:t.getAttribute("data-annotationjson")||void 0,viewerState:t.getAttribute("data-viewerstate")||void 0,initialLoggerConfig:o})),MC.set(t,{root:a,signature:n})};function x8(t){document.querySelectorAll(".dicom-viewer-test-root").forEach(n=>{if(!i7(n,t))return;o7(n,()=>DSe(),t)}),document.querySelectorAll(".dicom-viewer-root").forEach(n=>{if(!i7(n,t))return;let i;const o=n.getAttribute("data-empty")==="true",a=n.getAttribute("data-named-stacks"),s=n.getAttribute("data-images");if(o)i=()=>Promise.resolve([]);else if(a){let c;try{c=JSON.parse(a)}catch(f){zp.error("Invalid data-named-stacks JSON:",f),c=[]}const l=OSe(c);i=()=>Promise.resolve(l)}else if(s){let c;try{c=JSON.parse(s)}catch(l){zp.error("Invalid data-images JSON:",l),c=[]}Array.isArray(c)&&c.length>0&&typeof c[0]=="string"?i=()=>Promise.resolve([Km(c)]):Array.isArray(c)?i=()=>Promise.resolve(c.map(l=>Array.isArray(l)?Km(l):[])):i=()=>Promise.resolve([[]])}else i=()=>Promise.resolve([]);o7(n,i,t)})}x8();window.mountDicomViewers=x8;window.remountDicomViewer=t=>{x8({force:!0,containerIds:[t]})};window.setDicomViewerLogging=t=>{const e=t.minLevel?v5(t.minLevel):t.debug!==void 0?a_(t.debug):void 0;w8({minLevel:e,format:t.format?Wp(t.format):void 0})};window.getDicomViewerLogging=()=>m5();