var Tg=t=>{throw TypeError(t)};var Xh=(t,e,s)=>e.has(t)||Tg("Cannot "+s);var Pg=(t,e,s)=>(Xh(t,e,"read from private field"),s?s.call(t):e.get(t)),Zh=(t,e,s)=>e.has(t)?Tg("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),zg=(t,e,s,n)=>(Xh(t,e,"write to private field"),n?n.call(t,s):e.set(t,s),s),ep=(t,e,s)=>(Xh(t,e,"access private method"),s);function zw(t,e){for(var s=0;sn[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();function Aw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var n_={exports:{}},oh={},r_={exports:{}},ve={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var id=Symbol.for("react.element"),Rw=Symbol.for("react.portal"),Fw=Symbol.for("react.fragment"),Lw=Symbol.for("react.strict_mode"),Iw=Symbol.for("react.profiler"),Ow=Symbol.for("react.provider"),Dw=Symbol.for("react.context"),Mw=Symbol.for("react.forward_ref"),Vw=Symbol.for("react.suspense"),Hw=Symbol.for("react.memo"),$w=Symbol.for("react.lazy"),Ag=Symbol.iterator;function Ww(t){return t===null||typeof t!="object"?null:(t=Ag&&t[Ag]||t["@@iterator"],typeof t=="function"?t:null)}var i_={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},a_=Object.assign,o_={};function Hc(t,e,s){this.props=t,this.context=e,this.refs=o_,this.updater=s||i_}Hc.prototype.isReactComponent={};Hc.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};Hc.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function l_(){}l_.prototype=Hc.prototype;function ex(t,e,s){this.props=t,this.context=e,this.refs=o_,this.updater=s||i_}var tx=ex.prototype=new l_;tx.constructor=ex;a_(tx,Hc.prototype);tx.isPureReactComponent=!0;var Rg=Array.isArray,c_=Object.prototype.hasOwnProperty,sx={current:null},u_={key:!0,ref:!0,__self:!0,__source:!0};function d_(t,e,s){var n,r={},i=null,a=null;if(e!=null)for(n in e.ref!==void 0&&(a=e.ref),e.key!==void 0&&(i=""+e.key),e)c_.call(e,n)&&!u_.hasOwnProperty(n)&&(r[n]=e[n]);var l=arguments.length-2;if(l===1)r.children=s;else if(1>>1,te=R[G];if(0>>1;Gr($,z))eer(re,$)?(R[G]=re,R[ee]=z,G=ee):(R[G]=$,R[K]=z,G=K);else if(eer(re,z))R[G]=re,R[ee]=z,G=ee;else break e}}return U}function r(R,U){var z=R.sortIndex-U.sortIndex;return z!==0?z:R.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;t.unstable_now=function(){return i.now()}}else{var a=Date,l=a.now();t.unstable_now=function(){return a.now()-l}}var c=[],u=[],d=1,f=null,h=3,g=!1,v=!1,_=!1,k=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,p=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(R){for(var U=s(u);U!==null;){if(U.callback===null)n(u);else if(U.startTime<=R)n(u),U.sortIndex=U.expirationTime,e(c,U);else break;U=s(u)}}function N(R){if(_=!1,y(R),!v)if(s(c)!==null)v=!0,pe(j);else{var U=s(u);U!==null&&D(N,U.startTime-R)}}function j(R,U){v=!1,_&&(_=!1,x(T),T=-1),g=!0;var z=h;try{for(y(U),f=s(c);f!==null&&(!(f.expirationTime>U)||R&&!q());){var G=f.callback;if(typeof G=="function"){f.callback=null,h=f.priorityLevel;var te=G(f.expirationTime<=U);U=t.unstable_now(),typeof te=="function"?f.callback=te:f===s(c)&&n(c),y(U)}else n(c);f=s(c)}if(f!==null)var Z=!0;else{var K=s(u);K!==null&&D(N,K.startTime-U),Z=!1}return Z}finally{f=null,h=z,g=!1}}var w=!1,B=null,T=-1,O=5,C=-1;function q(){return!(t.unstable_now()-CR||125G?(R.sortIndex=z,e(u,R),s(c)===null&&R===s(u)&&(_?(x(T),T=-1):_=!0,D(N,z-G))):(R.sortIndex=te,e(c,R),v||g||(v=!0,pe(j))),R},t.unstable_shouldYield=q,t.unstable_wrapCallback=function(R){var U=h;return function(){var z=h;h=U;try{return R.apply(this,arguments)}finally{h=z}}}})(x_);m_.exports=x_;var nS=m_.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var rS=m,Wt=nS;function Y(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,s=1;s"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Hp=Object.prototype.hasOwnProperty,iS=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Lg={},Ig={};function aS(t){return Hp.call(Ig,t)?!0:Hp.call(Lg,t)?!1:iS.test(t)?Ig[t]=!0:(Lg[t]=!0,!1)}function oS(t,e,s,n){if(s!==null&&s.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return n?!1:s!==null?!s.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function lS(t,e,s,n){if(e===null||typeof e>"u"||oS(t,e,s,n))return!0;if(n)return!1;if(s!==null)switch(s.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function Tt(t,e,s,n,r,i,a){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=n,this.attributeNamespace=r,this.mustUseProperty=s,this.propertyName=t,this.type=e,this.sanitizeURL=i,this.removeEmptyString=a}var pt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){pt[t]=new Tt(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];pt[e]=new Tt(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){pt[t]=new Tt(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){pt[t]=new Tt(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){pt[t]=new Tt(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){pt[t]=new Tt(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){pt[t]=new Tt(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){pt[t]=new Tt(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){pt[t]=new Tt(t,5,!1,t.toLowerCase(),null,!1,!1)});var rx=/[\-:]([a-z])/g;function ix(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(rx,ix);pt[e]=new Tt(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(rx,ix);pt[e]=new Tt(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(rx,ix);pt[e]=new Tt(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){pt[t]=new Tt(t,1,!1,t.toLowerCase(),null,!1,!1)});pt.xlinkHref=new Tt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){pt[t]=new Tt(t,1,!1,t.toLowerCase(),null,!0,!0)});function ax(t,e,s,n){var r=pt.hasOwnProperty(e)?pt[e]:null;(r!==null?r.type!==0:n||!(2l||r[a]!==i[l]){var c=` `+r[a].replace(" at new "," at ");return t.displayName&&c.includes("")&&(c=c.replace("",t.displayName)),c}while(1<=a&&0<=l);break}}}finally{np=!1,Error.prepareStackTrace=s}return(t=t?t.displayName||t.name:"")?pu(t):""}function cS(t){switch(t.tag){case 5:return pu(t.type);case 16:return pu("Lazy");case 13:return pu("Suspense");case 19:return pu("SuspenseList");case 0:case 2:case 15:return t=rp(t.type,!1),t;case 11:return t=rp(t.type.render,!1),t;case 1:return t=rp(t.type,!0),t;default:return""}}function qp(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case ar:return"Fragment";case ir:return"Portal";case $p:return"Profiler";case ox:return"StrictMode";case Wp:return"Suspense";case Gp:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case __:return(t.displayName||"Context")+".Consumer";case y_:return(t._context.displayName||"Context")+".Provider";case lx:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case cx:return e=t.displayName||null,e!==null?e:qp(t.type)||"Memo";case Ys:e=t._payload,t=t._init;try{return qp(t(e))}catch{}}return null}function uS(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return qp(e);case 8:return e===ox?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function xn(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function b_(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function dS(t){var e=b_(t)?"checked":"value",s=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),n=""+t[e];if(!t.hasOwnProperty(e)&&typeof s<"u"&&typeof s.get=="function"&&typeof s.set=="function"){var r=s.get,i=s.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return r.call(this)},set:function(a){n=""+a,i.call(this,a)}}),Object.defineProperty(t,e,{enumerable:s.enumerable}),{getValue:function(){return n},setValue:function(a){n=""+a},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function Sd(t){t._valueTracker||(t._valueTracker=dS(t))}function w_(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var s=e.getValue(),n="";return t&&(n=b_(t)?t.checked?"true":"false":t.value),t=n,t!==s?(e.setValue(t),!0):!1}function bf(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function Jp(t,e){var s=e.checked;return $e({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:s??t._wrapperState.initialChecked})}function Dg(t,e){var s=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;s=xn(e.value!=null?e.value:s),t._wrapperState={initialChecked:n,initialValue:s,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function S_(t,e){e=e.checked,e!=null&&ax(t,"checked",e,!1)}function Kp(t,e){S_(t,e);var s=xn(e.value),n=e.type;if(s!=null)n==="number"?(s===0&&t.value===""||t.value!=s)&&(t.value=""+s):t.value!==""+s&&(t.value=""+s);else if(n==="submit"||n==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?Qp(t,e.type,s):e.hasOwnProperty("defaultValue")&&Qp(t,e.type,xn(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function Mg(t,e,s){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var n=e.type;if(!(n!=="submit"&&n!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,s||e===t.value||(t.value=e),t.defaultValue=e}s=t.name,s!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,s!==""&&(t.name=s)}function Qp(t,e,s){(e!=="number"||bf(t.ownerDocument)!==t)&&(s==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+s&&(t.defaultValue=""+s))}var mu=Array.isArray;function gr(t,e,s,n){if(t=t.options,e){e={};for(var r=0;r"+e.valueOf().toString()+"",e=kd.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function Iu(t,e){if(e){var s=t.firstChild;if(s&&s===t.lastChild&&s.nodeType===3){s.nodeValue=e;return}}t.textContent=e}var vu={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},fS=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(t){fS.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),vu[e]=vu[t]})});function j_(t,e,s){return e==null||typeof e=="boolean"||e===""?"":s||typeof e!="number"||e===0||vu.hasOwnProperty(t)&&vu[t]?(""+e).trim():e+"px"}function C_(t,e){t=t.style;for(var s in e)if(e.hasOwnProperty(s)){var n=s.indexOf("--")===0,r=j_(s,e[s],n);s==="float"&&(s="cssFloat"),n?t.setProperty(s,r):t[s]=r}}var hS=$e({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Zp(t,e){if(e){if(hS[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(Y(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(Y(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(Y(61))}if(e.style!=null&&typeof e.style!="object")throw Error(Y(62))}}function em(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var tm=null;function ux(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var sm=null,yr=null,_r=null;function $g(t){if(t=ld(t)){if(typeof sm!="function")throw Error(Y(280));var e=t.stateNode;e&&(e=fh(e),sm(t.stateNode,t.type,e))}}function U_(t){yr?_r?_r.push(t):_r=[t]:yr=t}function B_(){if(yr){var t=yr,e=_r;if(_r=yr=null,$g(t),e)for(t=0;t>>=0,t===0?32:31-(kS(t)/ES|0)|0}var Ed=64,Nd=4194304;function xu(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function Ef(t,e){var s=t.pendingLanes;if(s===0)return 0;var n=0,r=t.suspendedLanes,i=t.pingedLanes,a=s&268435455;if(a!==0){var l=a&~r;l!==0?n=xu(l):(i&=a,i!==0&&(n=xu(i)))}else a=s&~r,a!==0?n=xu(a):i!==0&&(n=xu(i));if(n===0)return 0;if(e!==0&&e!==n&&!(e&r)&&(r=n&-n,i=e&-e,r>=i||r===16&&(i&4194240)!==0))return e;if(n&4&&(n|=s&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=n;0s;s++)e.push(t);return e}function ad(t,e,s){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-us(e),t[e]=s}function US(t,e){var s=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var n=t.eventTimes;for(t=t.expirationTimes;0=wu),Zg=" ",e0=!1;function Q_(t,e){switch(t){case"keyup":return n2.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Y_(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var or=!1;function i2(t,e){switch(t){case"compositionend":return Y_(e);case"keypress":return e.which!==32?null:(e0=!0,Zg);case"textInput":return t=e.data,t===Zg&&e0?null:t;default:return null}}function a2(t,e){if(or)return t==="compositionend"||!yx&&Q_(t,e)?(t=J_(),Qd=mx=tn=null,or=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:s,offset:e-t};t=n}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=r0(s)}}function tv(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?tv(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function sv(){for(var t=window,e=bf();e instanceof t.HTMLIFrameElement;){try{var s=typeof e.contentWindow.location.href=="string"}catch{s=!1}if(s)t=e.contentWindow;else break;e=bf(t.document)}return e}function _x(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function m2(t){var e=sv(),s=t.focusedElem,n=t.selectionRange;if(e!==s&&s&&s.ownerDocument&&tv(s.ownerDocument.documentElement,s)){if(n!==null&&_x(s)){if(e=n.start,t=n.end,t===void 0&&(t=e),"selectionStart"in s)s.selectionStart=e,s.selectionEnd=Math.min(t,s.value.length);else if(t=(e=s.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var r=s.textContent.length,i=Math.min(n.start,r);n=n.end===void 0?i:Math.min(n.end,r),!t.extend&&i>n&&(r=n,n=i,i=r),r=i0(s,i);var a=i0(s,n);r&&a&&(t.rangeCount!==1||t.anchorNode!==r.node||t.anchorOffset!==r.offset||t.focusNode!==a.node||t.focusOffset!==a.offset)&&(e=e.createRange(),e.setStart(r.node,r.offset),t.removeAllRanges(),i>n?(t.addRange(e),t.extend(a.node,a.offset)):(e.setEnd(a.node,a.offset),t.addRange(e)))}}for(e=[],t=s;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof s.focus=="function"&&s.focus(),s=0;s=document.documentMode,lr=null,lm=null,ku=null,cm=!1;function a0(t,e,s){var n=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;cm||lr==null||lr!==bf(n)||(n=lr,"selectionStart"in n&&_x(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),ku&&$u(ku,n)||(ku=n,n=Cf(lm,"onSelect"),0dr||(t.current=mm[dr],mm[dr]=null,dr--)}function Te(t,e){dr++,mm[dr]=t.current,t.current=e}var gn={},kt=vn(gn),Ft=vn(!1),In=gn;function Rc(t,e){var s=t.type.contextTypes;if(!s)return gn;var n=t.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var r={},i;for(i in s)r[i]=e[i];return n&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=r),r}function Lt(t){return t=t.childContextTypes,t!=null}function Bf(){ze(Ft),ze(kt)}function h0(t,e,s){if(kt.current!==gn)throw Error(Y(168));Te(kt,e),Te(Ft,s)}function dv(t,e,s){var n=t.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return s;n=n.getChildContext();for(var r in n)if(!(r in e))throw Error(Y(108,uS(t)||"Unknown",r));return $e({},s,n)}function Tf(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||gn,In=kt.current,Te(kt,t),Te(Ft,Ft.current),!0}function p0(t,e,s){var n=t.stateNode;if(!n)throw Error(Y(169));s?(t=dv(t,e,In),n.__reactInternalMemoizedMergedChildContext=t,ze(Ft),ze(kt),Te(kt,t)):ze(Ft),Te(Ft,s)}var Rs=null,hh=!1,yp=!1;function fv(t){Rs===null?Rs=[t]:Rs.push(t)}function j2(t){hh=!0,fv(t)}function bn(){if(!yp&&Rs!==null){yp=!0;var t=0,e=je;try{var s=Rs;for(je=1;t>=a,r-=a,Fs=1<<32-us(e)+r|s<T?(O=B,B=null):O=B.sibling;var C=h(x,B,y[T],N);if(C===null){B===null&&(B=O);break}t&&B&&C.alternate===null&&e(x,B),p=i(C,p,T),w===null?j=C:w.sibling=C,w=C,B=O}if(T===y.length)return s(x,B),Ie&&En(x,T),j;if(B===null){for(;TT?(O=B,B=null):O=B.sibling;var q=h(x,B,C.value,N);if(q===null){B===null&&(B=O);break}t&&B&&q.alternate===null&&e(x,B),p=i(q,p,T),w===null?j=q:w.sibling=q,w=q,B=O}if(C.done)return s(x,B),Ie&&En(x,T),j;if(B===null){for(;!C.done;T++,C=y.next())C=f(x,C.value,N),C!==null&&(p=i(C,p,T),w===null?j=C:w.sibling=C,w=C);return Ie&&En(x,T),j}for(B=n(x,B);!C.done;T++,C=y.next())C=g(B,x,T,C.value,N),C!==null&&(t&&C.alternate!==null&&B.delete(C.key===null?T:C.key),p=i(C,p,T),w===null?j=C:w.sibling=C,w=C);return t&&B.forEach(function(V){return e(x,V)}),Ie&&En(x,T),j}function k(x,p,y,N){if(typeof y=="object"&&y!==null&&y.type===ar&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case wd:e:{for(var j=y.key,w=p;w!==null;){if(w.key===j){if(j=y.type,j===ar){if(w.tag===7){s(x,w.sibling),p=r(w,y.props.children),p.return=x,x=p;break e}}else if(w.elementType===j||typeof j=="object"&&j!==null&&j.$$typeof===Ys&&g0(j)===w.type){s(x,w.sibling),p=r(w,y.props),p.ref=ou(x,w,y),p.return=x,x=p;break e}s(x,w);break}else e(x,w);w=w.sibling}y.type===ar?(p=Rn(y.props.children,x.mode,N,y.key),p.return=x,x=p):(N=rf(y.type,y.key,y.props,null,x.mode,N),N.ref=ou(x,p,y),N.return=x,x=N)}return a(x);case ir:e:{for(w=y.key;p!==null;){if(p.key===w)if(p.tag===4&&p.stateNode.containerInfo===y.containerInfo&&p.stateNode.implementation===y.implementation){s(x,p.sibling),p=r(p,y.children||[]),p.return=x,x=p;break e}else{s(x,p);break}else e(x,p);p=p.sibling}p=Np(y,x.mode,N),p.return=x,x=p}return a(x);case Ys:return w=y._init,k(x,p,w(y._payload),N)}if(mu(y))return v(x,p,y,N);if(su(y))return _(x,p,y,N);zd(x,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,p!==null&&p.tag===6?(s(x,p.sibling),p=r(p,y),p.return=x,x=p):(s(x,p),p=Ep(y,x.mode,N),p.return=x,x=p),a(x)):s(x,p)}return k}var Lc=xv(!0),gv=xv(!1),Af=vn(null),Rf=null,pr=null,Sx=null;function kx(){Sx=pr=Rf=null}function Ex(t){var e=Af.current;ze(Af),t._currentValue=e}function ym(t,e,s){for(;t!==null;){var n=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,n!==null&&(n.childLanes|=e)):n!==null&&(n.childLanes&e)!==e&&(n.childLanes|=e),t===s)break;t=t.return}}function br(t,e){Rf=t,Sx=pr=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Rt=!0),t.firstContext=null)}function es(t){var e=t._currentValue;if(Sx!==t)if(t={context:t,memoizedValue:e,next:null},pr===null){if(Rf===null)throw Error(Y(308));pr=t,Rf.dependencies={lanes:0,firstContext:t}}else pr=pr.next=t;return e}var Un=null;function Nx(t){Un===null?Un=[t]:Un.push(t)}function yv(t,e,s,n){var r=e.interleaved;return r===null?(s.next=s,Nx(e)):(s.next=r.next,r.next=s),e.interleaved=s,Ms(t,n)}function Ms(t,e){t.lanes|=e;var s=t.alternate;for(s!==null&&(s.lanes|=e),s=t,t=t.return;t!==null;)t.childLanes|=e,s=t.alternate,s!==null&&(s.childLanes|=e),s=t,t=t.return;return s.tag===3?s.stateNode:null}var Xs=!1;function jx(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function _v(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function Is(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function cn(t,e,s){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,ke&2){var r=n.pending;return r===null?e.next=e:(e.next=r.next,r.next=e),n.pending=e,Ms(t,s)}return r=n.interleaved,r===null?(e.next=e,Nx(n)):(e.next=r.next,r.next=e),n.interleaved=e,Ms(t,s)}function Xd(t,e,s){if(e=e.updateQueue,e!==null&&(e=e.shared,(s&4194240)!==0)){var n=e.lanes;n&=t.pendingLanes,s|=n,e.lanes=s,fx(t,s)}}function y0(t,e){var s=t.updateQueue,n=t.alternate;if(n!==null&&(n=n.updateQueue,s===n)){var r=null,i=null;if(s=s.firstBaseUpdate,s!==null){do{var a={eventTime:s.eventTime,lane:s.lane,tag:s.tag,payload:s.payload,callback:s.callback,next:null};i===null?r=i=a:i=i.next=a,s=s.next}while(s!==null);i===null?r=i=e:i=i.next=e}else r=i=e;s={baseState:n.baseState,firstBaseUpdate:r,lastBaseUpdate:i,shared:n.shared,effects:n.effects},t.updateQueue=s;return}t=s.lastBaseUpdate,t===null?s.firstBaseUpdate=e:t.next=e,s.lastBaseUpdate=e}function Ff(t,e,s,n){var r=t.updateQueue;Xs=!1;var i=r.firstBaseUpdate,a=r.lastBaseUpdate,l=r.shared.pending;if(l!==null){r.shared.pending=null;var c=l,u=c.next;c.next=null,a===null?i=u:a.next=u,a=c;var d=t.alternate;d!==null&&(d=d.updateQueue,l=d.lastBaseUpdate,l!==a&&(l===null?d.firstBaseUpdate=u:l.next=u,d.lastBaseUpdate=c))}if(i!==null){var f=r.baseState;a=0,d=u=c=null,l=i;do{var h=l.lane,g=l.eventTime;if((n&h)===h){d!==null&&(d=d.next={eventTime:g,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var v=t,_=l;switch(h=e,g=s,_.tag){case 1:if(v=_.payload,typeof v=="function"){f=v.call(g,f,h);break e}f=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=_.payload,h=typeof v=="function"?v.call(g,f,h):v,h==null)break e;f=$e({},f,h);break e;case 2:Xs=!0}}l.callback!==null&&l.lane!==0&&(t.flags|=64,h=r.effects,h===null?r.effects=[l]:h.push(l))}else g={eventTime:g,lane:h,tag:l.tag,payload:l.payload,callback:l.callback,next:null},d===null?(u=d=g,c=f):d=d.next=g,a|=h;if(l=l.next,l===null){if(l=r.shared.pending,l===null)break;h=l,l=h.next,h.next=null,r.lastBaseUpdate=h,r.shared.pending=null}}while(!0);if(d===null&&(c=f),r.baseState=c,r.firstBaseUpdate=u,r.lastBaseUpdate=d,e=r.shared.interleaved,e!==null){r=e;do a|=r.lane,r=r.next;while(r!==e)}else i===null&&(r.shared.lanes=0);Mn|=a,t.lanes=a,t.memoizedState=f}}function _0(t,e,s){if(t=e.effects,e.effects=null,t!==null)for(e=0;es?s:4,t(!0);var n=vp.transition;vp.transition={};try{t(!1),e()}finally{je=s,vp.transition=n}}function Fv(){return ts().memoizedState}function T2(t,e,s){var n=dn(t);if(s={lane:n,action:s,hasEagerState:!1,eagerState:null,next:null},Lv(t))Iv(e,s);else if(s=yv(t,e,s,n),s!==null){var r=jt();ds(s,t,n,r),Ov(s,e,n)}}function P2(t,e,s){var n=dn(t),r={lane:n,action:s,hasEagerState:!1,eagerState:null,next:null};if(Lv(t))Iv(e,r);else{var i=t.alternate;if(t.lanes===0&&(i===null||i.lanes===0)&&(i=e.lastRenderedReducer,i!==null))try{var a=e.lastRenderedState,l=i(a,s);if(r.hasEagerState=!0,r.eagerState=l,fs(l,a)){var c=e.interleaved;c===null?(r.next=r,Nx(e)):(r.next=c.next,c.next=r),e.interleaved=r;return}}catch{}finally{}s=yv(t,e,r,n),s!==null&&(r=jt(),ds(s,t,n,r),Ov(s,e,n))}}function Lv(t){var e=t.alternate;return t===Ve||e!==null&&e===Ve}function Iv(t,e){Eu=If=!0;var s=t.pending;s===null?e.next=e:(e.next=s.next,s.next=e),t.pending=e}function Ov(t,e,s){if(s&4194240){var n=e.lanes;n&=t.pendingLanes,s|=n,e.lanes=s,fx(t,s)}}var Of={readContext:es,useCallback:gt,useContext:gt,useEffect:gt,useImperativeHandle:gt,useInsertionEffect:gt,useLayoutEffect:gt,useMemo:gt,useReducer:gt,useRef:gt,useState:gt,useDebugValue:gt,useDeferredValue:gt,useTransition:gt,useMutableSource:gt,useSyncExternalStore:gt,useId:gt,unstable_isNewReconciler:!1},z2={readContext:es,useCallback:function(t,e){return _s().memoizedState=[t,e===void 0?null:e],t},useContext:es,useEffect:b0,useImperativeHandle:function(t,e,s){return s=s!=null?s.concat([t]):null,ef(4194308,4,Tv.bind(null,e,t),s)},useLayoutEffect:function(t,e){return ef(4194308,4,t,e)},useInsertionEffect:function(t,e){return ef(4,2,t,e)},useMemo:function(t,e){var s=_s();return e=e===void 0?null:e,t=t(),s.memoizedState=[t,e],t},useReducer:function(t,e,s){var n=_s();return e=s!==void 0?s(e):e,n.memoizedState=n.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},n.queue=t,t=t.dispatch=T2.bind(null,Ve,t),[n.memoizedState,t]},useRef:function(t){var e=_s();return t={current:t},e.memoizedState=t},useState:v0,useDebugValue:Rx,useDeferredValue:function(t){return _s().memoizedState=t},useTransition:function(){var t=v0(!1),e=t[0];return t=B2.bind(null,t[1]),_s().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,s){var n=Ve,r=_s();if(Ie){if(s===void 0)throw Error(Y(407));s=s()}else{if(s=e(),ct===null)throw Error(Y(349));Dn&30||Sv(n,e,s)}r.memoizedState=s;var i={value:s,getSnapshot:e};return r.queue=i,b0(Ev.bind(null,n,i,t),[t]),n.flags|=2048,Xu(9,kv.bind(null,n,i,s,e),void 0,null),s},useId:function(){var t=_s(),e=ct.identifierPrefix;if(Ie){var s=Ls,n=Fs;s=(n&~(1<<32-us(n)-1)).toString(32)+s,e=":"+e+"R"+s,s=Qu++,0<\/script>",t=t.removeChild(t.firstChild)):typeof n.is=="string"?t=a.createElement(s,{is:n.is}):(t=a.createElement(s),s==="select"&&(a=t,n.multiple?a.multiple=!0:n.size&&(a.size=n.size))):t=a.createElementNS(t,s),t[ks]=e,t[qu]=n,Kv(t,e,!1,!1),e.stateNode=t;e:{switch(a=em(s,n),s){case"dialog":Pe("cancel",t),Pe("close",t),r=n;break;case"iframe":case"object":case"embed":Pe("load",t),r=n;break;case"video":case"audio":for(r=0;rDc&&(e.flags|=128,n=!0,lu(i,!1),e.lanes=4194304)}else{if(!n)if(t=Lf(a),t!==null){if(e.flags|=128,n=!0,s=t.updateQueue,s!==null&&(e.updateQueue=s,e.flags|=4),lu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!Ie)return yt(e),null}else 2*Ke()-i.renderingStartTime>Dc&&s!==1073741824&&(e.flags|=128,n=!0,lu(i,!1),e.lanes=4194304);i.isBackwards?(a.sibling=e.child,e.child=a):(s=i.last,s!==null?s.sibling=a:e.child=a,i.last=a)}return i.tail!==null?(e=i.tail,i.rendering=e,i.tail=e.sibling,i.renderingStartTime=Ke(),e.sibling=null,s=De.current,Te(De,n?s&1|2:s&1),e):(yt(e),null);case 22:case 23:return Mx(),n=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Vt&1073741824&&(yt(e),e.subtreeFlags&6&&(e.flags|=8192)):yt(e),null;case 24:return null;case 25:return null}throw Error(Y(156,e.tag))}function M2(t,e){switch(bx(e),e.tag){case 1:return Lt(e.type)&&Bf(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return Ic(),ze(Ft),ze(kt),Bx(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return Ux(e),null;case 13:if(ze(De),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(Y(340));Fc()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return ze(De),null;case 4:return Ic(),null;case 10:return Ex(e.type._context),null;case 22:case 23:return Mx(),null;case 24:return null;default:return null}}var Rd=!1,vt=!1,V2=typeof WeakSet=="function"?WeakSet:Set,oe=null;function mr(t,e){var s=t.ref;if(s!==null)if(typeof s=="function")try{s(null)}catch(n){qe(t,e,n)}else s.current=null}function jm(t,e,s){try{s()}catch(n){qe(t,e,n)}}var P0=!1;function H2(t,e){if(um=Nf,t=sv(),_x(t)){if("selectionStart"in t)var s={start:t.selectionStart,end:t.selectionEnd};else e:{s=(s=t.ownerDocument)&&s.defaultView||window;var n=s.getSelection&&s.getSelection();if(n&&n.rangeCount!==0){s=n.anchorNode;var r=n.anchorOffset,i=n.focusNode;n=n.focusOffset;try{s.nodeType,i.nodeType}catch{s=null;break e}var a=0,l=-1,c=-1,u=0,d=0,f=t,h=null;t:for(;;){for(var g;f!==s||r!==0&&f.nodeType!==3||(l=a+r),f!==i||n!==0&&f.nodeType!==3||(c=a+n),f.nodeType===3&&(a+=f.nodeValue.length),(g=f.firstChild)!==null;)h=f,f=g;for(;;){if(f===t)break t;if(h===s&&++u===r&&(l=a),h===i&&++d===n&&(c=a),(g=f.nextSibling)!==null)break;f=h,h=f.parentNode}f=g}s=l===-1||c===-1?null:{start:l,end:c}}else s=null}s=s||{start:0,end:0}}else s=null;for(dm={focusedElem:t,selectionRange:s},Nf=!1,oe=e;oe!==null;)if(e=oe,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,oe=t;else for(;oe!==null;){e=oe;try{var v=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(v!==null){var _=v.memoizedProps,k=v.memoizedState,x=e.stateNode,p=x.getSnapshotBeforeUpdate(e.elementType===e.type?_:as(e.type,_),k);x.__reactInternalSnapshotBeforeUpdate=p}break;case 3:var y=e.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Y(163))}}catch(N){qe(e,e.return,N)}if(t=e.sibling,t!==null){t.return=e.return,oe=t;break}oe=e.return}return v=P0,P0=!1,v}function Nu(t,e,s){var n=e.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var r=n=n.next;do{if((r.tag&t)===t){var i=r.destroy;r.destroy=void 0,i!==void 0&&jm(e,s,i)}r=r.next}while(r!==n)}}function xh(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var s=e=e.next;do{if((s.tag&t)===t){var n=s.create;s.destroy=n()}s=s.next}while(s!==e)}}function Cm(t){var e=t.ref;if(e!==null){var s=t.stateNode;switch(t.tag){case 5:t=s;break;default:t=s}typeof e=="function"?e(t):e.current=t}}function Xv(t){var e=t.alternate;e!==null&&(t.alternate=null,Xv(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[ks],delete e[qu],delete e[pm],delete e[E2],delete e[N2])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function Zv(t){return t.tag===5||t.tag===3||t.tag===4}function z0(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Zv(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Um(t,e,s){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?s.nodeType===8?s.parentNode.insertBefore(t,e):s.insertBefore(t,e):(s.nodeType===8?(e=s.parentNode,e.insertBefore(t,s)):(e=s,e.appendChild(t)),s=s._reactRootContainer,s!=null||e.onclick!==null||(e.onclick=Uf));else if(n!==4&&(t=t.child,t!==null))for(Um(t,e,s),t=t.sibling;t!==null;)Um(t,e,s),t=t.sibling}function Bm(t,e,s){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?s.insertBefore(t,e):s.appendChild(t);else if(n!==4&&(t=t.child,t!==null))for(Bm(t,e,s),t=t.sibling;t!==null;)Bm(t,e,s),t=t.sibling}var dt=null,os=!1;function qs(t,e,s){for(s=s.child;s!==null;)e1(t,e,s),s=s.sibling}function e1(t,e,s){if(Es&&typeof Es.onCommitFiberUnmount=="function")try{Es.onCommitFiberUnmount(lh,s)}catch{}switch(s.tag){case 5:vt||mr(s,e);case 6:var n=dt,r=os;dt=null,qs(t,e,s),dt=n,os=r,dt!==null&&(os?(t=dt,s=s.stateNode,t.nodeType===8?t.parentNode.removeChild(s):t.removeChild(s)):dt.removeChild(s.stateNode));break;case 18:dt!==null&&(os?(t=dt,s=s.stateNode,t.nodeType===8?gp(t.parentNode,s):t.nodeType===1&&gp(t,s),Vu(t)):gp(dt,s.stateNode));break;case 4:n=dt,r=os,dt=s.stateNode.containerInfo,os=!0,qs(t,e,s),dt=n,os=r;break;case 0:case 11:case 14:case 15:if(!vt&&(n=s.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){r=n=n.next;do{var i=r,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&jm(s,e,a),r=r.next}while(r!==n)}qs(t,e,s);break;case 1:if(!vt&&(mr(s,e),n=s.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=s.memoizedProps,n.state=s.memoizedState,n.componentWillUnmount()}catch(l){qe(s,e,l)}qs(t,e,s);break;case 21:qs(t,e,s);break;case 22:s.mode&1?(vt=(n=vt)||s.memoizedState!==null,qs(t,e,s),vt=n):qs(t,e,s);break;default:qs(t,e,s)}}function A0(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var s=t.stateNode;s===null&&(s=t.stateNode=new V2),e.forEach(function(n){var r=X2.bind(null,t,n);s.has(n)||(s.add(n),n.then(r,r))})}}function ns(t,e){var s=e.deletions;if(s!==null)for(var n=0;nr&&(r=a),n&=~i}if(n=r,n=Ke()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*W2(n/1960))-n,10t?16:t,sn===null)var n=!1;else{if(t=sn,sn=null,Vf=0,ke&6)throw Error(Y(331));var r=ke;for(ke|=4,oe=t.current;oe!==null;){var i=oe,a=i.child;if(oe.flags&16){var l=i.deletions;if(l!==null){for(var c=0;cKe()-Ox?An(t,0):Ix|=s),It(t,e)}function l1(t,e){e===0&&(t.mode&1?(e=Nd,Nd<<=1,!(Nd&130023424)&&(Nd=4194304)):e=1);var s=jt();t=Ms(t,e),t!==null&&(ad(t,e,s),It(t,s))}function Y2(t){var e=t.memoizedState,s=0;e!==null&&(s=e.retryLane),l1(t,s)}function X2(t,e){var s=0;switch(t.tag){case 13:var n=t.stateNode,r=t.memoizedState;r!==null&&(s=r.retryLane);break;case 19:n=t.stateNode;break;default:throw Error(Y(314))}n!==null&&n.delete(e),l1(t,s)}var c1;c1=function(t,e,s){if(t!==null)if(t.memoizedProps!==e.pendingProps||Ft.current)Rt=!0;else{if(!(t.lanes&s)&&!(e.flags&128))return Rt=!1,O2(t,e,s);Rt=!!(t.flags&131072)}else Rt=!1,Ie&&e.flags&1048576&&hv(e,zf,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;tf(t,e),t=e.pendingProps;var r=Rc(e,kt.current);br(e,s),r=Px(null,e,n,t,r,s);var i=zx();return e.flags|=1,typeof r=="object"&&r!==null&&typeof r.render=="function"&&r.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,Lt(n)?(i=!0,Tf(e)):i=!1,e.memoizedState=r.state!==null&&r.state!==void 0?r.state:null,jx(e),r.updater=mh,e.stateNode=r,r._reactInternals=e,vm(e,n,t,s),e=Sm(null,e,n,!0,i,s)):(e.tag=0,Ie&&i&&vx(e),Nt(null,e,r,s),e=e.child),e;case 16:n=e.elementType;e:{switch(tf(t,e),t=e.pendingProps,r=n._init,n=r(n._payload),e.type=n,r=e.tag=ek(n),t=as(n,t),r){case 0:e=wm(null,e,n,t,s);break e;case 1:e=U0(null,e,n,t,s);break e;case 11:e=j0(null,e,n,t,s);break e;case 14:e=C0(null,e,n,as(n.type,t),s);break e}throw Error(Y(306,n,""))}return e;case 0:return n=e.type,r=e.pendingProps,r=e.elementType===n?r:as(n,r),wm(t,e,n,r,s);case 1:return n=e.type,r=e.pendingProps,r=e.elementType===n?r:as(n,r),U0(t,e,n,r,s);case 3:e:{if(Gv(e),t===null)throw Error(Y(387));n=e.pendingProps,i=e.memoizedState,r=i.element,_v(t,e),Ff(e,n,null,s);var a=e.memoizedState;if(n=a.element,i.isDehydrated)if(i={element:n,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},e.updateQueue.baseState=i,e.memoizedState=i,e.flags&256){r=Oc(Error(Y(423)),e),e=B0(t,e,n,s,r);break e}else if(n!==r){r=Oc(Error(Y(424)),e),e=B0(t,e,n,s,r);break e}else for(Ht=ln(e.stateNode.containerInfo.firstChild),$t=e,Ie=!0,ls=null,s=gv(e,null,n,s),e.child=s;s;)s.flags=s.flags&-3|4096,s=s.sibling;else{if(Fc(),n===r){e=Vs(t,e,s);break e}Nt(t,e,n,s)}e=e.child}return e;case 5:return vv(e),t===null&&gm(e),n=e.type,r=e.pendingProps,i=t!==null?t.memoizedProps:null,a=r.children,fm(n,r)?a=null:i!==null&&fm(n,i)&&(e.flags|=32),Wv(t,e),Nt(t,e,a,s),e.child;case 6:return t===null&&gm(e),null;case 13:return qv(t,e,s);case 4:return Cx(e,e.stateNode.containerInfo),n=e.pendingProps,t===null?e.child=Lc(e,null,n,s):Nt(t,e,n,s),e.child;case 11:return n=e.type,r=e.pendingProps,r=e.elementType===n?r:as(n,r),j0(t,e,n,r,s);case 7:return Nt(t,e,e.pendingProps,s),e.child;case 8:return Nt(t,e,e.pendingProps.children,s),e.child;case 12:return Nt(t,e,e.pendingProps.children,s),e.child;case 10:e:{if(n=e.type._context,r=e.pendingProps,i=e.memoizedProps,a=r.value,Te(Af,n._currentValue),n._currentValue=a,i!==null)if(fs(i.value,a)){if(i.children===r.children&&!Ft.current){e=Vs(t,e,s);break e}}else for(i=e.child,i!==null&&(i.return=e);i!==null;){var l=i.dependencies;if(l!==null){a=i.child;for(var c=l.firstContext;c!==null;){if(c.context===n){if(i.tag===1){c=Is(-1,s&-s),c.tag=2;var u=i.updateQueue;if(u!==null){u=u.shared;var d=u.pending;d===null?c.next=c:(c.next=d.next,d.next=c),u.pending=c}}i.lanes|=s,c=i.alternate,c!==null&&(c.lanes|=s),ym(i.return,s,e),l.lanes|=s;break}c=c.next}}else if(i.tag===10)a=i.type===e.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(Y(341));a.lanes|=s,l=a.alternate,l!==null&&(l.lanes|=s),ym(a,s,e),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===e){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}Nt(t,e,r.children,s),e=e.child}return e;case 9:return r=e.type,n=e.pendingProps.children,br(e,s),r=es(r),n=n(r),e.flags|=1,Nt(t,e,n,s),e.child;case 14:return n=e.type,r=as(n,e.pendingProps),r=as(n.type,r),C0(t,e,n,r,s);case 15:return Hv(t,e,e.type,e.pendingProps,s);case 17:return n=e.type,r=e.pendingProps,r=e.elementType===n?r:as(n,r),tf(t,e),e.tag=1,Lt(n)?(t=!0,Tf(e)):t=!1,br(e,s),Dv(e,n,r),vm(e,n,r,s),Sm(null,e,n,!0,t,s);case 19:return Jv(t,e,s);case 22:return $v(t,e,s)}throw Error(Y(156,e.tag))};function u1(t,e){return L_(t,e)}function Z2(t,e,s,n){this.tag=t,this.key=s,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Xt(t,e,s,n){return new Z2(t,e,s,n)}function Hx(t){return t=t.prototype,!(!t||!t.isReactComponent)}function ek(t){if(typeof t=="function")return Hx(t)?1:0;if(t!=null){if(t=t.$$typeof,t===lx)return 11;if(t===cx)return 14}return 2}function fn(t,e){var s=t.alternate;return s===null?(s=Xt(t.tag,e,t.key,t.mode),s.elementType=t.elementType,s.type=t.type,s.stateNode=t.stateNode,s.alternate=t,t.alternate=s):(s.pendingProps=e,s.type=t.type,s.flags=0,s.subtreeFlags=0,s.deletions=null),s.flags=t.flags&14680064,s.childLanes=t.childLanes,s.lanes=t.lanes,s.child=t.child,s.memoizedProps=t.memoizedProps,s.memoizedState=t.memoizedState,s.updateQueue=t.updateQueue,e=t.dependencies,s.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},s.sibling=t.sibling,s.index=t.index,s.ref=t.ref,s}function rf(t,e,s,n,r,i){var a=2;if(n=t,typeof t=="function")Hx(t)&&(a=1);else if(typeof t=="string")a=5;else e:switch(t){case ar:return Rn(s.children,r,i,e);case ox:a=8,r|=8;break;case $p:return t=Xt(12,s,e,r|2),t.elementType=$p,t.lanes=i,t;case Wp:return t=Xt(13,s,e,r),t.elementType=Wp,t.lanes=i,t;case Gp:return t=Xt(19,s,e,r),t.elementType=Gp,t.lanes=i,t;case v_:return yh(s,r,i,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case y_:a=10;break e;case __:a=9;break e;case lx:a=11;break e;case cx:a=14;break e;case Ys:a=16,n=null;break e}throw Error(Y(130,t==null?t:typeof t,""))}return e=Xt(a,s,e,r),e.elementType=t,e.type=n,e.lanes=i,e}function Rn(t,e,s,n){return t=Xt(7,t,n,e),t.lanes=s,t}function yh(t,e,s,n){return t=Xt(22,t,n,e),t.elementType=v_,t.lanes=s,t.stateNode={isHidden:!1},t}function Ep(t,e,s){return t=Xt(6,t,null,e),t.lanes=s,t}function Np(t,e,s){return e=Xt(4,t.children!==null?t.children:[],t.key,e),e.lanes=s,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function tk(t,e,s,n,r){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=ap(0),this.expirationTimes=ap(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ap(0),this.identifierPrefix=n,this.onRecoverableError=r,this.mutableSourceEagerHydrationData=null}function $x(t,e,s,n,r,i,a,l,c){return t=new tk(t,e,s,l,c),e===1?(e=1,i===!0&&(e|=8)):e=0,i=Xt(3,null,null,e),t.current=i,i.stateNode=t,i.memoizedState={element:n,isDehydrated:s,cache:null,transitions:null,pendingSuspenseBoundaries:null},jx(i),t}function sk(t,e,s){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(p1)}catch(t){console.error(t)}}p1(),p_.exports=Gt;var ok=p_.exports,V0=ok;Vp.createRoot=V0.createRoot,Vp.hydrateRoot=V0.hydrateRoot;/** * @remix-run/router v1.23.2 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function ed(){return ed=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function Jx(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function ck(){return Math.random().toString(36).substr(2,8)}function $0(t,e){return{usr:t.state,key:t.key,idx:e}}function Rm(t,e,s,n){return s===void 0&&(s=null),ed({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?Gc(e):e,{state:s,key:e&&e.key||n||ck()})}function Wf(t){let{pathname:e="/",search:s="",hash:n=""}=t;return s&&s!=="?"&&(e+=s.charAt(0)==="?"?s:"?"+s),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function Gc(t){let e={};if(t){let s=t.indexOf("#");s>=0&&(e.hash=t.substr(s),t=t.substr(0,s));let n=t.indexOf("?");n>=0&&(e.search=t.substr(n),t=t.substr(0,n)),t&&(e.pathname=t)}return e}function uk(t,e,s,n){n===void 0&&(n={});let{window:r=document.defaultView,v5Compat:i=!1}=n,a=r.history,l=nn.Pop,c=null,u=d();u==null&&(u=0,a.replaceState(ed({},a.state,{idx:u}),""));function d(){return(a.state||{idx:null}).idx}function f(){l=nn.Pop;let k=d(),x=k==null?null:k-u;u=k,c&&c({action:l,location:_.location,delta:x})}function h(k,x){l=nn.Push;let p=Rm(_.location,k,x);u=d()+1;let y=$0(p,u),N=_.createHref(p);try{a.pushState(y,"",N)}catch(j){if(j instanceof DOMException&&j.name==="DataCloneError")throw j;r.location.assign(N)}i&&c&&c({action:l,location:_.location,delta:1})}function g(k,x){l=nn.Replace;let p=Rm(_.location,k,x);u=d();let y=$0(p,u),N=_.createHref(p);a.replaceState(y,"",N),i&&c&&c({action:l,location:_.location,delta:0})}function v(k){let x=r.location.origin!=="null"?r.location.origin:r.location.href,p=typeof k=="string"?k:Wf(k);return p=p.replace(/ $/,"%20"),He(x,"No window.location.(origin|href) available to create URL for href: "+p),new URL(p,x)}let _={get action(){return l},get location(){return t(r,a)},listen(k){if(c)throw new Error("A history only accepts one active listener");return r.addEventListener(H0,f),c=k,()=>{r.removeEventListener(H0,f),c=null}},createHref(k){return e(r,k)},createURL:v,encodeLocation(k){let x=v(k);return{pathname:x.pathname,search:x.search,hash:x.hash}},push:h,replace:g,go(k){return a.go(k)}};return _}var W0;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(W0||(W0={}));function dk(t,e,s){return s===void 0&&(s="/"),fk(t,e,s)}function fk(t,e,s,n){let r=typeof e=="string"?Gc(e):e,i=Mc(r.pathname||"/",s);if(i==null)return null;let a=m1(t);hk(a);let l=null;for(let c=0;l==null&&c{let c={relativePath:l===void 0?i.path||"":l,caseSensitive:i.caseSensitive===!0,childrenIndex:a,route:i};c.relativePath.startsWith("/")&&(He(c.relativePath.startsWith(n),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(n.length));let u=hn([n,c.relativePath]),d=s.concat(c);i.children&&i.children.length>0&&(He(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),m1(i.children,e,d,u)),!(i.path==null&&!i.index)&&e.push({path:u,score:vk(u,i.index),routesMeta:d})};return t.forEach((i,a)=>{var l;if(i.path===""||!((l=i.path)!=null&&l.includes("?")))r(i,a);else for(let c of x1(i.path))r(i,a,c)}),e}function x1(t){let e=t.split("/");if(e.length===0)return[];let[s,...n]=e,r=s.endsWith("?"),i=s.replace(/\?$/,"");if(n.length===0)return r?[i,""]:[i];let a=x1(n.join("/")),l=[];return l.push(...a.map(c=>c===""?i:[i,c].join("/"))),r&&l.push(...a),l.map(c=>t.startsWith("/")&&c===""?"/":c)}function hk(t){t.sort((e,s)=>e.score!==s.score?s.score-e.score:bk(e.routesMeta.map(n=>n.childrenIndex),s.routesMeta.map(n=>n.childrenIndex)))}const pk=/^:[\w-]+$/,mk=3,xk=2,gk=1,yk=10,_k=-2,G0=t=>t==="*";function vk(t,e){let s=t.split("/"),n=s.length;return s.some(G0)&&(n+=_k),e&&(n+=xk),s.filter(r=>!G0(r)).reduce((r,i)=>r+(pk.test(i)?mk:i===""?gk:yk),n)}function bk(t,e){return t.length===e.length&&t.slice(0,-1).every((n,r)=>n===e[r])?t[t.length-1]-e[e.length-1]:0}function wk(t,e,s){let{routesMeta:n}=t,r={},i="/",a=[];for(let l=0;l{let{paramName:h,isOptional:g}=d;if(h==="*"){let _=l[f]||"";a=i.slice(0,i.length-_.length).replace(/(.)\/+$/,"$1")}const v=l[f];return g&&!v?u[h]=void 0:u[h]=(v||"").replace(/%2F/g,"/"),u},{}),pathname:i,pathnameBase:a,pattern:t}}function Sk(t,e,s){e===void 0&&(e=!1),s===void 0&&(s=!0),Jx(t==="*"||!t.endsWith("*")||t.endsWith("/*"),'Route path "'+t+'" will be treated as if it were '+('"'+t.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+t.replace(/\*$/,"/*")+'".'));let n=[],r="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,l,c)=>(n.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return t.endsWith("*")?(n.push({paramName:"*"}),r+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):s?r+="\\/*$":t!==""&&t!=="/"&&(r+="(?:(?=\\/|$))"),[new RegExp(r,e?void 0:"i"),n]}function kk(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return Jx(!1,'The URL path "'+t+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),t}}function Mc(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let s=e.endsWith("/")?e.length-1:e.length,n=t.charAt(s);return n&&n!=="/"?null:t.slice(s)||"/"}const Ek=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Nk=t=>Ek.test(t);function jk(t,e){e===void 0&&(e="/");let{pathname:s,search:n="",hash:r=""}=typeof t=="string"?Gc(t):t,i;if(s)if(Nk(s))i=s;else{if(s.includes("//")){let a=s;s=s.replace(/\/\/+/g,"/"),Jx(!1,"Pathnames cannot have embedded double slashes - normalizing "+(a+" -> "+s))}s.startsWith("/")?i=q0(s.substring(1),"/"):i=q0(s,e)}else i=e;return{pathname:i,search:Bk(n),hash:Tk(r)}}function q0(t,e){let s=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(r=>{r===".."?s.length>1&&s.pop():r!=="."&&s.push(r)}),s.length>1?s.join("/"):"/"}function jp(t,e,s,n){return"Cannot include a '"+t+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+s+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function Ck(t){return t.filter((e,s)=>s===0||e.route.path&&e.route.path.length>0)}function Kx(t,e){let s=Ck(t);return e?s.map((n,r)=>r===s.length-1?n.pathname:n.pathnameBase):s.map(n=>n.pathnameBase)}function Qx(t,e,s,n){n===void 0&&(n=!1);let r;typeof t=="string"?r=Gc(t):(r=ed({},t),He(!r.pathname||!r.pathname.includes("?"),jp("?","pathname","search",r)),He(!r.pathname||!r.pathname.includes("#"),jp("#","pathname","hash",r)),He(!r.search||!r.search.includes("#"),jp("#","search","hash",r)));let i=t===""||r.pathname==="",a=i?"/":r.pathname,l;if(a==null)l=s;else{let f=e.length-1;if(!n&&a.startsWith("..")){let h=a.split("/");for(;h[0]==="..";)h.shift(),f-=1;r.pathname=h.join("/")}l=f>=0?e[f]:"/"}let c=jk(r,l),u=a&&a!=="/"&&a.endsWith("/"),d=(i||a===".")&&s.endsWith("/");return!c.pathname.endsWith("/")&&(u||d)&&(c.pathname+="/"),c}const hn=t=>t.join("/").replace(/\/\/+/g,"/"),Uk=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),Bk=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,Tk=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function Pk(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const g1=["post","put","patch","delete"];new Set(g1);const zk=["get",...g1];new Set(zk);/** * React Router v6.30.3 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function td(){return td=Object.assign?Object.assign.bind():function(t){for(var e=1;e{l.current=!0}),m.useCallback(function(u,d){if(d===void 0&&(d={}),!l.current)return;if(typeof u=="number"){n.go(u);return}let f=Qx(u,JSON.parse(a),i,d.relative==="path");t==null&&e!=="/"&&(f.pathname=f.pathname==="/"?e:hn([e,f.pathname])),(d.replace?n.replace:n.push)(f,d.state,d)},[e,n,a,i,t])}const Fk=m.createContext(null);function Lk(t){let e=m.useContext(Ws).outlet;return e&&m.createElement(Fk.Provider,{value:t},e)}function Nh(t,e){let{relative:s}=e===void 0?{}:e,{future:n}=m.useContext($s),{matches:r}=m.useContext(Ws),{pathname:i}=Jc(),a=JSON.stringify(Kx(r,n.v7_relativeSplatPath));return m.useMemo(()=>Qx(t,JSON.parse(a),i,s==="path"),[t,a,i,s])}function Ik(t,e){return Ok(t,e)}function Ok(t,e,s,n){qc()||He(!1);let{navigator:r}=m.useContext($s),{matches:i}=m.useContext(Ws),a=i[i.length-1],l=a?a.params:{};a&&a.pathname;let c=a?a.pathnameBase:"/";a&&a.route;let u=Jc(),d;if(e){var f;let k=typeof e=="string"?Gc(e):e;c==="/"||(f=k.pathname)!=null&&f.startsWith(c)||He(!1),d=k}else d=u;let h=d.pathname||"/",g=h;if(c!=="/"){let k=c.replace(/^\//,"").split("/");g="/"+h.replace(/^\//,"").split("/").slice(k.length).join("/")}let v=dk(t,{pathname:g}),_=$k(v&&v.map(k=>Object.assign({},k,{params:Object.assign({},l,k.params),pathname:hn([c,r.encodeLocation?r.encodeLocation(k.pathname).pathname:k.pathname]),pathnameBase:k.pathnameBase==="/"?c:hn([c,r.encodeLocation?r.encodeLocation(k.pathnameBase).pathname:k.pathnameBase])})),i,s,n);return e&&_?m.createElement(kh.Provider,{value:{location:td({pathname:"/",search:"",hash:"",state:null,key:"default"},d),navigationType:nn.Pop}},_):_}function Dk(){let t=Jk(),e=Pk(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),s=t instanceof Error?t.stack:null,r={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return m.createElement(m.Fragment,null,m.createElement("h2",null,"Unexpected Application Error!"),m.createElement("h3",{style:{fontStyle:"italic"}},e),s?m.createElement("pre",{style:r},s):null,null)}const Mk=m.createElement(Dk,null);class Vk extends m.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,s){return s.location!==e.location||s.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:s.error,location:s.location,revalidation:e.revalidation||s.revalidation}}componentDidCatch(e,s){console.error("React Router caught the following error during render",e,s)}render(){return this.state.error!==void 0?m.createElement(Ws.Provider,{value:this.props.routeContext},m.createElement(_1.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function Hk(t){let{routeContext:e,match:s,children:n}=t,r=m.useContext(Sh);return r&&r.static&&r.staticContext&&(s.route.errorElement||s.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=s.route.id),m.createElement(Ws.Provider,{value:e},n)}function $k(t,e,s,n){var r;if(e===void 0&&(e=[]),s===void 0&&(s=null),n===void 0&&(n=null),t==null){var i;if(!s)return null;if(s.errors)t=s.matches;else if((i=n)!=null&&i.v7_partialHydration&&e.length===0&&!s.initialized&&s.matches.length>0)t=s.matches;else return null}let a=t,l=(r=s)==null?void 0:r.errors;if(l!=null){let d=a.findIndex(f=>f.route.id&&(l==null?void 0:l[f.route.id])!==void 0);d>=0||He(!1),a=a.slice(0,Math.min(a.length,d+1))}let c=!1,u=-1;if(s&&n&&n.v7_partialHydration)for(let d=0;d=0?a=a.slice(0,u+1):a=[a[0]];break}}}return a.reduceRight((d,f,h)=>{let g,v=!1,_=null,k=null;s&&(g=l&&f.route.id?l[f.route.id]:void 0,_=f.route.errorElement||Mk,c&&(u<0&&h===0?(Qk("route-fallback"),v=!0,k=null):u===h&&(v=!0,k=f.route.hydrateFallbackElement||null)));let x=e.concat(a.slice(0,h+1)),p=()=>{let y;return g?y=_:v?y=k:f.route.Component?y=m.createElement(f.route.Component,null):f.route.element?y=f.route.element:y=d,m.createElement(Hk,{match:f,routeContext:{outlet:d,matches:x,isDataRoute:s!=null},children:y})};return s&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?m.createElement(Vk,{location:s.location,revalidation:s.revalidation,component:_,error:g,children:p(),routeContext:{outlet:null,matches:x,isDataRoute:!0}}):p()},null)}var b1=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(b1||{}),w1=function(t){return t.UseBlocker="useBlocker",t.UseLoaderData="useLoaderData",t.UseActionData="useActionData",t.UseRouteError="useRouteError",t.UseNavigation="useNavigation",t.UseRouteLoaderData="useRouteLoaderData",t.UseMatches="useMatches",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t.UseRouteId="useRouteId",t}(w1||{});function Wk(t){let e=m.useContext(Sh);return e||He(!1),e}function Gk(t){let e=m.useContext(y1);return e||He(!1),e}function qk(t){let e=m.useContext(Ws);return e||He(!1),e}function S1(t){let e=qk(),s=e.matches[e.matches.length-1];return s.route.id||He(!1),s.route.id}function Jk(){var t;let e=m.useContext(_1),s=Gk(),n=S1();return e!==void 0?e:(t=s.errors)==null?void 0:t[n]}function Kk(){let{router:t}=Wk(b1.UseNavigateStable),e=S1(w1.UseNavigateStable),s=m.useRef(!1);return v1(()=>{s.current=!0}),m.useCallback(function(r,i){i===void 0&&(i={}),s.current&&(typeof r=="number"?t.navigate(r):t.navigate(r,td({fromRouteId:e},i)))},[t,e])}const J0={};function Qk(t,e,s){J0[t]||(J0[t]=!0)}function Yk(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function Yx(t){let{to:e,replace:s,state:n,relative:r}=t;qc()||He(!1);let{future:i,static:a}=m.useContext($s),{matches:l}=m.useContext(Ws),{pathname:c}=Jc(),u=Eh(),d=Qx(e,Kx(l,i.v7_relativeSplatPath),c,r==="path"),f=JSON.stringify(d);return m.useEffect(()=>u(JSON.parse(f),{replace:s,state:n,relative:r}),[u,f,r,s,n]),null}function k1(t){return Lk(t.context)}function rs(t){He(!1)}function Xk(t){let{basename:e="/",children:s=null,location:n,navigationType:r=nn.Pop,navigator:i,static:a=!1,future:l}=t;qc()&&He(!1);let c=e.replace(/^\/*/,"/"),u=m.useMemo(()=>({basename:c,navigator:i,static:a,future:td({v7_relativeSplatPath:!1},l)}),[c,l,i,a]);typeof n=="string"&&(n=Gc(n));let{pathname:d="/",search:f="",hash:h="",state:g=null,key:v="default"}=n,_=m.useMemo(()=>{let k=Mc(d,c);return k==null?null:{location:{pathname:k,search:f,hash:h,state:g,key:v},navigationType:r}},[c,d,f,h,g,v,r]);return _==null?null:m.createElement($s.Provider,{value:u},m.createElement(kh.Provider,{children:s,value:_}))}function Zk(t){let{children:e,location:s}=t;return Ik(Lm(e),s)}new Promise(()=>{});function Lm(t,e){e===void 0&&(e=[]);let s=[];return m.Children.forEach(t,(n,r)=>{if(!m.isValidElement(n))return;let i=[...e,r];if(n.type===m.Fragment){s.push.apply(s,Lm(n.props.children,i));return}n.type!==rs&&He(!1),!n.props.index||!n.props.children||He(!1);let a={id:n.props.id||i.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(a.children=Lm(n.props.children,i)),s.push(a)}),s}/** * React Router DOM v6.30.3 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function Gf(){return Gf=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&(s[r]=t[r]);return s}function eE(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function tE(t,e){return t.button===0&&(!e||e==="_self")&&!eE(t)}const sE=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],nE=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],rE="6";try{window.__reactRouterVersion=rE}catch{}const iE=m.createContext({isTransitioning:!1}),aE="startTransition",K0=Qw[aE];function oE(t){let{basename:e,children:s,future:n,window:r}=t,i=m.useRef();i.current==null&&(i.current=lk({window:r,v5Compat:!0}));let a=i.current,[l,c]=m.useState({action:a.action,location:a.location}),{v7_startTransition:u}=n||{},d=m.useCallback(f=>{u&&K0?K0(()=>c(f)):c(f)},[c,u]);return m.useLayoutEffect(()=>a.listen(d),[a,d]),m.useEffect(()=>Yk(n),[n]),m.createElement(Xk,{basename:e,children:s,location:l.location,navigationType:l.action,navigator:a,future:n})}const lE=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",cE=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,uE=m.forwardRef(function(e,s){let{onClick:n,relative:r,reloadDocument:i,replace:a,state:l,target:c,to:u,preventScrollReset:d,viewTransition:f}=e,h=E1(e,sE),{basename:g}=m.useContext($s),v,_=!1;if(typeof u=="string"&&cE.test(u)&&(v=u,lE))try{let y=new URL(window.location.href),N=u.startsWith("//")?new URL(y.protocol+u):new URL(u),j=Mc(N.pathname,g);N.origin===y.origin&&j!=null?u=j+N.search+N.hash:_=!0}catch{}let k=Ak(u,{relative:r}),x=hE(u,{replace:a,state:l,target:c,preventScrollReset:d,relative:r,viewTransition:f});function p(y){n&&n(y),y.defaultPrevented||x(y)}return m.createElement("a",Gf({},h,{href:v||k,onClick:_||i?n:p,ref:s,target:c}))}),dE=m.forwardRef(function(e,s){let{"aria-current":n="page",caseSensitive:r=!1,className:i="",end:a=!1,style:l,to:c,viewTransition:u,children:d}=e,f=E1(e,nE),h=Nh(c,{relative:f.relative}),g=Jc(),v=m.useContext(y1),{navigator:_,basename:k}=m.useContext($s),x=v!=null&&pE(h)&&u===!0,p=_.encodeLocation?_.encodeLocation(h).pathname:h.pathname,y=g.pathname,N=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;r||(y=y.toLowerCase(),N=N?N.toLowerCase():null,p=p.toLowerCase()),N&&k&&(N=Mc(N,k)||N);const j=p!=="/"&&p.endsWith("/")?p.length-1:p.length;let w=y===p||!a&&y.startsWith(p)&&y.charAt(j)==="/",B=N!=null&&(N===p||!a&&N.startsWith(p)&&N.charAt(p.length)==="/"),T={isActive:w,isPending:B,isTransitioning:x},O=w?n:void 0,C;typeof i=="function"?C=i(T):C=[i,w?"active":null,B?"pending":null,x?"transitioning":null].filter(Boolean).join(" ");let q=typeof l=="function"?l(T):l;return m.createElement(uE,Gf({},f,{"aria-current":O,className:C,ref:s,style:q,to:c,viewTransition:u}),typeof d=="function"?d(T):d)});var Im;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(Im||(Im={}));var Q0;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Q0||(Q0={}));function fE(t){let e=m.useContext(Sh);return e||He(!1),e}function hE(t,e){let{target:s,replace:n,state:r,preventScrollReset:i,relative:a,viewTransition:l}=e===void 0?{}:e,c=Eh(),u=Jc(),d=Nh(t,{relative:a});return m.useCallback(f=>{if(tE(f,s)){f.preventDefault();let h=n!==void 0?n:Wf(u)===Wf(d);c(t,{replace:h,state:r,preventScrollReset:i,relative:a,viewTransition:l})}},[u,c,d,n,r,s,t,i,a,l])}function pE(t,e){e===void 0&&(e={});let s=m.useContext(iE);s==null&&He(!1);let{basename:n}=fE(Im.useViewTransitionState),r=Nh(t,{relative:e.relative});if(!s.isTransitioning)return!1;let i=Mc(s.currentLocation.pathname,n)||s.currentLocation.pathname,a=Mc(s.nextLocation.pathname,n)||s.nextLocation.pathname;return Fm(r.pathname,a)!=null||Fm(r.pathname,i)!=null}function N1(t,e){return function(){return t.apply(e,arguments)}}const{toString:mE}=Object.prototype,{getPrototypeOf:jh}=Object,{iterator:Ch,toStringTag:j1}=Symbol,Uh=(t=>e=>{const s=mE.call(e);return t[s]||(t[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),hs=t=>(t=t.toLowerCase(),e=>Uh(e)===t),Bh=t=>e=>typeof e===t,{isArray:Kc}=Array,Vc=Bh("undefined");function ud(t){return t!==null&&!Vc(t)&&t.constructor!==null&&!Vc(t.constructor)&&Ot(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const C1=hs("ArrayBuffer");function xE(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&C1(t.buffer),e}const gE=Bh("string"),Ot=Bh("function"),U1=Bh("number"),dd=t=>t!==null&&typeof t=="object",yE=t=>t===!0||t===!1,af=t=>{if(Uh(t)!=="object")return!1;const e=jh(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(j1 in t)&&!(Ch in t)},_E=t=>{if(!dd(t)||ud(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},vE=hs("Date"),bE=hs("File"),wE=t=>!!(t&&typeof t.uri<"u"),SE=t=>t&&typeof t.getParts<"u",kE=hs("Blob"),EE=hs("FileList"),NE=t=>dd(t)&&Ot(t.pipe);function jE(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const Y0=jE(),X0=typeof Y0.FormData<"u"?Y0.FormData:void 0,CE=t=>{if(!t)return!1;if(X0&&t instanceof X0)return!0;const e=jh(t);if(!e||e===Object.prototype||!Ot(t.append))return!1;const s=Uh(t);return s==="formdata"||s==="object"&&Ot(t.toString)&&t.toString()==="[object FormData]"},UE=hs("URLSearchParams"),[BE,TE,PE,zE]=["ReadableStream","Request","Response","Headers"].map(hs),AE=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fd(t,e,{allOwnKeys:s=!1}={}){if(t===null||typeof t>"u")return;let n,r;if(typeof t!="object"&&(t=[t]),Kc(t))for(n=0,r=t.length;n0;)if(r=s[n],e===r.toLowerCase())return r;return null}const Tn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,T1=t=>!Vc(t)&&t!==Tn;function Om(...t){const{caseless:e,skipUndefined:s}=T1(this)&&this||{},n={},r=(i,a)=>{if(a==="__proto__"||a==="constructor"||a==="prototype")return;const l=e&&B1(n,a)||a,c=Dm(n,l)?n[l]:void 0;af(c)&&af(i)?n[l]=Om(c,i):af(i)?n[l]=Om({},i):Kc(i)?n[l]=i.slice():(!s||!Vc(i))&&(n[l]=i)};for(let i=0,a=t.length;i(fd(e,(r,i)=>{s&&Ot(r)?Object.defineProperty(t,i,{__proto__:null,value:N1(r,s),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(t,i,{__proto__:null,value:r,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),t),FE=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),LE=(t,e,s,n)=>{t.prototype=Object.create(e.prototype,n),Object.defineProperty(t.prototype,"constructor",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(t,"super",{__proto__:null,value:e.prototype}),s&&Object.assign(t.prototype,s)},IE=(t,e,s,n)=>{let r,i,a;const l={};if(e=e||{},t==null)return e;do{for(r=Object.getOwnPropertyNames(t),i=r.length;i-- >0;)a=r[i],(!n||n(a,t,e))&&!l[a]&&(e[a]=t[a],l[a]=!0);t=s!==!1&&jh(t)}while(t&&(!s||s(t,e))&&t!==Object.prototype);return e},OE=(t,e,s)=>{t=String(t),(s===void 0||s>t.length)&&(s=t.length),s-=e.length;const n=t.indexOf(e,s);return n!==-1&&n===s},DE=t=>{if(!t)return null;if(Kc(t))return t;let e=t.length;if(!U1(e))return null;const s=new Array(e);for(;e-- >0;)s[e]=t[e];return s},ME=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&jh(Uint8Array)),VE=(t,e)=>{const n=(t&&t[Ch]).call(t);let r;for(;(r=n.next())&&!r.done;){const i=r.value;e.call(t,i[0],i[1])}},HE=(t,e)=>{let s;const n=[];for(;(s=t.exec(e))!==null;)n.push(s);return n},$E=hs("HTMLFormElement"),WE=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(s,n,r){return n.toUpperCase()+r}),Dm=(({hasOwnProperty:t})=>(e,s)=>t.call(e,s))(Object.prototype),GE=hs("RegExp"),P1=(t,e)=>{const s=Object.getOwnPropertyDescriptors(t),n={};fd(s,(r,i)=>{let a;(a=e(r,i,t))!==!1&&(n[i]=a||r)}),Object.defineProperties(t,n)},qE=t=>{P1(t,(e,s)=>{if(Ot(t)&&["arguments","caller","callee"].includes(s))return!1;const n=t[s];if(Ot(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+s+"'")})}})},JE=(t,e)=>{const s={},n=r=>{r.forEach(i=>{s[i]=!0})};return Kc(t)?n(t):n(String(t).split(e)),s},KE=()=>{},QE=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function YE(t){return!!(t&&Ot(t.append)&&t[j1]==="FormData"&&t[Ch])}const XE=t=>{const e=new WeakSet,s=n=>{if(dd(n)){if(e.has(n))return;if(ud(n))return n;if(!("toJSON"in n)){e.add(n);const r=Kc(n)?[]:{};return fd(n,(i,a)=>{const l=s(i);!Vc(l)&&(r[a]=l)}),e.delete(n),r}}return n};return s(t)},ZE=hs("AsyncFunction"),eN=t=>t&&(dd(t)||Ot(t))&&Ot(t.then)&&Ot(t.catch),z1=((t,e)=>t?setImmediate:e?((s,n)=>(Tn.addEventListener("message",({source:r,data:i})=>{r===Tn&&i===s&&n.length&&n.shift()()},!1),r=>{n.push(r),Tn.postMessage(s,"*")}))(`axios@${Math.random()}`,[]):s=>setTimeout(s))(typeof setImmediate=="function",Ot(Tn.postMessage)),tN=typeof queueMicrotask<"u"?queueMicrotask.bind(Tn):typeof process<"u"&&process.nextTick||z1,sN=t=>t!=null&&Ot(t[Ch]),P={isArray:Kc,isArrayBuffer:C1,isBuffer:ud,isFormData:CE,isArrayBufferView:xE,isString:gE,isNumber:U1,isBoolean:yE,isObject:dd,isPlainObject:af,isEmptyObject:_E,isReadableStream:BE,isRequest:TE,isResponse:PE,isHeaders:zE,isUndefined:Vc,isDate:vE,isFile:bE,isReactNativeBlob:wE,isReactNative:SE,isBlob:kE,isRegExp:GE,isFunction:Ot,isStream:NE,isURLSearchParams:UE,isTypedArray:ME,isFileList:EE,forEach:fd,merge:Om,extend:RE,trim:AE,stripBOM:FE,inherits:LE,toFlatObject:IE,kindOf:Uh,kindOfTest:hs,endsWith:OE,toArray:DE,forEachEntry:VE,matchAll:HE,isHTMLForm:$E,hasOwnProperty:Dm,hasOwnProp:Dm,reduceDescriptors:P1,freezeMethods:qE,toObjectSet:JE,toCamelCase:WE,noop:KE,toFiniteNumber:QE,findKey:B1,global:Tn,isContextDefined:T1,isSpecCompliantForm:YE,toJSONObject:XE,isAsyncFn:ZE,isThenable:eN,setImmediate:z1,asap:tN,isIterable:sN},nN=P.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),rN=t=>{const e={};let s,n,r;return t&&t.split(` `).forEach(function(a){r=a.indexOf(":"),s=a.substring(0,r).trim().toLowerCase(),n=a.substring(r+1).trim(),!(!s||e[s]&&nN[s])&&(s==="set-cookie"?e[s]?e[s].push(n):e[s]=[n]:e[s]=e[s]?e[s]+", "+n:n)}),e};function iN(t){let e=0,s=t.length;for(;ee;){const n=t.charCodeAt(s-1);if(n!==9&&n!==32)break;s-=1}return e===0&&s===t.length?t:t.slice(e,s)}const aN=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),oN=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function Xx(t,e){return P.isArray(t)?t.map(s=>Xx(s,e)):iN(String(t).replace(e,""))}const lN=t=>Xx(t,aN),cN=t=>Xx(t,oN);function A1(t){const e=Object.create(null);return P.forEach(t.toJSON(),(s,n)=>{e[n]=cN(s)}),e}const Z0=Symbol("internals");function uu(t){return t&&String(t).trim().toLowerCase()}function of(t){return t===!1||t==null?t:P.isArray(t)?t.map(of):lN(String(t))}function uN(t){const e=Object.create(null),s=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=s.exec(t);)e[n[1]]=n[2];return e}const dN=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function Cp(t,e,s,n,r){if(P.isFunction(n))return n.call(this,e,s);if(r&&(e=s),!!P.isString(e)){if(P.isString(n))return e.indexOf(n)!==-1;if(P.isRegExp(n))return n.test(e)}}function fN(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,s,n)=>s.toUpperCase()+n)}function hN(t,e){const s=P.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+s,{__proto__:null,value:function(r,i,a){return this[n].call(this,e,r,i,a)},configurable:!0})})}let Ct=class{constructor(e){e&&this.set(e)}set(e,s,n){const r=this;function i(l,c,u){const d=uu(c);if(!d)throw new Error("header name must be a non-empty string");const f=P.findKey(r,d);(!f||r[f]===void 0||u===!0||u===void 0&&r[f]!==!1)&&(r[f||c]=of(l))}const a=(l,c)=>P.forEach(l,(u,d)=>i(u,d,c));if(P.isPlainObject(e)||e instanceof this.constructor)a(e,s);else if(P.isString(e)&&(e=e.trim())&&!dN(e))a(rN(e),s);else if(P.isObject(e)&&P.isIterable(e)){let l={},c,u;for(const d of e){if(!P.isArray(d))throw TypeError("Object iterator must return a key-value pair");l[u=d[0]]=(c=l[u])?P.isArray(c)?[...c,d[1]]:[c,d[1]]:d[1]}a(l,s)}else e!=null&&i(s,e,n);return this}get(e,s){if(e=uu(e),e){const n=P.findKey(this,e);if(n){const r=this[n];if(!s)return r;if(s===!0)return uN(r);if(P.isFunction(s))return s.call(this,r,n);if(P.isRegExp(s))return s.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,s){if(e=uu(e),e){const n=P.findKey(this,e);return!!(n&&this[n]!==void 0&&(!s||Cp(this,this[n],n,s)))}return!1}delete(e,s){const n=this;let r=!1;function i(a){if(a=uu(a),a){const l=P.findKey(n,a);l&&(!s||Cp(n,n[l],l,s))&&(delete n[l],r=!0)}}return P.isArray(e)?e.forEach(i):i(e),r}clear(e){const s=Object.keys(this);let n=s.length,r=!1;for(;n--;){const i=s[n];(!e||Cp(this,this[i],i,e,!0))&&(delete this[i],r=!0)}return r}normalize(e){const s=this,n={};return P.forEach(this,(r,i)=>{const a=P.findKey(n,i);if(a){s[a]=of(r),delete s[i];return}const l=e?fN(i):String(i).trim();l!==i&&delete s[i],s[l]=of(r),n[l]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const s=Object.create(null);return P.forEach(this,(n,r)=>{n!=null&&n!==!1&&(s[r]=e&&P.isArray(n)?n.join(", "):n)}),s}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,s])=>e+": "+s).join(` `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...s){const n=new this(e);return s.forEach(r=>n.set(r)),n}static accessor(e){const n=(this[Z0]=this[Z0]={accessors:{}}).accessors,r=this.prototype;function i(a){const l=uu(a);n[l]||(hN(r,a),n[l]=!0)}return P.isArray(e)?e.forEach(i):i(e),this}};Ct.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);P.reduceDescriptors(Ct.prototype,({value:t},e)=>{let s=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[s]=n}}});P.freezeMethods(Ct);const pN="[REDACTED ****]";function mN(t){if(P.hasOwnProp(t,"toJSON"))return!0;let e=Object.getPrototypeOf(t);for(;e&&e!==Object.prototype;){if(P.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function xN(t,e){const s=new Set(e.map(i=>String(i).toLowerCase())),n=[],r=i=>{if(i===null||typeof i!="object"||P.isBuffer(i))return i;if(n.indexOf(i)!==-1)return;i instanceof Ct&&(i=i.toJSON()),n.push(i);let a;if(P.isArray(i))a=[],i.forEach((l,c)=>{const u=r(l);P.isUndefined(u)||(a[c]=u)});else{if(!P.isPlainObject(i)&&mN(i))return n.pop(),i;a=Object.create(null);for(const[l,c]of Object.entries(i)){const u=s.has(l.toLowerCase())?pN:r(c);P.isUndefined(u)||(a[l]=u)}}return n.pop(),a};return r(t)}let de=class R1 extends Error{static from(e,s,n,r,i,a){const l=new R1(e.message,s||e.code,n,r,i);return l.cause=e,l.name=e.name,e.status!=null&&l.status==null&&(l.status=e.status),a&&Object.assign(l,a),l}constructor(e,s,n,r,i){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,s&&(this.code=s),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status)}toJSON(){const e=this.config,s=e&&P.hasOwnProp(e,"redact")?e.redact:void 0,n=P.isArray(s)&&s.length>0?xN(e,s):P.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:n,code:this.code,status:this.status}}};de.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";de.ERR_BAD_OPTION="ERR_BAD_OPTION";de.ECONNABORTED="ECONNABORTED";de.ETIMEDOUT="ETIMEDOUT";de.ECONNREFUSED="ECONNREFUSED";de.ERR_NETWORK="ERR_NETWORK";de.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";de.ERR_DEPRECATED="ERR_DEPRECATED";de.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";de.ERR_BAD_REQUEST="ERR_BAD_REQUEST";de.ERR_CANCELED="ERR_CANCELED";de.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";de.ERR_INVALID_URL="ERR_INVALID_URL";de.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const gN=null;function Mm(t){return P.isPlainObject(t)||P.isArray(t)}function F1(t){return P.endsWith(t,"[]")?t.slice(0,-2):t}function Up(t,e,s){return t?t.concat(e).map(function(r,i){return r=F1(r),!s&&i?"["+r+"]":r}).join(s?".":""):e}function yN(t){return P.isArray(t)&&!t.some(Mm)}const _N=P.toFlatObject(P,{},null,function(e){return/^is[A-Z]/.test(e)});function Th(t,e,s){if(!P.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,s=P.toFlatObject(s,{metaTokens:!0,dots:!1,indexes:!1},!1,function(k,x){return!P.isUndefined(x[k])});const n=s.metaTokens,r=s.visitor||f,i=s.dots,a=s.indexes,l=s.Blob||typeof Blob<"u"&&Blob,c=s.maxDepth===void 0?100:s.maxDepth,u=l&&P.isSpecCompliantForm(e);if(!P.isFunction(r))throw new TypeError("visitor must be a function");function d(_){if(_===null)return"";if(P.isDate(_))return _.toISOString();if(P.isBoolean(_))return _.toString();if(!u&&P.isBlob(_))throw new de("Blob is not supported. Use a Buffer instead.");return P.isArrayBuffer(_)||P.isTypedArray(_)?u&&typeof Blob=="function"?new Blob([_]):Buffer.from(_):_}function f(_,k,x){let p=_;if(P.isReactNative(e)&&P.isReactNativeBlob(_))return e.append(Up(x,k,i),d(_)),!1;if(_&&!x&&typeof _=="object"){if(P.endsWith(k,"{}"))k=n?k:k.slice(0,-2),_=JSON.stringify(_);else if(P.isArray(_)&&yN(_)||(P.isFileList(_)||P.endsWith(k,"[]"))&&(p=P.toArray(_)))return k=F1(k),p.forEach(function(N,j){!(P.isUndefined(N)||N===null)&&e.append(a===!0?Up([k],j,i):a===null?k:k+"[]",d(N))}),!1}return Mm(_)?!0:(e.append(Up(x,k,i),d(_)),!1)}const h=[],g=Object.assign(_N,{defaultVisitor:f,convertValue:d,isVisitable:Mm});function v(_,k,x=0){if(!P.isUndefined(_)){if(x>c)throw new de("Object is too deeply nested ("+x+" levels). Max depth: "+c,de.ERR_FORM_DATA_DEPTH_EXCEEDED);if(h.indexOf(_)!==-1)throw Error("Circular reference detected in "+k.join("."));h.push(_),P.forEach(_,function(y,N){(!(P.isUndefined(y)||y===null)&&r.call(e,y,P.isString(N)?N.trim():N,k,g))===!0&&v(y,k?k.concat(N):[N],x+1)}),h.pop()}}if(!P.isObject(t))throw new TypeError("data must be an object");return v(t),e}function ey(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(t).replace(/[!'()~]|%20/g,function(n){return e[n]})}function Zx(t,e){this._pairs=[],t&&Th(t,this,e)}const L1=Zx.prototype;L1.append=function(e,s){this._pairs.push([e,s])};L1.toString=function(e){const s=e?function(n){return e.call(this,n,ey)}:ey;return this._pairs.map(function(r){return s(r[0])+"="+s(r[1])},"").join("&")};function vN(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function I1(t,e,s){if(!e)return t;const n=s&&s.encode||vN,r=P.isFunction(s)?{serialize:s}:s,i=r&&r.serialize;let a;if(i?a=i(e,r):a=P.isURLSearchParams(e)?e.toString():new Zx(e,r).toString(n),a){const l=t.indexOf("#");l!==-1&&(t=t.slice(0,l)),t+=(t.indexOf("?")===-1?"?":"&")+a}return t}class ty{constructor(){this.handlers=[]}use(e,s,n){return this.handlers.push({fulfilled:e,rejected:s,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){P.forEach(this.handlers,function(n){n!==null&&e(n)})}}const eg={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},bN=typeof URLSearchParams<"u"?URLSearchParams:Zx,wN=typeof FormData<"u"?FormData:null,SN=typeof Blob<"u"?Blob:null,kN={isBrowser:!0,classes:{URLSearchParams:bN,FormData:wN,Blob:SN},protocols:["http","https","file","blob","url","data"]},tg=typeof window<"u"&&typeof document<"u",Vm=typeof navigator=="object"&&navigator||void 0,EN=tg&&(!Vm||["ReactNative","NativeScript","NS"].indexOf(Vm.product)<0),NN=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",jN=tg&&window.location.href||"http://localhost",CN=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:tg,hasStandardBrowserEnv:EN,hasStandardBrowserWebWorkerEnv:NN,navigator:Vm,origin:jN},Symbol.toStringTag,{value:"Module"})),wt={...CN,...kN};function UN(t,e){return Th(t,new wt.classes.URLSearchParams,{visitor:function(s,n,r,i){return wt.isNode&&P.isBuffer(s)?(this.append(n,s.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...e})}function BN(t){return P.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function TN(t){const e={},s=Object.keys(t);let n;const r=s.length;let i;for(n=0;n=s.length;return a=!a&&P.isArray(r)?r.length:a,c?(P.hasOwnProp(r,a)?r[a]=P.isArray(r[a])?r[a].concat(n):[r[a],n]:r[a]=n,!l):((!P.hasOwnProp(r,a)||!P.isObject(r[a]))&&(r[a]=[]),e(s,n,r[a],i)&&P.isArray(r[a])&&(r[a]=TN(r[a])),!l)}if(P.isFormData(t)&&P.isFunction(t.entries)){const s={};return P.forEachEntry(t,(n,r)=>{e(BN(n),r,s,0)}),s}return null}const Zn=(t,e)=>t!=null&&P.hasOwnProp(t,e)?t[e]:void 0;function PN(t,e,s){if(P.isString(t))try{return(e||JSON.parse)(t),P.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(s||JSON.stringify)(t)}const hd={transitional:eg,adapter:["xhr","http","fetch"],transformRequest:[function(e,s){const n=s.getContentType()||"",r=n.indexOf("application/json")>-1,i=P.isObject(e);if(i&&P.isHTMLForm(e)&&(e=new FormData(e)),P.isFormData(e))return r?JSON.stringify(O1(e)):e;if(P.isArrayBuffer(e)||P.isBuffer(e)||P.isStream(e)||P.isFile(e)||P.isBlob(e)||P.isReadableStream(e))return e;if(P.isArrayBufferView(e))return e.buffer;if(P.isURLSearchParams(e))return s.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let l;if(i){const c=Zn(this,"formSerializer");if(n.indexOf("application/x-www-form-urlencoded")>-1)return UN(e,c).toString();if((l=P.isFileList(e))||n.indexOf("multipart/form-data")>-1){const u=Zn(this,"env"),d=u&&u.FormData;return Th(l?{"files[]":e}:e,d&&new d,c)}}return i||r?(s.setContentType("application/json",!1),PN(e)):e}],transformResponse:[function(e){const s=Zn(this,"transitional")||hd.transitional,n=s&&s.forcedJSONParsing,r=Zn(this,"responseType"),i=r==="json";if(P.isResponse(e)||P.isReadableStream(e))return e;if(e&&P.isString(e)&&(n&&!r||i)){const l=!(s&&s.silentJSONParsing)&&i;try{return JSON.parse(e,Zn(this,"parseReviver"))}catch(c){if(l)throw c.name==="SyntaxError"?de.from(c,de.ERR_BAD_RESPONSE,this,null,Zn(this,"response")):c}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:wt.classes.FormData,Blob:wt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};P.forEach(["delete","get","head","post","put","patch","query"],t=>{hd.headers[t]={}});function Bp(t,e){const s=this||hd,n=e||s,r=Ct.from(n.headers);let i=n.data;return P.forEach(t,function(l){i=l.call(s,i,r.normalize(),e?e.status:void 0)}),r.normalize(),i}function D1(t){return!!(t&&t.__CANCEL__)}let pd=class extends de{constructor(e,s,n){super(e??"canceled",de.ERR_CANCELED,s,n),this.name="CanceledError",this.__CANCEL__=!0}};function M1(t,e,s){const n=s.config.validateStatus;!s.status||!n||n(s.status)?t(s):e(new de("Request failed with status code "+s.status,s.status>=400&&s.status<500?de.ERR_BAD_REQUEST:de.ERR_BAD_RESPONSE,s.config,s.request,s))}function zN(t){const e=/^([-+\w]{1,25}):(?:\/\/)?/.exec(t);return e&&e[1]||""}function AN(t,e){t=t||10;const s=new Array(t),n=new Array(t);let r=0,i=0,a;return e=e!==void 0?e:1e3,function(c){const u=Date.now(),d=n[i];a||(a=u),s[r]=c,n[r]=u;let f=i,h=0;for(;f!==r;)h+=s[f++],f=f%t;if(r=(r+1)%t,r===i&&(i=(i+1)%t),u-a{s=d,r=null,i&&(clearTimeout(i),i=null),t(...u)};return[(...u)=>{const d=Date.now(),f=d-s;f>=n?a(u,d):(r=u,i||(i=setTimeout(()=>{i=null,a(r)},n-f)))},()=>r&&a(r)]}const qf=(t,e,s=3)=>{let n=0;const r=AN(50,250);return RN(i=>{if(!i||typeof i.loaded!="number")return;const a=i.loaded,l=i.lengthComputable?i.total:void 0,c=l!=null?Math.min(a,l):a,u=Math.max(0,c-n),d=r(u);n=Math.max(n,c);const f={loaded:c,total:l,progress:l?c/l:void 0,bytes:u,rate:d||void 0,estimated:d&&l?(l-c)/d:void 0,event:i,lengthComputable:l!=null,[e?"download":"upload"]:!0};t(f)},s)},sy=(t,e)=>{const s=t!=null;return[n=>e[0]({lengthComputable:s,total:t,loaded:n}),e[1]]},ny=t=>(...e)=>P.asap(()=>t(...e)),FN=wt.hasStandardBrowserEnv?((t,e)=>s=>(s=new URL(s,wt.origin),t.protocol===s.protocol&&t.host===s.host&&(e||t.port===s.port)))(new URL(wt.origin),wt.navigator&&/(msie|trident)/i.test(wt.navigator.userAgent)):()=>!0,LN=wt.hasStandardBrowserEnv?{write(t,e,s,n,r,i,a){if(typeof document>"u")return;const l=[`${t}=${encodeURIComponent(e)}`];P.isNumber(s)&&l.push(`expires=${new Date(s).toUTCString()}`),P.isString(n)&&l.push(`path=${n}`),P.isString(r)&&l.push(`domain=${r}`),i===!0&&l.push("secure"),P.isString(a)&&l.push(`SameSite=${a}`),document.cookie=l.join("; ")},read(t){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let s=0;st instanceof Ct?{...t}:t;function Hn(t,e){e=e||{};const s=Object.create(null);Object.defineProperty(s,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function n(u,d,f,h){return P.isPlainObject(u)&&P.isPlainObject(d)?P.merge.call({caseless:h},u,d):P.isPlainObject(d)?P.merge({},d):P.isArray(d)?d.slice():d}function r(u,d,f,h){if(P.isUndefined(d)){if(!P.isUndefined(u))return n(void 0,u,f,h)}else return n(u,d,f,h)}function i(u,d){if(!P.isUndefined(d))return n(void 0,d)}function a(u,d){if(P.isUndefined(d)){if(!P.isUndefined(u))return n(void 0,u)}else return n(void 0,d)}function l(u,d,f){if(P.hasOwnProp(e,f))return n(u,d);if(P.hasOwnProp(t,f))return n(void 0,u)}const c={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,allowedSocketPaths:a,responseEncoding:a,validateStatus:l,headers:(u,d,f)=>r(ry(u),ry(d),f,!0)};return P.forEach(Object.keys({...t,...e}),function(d){if(d==="__proto__"||d==="constructor"||d==="prototype")return;const f=P.hasOwnProp(c,d)?c[d]:r,h=P.hasOwnProp(t,d)?t[d]:void 0,g=P.hasOwnProp(e,d)?e[d]:void 0,v=f(h,g,d);P.isUndefined(v)&&f!==l||(s[d]=v)}),s}const DN=["content-type","content-length"];function MN(t,e,s){if(s!=="content-only"){t.set(e);return}Object.entries(e).forEach(([n,r])=>{DN.includes(n.toLowerCase())&&t.set(n,r)})}const VN=t=>encodeURIComponent(t).replace(/%([0-9A-F]{2})/gi,(e,s)=>String.fromCharCode(parseInt(s,16))),H1=t=>{const e=Hn({},t),s=h=>P.hasOwnProp(e,h)?e[h]:void 0,n=s("data");let r=s("withXSRFToken");const i=s("xsrfHeaderName"),a=s("xsrfCookieName");let l=s("headers");const c=s("auth"),u=s("baseURL"),d=s("allowAbsoluteUrls"),f=s("url");if(e.headers=l=Ct.from(l),e.url=I1(V1(u,f,d),t.params,t.paramsSerializer),c&&l.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?VN(c.password):""))),P.isFormData(n)&&(wt.hasStandardBrowserEnv||wt.hasStandardBrowserWebWorkerEnv?l.setContentType(void 0):P.isFunction(n.getHeaders)&&MN(l,n.getHeaders(),s("formDataHeaderPolicy"))),wt.hasStandardBrowserEnv&&(P.isFunction(r)&&(r=r(e)),r===!0||r==null&&FN(e.url))){const g=i&&a&&LN.read(a);g&&l.set(i,g)}return e},HN=typeof XMLHttpRequest<"u",$N=HN&&function(t){return new Promise(function(s,n){const r=H1(t);let i=r.data;const a=Ct.from(r.headers).normalize();let{responseType:l,onUploadProgress:c,onDownloadProgress:u}=r,d,f,h,g,v;function _(){g&&g(),v&&v(),r.cancelToken&&r.cancelToken.unsubscribe(d),r.signal&&r.signal.removeEventListener("abort",d)}let k=new XMLHttpRequest;k.open(r.method.toUpperCase(),r.url,!0),k.timeout=r.timeout;function x(){if(!k)return;const y=Ct.from("getAllResponseHeaders"in k&&k.getAllResponseHeaders()),j={data:!l||l==="text"||l==="json"?k.responseText:k.response,status:k.status,statusText:k.statusText,headers:y,config:t,request:k};M1(function(B){s(B),_()},function(B){n(B),_()},j),k=null}"onloadend"in k?k.onloadend=x:k.onreadystatechange=function(){!k||k.readyState!==4||k.status===0&&!(k.responseURL&&k.responseURL.startsWith("file:"))||setTimeout(x)},k.onabort=function(){k&&(n(new de("Request aborted",de.ECONNABORTED,t,k)),_(),k=null)},k.onerror=function(N){const j=N&&N.message?N.message:"Network Error",w=new de(j,de.ERR_NETWORK,t,k);w.event=N||null,n(w),_(),k=null},k.ontimeout=function(){let N=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const j=r.transitional||eg;r.timeoutErrorMessage&&(N=r.timeoutErrorMessage),n(new de(N,j.clarifyTimeoutError?de.ETIMEDOUT:de.ECONNABORTED,t,k)),_(),k=null},i===void 0&&a.setContentType(null),"setRequestHeader"in k&&P.forEach(A1(a),function(N,j){k.setRequestHeader(j,N)}),P.isUndefined(r.withCredentials)||(k.withCredentials=!!r.withCredentials),l&&l!=="json"&&(k.responseType=r.responseType),u&&([h,v]=qf(u,!0),k.addEventListener("progress",h)),c&&k.upload&&([f,g]=qf(c),k.upload.addEventListener("progress",f),k.upload.addEventListener("loadend",g)),(r.cancelToken||r.signal)&&(d=y=>{k&&(n(!y||y.type?new pd(null,t,k):y),k.abort(),_(),k=null)},r.cancelToken&&r.cancelToken.subscribe(d),r.signal&&(r.signal.aborted?d():r.signal.addEventListener("abort",d)));const p=zN(r.url);if(p&&!wt.protocols.includes(p)){n(new de("Unsupported protocol "+p+":",de.ERR_BAD_REQUEST,t));return}k.send(i||null)})},WN=(t,e)=>{if(t=t?t.filter(Boolean):[],!e&&!t.length)return;const s=new AbortController;let n=!1;const r=function(c){if(!n){n=!0,a();const u=c instanceof Error?c:this.reason;s.abort(u instanceof de?u:new pd(u instanceof Error?u.message:u))}};let i=e&&setTimeout(()=>{i=null,r(new de(`timeout of ${e}ms exceeded`,de.ETIMEDOUT))},e);const a=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(c=>{c.unsubscribe?c.unsubscribe(r):c.removeEventListener("abort",r)}),t=null)};t.forEach(c=>c.addEventListener("abort",r));const{signal:l}=s;return l.unsubscribe=()=>P.asap(a),l},GN=function*(t,e){let s=t.byteLength;if(s{const r=qN(t,e);let i=0,a,l=c=>{a||(a=!0,n&&n(c))};return new ReadableStream({async pull(c){try{const{done:u,value:d}=await r.next();if(u){l(),c.close();return}let f=d.byteLength;if(s){let h=i+=f;s(h)}c.enqueue(new Uint8Array(d))}catch(u){throw l(u),u}},cancel(c){return l(c),r.return()}},{highWaterMark:2})};function KN(t){if(!t||typeof t!="string"||!t.startsWith("data:"))return 0;const e=t.indexOf(",");if(e<0)return 0;const s=t.slice(5,e),n=t.slice(e+1);if(/;base64/i.test(s)){let a=n.length;const l=n.length;for(let g=0;g=48&&v<=57||v>=65&&v<=70||v>=97&&v<=102)&&(_>=48&&_<=57||_>=65&&_<=70||_>=97&&_<=102)&&(a-=2,g+=2)}let c=0,u=l-1;const d=g=>g>=2&&n.charCodeAt(g-2)===37&&n.charCodeAt(g-1)===51&&(n.charCodeAt(g)===68||n.charCodeAt(g)===100);u>=0&&(n.charCodeAt(u)===61?(c++,u--):d(u)&&(c++,u-=3)),c===1&&u>=0&&(n.charCodeAt(u)===61||d(u))&&c++;const h=Math.floor(a/4)*3-(c||0);return h>0?h:0}if(typeof Buffer<"u"&&typeof Buffer.byteLength=="function")return Buffer.byteLength(n,"utf8");let i=0;for(let a=0,l=n.length;a=55296&&c<=56319&&a+1=56320&&u<=57343?(i+=4,a++):i+=3}else i+=3}return i}const sg="1.16.1",ay=64*1024,{isFunction:Id}=P,oy=(t,...e)=>{try{return!!t(...e)}catch{return!1}},QN=t=>{const e=P.global!==void 0&&P.global!==null?P.global:globalThis,{ReadableStream:s,TextEncoder:n}=e;t=P.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},t);const{fetch:r,Request:i,Response:a}=t,l=r?Id(r):typeof fetch=="function",c=Id(i),u=Id(a);if(!l)return!1;const d=l&&Id(s),f=l&&(typeof n=="function"?(x=>p=>x.encode(p))(new n):async x=>new Uint8Array(await new i(x).arrayBuffer())),h=c&&d&&oy(()=>{let x=!1;const p=new i(wt.origin,{body:new s,method:"POST",get duplex(){return x=!0,"half"}}),y=p.headers.has("Content-Type");return p.body!=null&&p.body.cancel(),x&&!y}),g=u&&d&&oy(()=>P.isReadableStream(new a("").body)),v={stream:g&&(x=>x.body)};l&&["text","arrayBuffer","blob","formData","stream"].forEach(x=>{!v[x]&&(v[x]=(p,y)=>{let N=p&&p[x];if(N)return N.call(p);throw new de(`Response type '${x}' is not supported`,de.ERR_NOT_SUPPORT,y)})});const _=async x=>{if(x==null)return 0;if(P.isBlob(x))return x.size;if(P.isSpecCompliantForm(x))return(await new i(wt.origin,{method:"POST",body:x}).arrayBuffer()).byteLength;if(P.isArrayBufferView(x)||P.isArrayBuffer(x))return x.byteLength;if(P.isURLSearchParams(x)&&(x=x+""),P.isString(x))return(await f(x)).byteLength},k=async(x,p)=>{const y=P.toFiniteNumber(x.getContentLength());return y??_(p)};return async x=>{let{url:p,method:y,data:N,signal:j,cancelToken:w,timeout:B,onDownloadProgress:T,onUploadProgress:O,responseType:C,headers:q,withCredentials:V="same-origin",fetchOptions:I,maxContentLength:ne,maxBodyLength:X}=H1(x);const pe=P.isNumber(ne)&&ne>-1,D=P.isNumber(X)&&X>-1;let R=r||fetch;C=C?(C+"").toLowerCase():"text";let U=WN([j,w&&w.toAbortSignal()],B),z=null;const G=U&&U.unsubscribe&&(()=>{U.unsubscribe()});let te;try{if(pe&&typeof p=="string"&&p.startsWith("data:")&&KN(p)>ne)throw new de("maxContentLength size of "+ne+" exceeded",de.ERR_BAD_RESPONSE,x,z);if(D&&y!=="get"&&y!=="head"){const ie=await k(q,N);if(typeof ie=="number"&&isFinite(ie)&&ie>X)throw new de("Request body larger than maxBodyLength limit",de.ERR_BAD_REQUEST,x,z)}if(O&&h&&y!=="get"&&y!=="head"&&(te=await k(q,N))!==0){let ie=new i(p,{method:"POST",body:N,duplex:"half"}),ge;if(P.isFormData(N)&&(ge=ie.headers.get("content-type"))&&q.setContentType(ge),ie.body){const[We,Ye]=sy(te,qf(ny(O)));N=iy(ie.body,ay,We,Ye)}}P.isString(V)||(V=V?"include":"omit");const Z=c&&"credentials"in i.prototype;if(P.isFormData(N)){const ie=q.getContentType();ie&&/^multipart\/form-data/i.test(ie)&&!/boundary=/i.test(ie)&&q.delete("content-type")}q.set("User-Agent","axios/"+sg,!1);const K={...I,signal:U,method:y.toUpperCase(),headers:A1(q.normalize()),body:N,duplex:"half",credentials:Z?V:void 0};z=c&&new i(p,K);let $=await(c?R(z,I):R(p,K));if(pe){const ie=P.toFiniteNumber($.headers.get("content-length"));if(ie!=null&&ie>ne)throw new de("maxContentLength size of "+ne+" exceeded",de.ERR_BAD_RESPONSE,x,z)}const ee=g&&(C==="stream"||C==="response");if(g&&$.body&&(T||pe||ee&&G)){const ie={};["status","statusText","headers"].forEach(Ge=>{ie[Ge]=$[Ge]});const ge=P.toFiniteNumber($.headers.get("content-length")),[We,Ye]=T&&sy(ge,qf(ny(T),!0))||[];let Ue=0;const Pt=Ge=>{if(pe&&(Ue=Ge,Ue>ne))throw new de("maxContentLength size of "+ne+" exceeded",de.ERR_BAD_RESPONSE,x,z);We&&We(Ge)};$=new a(iy($.body,ay,Pt,()=>{Ye&&Ye(),G&&G()}),ie)}C=C||"text";let re=await v[P.findKey(v,C)||"text"]($,x);if(pe&&!g&&!ee){let ie;if(re!=null&&(typeof re.byteLength=="number"?ie=re.byteLength:typeof re.size=="number"?ie=re.size:typeof re=="string"&&(ie=typeof n=="function"?new n().encode(re).byteLength:re.length)),typeof ie=="number"&&ie>ne)throw new de("maxContentLength size of "+ne+" exceeded",de.ERR_BAD_RESPONSE,x,z)}return!ee&&G&&G(),await new Promise((ie,ge)=>{M1(ie,ge,{data:re,headers:Ct.from($.headers),status:$.status,statusText:$.statusText,config:x,request:z})})}catch(Z){if(G&&G(),U&&U.aborted&&U.reason instanceof de){const K=U.reason;throw K.config=x,z&&(K.request=z),Z!==K&&(K.cause=Z),K}throw Z&&Z.name==="TypeError"&&/Load failed|fetch/i.test(Z.message)?Object.assign(new de("Network Error",de.ERR_NETWORK,x,z,Z&&Z.response),{cause:Z.cause||Z}):de.from(Z,Z&&Z.code,x,z,Z&&Z.response)}}},YN=new Map,$1=t=>{let e=t&&t.env||{};const{fetch:s,Request:n,Response:r}=e,i=[n,r,s];let a=i.length,l=a,c,u,d=YN;for(;l--;)c=i[l],u=d.get(c),u===void 0&&d.set(c,u=l?new Map:QN(e)),d=u;return u};$1();const ng={http:gN,xhr:$N,fetch:{get:$1}};P.forEach(ng,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(t,"adapterName",{__proto__:null,value:e})}});const ly=t=>`- ${t}`,XN=t=>P.isFunction(t)||t===null||t===!1;function ZN(t,e){t=P.isArray(t)?t:[t];const{length:s}=t;let n,r;const i={};for(let a=0;a`adapter ${c} `+(u===!1?"is not supported by the environment":"is not available in the build"));let l=s?a.length>1?`since : `+a.map(ly).join(` `):" "+ly(a[0]):"as no adapter specified";throw new de("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return r}const W1={getAdapter:ZN,adapters:ng};function Tp(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new pd(null,t)}function cy(t){return Tp(t),t.headers=Ct.from(t.headers),t.data=Bp.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),W1.getAdapter(t.adapter||hd.adapter,t)(t).then(function(n){Tp(t),t.response=n;try{n.data=Bp.call(t,t.transformResponse,n)}finally{delete t.response}return n.headers=Ct.from(n.headers),n},function(n){if(!D1(n)&&(Tp(t),n&&n.response)){t.response=n.response;try{n.response.data=Bp.call(t,t.transformResponse,n.response)}finally{delete t.response}n.response.headers=Ct.from(n.response.headers)}return Promise.reject(n)})}const Ph={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Ph[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const uy={};Ph.transitional=function(e,s,n){function r(i,a){return"[Axios v"+sg+"] Transitional option '"+i+"'"+a+(n?". "+n:"")}return(i,a,l)=>{if(e===!1)throw new de(r(a," has been removed"+(s?" in "+s:"")),de.ERR_DEPRECATED);return s&&!uy[a]&&(uy[a]=!0,console.warn(r(a," has been deprecated since v"+s+" and will be removed in the near future"))),e?e(i,a,l):!0}};Ph.spelling=function(e){return(s,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function ej(t,e,s){if(typeof t!="object")throw new de("options must be an object",de.ERR_BAD_OPTION_VALUE);const n=Object.keys(t);let r=n.length;for(;r-- >0;){const i=n[r],a=Object.prototype.hasOwnProperty.call(e,i)?e[i]:void 0;if(a){const l=t[i],c=l===void 0||a(l,i,t);if(c!==!0)throw new de("option "+i+" must be "+c,de.ERR_BAD_OPTION_VALUE);continue}if(s!==!0)throw new de("Unknown option "+i,de.ERR_BAD_OPTION)}}const lf={assertOptions:ej,validators:Ph},Jt=lf.validators;let Fn=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ty,response:new ty}}async request(e,s){try{return await this._request(e,s)}catch(n){if(n instanceof Error){let r={};Error.captureStackTrace?Error.captureStackTrace(r):r=new Error;const i=(()=>{if(!r.stack)return"";const a=r.stack.indexOf(` `);return a===-1?"":r.stack.slice(a+1)})();try{if(!n.stack)n.stack=i;else if(i){const a=i.indexOf(` `),l=a===-1?-1:i.indexOf(` `,a+1),c=l===-1?"":i.slice(l+1);String(n.stack).endsWith(c)||(n.stack+=` `+i)}}catch{}}throw n}}_request(e,s){typeof e=="string"?(s=s||{},s.url=e):s=e||{},s=Hn(this.defaults,s);const{transitional:n,paramsSerializer:r,headers:i}=s;n!==void 0&&lf.assertOptions(n,{silentJSONParsing:Jt.transitional(Jt.boolean),forcedJSONParsing:Jt.transitional(Jt.boolean),clarifyTimeoutError:Jt.transitional(Jt.boolean),legacyInterceptorReqResOrdering:Jt.transitional(Jt.boolean)},!1),r!=null&&(P.isFunction(r)?s.paramsSerializer={serialize:r}:lf.assertOptions(r,{encode:Jt.function,serialize:Jt.function},!0)),s.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?s.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:s.allowAbsoluteUrls=!0),lf.assertOptions(s,{baseUrl:Jt.spelling("baseURL"),withXsrfToken:Jt.spelling("withXSRFToken")},!0),s.method=(s.method||this.defaults.method||"get").toLowerCase();let a=i&&P.merge(i.common,i[s.method]);i&&P.forEach(["delete","get","head","post","put","patch","query","common"],v=>{delete i[v]}),s.headers=Ct.concat(a,i);const l=[];let c=!0;this.interceptors.request.forEach(function(_){if(typeof _.runWhen=="function"&&_.runWhen(s)===!1)return;c=c&&_.synchronous;const k=s.transitional||eg;k&&k.legacyInterceptorReqResOrdering?l.unshift(_.fulfilled,_.rejected):l.push(_.fulfilled,_.rejected)});const u=[];this.interceptors.response.forEach(function(_){u.push(_.fulfilled,_.rejected)});let d,f=0,h;if(!c){const v=[cy.bind(this),void 0];for(v.unshift(...l),v.push(...u),h=v.length,d=Promise.resolve(s);f{if(!n._listeners)return;let i=n._listeners.length;for(;i-- >0;)n._listeners[i](r);n._listeners=null}),this.promise.then=r=>{let i;const a=new Promise(l=>{n.subscribe(l),i=l}).then(r);return a.cancel=function(){n.unsubscribe(i)},a},e(function(i,a,l){n.reason||(n.reason=new pd(i,a,l),s(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const s=this._listeners.indexOf(e);s!==-1&&this._listeners.splice(s,1)}toAbortSignal(){const e=new AbortController,s=n=>{e.abort(n)};return this.subscribe(s),e.signal.unsubscribe=()=>this.unsubscribe(s),e.signal}static source(){let e;return{token:new G1(function(r){e=r}),cancel:e}}};function sj(t){return function(s){return t.apply(null,s)}}function nj(t){return P.isObject(t)&&t.isAxiosError===!0}const Hm={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Hm).forEach(([t,e])=>{Hm[e]=t});function q1(t){const e=new Fn(t),s=N1(Fn.prototype.request,e);return P.extend(s,Fn.prototype,e,{allOwnKeys:!0}),P.extend(s,e,null,{allOwnKeys:!0}),s.create=function(r){return q1(Hn(t,r))},s}const Je=q1(hd);Je.Axios=Fn;Je.CanceledError=pd;Je.CancelToken=tj;Je.isCancel=D1;Je.VERSION=sg;Je.toFormData=Th;Je.AxiosError=de;Je.Cancel=Je.CanceledError;Je.all=function(e){return Promise.all(e)};Je.spread=sj;Je.isAxiosError=nj;Je.mergeConfig=Hn;Je.AxiosHeaders=Ct;Je.formToJSON=t=>O1(P.isHTMLForm(t)?new FormData(t):t);Je.getAdapter=W1.getAdapter;Je.HttpStatusCode=Hm;Je.default=Je;const{Axios:cP,AxiosError:uP,CanceledError:dP,isCancel:fP,CancelToken:hP,VERSION:pP,all:mP,Cancel:xP,isAxiosError:gP,spread:yP,toFormData:_P,AxiosHeaders:vP,HttpStatusCode:bP,formToJSON:wP,getAdapter:SP,mergeConfig:kP,create:EP}=Je;/*! js-cookie v3.0.7 | MIT */function Od(t){for(var e=1;e"u")){a=Od({},e,a),typeof a.expires=="number"&&(a.expires=new Date(Date.now()+a.expires*864e5)),a.expires&&(a.expires=a.expires.toUTCString()),r=encodeURIComponent(r).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var l="";for(var c in a)a[c]&&(l+="; "+c,a[c]!==!0&&(l+="="+a[c].split(";")[0]));return document.cookie=r+"="+t.write(i,r)+l}}function n(r){if(!(typeof document>"u"||arguments.length&&!r)){for(var i=document.cookie?document.cookie.split("; "):[],a={},l=0;l({sameSite:"strict",...t?{expires:new Date(t)}:{}});function ij(t){var e,s,n,r;zh.set(Ah,JSON.stringify({access_token:t.access_token,refresh_token:t.refresh_token,access_token_exp:t.access_token_exp,refresh_token_exp:t.refresh_token_exp,user_id:(e=t.user)==null?void 0:e.id,email:(s=t.user)==null?void 0:s.email,user_type:(n=t.user)==null?void 0:n.user_type,labelling_role:(r=t.user)==null?void 0:r.labelling_role}),J1(t.access_token_exp))}function Sr(){const t=zh.get(Ah);return t?JSON.parse(t):{}}function aj(t,e,s){const n=Sr();zh.set(Ah,JSON.stringify({...n,access_token:t,access_token_exp:e,refresh_token:s}),J1(e))}function K1(){zh.remove(Ah)}const oj="https://verifyai-auth-api-staging-143845647654.us-central1.run.app",lj="https://labelling-api-staging-qhltoug3za-uc.a.run.app";function Q1(t,e){return typeof t=="string"&&t.trim()?t.trim():e}const Jf=Je.create({baseURL:Q1("https://verifyai-auth-api-staging-143845647654.us-central1.run.app",oj),headers:{"Content-Type":"application/json"}}),we=Je.create({baseURL:Q1("https://labelling-api-staging-143845647654.us-central1.run.app",lj),headers:{"Content-Type":"application/json"}});let Dd=null;async function cj(){const{refresh_token:t}=Sr();if(!t)throw new Error("No refresh token");const s=(await Jf.post("/api/v1/auth/refresh",{refresh_token:t})).data;if(!s.access_token)throw new Error("No access_token in refresh response");return aj(s.access_token,s.access_token_exp,s.refresh_token),s.access_token}we.interceptors.request.use(t=>{const{access_token:e}=Sr();return e&&(t.headers.Authorization=`Bearer ${e}`),t});we.interceptors.response.use(t=>t,async t=>{var s,n;const e=t.config||{};if(((s=t.response)==null?void 0:s.status)===401&&!e._retry){e._retry=!0,Dd||(Dd=cj().finally(()=>{Dd=null}));try{const r=await Dd;return e.headers=e.headers||{},e.headers.Authorization=`Bearer ${r}`,we(e)}catch{return K1(),window.location.replace("/login"),Promise.reject(t)}}return Promise.reject(((n=t==null?void 0:t.response)==null?void 0:n.data)??t)});async function uj({email:t,password:e}){return(await Jf.post("/api/v1/auth/login",{email:t,password:e})).data}async function dj({access_token:t,refresh_token:e}){try{await Jf.post("/api/v1/auth/revoke",{token:t,token_type:"access"},{headers:{Authorization:`Bearer ${t}`}}),e&&await Jf.post("/api/v1/auth/revoke",{token:e,token_type:"refresh"},{headers:{Authorization:`Bearer ${t}`}})}catch{}}const Y1=m.createContext(null);function fj({children:t}){const[e,s]=m.useState(()=>{const i=Sr();return i!=null&&i.access_token?i:null}),n=m.useCallback(async i=>{const a=await uj(i);return ij(a),s(Sr()),a},[]),r=m.useCallback(async()=>{const i=Sr();await dj({access_token:i==null?void 0:i.access_token,refresh_token:i==null?void 0:i.refresh_token}),K1(),s(null)},[]);return o.jsx(Y1.Provider,{value:{user:e,login:n,logout:r},children:t})}function wn(){return m.useContext(Y1)}function hj(){const{user:t}=wn();return t?o.jsx(k1,{}):o.jsx(Yx,{to:"/login",replace:!0})}var md=t=>t.type==="checkbox",Pn=t=>t instanceof Date,ft=t=>t==null;const X1=t=>typeof t=="object";var Me=t=>!ft(t)&&!Array.isArray(t)&&X1(t)&&!Pn(t),pj=t=>Me(t)&&t.target?md(t.target)?t.target.checked:t.target.value:t,dy=(t,e)=>{const s=e.split("."),n=[];let r=s[0];for(let i=1;i{const e=t.constructor&&t.constructor.prototype;return Me(e)&&e.hasOwnProperty("isPrototypeOf")},rg=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Xe(t){if(t instanceof Date)return new Date(t);const e=typeof FileList<"u"&&t instanceof FileList;if(rg&&(t instanceof Blob||e))return t;const s=Array.isArray(t);if(!s&&!(Me(t)&&mj(t)))return t;const n=s?[]:Object.create(Object.getPrototypeOf(t));for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=Xe(t[r]));return n}var xd=t=>/^\w*$/.test(t),Fe=t=>t===void 0,ig=t=>Array.isArray(t)?t.filter(Boolean):[],Rh=t=>ig(t.replace(/["|']|\]/g,"").split(/\.|\[/)),ue=(t,e,s)=>{if(!e||!Me(t))return s;const r=(xd(e)?[e]:Rh(e)).reduce((i,a)=>ft(i)?void 0:i[a],t);return Fe(r)||r===t?Fe(t[e])?s:t[e]:r},bs=t=>typeof t=="boolean",Yt=t=>typeof t=="function",Ae=(t,e,s)=>{let n=-1;const r=xd(e)?[e]:Rh(e),i=r.length,a=i-1;for(;++n{const r={};for(const i in t)Object.defineProperty(r,i,{get:()=>{const a=i;return e._proxyFormState[a]!==cs.all&&(e._proxyFormState[a]=!n||cs.all),t[a]}});return r};const yj=typeof window<"u"?Re.useLayoutEffect:Re.useEffect;var St=t=>typeof t=="string",_j=(t,e,s,n,r)=>St(t)?(n&&e.watch.add(t),ue(s,t,r)):Array.isArray(t)?t.map(i=>(n&&e.watch.add(i),ue(s,i))):(n&&(e.watchAll=!0),s),Wm=t=>ft(t)||!X1(t);function ws(t,e,s=new WeakSet){if(t===e)return!0;if(Wm(t)||Wm(e))return Object.is(t,e);if(Pn(t)&&Pn(e))return Object.is(t.getTime(),e.getTime());const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;if(s.has(t)||s.has(e))return!0;s.add(t),s.add(e);for(const i of n){const a=t[i];if(!(i in e))return!1;if(i!=="ref"){const l=e[i];if(Pn(a)&&Pn(l)||(Me(a)||Array.isArray(a))&&(Me(l)||Array.isArray(l))?!ws(a,l,s):!Object.is(a,l))return!1}}return!0}const vj=Re.createContext(null);vj.displayName="HookFormContext";var bj=(t,e,s,n,r)=>e?{...s[t],types:{...s[t]&&s[t].types?s[t].types:{},[n]:r||!0}}:{},Uu=t=>Array.isArray(t)?t:[t],fy=()=>{let t=[];return{get observers(){return t},next:r=>{for(const i of t)i.next&&i.next(r)},subscribe:r=>(t.push(r),{unsubscribe:()=>{t=t.filter(i=>i!==r)}}),unsubscribe:()=>{t=[]}}};function eb(t,e){const s={};for(const n in t)if(t.hasOwnProperty(n)){const r=t[n],i=e[n];if(r&&Me(r)&&i){const a=eb(r,i);Me(a)&&(s[n]=a)}else t[n]&&(s[n]=i)}return s}var _t=t=>Me(t)&&!Object.keys(t).length,ag=t=>t.type==="file",Kf=t=>{if(!rg)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},tb=t=>t.type==="select-multiple",og=t=>t.type==="radio",wj=t=>og(t)||md(t),zp=t=>Kf(t)&&t.isConnected;function Sj(t,e){const s=e.slice(0,-1).length;let n=0;for(;n{for(const e in t)if(Yt(t[e]))return!0;return!1};function sb(t){return Array.isArray(t)||Me(t)&&!Ej(t)}function Gm(t,e={}){for(const s in t){const n=t[s];sb(n)?(e[s]=Array.isArray(n)?[]:{},Gm(n,e[s])):Fe(n)||(e[s]=!0)}return e}function qm(t){if(t!==!1){if(t===!0)return!0;if(Array.isArray(t)){const e=t.map(s=>qm(s));return e.some(s=>s!==void 0)?e:void 0}if(Me(t)){const e={};for(const s in t){const n=qm(t[s]);Fe(n)||(e[s]=n)}return Object.keys(e).length?e:void 0}}}function rr(t,e,s){s||(s=Gm(e));for(const n in t){const r=t[n];if(sb(r))Fe(e)||Wm(s[n])?s[n]=Gm(r,Array.isArray(r)?[]:{}):rr(r,ft(e)?{}:e[n],s[n]);else{const i=e[n];s[n]=!ws(r,i)}}return qm(s)||{}}const hy={value:!1,isValid:!1},py={value:!0,isValid:!0};var nb=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(s=>s&&s.checked&&!s.disabled).map(s=>s.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!Fe(t[0].attributes.value)?Fe(t[0].value)||t[0].value===""?py:{value:t[0].value,isValid:!0}:py:hy}return hy},rb=(t,{valueAsNumber:e,valueAsDate:s,setValueAs:n})=>Fe(t)?t:e?t===""?NaN:t&&+t:s&&St(t)?new Date(t):n?n(t):t;const my={isValid:!1,value:null};var ib=t=>Array.isArray(t)?t.reduce((e,s)=>s&&s.checked&&!s.disabled?{isValid:!0,value:s.value}:e,my):my;function xy(t){const e=t.ref;return ag(e)?e.files:og(e)?ib(t.refs).value:tb(e)?[...e.selectedOptions].map(({value:s})=>s):md(e)?nb(t.refs).value:rb(Fe(e.value)?t.ref.value:e.value,t)}var Nj=(t,e,s,n)=>{const r={};for(const i of t){const a=ue(e,i);a&&Ae(r,i,a._f)}return{criteriaMode:s,names:[...t],fields:r,shouldUseNativeValidation:n}},Qf=t=>t instanceof RegExp,du=t=>Fe(t)?t:Qf(t)?t.source:Me(t)?Qf(t.value)?t.value.source:t.value:t,gy=t=>({isOnSubmit:!t||t===cs.onSubmit,isOnBlur:t===cs.onBlur,isOnChange:t===cs.onChange,isOnAll:t===cs.all,isOnTouch:t===cs.onTouched});const yy="AsyncFunction";var jj=t=>!!t&&!!t.validate&&!!(Yt(t.validate)&&t.validate.constructor.name===yy||Me(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===yy)),Cj=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),_y=(t,e,s)=>!s&&(e.watchAll||e.watch.has(t)||[...e.watch].some(n=>t.startsWith(n)&&/^\.\w+/.test(t.slice(n.length))));const Bu=(t,e,s,n)=>{for(const r of s||Object.keys(t)){const i=ue(t,r);if(i){const{_f:a,...l}=i;if(a){if(a.refs&&a.refs[0]&&e(a.refs[0],r)&&!n)return!0;if(a.ref&&e(a.ref,a.name)&&!n)return!0;if(Bu(l,e))break}else if(Me(l)&&Bu(l,e))break}}};function vy(t,e,s){const n=ue(t,s);if(n||xd(s))return{error:n,name:s};const r=s.split(".");for(;r.length;){const i=r.join("."),a=ue(e,i),l=ue(t,i);if(a&&!Array.isArray(a)&&s!==i)return{name:s};if(l&&l.type)return{name:i,error:l};if(l&&l.root&&l.root.type)return{name:`${i}.root`,error:l.root};r.pop()}return{name:s}}var Uj=(t,e,s,n)=>{s(t);const{name:r,...i}=t;return _t(i)||n&&Object.keys(i).length>=Object.keys(e).length||Object.keys(i).find(a=>e[a]===(!n||cs.all))},Bj=(t,e,s)=>!t||!e||t===e||Uu(t).some(n=>n&&(s?n===e:n.startsWith(e)||e.startsWith(n))),Tj=(t,e,s,n,r)=>r.isOnAll?!1:!s&&r.isOnTouch?!(e||t):(s?n.isOnBlur:r.isOnBlur)?!t:(s?n.isOnChange:r.isOnChange)?t:!0,Pj=(t,e)=>!ig(ue(t,e)).length&&Ze(t,e),by=(t,e,s)=>{const n=Uu(ue(t,s));return Ae(n,Z1,e[s]),Ae(t,s,n),t};function wy(t,e,s="validate"){if(St(t)||Array.isArray(t)&&t.every(St)||bs(t)&&!t)return{type:s,message:St(t)?t:"",ref:e}}var tr=t=>Me(t)&&!Qf(t)?t:{value:t,message:""},Sy=async(t,e,s,n,r,i)=>{const{ref:a,refs:l,required:c,maxLength:u,minLength:d,min:f,max:h,pattern:g,validate:v,name:_,valueAsNumber:k,mount:x}=t._f,p=ue(s,_);if(!x||e.has(_))return{};const y=l?l[0]:a,N=V=>{r&&y.reportValidity&&(y.setCustomValidity(bs(V)?"":V||""),y.reportValidity())},j={},w=og(a),B=md(a),T=w||B,O=(k||ag(a))&&Fe(a.value)&&Fe(p)||Kf(a)&&a.value===""||p===""||Array.isArray(p)&&!p.length||k&&typeof p=="number"&&isNaN(p),C=bj.bind(null,_,n,j),q=(V,I,ne,X=is.maxLength,pe=is.minLength)=>{const D=V?I:ne;j[_]={type:V?X:pe,message:D,ref:a,...C(V?X:pe,D)}};if(i?!Array.isArray(p)||!p.length:c&&(!T&&(O||ft(p))||bs(p)&&!p||B&&!nb(l).isValid||w&&!ib(l).isValid)){const{value:V,message:I}=St(c)?{value:!!c,message:c}:tr(c);if(V&&(j[_]={type:is.required,message:I,ref:y,...C(is.required,I)},!n))return N(I),j}if(!O&&(!ft(f)||!ft(h))){let V,I;const ne=tr(h),X=tr(f);if(!ft(p)&&!isNaN(p)){const pe=a.valueAsNumber||p&&+p;ft(ne.value)||(V=pe>ne.value),ft(X.value)||(I=penew Date(new Date().toDateString()+" "+z),R=a.type=="time",U=a.type=="week";St(ne.value)&&p&&(V=R?D(p)>D(ne.value):U?p>ne.value:pe>new Date(ne.value)),St(X.value)&&p&&(I=R?D(p)+V.value,X=!ft(I.value)&&p.length<+I.value;if((ne||X)&&(q(ne,V.message,I.message),!n))return N(j[_].message),j}if(g&&!O&&St(p)){const{value:V,message:I}=tr(g);if(Qf(V)&&!p.match(V)&&(j[_]={type:is.pattern,message:I,ref:a,...C(is.pattern,I)},!n))return N(I),j}if(v){if(Yt(v)){const V=await v(p,s),I=wy(V,y);if(I&&(j[_]={...I,...C(is.validate,I.message)},!n))return N(I.message),j}else if(Me(v)){let V={};for(const I in v){if(!_t(V)&&!n)break;const ne=wy(await v[I](p,s),y,I);ne&&(V={...ne,...C(I,ne.message)},N(ne.message),n&&(j[_]=V))}if(!_t(V)&&(j[_]={ref:y,...V},!n))return j}}return N(!0),j};const zj={mode:cs.onSubmit,reValidateMode:cs.onChange,shouldFocusError:!0},ab={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function Aj(t={}){let e={...zj,...t},s={...Xe(ab),isLoading:Yt(e.defaultValues),errors:e.errors||{},disabled:e.disabled||!1},n={},r=Me(e.defaultValues)||Me(e.values)?Xe(e.defaultValues||e.values)||{}:{},i=e.shouldUnregister?{}:Xe(r),a={action:!1,mount:!1,watch:!1,keepIsValid:!1},l={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set},c,u=0;const d={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},f={...d};let h={...f};const g={array:fy(),state:fy()},v=e.criteriaMode===cs.all,_=b=>S=>{clearTimeout(u),u=setTimeout(b,S)},k=async b=>{if(!a.keepIsValid&&!e.disabled&&(f.isValid||h.isValid||b)){let S;e.resolver?(S=_t((await C()).errors),x()):S=await I({fields:n,onlyCheckValid:!0,eventType:er.VALID}),S!==s.isValid&&g.state.next({isValid:S})}},x=(b,S)=>{!e.disabled&&(f.isValidating||f.validatingFields||h.isValidating||h.validatingFields)&&((b||Array.from(l.mount)).forEach(E=>{E&&(S?Ae(s.validatingFields,E,S):Ze(s.validatingFields,E))}),g.state.next({validatingFields:s.validatingFields,isValidating:!_t(s.validatingFields)}))},p=()=>{s.dirtyFields=rr(r,i)},y=(b,S=[],E,F,L=!0,W=!0)=>{if(F&&E&&!e.disabled){if(a.action=!0,W&&Array.isArray(ue(n,b))){const Q=E(ue(n,b),F.argA,F.argB);L&&Ae(n,b,Q)}if(W&&Array.isArray(ue(s.errors,b))){const Q=E(ue(s.errors,b),F.argA,F.argB);L&&Ae(s.errors,b,Q),Pj(s.errors,b)}if((f.touchedFields||h.touchedFields)&&W&&Array.isArray(ue(s.touchedFields,b))){const Q=E(ue(s.touchedFields,b),F.argA,F.argB);L&&Ae(s.touchedFields,b,Q)}(f.dirtyFields||h.dirtyFields)&&p(),g.state.next({name:b,isDirty:X(b,S),dirtyFields:s.dirtyFields,errors:s.errors,isValid:s.isValid})}else Ae(i,b,S)},N=(b,S)=>{Ae(s.errors,b,S),g.state.next({errors:s.errors})},j=b=>{s.errors=b,g.state.next({errors:s.errors,isValid:!1})},w=b=>{const S=xd(b)?[b]:Rh(b);let E=i,F=r;for(let L=0;L{const L=ue(n,b);if(L){if(w(b))return;const W=Fe(ue(i,b)),Q=ue(i,b,Fe(E)?ue(r,b):E);Fe(Q)||F&&F.defaultChecked||S?Ae(i,b,S?Q:xy(L._f)):R(b,Q),a.mount&&!a.action&&(k(),W&&s.isDirty&&(f.isDirty||h.isDirty)&&(X()||(s.isDirty=!1,g.state.next({...s}))))}},T=(b,S,E,F,L)=>{let W=!1,Q=!1;const le={name:b};if(!e.disabled){if(!E||F){(f.isDirty||h.isDirty)&&(Q=s.isDirty,s.isDirty=le.isDirty=X(),W=Q!==le.isDirty);const he=ws(ue(r,b),S);Q=!!ue(s.dirtyFields,b),he!==s.isDirty?s.dirtyFields=rr(r,i):he?Ze(s.dirtyFields,b):Ae(s.dirtyFields,b,!0),le.dirtyFields=s.dirtyFields,W=W||(f.dirtyFields||h.dirtyFields)&&Q!==!he}if(E){const he=ue(s.touchedFields,b);he||(Ae(s.touchedFields,b,E),le.touchedFields=s.touchedFields,W=W||(f.touchedFields||h.touchedFields)&&he!==E)}W&&L&&g.state.next(le)}return W?le:{}},O=(b,S,E,F)=>{const L=ue(s.errors,b),W=(f.isValid||h.isValid)&&bs(S)&&s.isValid!==S;if(e.delayError&&E?(c=_(()=>N(b,E)),c(e.delayError)):(clearTimeout(u),c=null,E?Ae(s.errors,b,E):Ze(s.errors,b)),(E?!ws(L,E):L)||!_t(F)||W){const Q={...F,...W&&bs(S)?{isValid:S}:{},errors:s.errors,name:b};s={...s,...Q},g.state.next(Q)}},C=async b=>(x(b,!0),await e.resolver(i,e.context,Nj(b||l.mount,n,e.criteriaMode,e.shouldUseNativeValidation))),q=async b=>{const{errors:S}=await C(b);if(x(b),b)for(const E of b){const F=ue(S,E);F?l.array.has(E)&&Me(F)?by(s.errors,{[E]:F},E):Ae(s.errors,E,F):Ze(s.errors,E)}else s.errors=S;return S},V=async({name:b,eventType:S})=>{if(t.validate){const E=await t.validate({formValues:i,formState:s,name:b,eventType:S});if(Me(E))for(const F in E){const L=E[F];L&&ie(`${Pp}.${F}`,{message:St(L.message)?L.message:"",type:L.type||is.validate})}else St(E)||!E?ie(Pp,{message:E||"",type:is.validate}):re(Pp);return E}return!0},I=async({fields:b,onlyCheckValid:S,name:E,eventType:F,context:L={valid:!0,runRootValidation:!1}})=>{if(t.validate&&(L.runRootValidation=!0,!await V({name:E,eventType:F})&&(L.valid=!1,S)))return L.valid;for(const W in b){const Q=b[W];if(Q){const{_f:le,...he}=Q;if(le){const Be=l.array.has(le.name),xt=Q._f&&jj(Q._f),it=f.validatingFields||f.isValidating||h.validatingFields||h.isValidating;xt&&it&&x([le.name],!0);const gs=await Sy(Q,l.disabled,i,v,e.shouldUseNativeValidation&&!S,Be);if(xt&&it&&x([le.name]),gs[le.name]&&(L.valid=!1,S)||(!S&&(ue(gs,le.name)?Be?by(s.errors,gs,le.name):Ae(s.errors,le.name,gs[le.name]):Ze(s.errors,le.name)),t.shouldUseNativeValidation&&gs[le.name]))break}!_t(he)&&await I({context:L,onlyCheckValid:S,fields:he,name:W,eventType:F})}}return L.valid},ne=()=>{for(const b of l.unMount){const S=ue(n,b);S&&(S._f.refs?S._f.refs.every(E=>!zp(E)):!zp(S._f.ref))&&Ue(b)}l.unMount=new Set},X=(b,S)=>!e.disabled&&(b&&S&&Ae(i,b,S),!ws($(),r)),pe=(b,S,E)=>_j(b,l,{...a.mount?i:Fe(S)?r:St(b)?{[b]:S}:S},E,S),D=b=>ig(ue(a.mount?i:r,b,e.shouldUnregister?ue(r,b,[]):[])),R=(b,S,E={})=>{const F=ue(n,b);let L=S;if(F){const W=F._f;W&&(!W.disabled&&Ae(i,b,rb(S,W)),L=Kf(W.ref)&&ft(S)?"":S,tb(W.ref)?[...W.ref.options].forEach(Q=>Q.selected=L.includes(Q.value)):W.refs?md(W.ref)?W.refs.forEach(Q=>{(!Q.defaultChecked||!Q.disabled)&&(Array.isArray(L)?Q.checked=!!L.find(le=>le===Q.value):Q.checked=L===Q.value||!!L)}):W.refs.forEach(Q=>Q.checked=Q.value===L):ag(W.ref)?W.ref.value="":(W.ref.value=L,W.ref.type||g.state.next({name:b,values:Xe(i)})))}(E.shouldDirty||E.shouldTouch)&&T(b,L,E.shouldTouch,E.shouldDirty,!0),E.shouldValidate&&K(b)},U=(b,S,E)=>{for(const F in S){if(!S.hasOwnProperty(F))return;const L=S[F],W=b+"."+F,Q=ue(n,W);(l.array.has(b)||Me(L)||Q&&!Q._f)&&!Pn(L)?U(W,L,E):R(W,L,E)}},z=(b,S,E={})=>{const F=ue(n,b),L=l.array.has(b),W=Xe(S),Q=ue(i,b),le=ws(Q,W);if(le||Ae(i,b,W),L)g.array.next({name:b,values:Xe(i)}),(f.isDirty||f.dirtyFields||h.isDirty||h.dirtyFields)&&E.shouldDirty&&(p(),g.state.next({name:b,dirtyFields:s.dirtyFields,isDirty:X(b,W)}));else{const he=Array.isArray(W)&&!W.length||_t(W);!F||F._f||ft(W)||he?R(b,W,E):U(b,W,E)}if(!le){const he=_y(b,l),Be=Xe(i);if(!L)for(const xt of dy(l.array,b))g.array.next({name:xt,values:Be});g.state.next({...he&&s,name:a.mount||he?b:void 0,values:Be})}},G=b=>{const S=Yt(b)?b(i):b;if(!ws(i,S)){i={...i,...S};for(const E of l.mount)z(E,ue(S,E));g.state.next({...s,values:i})}},te=async b=>{a.mount=!0;const S=b.target;let E=S.name,F=!0;const L=ue(n,E),W=he=>{F=Number.isNaN(he)||Pn(he)&&isNaN(he.getTime())||ws(he,ue(i,E,he))},Q=gy(e.mode),le=gy(e.reValidateMode);if(L){let he,Be;const xt=S.type?xy(L._f):pj(b),it=b.type===er.BLUR||b.type===er.FOCUS_OUT,gs=!Cj(L._f)&&!t.validate&&!e.resolver&&!ue(s.errors,E)&&!L._f.deps||Tj(it,ue(s.touchedFields,E),s.isSubmitted,le,Q),Kn=_y(E,l,it);Ae(i,E,xt),it?(!S||!S.readOnly)&&(L._f.onBlur&&L._f.onBlur(b),c&&c(0)):L._f.onChange&&L._f.onChange(b);const Qn=T(E,xt,it),gd=!_t(Qn)||Kn;if(!it&&g.state.next({name:E,type:b.type,values:Xe(i)}),gs)return(f.isValid||h.isValid)&&(e.mode==="onBlur"?it&&k():it||k()),gd&&g.state.next({name:E,...Kn?{}:Qn});if(!e.resolver&&t.validate&&await V({name:E,eventType:b.type}),!it&&Kn&&g.state.next({...s}),e.resolver){const{errors:yd}=await C([E]);if(x([E]),W(xt),F){const Yc=vy(s.errors,n,E),Mt=vy(yd,n,Yc.name||E);he=Mt.error,E=Mt.name,Be=_t(yd)}}else x([E],!0),he=(await Sy(L,l.disabled,i,v,e.shouldUseNativeValidation))[E],x([E]),W(xt),F&&(he?Be=!1:(f.isValid||h.isValid)&&(Be=await I({fields:n,onlyCheckValid:!0,name:E,eventType:b.type})));F&&(L._f.deps&&(!Array.isArray(L._f.deps)||L._f.deps.length>0)&&K(L._f.deps),O(E,Be,he,Qn))}},Z=(b,S)=>{if(ue(s.errors,S)&&b.focus)return b.focus(),1},K=async(b,S={})=>{let E,F;const L=Uu(b);if(e.resolver){const W=await q(Fe(b)?b:L);E=_t(W),F=b?!L.some(Q=>ue(W,Q)):E}else b?(F=(await Promise.all(L.map(async W=>{const Q=ue(n,W);return await I({fields:Q&&Q._f?{[W]:Q}:Q,eventType:er.TRIGGER})}))).every(Boolean),!(!F&&!s.isValid)&&k()):F=E=await I({fields:n,name:b,eventType:er.TRIGGER});return g.state.next({...!St(b)||(f.isValid||h.isValid)&&E!==s.isValid?{}:{name:b},...e.resolver||!b?{isValid:E}:{},errors:s.errors}),S.shouldFocus&&!F&&Bu(n,Z,b?L:l.mount),F},$=(b,S)=>{let E={...a.mount?i:r};return S&&(E=eb(S.dirtyFields?s.dirtyFields:s.touchedFields,E)),Fe(b)?E:St(b)?ue(E,b):b.map(F=>ue(E,F))},ee=(b,S)=>({invalid:!!ue((S||s).errors,b),isDirty:!!ue((S||s).dirtyFields,b),error:ue((S||s).errors,b),isValidating:!!ue(s.validatingFields,b),isTouched:!!ue((S||s).touchedFields,b)}),re=b=>{const S=b?Uu(b):void 0;S==null||S.forEach(E=>Ze(s.errors,E)),S?S.forEach(E=>{g.state.next({name:E,errors:s.errors})}):g.state.next({errors:{}})},ie=(b,S,E)=>{const F=(ue(n,b,{_f:{}})._f||{}).ref,L=ue(s.errors,b)||{},{ref:W,message:Q,type:le,...he}=L;Ae(s.errors,b,{...he,...S,ref:F}),g.state.next({name:b,errors:s.errors,isValid:!1}),E&&E.shouldFocus&&F&&F.focus&&F.focus()},ge=(b,S)=>Yt(b)?g.state.subscribe({next:E=>"values"in E&&b(E.values||pe(void 0,S),E)}):pe(b,S,!0),We=b=>g.state.subscribe({next:S=>{if(Bj(b.name,S.name,b.exact)&&Uj(S,b.formState||f,me,b.reRenderRoot)){const E={...i};b.callback({values:E,...s,...S,defaultValues:r})}}}).unsubscribe,Ye=b=>(a.mount=!0,h={...h,...b.formState},We({...b,formState:{...d,...b.formState}})),Ue=(b,S={})=>{for(const E of b?Uu(b):l.mount)l.mount.delete(E),l.array.delete(E),S.keepValue||(Ze(n,E),Ze(i,E)),!S.keepError&&Ze(s.errors,E),!S.keepDirty&&Ze(s.dirtyFields,E),!S.keepTouched&&Ze(s.touchedFields,E),!S.keepIsValidating&&Ze(s.validatingFields,E),!e.shouldUnregister&&!S.keepDefaultValue&&Ze(r,E);g.state.next({values:Xe(i)}),g.state.next({...s,...S.keepDirty?{isDirty:X()}:{}}),!S.keepIsValid&&k()},Pt=({disabled:b,name:S})=>{if(bs(b)&&a.mount||b||l.disabled.has(S)){const L=l.disabled.has(S)!==!!b;b?l.disabled.add(S):l.disabled.delete(S),L&&a.mount&&!a.action&&k()}},Ge=(b,S={})=>{let E=ue(n,b);const F=bs(S.disabled)||bs(e.disabled),L=!l.registerName.has(b)&&E&&E._f&&!E._f.mount;return Ae(n,b,{...E||{},_f:{...E&&E._f?E._f:{ref:{name:b}},name:b,mount:!0,...S}}),l.mount.add(b),E&&!L?Pt({disabled:bs(S.disabled)?S.disabled:e.disabled,name:b}):B(b,!0,S.value),{...F?{disabled:S.disabled||e.disabled}:{},...e.progressive?{required:!!S.required,min:du(S.min),max:du(S.max),minLength:du(S.minLength),maxLength:du(S.maxLength),pattern:du(S.pattern)}:{},name:b,onChange:te,onBlur:te,ref:W=>{if(W){l.registerName.add(b),Ge(b,S),l.registerName.delete(b),E=ue(n,b);const Q=Fe(W.value)&&W.querySelectorAll&&W.querySelectorAll("input,select,textarea")[0]||W,le=wj(Q),he=E._f.refs||[];if(le?he.find(Be=>Be===Q):Q===E._f.ref)return;Ae(n,b,{_f:{...E._f,...le?{refs:[...he.filter(zp),Q,...Array.isArray(ue(r,b))?[{}]:[]],ref:{type:Q.type,name:b}}:{ref:Q}}}),B(b,!1,void 0,Q)}else E=ue(n,b,{}),E._f&&(E._f.mount=!1),(e.shouldUnregister||S.shouldUnregister)&&!(dy(l.array,b).length&&a.action)&&l.unMount.add(b)}}},ut=()=>e.shouldFocusError&&!e.shouldUseNativeValidation&&Bu(n,Z,l.mount),Et=b=>{bs(b)&&(g.state.next({disabled:b}),Bu(n,(S,E)=>{const F=ue(n,E);F&&(S.disabled=F._f.disabled||b,Array.isArray(F._f.refs)&&F._f.refs.forEach(L=>{L.disabled=F._f.disabled||b}))},0,!1))},ms=(b,S)=>async E=>{let F;E&&(E.preventDefault&&E.preventDefault(),E.persist&&E.persist());let L=Xe(i);if(g.state.next({isSubmitting:!0}),e.resolver){const{errors:W,values:Q}=await C();x(),s.errors=W,L=Xe(Q)}else await I({fields:n,eventType:er.SUBMIT});if(l.disabled.size)for(const W of l.disabled)Ze(L,W);if(Ze(s.errors,Z1),_t(s.errors)){g.state.next({errors:{}});try{await b(L,E)}catch(W){F=W}}else S&&await S({...s.errors},E),ut(),setTimeout(ut);if(g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:_t(s.errors)&&!F,submitCount:s.submitCount+1,errors:s.errors}),F)throw F},tt=(b,S={})=>{ue(n,b)&&(Fe(S.defaultValue)?z(b,Xe(ue(r,b))):(z(b,S.defaultValue),Ae(r,b,Xe(S.defaultValue))),S.keepTouched||Ze(s.touchedFields,b),S.keepDirty||(Ze(s.dirtyFields,b),s.isDirty=S.defaultValue?X(b,Xe(ue(r,b))):X()),S.keepError||(Ze(s.errors,b),f.isValid&&k()),g.state.next({...s}))},xs=(b,S={})=>{const E=b?Xe(b):r,F=Xe(E),L=_t(b),W=L?r:F;if(S.keepDefaultValues||(r=E),!S.keepValues){if(S.keepDirtyValues){const Q=new Set([...l.mount,...Object.keys(rr(r,i))]);for(const le of Array.from(Q)){const he=ue(s.dirtyFields,le),Be=ue(i,le),xt=ue(W,le);he&&!Fe(Be)?Ae(W,le,Be):!he&&!Fe(xt)&&z(le,xt)}}else{if(rg&&Fe(b))for(const Q of l.mount){const le=ue(n,Q);if(le&&le._f){const he=Array.isArray(le._f.refs)?le._f.refs[0]:le._f.ref;if(Kf(he)){const Be=he.closest("form");if(Be){Be.reset();break}}}}if(S.keepFieldsRef)for(const Q of l.mount)z(Q,ue(W,Q));else n={}}i=e.shouldUnregister?S.keepDefaultValues?Xe(r):{}:Xe(W),g.array.next({values:{...W}}),g.state.next({values:{...W}})}l={mount:S.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},a.mount=!f.isValid||!!S.keepIsValid||!!S.keepDirtyValues||!e.shouldUnregister&&!_t(W),a.watch=!!e.shouldUnregister,a.keepIsValid=!!S.keepIsValid,a.action=!1,S.keepErrors||(s.errors={}),g.state.next({submitCount:S.keepSubmitCount?s.submitCount:0,isDirty:L?!1:S.keepDirty?s.isDirty:!!(S.keepDefaultValues&&!ws(b,r)),isSubmitted:S.keepIsSubmitted?s.isSubmitted:!1,dirtyFields:L?{}:S.keepDirtyValues?S.keepDefaultValues&&i?rr(r,i):s.dirtyFields:S.keepDefaultValues&&b?rr(r,b):S.keepDirty?s.dirtyFields:{},touchedFields:S.keepTouched?s.touchedFields:{},errors:S.keepErrors?s.errors:{},isSubmitSuccessful:S.keepIsSubmitSuccessful?s.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:r})},Us=(b,S)=>xs(Yt(b)?b(i):b,{...e.resetOptions,...S}),se=(b,S={})=>{const E=ue(n,b),F=E&&E._f;if(F){const L=F.refs?F.refs[0]:F.ref;L.focus&&setTimeout(()=>{L.focus(),S.shouldSelect&&Yt(L.select)&&L.select()})}},me=b=>{s={...s,...b}},Ne={control:{register:Ge,unregister:Ue,getFieldState:ee,handleSubmit:ms,setError:ie,_subscribe:We,_runSchema:C,_updateIsValidating:x,_focusError:ut,_getWatch:pe,_getDirty:X,_setValid:k,_setFieldArray:y,_setDisabledField:Pt,_setErrors:j,_getFieldArray:D,_reset:xs,_resetDefaultValues:()=>Yt(e.defaultValues)&&e.defaultValues().then(b=>{Us(b,e.resetOptions),g.state.next({isLoading:!1})}),_removeUnmounted:ne,_disableForm:Et,_subjects:g,_proxyFormState:f,get _fields(){return n},get _formValues(){return i},get _state(){return a},set _state(b){a=b},get _defaultValues(){return r},get _names(){return l},set _names(b){l=b},get _formState(){return s},get _options(){return e},set _options(b){e={...e,...b}}},subscribe:Ye,trigger:K,register:Ge,handleSubmit:ms,watch:ge,setValue:z,setValues:G,getValues:$,reset:Us,resetField:tt,clearErrors:re,unregister:Ue,setError:ie,setFocus:se,getFieldState:ee};return{...Ne,formControl:Ne}}function Rj(t={}){const e=Re.useRef(void 0),s=Re.useRef(void 0),[n,r]=Re.useState(()=>({...Xe(ab),isLoading:Yt(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1,defaultValues:Yt(t.defaultValues)?void 0:t.defaultValues}));if(!e.current)if(t.formControl)e.current={...t.formControl,formState:n},t.defaultValues&&!Yt(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:a,...l}=Aj(t);e.current={...l,formState:n}}const i=e.current.control;return i._options=t,yj(()=>{const a=i._subscribe({formState:i._proxyFormState,callback:()=>r({...i._formState,defaultValues:i._defaultValues}),reRenderRoot:!0});return r(l=>({...l,isReady:!0})),i._formState.isReady=!0,a},[i]),Re.useEffect(()=>i._disableForm(t.disabled),[i,t.disabled]),Re.useEffect(()=>{t.mode&&(i._options.mode=t.mode),t.reValidateMode&&(i._options.reValidateMode=t.reValidateMode)},[i,t.mode,t.reValidateMode]),Re.useEffect(()=>{t.errors&&(i._setErrors(t.errors),i._focusError())},[i,t.errors]),Re.useEffect(()=>{t.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,t.shouldUnregister]),Re.useEffect(()=>{if(i._proxyFormState.isDirty){const a=i._getDirty();a!==n.isDirty&&i._subjects.state.next({isDirty:a})}},[i,n.isDirty]),Re.useEffect(()=>{var a;t.values&&!ws(t.values,s.current)?(i._reset(t.values,{keepFieldsRef:!0,...i._options.resetOptions}),!((a=i._options.resetOptions)===null||a===void 0)&&a.keepIsValid||i._setValid(),s.current=t.values,r(l=>({...l}))):i._resetDefaultValues()},[i,t.values]),Re.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),e.current.formState=Re.useMemo(()=>gj(n,i),[i,n]),e.current}var ob={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ky=Re.createContext&&Re.createContext(ob),Fj=["attr","size","title"];function Lj(t,e){if(t==null)return{};var s,n,r=Ij(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;nRe.createElement(e.tag,Xf({key:s},e.attr),lb(e.child)))}function _e(t){return e=>Re.createElement(Vj,Yf({attr:Xf({},t.attr)},e),lb(t.child))}function Vj(t){var e=s=>{var{attr:n,size:r,title:i}=t,a=Lj(t,Fj),l=r||s.size||"1em",c;return s.className&&(c=s.className),t.className&&(c=(c?c+" ":"")+t.className),Re.createElement("svg",Yf({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},s.attr,n,a,{className:c,style:Xf(Xf({color:t.color||s.color},s.style),t.style),height:l,width:l,xmlns:"http://www.w3.org/2000/svg"}),i&&Re.createElement("title",null,i),t.children)};return ky!==void 0?Re.createElement(ky.Consumer,null,s=>e(s)):e(ob)}function yu(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"},child:[]}]})(t)}function js(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"18",y1:"6",x2:"6",y2:"18"},child:[]},{tag:"line",attr:{x1:"6",y1:"6",x2:"18",y2:"18"},child:[]}]})(t)}function Hj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"23 7 16 12 23 17 23 7"},child:[]},{tag:"rect",attr:{x:"1",y:"5",width:"15",height:"14",rx:"2",ry:"2"},child:[]}]})(t)}function $j(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"},child:[]},{tag:"circle",attr:{cx:"12",cy:"7",r:"4"},child:[]}]})(t)}function cb(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"16 16 12 12 8 16"},child:[]},{tag:"line",attr:{x1:"12",y1:"12",x2:"12",y2:"21"},child:[]},{tag:"path",attr:{d:"M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"},child:[]},{tag:"polyline",attr:{points:"16 16 12 12 8 16"},child:[]}]})(t)}function sd(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(t)}function lg(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]}]})(t)}function Wj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]},{tag:"path",attr:{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"},child:[]}]})(t)}function Gj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]}]})(t)}function qj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"},child:[]},{tag:"polyline",attr:{points:"17 21 17 13 7 13 7 21"},child:[]},{tag:"polyline",attr:{points:"7 3 7 8 15 8"},child:[]}]})(t)}function ub(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"path",attr:{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"},child:[]}]})(t)}function db(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"polyline",attr:{points:"1 20 1 14 7 14"},child:[]},{tag:"path",attr:{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"},child:[]}]})(t)}function fb(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(t)}function cg(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"5 3 19 12 5 21 5 3"},child:[]}]})(t)}function ug(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"6",y:"4",width:"4",height:"16"},child:[]},{tag:"rect",attr:{x:"14",y:"4",width:"4",height:"16"},child:[]}]})(t)}function Jj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"},child:[]},{tag:"path",attr:{d:"M13 13l6 6"},child:[]}]})(t)}function Kj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},child:[]}]})(t)}function Qj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"},child:[]},{tag:"polyline",attr:{points:"16 17 21 12 16 7"},child:[]},{tag:"line",attr:{x1:"21",y1:"12",x2:"9",y2:"12"},child:[]}]})(t)}function Ce(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"2",x2:"12",y2:"6"},child:[]},{tag:"line",attr:{x1:"12",y1:"18",x2:"12",y2:"22"},child:[]},{tag:"line",attr:{x1:"4.93",y1:"4.93",x2:"7.76",y2:"7.76"},child:[]},{tag:"line",attr:{x1:"16.24",y1:"16.24",x2:"19.07",y2:"19.07"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"6",y2:"12"},child:[]},{tag:"line",attr:{x1:"18",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.93",y1:"19.07",x2:"7.76",y2:"16.24"},child:[]},{tag:"line",attr:{x1:"16.24",y1:"7.76",x2:"19.07",y2:"4.93"},child:[]}]})(t)}function Yj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"12 2 2 7 12 12 22 7 12 2"},child:[]},{tag:"polyline",attr:{points:"2 17 12 22 22 17"},child:[]},{tag:"polyline",attr:{points:"2 12 12 17 22 12"},child:[]}]})(t)}function hb(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"22 12 16 12 14 15 10 15 8 12 2 12"},child:[]},{tag:"path",attr:{d:"M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"},child:[]}]})(t)}function pb(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]},{tag:"circle",attr:{cx:"8.5",cy:"8.5",r:"1.5"},child:[]},{tag:"polyline",attr:{points:"21 15 16 10 5 21"},child:[]}]})(t)}function Xj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"14",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"3",y:"14",width:"7",height:"7"},child:[]}]})(t)}function Zj(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]}]})(t)}function e3(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"},child:[]},{tag:"line",attr:{x1:"1",y1:"1",x2:"23",y2:"23"},child:[]}]})(t)}function mb(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"ellipse",attr:{cx:"12",cy:"5",rx:"9",ry:"3"},child:[]},{tag:"path",attr:{d:"M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"},child:[]},{tag:"path",attr:{d:"M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"},child:[]}]})(t)}function t3(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"},child:[]}]})(t)}function xb(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]}]})(t)}function s3(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"13 17 18 12 13 7"},child:[]},{tag:"polyline",attr:{points:"6 17 11 12 6 7"},child:[]}]})(t)}function n3(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"11 17 6 12 11 7"},child:[]},{tag:"polyline",attr:{points:"18 17 13 12 18 7"},child:[]}]})(t)}function r3(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"18 15 12 9 6 15"},child:[]}]})(t)}function Fh(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function Lh(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 18 9 12 15 6"},child:[]}]})(t)}function i3(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"6 9 12 15 18 9"},child:[]}]})(t)}function zn(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"20 6 9 17 4 12"},child:[]}]})(t)}function Jm(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"},child:[]},{tag:"polyline",attr:{points:"22 4 12 14.01 9 11.01"},child:[]}]})(t)}function gb(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"2",y:"7",width:"20",height:"14",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"},child:[]}]})(t)}function dg(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"19",y1:"12",x2:"5",y2:"12"},child:[]},{tag:"polyline",attr:{points:"12 19 5 12 12 5"},child:[]}]})(t)}function lt(t){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12.01",y2:"16"},child:[]}]})(t)}function a3(){const t=Eh(),{user:e,login:s}=wn(),[n,r]=m.useState(!1),[i,a]=m.useState(""),[l,c]=m.useState(!1);m.useEffect(()=>{e&&t("/app",{replace:!0})},[e,t]);const{register:u,handleSubmit:d,formState:{errors:f}}=Rj({defaultValues:{email:"",password:""}}),h=async({email:g,password:v})=>{a(""),c(!0);try{await s({email:g,password:v}),t("/app",{replace:!0})}catch(_){const k=(_==null?void 0:_.detail)||(_==null?void 0:_.message)||(typeof _=="string"?_:"Login failed. Check your credentials.");a(k)}finally{c(!1)}};return o.jsx("div",{className:"min-h-screen bg-slate-50 flex items-center justify-center p-4",children:o.jsxs("div",{className:"w-full max-w-md",children:[o.jsxs("div",{className:"text-center mb-8",children:[o.jsx("div",{className:"inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-brand-600 mb-4",children:o.jsx("svg",{className:"w-8 h-8 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.8,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),o.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"VerifyAI Labelling"}),o.jsx("p",{className:"text-sm text-slate-500 mt-1",children:"Sign in with your VerifyAI account"})]}),o.jsx("div",{className:"bg-white rounded-2xl shadow-sm border border-slate-200 p-8",children:o.jsxs("form",{onSubmit:d(h),noValidate:!0,className:"space-y-5",children:[o.jsxs("div",{children:[o.jsx("label",{htmlFor:"email",className:"block text-sm font-medium text-slate-700 mb-1.5",children:"Email"}),o.jsx("input",{id:"email",type:"email",autoComplete:"email",placeholder:"you@example.com",className:`w-full px-3.5 py-2.5 rounded-lg border text-sm outline-none transition focus:ring-2 focus:ring-brand-500 focus:border-brand-500 ${f.email?"border-red-400 bg-red-50":"border-slate-300 bg-white"}`,...u("email",{required:"Email is required",pattern:{value:/\S+@\S+\.\S+/,message:"Enter a valid email"}})}),f.email&&o.jsx("p",{className:"mt-1 text-xs text-red-600",children:f.email.message})]}),o.jsxs("div",{children:[o.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-slate-700 mb-1.5",children:"Password"}),o.jsxs("div",{className:"relative",children:[o.jsx("input",{id:"password",type:n?"text":"password",autoComplete:"current-password",placeholder:"••••••••",className:`w-full px-3.5 py-2.5 pr-10 rounded-lg border text-sm outline-none transition focus:ring-2 focus:ring-brand-500 focus:border-brand-500 ${f.password?"border-red-400 bg-red-50":"border-slate-300 bg-white"}`,...u("password",{required:"Password is required"})}),o.jsx("button",{type:"button",onClick:()=>r(g=>!g),className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition",tabIndex:-1,children:n?o.jsx(e3,{size:16}):o.jsx(Zj,{size:16})})]}),f.password&&o.jsx("p",{className:"mt-1 text-xs text-red-600",children:f.password.message})]}),i&&o.jsxs("div",{className:"flex items-start gap-2 rounded-lg bg-red-50 border border-red-200 px-3.5 py-3 text-sm text-red-700",children:[o.jsx(lt,{className:"shrink-0 mt-0.5",size:15}),o.jsx("span",{children:i})]}),o.jsx("button",{type:"submit",disabled:l,className:`w-full bg-brand-600 hover:bg-brand-700 disabled:opacity-60 disabled:cursor-not-allowed\r text-white font-medium text-sm py-2.5 rounded-lg transition focus:outline-none\r focus:ring-2 focus:ring-offset-2 focus:ring-brand-500`,children:l?"Signing in…":"Sign in"})]})})]})})}const o3=new Set(["system-admin","network-admin"]),l3=[{to:"/app/overview",label:"Overview",icon:Xj,adminOnly:!0},{to:"/app/videos",label:"Videos",icon:Hj,adminOnly:!0},{to:"/app/jobs",label:"Jobs",icon:gb,adminOnly:!1},{to:"/app/datasets",label:"Datasets",icon:mb,adminOnly:!1},{to:"/app/admin",label:"Admin",icon:Wj,adminOnly:!0}];function c3(){const{user:t,logout:e}=wn(),s=o3.has(t==null?void 0:t.user_type),n=l3.filter(a=>!a.adminOnly||s),r=Eh(),i=async()=>{await e(),r("/login",{replace:!0})};return o.jsxs("div",{className:"flex h-screen bg-slate-100 overflow-hidden",children:[o.jsxs("aside",{className:"flex flex-col w-56 shrink-0 bg-slate-900 text-slate-100",children:[o.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-5 border-b border-slate-700/60",children:[o.jsx("div",{className:"flex items-center justify-center w-8 h-8 rounded-lg bg-brand-600 shrink-0",children:o.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm font-semibold leading-tight text-white",children:"VerifyAI"}),o.jsx("div",{className:"text-[10px] text-slate-400 leading-tight",children:"Labelling"})]})]}),o.jsx("nav",{className:"flex-1 px-3 py-4 space-y-0.5 overflow-y-auto",children:n.map(({to:a,label:l,icon:c})=>o.jsxs(dE,{to:a,className:({isActive:u})=>`flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${u?"bg-brand-600 text-white":"text-slate-400 hover:text-slate-100 hover:bg-slate-800"}`,children:[o.jsx(c,{size:16,className:"shrink-0"}),l]},a))}),o.jsxs("div",{className:"px-3 py-4 border-t border-slate-700/60 space-y-0.5",children:[o.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-lg text-xs text-slate-400",children:[o.jsx($j,{size:14,className:"shrink-0"}),o.jsx("span",{className:"truncate",children:(t==null?void 0:t.email)??"—"})]}),o.jsxs("button",{onClick:i,className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm text-slate-400\r hover:text-red-400 hover:bg-slate-800 transition-colors`,children:[o.jsx(Qj,{size:16,className:"shrink-0"}),"Sign out"]})]})]}),o.jsx("main",{className:"flex-1 flex flex-col overflow-hidden",children:o.jsx("div",{className:"flex-1 overflow-y-auto",children:o.jsx(k1,{})})})]})}function u3(){return o.jsxs("div",{className:"p-8",children:[o.jsx("h2",{className:"text-xl font-semibold text-slate-800 mb-1",children:"Overview"}),o.jsx("p",{className:"text-sm text-slate-500",children:"Dashboard summary will appear here."})]})}async function d3({source:t="production",page:e=1,page_size:s=50,search:n="",company_id:r=null,date_from:i=null,date_to:a=null}={}){const l={source:t,page:e,page_size:s};return n&&(l.search=n),r&&(l.company_id=r),i&&(l.date_from=i),a&&(l.date_to=a),(await we.get("/api/v1/videos",{params:l})).data}async function f3(t="production"){return(await we.get("/api/v1/companies",{params:{source:t}})).data}async function h3(t,e="production"){return(await we.get(`/api/v1/videos/${t}`,{params:{source:e}})).data}async function fg(t,e="production"){return(await we.get(`/api/v1/videos/${t}/stream-url`,{params:{source:e}})).data}async function hg({status:t}={}){const e={};return t&&(e.status=t),(await we.get("/api/v1/jobs",{params:e})).data}async function p3(t){return(await we.post("/api/v1/jobs",t)).data}async function Zf(t,e){return(await we.put(`/api/v1/jobs/${t}`,e)).data}function Ny(t){if(!t||isNaN(t))return"0:00";const e=Math.floor(t/60),s=Math.floor(t%60);return`${e}:${String(s).padStart(2,"0")}`}function m3({video:t,onClose:e}){const[s,n]=m.useState(null),[r,i]=m.useState(""),[a,l]=m.useState(!1),[c,u]=m.useState(0),[d,f]=m.useState(0),[h,g]=m.useState(!1),v=m.useRef(null),_=m.useRef(null),[k,x]=m.useState(!1),[p,y]=m.useState(!1),[N,j]=m.useState(null),[w,B]=m.useState(20),[T,O]=m.useState(""),[C,q]=m.useState("detection"),[V,I]=m.useState(!1),[ne,X]=m.useState(null),[pe,D]=m.useState("");m.useEffect(()=>{n(null),i(""),fg(t.id,t.source).then(({signed_url:$})=>n($)).catch(()=>i("Could not load video URL. Check GCS permissions."))},[t.id,t.source]),m.useEffect(()=>{const $=ee=>{var ie;if(ee.key==="Escape"){e();return}const re=(ie=ee.target)==null?void 0:ie.tagName;ee.key===" "&&s&&re!=="INPUT"&&re!=="TEXTAREA"&&(ee.preventDefault(),R())};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[s,a]);const R=m.useCallback(()=>{const $=v.current;$&&($.paused?$.play():$.pause())},[]),U=m.useCallback(()=>{const $=v.current;$&&($.pause(),$.currentTime=0)},[]),z=m.useCallback($=>{const ee=_.current;if(!ee||!d)return;const{left:re,width:ie}=ee.getBoundingClientRect(),ge=Math.max(0,Math.min(1,($-re)/ie));v.current&&(v.current.currentTime=ge*d)},[d]),G=$=>{$.preventDefault(),g(!0),z($.clientX)};m.useEffect(()=>{if(!h)return;const $=re=>z(re.clientX),ee=()=>g(!1);return window.addEventListener("mousemove",$),window.addEventListener("mouseup",ee),()=>{window.removeEventListener("mousemove",$),window.removeEventListener("mouseup",ee)}},[h,z]);const te=async()=>{x(!0),X(null),D(""),j(null),y(!0);try{const ee=(await hg()).find(re=>re.video_id===t.id&&re.video_source===t.source&&["pending","in_progress"].includes(re.status));j(ee??null)}catch{}finally{y(!1)}},Z=async()=>{var $,ee;I(!0),D("");try{const re=t.google_bucket_processed_path||t.google_bucket_path,ie=await p3({video_id:t.id,video_source:t.source,video_gcs_path:re,frame_target:w,notes:T.trim()||null,job_type:C});X(ie)}catch(re){D(((ee=($=re.response)==null?void 0:$.data)==null?void 0:ee.detail)??"Failed to create job.")}finally{I(!1)}},K=d?c/d*100:0;return o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-sm",onMouseDown:$=>$.target===$.currentTarget&&e(),children:o.jsxs("div",{className:"relative bg-slate-900 rounded-2xl shadow-2xl w-full max-w-4xl mx-4 flex flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex items-start justify-between px-5 pt-4 pb-3 border-b border-slate-700/60",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"text-white font-semibold text-sm truncate max-w-xl",title:t.filename,children:t.filename}),o.jsxs("p",{className:"text-slate-400 text-xs mt-0.5 flex items-center gap-1.5 flex-wrap",children:[o.jsx("span",{children:t.company_name??"—"}),o.jsx("span",{className:"text-slate-600",children:"·"}),o.jsx("span",{children:t.equipment_name??"—"}),o.jsx("span",{className:"text-slate-600",children:"·"}),o.jsx("span",{className:"capitalize",children:t.source}),t.video_status&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-slate-600",children:"·"}),o.jsx("span",{className:t.video_status==="processed"?"text-emerald-400":"text-sky-400",children:t.video_status})]})]})]}),o.jsx("button",{onClick:e,className:`ml-4 p-1 text-slate-400 hover:text-white transition shrink-0 rounded-lg\r hover:bg-slate-700/50`,children:o.jsx(js,{size:20})})]}),o.jsxs("div",{className:"relative bg-black flex items-center justify-center",style:{aspectRatio:"16/9"},children:[r&&o.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm px-6 text-center",children:[o.jsx(lt,{size:16,className:"shrink-0"}),r]}),!s&&!r&&o.jsxs("div",{className:"flex flex-col items-center gap-3 text-slate-400",children:[o.jsx(Ce,{className:"animate-spin",size:32}),o.jsx("span",{className:"text-sm",children:"Loading video…"})]}),s&&o.jsx("video",{ref:v,src:s,className:"w-full h-full object-contain",onTimeUpdate:()=>{var $;return u((($=v.current)==null?void 0:$.currentTime)??0)},onLoadedMetadata:()=>{var $;return f((($=v.current)==null?void 0:$.duration)??0)},onEnded:()=>l(!1),onPlay:()=>l(!0),onPause:()=>l(!1)})]}),o.jsxs("div",{className:"px-5 py-4 bg-slate-900 space-y-3",children:[o.jsxs("div",{ref:_,className:"relative h-1.5 bg-slate-700 rounded-full cursor-pointer group",onMouseDown:G,children:[o.jsx("div",{className:"absolute left-0 top-0 h-full bg-brand-500 rounded-full pointer-events-none",style:{width:`${K}%`}}),o.jsx("div",{className:`absolute top-1/2 -translate-y-1/2 w-3.5 h-3.5 bg-white rounded-full shadow transition-opacity pointer-events-none ${h?"opacity-100":"opacity-0 group-hover:opacity-100"}`,style:{left:`calc(${K}% - 7px)`}})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("button",{onClick:R,disabled:!s,className:"text-white hover:text-brand-400 transition disabled:opacity-30",title:a?"Pause (Space)":"Play (Space)",children:a?o.jsx(ug,{size:22}):o.jsx(cg,{size:22})}),o.jsx("button",{onClick:U,disabled:!s,className:"text-slate-400 hover:text-white transition disabled:opacity-30",title:"Stop",children:o.jsx(lg,{size:18})}),o.jsxs("span",{className:"text-slate-400 text-xs tabular-nums ml-1 select-none",children:[Ny(c),o.jsx("span",{className:"text-slate-600",children:" / "}),Ny(d)]}),o.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[o.jsx("span",{className:"text-slate-600 text-xs select-none hidden sm:block",children:"Space to play/pause · Esc to close"}),o.jsxs("button",{onClick:k?()=>x(!1):te,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition ${k?"bg-slate-700 text-slate-300 hover:bg-slate-600":"bg-brand-600 hover:bg-brand-500 text-white"}`,title:"Create a labelling job for this video",children:[o.jsx(gb,{size:13}),k?"Cancel":"Create Job"]})]})]})]}),k&&o.jsx("div",{className:"px-5 py-4 bg-slate-800/80 border-t border-slate-700/60",children:ne?o.jsxs("div",{className:"flex items-center gap-2 text-emerald-400 text-sm",children:[o.jsx(Jm,{size:16}),"Job ",o.jsxs("span",{className:"font-semibold mx-0.5",children:["#",ne.id]})," created — frame target: ",ne.frame_target,"."]}):o.jsxs(o.Fragment,{children:[p&&o.jsxs("p",{className:"text-slate-400 text-xs mb-3 flex items-center gap-1.5",children:[o.jsx(Ce,{className:"animate-spin",size:12}),"Checking for existing jobs…"]}),!p&&N&&o.jsxs("div",{className:"flex items-center gap-1.5 text-amber-400 text-xs mb-3",children:[o.jsx(lt,{size:13,className:"shrink-0"}),"Active job"," ",o.jsxs("span",{className:"font-semibold",children:["#",N.id]})," already exists for this video (status:"," ",o.jsx("span",{className:"font-semibold",children:N.status}),"). You can still create another."]}),o.jsxs("div",{className:"flex items-end gap-4 flex-wrap",children:[o.jsxs("div",{className:"flex flex-col gap-1 text-xs text-slate-400",children:["Job type",o.jsx("div",{className:"flex items-center border border-slate-600 rounded overflow-hidden",children:["detection","classification"].map($=>o.jsx("button",{type:"button",onClick:()=>q($),className:`px-3 py-1.5 text-xs font-medium capitalize transition ${C===$?"bg-brand-600 text-white":"bg-slate-700 text-slate-400 hover:text-white"}`,children:$},$))})]}),o.jsxs("label",{className:"flex flex-col gap-1 text-xs text-slate-400 w-32",children:["Frame target",o.jsx("input",{type:"number",min:1,max:500,value:w,onChange:$=>B(Number($.target.value)),className:`bg-slate-700 border border-slate-600 rounded px-2 py-1.5\r text-white text-sm w-full focus:outline-none focus:border-brand-500`})]}),o.jsxs("label",{className:"flex flex-col gap-1 text-xs text-slate-400 flex-1 min-w-40",children:["Notes",o.jsx("input",{type:"text",value:T,onChange:$=>O($.target.value),placeholder:"Optional instructions…",className:`bg-slate-700 border border-slate-600 rounded px-2 py-1.5\r text-white text-sm w-full focus:outline-none focus:border-brand-500\r placeholder:text-slate-500`})]}),o.jsx("button",{onClick:Z,disabled:V,className:`px-4 py-1.5 bg-brand-600 hover:bg-brand-500 text-white text-sm\r rounded-lg disabled:opacity-50 transition font-medium shrink-0`,children:V?"Creating…":"Create Job"})]}),pe&&o.jsxs("p",{className:"text-red-400 text-xs mt-2 flex items-center gap-1.5",children:[o.jsx(lt,{size:12}),pe]})]})})]})})}function x3(t){if(t==null)return"—";const e=Math.floor(t/60),s=Math.round(t%60);return`${e}:${String(s).padStart(2,"0")}`}function g3(t){return t?new Date(t).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):"—"}const y3={assigned:"bg-blue-50 text-blue-700 border-blue-200",in_review:"bg-amber-50 text-amber-700 border-amber-200",reviewed:"bg-green-50 text-green-700 border-green-200"},_3={assigned:"Assigned",in_review:"In Review",reviewed:"Reviewed"};function v3({status:t}){if(!t)return o.jsx("span",{className:"text-slate-400 text-xs",children:"—"});const e=y3[t]??"bg-slate-100 text-slate-600 border-slate-200",s=_3[t]??t;return o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${e}`,children:s})}const b3={processed:"bg-emerald-50 text-emerald-700 border-emerald-200",uploaded:"bg-sky-50 text-sky-700 border-sky-200"};function w3({status:t}){if(!t)return o.jsx("span",{className:"text-slate-400 text-xs",children:"—"});const e=b3[t]??"bg-slate-100 text-slate-600 border-slate-200";return o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${e}`,children:t})}const jy=50;function S3(){const[t,e]=m.useState("production"),[s,n]=m.useState(""),[r,i]=m.useState(""),[a,l]=m.useState(1),[c,u]=m.useState(""),[d,f]=m.useState(""),[h,g]=m.useState(""),[v,_]=m.useState([]),[k,x]=m.useState(null),[p,y]=m.useState(!1),[N,j]=m.useState(""),[w,B]=m.useState(null),T=m.useRef(null);m.useEffect(()=>{f3(t).then(_).catch(()=>_([])),u(""),l(1)},[t]),m.useEffect(()=>(clearTimeout(T.current),T.current=setTimeout(()=>{i(s),l(1)},400),()=>clearTimeout(T.current)),[s]);const O=m.useCallback(async()=>{y(!0),j("");try{const I=await d3({source:t,page:a,page_size:jy,search:r,company_id:c||void 0,date_from:d||void 0,date_to:h||void 0});x(I)}catch(I){j((I==null?void 0:I.detail)||(I==null?void 0:I.message)||"Failed to load videos.")}finally{y(!1)}},[t,a,r,c,d,h]);m.useEffect(()=>{O()},[O]);const C=()=>{n(""),u(""),f(""),g(""),l(1)},q=s||c||d||h,V=k?Math.max(1,Math.ceil(k.total/jy)):1;return o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-6 py-4 border-b border-slate-200 bg-white",children:[o.jsx("h2",{className:"text-base font-semibold text-slate-800 mr-2",children:"Videos"}),o.jsx("div",{className:"flex rounded-lg border border-slate-200 overflow-hidden text-sm",children:["production","staging"].map(I=>o.jsx("button",{onClick:()=>e(I),className:`px-3.5 py-1.5 font-medium capitalize transition-colors ${t===I?"bg-brand-600 text-white":"bg-white text-slate-600 hover:bg-slate-50"}`,children:I},I))}),o.jsxs("select",{value:c,onChange:I=>{u(I.target.value),l(1)},className:`text-sm border border-slate-200 rounded-lg px-2.5 py-1.5\r outline-none focus:ring-2 focus:ring-brand-500 text-slate-700 bg-white`,children:[o.jsx("option",{value:"",children:"All companies"}),v.map(I=>o.jsx("option",{value:I.id,children:I.name},I.id))]}),o.jsx("input",{type:"date",value:d,onChange:I=>{f(I.target.value),l(1)},className:`text-sm border border-slate-200 rounded-lg px-2.5 py-1.5\r outline-none focus:ring-2 focus:ring-brand-500 text-slate-700`,title:"Recorded from"}),o.jsx("span",{className:"text-slate-400 text-sm",children:"–"}),o.jsx("input",{type:"date",value:h,onChange:I=>{g(I.target.value),l(1)},className:`text-sm border border-slate-200 rounded-lg px-2.5 py-1.5\r outline-none focus:ring-2 focus:ring-brand-500 text-slate-700`,title:"Recorded to"}),o.jsxs("div",{className:"relative flex-1 min-w-[160px] max-w-sm",children:[o.jsx(Gj,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:14}),o.jsx("input",{type:"text",value:s,onChange:I=>n(I.target.value),placeholder:"Search filename…",className:`w-full pl-8 pr-3 py-1.5 text-sm border border-slate-200 rounded-lg\r outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500`})]}),q&&o.jsxs("button",{onClick:C,className:"flex items-center gap-1 text-sm text-slate-500 hover:text-slate-800 transition",children:[o.jsx(js,{size:14}),"Clear"]}),k&&o.jsxs("span",{className:"ml-auto text-xs text-slate-400 shrink-0",children:[k.total.toLocaleString()," video",k.total!==1?"s":""]})]}),N&&o.jsxs("div",{className:"mx-6 mt-4 flex items-center gap-2 rounded-lg bg-red-50 border border-red-200 px-4 py-3 text-sm text-red-700",children:[o.jsx(lt,{size:15,className:"shrink-0"}),N]}),o.jsx("div",{className:"flex-1 overflow-auto",children:o.jsxs("table",{className:"w-full text-sm border-collapse",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"bg-slate-50 border-b border-slate-200 text-left",children:[o.jsx("th",{className:"px-4 py-3 font-medium text-slate-500 w-16",children:"ID"}),o.jsx("th",{className:"px-4 py-3 font-medium text-slate-500",children:"Filename"}),o.jsx("th",{className:"px-4 py-3 font-medium text-slate-500",children:"Company"}),o.jsx("th",{className:"px-4 py-3 font-medium text-slate-500",children:"Equipment"}),o.jsx("th",{className:"px-4 py-3 font-medium text-slate-500 w-28",children:"Video Status"}),o.jsx("th",{className:"px-4 py-3 font-medium text-slate-500 w-32",children:"Recorded"}),o.jsx("th",{className:"px-4 py-3 font-medium text-slate-500 w-24 text-right",children:"Duration"}),o.jsx("th",{className:"px-4 py-3 font-medium text-slate-500 w-16 text-right",children:"FPS"}),o.jsx("th",{className:"px-4 py-3 font-medium text-slate-500 w-28",children:"Status"})]})}),o.jsxs("tbody",{children:[p&&o.jsx("tr",{children:o.jsxs("td",{colSpan:9,className:"px-4 py-16 text-center text-slate-400",children:[o.jsx(Ce,{className:"inline animate-spin mr-2",size:16}),"Loading…"]})}),!p&&(k==null?void 0:k.items.length)===0&&o.jsx("tr",{children:o.jsx("td",{colSpan:9,className:"px-4 py-16 text-center text-slate-400",children:"No videos found."})}),!p&&(k==null?void 0:k.items.map(I=>o.jsxs("tr",{className:"border-b border-slate-100 hover:bg-slate-50 transition-colors cursor-pointer",onClick:()=>B(I),children:[o.jsx("td",{className:"px-4 py-2.5 text-slate-400 tabular-nums",children:I.id}),o.jsx("td",{className:"px-4 py-2.5 text-slate-800 max-w-xs",children:o.jsx("span",{className:"block truncate",title:I.filename,children:I.filename})}),o.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:I.company_name??"—"}),o.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:I.equipment_name??"—"}),o.jsx("td",{className:"px-4 py-2.5",children:o.jsx(w3,{status:I.video_status})}),o.jsx("td",{className:"px-4 py-2.5 text-slate-500 text-xs tabular-nums",children:g3(I.recording_started_at)}),o.jsx("td",{className:"px-4 py-2.5 text-slate-600 text-right tabular-nums",children:x3(I.duration_seconds)}),o.jsx("td",{className:"px-4 py-2.5 text-slate-600 text-right tabular-nums",children:I.fps!=null?I.fps.toFixed(1):"—"}),o.jsx("td",{className:"px-4 py-2.5",children:o.jsx(v3,{status:I.labelling_status})})]},I.id)))]})]})}),k&&V>1&&o.jsxs("div",{className:"flex items-center justify-between px-6 py-3 border-t border-slate-200 bg-white text-sm",children:[o.jsxs("span",{className:"text-slate-500",children:["Page ",a," of ",V]}),o.jsxs("div",{className:"flex gap-1",children:[o.jsx("button",{onClick:()=>l(I=>Math.max(1,I-1)),disabled:a===1,className:`p-1.5 rounded-lg border border-slate-200 text-slate-600\r hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition`,children:o.jsx(Lh,{size:16})}),o.jsx("button",{onClick:()=>l(I=>Math.min(V,I+1)),disabled:a===V,className:`p-1.5 rounded-lg border border-slate-200 text-slate-600\r hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition`,children:o.jsx(Fh,{size:16})})]})]}),w&&o.jsx(m3,{video:w,onClose:()=>B(null)})]})}async function k3({role:t}={}){const e={};return t&&(e.role=t),(await we.get("/api/v1/users",{params:e})).data}async function E3(){return(await we.get("/api/v1/admin/users")).data}async function N3(t){return(await we.post("/api/v1/admin/users",t)).data}async function Cy(t,e){return(await we.put(`/api/v1/admin/users/${t}`,e)).data}const j3=new Set(["system-admin","network-admin"]);function Ih(t){return t?j3.has(t.user_type)?!0:t.labelling_role==="reviewer"||t.labelling_role==="admin":!1}var C3=Object.defineProperty,yb=(t,e)=>{for(var s in e)C3(t,s,{get:e[s],enumerable:!0})},Ap=Math.pow(2,32),rt=Math.pow(2,32)-1,U3=1,B3=2,T3=4,cf=1,uf=2,df=8,ff=16,hf=32,Uy=131072,Tu=1,pf=4,Pu=256,zu=512,Au=1024,Ru=2048,_b=-1,Ks=0,Dt=1,Ss=class vb extends ArrayBuffer{constructor(e){super(e),this.fileStart=0,this.usedBytes=0}static fromArrayBuffer(e,s){const n=new vb(e.byteLength);return new Uint8Array(n).set(new Uint8Array(e)),n.fileStart=s,n}},bb=(t=>(t[t.BIG_ENDIAN=1]="BIG_ENDIAN",t[t.LITTLE_ENDIAN=2]="LITTLE_ENDIAN",t))(bb||{}),nd,Km,be,at=(be=class{constructor(e,s,n){Zh(this,nd);this._byteLength=0,this.failurePosition=0,this._dynamicSize=1,this._byteOffset=s||0,e instanceof ArrayBuffer?this.buffer=Ss.fromArrayBuffer(e,0):e instanceof DataView?(this.dataView=e,s&&(this._byteOffset+=s)):this.buffer=new Ss(e||0),this.position=0,this.endianness=n||1}getPosition(){return this.position}_realloc(e){if(!this._dynamicSize)return;const s=this._byteOffset+this.position+e;let n=this._buffer.byteLength;if(s<=n){s>this._byteLength&&(this._byteLength=s);return}for(n<1&&(n=1);s>n;)n*=2;const r=new Ss(n),i=new Uint8Array(this._buffer);new Uint8Array(r,0,i.length).set(i),this.buffer=r,this._byteLength=s}_trimAlloc(){if(this._byteLength===this._buffer.byteLength)return;const e=new Ss(this._byteLength),s=new Uint8Array(e),n=new Uint8Array(this._buffer,0,s.length);s.set(n),this.buffer=e}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(e){this._buffer=e,this._dataView=new DataView(e,this._byteOffset),this._byteLength=e.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(e){this._byteOffset=e.byteOffset,this._buffer=Ss.fromArrayBuffer(e.buffer,0),this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}seek(e){const s=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(s)||!isFinite(s)?0:s}isEof(){return this.position>=this._byteLength}mapUint8Array(e){this._realloc(e*1);const s=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,s}readInt32Array(e,s){e=e===void 0?this.byteLength-this.position/4:e;const n=new Int32Array(e);return be.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),be.arrayToNative(n,s??this.endianness),this.position+=n.byteLength,n}readInt16Array(e,s){e=e===void 0?this.byteLength-this.position/2:e;const n=new Int16Array(e);return be.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),be.arrayToNative(n,s??this.endianness),this.position+=n.byteLength,n}readInt8Array(e){e=e===void 0?this.byteLength-this.position:e;const s=new Int8Array(e);return be.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,e*s.BYTES_PER_ELEMENT),this.position+=s.byteLength,s}readUint32Array(e,s){e=e===void 0?this.byteLength-this.position/4:e;const n=new Uint32Array(e);return be.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),be.arrayToNative(n,s??this.endianness),this.position+=n.byteLength,n}readUint16Array(e,s){e=e===void 0?this.byteLength-this.position/2:e;const n=new Uint16Array(e);return be.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),be.arrayToNative(n,s??this.endianness),this.position+=n.byteLength,n}readUint8Array(e){e=e===void 0?this.byteLength-this.position:e;const s=new Uint8Array(e);return be.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,e*s.BYTES_PER_ELEMENT),this.position+=s.byteLength,s}readFloat64Array(e,s){e=e===void 0?this.byteLength-this.position/8:e;const n=new Float64Array(e);return be.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),be.arrayToNative(n,s??this.endianness),this.position+=n.byteLength,n}readFloat32Array(e,s){e=e===void 0?this.byteLength-this.position/4:e;const n=new Float32Array(e);return be.memcpy(n.buffer,0,this.buffer,this.byteOffset+this.position,e*n.BYTES_PER_ELEMENT),be.arrayToNative(n,s??this.endianness),this.position+=n.byteLength,n}readInt32(e){const s=this._dataView.getInt32(this.position,(e??this.endianness)===2);return this.position+=4,s}readInt16(e){const s=this._dataView.getInt16(this.position,(e??this.endianness)===2);return this.position+=2,s}readInt8(){const e=this._dataView.getInt8(this.position);return this.position+=1,e}readUint32(e){const s=this._dataView.getUint32(this.position,(e??this.endianness)===2);return this.position+=4,s}readUint16(e){const s=this._dataView.getUint16(this.position,(e??this.endianness)===2);return this.position+=2,s}readUint8(){const e=this._dataView.getUint8(this.position);return this.position+=1,e}readFloat32(e){const s=this._dataView.getFloat32(this.position,(e??this.endianness)===2);return this.position+=4,s}readFloat64(e){const s=this._dataView.getFloat64(this.position,(e??this.endianness)===2);return this.position+=8,s}static memcpy(e,s,n,r,i){const a=new Uint8Array(e,s,i),l=new Uint8Array(n,r,i);a.set(l)}static arrayToNative(e,s){return s===be.ENDIANNESS?e:this.flipArrayEndianness(e)}static nativeToEndian(e,s){return s&&be.ENDIANNESS===2?e:this.flipArrayEndianness(e)}static flipArrayEndianness(e){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(let n=0;ni;r--,i++){const a=s[i];s[i]=s[r],s[r]=a}return e}readString(e,s){return s===void 0||s==="ASCII"?By(this.mapUint8Array(e===void 0?this.byteLength-this.position:e)):new TextDecoder(s).decode(this.mapUint8Array(e))}readCString(e){let s=0;const n=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),i=e!==void 0?Math.min(e,n):n;for(;s>16),this.writeUint8((e&65280)>>8),this.writeUint8(e&255)}adjustUint32(e,s){const n=this.position;this.seek(e),this.writeUint32(s),this.seek(n)}readStruct(e){const s={},n=this.position;for(let r=0;r0?2:1,be);function By(t){const e=[];for(let s=0;s=Ts&&console.debug("["+M.getDurationString(new Date().getTime()-Md.getTime(),1e3)+"]","["+t+"]",e)},log(t,e){this.debug(t.msg)},info(t,e){Py>=Ts&&console.info("["+M.getDurationString(new Date().getTime()-Md.getTime(),1e3)+"]","["+t+"]",e)},warn(t,e){Ty>=Ts&&console.warn("["+M.getDurationString(new Date().getTime()-Md.getTime(),1e3)+"]","["+t+"]",e)},error(t,e,s){s!=null&&s.onError?s.onError(t,e):mf>=Ts&&console.error("["+M.getDurationString(new Date().getTime()-Md.getTime(),1e3)+"]","["+t+"]",e)},getDurationString(t,e){let s;function n(u,d){const h=(""+u).split(".");for(;h[0].length0){let s="";for(let n=0;n0&&(s+=","),s+="["+M.getDurationString(t.start(n))+","+M.getDurationString(t.end(n))+"]";return s}else return"(empty)"}};function P3(t,e){M.debug("ArrayBuffer","Trying to create a new buffer of size: "+(t.byteLength+e.byteLength));const s=new Uint8Array(t.byteLength+e.byteLength);return s.set(new Uint8Array(t),0),s.set(new Uint8Array(e),t.byteLength),s.buffer}var kr=class extends at{constructor(t){super(new ArrayBuffer,0),this.buffers=[],this.bufferIndex=-1,t&&(this.insertBuffer(t),this.bufferIndex=0)}initialized(){if(this.bufferIndex>-1)return!0;if(this.buffers.length>0){const t=this.buffers[0];return t.fileStart===0?(this.buffer=t,this.bufferIndex=0,M.debug("MultiBufferStream","Stream ready for parsing"),!0):(M.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)}else return M.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1}reduceBuffer(t,e,s){const n=new Uint8Array(s);return n.set(new Uint8Array(t,e,s)),n.buffer.fileStart=t.fileStart+e,n.buffer.usedBytes=0,n.buffer}insertBuffer(t){let e=!0,s=0;for(;sn.byteLength){this.buffers.splice(s,1),s--;continue}else M.warn("MultiBufferStream","Buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+") already appended, ignoring");else t.fileStart+t.byteLength<=n.fileStart||(t=this.reduceBuffer(t,0,n.fileStart-t.fileStart)),M.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.splice(s,0,t),s===0&&(this.buffer=t);e=!1;break}else if(t.fileStart0)t=this.reduceBuffer(t,r,i);else{e=!1;break}}}e&&(M.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.push(t),s===0&&(this.buffer=t))}logBufferLevel(t){const e=[];let s="",n,r=0,i=0;for(let l=0;l0&&(s+=n.end-1+"]");const a=t?M.info:M.debug;this.buffers.length===0?a("MultiBufferStream","No more buffer in memory"):a("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+r+"/"+i+" bytes), continuous ranges: "+s)}cleanBuffers(){for(let t=0;t"+this.buffer.byteLength+")"),!0}else return!1}else return!1}findPosition(t,e,s){let n=-1,r=t===!0?0:this.bufferIndex;for(;r=e?(M.debug("MultiBufferStream","Found position in existing buffer #"+n),n):-1}findEndContiguousBuf(t){const e=t!==void 0?t:this.bufferIndex;let s=this.buffers[e];if(this.buffers.length>e+1)for(let n=e+1;nrt||this.original_size===1)&&(this.size+=8),this.type==="uuid"&&(this.size+=16),M.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.getPosition()+(s||"")),this.original_size===0?e.writeUint32(0):this.size>rt||this.original_size===1?e.writeUint32(1):(this.sizePosition=e.getPosition(),e.writeUint32(this.size)),e.writeString(this.type,void 0,4),this.type==="uuid"){const n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(this.uuid.substring(r*2,r*2+2),16);e.writeUint8Array(n)}(this.size>rt||this.original_size===1)&&(this.sizePosition=e.getPosition(),e.writeUint64(this.size))}write(e){if(this.type==="mdat"){const s=this;if(s.stream){this.size=s.stream.getAbsoluteEndPosition(),this.writeHeader(e);for(const n of s.stream.buffers){const r=new Uint8Array(n);e.writeUint8Array(r)}}else s.data&&(this.size=s.data.length,this.writeHeader(e),e.writeUint8Array(s.data))}else this.size=this.data?this.data.length:0,this.writeHeader(e),this.data&&e.writeUint8Array(this.data)}printHeader(e){this.size+=8,this.size>rt&&(this.size+=8),this.type==="uuid"&&(this.size+=16),e.log(e.indent+"size:"+this.size),e.log(e.indent+"type:"+this.type)}print(e){this.printHeader(e)}parse(e){this.type!=="mdat"?this.data=e.readUint8Array(this.size-this.hdr_size):this.size===0?e.seek(e.getEndPosition()):e.seek(this.start+this.size)}parseDataAndRewind(e){this.data=e.readUint8Array(this.size-this.hdr_size),e.seek(this.start+this.hdr_size)}parseLanguage(e){this.language=e.readUint16();const s=[];s[0]=this.language>>10&31,s[1]=this.language>>5&31,s[2]=this.language&31,this.languageString=String.fromCharCode(s[0]+96,s[1]+96,s[2]+96)}computeSize(e){const s=e||new kr;this.write(s)}isEndOfBox(e){const s=e.getPosition(),n=this.start+this.size;return s===n}},rd=new WeakMap,Nr.registryId=Symbol.for("BoxIdentifier"),Nr),J=class extends ae{constructor(){super(...arguments),this.flags=0,this.version=0}writeHeader(t){this.size+=4,super.writeHeader(t," v="+this.version+" f="+this.flags),t.writeUint8(this.version),t.writeUint24(this.flags)}printHeader(t){this.size+=4,super.printHeader(t),t.log(t.indent+"version:"+this.version),t.log(t.indent+"flags:"+this.flags)}parseDataAndRewind(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,t.seek(this.start+this.hdr_size)}parseFullHeader(t){this.version=t.readUint8(),this.flags=t.readUint24(),this.hdr_size+=4}parse(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)}},jr,Qe=(jr=class{constructor(e){this.grouping_type=e}write(e){e.writeUint8Array(this.data)}parse(e){M.warn("BoxParser",`Unknown sample group type: '${this.grouping_type}'`),this.data=e.readUint8Array(this.description_length)}},jr.registryId=Symbol.for("SampleGroupEntryIdentifier"),jr),wb=class extends J{parse(t){this.parseFullHeader(t),this.track_group_id=t.readUint32()}},Sb=class extends ae{constructor(t,e,s,n,r){super(e),this.box_name=s,this.hdr_size=n,this.start=r,this.type=t}parse(t){this.from_item_ID=t.readUint16();const e=t.readUint16();this.references=[];for(let s=0;sn===s)){if(t[s]instanceof ae||e[s]instanceof ae)continue;if(typeof t[s]>"u"||typeof e[s]>"u")continue;if(typeof t[s]=="function"||typeof e[s]=="function")continue;if("subBoxNames"in t&&t.subBoxNames.indexOf(s.slice(0,4))>-1||"subBoxNames"in e&&e.subBoxNames.indexOf(s.slice(0,4))>-1)continue;if(s==="data"||s==="start"||s==="size"||s==="creation_time"||s==="modification_time")continue;if(Nb.find(n=>n===s))continue;if(t[s]!==e[s])return!1}return!0}function pg(t,e){if(!jb(t,e))return!1;for(let s=0;s{const e=Symbol.for("SampleGroupEntryIdentifier");return mg(t)===e},A3=t=>{const e=Symbol.for("SampleEntryIdentifier");return mg(t)===e},R3=t=>{const e=Symbol.for("BoxIdentifier");return mg(t)===e},At={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};function F3(t){const e={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};for(const[s,n]of Object.entries(t)){if(z3(n)){const r="grouping_type"in n?n.grouping_type:void 0;if(!r)throw new Error(`SampleGroupEntry class ${s} does not have a valid static grouping_type. Please ensure it is defined correctly.`);if(r in e.sampleGroupEntry)throw new Error(`SampleGroupEntry class ${s} has a grouping_type that is already registered. Please ensure it is unique.`);e.sampleGroupEntry[r]=n;continue}if(A3(n)){const r="fourcc"in n?n.fourcc:void 0;if(!r)throw new Error(`SampleEntry class ${s} does not have a valid static fourcc. Please ensure it is defined correctly.`);if(r in e.sampleEntry)throw new Error(`SampleEntry class ${s} has a fourcc that is already registered. Please ensure it is unique.`);e.sampleEntry[r]=n;continue}if(R3(n)){const r="fourcc"in n?n.fourcc:void 0,i="uuid"in n?n.uuid:void 0;if(r==="uuid"){if(!i)throw new Error(`Box class ${s} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.`);if(i in e.uuid)throw new Error(`Box class ${s} has a uuid that is already registered. Please ensure it is unique.`);e.uuid[i]=n;continue}e.box[r]=n;continue}throw new Error(`Box class ${s} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.`)}return At.uuid={...e.uuid},At.sampleEntry={...e.sampleEntry},At.sampleGroupEntry={...e.sampleGroupEntry},At.box={...e.box},At}var th={};function L3(t){return Object.entries(t).forEach(([e,s])=>th[e]=s),th}function I3(t){return $n(t)}function $n(t){let e="";for(let s=0;s<16;s++){const n=t.readUint8().toString(16);e+=n.length===1?"0"+n:n}return e}function ps(t,e,s){let n,r;const i=t.getPosition();let a=0,l;if(t.getEndPosition()-i<8)return M.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:Ks};if(s&&s<8)return M.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:Ks};let c=t.readUint32();const u=t.readString(4);if(u.length!==4||!/^[\x20-\x7E]{4}$/.test(u))return M.error("BoxParser",`Invalid box type: '${u}'`),{code:_b,start:i,type:u};let d=u;if(M.debug("BoxParser","Found box of type '"+u+"' and size "+c+" at position "+i),a=8,u==="uuid"){if(t.getEndPosition()-t.getPosition()<16||s-a<16)return t.seek(i),M.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:Ks};l=I3(t),a+=16,d=l}if(c===1){if(t.getEndPosition()-t.getPosition()<8||s&&s-a<8)return t.seek(i),M.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+u+'" box'),{code:Ks};r=c,c=t.readUint64(),a+=8}else if(c===0){if(s)c=s;else if(u!=="mdat")return M.error("BoxParser","Unlimited box size not supported for type: '"+u+"'"),n=new ae(c),n.type=u,{code:Dt,box:n,size:n.size}}if(c!==0&&cs)return M.error("BoxParser","Box of type '"+u+"' has a size "+c+" greater than its container size "+s),{code:Ks,type:u,size:c,hdr_size:a,start:i};if(c!==0&&i+c>t.getEndPosition())return t.seek(i),M.info("BoxParser","Not enough data in stream to parse the entire '"+u+"' box"),{code:Ks,type:u,size:c,hdr_size:a,start:i,original_size:r};if(e)return{code:Dt,type:u,size:c,hdr_size:a,start:i};u in At.box?n=new At.box[u](c):u!=="uuid"?(M.warn("BoxParser",`Unknown box type: '${u}'`),n=new ae(c),n.type=u,n.has_unparsed_data=!0):l in At.uuid?n=new At.uuid[l](c):(M.warn("BoxParser",`Unknown UUID box type: '${l}'`),n=new ae(c),n.type=u,n.uuid=l,n.has_unparsed_data=!0),n.original_size=r,n.hdr_size=a,n.start=i,n.write===ae.prototype.write&&n.type!=="mdat"&&(M.info("BoxParser","'"+d+"' box writing not yet implemented, keeping unparsed data in memory for later write"),n.parseDataAndRewind(t)),n.parse(t);const f=t.getPosition()-(n.start+n.size);return f<0?(M.warn("BoxParser","Parsing of box '"+d+"' did not read the entire indicated box data size (missing "+-f+" bytes), seeking forward"),t.seek(n.start+n.size)):f>0&&n.size!==0&&(M.error("BoxParser","Parsing of box '"+d+"' read "+f+" more bytes than the indicated box data size, seeking backwards"),t.seek(n.start+n.size)),{code:Dt,box:n,size:n.size}}var Ee=class extends ae{write(t){if(this.size=0,this.writeHeader(t),this.boxes)for(let e=0;e",t+=""+s.length+"",t+="",t+=s.data.reduce(function(n,r){return n+r.toString(16).padStart(2,"0")},"0x"),t+=""}return t+="",t}},Ur,Ub=(Ur=class extends ae{constructor(){super(...arguments),this.box_name="AVCConfigurationBox"}parse(e){this.configurationVersion=e.readUint8(),this.AVCProfileIndication=e.readUint8(),this.profile_compatibility=e.readUint8(),this.AVCLevelIndication=e.readUint8(),this.lengthSizeMinusOne=e.readUint8()&3,this.nb_SPS_nalus=e.readUint8()&31;let s=this.size-this.hdr_size-6;this.SPS=new Ay;for(let n=0;n0&&(this.ext=e.readUint8Array(s))}write(e){this.size=7;for(let s=0;s=4;)this.compatible_brands[n]=e.readString(4),s-=4,n++}write(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,void 0,4),e.writeUint32(this.minor_version);for(let s=0;s1&&(M.info("BoxParser","Warning: hdlr name is not null-terminated, possibly length-prefixed string. Trimming first byte."),this.name=this.name.slice(1))}}write(e){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(e),e.writeUint32(0),e.writeString(this.handler,void 0,4),e.writeUint32Array([0,0,0]),e.writeCString(this.name)}},gi.fourcc="hdlr",gi),yi,Vb=(yi=class extends ae{constructor(){super(...arguments),this.box_name="HEVCConfigurationBox"}parse(e){this.configurationVersion=e.readUint8();let s=e.readUint8();this.general_profile_space=s>>6,this.general_tier_flag=(s&32)>>5,this.general_profile_idc=s&31,this.general_profile_compatibility=e.readUint32(),this.general_constraint_indicator=e.readUint8Array(6),this.general_level_idc=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,this.chroma_format_idc=e.readUint8()&3,this.bit_depth_luma_minus8=e.readUint8()&7,this.bit_depth_chroma_minus8=e.readUint8()&7,this.avgFrameRate=e.readUint16(),s=e.readUint8(),this.constantFrameRate=s>>6,this.numTemporalLayers=(s&13)>>3,this.temporalIdNested=(s&4)>>2,this.lengthSizeMinusOne=s&3,this.nalu_arrays=[];const n=e.readUint8();for(let r=0;r>7,i.nalu_type=s&63;const a=e.readUint16();for(let l=0;lrt||this.creation_time>rt||this.duration>rt||this.version===1;this.version=s?1:0,this.size=4*4+2*2,this.size+=s?3*4:0,this.flags=0,this.writeHeader(e),s?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.timescale),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration)),e.writeUint16(this.language),e.writeUint16(0)}},_i.fourcc="mdhd",_i),vi,$b=(vi=class extends J{constructor(){super(...arguments),this.box_name="MovieExtendsHeaderBox"}parse(e){this.parseFullHeader(e),this.flags&1&&(M.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version===1?this.fragment_duration=e.readUint64():this.fragment_duration=e.readUint32()}write(e){const s=this.fragment_duration>rt||this.version===1;this.version=s?1:0,this.size=4,this.size+=s?4:0,this.flags=0,this.writeHeader(e),s?e.writeUint64(this.fragment_duration):e.writeUint32(this.fragment_duration)}},vi.fourcc="mehd",vi),bi,dC=(bi=class extends J{constructor(){super(...arguments),this.box_name="ItemInfoEntry"}parse(e){if(this.parseFullHeader(e),(this.version===0||this.version===1)&&(this.item_ID=e.readUint16(),this.item_protection_index=e.readUint16(),this.item_name=e.readCString(),this.content_type=e.readCString(),this.isEndOfBox(e)||(this.content_encoding=e.readCString())),this.version===1){this.extension_type=e.readString(4),M.warn("BoxParser","Cannot parse extension type"),e.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=e.readUint16():this.version===3&&(this.item_ID=e.readUint32()),this.item_protection_index=e.readUint16(),this.item_type=e.readString(4),this.item_name=e.readCString(),this.item_type==="mime"?(this.content_type=e.readCString(),this.content_encoding=e.readCString()):this.item_type==="uri "&&(this.item_uri_type=e.readCString()))}},bi.fourcc="infe",bi),wi,fC=(wi=class extends J{constructor(){super(...arguments),this.box_name="ItemInfoBox"}parse(e){this.parseFullHeader(e),this.version===0?this.entry_count=e.readUint16():this.entry_count=e.readUint32(),this.item_infos=[];for(let s=0;s>4&15,this.length_size=s&15,s=e.readUint8(),this.base_offset_size=s>>4&15,this.version===1||this.version===2?this.index_size=s&15:this.index_size=0,this.items=[];let n=0;if(this.version<2)n=e.readUint16();else if(this.version===2)n=e.readUint32();else throw new Error("version of iloc box not supported");for(let r=0;r8){switch(e.readUint32(),e.readString(4)){case"hdlr":case"mhdr":case"keys":case"ilst":case"ctry":case"lang":this.isQT=!0;break}e.seek(s)}this.isQT||this.parseFullHeader(e),Ee.prototype.parse.call(this,e)}},Ei.fourcc="meta",Ei),Ni,Wb=(Ni=class extends J{constructor(){super(...arguments),this.box_name="MovieFragmentHeaderBox"}parse(e){this.parseFullHeader(e),this.sequence_number=e.readUint32()}write(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.sequence_number)}},Ni.fourcc="mfhd",Ni),ji,Gb=(ji=class extends J{constructor(){super(...arguments),this.box_name="MovieHeaderBox"}parse(e){this.parseFullHeader(e),this.version===1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.rate=e.readUint32(),this.volume=e.readUint16()>>8,e.readUint16(),e.readUint32Array(2),this.matrix=e.readInt32Array(9),e.readUint32Array(6),this.next_track_id=e.readUint32()}write(e){const s=this.modification_time>rt||this.creation_time>rt||this.duration>rt||this.version===1;this.version=s?1:0,this.size=4*4+20*4,this.size+=s?3*4:0,this.flags=0,this.writeHeader(e),s?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.timescale),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration)),e.writeUint32(this.rate),e.writeUint16(this.volume<<8),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeInt32Array(this.matrix),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(this.next_track_id)}print(e){super.printHeader(e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"timescale: "+this.timescale),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"rate: "+this.rate),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"next_track_id: "+this.next_track_id)}},ji.fourcc="mvhd",ji),Ci,yC=(Ci=class extends Wn{parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}},Ci.fourcc="mett",Ci),Ui,_C=(Ui=class extends Wn{parse(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.parseFooter(e)}},Ui.fourcc="metx",Ui),Bi,vC=(Bi=class extends ae{constructor(){super(...arguments),this.box_name="AV1CodecConfigurationBox"}parse(e){let s=e.readUint8();if((s>>7&1)!==1){M.error("BoxParser","av1C marker problem",e.isofile);return}if(this.version=s&127,this.version!==1){M.error("BoxParser","av1C version "+this.version+" not supported",e.isofile);return}if(s=e.readUint8(),this.seq_profile=s>>5&7,this.seq_level_idx_0=s&31,s=e.readUint8(),this.seq_tier_0=s>>7&1,this.high_bitdepth=s>>6&1,this.twelve_bit=s>>5&1,this.monochrome=s>>4&1,this.chroma_subsampling_x=s>>3&1,this.chroma_subsampling_y=s>>2&1,this.chroma_sample_position=s&3,s=e.readUint8(),this.reserved_1=s>>5&7,this.reserved_1!==0){M.error("BoxParser","av1C reserved_1 parsing problem",e.isofile);return}if(this.initial_presentation_delay_present=s>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=s&15;else if(this.reserved_2=s&15,this.reserved_2!==0){M.error("BoxParser","av1C reserved_2 parsing problem",e.isofile);return}const n=this.size-this.hdr_size-4;this.configOBUs=e.readUint8Array(n)}},Bi.fourcc="av1C",Bi),Ti,bC=(Ti=class extends J{constructor(){super(...arguments),this.box_name="ElementaryStreamDescriptorBox"}parse(e){this.parseFullHeader(e);const s=e.readUint8Array(this.size-this.hdr_size);if("MPEG4DescriptorParser"in th){const n=new th.MPEG4DescriptorParser;this.esd=n.parseOneDescriptor(new at(s.buffer,0))}}},Ti.fourcc="esds",Ti),Pi,wC=(Pi=class extends J{constructor(){super(...arguments),this.box_name="VPCodecConfigurationRecord"}parse(e){if(this.parseFullHeader(e),this.version===1){this.profile=e.readUint8(),this.level=e.readUint8();const s=e.readUint8();this.bitDepth=s>>4,this.chromaSubsampling=s>>1&7,this.videoFullRangeFlag=s&1,this.colourPrimaries=e.readUint8(),this.transferCharacteristics=e.readUint8(),this.matrixCoefficients=e.readUint8(),this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)}else{this.profile=e.readUint8(),this.level=e.readUint8();let s=e.readUint8();this.bitDepth=s>>4&15,this.colorSpace=s&15,s=e.readUint8(),this.chromaSubsampling=s>>4&15,this.transferFunction=s>>1&7,this.videoFullRangeFlag=s&1,this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)}}},Pi.fourcc="vpcC",Pi),zi,SC=(zi=class extends J{constructor(){super(...arguments),this.box_name="VvcConfigurationBox"}parse(e){this.parseFullHeader(e);const s={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(a){this.held_bits=a.readUint8(),this.num_held_bits=1*8},stream_read_2_bytes:function(a){this.held_bits=a.readUint16(),this.num_held_bits=2*8},extract_bits:function(a){const l=this.held_bits>>this.num_held_bits-a&(1<1){s.stream_read_1_bytes(e),this.ptl_sublayer_present_mask=0;for(let a=this.num_sublayers-2;a>=0;--a){const l=s.extract_bits(1);this.ptl_sublayer_present_mask|=l<1;++a)s.extract_bits(1);this.sublayer_level_idc=[];for(let a=this.num_sublayers-2;a>=0;--a)this.ptl_sublayer_present_mask&1<>7}else this.colour_type==="rICC"?this.ICC_profile=e.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=e.readUint8Array(this.size-4))}},Ai.fourcc="colr",Ai);function Er(t,e){let s=Number(t).toString(16);for(e=typeof e>"u"?2:e;s.length>=1;t+=Er(s,0),t+=".",this.hvcC.general_tier_flag===0?t+="L":t+="H",t+=this.hvcC.general_level_idc;let n=!1,r="";for(let i=5;i>=0;i--)(this.hvcC.general_constraint_indicator[i]||n)&&(r="."+Er(this.hvcC.general_constraint_indicator[i],0)+r,n=!0);t+=r}return t}},Mi,TC=(Mi=class extends Mh{constructor(){super(...arguments),this.box_name="HEVCSampleEntry"}},Mi.fourcc="hvc1",Mi),Vi,PC=(Vi=class extends Mh{},Vi.fourcc="hvc2",Vi),Hi,zC=(Hi=class extends Mh{constructor(){super(...arguments),this.box_name="HEVCSampleEntry",this.colrs=[],this.subBoxNames=["colr"]}},Hi.fourcc="hev1",Hi),$i,AC=($i=class extends Mh{},$i.fourcc="hev2",$i),Wi,RC=(Wi=class extends Oe{constructor(){super(...arguments),this.box_name="HEVCTileSampleSampleEntry"}},Wi.fourcc="hvt1",Wi),Gi,FC=(Gi=class extends Oe{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},Gi.fourcc="lhe1",Gi),qi,LC=(qi=class extends Oe{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},qi.fourcc="lhv1",qi),Ji,IC=(Ji=class extends Oe{},Ji.fourcc="dvh1",Ji),Ki,OC=(Ki=class extends Oe{},Ki.fourcc="dvhe",Ki),qb=class extends Oe{getCodec(){let t=super.getCodec();if(this.vvcC){t+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?t+=".H":t+=".L",t+=this.vvcC.general_level_idc;let e="";if(this.vvcC.general_constraint_info){const s=[];let n=0;n|=this.vvcC.ptl_frame_only_constraint_flag<<7,n|=this.vvcC.ptl_multilayer_enabled_flag<<6;let r;for(let i=0;i>2&63,s.push(n),n&&(r=i),n=this.vvcC.general_constraint_info[i]>>2&3;if(r===void 0)e=".CA";else{e=".C";const i="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";let a=0,l=0;for(let c=0;c<=r;++c)for(a=a<<8|s[c],l+=8;l>=5;){const u=a>>l-5&31;e+=i[u],l-=5,a&=(1<>6,this.sample_depends_on[n]=r>>4&3,this.sample_is_depended_on[n]=r>>2&3,this.sample_has_redundancy[n]=r&3}}},za.fourcc="sdtp",za),Aa,SU=(Aa=class extends J{constructor(){super(...arguments),this.box_name="SampleGroupDescriptionBox"}parse(e){this.parseFullHeader(e),this.grouping_type=e.readString(4),M.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=e.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=e.readUint32()),this.entries=[];const s=e.readUint32();for(let n=0;n=2&&e.writeUint32(this.default_sample_description_index),e.writeUint32(this.entries.length);for(let s=0;s>31&1,referenced_size:r&2147483647,subsegment_duration:i,starts_with_SAP:a>>31&1,SAP_type:a>>28&7,SAP_delta_time:a&268435455})}}write(e){const s=this.earliest_presentation_time>rt||this.first_offset>rt||this.version===1;this.version=s?1:0,this.size=4*2+2+2+12*this.references.length,this.size+=s?16:8,this.flags=0,this.writeHeader(e),e.writeUint32(this.reference_ID),e.writeUint32(this.timescale),s?(e.writeUint64(this.earliest_presentation_time),e.writeUint64(this.first_offset)):(e.writeUint32(this.earliest_presentation_time),e.writeUint32(this.first_offset)),e.writeUint16(0),e.writeUint16(this.references.length);for(let n=0;n0){let n=0;for(;n+1rt||this.version===1;this.version=s?1:0,this.size=4,this.size+=s?4:0,this.flags=0,this.writeHeader(e),s?e.writeUint64(this.baseMediaDecodeTime):e.writeUint32(this.baseMediaDecodeTime)}},Ha.fourcc="tfdt",Ha),$a,rw=($a=class extends J{constructor(){super(...arguments),this.box_name="TrackFragmentHeaderBox"}parse(e){this.parseFullHeader(e);let s=0;this.track_id=e.readUint32(),this.size-this.hdr_size>s&&this.flags&cf?(this.base_data_offset=e.readUint64(),s+=8):this.base_data_offset=0,this.size-this.hdr_size>s&&this.flags&uf?(this.default_sample_description_index=e.readUint32(),s+=4):this.default_sample_description_index=0,this.size-this.hdr_size>s&&this.flags&df?(this.default_sample_duration=e.readUint32(),s+=4):this.default_sample_duration=0,this.size-this.hdr_size>s&&this.flags&ff?(this.default_sample_size=e.readUint32(),s+=4):this.default_sample_size=0,this.size-this.hdr_size>s&&this.flags&hf?(this.default_sample_flags=e.readUint32(),s+=4):this.default_sample_flags=0}write(e){this.version=0,this.size=4,this.flags&cf&&(this.size+=8),this.flags&uf&&(this.size+=4),this.flags&df&&(this.size+=4),this.flags&ff&&(this.size+=4),this.flags&hf&&(this.size+=4),this.writeHeader(e),e.writeUint32(this.track_id),this.flags&cf&&e.writeUint64(this.base_data_offset),this.flags&uf&&e.writeUint32(this.default_sample_description_index),this.flags&df&&e.writeUint32(this.default_sample_duration),this.flags&ff&&e.writeUint32(this.default_sample_size),this.flags&hf&&e.writeUint32(this.default_sample_flags)}},$a.fourcc="tfhd",$a),Wa,iw=(Wa=class extends J{constructor(){super(...arguments),this.box_name="TrackHeaderBox",this.layer=0,this.alternate_group=0}parse(e){this.parseFullHeader(e),this.version===1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint32()),e.readUint32Array(2),this.layer=e.readInt16(),this.alternate_group=e.readInt16(),this.volume=e.readInt16()>>8,e.readUint16(),this.matrix=e.readInt32Array(9),this.width=e.readUint32(),this.height=e.readUint32()}write(e){const s=this.modification_time>rt||this.creation_time>rt||this.duration>rt||this.version===1;this.version=s?1:0,this.size=5*4+15*4,this.size+=s?3*4:0,this.flags=this.flags??3,this.writeHeader(e),s?(e.writeUint64(this.creation_time),e.writeUint64(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint64(this.duration)):(e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint32(this.duration)),e.writeUint32Array([0,0]),e.writeInt16(this.layer),e.writeInt16(this.alternate_group),e.writeInt16(this.volume<<8),e.writeInt16(0),e.writeInt32Array(this.matrix),e.writeUint32(this.width),e.writeUint32(this.height)}print(e){super.printHeader(e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"track_id: "+this.track_id),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"layer: "+this.layer),e.log(e.indent+"alternate_group: "+this.alternate_group),e.log(e.indent+"width: "+this.width),e.log(e.indent+"height: "+this.height)}},Wa.fourcc="tkhd",Wa),Ga,Zm=(Ga=class extends J{constructor(){super(...arguments),this.box_name="TrackExtendsBox"}parse(e){this.parseFullHeader(e),this.track_id=e.readUint32(),this.default_sample_description_index=e.readUint32(),this.default_sample_duration=e.readUint32(),this.default_sample_size=e.readUint32(),this.default_sample_flags=e.readUint32()}write(e){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(e),e.writeUint32(this.track_id),e.writeUint32(this.default_sample_description_index),e.writeUint32(this.default_sample_duration),e.writeUint32(this.default_sample_size),e.writeUint32(this.default_sample_flags)}},Ga.fourcc="trex",Ga),qa,aw=(qa=class extends J{constructor(){super(...arguments),this.box_name="TrackRunBox",this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[]}parse(e){this.parseFullHeader(e);let s=0;if(this.sample_count=e.readUint32(),s+=4,this.size-this.hdr_size>s&&this.flags&Tu?(this.data_offset=e.readInt32(),s+=4):this.data_offset=0,this.size-this.hdr_size>s&&this.flags&pf?(this.first_sample_flags=e.readUint32(),s+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>s)for(let n=0;nu.nb_samples!==a)){M.error("ISOFile",`Cannot set segment options for track ${e}: nbSamples (${a}) does not match existing tracks`);return}const c=this.getTrackById(e);if(c){const u={id:e,user:s,trak:c,segmentStream:void 0,nb_samples:a,nb_samples_per_fragment:l,size_per_segment:r,rapAlignement:i,state:{lastFragmentSampleNumber:0,lastSegmentSampleNumber:0,accumulatedSize:0}};this.fragmentedTracks.push(u),c.nextSample=0}this.discardMdatData&&M.warn("ISOFile","Segmentation options set but discardMdatData is true, samples will not be segmented")}unsetSegmentOptions(e){let s=-1;for(let n=0;n-1&&this.fragmentedTracks.splice(s,1)}setExtractionOptions(e,s,{nbSamples:n=1e3}={}){const r=this.getTrackById(e);r&&(this.extractedTracks.push({id:e,user:s,trak:r,nb_samples:n,samples:[]}),r.nextSample=0),this.discardMdatData&&M.warn("ISOFile","Extraction options set but discardMdatData is true, samples will not be extracted")}unsetExtractionOptions(e){let s=-1;for(let n=0;n-1&&this.extractedTracks.splice(s,1)}parse(){if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else{this.saveParsePosition&&this.saveParsePosition();const s=ps(this.stream,!1);if(s.code===Ks)if(this.processIncompleteBox){if(this.processIncompleteBox(s))continue;return}else return;else if(s.code===Dt){const n=s.box;if(this.boxes.push(n),n.type==="uuid")this[n.uuid]!==void 0&&M.warn("ISOFile","Duplicate Box of uuid: "+n.uuid+", overriding previous occurrence"),this[n.uuid]=n;else switch(n.type){case"mdat":this.mdats.push(n),this.transferMdatData(n);break;case"moof":this.moofs.push(n);break;case"free":case"skip":break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[n.type]!==void 0?Array.isArray(this[n.type+"s"])?(M.info("ISOFile",`Found multiple boxes of type ${n.type} in ISOFile, adding to array`),this[n.type+"s"].push(n)):(M.warn("ISOFile",`Found multiple boxes of type ${n.type} but no array exists. Creating array dynamically.`),this[n.type+"s"]=[this[n.type],n]):(this[n.type]=n,Array.isArray(this[n.type+"s"])&&this[n.type+"s"].push(n));break}this.updateUsedBytes&&this.updateUsedBytes(n,s)}else if(s.code===_b){M.error("ISOFile",`Invalid data found while parsing box of type '${s.type}' at position ${s.start}. Aborting parsing.`,this);break}}}checkBuffer(e){if(!e)throw new Error("Buffer must be defined and non empty");return e.byteLength===0?(M.warn("ISOFile","Ignoring empty buffer (fileStart: "+e.fileStart+")"),this.stream.logBufferLevel(),!1):(M.info("ISOFile","Processing buffer (fileStart: "+e.fileStart+")"),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(M.warn("ISOFile","Not ready to start parsing"),!1))}appendBuffer(e,s){let n;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(s),this.nextSeekPosition?(n=this.nextSeekPosition,this.nextSeekPosition=void 0):n=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(n=this.stream.getEndFilePositionAfter(n))):this.nextParsePosition?n=this.nextParsePosition:n=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(M.info("ISOFile","Done processing buffer (fileStart: "+e.fileStart+") - next buffer to fetch should have a fileStart position of "+n),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),M.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),n}getFragmentDuration(){const e=this.getBox("mvex");if(!e)return;if(e.mehd)return{num:e.mehd.fragment_duration,den:this.moov.mvhd.timescale};const s=this.getBoxes("trak",!1);let n={num:0,den:1};for(const r of s){const i=r.samples_duration,a=r.mdia.mdhd.timescale;i&&a&&i/a>n.num/n.den&&(n={num:i,den:a})}return n}getInfo(){if(!this.moov)return{hasMoov:!1,mime:""};const e=new Date("1904-01-01T00:00:00Z").getTime(),s=this.getBox("mvex")!==void 0,n={hasMoov:!0,duration:this.moov.mvhd.duration,timescale:this.moov.mvhd.timescale,isFragmented:s,fragment_duration:this.getFragmentDuration(),isProgressive:this.isProgressive,hasIOD:this.moov.iods!==void 0,brands:[this.ftyp.major_brand].concat(this.ftyp.compatible_brands),created:new Date(e+this.moov.mvhd.creation_time*1e3),modified:new Date(e+this.moov.mvhd.modification_time*1e3),tracks:[],audioTracks:[],videoTracks:[],subtitleTracks:[],metadataTracks:[],hintTracks:[],otherTracks:[],mime:""};for(let r=0;r0?n.mime+='video/mp4; codecs="':n.audioTracks&&n.audioTracks.length>0?n.mime+='audio/mp4; codecs="':n.mime+='application/mp4; codecs="';for(let r=0;rn.trak.nextSamplen.nb_samples_per_fragment,c=a-n.state.lastSegmentSampleNumber>n.nb_samples;let u=l||a%n.nb_samples_per_fragment===0,d=c||a%n.nb_samples===0,f=n.state.accumulatedSize>=n.size_per_segment;const h=!n.rapAlignement||i.is_sync,g=e||r.nextSample+1>=r.samples.length;if(g&&!h&&M.warn("ISOFile","Flushing track #"+n.id+" at sample #"+r.nextSample+" which is not a RAP, this may lead to playback issues"),u=u&&h,d=d&&h,f=f&&h,u||f||g){l?M.warn("ISOFile","Fragment on track #"+n.id+" is overdue, creating it with samples ["+n.state.lastFragmentSampleNumber+", "+r.nextSample+"]"):M.debug("ISOFile","Creating media fragment on track #"+n.id+" for samples ["+n.state.lastFragmentSampleNumber+", "+r.nextSample+"]");const v=this.createFragment(n.id,n.state.lastFragmentSampleNumber,r.nextSample,n.segmentStream);if(v)n.segmentStream=v,n.state.lastFragmentSampleNumber=r.nextSample+1;else{s.add(n.id);continue}}(d||f||g)&&(c?M.warn("ISOFile","Segment on track #"+n.id+" is overdue, sending it with samples ["+Math.max(0,r.nextSample-n.nb_samples)+", "+(r.nextSample-1)+"]"):M.info("ISOFile","Sending fragmented data on track #"+n.id+" for samples ["+Math.max(0,r.nextSample-n.nb_samples)+", "+(r.nextSample-1)+"]"),M.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(n.id,n.user,n.segmentStream.buffer,r.nextSample+1,e||r.nextSample+1>=r.samples.length),n.segmentStream=void 0,n.state.accumulatedSize=0,n.state.lastSegmentSampleNumber=r.nextSample+1),r.nextSample++}}}if(this.onSamples!==void 0)for(let s=0;s=r.samples.length)&&(M.debug("ISOFile","Sending samples on track #"+n.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(n.id,n.user,n.samples),n.samples=[],n!==this.extractedTracks[s]))break}}}}getBox(e){const s=this.getBoxes(e,!0);return s.length?s[0]:void 0}getBoxes(e,s){const n=[],r=i=>{i instanceof ae&&i.type&&i.type===e&&n.push(i);const a=[];i.boxes&&a.push(...i.boxes),i.entries&&a.push(...i.entries),i.item_infos&&a.push(...i.item_infos),i.references&&a.push(...i.references);for(const l of a){if(n.length&&s)return;r(l)}};return r(this),n}getTrackSamplesInfo(e){const s=this.getTrackById(e);if(s)return s.samples}getTrackSample(e,s){const n=this.getTrackById(e);return this.getSample(n,s)}releaseUsedSamples(e,s){let n=0;const r=this.getTrackById(e);r.lastValidSample||(r.lastValidSample=0);for(let i=r.lastValidSample;ie*u.timescale){i=c-1;break}s&&u.is_sync&&(r=c)}for(s&&(i=r),e=n.samples[i].cts,n.nextSample=i;n.samples[i].alreadyRead===n.samples[i].size&&n.samples[i+1];)i++;const l=n.samples[i].offset+n.samples[i].alreadyRead;return M.info("ISOFile","Seeking to "+(s?"RAP":"")+" sample #"+n.nextSample+" on track "+n.tkhd.track_id+", time "+M.getDurationString(e,a)+" and offset: "+l),{offset:l,time:e/a}}getTrackDuration(e){if(!e.samples)return 1/0;const s=e.samples[e.samples.length-1];return(s.cts+s.duration)/s.timescale}seek(e,s){const n=this.moov;let r={offset:1/0,time:1/0};if(this.moov){for(let i=0;ithis.getTrackDuration(a))continue;const l=this.seekTrack(e,s,a);l.offset({id:r.tkhd.track_id,user:this.fragmentedTracks[i].user})),buffer:Qs.writeInitializationSegment(this.ftyp,e,(n=(s=this.moov)==null?void 0:s.mvex)==null?void 0:n.mehd.fragment_duration)}}resetTables(){this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0;for(let e=0;e=2){const l=i[a].grouping_type+"/0",c=new yf(i[a].grouping_type,0);c.is_fragment=!0,s.sample_groups_info[l]||(s.sample_groups_info[l]=c)}}}else for(let a=0;a=2){const l=r[a].grouping_type+"/0",c=new yf(r[a].grouping_type,0);e.sample_groups_info[l]||(e.sample_groups_info[l]=c)}}static setSampleGroupProperties(e,s,n,r){s.sample_groups=[];for(const i in r)if(s.sample_groups[i]={grouping_type:r[i].grouping_type,grouping_type_parameter:r[i].grouping_type_parameter},n>=r[i].last_sample_in_run&&(r[i].last_sample_in_run<0&&(r[i].last_sample_in_run=0),r[i].entry_index++,r[i].entry_index<=r[i].sbgp.entries.length-1&&(r[i].last_sample_in_run+=r[i].sbgp.entries[r[i].entry_index].sample_count)),r[i].entry_index<=r[i].sbgp.entries.length-1?s.sample_groups[i].group_description_index=r[i].sbgp.entries[r[i].entry_index].group_description_index:s.sample_groups[i].group_description_index=-1,s.sample_groups[i].group_description_index!==0){let a;if(r[i].fragment_description?a=r[i].fragment_description:a=r[i].description,s.sample_groups[i].group_description_index>0){let l;s.sample_groups[i].group_description_index>65535?l=(s.sample_groups[i].group_description_index>>16)-1:l=s.sample_groups[i].group_description_index-1,a&&l>=0&&(s.sample_groups[i].description=a.entries[l])}else a&&a.version>=2&&a.default_group_description_index>0&&(s.sample_groups[i].description=a.entries[a.default_group_description_index-1])}}static process_sdtp(e,s,n){s&&(e?(s.is_leading=e.is_leading[n],s.depends_on=e.sample_depends_on[n],s.is_depended_on=e.sample_is_depended_on[n],s.has_redundancy=e.sample_has_redundancy[n]):(s.is_leading=0,s.depends_on=0,s.is_depended_on=0,s.has_redundancy=0))}buildSampleLists(){for(let e=0;e"u")){for(s=0;sy&&(N++,y<0&&(y=0),y+=f.sample_counts[N]),s>0?(e.samples[s-1].duration=f.sample_deltas[N],e.samples_duration+=e.samples[s-1].duration,C.dts=e.samples[s-1].dts+e.samples[s-1].duration):C.dts=0,h?(s>=j&&(w++,j<0&&(j=0),j+=h.sample_counts[w]),C.cts=e.samples[s].dts+h.sample_offsets[w]):C.cts=C.dts,g?(s===g.sample_numbers[B]-1?(C.is_sync=!0,B++):(C.is_sync=!1,C.degradation_priority=0),_&&_.entries[T].sample_delta+O===s+1&&(C.subsamples=_.entries[T].subsamples,O+=_.entries[T].sample_delta,T++)):C.is_sync=!0,Qs.process_sdtp(e.mdia.minf.stbl.sdtp,C,C.number),k?C.degradation_priority=k.priority[s]:C.degradation_priority=0,_&&_.entries[T].sample_delta+O===s&&(C.subsamples=_.entries[T].subsamples,O+=_.entries[T].sample_delta),(x.length>0||p.length>0)&&Qs.setSampleGroupProperties(e,C,s,e.sample_groups_info)}s>0&&(e.samples[s-1].duration=Math.max(e.mdia.mdhd.duration-e.samples[s-1].dts,0),e.samples_duration+=e.samples[s-1].duration)}}updateSampleLists(){let e,s,n,r,i;if(this.moov!==void 0)for(;this.lastMoofIndex0&&Qs.initSampleGroups(d,u,u.sbgps,d.mdia.minf.stbl.sgpds,u.sgpds);for(let h=0;h0?y=d.samples[d.samples.length-1].dts+d.samples[d.samples.length-1].duration:(u.tfdt?y=u.tfdt.baseMediaDecodeTime:y=0,d.first_traf_merged=!0);let N=y;g.flags&Ru&&(N=y+g.sample_composition_time_offset[v]);const j=!!(u.tfhd.flags&cf),w=!!(u.tfhd.flags&Uy),B=!!(g.flags&Tu);let T=0;j?T=u.tfhd.base_data_offset:w||h===0?T=l.start:T=i;let O;h===0&&v===0?B?O=T+g.data_offset:O=T:O=i,i=O+x;const C=u.sample_number;u.sample_number++;const q={cts:N,description_index:_,description:d.mdia.minf.stbl.stsd.entries[_],dts:y,duration:p,moof_number:this.lastMoofIndex,number_in_traf:C,number:d.samples.length,offset:O,size:x,timescale:d.mdia.mdhd.timescale,track_id:d.tkhd.track_id,is_sync:!(k>>16&1),is_leading:k>>26&3,depends_on:k>>24&3,is_depended_on:k>>22&3,has_redundancy:k>>20&3,degradation_priority:k&65535};u.first_sample_index=d.samples.length,d.samples.push(q),(u.sbgps.length>0||u.sgpds.length>0||d.mdia.minf.stbl.sbgps.length>0||d.mdia.minf.stbl.sgpds.length>0)&&Qs.setSampleGroupProperties(d,q,q.number_in_traf,u.sample_groups_info)}}if(u.subs){d.has_fragment_subsamples=!0;let h=u.first_sample_index;for(let g=0;g-1)a=r.buffers[i],l=a.fileStart;else for(const c of this.mdats){if(!c.stream){M.debug("ISOFile","mdat stream not yet fully read for #"+this.mdats.indexOf(c)+" mdat");continue}if(i=c.stream.findPosition(!0,n.offset+n.alreadyRead-c.start-c.hdr_size,!1),i>-1){r=c.stream,a=c.stream.buffers[i],l=c.start+c.hdr_size+a.fileStart;break}}if(a){const c=a.byteLength-(n.offset+n.alreadyRead-l);if(n.size-n.alreadyRead<=c)return M.debug("ISOFile","Getting sample #"+s+" data (alreadyRead: "+n.alreadyRead+" offset: "+(n.offset+n.alreadyRead-l)+" read size: "+(n.size-n.alreadyRead)+" full size: "+n.size+")"),at.memcpy(n.data.buffer,n.alreadyRead,a,n.offset+n.alreadyRead-l,n.size-n.alreadyRead),a.usedBytes+=n.size-n.alreadyRead,r.logBufferLevel(),n.alreadyRead=n.size,n;if(c===0)return;M.debug("ISOFile","Getting sample #"+s+" partial data (alreadyRead: "+n.alreadyRead+" offset: "+(n.offset+n.alreadyRead-l)+" read size: "+c+" full size: "+n.size+")"),at.memcpy(n.data.buffer,n.alreadyRead,a,n.offset+n.alreadyRead-l,c),n.alreadyRead+=c,a.usedBytes+=c,r.logBufferLevel()}else return}}}releaseSample(e,s){const n=e.samples[s];return n.data?(this.samplesDataSize-=n.size,n.data=void 0,n.alreadyRead=0,n.size):0}getAllocatedSampleDataSize(){return this.samplesDataSize}getCodecs(){let e="";for(let s=0;s0&&(e+=","),e+=n.mdia.minf.stbl.stsd.entries[0].getCodec()}return e}getTrexById(e){if(!(!this.moov||!this.moov.mvex))for(let s=0;s0?n.ipro.protections[n.iinf.item_infos[r].item_protection_index-1]:void 0}}if(n.grpl)for(let r=0;r0&&d.property_index-1-1){const a=this.stream.buffers[i],l=a.byteLength-(r.offset+r.alreadyRead-a.fileStart);if(r.length-r.alreadyRead<=l)M.debug("ISOFile","Getting item #"+e+" extent #"+n+" data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-a.fileStart)+" read size: "+(r.length-r.alreadyRead)+" full extent size: "+r.length+" full item size: "+s.size+")"),at.memcpy(s.data.buffer,s.alreadyRead,a,r.offset+r.alreadyRead-a.fileStart,r.length-r.alreadyRead),(!this.parsingMdat||this.discardMdatData)&&(a.usedBytes+=r.length-r.alreadyRead),this.stream.logBufferLevel(),s.alreadyRead+=r.length-r.alreadyRead,r.alreadyRead=r.length;else{M.debug("ISOFile","Getting item #"+e+" extent #"+n+" partial data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-a.fileStart)+" read size: "+l+" full extent size: "+r.length+" full item size: "+s.size+")"),at.memcpy(s.data.buffer,s.alreadyRead,a,r.offset+r.alreadyRead-a.fileStart,l),r.alreadyRead+=l,s.alreadyRead+=l,(!this.parsingMdat||this.discardMdatData)&&(a.usedBytes+=l),this.stream.logBufferLevel();return}}else return}}if(s.alreadyRead===s.size)return s}releaseItem(e){const s=this.items[e];if(s.data){this.itemsDataSize-=s.size,s.data=void 0,s.alreadyRead=0;for(let n=0;nl){M.debug("ISOFile","Transferring 'mdat' data from buffer #"+i+" ("+l+" to "+c+")");const u=c-l,d=new Ss(u),f=s.stream.getAbsoluteEndPosition();at.memcpy(d,0,a,l,u),d.fileStart=f,s.stream.insertBuffer(d),a.usedBytes+=u}}}processIncompleteMdat(){const e=this.parsingMdat;return this.stream.seek(e.start+e.size,!1,this.discardMdatData)?(M.debug("ISOFile","Found 'mdat' end in buffered data"),this.transferMdatData(),this.parsingMdat=void 0,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)}restoreParsePosition(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)}saveParsePosition(){this.lastBoxStartPosition=this.stream.getPosition()}updateUsedBytes(e,s){this.stream.addUsedBytes&&(e.type==="mdat"?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))}addBox(e){return ae.prototype.addBox.call(this,e)}init(e={}){const s=this.addBox(new Db);s.major_brand=e.brands&&e.brands[0]||"iso4",s.minor_version=0,s.compatible_brands=e.brands||["iso4"];const n=this.addBox(new Ym);n.addBox(new Xm);const r=n.addBox(new Gb);return r.timescale=e.timescale||600,r.rate=e.rate||65536,r.creation_time=0,r.modification_time=0,r.duration=e.duration||0,r.volume=e.width?0:256,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.next_track_id=1,this}addTrack(e={}){this.moov||this.init(e);const s=e||{};s.width=s.width||320,s.height=s.height||320,s.id=s.id||this.moov.mvhd.next_track_id,s.type=s.type||"avc1";const n=this.moov.addBox(new Tb);this.moov.mvhd.next_track_id=s.id+1;const r=n.addBox(new iw);r.flags=U3|B3|T3,r.creation_time=0,r.modification_time=0,r.track_id=s.id,r.duration=s.duration||0,r.layer=s.layer||0,r.alternate_group=0,r.volume=1,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.width=s.width<<16,r.height=s.height<<16;const i=n.addBox(new Pb),a=i.addBox(new Hb);a.creation_time=0,a.modification_time=0,a.timescale=s.timescale||1,a.duration=s.media_duration||0,a.language=s.language||"und";const l=i.addBox(new Mb);l.handler=s.hdlr||"vide",l.name=s.name||"Track created with MP4Box.js";const c=i.addBox(new Ob);c.extended_language=s.language||"fr-FR";const u=i.addBox(new zb),d=At.sampleEntry[s.type];if(!d)return;const f=new d;if(f.data_reference_index=1,f instanceof Oe){const w=f,B=u.addBox(new lw);B.graphicsmode=0,B.opcolor=[0,0,0],w.width=s.width,w.height=s.height,w.horizresolution=72<<16,w.vertresolution=72<<16,w.frame_count=1,w.compressorname=s.type+" Compressor",w.depth=24,s.avcDecoderConfigRecord?w.addBox(new Ub(s.avcDecoderConfigRecord.byteLength)).parse(new at(s.avcDecoderConfigRecord)):s.hevcDecoderConfigRecord&&w.addBox(new Vb(s.hevcDecoderConfigRecord.byteLength)).parse(new at(s.hevcDecoderConfigRecord))}else if(f instanceof Ut){const w=f,B=u.addBox(new Qb);B.balance=s.balance||0,w.channel_count=s.channel_count||2,w.samplesize=s.samplesize||16,w.samplerate=s.samplerate||65536}else f instanceof Qm?u.addBox(new Bb):f instanceof yn?(u.addBox(new Xb),f instanceof Kb&&(f.namespace=s.namespace||"nonamespace",f.schema_location=s.schema_location||"",f.auxiliary_mime_types=s.auxiliary_mime_types||"")):f instanceof Wn?u.addBox(new gf):f instanceof Oh?u.addBox(new gf):u.addBox(new gf);s.description&&f.addBox.call(f,s.description),s.description_boxes&&s.description_boxes.forEach(function(w){f.addBox.call(f,w)});const g=u.addBox(new Ab).addBox(new Ib),v=new ow;v.flags=1,g.addEntry(v);const _=u.addBox(new Rb);_.addBox(new ew).addEntry(f);const x=_.addBox(new sw);x.sample_counts=[],x.sample_deltas=[];const p=_.addBox(new Zb);p.first_chunk=[],p.samples_per_chunk=[],p.sample_description_index=[];const y=_.addBox(new Yb);y.chunk_offsets=[];const N=_.addBox(new tw);N.sample_sizes=[];const j=this.moov.mvex.addBox(new Zm);return j.track_id=s.id,j.default_sample_description_index=s.default_sample_description_index||1,j.default_sample_duration=s.default_sample_duration||0,j.default_sample_size=s.default_sample_size||0,j.default_sample_flags=s.default_sample_flags||0,this.buildTrakSampleLists(n),s.id}addSample(e,s,{sample_description_index:n,duration:r=1,cts:i=0,dts:a=0,is_sync:l=!1,is_leading:c=0,depends_on:u=0,is_depended_on:d=0,has_redundancy:f=0,degradation_priority:h=0,subsamples:g,offset:v=0}={}){const _=this.getTrackById(e);if(_===void 0)return;const k=n?n-1:0,x={number:_.samples.length,track_id:_.tkhd.track_id,timescale:_.mdia.mdhd.timescale,description_index:k,description:_.mdia.minf.stbl.stsd.entries[k],data:s,size:s.byteLength,alreadyRead:s.byteLength,duration:r,cts:i,dts:a,is_sync:l,is_leading:c,depends_on:u,is_depended_on:d,has_redundancy:f,degradation_priority:h,offset:v,subsamples:g};_.samples.push(x),_.samples_size+=x.size,_.samples_duration+=x.duration,_.first_dts===void 0&&(_.first_dts=a),this.processSamples();const p=this.addBox(this.createMoof([x]));p.computeSize(),p.trafs[0].truns[0].data_offset=p.size+8;const y=this.addBox(new xf);return y.data=new Uint8Array(s),x}createMoof(e){if(e.length===0)return;if(e.some(d=>d.track_id!==e[0].track_id))throw new Error("Cannot create moof for samples from different tracks: "+e.map(d=>d.track_id).join(", "));const s=e[0].track_id,n=this.getTrackById(s);if(!n)throw new Error("Cannot create moof for non-existing track: "+s);const r=new Fb,i=r.addBox(new Wb);i.sequence_number=++this.nextMoofNumber;const a=r.addBox(new Lb),l=a.addBox(new rw);l.track_id=s,l.flags=Uy;const c=a.addBox(new nw);c.baseMediaDecodeTime=e[0].dts-(n.first_dts||0);const u=a.addBox(new aw);u.flags=Tu|Pu|zu|Au|Ru,u.data_offset=0,u.first_sample_flags=0,u.sample_count=e.length;for(const d of e){let f=0;d.is_sync?f=1<<25:f=65536,u.sample_duration.push(d.duration),u.sample_size.push(d.size),u.sample_flags.push(f),u.sample_composition_time_offset.push(d.cts-d.dts)}return r}print(e){e.indent="";for(let s=0;sSn,ES_Descriptor:()=>gg,MPEG4DescriptorParser:()=>pw});var dw=3,sh=4,xg=5,fw=6,Sn=class hw{constructor(e,s){this.tag=e,this.size=s,this.descs=[]}parse(e){this.data=e.readUint8Array(this.size)}findDescriptor(e){for(let s=0;s>3;return s===31&&e.data.length>=2&&(s=32+((e.data[0]&7)<<3)+((e.data[1]&224)>>5)),s}}},NU=class extends Sn{constructor(t){super(sh,t)}parse(t){this.oti=t.readUint8(),this.streamType=t.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=t.readUint24(),this.maxBitrate=t.readUint32(),this.avgBitrate=t.readUint32(),this.size-=13,this.parseRemainingDescriptors(t)}},jU=class extends Sn{constructor(t){super(xg,t)}},CU=class extends Sn{constructor(t){super(fw,t)}},UU={Descriptor:Sn,ES_Descriptor:gg,DecoderConfigDescriptor:NU,DecoderSpecificInfo:jU,SLConfigDescriptor:CU},_f={[dw]:"ES_Descriptor",[sh]:"DecoderConfigDescriptor",[xg]:"DecoderSpecificInfo",[fw]:"SLConfigDescriptor"},pw=class{constructor(){this.parseOneDescriptor=Sn.prototype.parseOneDescriptor}getDescriptorName(t){return _f[t]}},BU=class{parseSample(t){var n;const e=[],s=new kr(Ss.fromArrayBuffer(t.buffer,0));for(;!s.isEof();){const r=ps(s,!1);r.code===Dt&&((n=r.box)==null?void 0:n.type)==="vttc"&&e.push(r.box)}return e}getText(t,e,s){function n(l,c){const u=l.toString();return u.length>=c?u:new Array(c-u.length+1).join("0")+u}function r(l){const c=Math.floor(l/3600),u=Math.floor((l-c*3600)/60),d=Math.floor(l-c*3600-u*60),f=Math.floor((l-c*3600-u*60-d)*1e3);return""+n(c,2)+":"+n(u,2)+":"+n(d,2)+"."+n(f,3)}const i=this.parseSample(s);let a="";for(let l=0;l "+r(e)+`\r `,a+=c.payl.text}return a}},TU=class{parseSample(t){const e={resources:[],documentString:"",document:void 0},s=new at(t.data.buffer);if(!t.subsamples||t.subsamples.length===0)e.documentString=s.readString(t.data.length);else if(e.documentString=s.readString(t.subsamples[0].size),t.subsamples.length>1)for(let n=1;nGU,ItemContentIDPropertyBox:()=>b6,OpusSampleEntry:()=>nU,SmDmBox:()=>yB,a1lxBox:()=>AU,a1opBox:()=>RU,ac_3SampleEntry:()=>eU,ac_4SampleEntry:()=>tU,aebrBox:()=>u4,afbrBox:()=>d4,albcBox:()=>f4,alstSampleGroupEntry:()=>QB,altrBox:()=>h4,auxCBox:()=>FU,av01SampleEntry:()=>UC,av1CBox:()=>vC,avc1SampleEntry:()=>EC,avc2SampleEntry:()=>NC,avc3SampleEntry:()=>jC,avc4SampleEntry:()=>CC,avcCBox:()=>Ub,avllSampleGroupEntry:()=>YB,avs3SampleEntry:()=>GC,avssSampleGroupEntry:()=>XB,brstBox:()=>p4,btrtBox:()=>LU,bxmlBox:()=>$3,ccstBox:()=>IU,cdefBox:()=>OU,clapBox:()=>DU,clefBox:()=>sB,clliBox:()=>MU,cmexBox:()=>VU,cminBox:()=>HU,cmpdBox:()=>$U,co64Box:()=>WU,colrBox:()=>kC,coviBox:()=>KU,cprtBox:()=>QU,cschBox:()=>YU,cslgBox:()=>XU,cttsBox:()=>ZU,dOpsBox:()=>a4,dac3Box:()=>e4,dataBox:()=>_u,dav1SampleEntry:()=>BC,dec3Box:()=>t4,dfLaBox:()=>s4,dimmBox:()=>n4,dinfBox:()=>Ab,dmax:()=>r4,dmedBox:()=>i4,dobrBox:()=>m4,drefBox:()=>Ib,drepBox:()=>o4,dtrtSampleGroupEntry:()=>ZB,dvh1SampleEntry:()=>IC,dvheSampleEntry:()=>OC,ec_3SampleEntry:()=>sU,edtsBox:()=>G3,elngBox:()=>Ob,elstBox:()=>l4,emsgBox:()=>c4,encaSampleEntry:()=>uU,encmSampleEntry:()=>mU,encsSampleEntry:()=>fU,enctSampleEntry:()=>pU,encuSampleEntry:()=>dU,encvSampleEntry:()=>cU,enofBox:()=>rB,eqivBox:()=>x4,esdsBox:()=>bC,etypBox:()=>cC,fLaCSampleEntry:()=>lU,favcBox:()=>g4,fielBox:()=>j4,fobrBox:()=>y4,freeBox:()=>D3,frmaBox:()=>C4,ftypBox:()=>Db,grplBox:()=>oC,hdlrBox:()=>Mb,hev1SampleEntry:()=>zC,hev2SampleEntry:()=>AC,hinfBox:()=>Y3,hmhdBox:()=>Bb,hntiBox:()=>Q3,hvc1SampleEntry:()=>TC,hvc2SampleEntry:()=>PC,hvcCBox:()=>Vb,hvt1SampleEntry:()=>RC,iaugBox:()=>_4,idatBox:()=>O3,iinfBox:()=>fC,ilocBox:()=>hC,ilstBox:()=>iB,imirBox:()=>U4,infeBox:()=>dC,iodsBox:()=>V3,ipcoBox:()=>aC,ipmaBox:()=>B4,iproBox:()=>W3,iprpBox:()=>iC,irefBox:()=>mC,irotBox:()=>T4,ispeBox:()=>P4,itaiBox:()=>z4,j2kHBox:()=>lC,j2kiSampleEntry:()=>qC,keysBox:()=>aB,kindBox:()=>A4,levaBox:()=>R4,lhe1SampleEntry:()=>FC,lhv1SampleEntry:()=>LC,lhvCBox:()=>F4,lselBox:()=>L4,m4aeSampleEntry:()=>ZC,maxrBox:()=>I4,mdatBox:()=>xf,mdcvBox:()=>O4,mdhdBox:()=>Hb,mdiaBox:()=>Pb,mecoBox:()=>K3,mehdBox:()=>$b,metaBox:()=>gC,mettSampleEntry:()=>yC,metxSampleEntry:()=>_C,mfhdBox:()=>Wb,mfraBox:()=>J3,mfroBox:()=>D4,mha1SampleEntry:()=>rU,mha2SampleEntry:()=>iU,mhm1SampleEntry:()=>aU,mhm2SampleEntry:()=>oU,minfBox:()=>zb,mjp2SampleEntry:()=>JC,mjpgSampleEntry:()=>KC,moofBox:()=>Fb,moovBox:()=>Ym,mp4aSampleEntry:()=>XC,mp4sSampleEntry:()=>hU,mp4vSampleEntry:()=>YC,mskCBox:()=>M4,msrcTrackGroupTypeBox:()=>IB,mvexBox:()=>Xm,mvhdBox:()=>Gb,mvifSampleGroupEntry:()=>e6,nmhdBox:()=>gf,npckBox:()=>V4,numpBox:()=>H4,padbBox:()=>W4,panoBox:()=>v4,paspBox:()=>G4,paylBox:()=>q4,paytBox:()=>J4,pdinBox:()=>K4,piffLsmBox:()=>m6,piffPsshBox:()=>x6,piffSencBox:()=>g6,piffTencBox:()=>y6,piffTfrfBox:()=>_6,piffTfxdBox:()=>v6,pitmBox:()=>xC,pixiBox:()=>Q4,pmaxBox:()=>Y4,povdBox:()=>uC,prdiBox:()=>X4,prfrBox:()=>Z4,prftBox:()=>eB,prgrBox:()=>E4,profBox:()=>oB,prolSampleGroupEntry:()=>t6,psshBox:()=>tB,pymdBox:()=>N4,rapSampleGroupEntry:()=>s6,rashSampleGroupEntry:()=>n6,resvSampleEntry:()=>xU,rinfBox:()=>tC,rollSampleGroupEntry:()=>r6,rtp_Box:()=>uB,saioBox:()=>dB,saizBox:()=>fB,sbgpBox:()=>bU,sbpmBox:()=>pB,sbttSampleEntry:()=>gU,schiBox:()=>sC,schmBox:()=>mB,scifSampleGroupEntry:()=>i6,scnmSampleGroupEntry:()=>a6,sdp_Box:()=>xB,sdtpBox:()=>wU,seigSampleGroupEntry:()=>o6,sencBox:()=>gB,sgpdBox:()=>SU,sidxBox:()=>kU,sinfBox:()=>eC,skipBox:()=>M3,slidBox:()=>b4,smhdBox:()=>Qb,sratBox:()=>_B,ssixBox:()=>vB,stblBox:()=>Rb,stcoBox:()=>Yb,stdpBox:()=>bB,sterBox:()=>w4,sthdBox:()=>Xb,stppSampleEntry:()=>Kb,strdBox:()=>Z3,striBox:()=>wB,strkBox:()=>X3,stsaSampleGroupEntry:()=>l6,stscBox:()=>Zb,stsdBox:()=>ew,stsgBox:()=>SB,stshBox:()=>kB,stssBox:()=>EB,stszBox:()=>tw,sttsBox:()=>sw,stviBox:()=>NB,stxtSampleEntry:()=>yU,stypBox:()=>jB,stz2Box:()=>CB,subsBox:()=>UB,syncSampleGroupEntry:()=>c6,taicBox:()=>BB,taptBox:()=>lB,teleSampleGroupEntry:()=>u6,tencBox:()=>TB,tfdtBox:()=>nw,tfhdBox:()=>rw,tfraBox:()=>PB,tkhdBox:()=>iw,tmaxBox:()=>zB,tminBox:()=>AB,totlBox:()=>RB,tpayBox:()=>FB,tpylBox:()=>LB,trafBox:()=>Lb,trakBox:()=>Tb,trefBox:()=>OB,trepBox:()=>DB,trexBox:()=>Zm,trgrBox:()=>nC,trpyBox:()=>MB,trunBox:()=>aw,tsasSampleGroupEntry:()=>d6,tsclSampleGroupEntry:()=>f6,tselBox:()=>VB,tsynBox:()=>S4,tx3gSampleEntry:()=>_U,txtcBox:()=>HB,tycoBox:()=>$B,udesBox:()=>WB,udtaBox:()=>rC,uncCBox:()=>GB,uncvSampleEntry:()=>QC,urlBox:()=>ow,urnBox:()=>qB,viprSampleGroupEntry:()=>h6,vmhdBox:()=>lw,vp08SampleEntry:()=>$C,vp09SampleEntry:()=>WC,vpcCBox:()=>wC,vttCBox:()=>JB,vttcBox:()=>q3,vvc1SampleEntry:()=>DC,vvcCBox:()=>SC,vvcNSampleEntry:()=>HC,vvi1SampleEntry:()=>MC,vvnCBox:()=>KB,vvs1SampleEntry:()=>VC,waveBox:()=>cB,wbbrBox:()=>k4,wvttSampleEntry:()=>vU,xmlBox:()=>H3});var Qa,AU=(Qa=class extends ae{constructor(){super(...arguments),this.box_name="AV1LayeredImageIndexingProperty"}parse(e){const n=((e.readUint8()&1&1)+1)*16;this.layer_size=[];for(let r=0;r<3;r++)n===16?this.layer_size[r]=e.readUint16():this.layer_size[r]=e.readUint32()}},Qa.fourcc="a1lx",Qa),Ya,RU=(Ya=class extends ae{constructor(){super(...arguments),this.box_name="OperatingPointSelectorProperty"}parse(e){this.op_index=e.readUint8()}},Ya.fourcc="a1op",Ya),Xa,FU=(Xa=class extends J{constructor(){super(...arguments),this.box_name="AuxiliaryTypeProperty"}parse(e){this.parseFullHeader(e),this.aux_type=e.readCString();const s=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=e.readUint8Array(s)}},Xa.fourcc="auxC",Xa),Za,LU=(Za=class extends ae{constructor(){super(...arguments),this.box_name="BitRateBox"}parse(e){this.bufferSizeDB=e.readUint32(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32()}},Za.fourcc="btrt",Za),eo,IU=(eo=class extends J{constructor(){super(...arguments),this.box_name="CodingConstraintsBox"}parse(e){this.parseFullHeader(e);const s=e.readUint8();this.all_ref_pics_intra=(s&128)===128,this.intra_pred_used=(s&64)===64,this.max_ref_per_pic=(s&63)>>2,e.readUint24()}},eo.fourcc="ccst",eo),to,OU=(to=class extends ae{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}parse(e){this.channel_count=e.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[];for(let s=0;s=32768&&this.component_type_urls.push(e.readCString())}}},ao.fourcc="cmpd",ao),oo,WU=(oo=class extends J{constructor(){super(...arguments),this.box_name="ChunkLargeOffsetBox"}parse(e){this.parseFullHeader(e);const s=e.readUint32();if(this.chunk_offsets=[],this.version===0)for(let n=0;n>5),this.coverage_regions=new Array;for(let i=0;i>6),a.sphere_region=this.parseSphereRegion(e,!0,!0),this.coverage_regions.push(a)}}parseSphereRegion(e,s,n){const r=new qU;return r.centre_azimuth=e.readInt32(),r.centre_elevation=e.readInt32(),r.centre_tilt=e.readInt32(),r.range_included_flag=s,s&&(r.azimuth_range=e.readUint32(),r.elevation_range=e.readUint32()),r.interpolate_included_flag=n,n&&(r.interpolate=(e.readUint8()&128)===128),r}},co.fourcc="covi",co),uo,QU=(uo=class extends J{constructor(){super(...arguments),this.box_name="CopyrightBox"}parse(e){this.parseFullHeader(e),this.parseLanguage(e),this.notice=e.readCString()}},uo.fourcc="cprt",uo),fo,YU=(fo=class extends J{constructor(){super(...arguments),this.box_name="CompatibleSchemeTypeBox"}parse(e){this.parseFullHeader(e),this.scheme_type=e.readString(4),this.scheme_version=e.readUint32(),this.flags&1&&(this.scheme_uri=e.readCString())}},fo.fourcc="csch",fo),fu=2147483647,ho,XU=(ho=class extends J{constructor(){super(...arguments),this.box_name="CompositionToDecodeBox"}parse(e){this.parseFullHeader(e),this.version===0?(this.compositionToDTSShift=e.readInt32(),this.leastDecodeToDisplayDelta=e.readInt32(),this.greatestDecodeToDisplayDelta=e.readInt32(),this.compositionStartTime=e.readInt32(),this.compositionEndTime=e.readInt32()):this.version===1&&(this.compositionToDTSShift=e.readInt64(),this.leastDecodeToDisplayDelta=e.readInt64(),this.greatestDecodeToDisplayDelta=e.readInt64(),this.compositionStartTime=e.readInt64(),this.compositionEndTime=e.readInt64())}write(e){this.version=0,(this.compositionToDTSShift>fu||this.leastDecodeToDisplayDelta>fu||this.greatestDecodeToDisplayDelta>fu||this.compositionStartTime>fu||this.compositionEndTime>fu)&&(this.version=1),this.flags=0,this.version===0?(this.size=4*5,this.writeHeader(e),e.writeInt32(this.compositionToDTSShift),e.writeInt32(this.leastDecodeToDisplayDelta),e.writeInt32(this.greatestDecodeToDisplayDelta),e.writeInt32(this.compositionStartTime),e.writeInt32(this.compositionEndTime)):this.version===1&&(this.size=8*5,this.writeHeader(e),e.writeInt64(this.compositionToDTSShift),e.writeInt64(this.leastDecodeToDisplayDelta),e.writeInt64(this.greatestDecodeToDisplayDelta),e.writeInt64(this.compositionStartTime),e.writeInt64(this.compositionEndTime))}},ho.fourcc="cslg",ho),po,ZU=(po=class extends J{constructor(){super(...arguments),this.box_name="CompositionOffsetBox"}parse(e){this.parseFullHeader(e);const s=e.readUint32();if(this.sample_counts=[],this.sample_offsets=[],this.version===0)for(let n=0;ns<0)?1:0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length);for(let s=0;s>6,this.bsid=s>>1&31,this.bsmod=(s&1)<<2|n>>6&3,this.acmod=n>>3&7,this.lfeon=n>>2&1,this.bit_rate_code=n&3|r>>5&7}},mo.fourcc="dac3",mo),xo,t4=(xo=class extends ae{constructor(){super(...arguments),this.box_name="EC3SpecificBox"}parse(e){const s=e.readUint16();this.data_rate=s>>3,this.num_ind_sub=s&7,this.ind_subs=[];for(let n=0;n>6,bsid:r>>1&31,bsmod:(r&1)<<4|i>>4&15,acmod:i>>1&7,lfeon:i&1,num_dep_sub:a>>1&15};this.ind_subs.push(l),l.num_dep_sub>0&&(l.chan_loc=(a&1)<<8|e.readUint8())}}},xo.fourcc="dec3",xo),go,s4=(go=class extends J{constructor(){super(...arguments),this.box_name="FLACSpecificBox"}parse(e){this.parseFullHeader(e);const s=127,n=128,r=[],i=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];let a;do{a=e.readUint8();const l=Math.min(a&s,i.length-1);l?e.readUint8Array(e.readUint24()):(e.readUint8Array(13),this.samplerate=e.readUint32()>>12,e.readUint8Array(20)),r.push(i[l])}while(a&n);this.numMetadataBlocks=r.length+" ("+r.join(", ")+")"}},go.fourcc="dfLa",go),yo,n4=(yo=class extends ae{constructor(){super(...arguments),this.box_name="hintimmediateBytesSent"}parse(e){this.bytessent=e.readUint64()}},yo.fourcc="dimm",yo),_o,r4=(_o=class extends ae{constructor(){super(...arguments),this.box_name="hintlongestpacket"}parse(e){this.time=e.readUint32()}},_o.fourcc="dmax",_o),vo,i4=(vo=class extends ae{constructor(){super(...arguments),this.box_name="hintmediaBytesSent"}parse(e){this.bytessent=e.readUint64()}},vo.fourcc="dmed",vo),bo,a4=(bo=class extends ae{constructor(){super(...arguments),this.box_name="OpusSpecificBox"}parse(e){if(this.Version=e.readUint8(),this.OutputChannelCount=e.readUint8(),this.PreSkip=e.readUint16(),this.InputSampleRate=e.readUint32(),this.OutputGain=e.readInt16(),this.ChannelMappingFamily=e.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=e.readUint8(),this.CoupledCount=e.readUint8(),this.ChannelMapping=[];for(let s=0;sn.segment_duration>rt||n.media_time>rt)||this.version===1;this.version=s?1:0,this.size=4+12*this.entries.length,this.size+=s?2*4*this.entries.length:0,this.writeHeader(e),e.writeUint32(this.entries.length);for(let n=0;n>7,this.axis=s&1}},$o.fourcc="imir",$o),Wo,B4=(Wo=class extends J{constructor(){super(...arguments),this.box_name="ItemPropertyAssociationBox"}parse(e){this.parseFullHeader(e);const s=e.readUint32();this.associations=[];for(let n=0;n>7===1,property_index:this.flags&1?(c&127)<<8|e.readUint8():c&127})}this.associations.push({id:r,props:i})}}},Wo.fourcc="ipma",Wo),Go,T4=(Go=class extends ae{constructor(){super(...arguments),this.box_name="ImageRotation"}parse(e){this.angle=e.readUint8()&3}},Go.fourcc="irot",Go),qo,P4=(qo=class extends J{constructor(){super(...arguments),this.box_name="ImageSpatialExtentsProperty"}parse(e){this.parseFullHeader(e),this.image_width=e.readUint32(),this.image_height=e.readUint32()}},qo.fourcc="ispe",qo),Jo,z4=(Jo=class extends J{constructor(){super(...arguments),this.box_name="TAITimestampBox"}parse(e){this.TAI_timestamp=e.readUint64();const s=e.readUint8();this.sychronization_state=s>>7&1,this.timestamp_generation_failure=s>>6&1,this.timestamp_is_modified=s>>5&1}},Jo.fourcc="itai",Jo),Ko,A4=(Ko=class extends J{constructor(){super(...arguments),this.box_name="KindBox"}parse(e){this.parseFullHeader(e),this.schemeURI=e.readCString(),this.isEndOfBox(e)||(this.value=e.readCString())}write(e){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value?this.value.length+1:0),this.writeHeader(e),e.writeCString(this.schemeURI),this.value&&e.writeCString(this.value)}},Ko.fourcc="kind",Ko),Qo,R4=(Qo=class extends J{constructor(){super(...arguments),this.box_name="LevelAssignmentBox"}parse(e){this.parseFullHeader(e);const s=e.readUint8();this.levels=[];for(let n=0;n>7,r.assignment_type=i&127,r.assignment_type){case 0:r.grouping_type=e.readString(4);break;case 1:r.grouping_type=e.readString(4),r.grouping_type_parameter=e.readUint32();break;case 2:break;case 3:break;case 4:r.sub_track_id=e.readUint32();break;default:M.warn("BoxParser",`Unknown level assignment type: ${r.assignment_type}`)}}}},Qo.fourcc="leva",Qo),Yo,F4=(Yo=class extends ae{constructor(){super(...arguments),this.box_name="LHEVCConfigurationBox"}parse(e){this.configurationVersion=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3;let s=e.readUint8();this.numTemporalLayers=(s&13)>>3,this.temporalIdNested=(s&4)>>2,this.lengthSizeMinusOne=s&3,this.nalu_arrays=[];const n=e.readUint8();for(let r=0;r>7,i.nalu_type=s&63;const a=e.readUint16();for(let l=0;l>4,a=r&7;this.padbits.push(new $4(i,a))}}},il.fourcc="padb",il),al,G4=(al=class extends ae{constructor(){super(...arguments),this.box_name="PixelAspectRatioBox"}parse(e){this.hSpacing=e.readUint32(),this.vSpacing=e.readUint32()}},al.fourcc="pasp",al),ol,q4=(ol=class extends ae{constructor(){super(...arguments),this.box_name="CuePayloadBox"}parse(e){this.text=e.readString(this.size-this.hdr_size)}},ol.fourcc="payl",ol),ll,J4=(ll=class extends ae{constructor(){super(...arguments),this.box_name="hintpayloadID"}parse(e){this.payloadID=e.readUint32();const s=e.readUint8();this.rtpmap_string=e.readString(s)}},ll.fourcc="payt",ll),cl,K4=(cl=class extends J{constructor(){super(...arguments),this.box_name="ProgressiveDownloadInfoBox",this.rate=[],this.initial_delay=[]}parse(e){this.parseFullHeader(e);const s=(this.size-this.hdr_size)/8;for(let n=0;n0){const n=e.readUint32();for(let r=0;r0&&(this.protection_data=e.readUint8Array(s))}},ml.fourcc="pssh",ml),xl,sB=(xl=class extends J{constructor(){super(...arguments),this.box_name="TrackCleanApertureDimensionsBox"}parse(e){this.parseFullHeader(e),this.width=e.readUint32(),this.height=e.readUint32()}},xl.fourcc="clef",xl);function nB(t,e){if(t===_u.Types.UTF8)return new TextDecoder("utf-8").decode(e);const s=new DataView(e.buffer);if(t===_u.Types.BE_UNSIGNED_INT){if(e.length===1)return s.getUint8(0);if(e.length===2)return s.getUint16(0,!1);if(e.length===4)return s.getUint32(0,!1);if(e.length===8)return s.getBigUint64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_UNSIGNED_INT length "+e.length)}else if(t===_u.Types.BE_SIGNED_INT){if(e.length===1)return s.getInt8(0);if(e.length===2)return s.getInt16(0,!1);if(e.length===4)return s.getInt32(0,!1);if(e.length===8)return s.getBigInt64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_SIGNED_INT length "+e.length)}else if(t===_u.Types.BE_FLOAT32)return s.getFloat32(0,!1);M.warn("DataBox","Unsupported or unimplemented itif data type: "+t)}var Ln,_u=(Ln=class extends ae{constructor(){super(...arguments),this.box_name="DataBox"}parse(e){this.valueType=e.readUint32(),this.country=e.readUint16(),this.country>255&&(e.seek(e.getPosition()-2),this.countryString=e.readString(2)),this.language=e.readUint16(),this.language>255&&(e.seek(e.getPosition()-2),this.parseLanguage(e)),this.raw=e.readUint8Array(this.size-this.hdr_size-8),this.value=nB(this.valueType,this.raw)}},Ln.fourcc="data",Ln.Types={RESERVED:0,UTF8:1,UTF16:2,SJIS:3,UTF8_SORT:4,UTF16_SORT:5,JPEG:13,PNG:14,BE_SIGNED_INT:21,BE_UNSIGNED_INT:22,BE_FLOAT32:23,BE_FLOAT64:24,BMP:27,QT_ATOM:28,BE_SIGNED_INT8:65,BE_SIGNED_INT16:66,BE_SIGNED_INT32:67,BE_FLOAT32_POINT:70,BE_FLOAT32_DIMENSIONS:71,BE_FLOAT32_RECT:72,BE_SIGNED_INT64:74,BE_UNSIGNED_INT8:75,BE_UNSIGNED_INT16:76,BE_UNSIGNED_INT32:77,BE_UNSIGNED_INT64:78,BE_FLOAT64_AFFINE_TRANSFORM:79},Ln),gl,rB=(gl=class extends J{constructor(){super(...arguments),this.box_name="TrackEncodedPixelsDimensionsBox"}parse(e){this.parseFullHeader(e),this.width=e.readUint32(),this.height=e.readUint32()}},gl.fourcc="enof",gl),yl,iB=(yl=class extends ae{constructor(){super(...arguments),this.box_name="IlstBox"}parse(e){this.list={};let s=this.size-this.hdr_size;for(;s>0;){const n=e.readUint32(),r=e.readUint32(),i=ps(e,!1,n-8);i.code===Dt&&(this.list[r]=i.box),s-=n}}},yl.fourcc="ilst",yl),_l,aB=(_l=class extends J{constructor(){super(...arguments),this.box_name="KeysBox"}parse(e){this.parseFullHeader(e),this.count=e.readUint32(),this.keys={};for(let s=0;s=4;)this.compatible_brands[n]=e.readString(4),s-=4,n++}write(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,void 0,4),e.writeUint32(this.minor_version);for(let s=0;s>4&15,this.sample_sizes[n+1]=r&15}else if(this.field_size===8)for(let n=0;n0)for(let a=0;a>6}},Vl.fourcc="taic",Vl),Hl,TB=(Hl=class extends J{constructor(){super(...arguments),this.box_name="TrackEncryptionBox"}parse(e){if(this.parseFullHeader(e),e.readUint8(),this.version===0)e.readUint8();else{const s=e.readUint8();this.default_crypt_byte_block=s>>4&15,this.default_skip_byte_block=s&15}this.default_isProtected=e.readUint8(),this.default_Per_Sample_IV_Size=e.readUint8(),this.default_KID=$n(e),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=e.readUint8(),this.default_constant_IV=e.readUint8Array(this.default_constant_IV_size))}},Hl.fourcc="tenc",Hl),$l,PB=($l=class extends J{constructor(){super(...arguments),this.box_name="TrackFragmentRandomAccessBox"}parse(e){this.parseFullHeader(e),this.track_ID=e.readUint32(),e.readUint24();const s=e.readUint8();this.length_size_of_traf_num=s>>4&3,this.length_size_of_trun_num=s>>2&3,this.length_size_of_sample_num=s&3,this.entries=[];const n=e.readUint32();for(let r=0;r>7&1,this.block_pad_lsb=s>>6&1,this.block_little_endian=s>>5&1,this.block_reversed=s>>4&1,this.pad_unknown=s>>3&1,this.pixel_size=e.readUint32(),this.row_align_size=e.readUint32(),this.tile_align_size=e.readUint32(),this.num_tile_cols_minus_one=e.readUint32(),this.num_tile_rows_minus_one=e.readUint32()}}}},nc.fourcc="uncC",nc),rc,qB=(rc=class extends J{constructor(){super(...arguments),this.box_name="DataEntryUrnBox"}parse(e){this.parseFullHeader(e),this.name=e.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=e.readCString())}write(e){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(e),e.writeCString(this.name),this.location&&e.writeCString(this.location)}},rc.fourcc="urn ",rc),ic,JB=(ic=class extends ae{constructor(){super(...arguments),this.box_name="WebVTTConfigurationBox"}parse(e){this.text=e.readString(this.size-this.hdr_size)}},ic.fourcc="vttC",ic),ac,KB=(ac=class extends J{constructor(){super(...arguments),this.box_name="VvcNALUConfigBox"}parse(e){this.parseFullHeader(e);const s=e.readUint8();this.lengthSizeMinusOne=s&3}},ac.fourcc="vvnC",ac),oc,QB=(oc=class extends Qe{parse(e){const s=e.readUint16();this.first_output_sample=e.readUint16(),this.sample_offset=[];for(let r=0;r>7,this.avgRateFlag=s>>6&1,this.durationFlag&&(this.duration=e.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()),this.dependency=[];const n=e.readUint8();for(let r=0;r>7,this.num_leading_samples=s&127}},hc.grouping_type="rap ",hc),pc,n6=(pc=class extends Qe{parse(e){if(this.operation_point_count=e.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)M.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=e.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=e.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(let s=0;s>4,this.skip_byte_block=s&15,this.isProtected=e.readUint8(),this.Per_Sample_IV_Size=e.readUint8(),this.KID=$n(e),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=e.readUint8(),this.constant_IV=e.readUint8Array(this.constant_IV_size))}},yc.grouping_type="seig",yc),_c,l6=(_c=class extends Qe{parse(e){M.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},_c.grouping_type="stsa",_c),vc,c6=(vc=class extends Qe{parse(e){const s=e.readUint8();this.NAL_unit_type=s&63}},vc.grouping_type="sync",vc),bc,u6=(bc=class extends Qe{parse(e){const s=e.readUint8();this.level_independently_decodable=s>>7}},bc.grouping_type="tele",bc),wc,d6=(wc=class extends Qe{parse(e){M.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},wc.grouping_type="tsas",wc),Sc,f6=(Sc=class extends Qe{parse(e){M.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Sc.grouping_type="tscl",Sc),kc,h6=(kc=class extends Qe{parse(e){M.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},kc.grouping_type="vipr",kc),Ec,p6=(Ec=class extends ae{},Ec.fourcc="uuid",Ec),Nc,Qc=(Nc=class extends J{},Nc.fourcc="uuid",Nc),jc,m6=(jc=class extends Qc{constructor(){super(...arguments),this.box_name="LiveServerManifestBox"}parse(e){this.parseFullHeader(e),this.LiveServerManifest=e.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}},jc.uuid="a5d40b30e81411ddba2f0800200c9a66",jc),Cc,x6=(Cc=class extends Qc{constructor(){super(...arguments),this.box_name="PiffProtectionSystemSpecificHeaderBox"}parse(e){this.parseFullHeader(e),this.system_id=$n(e);const s=e.readUint32();s>0&&(this.data=e.readUint8Array(s))}},Cc.uuid="d08a4f1810f34a82b6c832d8aba183d3",Cc),Uc,g6=(Uc=class extends Qc{constructor(){super(...arguments),this.box_name="PiffSampleEncryptionBox"}},Uc.uuid="a2394f525a9b4f14a2446c427c648df4",Uc),Bc,y6=(Bc=class extends Qc{constructor(){super(...arguments),this.box_name="PiffTrackEncryptionBox"}parse(e){this.parseFullHeader(e),this.default_AlgorithmID=e.readUint24(),this.default_IV_size=e.readUint8(),this.default_KID=$n(e)}},Bc.uuid="8974dbce7be74c5184f97148f9882554",Bc),Tc,_6=(Tc=class extends Qc{constructor(){super(...arguments),this.box_name="TfrfBox"}parse(e){this.parseFullHeader(e),this.fragment_count=e.readUint8(),this.entries=[];for(let s=0;sr.name===t.class_name),n=e[s];return n!=null&&n.color?n.color:Fp[Math.max(0,s)%Fp.length]}function $h(t,e){const s=Jn(t.cx,t.cy,e),n=t.w*e.w/2,r=t.h*e.h/2;return{x:s.x-n,y:s.y-r,w:t.w*e.w,h:t.h*e.h,cx:s.x,cy:s.y}}function yw(t){const{x:e,y:s,w:n,h:r,cx:i,cy:a}=t;return[{x:e,y:s},{x:e+n,y:s},{x:e+n,y:s+r},{x:e,y:s+r},{x:i,y:s},{x:e+n,y:a},{x:i,y:s+r},{x:e,y:a}]}function z6(t,e){const s=$h(t,e);return{left:s.x,right:s.x+s.w,top:s.y,bottom:s.y+s.h,cx:s.cx,cy:s.cy}}function _w(t,e){const{cx:s,cy:n,w:r,h:i,angle:a=0}=t.points,l=Jn(s,n,e),c=r*e.w/2,u=i*e.h/2,d=Le(a),f=Math.cos(d),h=Math.sin(d);return[[-c,-u],[c,-u],[c,u],[-c,u]].map(([g,v])=>({x:l.x+g*f-v*h,y:l.y+g*h+v*f}))}function vw(t,e=0){const s={x:(t[0].x+t[1].x)/2,y:(t[0].y+t[1].y)/2},n=Le(e);return{x:s.x-Math.sin(n)*Fy,y:s.y-Math.cos(n)*Fy,mid:s}}function bw(t,e){const{cx:s,cy:n,r_inner:r,r_outer:i,angle_start:a,angle_end:l}=t.points,c=Jn(s,n,e),u=Math.min(e.w,e.h);return{sc:c,ri:r*u,ro:i*u,a0:Le(a),a1:Le(l),angle_start:a,angle_end:l,midAngle:(a+l)/2}}function A6(t,e,s,n){const{cx:r,cy:i,r_inner:a,r_outer:l,angle_start:c,angle_end:u}=s.points,d=Jn(r,i,n),f=Math.min(n.w,n.h),h=t-d.x,g=e-d.y,v=Math.sqrt(h*h+g*g),_=a*f,k=l*f;if(v<_||v>k)return!1;let x=Hh(Math.atan2(g,h)),p=c,y=u;for(;yy&&(x-=360),x>=p&&x<=y}function Js(t,e,s,n){return P6(t,e,s,n)<=(vs+4)**2}function R6(t){return!!t&&t!=="body"&&t!=="rot"}function F6(t){return(t==null?void 0:t.currentSrc)||(t==null?void 0:t.src)||""}function L6(t,e,s,n,r){const i=new Set;return e==="c0"&&(i.add("left"),i.add("top")),e==="c1"&&(i.add("right"),i.add("top")),e==="c2"&&(i.add("right"),i.add("bottom")),e==="c3"&&(i.add("left"),i.add("bottom")),e==="e0"&&i.add("top"),e==="e1"&&i.add("right"),e==="e2"&&i.add("bottom"),e==="e3"&&i.add("left"),[{key:"left",orientation:"v",offset:(t.left-s)*r},{key:"right",orientation:"v",offset:(t.right-s)*r},{key:"top",orientation:"h",offset:(t.top-n)*r},{key:"bottom",orientation:"h",offset:(t.bottom-n)*r}].map(a=>({...a,active:i.has(a.key)}))}function I6(t,e,s,n,r,i,a){if(t.shape_type!=="rect"||!R6(e)||!a)return null;const l=F6(n);if(!l)return null;const c=z6(t,s);let u=c.cx,d=c.cy;e==="c0"&&(u=c.left,d=c.top),e==="c1"&&(u=c.right,d=c.top),e==="c2"&&(u=c.right,d=c.bottom),e==="c3"&&(u=c.left,d=c.bottom),e==="e0"&&(u=c.cx,d=c.top),e==="e1"&&(u=c.right,d=c.cy),e==="e2"&&(u=c.cx,d=c.bottom),e==="e3"&&(u=c.left,d=c.cy);const f=Rp*2,h=s.x+Math.max(0,s.w-f),g=s.y+Math.max(0,s.h-f),v=Ly(u-Rp,s.x,h),_=Ly(d-Rp,s.y,g),k=jn/f,x=r+sr+jn<=a.clientWidth,p=i+sr+jn<=a.clientHeight,y=x?r+sr:Math.max(0,r-sr-jn),N=p?i+sr:Math.max(0,i-sr-jn);return{mediaSrc:l,panelLeft:y,panelTop:N,backgroundSize:{width:s.w*k,height:s.h*k},backgroundPosition:{x:(s.x-v)*k,y:(s.y-_)*k},lines:L6(c,e,v,_,k)}}function Hd(t,e,s,n){if(s.shape_type==="rect"){const r=$h(s,n),i=yw(r),a=["c0","c1","c2","c3","e0","e1","e2","e3"];for(let l=0;l=r.x&&t<=r.x+r.w&&e>=r.y&&e<=r.y+r.h?"body":null}if(s.shape_type==="rotated_rect"){const{cx:r,cy:i,w:a,h:l,angle:c=0}=s.points,u=_w(s,n),d=vw(u,c);if(Js(t,e,d.x,d.y))return"rot";for(let y=0;y<4;y++)if(Js(t,e,u[y].x,u[y].y))return`c${y}`;const f=Jn(r,i,n),h=-Le(c),g=Math.cos(h),v=Math.sin(h),_=t-f.x,k=e-f.y,x=_*g-k*v,p=_*v+k*g;return Math.abs(x)<=a*n.w/2&&Math.abs(p)<=l*n.h/2?"body":null}if(s.shape_type==="annular_sector"){const{sc:r,ri:i,ro:a,midAngle:l,angle_start:c,angle_end:u}=bw(s,n),d=(i+a)/2;return Js(t,e,r.x,r.y)?"center":Js(t,e,r.x+i*Math.cos(Le(l)),r.y+i*Math.sin(Le(l)))?"inner":Js(t,e,r.x+a*Math.cos(Le(l)),r.y+a*Math.sin(Le(l)))?"outer":Js(t,e,r.x+d*Math.cos(Le(c)),r.y+d*Math.sin(Le(c)))?"arc_s":Js(t,e,r.x+d*Math.cos(Le(u)),r.y+d*Math.sin(Le(u)))?"arc_e":A6(t,e,s,n)?"body":null}return null}function ih(t,e,s,n){t.fillStyle="#fff",t.strokeStyle=n,t.lineWidth=1.5,t.fillRect(e-vs,s-vs,vs*2,vs*2),t.strokeRect(e-vs,s-vs,vs*2,vs*2)}function Fu(t,e,s,n){t.fillStyle="#fff",t.strokeStyle=n,t.lineWidth=1.5,t.beginPath(),t.arc(e,s,vs,0,Math.PI*2),t.fill(),t.stroke()}function _g(t,e,s,n,r){t.save(),t.font="bold 10px ui-monospace, monospace";const i=t.measureText(e).width;t.fillStyle=r,t.fillRect(s,n-15,i+8,16),t.fillStyle="#fff",t.fillText(e,s+4,n-3),t.restore()}function vg(t,e){const s=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),r=parseInt(t.slice(5,7),16);return`rgba(${s},${n},${r},${e})`}function O6(t,e,s,n,r,i={}){const{dashed:a=!1,fillAlpha:l=.15}=i,c=$h(e,s);t.save(),a&&t.setLineDash([6,4]),t.fillStyle=vg(r,l),t.strokeStyle=r,t.lineWidth=n?2.5:1.5,t.beginPath(),t.rect(c.x,c.y,c.w,c.h),t.fill(),t.stroke(),t.restore();const u=[e.class_name,e.severity].filter(Boolean).join(" · ");_g(t,u,c.x,c.y,r),n&&(t.save(),yw(c).forEach((f,h)=>{h<4?ih(t,f.x,f.y,r):Fu(t,f.x,f.y,r)}),t.restore())}function D6(t,e,s,n,r,i={}){const{dashed:a=!1,fillAlpha:l=.15}=i,c=_w(e,s);t.save(),a&&t.setLineDash([6,4]),t.fillStyle=vg(r,l),t.strokeStyle=r,t.lineWidth=n?2.5:1.5,t.beginPath(),t.moveTo(c[0].x,c[0].y),c.slice(1).forEach(d=>t.lineTo(d.x,d.y)),t.closePath(),t.fill(),t.stroke(),t.restore();const u=[e.class_name,e.severity].filter(Boolean).join(" · ");if(_g(t,u,c[0].x,c[0].y,r),n){const d=vw(c,e.points.angle??0);t.save(),t.setLineDash([4,4]),t.strokeStyle="#a855f7",t.lineWidth=1,t.beginPath(),t.moveTo(d.mid.x,d.mid.y),t.lineTo(d.x,d.y),t.stroke(),t.restore(),c.forEach(f=>ih(t,f.x,f.y,r)),Fu(t,d.x,d.y,"#a855f7")}}function M6(t,e,s,n,r,i={}){const{dashed:a=!1,fillAlpha:l=.15}=i,{sc:c,ri:u,ro:d,a0:f,a1:h,midAngle:g,angle_start:v,angle_end:_}=bw(e,s);t.save(),a&&t.setLineDash([6,4]),t.beginPath(),t.arc(c.x,c.y,d,f,h),t.arc(c.x,c.y,u,h,f,!0),t.closePath(),t.fillStyle=vg(r,l),t.strokeStyle=r,t.lineWidth=n?2.5:1.5,t.fill(),t.stroke(),t.restore();const k=[e.class_name,e.severity].filter(Boolean).join(" · ");if(_g(t,k,c.x+d*Math.cos(Le(g)),c.y+d*Math.sin(Le(g))-18,r),n){const x=(u+d)/2;t.save(),Fu(t,c.x,c.y,r),ih(t,c.x+u*Math.cos(Le(g)),c.y+u*Math.sin(Le(g)),r),ih(t,c.x+d*Math.cos(Le(g)),c.y+d*Math.sin(Le(g)),r),Fu(t,c.x+x*Math.cos(Le(v)),c.y+x*Math.sin(Le(v)),"#f59e0b"),Fu(t,c.x+x*Math.cos(Le(_)),c.y+x*Math.sin(Le(_)),"#f59e0b"),t.restore()}}function Oy(t,e,s,n,r,i={}){e.shape_type==="rect"?O6(t,e,s,n,r,i):e.shape_type==="rotated_rect"?D6(t,e,s,n,r,i):e.shape_type==="annular_sector"&&M6(t,e,s,n,r,i)}function V6(t,e,s){if(t.save(),t.setLineDash([6,4]),t.strokeStyle="#94a3b8",t.fillStyle="rgba(148,163,184,0.12)",t.lineWidth=1.5,e.type==="rect"||e.type==="rotated_rect"){if(e.x2!==void 0){const n=Math.min(e.x1,e.x2),r=Math.min(e.y1,e.y2);t.beginPath(),t.rect(n,r,Math.abs(e.x2-e.x1),Math.abs(e.y2-e.y1)),t.fill(),t.stroke()}}else e.type==="annular_sector"&&(e.r!==void 0&&(t.beginPath(),t.arc(e.cx,e.cy,e.r,0,Math.PI*2),t.stroke(),t.beginPath(),t.arc(e.cx,e.cy,e.r*.6,0,Math.PI*2),t.stroke()),t.setLineDash([]),t.fillStyle="#94a3b8",t.beginPath(),t.arc(e.cx,e.cy,3,0,Math.PI*2),t.fill());t.restore()}function H6(t,e,s,n,r,i){if(e==="body"){const{cx:_,cy:k}=n;return{...t,cx:bt(_+r/s.w),cy:bt(k+i/s.h)}}const a=$h(n,s);let l=a.x,c=a.y,u=a.x+a.w,d=a.y+a.h;e==="c0"?(l+=r,c+=i):e==="c1"?(u+=r,c+=i):e==="c2"?(u+=r,d+=i):e==="c3"?(l+=r,d+=i):e==="e0"?c+=i:e==="e1"?u+=r:e==="e2"?d+=i:e==="e3"&&(l+=r);const f=Math.max(rh*s.w,Math.abs(u-l)),h=Math.max(rh*s.h,Math.abs(d-c)),g=(l+u)/2,v=(c+d)/2;return{...t,cx:bt((g-s.x)/s.w),cy:bt((v-s.y)/s.h),w:f/s.w,h:h/s.h}}function $6(t,e,s,n,r,i){const a=n.points,l=Jn(a.cx,a.cy,s);if(e==="body")return{...t,points:{...a,cx:bt(a.cx+(r-l.x)/s.w),cy:bt(a.cy+(i-l.y)/s.h)}};if(e==="rot"){const p=Hh(Math.atan2(r-l.x,-(i-l.y)));return{...t,points:{...a,angle:p}}}const c=a.angle??0,u=-Le(c),d=Math.cos(u),f=Math.sin(u),h=r-l.x,g=i-l.y,v=h*d-g*f,_=h*f+g*d,k=Math.max(rh,Math.abs(v)*2/s.w),x=Math.max(rh,Math.abs(_)*2/s.h);return{...t,points:{...a,w:k,h:x}}}function W6(t,e,s,n,r,i){const a=n.points,l=Jn(a.cx,a.cy,s),c=Math.min(s.w,s.h);if(e==="body")return{...t,points:{...a,cx:bt(a.cx+(r-l.x)/s.w),cy:bt(a.cy+(i-l.y)/s.h)}};if(e==="center"){const g=vf(r,i,s);return{...t,points:{...a,cx:bt(g.x),cy:bt(g.y)}}}const u=r-l.x,d=i-l.y,f=Math.sqrt(u*u+d*d),h=Hh(Math.atan2(d,u));if(e==="inner"){const g=Math.max(.005,Math.min(a.r_outer*c-2,f)/c);return{...t,points:{...a,r_inner:g}}}if(e==="outer"){const g=Math.max(a.r_inner*c+2,f)/c;return{...t,points:{...a,r_outer:g}}}return e==="arc_s"?{...t,points:{...a,angle_start:h}}:e==="arc_e"?{...t,points:{...a,angle_end:h}}:t}const G6={low:"bg-emerald-900/80 text-emerald-300 border-emerald-700/60",medium:"bg-amber-900/80 text-amber-300 border-amber-700/60",high:"bg-red-900/80 text-red-300 border-red-700/60"},q6="bg-transparent text-slate-400 border-slate-700 hover:text-white hover:border-slate-500";function Dy({ann:t,pos:e,classes:s,onApprove:n,onDelete:r,onClassChange:i,onSeverityChange:a}){const l=e.top>52;return o.jsxs("div",{className:`absolute z-20 flex items-center gap-1 px-2 py-1.5 rounded-lg\r bg-slate-900/95 border border-slate-700/60 shadow-2xl text-xs select-none\r backdrop-blur-sm pointer-events-auto`,style:{left:e.centerX,transform:"translateX(-50%)",...l?{top:e.top-46}:{top:e.bottom+6}},onMouseDown:c=>c.stopPropagation(),children:[o.jsx("select",{value:t.class_name??"",onChange:c=>i(c.target.value),className:`bg-slate-800 border border-slate-700 rounded text-[10px] text-slate-200\r px-1.5 py-0.5 max-w-[90px] cursor-pointer hover:border-slate-500 transition`,children:s.length===0?o.jsx("option",{value:t.class_name,children:t.class_name}):s.map(c=>o.jsx("option",{value:c.name,children:c.display_name??c.name},c.name))}),o.jsx("div",{className:"w-px h-4 bg-slate-700 mx-0.5 shrink-0"}),o.jsx("span",{className:"text-[9px] text-slate-500 shrink-0",children:"Sev:"}),["low","medium","high"].map(c=>o.jsx("button",{onClick:()=>a(c),className:`px-1.5 py-0.5 rounded border text-[10px] capitalize transition ${t.severity===c?G6[c]:q6}`,children:c[0].toUpperCase()},c)),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"w-px h-4 bg-slate-700 mx-0.5 shrink-0"}),o.jsx("button",{onClick:n,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium\r bg-violet-700 hover:bg-violet-600 text-white transition shrink-0`,children:"✓ Approve"})]}),o.jsx("div",{className:"w-px h-4 bg-slate-700 mx-0.5 shrink-0"}),o.jsx("button",{onClick:r,className:"text-red-400 hover:text-red-300 transition px-1 shrink-0",title:"Delete",children:"✕"})]})}function J6({magnifier:t}){return t?o.jsxs("div",{className:"absolute z-30 pointer-events-none overflow-hidden rounded-xl border border-slate-600/80 shadow-2xl",style:{left:t.panelLeft,top:t.panelTop,width:jn,height:jn,backgroundColor:"#020617"},children:[o.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url("${t.mediaSrc}")`,backgroundRepeat:"no-repeat",backgroundSize:`${t.backgroundSize.width}px ${t.backgroundSize.height}px`,backgroundPosition:`${t.backgroundPosition.x}px ${t.backgroundPosition.y}px`}}),o.jsx("div",{className:"absolute inset-0 bg-slate-950/10"}),t.lines.map(e=>o.jsx("div",{className:"absolute",style:e.orientation==="v"?{left:e.offset,top:0,bottom:0,width:e.active?2:1,backgroundColor:e.active?"#f8fafc":"rgba(148, 163, 184, 0.8)",boxShadow:e.active?"0 0 0 1px rgba(15, 23, 42, 0.7)":"none"}:{top:e.offset,left:0,right:0,height:e.active?2:1,backgroundColor:e.active?"#f8fafc":"rgba(148, 163, 184, 0.8)",boxShadow:e.active?"0 0 0 1px rgba(15, 23, 42, 0.7)":"none"}},e.key)),o.jsx("div",{className:"absolute left-2 top-2 rounded bg-slate-950/80 px-1.5 py-0.5 text-[10px] font-medium text-slate-100",children:"2x"})]}):null}function ww({containerRef:t,videoRef:e,tool:s,annotations:n,modelAnnotations:r=[],selectedIdx:i,selectedModelIdx:a=null,classes:l,disabled:c,onAdd:u,onChange:d,onDelete:f,onSelect:h,onModelSelect:g,onModelChange:v,onModelDelete:_,onModelApprove:k}){const x=m.useRef(null),p=m.useRef(null),y=m.useRef(null),N=m.useRef(null),[j,w]=m.useState(null),[B,T]=m.useState(null),O=m.useCallback(()=>{const U=t.current,z=e.current;if(!U||!z)return;const G=T6(U,z);p.current=G,w(G)},[t,e]);m.useEffect(()=>{O();const U=new ResizeObserver(O);return t.current&&U.observe(t.current),()=>U.disconnect()},[O]),m.useEffect(()=>{const U=e.current;if(!U)return;const z=()=>O();return U.addEventListener("loadedmetadata",z),U.addEventListener("load",z),()=>{U.removeEventListener("loadedmetadata",z),U.removeEventListener("load",z)}},[e,O]);const C=m.useCallback(()=>{const U=x.current;if(!U)return;const z=p.current,G=window.devicePixelRatio||1,te=U.clientWidth,Z=U.clientHeight;(U.width!==Math.round(te*G)||U.height!==Math.round(Z*G))&&(U.width=Math.round(te*G),U.height=Math.round(Z*G));const K=U.getContext("2d");if(K.save(),K.scale(G,G),K.clearRect(0,0,te,Z),z){K.save(),K.strokeStyle="rgba(100,116,139,0.3)",K.lineWidth=1,K.strokeRect(z.x,z.y,z.w,z.h),K.restore(),r.forEach((ee,re)=>{const ie=re===a;Oy(K,ee,z,ie,Iy(ee,l),{dashed:!0,fillAlpha:ie?.14:.06})}),n.forEach((ee,re)=>{const ie=re===i,ge=ee.is_ai_suggestion;Oy(K,ee,z,ie,Iy(ee,l),ge?{dashed:!0,fillAlpha:ie?.14:.06}:{})});const $=y.current;$&&V6(K,$)}K.restore()},[n,r,i,a,l]);m.useEffect(()=>{C()},[C]);function q(U){const z=x.current.getBoundingClientRect();return{x:U.clientX-z.left,y:U.clientY-z.top}}function V(){return c?"default":N.current?"grabbing":s?"crosshair":"default"}function I(U){if(U.button!==0)return;O();const z=p.current;if(!z)return;const{x:G,y:te}=q(U);for(let Z=n.length-1;Z>=0;Z--){const K=Hd(G,te,n[Z],z);if(K){h(Z),g==null||g(null),c||(N.current={annIdx:Z,handle:K,startX:G,startY:te,origAnn:JSON.parse(JSON.stringify(n[Z])),isModel:!1});return}}for(let Z=r.length-1;Z>=0;Z--){const K=Hd(G,te,r[Z],z);if(K){g==null||g(Z),h(null),N.current={annIdx:Z,handle:K,startX:G,startY:te,origAnn:JSON.parse(JSON.stringify(r[Z])),isModel:!0};return}}h(null),g==null||g(null),!(c||!s)&&(s==="rect"||s==="rotated_rect"?y.current={type:s,x1:G,y1:te}:s==="annular_sector"&&(y.current={type:"annular_sector",cx:G,cy:te}))}function ne(U){const z=p.current;if(!z)return;const{x:G,y:te}=q(U),Z=N.current;if(Z){x.current.style.cursor="grabbing";const $=G-Z.startX,ee=te-Z.startY,re=Z.isModel?r:n,ie=re[Z.annIdx];let ge;ie.shape_type==="rect"?ge=H6(ie,Z.handle,z,Z.origAnn,$,ee):ie.shape_type==="rotated_rect"?ge=$6(ie,Z.handle,z,Z.origAnn,G,te):ie.shape_type==="annular_sector"&&(ge=W6(ie,Z.handle,z,Z.origAnn,G,te)),ge&&(re[Z.annIdx]=ge,T(I6(ge,Z.handle,z,e.current,G,te,t.current)),C());return}const K=y.current;if(!K){const $=x.current;if(!c){let ee=!1;for(let re=n.length-1;re>=0&&!ee;re--)Hd(G,te,n[re],z)&&(ee=!0);for(let re=r.length-1;re>=0&&!ee;re--)Hd(G,te,r[re],z)&&(ee=!0);$.style.cursor=ee?"grab":s?"crosshair":"default"}return}if(K.type==="rect"||K.type==="rotated_rect")y.current={...K,x2:G,y2:te};else if(K.type==="annular_sector"){const $=G-K.cx,ee=te-K.cy,re=Math.sqrt($*$+ee*ee);y.current={...K,r:re,angle:Hh(Math.atan2(ee,$))}}C()}function X(U){if(U.button!==0)return;const z=p.current;if(!z)return;const{x:G,y:te}=q(U),Z=N.current;if(Z){const re=(Z.isModel?r:n)[Z.annIdx];Z.isModel?v==null||v(Z.annIdx,re):d(Z.annIdx,re),N.current=null,T(null),C();return}const K=y.current;if(y.current=null,!K)return;const $=Math.min(z.w,z.h);if(K.type==="rect"){const ee=K.x2??G,re=K.y2??te,ie=Math.abs(ee-K.x1),ge=Math.abs(re-K.y1);if(ie<5||ge<5){C();return}const We=Math.min(K.x1,ee),Ye=Math.min(K.y1,re),Ue=vf(We+ie/2,Ye+ge/2,z);u({shape_type:"rect",cx:bt(Ue.x),cy:bt(Ue.y),w:ie/z.w,h:ge/z.h})}if(K.type==="rotated_rect"){const ee=K.x2??G,re=K.y2??te,ie=Math.abs(ee-K.x1),ge=Math.abs(re-K.y1);if(ie<5||ge<5){C();return}const We=Math.min(K.x1,ee),Ye=Math.min(K.y1,re),Ue=vf(We+ie/2,Ye+ge/2,z);u({shape_type:"rotated_rect",points:{cx:bt(Ue.x),cy:bt(Ue.y),w:ie/z.w,h:ge/z.h,angle:0}})}if(K.type==="annular_sector"){if(!K.r||K.r<5){C();return}const ee=K.r/$,re=ee*.5,ie=K.angle??0,ge=vf(K.cx,K.cy,z);u({shape_type:"annular_sector",points:{cx:bt(ge.x),cy:bt(ge.y),r_inner:re,r_outer:ee,angle_start:ie-30,angle_end:ie+30}})}C()}m.useEffect(()=>{const U=z=>{["INPUT","TEXTAREA"].includes(z.target.tagName)||((z.key==="Delete"||z.key==="Backspace")&&(i!==null?f(i):a!==null&&(_==null||_(a))),z.key==="Escape"&&(y.current=null,N.current=null,T(null),C()))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[i,a,f,_,C]);function pe(U,z){if(!U||!z||U.shape_type!=="rect")return null;const G=(U.cx-U.w/2)*z.w+z.x,te=(U.cy-U.h/2)*z.h+z.y,Z=(U.cx+U.w/2)*z.w+z.x,K=(U.cy+U.h/2)*z.h+z.y;return{centerX:(G+Z)/2,top:te,bottom:K}}const D=m.useMemo(()=>pe(r[a],j),[a,r,j]),R=m.useMemo(()=>pe(n[i],j),[i,n,j]);return o.jsxs(o.Fragment,{children:[o.jsx("canvas",{ref:x,className:"absolute inset-0 w-full h-full",style:{cursor:V(),touchAction:"none"},onMouseDown:I,onMouseMove:ne,onMouseUp:X,onMouseLeave:()=>{y.current&&(y.current=null,C()),N.current&&(N.current=null),T(null)}}),o.jsx(J6,{magnifier:B}),D&&a!==null&&r[a]&&o.jsx(Dy,{ann:r[a],pos:D,classes:l,onApprove:()=>k==null?void 0:k(a),onDelete:()=>_==null?void 0:_(a),onClassChange:U=>v==null?void 0:v(a,{...r[a],class_name:U}),onSeverityChange:U=>v==null?void 0:v(a,{...r[a],severity:U})}),R&&i!==null&&n[i]&&o.jsx(Dy,{ann:n[i],pos:R,classes:l,onDelete:()=>f(i),onClassChange:U=>d(i,{...n[i],class_name:U}),onSeverityChange:U=>d(i,{...n[i],severity:U})})]})}const K6=S6,My=typeof HTMLVideoElement<"u"&&"requestVideoFrameCallback"in HTMLVideoElement.prototype;async function Q6(t){return new Promise((e,s)=>{const n=K6.createFile();n.onReady=r=>{var c;const i=(c=r.videoTracks)==null?void 0:c[0];if(!i){s(new Error("No video track"));return}const a=i.nb_samples*i.timescale/i.duration,l=i.nb_samples;e({fps:a,frameCount:l})},n.onError=r=>s(new Error(String(r))),fetch(t,{headers:{Range:"bytes=0-1048575"}}).then(r=>r.arrayBuffer()).then(r=>{r.fileStart=0,n.appendBuffer(r),n.flush()}).catch(s)})}function Lp(t){if(!t||isNaN(t))return"0:00";const e=Math.floor(t/60),s=Math.floor(t%60);return`${e}:${String(s).padStart(2,"0")}`}function Y6(t){return t?t.split("/").pop()||t:"--"}function X6(t,e){if(t==null)return"--";const s=Number(t.toFixed(5)).toString(),n={mp4box:"MP4",rvfc:"live",db:"DB",default:"est."}[e]??"";return n?`${s} (${n})`:s}function Z6(t){return t==="mp4box"||t==="rvfc"?"text-emerald-400":t==="db"?"text-amber-400":t==="probing"?"text-slate-500":"text-slate-400"}const $d={low:"bg-emerald-900/60 text-emerald-300",medium:"bg-amber-900/60 text-amber-300",high:"bg-red-900/60 text-red-300"},eT={damage_deformed:"deformation",damage_peeling:"peeling",damage_scratch:"scratch",contamination_dirt:"dirt",contamination_fluid:"fluid"},tT=.05;function Sw(t){return[...t].sort((e,s)=>e.timestamp_seconds-s.timestamp_seconds)}function sT(t,e){return t.find(s=>Math.abs(s.timestamp_seconds-e)<=tT)??null}function Vy(t,e){const s=t.filter(n=>n.id!==e.id);return Sw([...s,e])}const kw={pending:{label:"Pending",cls:"bg-slate-700 text-slate-300"},in_progress:{label:"In Progress",cls:"bg-blue-900/60 text-blue-300"},submitted:{label:"Submitted",cls:"bg-amber-900/60 text-amber-300"},reviewed:{label:"Reviewed",cls:"bg-green-900/60 text-green-300"}},Hy=["pending","in_progress","submitted","reviewed"];function $y({status:t}){const e=kw[t]??{label:t,cls:"bg-slate-700 text-slate-300"};return o.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${e.cls}`,children:e.label})}function Ip({title:t,children:e}){return o.jsxs("div",{children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-2",children:t}),o.jsx("div",{className:"space-y-1.5",children:e})]})}function Ps({label:t,value:e,valueClass:s=""}){return o.jsxs("div",{className:"flex justify-between items-start gap-2",children:[o.jsx("span",{className:"text-xs text-slate-500 shrink-0",children:t}),o.jsx("span",{className:`text-xs text-right break-all ${s||"text-slate-300"}`,children:e??"--"})]})}function zs({onClick:t,title:e,disabled:s,children:n,primary:r,active:i}){return o.jsx("button",{onClick:t,disabled:s,title:e,className:`flex items-center justify-center w-8 h-8 rounded-lg transition disabled:opacity-30 ${r?"bg-brand-600 hover:bg-brand-500 text-white":i?"bg-slate-600 text-white":"text-slate-400 hover:text-white hover:bg-slate-700"}`,children:n})}function nT({job:t,onBack:e,onJobUpdated:s}){var Cg,Ug,Bg;const{user:n}=wn(),r=Ih(n),[i,a]=m.useState(null),[l,c]=m.useState(""),[u,d]=m.useState(null),[f,h]=m.useState(!1),[g,v]=m.useState(0),[_,k]=m.useState(0),[x,p]=m.useState(!1),[y,N]=m.useState(!1),[j,w]=m.useState(null),[B,T]=m.useState("probing"),[O,C]=m.useState(null),[q,V]=m.useState("rect"),[I,ne]=m.useState([]),[X,pe]=m.useState(null),[D,R]=m.useState([]),[U,z]=m.useState([]),[G,te]=m.useState([]),[Z,K]=m.useState(null),[$,ee]=m.useState([]),[re,ie]=m.useState(!1),[ge,We]=m.useState(t.status),[Ye,Ue]=m.useState(!1),[Pt,Ge]=m.useState(""),[ut,Et]=m.useState(""),[ms,tt]=m.useState(""),[xs,Us]=m.useState(!0),[se,me]=m.useState(!1),[Se,Ne]=m.useState(""),[b,S]=m.useState(null),E=m.useRef(null),F=m.useRef(null),L=m.useRef(null),W=m.useRef(null),Q=m.useRef([]),le=m.useRef(null),he=m.useRef(!1),Be=m.useRef(0),xt=m.useRef(null),it=j??(u==null?void 0:u.fps)??25,gs=Math.max(1,Math.floor(g*it)+1),Kn=O??(_?Math.floor(_*it):null),Qn=_?g/_*100:0,gd=(u==null?void 0:u.filename)??Y6(t.video_gcs_path),yd=JSON.stringify(D)!==JSON.stringify(G),Yc=!f&&!!i,Mt=((Cg=D[0])==null?void 0:Cg.shape_type)??((Ug=G[0])==null?void 0:Ug.shape_type)??null,bg=(n==null?void 0:n.labelling_role)??null,Nw=bg==="reviewer"||bg==="admin"||(n==null?void 0:n.user_type)==="system-admin"||(n==null?void 0:n.user_type)==="network-admin"?Hy:["in_progress","submitted"];m.useEffect(()=>{We(t.status),Ge(""),a(null),c(""),d(null),w(null),T("probing"),v(0),k(0),pe(null),R([]),z([]),te([]),K(null),S(null),ee([]),Et(""),tt(""),me(!1),Ne(""),fg(t.video_id,t.video_source).then(({signed_url:A})=>a(A)).catch(()=>c("Could not load video URL.")),h3(t.video_id,t.video_source).then(d).catch(()=>{}),yg(t.id).then(A=>ee(Sw(A))).catch(()=>Et("Could not load saved frames from the database.")),Vh().then(ne).catch(()=>{})},[t.id,t.video_id,t.video_source]);async function jw(A){if(!(!A||A===ge)){Ge(""),Ue(!0);try{const H=await Zf(t.id,{status:A});We(H.status),s==null||s(H)}catch(H){Ge((H==null?void 0:H.detail)??(H==null?void 0:H.message)??"Could not update job status."),We(t.status)}finally{Ue(!1)}}}m.useEffect(()=>{if(!i)return;let A=!1;return Q6(i).then(({fps:H,frameCount:fe})=>{A||(w(H),T("mp4box"),C(fe))}).catch(()=>{if(A)return;const H=u==null?void 0:u.fps;H&&H>1?(w(H),T("db")):(w(25),T("default"))}),()=>{A=!0}},[i]);const _d=m.useCallback(()=>{const A=E.current;A&&W.current!=null&&(A.cancelVideoFrameCallback(W.current),W.current=null)},[]),Cw=m.useCallback(()=>{const A=E.current;if(!A||!My)return;Q.current=[];let H=null;const fe=(ce,ye)=>{const xe=Q.current;if(xe.push(ye.mediaTime),xe.length>30&&xe.shift(),xe.length>=10){let ss=0;for(let tu=1;tu5&&Bs<120&&(H===null||Math.abs(Bs-H)>.5)&&(H=Bs,w(Bs),T("rvfc"))}!A.paused&&!A.ended?W.current=A.requestVideoFrameCallback(fe):W.current=null};W.current=A.requestVideoFrameCallback(fe)},[]);m.useEffect(()=>()=>_d(),[_d]);function Uw(){pe(null),R([]),z([]),te([]),K(null),S(null),xt.current=null}async function wg({allowEmpty:A=!1}={}){if(!X)return null;if(!A&&D.length===0)return!1;const fe={...await xw(t.id,{timestamp_seconds:X.timestamp_seconds,annotations:D,mark_empty:D.length===0,tube_type:xt.current??void 0}),annotation_count:D.length},ce=Vy($,fe);return ee(ce),pe(fe),te(JSON.parse(JSON.stringify(D))),fe}async function Xc(A,{saveEmpty:H=!1}={}){const fe=D.length>0||H;try{fe?(await wg({allowEmpty:H}),tt(D.length>0?"Draft saved to the database.":"Empty frame saved to the database.")):tt(""),Uw(),A()}catch(ce){Et((ce==null?void 0:ce.message)??"Could not save draft to the database.")}}function Wh(A){Mt&&Mt!==A||V(A)}const Gh=m.useCallback(()=>{const A=E.current;A&&Xc(()=>{A.paused?A.play():A.pause()})},[D.length,X,$,t.id,G]),vd=m.useCallback(A=>{const H=E.current;!H||he.current||(he.current=!0,N(!0),Xc(()=>{H.pause();const fe=Math.round(H.currentTime*it),ce=Math.max(0,Math.min(H.duration||0,(fe+A)/it));H.currentTime=ce,My?(le.current!=null&&H.cancelVideoFrameCallback(le.current),le.current=H.requestVideoFrameCallback((ye,xe)=>{v(xe.mediaTime),Yn(xe.mediaTime),he.current=!1,N(!1),le.current=null})):(v(ce),Yn(ce),he.current=!1,N(!1))}).then(()=>{he.current&&le.current==null&&(he.current=!1,N(!1))}))},[D.length,X,it,$,t.id,G]),qh=m.useCallback(()=>vd(1),[vd]),Jh=m.useCallback(()=>vd(-1),[vd]),Zc=m.useCallback(A=>{const H=E.current;H&&Xc(()=>{H.currentTime=Math.max(0,Math.min(H.duration||0,H.currentTime+A))})},[D.length,X,$,t.id,G]),kn=m.useCallback(async(A,H)=>{try{const fe=await nh(A,{status:H});ee(ce=>Vy(ce,fe)),pe(ce=>(ce==null?void 0:ce.id)===A?fe:ce)}catch(fe){console.error("Failed to update frame status",fe)}},[]);m.useEffect(()=>{const A=H=>{if(!["INPUT","TEXTAREA"].includes(H.target.tagName)){if(H.key==="Escape"){e();return}if(H.key===" "){H.preventDefault(),Gh();return}if(H.key==="ArrowLeft"){H.preventDefault(),H.shiftKey?Zc(-1):Jh();return}if(H.key==="ArrowRight"){H.preventDefault(),H.shiftKey?Zc(1):qh();return}H.key==="r"&&V("rect"),H.key==="o"&&V("rotated_rect"),H.key==="a"&&V("annular_sector")}};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[e,Gh,Jh,qh,Zc]);const eu=m.useRef(null);eu.current=Sg,m.useEffect(()=>{if(!r)return;const A=H=>{if(["INPUT","TEXTAREA"].includes(H.target.tagName)||!$.length)return;const fe=$.findIndex(ce=>ce.id===(X==null?void 0:X.id));if(H.key==="["){H.preventDefault(),fe>0&&eu.current($[fe-1]);return}if(H.key==="]"){H.preventDefault(),fe<$.length-1&&eu.current($[fe+1]);return}if((H.key==="y"||H.key==="Y")&&X){H.preventDefault();const ce=$.find((ye,xe)=>xe>fe&&ye.status!=="approved"&&ye.status!=="rejected")??$.find(ye=>ye.id!==X.id&&ye.status!=="approved"&&ye.status!=="rejected");kn(X.id,"approved"),ce&&eu.current(ce);return}if((H.key==="n"||H.key==="N")&&X){H.preventDefault();const ce=$.find((ye,xe)=>xe>fe&&ye.status!=="approved"&&ye.status!=="rejected")??$.find(ye=>ye.id!==X.id&&ye.status!=="approved"&&ye.status!=="rejected");kn(X.id,"rejected"),ce&&eu.current(ce);return}};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[r,X,$,kn]);const Kh=m.useCallback(A=>{const H=L.current;if(!H||!_)return;const{left:fe,width:ce}=H.getBoundingClientRect(),ye=Math.max(0,Math.min(1,(A-fe)/ce));E.current&&(E.current.currentTime=ye*_)},[_]);m.useEffect(()=>{if(!x)return;const A=fe=>Kh(fe.clientX),H=()=>{var fe;p(!1),(fe=E.current)!=null&&fe.paused&&Yn(E.current.currentTime)};return window.addEventListener("mousemove",A),window.addEventListener("mouseup",H),()=>{window.removeEventListener("mousemove",A),window.removeEventListener("mouseup",H)}},[x,Kh]);function Yn(A){const H=++Be.current,fe=sT($,A);if(!fe){pe({id:null,timestamp_seconds:A,annotation_count:0,status:"pending"}),R([]),z([]),te([]),K(null),S(null),Et(""),tt("Working on an unsaved frame. Save to store it in the database."),kg();return}pe(fe),R([]),z([]),te([]),K(null),S(null),Et(""),tt("Loading saved frame..."),gw(fe.id).then(ce=>{if(Be.current!==H)return;const ye=ce.filter(ss=>!ss.is_ai_suggestion),xe=ce.filter(ss=>ss.is_ai_suggestion);R(JSON.parse(JSON.stringify(ye))),z(JSON.parse(JSON.stringify(xe))),te(JSON.parse(JSON.stringify(ye))),tt("Loaded saved frame from the database.")}).catch(()=>{Be.current===H&&Et("Could not load annotations for this frame.")})}async function Bw(){if(!(!X||re)){Et(""),ie(!0);try{await wg({allowEmpty:!0}),tt(D.length>0?"Draft saved to the database.":"Empty frame saved to the database.")}catch(A){Et((A==null?void 0:A.message)??"Could not save draft to the database.")}finally{ie(!1)}}}function Sg(A){Xc(()=>{E.current&&(E.current.currentTime=A.timestamp_seconds),Yn(A.timestamp_seconds)})}const kg=m.useCallback(async()=>{const A=E.current;if(!A||A.readyState<2||A.videoWidth===0)return;const H=document.createElement("canvas");H.width=A.videoWidth,H.height=A.videoHeight,H.getContext("2d").drawImage(A,0,0);const fe=H.toDataURL("image/jpeg",.92).split(",")[1];me(!0),Ne(""),z([]);try{const ce=await B6(fe),ye=(ce.predictions??[]).map(xe=>({id:null,shape_type:"rect",cx:xe.cx,cy:xe.cy,w:xe.w,h:xe.h,class_name:eT[xe.class_name]??xe.class_name,severity:"low",confidence:xe.confidence,is_ai_suggestion:!0}));if(z(ye),ce.tube_type){xt.current=ce.tube_type;const xe=X==null?void 0:X.id;xe&&nh(xe,{tube_type:ce.tube_type}).catch(()=>{})}}catch(ce){const ye=(ce==null?void 0:ce.detail)??(ce==null?void 0:ce.message)??"AI inference failed.";String(ye).includes("not configured")||Ne(ye)}finally{me(!1)}},[]);function Tw(A){var xe,ss;X||Yn(g);const H=((xe=D[0])==null?void 0:xe.shape_type)??((ss=G[0])==null?void 0:ss.shape_type)??null;if(H&&H!==A.shape_type){tt(`This frame is locked to ${H}.`);return}const fe=I[0],ce={id:null,...A,class_name:(fe==null?void 0:fe.name)??"deformation",severity:"low"},ye=[...D,ce];R(ye),K(ye.length-1),tt("Unsaved changes. Save this frame to keep the draft.")}function Qh(A,H){R(fe=>fe.map((ce,ye)=>ye===A?H:ce)),tt("Unsaved changes. Save this frame to keep the draft.")}function Eg(A){R(H=>H.filter((fe,ce)=>ce!==A)),K(null),tt("Unsaved changes. Save this frame to keep the draft.")}function Yh(A,H){z(fe=>fe.map((ce,ye)=>ye===A?H:ce))}function Ng(A){const H=U[A],{is_ai_suggestion:fe,confidence:ce,...ye}=H,xe=I[0],ss={...ye,id:null,class_name:ye.class_name??(xe==null?void 0:xe.name)??"deformation",severity:ye.severity??"low"};R(Bs=>[...Bs,ss]),z(Bs=>Bs.filter((tu,Pw)=>Pw!==A)),S(null),tt("Unsaved changes. Save this frame to keep the draft.")}function jg(A){z(H=>H.filter((fe,ce)=>ce!==A)),S(H=>H===null||H===A?null:H>A?H-1:H)}const Gs=Z!==null?D[Z]:null;return b!==null&&U[b],o.jsxs("div",{className:"flex flex-col h-full bg-slate-900 text-white overflow-hidden",children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 bg-slate-800 border-b border-slate-700/60 shrink-0",children:[o.jsxs("button",{onClick:e,className:`flex items-center gap-1.5 text-slate-400 hover:text-white text-xs transition px-2 py-1 rounded-lg hover:bg-slate-700 shrink-0`,children:[o.jsx(dg,{size:14})," Jobs"]}),o.jsx("span",{className:"text-slate-600",children:"·"}),o.jsx("h2",{className:"text-sm font-medium text-slate-200 truncate max-w-xs",title:gd,children:gd}),o.jsx($y,{status:ge}),o.jsxs("div",{className:"ml-auto flex items-center gap-2 shrink-0",children:[o.jsx("label",{className:"text-[10px] uppercase tracking-widest text-slate-500",children:"Status"}),o.jsx("select",{value:ge,onChange:A=>{We(A.target.value),jw(A.target.value)},disabled:Ye,className:"text-xs bg-slate-700 border border-slate-600 rounded px-2 py-1 text-slate-200 disabled:opacity-50",children:Hy.map(A=>{var H;return o.jsx("option",{value:A,disabled:!Nw.includes(A),children:((H=kw[A])==null?void 0:H.label)??A},A)})}),o.jsxs("span",{className:"text-xs text-slate-500",children:["Job #",t.id]})]})]}),o.jsxs("div",{className:"flex flex-1 min-h-0",children:[o.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[o.jsxs("div",{ref:F,className:"relative flex-1 bg-black min-h-0",children:[!i&&!l&&o.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 text-slate-400",children:[o.jsx(Ce,{className:"animate-spin",size:28}),o.jsx("span",{className:"text-sm",children:"Loading video…"})]}),l&&o.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:o.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm px-8 text-center",children:[o.jsx(lt,{size:16,className:"shrink-0"})," ",l]})}),i&&o.jsx("video",{ref:E,src:i,crossOrigin:"anonymous",className:"absolute inset-0 w-full h-full object-contain",onTimeUpdate:()=>{var A;return v(((A=E.current)==null?void 0:A.currentTime)??0)},onLoadedMetadata:()=>{var A;return k(((A=E.current)==null?void 0:A.duration)??0)},onPlay:()=>{h(!0),Cw()},onPause:A=>{h(!1),_d(),x||Yn(A.target.currentTime)},onEnded:()=>{h(!1),_d()}}),i&&o.jsx(ww,{containerRef:F,videoRef:E,tool:Yc?q:null,annotations:D,modelAnnotations:U,selectedIdx:Z,selectedModelIdx:b,classes:I,disabled:!Yc,onAdd:Tw,onChange:Qh,onDelete:Eg,onSelect:K,onModelSelect:S,onModelChange:Yh,onModelDelete:jg,onModelApprove:Ng})]}),o.jsxs("div",{className:"px-4 py-3 bg-slate-800 border-t border-slate-700/60 space-y-2.5 shrink-0",children:[o.jsxs("div",{ref:L,className:"relative h-1.5 bg-slate-700 rounded-full cursor-pointer group",onMouseDown:A=>{A.preventDefault(),Xc(()=>{p(!0),Kh(A.clientX)})},children:[o.jsx("div",{className:"absolute left-0 top-0 h-full bg-brand-500 rounded-full pointer-events-none",style:{width:`${Qn}%`}}),$.map(A=>o.jsx("div",{className:"absolute top-0 w-0.5 h-full bg-amber-400 pointer-events-none opacity-80",style:{left:`${A.timestamp_seconds/(_||1)*100}%`}},A.id)),o.jsx("div",{className:`absolute top-1/2 -translate-y-1/2 w-3 h-3 bg-white rounded-full shadow pointer-events-none transition-opacity ${x?"opacity-100":"opacity-0 group-hover:opacity-100"}`,style:{left:`calc(${Qn}% - 6px)`}})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[o.jsx(zs,{onClick:Jh,disabled:!i||y,title:"Prev frame ArrowLeft",children:o.jsx(Lh,{size:16})}),o.jsx(zs,{onClick:()=>Zc(-1),disabled:!i,title:"Back 1 s Shift+ArrowLeft",children:o.jsx(n3,{size:16})}),o.jsx(zs,{onClick:Gh,disabled:!i,title:"Play / Pause Space",primary:!0,children:f?o.jsx(ug,{size:16}):o.jsx(cg,{size:16})}),o.jsx(zs,{onClick:()=>Zc(1),disabled:!i,title:"Forward 1 s Shift+ArrowRight",children:o.jsx(s3,{size:16})}),o.jsx(zs,{onClick:qh,disabled:!i||y,title:"Next frame ArrowRight",children:o.jsx(Fh,{size:16})}),o.jsxs("span",{className:"text-slate-400 text-xs tabular-nums ml-2 select-none",children:[Lp(g),o.jsx("span",{className:"text-slate-600",children:" / "}),Lp(_)]}),!f&&o.jsxs("div",{className:"flex items-center gap-1 ml-3 border-l border-slate-700 pl-3",children:[o.jsx(zs,{onClick:()=>Wh("rect"),title:"Rect tool R",active:q==="rect",disabled:!!Mt&&Mt!=="rect",children:o.jsx(lg,{size:14})}),o.jsx(zs,{onClick:()=>Wh("rotated_rect"),title:"Rotated rect O",active:q==="rotated_rect",disabled:!!Mt&&Mt!=="rotated_rect",children:o.jsx(ub,{size:14})}),o.jsx(zs,{onClick:()=>Wh("annular_sector"),title:"Annular sector A",active:q==="annular_sector",disabled:!!Mt&&Mt!=="annular_sector",children:o.jsx(xb,{size:14})})]}),o.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[se&&o.jsxs("span",{className:"flex items-center gap-1 text-xs text-violet-400",children:[o.jsx(Ce,{className:"animate-spin",size:11})," AI running…"]}),Se&&!se&&o.jsxs("span",{className:"flex items-center gap-1 text-xs text-red-400",children:[o.jsx(lt,{size:11})," ",Se]}),!f&&Yc&&o.jsx(zs,{onClick:kg,disabled:se,title:"Run AI inference on this frame",children:o.jsx(yu,{size:14,className:"text-violet-400"})}),Pt&&o.jsx("span",{className:"text-xs text-red-400",children:Pt}),ms&&o.jsx("span",{className:"text-xs text-slate-400",children:ms})]})]})]})]}),o.jsxs("div",{className:"w-64 shrink-0 border-l border-slate-700/50 flex flex-col overflow-y-auto",style:{backgroundColor:"#0f172a"},children:[o.jsxs("div",{className:"flex flex-col gap-4 p-4 border-b border-slate-800",children:[o.jsxs(Ip,{title:"Video",children:[o.jsx(Ps,{label:"Duration",value:_?Lp(_):"--"}),o.jsx(Ps,{label:"FPS",value:B==="probing"?o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(Ce,{className:"animate-spin",size:10})," probing..."]}):X6(it,B),valueClass:Z6(B)})]}),o.jsxs(Ip,{title:"Frame",children:[o.jsx(Ps,{label:"Current",value:Kn?`${gs} / ${Kn}`:gs}),o.jsx(Ps,{label:"Time",value:`${g.toFixed(4)} s`}),o.jsx(Ps,{label:"Labelled",value:`${$.length} / ${t.frame_target}`}),o.jsxs("div",{className:"mt-1",children:[o.jsx("div",{className:"h-1.5 bg-slate-800 rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full bg-brand-500 rounded-full transition-all",style:{width:`${Math.min(100,Math.round($.length/t.frame_target*100))}%`}})}),o.jsxs("p",{className:"text-[10px] text-slate-600 mt-1 text-right",children:[Math.min(100,Math.round($.length/t.frame_target*100)),"% labelled"]})]})]})]}),X?o.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-slate-500",children:["Frame #",X.id]}),o.jsxs("span",{className:"text-[10px] text-slate-500 tabular-nums",children:[(Bg=X.timestamp_seconds)==null?void 0:Bg.toFixed(3)," s"]})]}),o.jsx("div",{className:"text-[10px] text-slate-600 leading-relaxed",children:f?"Pause video to draw annotations.":Mt?`This frame is locked to ${Mt}.`:"Paused frames are editable immediately. Save only the frames you want to keep as draft."}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(yu,{size:11,className:"text-violet-400 shrink-0"}),o.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-slate-500",children:"AI Suggestions"}),se&&o.jsx(Ce,{size:10,className:"animate-spin text-violet-400"})]}),!se&&U.length>0&&o.jsxs("span",{className:"text-[10px] text-slate-500 tabular-nums",children:[U.length," box",U.length!==1?"es":""]})]}),Se&&o.jsxs("p",{className:"text-[10px] text-red-400 flex items-center gap-1 mb-1",children:[o.jsx(lt,{size:10})," ",Se]}),!se&&!Se&&U.length===0&&o.jsxs("p",{className:"text-[10px] text-slate-600",children:["No detections. Click ",o.jsx(yu,{size:9,className:"inline text-violet-400"})," to run inference."]}),U.length>0&&o.jsx("div",{className:"space-y-1",children:U.map((A,H)=>{var ye;const fe=I.find(xe=>xe.name===A.class_name),ce=H===b;return o.jsxs("div",{children:[o.jsxs("button",{onClick:()=>{S(ce?null:H),K(null)},className:`w-full text-left px-2 py-1.5 rounded-lg text-xs flex items-center gap-2 transition border ${ce?"bg-violet-900/30 border-violet-700/50 text-white":"border-transparent text-slate-400 hover:bg-slate-800 hover:text-slate-200"}`,children:[o.jsx(yu,{size:10,className:"text-violet-400 shrink-0"}),o.jsx("span",{className:"truncate flex-1",children:(fe==null?void 0:fe.display_name)??A.class_name}),o.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded ${$d[A.severity]??""}`,children:(ye=A.severity)==null?void 0:ye[0]}),A.confidence!=null&&o.jsxs("span",{className:"text-[9px] text-slate-500 tabular-nums shrink-0",children:[Math.round(A.confidence*100),"%"]})]}),ce&&o.jsxs("div",{className:"bg-slate-800/60 rounded-lg p-3 space-y-2.5 mt-1",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-[10px] text-slate-500 block mb-1",children:"Class"}),o.jsxs("select",{value:A.class_name??"",onChange:xe=>Yh(H,{...A,class_name:xe.target.value}),className:"w-full text-xs bg-slate-700 border border-slate-600 rounded px-2 py-1 text-slate-200",children:[I.length===0&&o.jsx("option",{value:A.class_name,children:A.class_name}),I.map(xe=>o.jsx("option",{value:xe.name,children:xe.display_name??xe.name},xe.name))]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-[10px] text-slate-500 block mb-1",children:"Severity"}),o.jsx("div",{className:"flex gap-1.5",children:["low","medium","high"].map(xe=>o.jsx("button",{onClick:()=>Yh(H,{...A,severity:xe}),className:`flex-1 text-[10px] py-1 rounded capitalize transition ${A.severity===xe?$d[xe]:"bg-slate-700 text-slate-500 hover:text-slate-300"}`,children:xe},xe))})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsxs("button",{onClick:()=>Ng(H),className:`flex-1 flex items-center justify-center gap-1 text-xs bg-violet-700 hover:bg-violet-600 text-white py-1.5 rounded transition`,children:[o.jsx(zn,{size:11})," Approve"]}),o.jsx("button",{onClick:()=>jg(H),className:"flex items-center gap-1 text-xs text-red-400 hover:text-red-300 transition px-2",children:o.jsx(sd,{size:11})})]})]})]},H)})})]}),Gs&&o.jsxs("div",{className:"bg-slate-800/60 rounded-lg p-3 space-y-2.5",children:[o.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-slate-400",children:["Annotation ",Z+1,o.jsxs("span",{className:"ml-1 font-normal normal-case text-slate-500",children:["(",Gs.shape_type,")"]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-[10px] text-slate-500 block mb-1",children:"Class"}),o.jsxs("select",{value:Gs.class_name??"",onChange:A=>Qh(Z,{...Gs,class_name:A.target.value}),className:"w-full text-xs bg-slate-700 border border-slate-600 rounded px-2 py-1 text-slate-200",children:[I.length===0&&o.jsx("option",{value:Gs.class_name,children:Gs.class_name}),I.map(A=>o.jsx("option",{value:A.name,children:A.display_name??A.name},A.name))]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-[10px] text-slate-500 block mb-1",children:"Severity"}),o.jsx("div",{className:"flex gap-1.5",children:["low","medium","high"].map(A=>o.jsx("button",{onClick:()=>Qh(Z,{...Gs,severity:A}),className:`flex-1 text-[10px] py-1 rounded capitalize transition ${Gs.severity===A?$d[A]:"bg-slate-700 text-slate-500 hover:text-slate-300"}`,children:A},A))})]}),o.jsxs("button",{onClick:()=>Eg(Z),className:"flex items-center gap-1 text-xs text-red-400 hover:text-red-300 transition",children:[o.jsx(sd,{size:11})," Remove"]})]}),D.length>0&&o.jsxs("div",{children:[o.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-2",children:["Annotations (",D.length,")"]}),o.jsx("div",{className:"space-y-1",children:D.map((A,H)=>{var ce;const fe=I.find(ye=>ye.name===A.class_name);return o.jsxs("button",{onClick:()=>{K(H),S(null)},className:`w-full text-left px-2 py-1.5 rounded-lg text-xs flex items-center gap-2 transition ${H===Z?"bg-slate-700 text-white":"text-slate-400 hover:bg-slate-800 hover:text-slate-200"}`,children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:(fe==null?void 0:fe.color)??"#94a3b8"}}),o.jsx("span",{className:"truncate flex-1",children:(fe==null?void 0:fe.display_name)??A.class_name}),o.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded ${$d[A.severity]??""}`,children:(ce=A.severity)==null?void 0:ce[0]})]},H)})})]}),D.length===0&&!f&&o.jsx("p",{className:"text-xs text-slate-600 text-center py-2",children:"No annotations yet. Draw boxes or save this frame as empty."}),ut&&o.jsxs("p",{className:"text-xs text-red-400 flex items-center gap-1",children:[o.jsx(lt,{size:11})," ",ut]}),o.jsxs("button",{onClick:Bw,disabled:re||!X,className:`flex items-center justify-center gap-1.5 w-full py-2 rounded-lg text-sm font-medium transition disabled:opacity-40 ${yd||D.length===0?"bg-brand-600 hover:bg-brand-500 text-white":"bg-slate-800 text-slate-500 cursor-default"}`,children:[re?o.jsx(Ce,{className:"animate-spin",size:14}):o.jsx(qj,{size:14}),re?"Saving...":D.length>0?"Save Draft Frame":"Save Empty Frame"]}),r&&X&&(X.status==="approved"||X.status==="rejected"?o.jsxs("div",{className:`flex items-center justify-center gap-1.5 py-2 rounded-lg text-sm border ${X.status==="approved"?"bg-green-900/20 text-green-400 border-green-800/30":"bg-red-900/20 text-red-400 border-red-800/30"}`,children:[X.status==="approved"?o.jsx(zn,{size:14}):o.jsx(js,{size:14}),X.status==="approved"?"Approved":"Rejected"]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsxs("button",{onClick:()=>kn(X.id,"approved"),className:`flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg text-sm font-medium bg-green-900/30 hover:bg-green-800/50 text-green-400 border border-green-800/50 transition`,children:[o.jsx(zn,{size:14})," Approve"]}),o.jsxs("button",{onClick:()=>kn(X.id,"rejected"),className:`flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg text-sm font-medium bg-red-900/30 hover:bg-red-800/50 text-red-400 border border-red-800/50 transition`,children:[o.jsx(js,{size:14})," Reject"]})]}),o.jsxs("p",{className:"text-[10px] text-slate-600 text-center",children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-slate-800 text-slate-500",children:"Y"})," approve  ",o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-slate-800 text-slate-500",children:"N"})," reject  ",o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-slate-800 text-slate-500",children:"["}),o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-slate-800 text-slate-500",children:"]"})," navigate"]})]})),o.jsx("div",{className:"border-t border-slate-800"})]}):o.jsxs("div",{className:"flex flex-col gap-5 p-4",children:[o.jsxs(Ip,{title:"Job",children:[o.jsx(Ps,{label:"ID",value:`#${t.id}`}),o.jsx(Ps,{label:"Status",value:o.jsx($y,{status:ge})}),o.jsx(Ps,{label:"Assigned to",value:t.assigned_to!=null?`User #${t.assigned_to}`:"Unassigned"}),t.notes&&o.jsx(Ps,{label:"Notes",value:t.notes})]}),$.length===0&&o.jsx("p",{className:"text-xs text-slate-600 text-center",children:"Pause the video to start annotating. Nothing is saved until you save the draft frame."})]}),$.length>0&&o.jsxs("div",{className:"mt-auto border-t border-slate-800",children:[o.jsxs("button",{onClick:()=>Us(A=>!A),className:`w-full flex items-center justify-between px-4 py-2.5 text-[10px] font-semibold uppercase tracking-widest text-slate-500 hover:text-slate-300 transition`,children:[o.jsxs("span",{children:["Frames (",$.length,")"]}),xs?o.jsx(i3,{size:12}):o.jsx(r3,{size:12})]}),xs&&o.jsx("div",{className:"flex flex-col max-h-52 overflow-y-auto",children:$.map(A=>{var fe;const H=(X==null?void 0:X.id)===A.id;return o.jsxs("button",{onClick:()=>Sg(A),className:`flex items-center gap-2 px-4 py-2 text-xs text-left transition ${H?"bg-slate-700 text-white":"text-slate-400 hover:bg-slate-800 hover:text-slate-200"}`,children:[o.jsxs("span",{className:"tabular-nums text-[10px] text-slate-500 shrink-0 w-14",children:[(fe=A.timestamp_seconds)==null?void 0:fe.toFixed(2)," s"]}),o.jsxs("span",{className:"truncate flex-1",children:[A.annotation_count??0," box",(A.annotation_count??0)!==1?"es":""]}),o.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded shrink-0 ${A.status==="approved"?"bg-green-900/50 text-green-400":A.status==="rejected"?"bg-red-900/50 text-red-400":A.status==="labelled"?"bg-blue-900/50 text-blue-300":A.status==="pending"?"bg-amber-900/50 text-amber-300":"bg-slate-700 text-slate-500"}`,children:A.status}),r&&A.status!=="approved"&&A.status!=="rejected"&&o.jsxs("div",{className:"flex gap-0.5 shrink-0",children:[o.jsx("button",{onClick:ce=>{ce.stopPropagation(),kn(A.id,"approved")},title:"Approve",className:`w-5 h-5 flex items-center justify-center rounded text-slate-600 hover:text-green-400 hover:bg-green-900/40 transition`,children:o.jsx(zn,{size:10})}),o.jsx("button",{onClick:ce=>{ce.stopPropagation(),kn(A.id,"rejected")},title:"Reject",className:`w-5 h-5 flex items-center justify-center rounded text-slate-600 hover:text-red-400 hover:bg-red-900/40 transition`,children:o.jsx(js,{size:10})})]})]},A.id)})})]})]})]})]})}const Wy=typeof HTMLVideoElement<"u"&&"requestVideoFrameCallback"in HTMLVideoElement.prototype,rT=[{key:"clear",label:"Clear",active:"bg-sky-500",inactive:"bg-slate-700/80 hover:bg-sky-900/60"},{key:"spiral",label:"Spiral",active:"bg-amber-500",inactive:"bg-slate-700/80 hover:bg-amber-900/60"},{key:"white",label:"White",active:"bg-slate-400",inactive:"bg-slate-600/80 hover:bg-slate-500/60"},{key:"outside",label:"Outside",active:"bg-violet-500",inactive:"bg-slate-700/80 hover:bg-violet-900/60"}],Gy={clear:"bg-sky-900/60 text-sky-300",spiral:"bg-amber-900/60 text-amber-300",white:"bg-slate-600 text-slate-200",outside:"bg-violet-900/60 text-violet-300"},iT=["pending","in_progress","submitted","reviewed"],aT=.05;function Wd(t){return!t||isNaN(t)?"0:00":`${Math.floor(t/60)}:${String(Math.floor(t%60)).padStart(2,"0")}`}function oT({job:t,onBack:e,onJobUpdated:s}){const{user:n}=wn(),r=Ih(n),[i,a]=m.useState(null),[l,c]=m.useState(""),[u,d]=m.useState(!1),[f,h]=m.useState(0),[g,v]=m.useState(0),[_,k]=m.useState(!1),[x,p]=m.useState(!1),[y,N]=m.useState(null),[j,w]=m.useState(!1),[B,T]=m.useState(null),[O,C]=m.useState(null),[q,V]=m.useState(!1),[I,ne]=m.useState([]),[X,pe]=m.useState(t.status),[D,R]=m.useState(!1),[U,z]=m.useState(""),G=m.useRef(null),te=m.useRef(null),Z=m.useRef([]),K=m.useRef(null),$=m.useRef([]),ee=m.useRef(null),re=m.useRef(!1);m.useEffect(()=>{Z.current=I},[I]);const ie=y??25;m.useEffect(()=>{fg(t.video_id,t.video_source).then(({signed_url:se})=>a(se)).catch(()=>c("Could not load video URL. Check GCS permissions.")),yg(t.id).then(se=>ne([...se].sort((me,Se)=>me.timestamp_seconds-Se.timestamp_seconds))).catch(()=>{})},[t.id,t.video_id,t.video_source]);const ge=m.useCallback(()=>{const se=G.current;se&&K.current!=null&&(se.cancelVideoFrameCallback(K.current),K.current=null)},[]),We=m.useCallback(()=>{const se=G.current;if(!se||!Wy)return;$.current=[];let me=null;const Se=(Ne,b)=>{const S=$.current;if(S.push(b.mediaTime),S.length>30&&S.shift(),S.length>=10){const E=S.slice(1).map((L,W)=>L-S[W]).filter(L=>L>0),F=E.length?1/(E.reduce((L,W)=>L+W,0)/E.length):null;F&&(me===null||Math.abs(F-me)>.5)&&(me=F,N(F))}!se.paused&&!se.ended?K.current=se.requestVideoFrameCallback(Se):K.current=null};K.current=se.requestVideoFrameCallback(Se)},[]);m.useEffect(()=>()=>ge(),[ge]);const Ye=m.useCallback(se=>{const me=te.current;if(!me||!g)return;const{left:Se,width:Ne}=me.getBoundingClientRect(),b=Math.max(0,Math.min(1,(se-Se)/Ne));G.current&&(G.current.currentTime=b*g)},[g]);m.useEffect(()=>{if(!_)return;const se=Se=>Ye(Se.clientX),me=()=>k(!1);return window.addEventListener("mousemove",se),window.addEventListener("mouseup",me),()=>{window.removeEventListener("mousemove",se),window.removeEventListener("mouseup",me)}},[_,Ye]);const Ue=m.useCallback(se=>{const me=parseFloat(se.toFixed(3)),Se=Z.current.find(Ne=>Math.abs(Ne.timestamp_seconds-me)<=aT);C(Se??null),T(Se?null:me),w(!0)},[]),Pt=m.useCallback(se=>{const me=G.current;if(!me||re.current)return;re.current=!0,p(!0),me.pause();const Se=Math.round(me.currentTime*ie),Ne=Math.max(0,Math.min(me.duration||0,(Se+se)/ie));me.currentTime=Ne,Wy?(ee.current!=null&&me.cancelVideoFrameCallback(ee.current),ee.current=me.requestVideoFrameCallback((b,S)=>{h(S.mediaTime),Ue(S.mediaTime),re.current=!1,p(!1),ee.current=null})):(h(Ne),Ue(Ne),re.current=!1,p(!1))},[ie,Ue]),Ge=m.useCallback(()=>Pt(1),[Pt]),ut=m.useCallback(()=>Pt(-1),[Pt]),Et=m.useCallback(async se=>{var Se,Ne;if(q)return;const me=(O==null?void 0:O.timestamp_seconds)??B;if(me!=null){V(!0),z(""),X==="pending"&&Zf(t.id,{status:"in_progress"}).then(b=>{pe("in_progress"),s==null||s(b)}).catch(()=>{});try{const b=await xw(t.id,{timestamp_seconds:me,annotations:[],tube_type:se});ne(S=>[...S.filter(E=>E.id!==b.id),b].sort((E,F)=>E.timestamp_seconds-F.timestamp_seconds)),C(b),T(null),setTimeout(()=>w(!1),350)}catch(b){z(((Ne=(Se=b.response)==null?void 0:Se.data)==null?void 0:Ne.detail)??"Failed to save.")}finally{V(!1)}}},[q,O,B,t.id,X,s]),ms=m.useCallback(se=>{G.current&&(G.current.currentTime=se.timestamp_seconds),C(se),T(null),w(!0)},[]),tt=async se=>{var me,Se;R(!0),z("");try{const Ne=await Zf(t.id,{status:se});pe(Ne.status),s==null||s(Ne)}catch(Ne){z(((Se=(me=Ne.response)==null?void 0:me.data)==null?void 0:Se.detail)??"Failed to update status.")}finally{R(!1)}};m.useEffect(()=>{const se=me=>{var Se,Ne;if(!["INPUT","SELECT","TEXTAREA"].includes(me.target.tagName)){if(me.key===" "){me.preventDefault(),(Se=G.current)!=null&&Se.paused?G.current.play():(Ne=G.current)==null||Ne.pause();return}if(me.key==="ArrowLeft"){me.preventDefault(),ut();return}if(me.key==="ArrowRight"){me.preventDefault(),Ge();return}}};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[ut,Ge]);const xs=g?f/g*100:0,Us=I.filter(se=>se.tube_type).length;return o.jsxs("div",{className:"flex flex-col h-full bg-slate-900 text-white overflow-hidden",children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-slate-700/80 shrink-0",children:[o.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 text-sm text-slate-400 hover:text-white transition",children:[o.jsx(dg,{size:15}),"Jobs"]}),o.jsx("span",{className:"text-slate-600",children:"/"}),o.jsxs("span",{className:"text-sm font-semibold",children:["Job #",t.id]}),o.jsx("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-semibold bg-sky-900/60 text-sky-300 border border-sky-700/60 uppercase tracking-wide`,children:"Classification"}),o.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[U&&o.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-red-400",children:[o.jsx(lt,{size:13}),U]}),!r&&X!=="submitted"&&X!=="reviewed"&&o.jsx("button",{onClick:()=>tt("submitted"),disabled:D||Us===0,className:`px-3 py-1.5 bg-brand-600 hover:bg-brand-500 text-white text-xs font-medium rounded-lg disabled:opacity-40 transition`,children:D?"Saving…":"Submit Job"}),r&&o.jsx("select",{value:X,onChange:se=>tt(se.target.value),disabled:D,className:`text-xs bg-slate-700 border border-slate-600 rounded px-2 py-1.5 text-white focus:outline-none focus:border-brand-500 disabled:opacity-50 capitalize`,children:iT.map(se=>o.jsx("option",{value:se,children:se.replace("_"," ")},se))})]})]}),o.jsxs("div",{className:"flex flex-1 min-h-0",children:[o.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[o.jsxs("div",{className:"relative flex-1 bg-black min-h-0",children:[l&&o.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:o.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm px-6 text-center",children:[o.jsx(lt,{size:16,className:"shrink-0"}),l]})}),!i&&!l&&o.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 text-slate-400",children:[o.jsx(Ce,{className:"animate-spin",size:32}),o.jsx("span",{className:"text-sm",children:"Loading video…"})]}),i&&o.jsx("video",{ref:G,src:i,crossOrigin:"anonymous",className:"absolute inset-0 w-full h-full object-contain",onTimeUpdate:()=>{var se;return h(((se=G.current)==null?void 0:se.currentTime)??0)},onLoadedMetadata:()=>{var se;return v(((se=G.current)==null?void 0:se.duration)??0)},onPlay:()=>{d(!0),w(!1),We()},onPause:se=>{d(!1),ge(),Ue(se.target.currentTime)},onEnded:()=>{d(!1),ge()}}),j&&!u&&i&&o.jsx("div",{className:"absolute inset-x-0 bottom-0 pb-5 flex justify-center pointer-events-none",children:o.jsxs("div",{className:`pointer-events-auto bg-slate-900/85 backdrop-blur-sm rounded-2xl px-5 py-4 flex flex-col items-center gap-3 w-80 shadow-xl`,children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"text-slate-400 tabular-nums",children:Wd((O==null?void 0:O.timestamp_seconds)??B??f)}),O!=null&&O.tube_type?o.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase ${Gy[O.tube_type]}`,children:O.tube_type}):o.jsx("span",{className:"text-[10px] text-slate-600",children:"select a class to save this frame"})]}),o.jsx("div",{className:"grid grid-cols-4 gap-2 w-full",children:rT.map(({key:se,label:me,active:Se,inactive:Ne})=>{const b=(O==null?void 0:O.tube_type)===se;return o.jsxs("button",{onClick:()=>Et(se),disabled:q,className:`py-2.5 rounded-xl text-xs font-semibold text-white transition flex items-center justify-center gap-1 disabled:opacity-50 ${b?`${Se} ring-2 ring-white/30`:Ne}`,children:[b&&o.jsx(zn,{size:10}),me]},se)})}),o.jsx("button",{onClick:()=>w(!1),className:"text-[10px] text-slate-500 hover:text-slate-300 transition",children:"Skip this frame"})]})})]}),o.jsxs("div",{className:"px-4 py-3 border-t border-slate-700/80 space-y-2.5 shrink-0",children:[o.jsxs("div",{ref:te,className:"relative h-1.5 bg-slate-700 rounded-full cursor-pointer group",onMouseDown:se=>{se.preventDefault(),k(!0),Ye(se.clientX)},children:[o.jsx("div",{className:"absolute left-0 top-0 h-full bg-brand-500 rounded-full pointer-events-none",style:{width:`${xs}%`}}),o.jsx("div",{className:`absolute top-1/2 -translate-y-1/2 w-3 h-3 bg-white rounded-full shadow pointer-events-none transition-opacity ${_?"opacity-100":"opacity-0 group-hover:opacity-100"}`,style:{left:`calc(${xs}% - 6px)`}})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("button",{onClick:ut,disabled:!i||x,className:"text-slate-400 hover:text-white transition disabled:opacity-30",title:"Previous frame (←)",children:o.jsx(Lh,{size:18})}),o.jsx("button",{onClick:()=>{var se,me;return(se=G.current)!=null&&se.paused?G.current.play():(me=G.current)==null?void 0:me.pause()},disabled:!i,className:"text-white hover:text-brand-400 transition disabled:opacity-30",title:u?"Pause (Space)":"Play (Space)",children:u?o.jsx(ug,{size:20}):o.jsx(cg,{size:20})}),o.jsx("button",{onClick:Ge,disabled:!i||x,className:"text-slate-400 hover:text-white transition disabled:opacity-30",title:"Next frame (→)",children:o.jsx(Fh,{size:18})}),o.jsxs("span",{className:"text-slate-400 text-xs tabular-nums",children:[Wd(f),o.jsx("span",{className:"text-slate-600",children:" / "}),Wd(g)]}),o.jsxs("span",{className:"text-xs text-slate-600",children:[I.length," frame",I.length!==1?"s":""," · ",Us," classified"]})]})]})]}),o.jsxs("div",{className:"w-64 shrink-0 flex flex-col border-l border-slate-700/80 bg-slate-800 overflow-hidden",children:[o.jsxs("div",{className:"shrink-0 border-b border-slate-700/80 px-3 py-3",children:[o.jsxs("p",{className:"text-xs font-semibold text-slate-400 uppercase tracking-wide",children:["Frames"," ",o.jsxs("span",{className:"font-normal text-slate-600",children:["(",I.length,")"]})]}),o.jsx("p",{className:"text-[10px] text-slate-600 mt-1",children:"Pause or step the video, then select a class."})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto divide-y divide-slate-700/40",children:[I.length===0&&o.jsx("div",{className:"flex items-center justify-center h-24 text-xs text-slate-600",children:"No frames classified yet"}),I.map(se=>{const me=(O==null?void 0:O.id)===se.id;return o.jsxs("button",{onClick:()=>ms(se),className:`w-full flex items-center justify-between px-3 py-2.5 text-left transition border-l-2 ${me?"bg-slate-700/80 border-brand-500":"border-transparent hover:bg-slate-700/40"}`,children:[o.jsx("span",{className:"text-xs font-mono text-slate-400",children:Wd(se.timestamp_seconds)}),se.tube_type?o.jsx("span",{className:`text-[10px] font-semibold uppercase px-1.5 py-0.5 rounded ${Gy[se.tube_type]}`,children:se.tube_type}):o.jsx("span",{className:"text-[10px] text-slate-600",children:"?"})]},se.id)})]})]})]})]})}function lT(t){return t?t.split("/").pop()||t:"—"}function cT(t){return t?new Date(t).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):"—"}const uT={pending:{label:"Pending",style:"bg-slate-100 text-slate-600 border-slate-200"},in_progress:{label:"In Progress",style:"bg-blue-50 text-blue-700 border-blue-200"},submitted:{label:"Submitted",style:"bg-amber-50 text-amber-700 border-amber-200"},reviewed:{label:"Reviewed",style:"bg-green-50 text-green-700 border-green-200"}};function dT({status:t}){const e=uT[t]??{label:t,style:"bg-slate-100 text-slate-600 border-slate-200"};return o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${e.style}`,children:e.label})}function fT({source:t}){const e=t==="production"?"bg-violet-50 text-violet-700 border-violet-200":"bg-sky-50 text-sky-700 border-sky-200";return o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${e} capitalize`,children:t})}function hT({type:t}){const e=t==="classification"?"bg-sky-50 text-sky-700 border-sky-200":"bg-slate-100 text-slate-600 border-slate-200";return o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${e} capitalize`,children:t??"detection"})}function pT({count:t,target:e}){const s=e>0?Math.min(100,Math.round(t/e*100)):0,n=s>=100?"bg-emerald-500":"bg-brand-500";return o.jsxs("div",{className:"flex items-center gap-2 min-w-28",children:[o.jsx("div",{className:"flex-1 h-1.5 bg-slate-200 rounded-full overflow-hidden",children:o.jsx("div",{className:`h-full ${n} rounded-full`,style:{width:`${s}%`}})}),o.jsxs("span",{className:"text-xs text-slate-500 tabular-nums whitespace-nowrap",children:[t,"/",e]})]})}const qy=[{value:"",label:"All"},{value:"pending",label:"Pending"},{value:"in_progress",label:"In Progress"},{value:"submitted",label:"Submitted"},{value:"reviewed",label:"Reviewed"}];function mT(){var N;const{user:t}=wn(),[e,s]=m.useState([]),[n,r]=m.useState(""),[i,a]=m.useState(!1),[l,c]=m.useState(""),[u,d]=m.useState(null),[f,h]=m.useState([]),[g,v]=m.useState(null),_=Ih(t),k=m.useMemo(()=>{const j=f.map(w=>{const B=w.full_name||w.email||`User #${w.user_id}`;return[w.user_id,B]});return Object.fromEntries(j)},[f]),x=m.useCallback(async()=>{var j,w;a(!0),c("");try{const B=await hg({status:n||void 0});s(B)}catch(B){c(((w=(j=B.response)==null?void 0:j.data)==null?void 0:w.detail)??"Failed to load jobs.")}finally{a(!1)}},[n]);m.useEffect(()=>{x()},[x]),m.useEffect(()=>{_&&k3({role:"marker"}).then(h).catch(()=>{})},[_]);const p=m.useCallback(j=>{d(j),s(w=>w.map(B=>B.id===j.id?j:B))},[]),y=m.useCallback(async(j,w)=>{var B,T;v(j),c("");try{const O=await Zf(j,{assigned_to:w===""?null:Number(w)});s(C=>C.map(q=>q.id===O.id?O:q))}catch(O){c(((T=(B=O.response)==null?void 0:B.data)==null?void 0:T.detail)??(O==null?void 0:O.detail)??"Failed to update job assignee.")}finally{v(null)}},[]);if(u){const j=u.job_type==="classification"?oT:nT;return o.jsx(j,{job:u,onJobUpdated:p,onBack:()=>{d(null),x()}})}return o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-b border-slate-200 bg-white shrink-0",children:[o.jsx("h1",{className:"text-lg font-semibold text-slate-800 mr-2",children:"Jobs"}),o.jsx("div",{className:"flex items-center gap-1",children:qy.map(j=>o.jsx("button",{onClick:()=>r(j.value),className:`px-3 py-1 rounded-full text-xs font-medium transition ${n===j.value?"bg-brand-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,children:j.label},j.value))}),o.jsx("button",{onClick:x,disabled:i,className:`ml-auto p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100\r rounded-lg transition disabled:opacity-40`,title:"Refresh",children:o.jsx(db,{size:15,className:i?"animate-spin":""})})]}),o.jsxs("div",{className:"flex-1 overflow-auto px-6 py-4",children:[l&&o.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm mb-4",children:[o.jsx(lt,{size:15}),l]}),i&&e.length===0&&o.jsxs("div",{className:"flex items-center justify-center h-48 gap-3 text-slate-400",children:[o.jsx(Ce,{className:"animate-spin",size:22}),o.jsx("span",{className:"text-sm",children:"Loading jobs…"})]}),!i&&!l&&e.length===0&&o.jsxs("div",{className:"flex flex-col items-center justify-center h-48 gap-2 text-slate-400",children:[o.jsx(hb,{size:32}),o.jsx("p",{className:"text-sm",children:"No jobs found."})]}),e.length>0&&o.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 overflow-hidden shadow-sm",children:[o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-slate-200 bg-slate-50 text-xs text-slate-500 uppercase tracking-wide",children:[o.jsx("th",{className:"px-4 py-3 text-left font-medium w-12",children:"#"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Video"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Type"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Source"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Status"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Progress"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Assigned to"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Created"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Notes"})]})}),o.jsx("tbody",{className:"divide-y divide-slate-100",children:e.map(j=>o.jsxs("tr",{className:"hover:bg-slate-50 transition-colors cursor-pointer",onClick:()=>d(j),children:[o.jsx("td",{className:"px-4 py-3 text-slate-400 tabular-nums",children:j.id}),o.jsxs("td",{className:"px-4 py-3 max-w-xs",children:[o.jsx("span",{className:"block truncate text-slate-700 font-medium",title:j.video_gcs_path,children:lT(j.video_gcs_path)}),o.jsxs("span",{className:"text-xs text-slate-400",children:["video #",j.video_id]})]}),o.jsx("td",{className:"px-4 py-3",children:o.jsx(hT,{type:j.job_type})}),o.jsx("td",{className:"px-4 py-3",children:o.jsx(fT,{source:j.video_source})}),o.jsx("td",{className:"px-4 py-3",children:o.jsx(dT,{status:j.status})}),o.jsx("td",{className:"px-4 py-3",children:o.jsx(pT,{count:j.frame_count,target:j.frame_target})}),o.jsx("td",{className:"px-4 py-3 text-slate-500",children:_?o.jsxs("select",{value:j.assigned_to??"",onClick:w=>w.stopPropagation(),onChange:w=>void y(j.id,w.target.value),disabled:g===j.id,className:"min-w-40 text-xs bg-white border border-slate-300 rounded px-2 py-1 text-slate-700 disabled:opacity-50",children:[o.jsx("option",{value:"",children:"Unassigned"}),f.map(w=>o.jsx("option",{value:w.user_id,children:w.full_name||w.email||`User #${w.user_id}`},w.user_id))]}):j.assigned_to!=null?k[j.assigned_to]??`User #${j.assigned_to}`:o.jsx("span",{className:"text-slate-300",children:"Unassigned"})}),o.jsx("td",{className:"px-4 py-3 text-slate-500 whitespace-nowrap",children:cT(j.created_at)}),o.jsx("td",{className:"px-4 py-3 text-slate-400 max-w-xs",children:j.notes?o.jsx("span",{className:"truncate block",title:j.notes,children:j.notes}):o.jsx("span",{className:"text-slate-200",children:"—"})})]},j.id))})]}),o.jsxs("div",{className:"px-4 py-2.5 border-t border-slate-100 bg-slate-50 text-xs text-slate-400",children:[e.length," job",e.length!==1?"s":"",n?` · filtered by "${(N=qy.find(j=>j.value===n))==null?void 0:N.label}"`:""]})]})]})]})}async function xT(){return(await we.get("/api/v1/datasets")).data}async function gT(t,e=null){return(await we.post("/api/v1/datasets",{name:t,description:e})).data}async function yT(t){return(await we.get(`/api/v1/datasets/${t}`)).data}async function Jy(t,{page:e=1,pageSize:s=25,tag:n,tubeType:r}={}){const i={page:e,page_size:s};return n!==void 0&&n!=="all"&&(i.tag=n===null?"untagged":n),r!==void 0&&r!=="all"&&(i.tube_type=r===null?"untyped":r),(await we.get(`/api/v1/datasets/${t}/frames`,{params:i})).data}async function _T(t,e){return(await we.post(`/api/v1/datasets/${t}/frames`,{frame_ids:e})).data}async function Ky(t,{page:e=1,pageSize:s=200,className:n=null,severity:r=null,approvedOnly:i=!0}={}){const a={page:e,page_size:s,approved_only:i};return n&&n!=="all"&&(a.class_name=n),r&&(a.severity=r),(await we.get(`/api/v1/datasets/${t}/severity`,{params:a})).data}async function vT(t,e){return(await we.post(`/api/v1/datasets/${t}/export`,e)).data}const bT=[{key:"approved",label:"Approved"},{key:"to_discuss",label:"To discuss"},{key:"remove",label:"Remove"}];function wT({dataset:t,onClose:e,onExported:s}){const[n,r]=m.useState(80),[i,a]=m.useState({approved:!0,to_discuss:!0,remove:!1}),[l,c]=m.useState(!1),[u,d]=m.useState(!0),[f,h]=m.useState(!1),[g,v]=m.useState(""),[_,k]=m.useState(new Set),[x,p]=m.useState([]),[y,N]=m.useState(!0),[j,w]=m.useState(!1),[B,T]=m.useState("form"),[O,C]=m.useState(""),[q,V]=m.useState(!1),[I,ne]=m.useState("");m.useEffect(()=>{Vh().then(p).catch(()=>{}).finally(()=>N(!1))},[]),m.useEffect(()=>{if(B!=="building")return;const U=setInterval(async()=>{try{const z=await yT(t.id);z.status!=="building"&&(clearInterval(U),z.status==="exported"?(C(z.gcs_export_path??""),T("done"),s(z)):(ne("Export failed — dataset was reset to ready status."),T("form")))}catch{}},2e3);return()=>clearInterval(U)},[B,t.id,s]);async function X(U){var z,G;U.preventDefault(),w(!0),ne("");try{await vT(t.id,{train_split:n/100,allowed_review_tags:Object.entries(i).filter(([,te])=>te).map(([te])=>te),include_untagged:l,include_no_label_frames:u,balance:f,target_per_class:f&&g!==""?Number(g):null,excluded_classes:[..._]}),T("building")}catch(te){ne(((G=(z=te.response)==null?void 0:z.data)==null?void 0:G.detail)??"Failed to start export.")}finally{w(!1)}}function pe(U){a(z=>({...z,[U]:!z[U]}))}function D(U){k(z=>{const G=new Set(z);return G.has(U)?G.delete(U):G.add(U),G})}async function R(){try{await navigator.clipboard.writeText(O),V(!0),setTimeout(()=>V(!1),2e3)}catch{}}return o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40",children:o.jsxs("div",{className:"bg-white rounded-xl shadow-xl w-full max-w-lg mx-4 max-h-[90vh] flex flex-col",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 pt-5 pb-4 border-b border-slate-100 shrink-0",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Export Dataset"}),o.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[t.name," · ",t.frame_count," frame",t.frame_count!==1?"s":""]})]}),o.jsx("button",{onClick:e,className:"p-1 text-slate-400 hover:text-slate-700 rounded transition",children:o.jsx(js,{size:16})})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:[B==="done"&&o.jsxs("div",{className:"flex flex-col items-center text-center py-4 gap-3",children:[o.jsx(Jm,{size:36,className:"text-emerald-500"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-semibold text-slate-800 text-sm",children:"Export complete"}),o.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"Dataset saved at"})]}),o.jsxs("div",{className:"w-full bg-slate-50 rounded-lg px-3 py-2.5 flex items-start gap-2 border border-slate-200",children:[o.jsx("code",{className:"flex-1 text-xs text-slate-700 break-all text-left",children:O}),o.jsx("button",{onClick:R,className:"shrink-0 mt-0.5 text-slate-400 hover:text-slate-700 transition",title:"Copy path",children:q?o.jsx(Jm,{size:14,className:"text-emerald-500"}):o.jsx(t3,{size:14})})]})]}),B==="building"&&o.jsxs("div",{className:"flex flex-col items-center text-center py-10 gap-3 text-slate-500",children:[o.jsx(Ce,{size:28,className:"animate-spin text-brand-500"}),o.jsx("p",{className:"text-sm font-medium text-slate-700",children:"Exporting…"}),o.jsx("p",{className:"text-xs text-slate-400",children:"Copying frames and generating label files in GCS"})]}),B==="form"&&o.jsxs("form",{id:"export-form",onSubmit:X,className:"space-y-5",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex justify-between items-center mb-2",children:[o.jsx("label",{className:"text-xs font-medium text-slate-600",children:"Train / val split"}),o.jsxs("span",{className:"text-xs tabular-nums font-medium text-slate-700",children:[n,"% / ",100-n,"%"]})]}),o.jsx("input",{type:"range",min:"50",max:"95",step:"5",value:n,onChange:U=>r(Number(U.target.value)),className:"w-full accent-brand-600"}),o.jsxs("div",{className:"flex justify-between text-[10px] text-slate-400 mt-1 px-0.5",children:[o.jsx("span",{children:"50%"}),o.jsx("span",{children:"95%"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-2",children:"Include frames tagged as"}),o.jsxs("div",{className:"space-y-1.5 bg-slate-50 rounded-lg p-3",children:[bT.map(({key:U,label:z})=>o.jsxs("label",{className:"flex items-center gap-2.5 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:!!i[U],onChange:()=>pe(U),className:"w-4 h-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500 cursor-pointer"}),o.jsx("span",{className:"text-sm text-slate-700",children:z})]},U)),o.jsxs("label",{className:"flex items-center gap-2.5 cursor-pointer border-t border-slate-200 pt-2 mt-1",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:U=>c(U.target.checked),className:"w-4 h-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500 cursor-pointer"}),o.jsx("span",{className:"text-sm text-slate-400 italic",children:"Untagged"})]})]})]}),!y&&x.length>0&&o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-2",children:"Exclude classes"}),o.jsx("div",{className:"grid grid-cols-2 gap-1.5 bg-slate-50 rounded-lg p-3",children:x.map(U=>o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:_.has(U.name),onChange:()=>D(U.name),className:"w-4 h-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500 cursor-pointer"}),o.jsxs("span",{className:"flex items-center gap-1.5 text-sm text-slate-700 min-w-0",children:[U.color&&o.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:U.color}}),o.jsx("span",{className:"truncate",children:U.display_name??U.name})]})]},U.name))})]}),o.jsxs("label",{className:"flex items-center gap-2.5 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:u,onChange:U=>d(U.target.checked),className:"w-4 h-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500 cursor-pointer"}),o.jsx("span",{className:"text-sm text-slate-700",children:"Include frames with no annotations"})]}),o.jsxs("div",{className:"border border-slate-200 rounded-lg p-3 space-y-3",children:[o.jsxs("label",{className:"flex items-start gap-2.5 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:f,onChange:U=>h(U.target.checked),className:"mt-0.5 w-4 h-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500 cursor-pointer"}),o.jsxs("div",{children:[o.jsx("span",{className:"text-sm font-medium text-slate-700",children:"Balanced mode"}),o.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Oversample under-represented (class, severity) groups in the train split"})]})]}),f&&o.jsxs("div",{className:"pl-6",children:[o.jsxs("label",{className:"block text-xs font-medium text-slate-600 mb-1.5",children:["Target per group"," ",o.jsx("span",{className:"font-normal text-slate-400",children:"(leave blank to use median)"})]}),o.jsx("input",{type:"number",min:"1",value:g,onChange:U=>v(U.target.value),placeholder:"auto",className:`w-28 text-sm border border-slate-300 rounded-lg px-3 py-1.5 text-slate-800 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500`})]})]}),I&&o.jsxs("p",{className:"text-xs text-red-600 flex items-center gap-1.5",children:[o.jsx(lt,{size:12}),I]})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 px-6 py-4 border-t border-slate-100 shrink-0",children:[o.jsx("button",{onClick:e,className:"px-4 py-2 text-sm text-slate-600 hover:text-slate-800 rounded-lg hover:bg-slate-100 transition",children:B==="done"?"Close":"Cancel"}),B==="form"&&o.jsxs("button",{type:"submit",form:"export-form",disabled:j,className:`px-4 py-2 text-sm font-medium bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 transition flex items-center gap-2`,children:[j?o.jsx(Ce,{size:13,className:"animate-spin"}):o.jsx(cb,{size:14}),"Export to GCS"]})]})]})})}const ST=[{key:"clear",label:"Clear",dot:"bg-sky-500"},{key:"spiral",label:"Spiral",dot:"bg-amber-500"},{key:"white",label:"White",dot:"bg-slate-400"},{key:"outside",label:"Outside",dot:"bg-violet-400"},{key:"_unclassified",label:"Unclassified",dot:"bg-slate-300"}];function kT(t){return t.tube_type??"_unclassified"}function ET(t){return t?new Date(t).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):"—"}const NT={building:"bg-amber-50 text-amber-700 border-amber-200",ready:"bg-emerald-50 text-emerald-700 border-emerald-200",exported:"bg-violet-50 text-violet-700 border-violet-200"};function jT({onClose:t,onCreate:e}){const[s,n]=m.useState(""),[r,i]=m.useState(""),[a,l]=m.useState(!1),[c,u]=m.useState("");async function d(f){var h,g;if(f.preventDefault(),!!s.trim()){l(!0),u("");try{const v=await gT(s.trim(),r.trim()||null);e(v)}catch(v){u(((g=(h=v.response)==null?void 0:h.data)==null?void 0:g.detail)??"Failed to create dataset.")}finally{l(!1)}}}return o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40",children:o.jsxs("div",{className:"bg-white rounded-xl shadow-xl w-full max-w-sm mx-4 p-6",children:[o.jsxs("div",{className:"flex items-center justify-between mb-5",children:[o.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"New Dataset"}),o.jsx("button",{onClick:t,className:"p-1 text-slate-400 hover:text-slate-700 rounded transition",children:o.jsx(js,{size:16})})]}),o.jsxs("form",{onSubmit:d,className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1.5",children:"Name *"}),o.jsx("input",{autoFocus:!0,value:s,onChange:f=>n(f.target.value),placeholder:"e.g. endoscope-v1",className:`w-full text-sm border border-slate-300 rounded-lg px-3 py-2 text-slate-800 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500`})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1.5",children:"Description"}),o.jsx("textarea",{value:r,onChange:f=>i(f.target.value),rows:2,placeholder:"Optional description…",className:`w-full text-sm border border-slate-300 rounded-lg px-3 py-2 text-slate-800 resize-none focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500`})]}),c&&o.jsxs("p",{className:"text-xs text-red-600 flex items-center gap-1.5",children:[o.jsx(lt,{size:12}),c]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[o.jsx("button",{type:"button",onClick:t,className:"px-4 py-2 text-sm text-slate-600 hover:text-slate-800 rounded-lg hover:bg-slate-100 transition",children:"Cancel"}),o.jsxs("button",{type:"submit",disabled:a||!s.trim(),className:`px-4 py-2 text-sm font-medium bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 transition flex items-center gap-2`,children:[a&&o.jsx(Ce,{size:13,className:"animate-spin"}),"Create"]})]})]})]})})}function CT({dataset:t,onClose:e,onAdded:s}){const[n,r]=m.useState([]),[i,a]=m.useState(!0),[l,c]=m.useState(""),[u,d]=m.useState({}),[f,h]=m.useState(!1),[g,v]=m.useState({}),[_,k]=m.useState(!1),[x,p]=m.useState(""),[y,N]=m.useState(null);m.useEffect(()=>{hg().then(C=>{const q=[...C].sort((V,I)=>{const ne={reviewed:0,submitted:1,in_progress:2,pending:3};return(ne[V.status]??9)-(ne[I.status]??9)});r(q),q.length&&c(String(q[0].id))}).catch(()=>p("Could not load jobs.")).finally(()=>a(!1))},[]),m.useEffect(()=>{l&&(h(!0),d({}),v({}),p(""),yg(Number(l)).then(C=>{const q=C.filter(ne=>ne.status==="approved"),V={};for(const ne of q){const X=kT(ne);V[X]||(V[X]=[]),V[X].push(ne)}d(V);const I={};for(const ne of Object.keys(V))I[ne]=ne!=="outside";v(I)}).catch(()=>p("Could not load frames for this job.")).finally(()=>h(!1)))},[l]);function j(C){v(q=>({...q,[C]:!q[C]}))}const w=Object.entries(u).filter(([C])=>g[C]).flatMap(([,C])=>C.map(q=>q.id));async function B(){var C,q;if(w.length!==0){k(!0),p("");try{const V=await _T(t.id,w);N(V),s(V)}catch(V){p(((q=(C=V.response)==null?void 0:C.data)==null?void 0:q.detail)??"Failed to add frames.")}finally{k(!1)}}}const T=Object.keys(u).length>0,O=Object.values(u).reduce((C,q)=>C+q.length,0);return o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40",children:o.jsxs("div",{className:"bg-white rounded-xl shadow-xl w-full max-w-md mx-4 p-6",children:[o.jsxs("div",{className:"flex items-center justify-between mb-5",children:[o.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Add Frames from Job"}),o.jsx("button",{onClick:e,className:"p-1 text-slate-400 hover:text-slate-700 rounded transition",children:o.jsx(js,{size:16})})]}),y?o.jsxs("div",{className:"text-center py-4 space-y-2",children:[o.jsx("div",{className:"text-emerald-600 font-semibold text-sm",children:"Frames added successfully"}),o.jsxs("div",{className:"text-xs text-slate-500",children:["Dataset now has ",y.frame_count," frame",y.frame_count!==1?"s":""]}),o.jsx("button",{onClick:e,className:"mt-3 px-5 py-2 bg-brand-600 text-white text-sm rounded-lg hover:bg-brand-700 transition",children:"Done"})]}):o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1.5",children:"Job"}),i?o.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400 py-2",children:[o.jsx(Ce,{size:13,className:"animate-spin"})," Loading jobs…"]}):o.jsx("select",{value:l,onChange:C=>c(C.target.value),className:`w-full text-sm border border-slate-300 rounded-lg px-3 py-2 text-slate-800 focus:outline-none focus:ring-2 focus:ring-brand-500`,children:n.map(C=>{var V;const q=((V=C.video_gcs_path)==null?void 0:V.split("/").pop())??`Job #${C.id}`;return o.jsxs("option",{value:C.id,children:["#",C.id," · ",q," (",C.status,")"]},C.id)})})]}),f&&o.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400 py-1",children:[o.jsx(Ce,{size:13,className:"animate-spin"})," Loading frames…"]}),!f&&O===0&&l&&o.jsx("p",{className:"text-xs text-slate-500 bg-slate-50 rounded-lg px-3 py-2",children:"No approved frames in this job."}),!f&&T&&o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-2",children:"Tube types — select which to include"}),o.jsx("div",{className:"space-y-1.5 bg-slate-50 rounded-lg p-3",children:ST.filter(C=>u[C.key]).map(({key:C,label:q,dot:V})=>{var ne;const I=((ne=u[C])==null?void 0:ne.length)??0;return o.jsxs("label",{className:"flex items-center gap-3 cursor-pointer group",children:[o.jsx("input",{type:"checkbox",checked:!!g[C],onChange:()=>j(C),className:`w-4 h-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500 cursor-pointer`}),o.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${V}`}),o.jsx("span",{className:"flex-1 text-sm text-slate-700",children:q}),o.jsxs("span",{className:"text-xs font-medium tabular-nums text-slate-500",children:[I," frame",I!==1?"s":""]})]},C)})}),o.jsx("p",{className:"text-xs text-slate-500 mt-2 px-1",children:w.length===0?"No types selected.":o.jsxs(o.Fragment,{children:["Will add ",o.jsx("span",{className:"font-semibold text-slate-700",children:w.length})," frame",w.length!==1?"s":""," · frames already in the dataset will be skipped."]})})]}),x&&o.jsxs("p",{className:"text-xs text-red-600 flex items-center gap-1.5",children:[o.jsx(lt,{size:12}),x]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[o.jsx("button",{onClick:e,className:"px-4 py-2 text-sm text-slate-600 hover:text-slate-800 rounded-lg hover:bg-slate-100 transition",children:"Cancel"}),o.jsxs("button",{onClick:B,disabled:_||i||f||w.length===0,className:`px-4 py-2 text-sm font-medium bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 transition flex items-center gap-2`,children:[_&&o.jsx(Ce,{size:13,className:"animate-spin"}),"Add ",w.length>0?`${w.length} `:"","Frames"]})]})]})]})})}function UT({onSelect:t}){const{user:e}=wn(),[s,n]=m.useState([]),[r,i]=m.useState(!1),[a,l]=m.useState(""),[c,u]=m.useState(!1),[d,f]=m.useState(null),[h,g]=m.useState(null),v=Ih(e),_=m.useCallback(async()=>{var y,N;i(!0),l("");try{n(await xT())}catch(j){l(((N=(y=j.response)==null?void 0:y.data)==null?void 0:N.detail)??"Failed to load datasets.")}finally{i(!1)}},[]);m.useEffect(()=>{_()},[_]);function k(y){n(N=>[y,...N]),u(!1)}function x(y){n(N=>N.map(j=>j.id===y.id?y:j))}function p(y){n(N=>N.map(j=>j.id===y.id?y:j))}return o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-b border-slate-200 bg-white shrink-0",children:[o.jsx("h1",{className:"text-lg font-semibold text-slate-800 mr-2",children:"Datasets"}),v&&o.jsxs("button",{onClick:()=>u(!0),className:`flex items-center gap-1.5 px-3 py-1.5 bg-brand-600 text-white text-sm font-medium rounded-lg hover:bg-brand-700 transition`,children:[o.jsx(fb,{size:14}),"New Dataset"]}),o.jsx("button",{onClick:_,disabled:r,className:`ml-auto p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition disabled:opacity-40`,title:"Refresh",children:o.jsx(db,{size:15,className:r?"animate-spin":""})})]}),o.jsxs("div",{className:"flex-1 overflow-auto px-6 py-4",children:[a&&o.jsxs("div",{className:"flex items-center gap-2 text-red-600 text-sm mb-4",children:[o.jsx(lt,{size:15})," ",a]}),r&&s.length===0&&o.jsxs("div",{className:"flex items-center justify-center h-48 gap-3 text-slate-400",children:[o.jsx(Ce,{className:"animate-spin",size:22}),o.jsx("span",{className:"text-sm",children:"Loading datasets…"})]}),!r&&!a&&s.length===0&&o.jsxs("div",{className:"flex flex-col items-center justify-center h-48 gap-2 text-slate-400",children:[o.jsx(hb,{size:32}),o.jsx("p",{className:"text-sm",children:"No datasets yet."}),v&&o.jsx("button",{onClick:()=>u(!0),className:"mt-1 text-sm text-brand-600 hover:text-brand-700 font-medium",children:"Create the first one"})]}),s.length>0&&o.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 overflow-hidden shadow-sm",children:[o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-slate-200 bg-slate-50 text-xs text-slate-500 uppercase tracking-wide",children:[o.jsx("th",{className:"px-4 py-3 text-left font-medium w-10",children:"#"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Name"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Description"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Frames"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Status"}),o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Created"}),v&&o.jsx("th",{className:"px-4 py-3 text-left font-medium",children:"Actions"})]})}),o.jsx("tbody",{className:"divide-y divide-slate-100",children:s.map(y=>o.jsxs("tr",{className:"hover:bg-slate-50 transition-colors cursor-pointer",onClick:()=>t(y),children:[o.jsx("td",{className:"px-4 py-3 text-slate-400 tabular-nums",children:y.id}),o.jsx("td",{className:"px-4 py-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(mb,{size:14,className:"text-slate-400 shrink-0"}),o.jsx("span",{className:"font-medium text-slate-800",children:y.name})]})}),o.jsx("td",{className:"px-4 py-3 text-slate-500 max-w-xs",children:y.description?o.jsx("span",{className:"truncate block",title:y.description,children:y.description}):o.jsx("span",{className:"text-slate-300",children:"—"})}),o.jsx("td",{className:"px-4 py-3",children:o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(Yj,{size:12,className:"text-slate-400"}),o.jsx("span",{className:"tabular-nums font-medium text-slate-700",children:y.frame_count})]})}),o.jsx("td",{className:"px-4 py-3",children:o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border capitalize ${NT[y.status]??"bg-slate-100 text-slate-600 border-slate-200"}`,children:y.status})}),o.jsx("td",{className:"px-4 py-3 text-slate-500 whitespace-nowrap",children:ET(y.created_at)}),v&&o.jsx("td",{className:"px-4 py-3",onClick:N=>N.stopPropagation(),children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("button",{onClick:()=>f(y),className:"text-xs text-brand-600 hover:text-brand-800 font-medium transition",children:"+ Add frames"}),o.jsxs("button",{onClick:()=>g(y),disabled:y.frame_count===0||y.status==="building",className:`flex items-center gap-1 text-xs text-violet-600 hover:text-violet-800 font-medium transition disabled:opacity-40 disabled:cursor-not-allowed`,title:y.status==="building"?"Export in progress…":"Export to GCS",children:[o.jsx(cb,{size:12}),y.status==="building"?"Building…":y.status==="exported"?"Re-export":"Export"]})]})})]},y.id))})]}),o.jsxs("div",{className:"px-4 py-2.5 border-t border-slate-100 bg-slate-50 text-xs text-slate-400",children:[s.length," dataset",s.length!==1?"s":""]})]})]}),c&&o.jsx(jT,{onClose:()=>u(!1),onCreate:k}),d&&o.jsx(CT,{dataset:d,onClose:()=>f(null),onAdded:x}),h&&o.jsx(wT,{dataset:h,onClose:()=>g(null),onExported:p})]})}const BT={approved:{label:"Approved",dot:"bg-emerald-500"},to_discuss:{label:"To Discuss",dot:"bg-amber-500"},remove:{label:"Remove",dot:"bg-red-500"}},TT={clear:{label:"Clear",dot:"bg-sky-500"},spiral:{label:"Spiral",dot:"bg-amber-500"},white:{label:"White",dot:"bg-slate-400"},outside:{label:"Outside",dot:"bg-violet-400"}},PT=[{value:"all",label:"All"},{value:null,label:"Untagged"},{value:"approved",label:"Approved"},{value:"to_discuss",label:"Discuss"},{value:"remove",label:"Remove"}],zT=[{value:"all",label:"All"},{value:null,label:"Unknown"},{value:"clear",label:"Clear"},{value:"spiral",label:"Spiral"},{value:"white",label:"White"},{value:"outside",label:"Outside"}];function Qy({filters:t,active:e,onChange:s}){return o.jsx("div",{className:"flex flex-wrap gap-1",children:t.map(n=>{const r=e===n.value;return o.jsx("button",{onClick:()=>s(n.value),className:`px-2 py-0.5 rounded-full text-[10px] font-medium transition ${r?"bg-brand-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,children:n.label},String(n.value))})})}function AT({frames:t,total:e,selectedFrame:s,onSelect:n,tagFilter:r,onTagFilterChange:i,tubeFilter:a,onTubeFilterChange:l,hasMore:c,loadingMore:u,onLoadMore:d}){const f=m.useRef(null);return m.useEffect(()=>{const h=f.current;if(!h)return;const g=new IntersectionObserver(([v])=>{v.isIntersecting&&c&&!u&&d()},{threshold:.1});return g.observe(h),()=>g.disconnect()},[c,u,d]),o.jsxs("div",{className:"flex flex-col h-full w-60 shrink-0 border-r border-slate-200 bg-white",children:[o.jsxs("div",{className:"px-3 pt-3 pb-2 border-b border-slate-200 shrink-0 space-y-2",children:[o.jsxs("div",{className:"text-xs font-semibold text-slate-700",children:["Frames ",o.jsxs("span",{className:"font-normal text-slate-400",children:["(",t.length,e>t.length?` / ${e}`:"",")"]})]}),o.jsx(Qy,{filters:PT,active:r,onChange:i}),o.jsxs("div",{className:"pt-1 border-t border-slate-100",children:[o.jsx("div",{className:"text-[9px] font-semibold uppercase tracking-wider text-slate-400 mb-1",children:"Tube type"}),o.jsx(Qy,{filters:zT,active:a,onChange:l})]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto divide-y divide-slate-100",children:[t.length===0&&o.jsx("div",{className:"flex items-center justify-center h-24 text-xs text-slate-400",children:"No frames"}),t.map(h=>{const g=(s==null?void 0:s.id)===h.id,v=h.review_tag?BT[h.review_tag]:null,_=h.tube_type?TT[h.tube_type]:null,k=h.manual_annotation_count!=null||h.ai_annotation_count!=null,x=h.manual_annotation_count??h.annotation_count??0,p=h.ai_annotation_count??0,y=h.annotation_count??x+p;return o.jsxs("button",{onClick:()=>n(h),className:`w-full flex items-start gap-2.5 px-3 py-2.5 text-left transition-colors border-l-2 ${g?"bg-brand-50 border-brand-600":"border-transparent hover:bg-slate-50"}`,children:[o.jsx("div",{className:"w-14 h-10 bg-slate-100 rounded shrink-0 overflow-hidden flex items-center justify-center",children:h.signed_frame_url?o.jsx("img",{src:h.signed_frame_url,alt:"",className:"w-full h-full object-cover",loading:"lazy"}):o.jsx(pb,{size:14,className:"text-slate-300"})}),o.jsxs("div",{className:"flex-1 min-w-0 space-y-0.5",children:[o.jsxs("div",{className:"text-xs font-medium text-slate-700",children:["#",h.id]}),o.jsx("div",{className:"text-[10px] text-slate-400",children:k?`${x} manual + ${p} AI (${y} total)`:`${y} ann.`}),_&&o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${_.dot}`}),o.jsx("span",{className:"text-[10px] text-slate-500",children:_.label})]}),v&&o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${v.dot}`}),o.jsx("span",{className:"text-[10px] text-slate-500",children:v.label})]})]})]},h.id)}),o.jsx("div",{ref:f,className:"h-1"}),u&&o.jsxs("div",{className:"flex items-center justify-center gap-2 py-3 text-xs text-slate-400",children:[o.jsx(Ce,{className:"animate-spin",size:12}),"Loading…"]})]})]})}const RT=[{key:null,icon:Jj,label:"Select"},{key:"rect",icon:lg,label:"Box"},{key:"rotated_rect",icon:ub,label:"Rotated box"},{key:"annular_sector",icon:xb,label:"Arc sector"}],FT=[{key:"approved",label:"Approved",icon:zn,active:"bg-emerald-500 text-white border-emerald-500"},{key:"to_discuss",label:"To Discuss",icon:Kj,active:"bg-amber-500 text-white border-amber-500"},{key:"remove",label:"Remove",icon:js,active:"bg-red-500 text-white border-red-500"}],LT=[{value:"",label:"— type"},{value:"clear",label:"Clear"},{value:"spiral",label:"Spiral"},{value:"white",label:"White"},{value:"outside",label:"Outside"}];function IT({frame:t,annotations:e,modelAnnotations:s=[],classes:n,tool:r,selectedAnnIdx:i,selectedModelIdx:a=null,saving:l,predictingFrame:c,onToolChange:u,onAdd:d,onChange:f,onDelete:h,onSelect:g,onModelApprove:v,onModelRemove:_,onTagChange:k,onTubeTypeChange:x,onPredict:p,onPrev:y,onNext:N,hasPrev:j,hasNext:w}){const B=m.useRef(null),T=m.useRef(null);return t?o.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-slate-900 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-slate-800 border-b border-slate-700 shrink-0",children:[o.jsx("span",{className:"text-xs text-slate-500 shrink-0",children:"Tag:"}),FT.map(({key:O,label:C,icon:q,active:V})=>{const I=t.review_tag===O;return o.jsxs("button",{onClick:()=>k(I?null:O),title:C,className:`flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border transition ${I?V:"bg-slate-700 text-slate-300 border-slate-600 hover:bg-slate-600 hover:text-white"}`,children:[o.jsx(q,{size:11}),C]},O)}),o.jsxs("div",{className:"flex items-center gap-1.5 ml-2 border-l border-slate-700 pl-3",children:[o.jsx("span",{className:"text-xs text-slate-500 shrink-0",children:"Tube:"}),o.jsx("select",{value:t.tube_type??"",onChange:O=>x(O.target.value||null),className:`text-xs bg-slate-700 border border-slate-600 rounded px-2 py-0.5 text-slate-200 focus:outline-none focus:ring-1 focus:ring-brand-500`,children:LT.map(O=>o.jsx("option",{value:O.value,children:O.label},O.value))})]}),o.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[l&&o.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-slate-400",children:[o.jsx(Ce,{size:11,className:"animate-spin"}),"Saving…"]}),p&&o.jsxs("button",{onClick:p,disabled:!t.signed_frame_url||c,title:"Run AI prediction on this frame",className:`flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium border transition text-amber-400 border-amber-500/40 hover:bg-amber-500/10 disabled:opacity-30`,children:[c?o.jsx(Ce,{size:11,className:"animate-spin"}):o.jsx(yu,{size:11}),"Predict"]}),o.jsxs("div",{className:"flex items-center gap-1 border-l border-slate-700 pl-2",children:[o.jsx("button",{onClick:y,disabled:!j,title:"Previous frame",className:"p-1 rounded text-slate-400 hover:text-white hover:bg-slate-700 disabled:opacity-25 transition",children:o.jsx(Lh,{size:16})}),o.jsxs("span",{className:"text-xs text-slate-500 tabular-nums min-w-12 text-center",children:["#",t.id]}),o.jsx("button",{onClick:N,disabled:!w,title:"Next frame",className:"p-1 rounded text-slate-400 hover:text-white hover:bg-slate-700 disabled:opacity-25 transition",children:o.jsx(Fh,{size:16})})]})]})]}),o.jsx("div",{className:"flex-1 relative overflow-hidden",ref:B,children:t.signed_frame_url?o.jsxs(o.Fragment,{children:[o.jsx("img",{ref:T,src:t.signed_frame_url,alt:`Frame #${t.id}`,className:"w-full h-full object-contain",draggable:!1}),o.jsx(ww,{containerRef:B,videoRef:T,tool:r,annotations:e,modelAnnotations:s,selectedIdx:i,selectedModelIdx:a,classes:n,onAdd:d,onChange:f,onDelete:h,onSelect:g,onModelApprove:v,onModelDelete:_})]}):o.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-slate-500",children:[o.jsx(pb,{size:36,className:"text-slate-600"}),o.jsx("p",{className:"text-sm",children:"Image not yet extracted"}),o.jsxs("p",{className:"text-xs text-slate-600",children:["Frame #",t.id," · Ask an admin to run frame extraction for this job"]})]})}),o.jsx("div",{className:"flex items-center gap-1 px-4 py-2 bg-slate-800 border-t border-slate-700 shrink-0",children:RT.map(({key:O,icon:C,label:q})=>o.jsxs("button",{title:q,onClick:()=>u(O===r?null:O),className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs font-medium transition ${r===O?"bg-brand-600 text-white":"text-slate-400 hover:text-white hover:bg-slate-700"}`,children:[o.jsx(C,{size:13}),q]},String(O)))})]}):o.jsx("div",{className:"flex-1 flex items-center justify-center text-slate-500 text-sm bg-slate-50",children:"Select a frame from the list"})}const Op=["#ef4444","#3b82f6","#22c55e","#f59e0b","#a855f7","#06b6d4","#f97316","#84cc16","#ec4899","#14b8a6"];function Yy(t,e){if(!(e!=null&&e.length))return Op[0];const s=e.findIndex(r=>r.name===t),n=e[s];return n!=null&&n.color?n.color:Op[Math.max(0,s)%Op.length]}const OT=[{key:"low",label:"Low",active:"bg-emerald-500 text-white border-emerald-500"},{key:"medium",label:"Med",active:"bg-amber-500 text-white border-amber-500"},{key:"high",label:"High",active:"bg-red-500 text-white border-red-500"}];function DT({annotations:t,modelAnnotations:e=[],selectedIdx:s,selectedModelIdx:n=null,classes:r,onSelect:i,onUpdate:a,onDelete:l,onModelApprove:c,onModelRemove:u}){var f;const d=s!=null?t[s]:null;return o.jsxs("div",{className:"flex flex-col h-full w-72 shrink-0 border-l border-slate-200 bg-white",children:[o.jsx("div",{className:"px-4 py-3 border-b border-slate-200 shrink-0",children:o.jsxs("h3",{className:"text-sm font-semibold text-slate-700",children:["Annotations"," ",o.jsxs("span",{className:"font-normal text-slate-400",children:["(",t.length,")"]})]})}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:t.length===0?o.jsx("div",{className:"flex items-center justify-center h-20 text-xs text-slate-400",children:"No annotations"}):o.jsx("div",{className:"divide-y divide-slate-100",children:t.map((h,g)=>{const v=Yy(h.class_name,r),_=g===s;return o.jsxs("button",{onClick:()=>i(_?null:g),className:`w-full flex items-center gap-2.5 px-4 py-2.5 text-left transition-colors ${_?"bg-brand-50":"hover:bg-slate-50"}`,children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-sm shrink-0",style:{background:v}}),o.jsx("span",{className:"flex-1 text-xs font-medium text-slate-700 truncate",children:h.class_name}),o.jsx("span",{className:`text-[10px] font-semibold px-1.5 py-0.5 rounded uppercase shrink-0 ${h.severity==="high"?"bg-red-100 text-red-700":h.severity==="medium"?"bg-amber-100 text-amber-700":"bg-emerald-100 text-emerald-700"}`,children:(h.severity??"low")[0]})]},g)})})}),e.length>0&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"px-4 py-3 border-t border-slate-200 bg-violet-50 shrink-0",children:[o.jsxs("h3",{className:"text-sm font-semibold text-violet-900",children:["AI Predictions"," ",o.jsxs("span",{className:"font-normal text-violet-600",children:["(",e.length,")"]})]}),o.jsx("p",{className:"text-[11px] text-violet-700 mt-1",children:"Review and approve predicted boxes to add them to the dataset"})]}),o.jsx("div",{className:"max-h-52 overflow-y-auto border-t border-slate-100",children:o.jsx("div",{className:"divide-y divide-slate-100",children:e.map((h,g)=>{const v=Yy(h.class_name,r),_=g===n;return o.jsxs("div",{className:`p-3 space-y-2 transition-colors ${_?"bg-violet-100":"hover:bg-slate-50"}`,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-sm shrink-0",style:{background:v}}),o.jsx("span",{className:"flex-1 text-xs font-medium text-slate-700",children:h.class_name}),h.confidence&&o.jsxs("span",{className:"text-[10px] text-slate-500",children:[(h.confidence*100).toFixed(0),"%"]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsxs("button",{onClick:()=>c==null?void 0:c(g),className:`flex-1 flex items-center justify-center gap-1 text-xs bg-emerald-600 hover:bg-emerald-700 text-white py-1.5 rounded transition`,children:[o.jsx(zn,{size:11})," Approve"]}),o.jsx("button",{onClick:()=>u==null?void 0:u(g),className:`flex items-center justify-center gap-1 text-xs text-red-500 hover:text-red-700 transition px-2 py-1.5`,children:o.jsx(sd,{size:11})})]})]},g)})})})]}),d&&o.jsxs("div",{className:"border-t border-slate-200 p-4 space-y-3 shrink-0 bg-slate-50",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-[10px] font-semibold text-slate-500 uppercase tracking-wide mb-1.5",children:"Class"}),o.jsxs("select",{value:d.class_name,onChange:h=>a(s,{...d,class_name:h.target.value}),className:`w-full text-xs bg-white border border-slate-300 rounded-md px-2.5 py-1.5 text-slate-700 focus:outline-none focus:ring-1 focus:ring-brand-500 focus:border-brand-500`,children:[r.map(h=>o.jsx("option",{value:h.name,children:h.display_name??h.name},h.name)),!r.some(h=>h.name===d.class_name)&&o.jsx("option",{value:d.class_name,children:d.class_name})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-[10px] font-semibold text-slate-500 uppercase tracking-wide mb-1.5",children:"Severity"}),o.jsx("div",{className:"flex gap-1.5",children:OT.map(({key:h,label:g,active:v})=>o.jsx("button",{onClick:()=>a(s,{...d,severity:h}),className:`flex-1 text-xs font-semibold py-1 rounded border transition ${d.severity===h?v:"bg-white text-slate-600 border-slate-300 hover:bg-slate-100"}`,children:g},h))})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[10px] text-slate-400 uppercase tracking-wide",children:(f=d.shape_type)==null?void 0:f.replace("_"," ")}),o.jsxs("button",{onClick:()=>l(s),className:"flex items-center gap-1 text-xs text-red-500 hover:text-red-700 transition",children:[o.jsx(sd,{size:12}),"Delete"]})]})]})]})}const Xy=40,ah=180,Dp=new Map;function MT(t,e){const s=t.getBoundingClientRect();let n=s.left+s.width/2-ah/2,r=s.top-e-8;return n=Math.max(8,Math.min(n,window.innerWidth-ah-8)),r<8&&(r=s.bottom+8),{left:n,top:r}}const VT=["low","medium","high"],HT=["L","M","H"],$T=["bg-emerald-500 text-white","bg-amber-500 text-white","bg-red-500 text-white"];function WT({frameId:t,frameUrl:e,annotation:s,currentSev:n,maxWidth:r,onSeverityChange:i,onDelete:a,onPreview:l}){const c=r??150,[u,d]=m.useState(s.thumbnail_url??null),[f,h]=m.useState(!s.thumbnail_url),[g,v]=m.useState(!1),[_,k]=m.useState(!1),[x,p]=m.useState(!1),y=m.useRef(null);m.useEffect(()=>{if(s.thumbnail_url&&!g){d(s.thumbnail_url),h(!1);return}let w=!1;h(!0),d(null);async function B(){try{let T;if(Dp.has(e)?T=Dp.get(e):(T=await new Promise((Z,K)=>{const $=new Image;$.crossOrigin="anonymous",$.onload=()=>Z($),$.onerror=K,$.src=e}),Dp.set(e,T)),w)return;const{cx:O,cy:C,w:q,h:V}=s,I=T.naturalWidth,ne=T.naturalHeight,X=Math.abs(q),pe=Math.abs(V),D=(O-X/2)*I,R=(C-pe/2)*ne,U=X*I,z=pe*ne;if(U<1||z<1){h(!1);return}const G=U>c?c/U:U{w=!0}},[e,s.thumbnail_url,g,s.cx,s.cy,s.w,s.h,c]);const N=w=>{w.dataTransfer.setData("text/plain",JSON.stringify({annId:s.id,currentSev:n})),w.dataTransfer.effectAllowed="move"},j=_&&y.current?MT(y.current,x?82:50):null;return f?o.jsx("div",{style:{width:c,height:Math.round(c*.67)},className:"bg-slate-100 rounded animate-pulse shrink-0"}):u?o.jsxs("div",{ref:y,style:{maxWidth:c},className:`inline-block rounded overflow-hidden cursor-pointer border-2 border-transparent hover:border-brand-400 transition-all shrink-0`,draggable:!x,onDragStart:N,onClick:()=>{x||l==null||l()},onMouseEnter:()=>k(!0),onMouseLeave:()=>{k(!1),p(!1)},title:`Frame #${t} · ${s.class_name}`,children:[o.jsx("img",{src:u,alt:"",className:"block w-full",draggable:!1,onError:()=>{v(!0),d(null),e&&h(!0)}}),_&&!x&&j&&o.jsxs("div",{className:"fixed z-50 bg-white border border-slate-200 rounded-lg shadow-xl p-2 flex flex-col gap-1.5",style:{width:ah,left:j.left,top:j.top},children:[o.jsxs("div",{className:"flex gap-1 items-center",children:[VT.map((w,B)=>o.jsx("button",{onClick:T=>{T.stopPropagation(),w!==n&&i(w)},className:`flex-1 text-xs font-semibold py-1 rounded transition ${w===n?$T[B]:"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,children:HT[B]},w)),o.jsx("button",{onClick:w=>{w.stopPropagation(),p(!0)},className:"px-2 py-1 text-xs text-red-500 hover:bg-red-50 rounded transition",title:"Delete annotation",children:"×"})]}),o.jsxs("span",{className:"text-[10px] text-slate-400 truncate",children:["Frame #",t," · ",s.class_name]})]}),_&&x&&j&&o.jsxs("div",{className:"fixed z-50 bg-white border border-slate-200 rounded-lg shadow-xl p-2 flex flex-col gap-2",style:{width:ah,left:j.left,top:j.top},children:[o.jsx("span",{className:"text-xs text-slate-700",children:"Delete this annotation?"}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:w=>{w.stopPropagation(),a()},className:"flex-1 text-xs bg-red-500 text-white py-1 rounded hover:bg-red-600 transition",children:"Yes, delete"}),o.jsx("button",{onClick:w=>{w.stopPropagation(),p(!1)},className:"flex-1 text-xs bg-slate-100 text-slate-600 py-1 rounded hover:bg-slate-200 transition",children:"Cancel"})]})]})]}):null}const GT={low:"#22c55e",medium:"#f59e0b",high:"#ef4444"};function qT({frameId:t,frameUrl:e,annotations:s,highlightAnnId:n,onClose:r}){const[i,a]=m.useState(null),l=m.useRef(null);m.useEffect(()=>{const u=d=>{d.key==="Escape"&&r()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[r]);const c=s.find(u=>u.id===n);return o.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-6",onClick:r,children:o.jsxs("div",{className:"bg-white rounded-xl shadow-2xl flex flex-col max-w-4xl max-h-full w-full overflow-hidden",onClick:u=>u.stopPropagation(),children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-slate-200 shrink-0",children:[o.jsxs("span",{className:"text-sm font-semibold text-slate-700",children:["Frame #",t]}),o.jsx("button",{onClick:r,className:"text-slate-400 hover:text-slate-700 transition",children:o.jsx(js,{size:18})})]}),o.jsx("div",{className:"flex-1 overflow-auto bg-slate-900 flex items-center justify-center p-4 min-h-0",children:o.jsxs("div",{className:"relative inline-block",children:[o.jsx("img",{ref:l,src:e,alt:"",className:"block max-w-full max-h-[70vh]",onLoad:u=>a({w:u.target.clientWidth,h:u.target.clientHeight}),draggable:!1}),i&&o.jsx("svg",{className:"absolute inset-0 pointer-events-none",width:i.w,height:i.h,children:s.map(u=>{if(u.cx==null||u.cy==null||u.w==null||u.h==null)return null;const d=Math.abs(u.w),f=Math.abs(u.h),h=(u.cx-d/2)*i.w,g=(u.cy-f/2)*i.h,v=d*i.w,_=f*i.h,k=u.id===n,x=GT[u.severity??"low"];return o.jsxs("g",{children:[o.jsx("rect",{x:h,y:g,width:v,height:_,fill:k?`${x}22`:"none",stroke:x,strokeWidth:k?2.5:1.5,opacity:k?1:.4,strokeDasharray:k?void 0:"5 3"}),k&&o.jsx("text",{x:h+3,y:g>14?g-4:g+_+13,fill:x,fontSize:11,fontFamily:"system-ui, sans-serif",fontWeight:"600",children:u.class_name})]},u.id??`${u.class_name}-${h}-${g}-${v}-${_}`)})})]})}),c&&o.jsxs("div",{className:"px-4 py-3 border-t border-slate-200 shrink-0 flex items-center gap-3",children:[o.jsx("span",{className:`text-xs font-semibold px-2 py-0.5 rounded uppercase ${c.severity==="high"?"bg-red-100 text-red-700":c.severity==="medium"?"bg-amber-100 text-amber-700":"bg-emerald-100 text-emerald-700"}`,children:c.severity??"low"}),o.jsx("span",{className:"text-sm text-slate-600",children:c.class_name}),o.jsxs("span",{className:"text-xs text-slate-400 ml-auto",children:[s.length," annotation",s.length!==1?"s":""," on this frame"]})]})]})})}const Gd=[{key:"low",label:"Low",header:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-200"},{key:"medium",label:"Medium",header:"text-amber-600",bg:"bg-amber-50",border:"border-amber-200"},{key:"high",label:"High",header:"text-red-600",bg:"bg-red-50",border:"border-red-200"}],JT=[{label:"S (80px)",value:80},{label:"M (150px)",value:150},{label:"L (250px)",value:250},{label:"XL (400px)",value:400}],Zy=50;function Ew(t,e){return`severity_${t}_${e}`}function e_(t,e,s){try{return localStorage.getItem(Ew(t,e))??s}catch{return s}}function t_(t,e,s){try{localStorage.setItem(Ew(t,e),s)}catch{}}const nr=()=>({items:[],total:null,page:0,loading:!0,hasMore:!0});function KT({datasetId:t,classes:e}){const[s,n]=m.useState(()=>e_(t,"class","all")),[r,i]=m.useState(()=>parseInt(e_(t,"zoom","150"))),[a,l]=m.useState(null),[c,u]=m.useState(null),[d,f]=m.useState({low:nr(),medium:nr(),high:nr()}),h=m.useRef(0),g=m.useRef({low:!1,medium:!1,high:!1}),v=m.useRef({low:null,medium:null,high:null});m.useEffect(()=>{const w=++h.current;g.current={low:!1,medium:!1,high:!1},f({low:nr(),medium:nr(),high:nr()});for(const B of["low","medium","high"])g.current[B]=!0,Ky(t,{page:1,pageSize:Zy,className:s==="all"?null:s,severity:B}).then(T=>{g.current[B]=!1,w===h.current&&f(O=>({...O,[B]:{items:T.items,total:T.total,page:1,loading:!1,hasMore:T.has_more}}))}).catch(()=>{g.current[B]=!1,w===h.current&&f(T=>({...T,[B]:{...T[B],loading:!1}}))})},[t,s]);const _=m.useCallback(async w=>{if(g.current[w])return;let B;if(f(O=>{const C=O[w];return C.hasMore?(B=C.page+1,{...O,[w]:{...C,loading:!0}}):O}),B===void 0)return;g.current[w]=!0;const T=h.current;try{const O=await Ky(t,{page:B,pageSize:Zy,className:s==="all"?null:s,severity:w});if(g.current[w]=!1,T!==h.current)return;f(C=>({...C,[w]:{items:[...C[w].items,...O.items],total:O.total,page:B,loading:!1,hasMore:O.has_more}}))}catch{if(g.current[w]=!1,T!==h.current)return;f(O=>({...O,[w]:{...O[w],loading:!1}}))}},[t,s]);m.useEffect(()=>{const w=new IntersectionObserver(B=>{B.forEach(T=>{T.isIntersecting&&_(T.target.dataset.sev)})},{rootMargin:"100px 0px"});for(const B of["low","medium","high"]){const T=v.current[B];T&&w.observe(T)}return()=>w.disconnect()},[_]);const k=m.useCallback(async(w,B,T)=>{if(B===T)return;let O;f(C=>{const q=C[B].items,V=q.findIndex(ne=>ne.annotation.id===w);if(V===-1)return C;O=q[V];const I={...O.annotation,severity:T};return{...C,[B]:{...C[B],items:q.filter((ne,X)=>X!==V),total:Math.max(0,(C[B].total??1)-1)},[T]:{...C[T],items:[{...O,annotation:I},...C[T].items],total:(C[T].total??0)+1}}});try{await C6(w,T)}catch(C){console.error("Failed to update severity",C),f(q=>{const V=q[T].items,I=V.findIndex(pe=>pe.annotation.id===w);if(I===-1)return q;const ne=V[I],X={...ne,annotation:{...ne.annotation,severity:B}};return{...q,[T]:{...q[T],items:V.filter((pe,D)=>D!==I),total:Math.max(0,(q[T].total??1)-1)},[B]:{...q[B],items:[X,...q[B].items],total:(q[B].total??0)+1}}})}},[]),x=m.useCallback(async(w,B)=>{f(T=>({...T,[B]:{...T[B],items:T[B].items.filter(O=>O.annotation.id!==w),total:Math.max(0,(T[B].total??1)-1)}}));try{await U6(w)}catch(T){console.error("Failed to delete annotation",T)}},[]),p=m.useCallback((w,B)=>{B.preventDefault(),l(null);const T=B.dataTransfer.getData("text/plain");if(!T)return;const{annId:O,currentSev:C}=JSON.parse(T);k(O,C,w)},[k]),y=m.useMemo(()=>{if(!c)return[];const w=[];for(const{key:B}of Gd)for(const T of d[B].items)T.frame_id===c.frameId&&w.push(T.annotation);return w},[c,d]),N=Gd.some(w=>d[w.key].loading),j=Gd.reduce((w,B)=>w+d[B.key].items.length,0);return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[o.jsxs("div",{className:"flex items-center gap-4 px-4 py-2 border-b border-slate-200 bg-white shrink-0 flex-wrap",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"text-xs text-slate-500",children:"Class"}),o.jsxs("select",{value:s,onChange:w=>{t_(t,"class",w.target.value),n(w.target.value)},className:`text-xs border border-slate-300 rounded-md px-2 py-1 text-slate-700 bg-white\r focus:outline-none focus:ring-1 focus:ring-brand-500`,children:[o.jsx("option",{value:"all",children:"All classes"}),e.map(w=>o.jsx("option",{value:w.name,children:w.display_name??w.name},w.name))]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"text-xs text-slate-500",children:"Zoom"}),o.jsx("select",{value:r,onChange:w=>{const B=parseInt(w.target.value);t_(t,"zoom",String(B)),i(B)},className:`text-xs border border-slate-300 rounded-md px-2 py-1 text-slate-700 bg-white\r focus:outline-none focus:ring-1 focus:ring-brand-500`,children:JT.map(w=>o.jsx("option",{value:w.value,children:w.label},w.value))})]}),o.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[N&&o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-slate-400",children:[o.jsx(Ce,{className:"animate-spin",size:11}),o.jsx("span",{children:"Loading…"})]}),!N&&o.jsxs("span",{className:"text-xs text-slate-400",children:[j," annotation",j!==1?"s":""," (approved frames only)"]}),o.jsx("span",{className:"text-xs text-slate-300",children:"Drag to reassign В· hover for actions"})]})]}),o.jsx("div",{className:"flex flex-1 overflow-hidden",children:Gd.map(({key:w,label:B,header:T,bg:O,border:C})=>{const q=d[w];return o.jsxs("div",{className:`flex flex-col flex-1 border-r border-slate-200 last:border-r-0 overflow-hidden ${a===w?"ring-2 ring-inset ring-brand-400":""}`,onDragOver:V=>{V.preventDefault(),V.dataTransfer.dropEffect="move",l(w)},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||l(null)},onDrop:V=>p(w,V),children:[o.jsxs("div",{className:`flex items-center justify-between px-3 py-2 border-b ${C} ${O} shrink-0`,children:[o.jsx("span",{className:`text-sm font-semibold ${T}`,children:B}),o.jsx("span",{className:"text-xs text-slate-400",children:q.items.length})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-2 flex flex-wrap gap-2 content-start",children:[q.items.filter(V=>V.annotation).map(V=>o.jsx(WT,{frameId:V.frame_id,frameUrl:V.signed_frame_url,annotation:V.annotation,currentSev:w,maxWidth:r,onSeverityChange:I=>k(V.annotation.id,w,I),onDelete:()=>x(V.annotation.id,w),onPreview:()=>u({annId:V.annotation.id,frameId:V.frame_id,frameUrl:V.signed_frame_url})},V.annotation.id)),q.items.length===0&&!q.loading&&o.jsx("div",{className:"w-full flex items-center justify-center py-10 text-xs text-slate-300",children:"No annotations"}),q.loading&&o.jsx("div",{className:"w-full flex items-center justify-center py-4",children:o.jsx(Ce,{className:"animate-spin text-slate-300",size:16})}),o.jsx("div",{ref:V=>{v.current[w]=V},"data-sev":w,className:"w-full h-2","aria-hidden":"true"})]})]},w)})})]}),c&&o.jsx(qT,{frameId:c.frameId,frameUrl:c.frameUrl,annotations:y,highlightAnnId:c.annId,onClose:()=>u(null)})]})}const hu={damage_deformed:"deformation",damage_peeling:"peeling",damage_scratch:"scratch",contamination_dirt:"dirt",contamination_fluid:"fluid",contamination_stain:"Stain",contamination_lint_fiber:"Lint/Fiber"};function QT(t){return{class_name:t.class_name,shape_type:t.shape_type,cx:t.cx??null,cy:t.cy??null,w:t.w??null,h:t.h??null,points:t.points??null,severity:t.severity??"low",is_ai_suggestion:t.is_ai_suggestion??!1,confidence:t.confidence??null,mlflow_run_id:t.mlflow_run_id??null}}function YT({dataset:t,onBack:e}){const[s,n]=m.useState([]),[r,i]=m.useState(0),[a,l]=m.useState(!1),[c,u]=m.useState([]),[d,f]=m.useState(null),[h,g]=m.useState([]),[v,_]=m.useState([]),[k,x]=m.useState(null),[p,y]=m.useState(null),[N,j]=m.useState("edit"),[w,B]=m.useState("all"),[T,O]=m.useState("all"),[C,q]=m.useState(null),[V,I]=m.useState(!1),[ne,X]=m.useState(!0),[pe,D]=m.useState(!1),[R,U]=m.useState(!1),[z,G]=m.useState(!1),[te,Z]=m.useState(""),K=m.useRef(null),$=m.useRef(!1),ee=m.useRef(null),re=m.useRef([]),ie=m.useRef(1);m.useEffect(()=>{re.current=h},[h]),m.useEffect(()=>{Vh().then(u).catch(()=>{})},[]),m.useEffect(()=>{let S=!1;return X(!0),n([]),i(0),l(!1),ie.current=1,Jy(t.id,{page:1,pageSize:25,tag:w,tubeType:T}).then(E=>{if(S)return;n(E.items),i(E.total),l(E.has_more);const F=E.items.find(L=>!L.review_tag)??E.items[0];F&&Ge(F,!1)}).catch(E=>{var F,L;S||Z(((L=(F=E.response)==null?void 0:F.data)==null?void 0:L.detail)??"Failed to load dataset.")}).finally(()=>{S||X(!1)}),()=>{S=!0}},[t.id,w,T]);const ge=m.useCallback(async()=>{if(pe||!a)return;D(!0);const S=ie.current+1;try{const E=await Jy(t.id,{page:S,pageSize:25,tag:w,tubeType:T});n(F=>[...F,...E.items]),i(E.total),l(E.has_more),ie.current=S}catch{}finally{D(!1)}},[t.id,w,T,pe,a]);m.useEffect(()=>{function S(E){["INPUT","TEXTAREA","SELECT"].includes(E.target.tagName)||(E.key==="ArrowLeft"&&Et(),E.key==="ArrowRight"&&ms())}return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[d,s]);const We=m.useCallback(async(S,E)=>{if(S){I(!0);try{await j6(S,E.map(QT)),n(F=>F.map(L=>L.id===S?{...L,manual_annotation_count:E.length,annotation_count:E.length+(L.ai_annotation_count??0)}:L))}catch(F){console.error("Failed to save annotations",F)}finally{I(!1)}}},[]),Ye=m.useCallback(async()=>{clearTimeout(K.current),$.current&&ee.current&&($.current=!1,await We(ee.current,re.current))},[We]);function Ue(S,E){$.current=!0,clearTimeout(K.current),K.current=setTimeout(()=>{$.current=!1,We(S,E)},700)}async function Pt(){var S,E;if(!(!d||z)){G(!0),Z("");try{const F=await Ry(d.id);ee.current===d.id&&g(L=>{const W=L.filter(le=>!le.is_ai_suggestion),Q=F.map(le=>({...le,class_name:hu[le.class_name]??le.class_name}));return _(Q),n(le=>le.map(he=>he.id===d.id?{...he,manual_annotation_count:W.length,ai_annotation_count:Q.length,annotation_count:W.length+Q.length}:he)),W})}catch(F){Z(((E=(S=F.response)==null?void 0:S.data)==null?void 0:E.detail)??"Frame prediction failed")}finally{G(!1)}}}async function Ge(S,E=!0){E&&await Ye(),f(S),x(null),y(null),_([]),ee.current=S.id,$.current=!1,G(!1),U(!0),g([]);try{const F=await gw(S.id);if(ee.current!==S.id)return;const L=F.filter(Q=>!Q.is_ai_suggestion).map(Q=>({...Q,class_name:hu[Q.class_name]??Q.class_name})),W=F.filter(Q=>Q.is_ai_suggestion).map(Q=>({...Q,class_name:hu[Q.class_name]??Q.class_name}));if(g(L),_(W),n(Q=>Q.map(le=>le.id===S.id?{...le,manual_annotation_count:L.length,ai_annotation_count:W.length,annotation_count:L.length+W.length}:le)),U(!1),S.gcs_frame_path){G(!0);try{const Q=await Ry(S.id);if(ee.current===S.id){const le=Q.map(he=>({...he,class_name:hu[he.class_name]??he.class_name}));_(le),n(he=>he.map(Be=>Be.id===S.id?{...Be,ai_annotation_count:le.length,annotation_count:L.length+le.length}:Be))}}catch{}finally{ee.current===S.id&&G(!1)}}}catch{ee.current===S.id&&(g([]),U(!1))}}const ut=s.findIndex(S=>S.id===(d==null?void 0:d.id));function Et(){ut>0&&Ge(s[ut-1])}function ms(){ut({...F,review_tag:S})),n(F=>F.map(L=>L.id===d.id?{...L,review_tag:S}:L));try{await nh(d.id,{review_tag:S})}catch{f(F=>({...F,review_tag:E})),n(F=>F.map(L=>L.id===d.id?{...L,review_tag:E}:L))}}async function xs(S){if(!d)return;const E=d.tube_type;f(F=>({...F,tube_type:S})),n(F=>F.map(L=>L.id===d.id?{...L,tube_type:S}:L));try{await nh(d.id,{tube_type:S})}catch{f(F=>({...F,tube_type:E})),n(F=>F.map(L=>L.id===d.id?{...L,tube_type:E}:L))}}function Us(S){const E=c[0],F={...S,class_name:(E==null?void 0:E.name)??"unknown",severity:"low",is_ai_suggestion:!1,confidence:null,mlflow_run_id:null},L=[...h,F];g(L),x(L.length-1),Ue(ee.current,L)}function se(S,E){const F=h.map((L,W)=>W===S?E:L);g(F),Ue(ee.current,F)}function me(S){const E=h.filter((F,L)=>L!==S);g(E),x(null),Ue(ee.current,E)}function Se(S,E){const F=h.map((L,W)=>W===S?E:L);g(F),Ue(ee.current,F)}function Ne(S){const E=v[S],F=c[0],L={id:null,shape_type:E.shape_type,cx:E.cx,cy:E.cy,w:E.w,h:E.h,class_name:hu[E.class_name]??E.class_name??(F==null?void 0:F.name)??"unknown",severity:E.severity??"low",confidence:E.confidence??null,mlflow_run_id:E.mlflow_run_id??"inference:approved",is_ai_suggestion:!1},W=[...h,L];g(W),_(Q=>Q.filter((le,he)=>he!==S)),y(null),Ue(ee.current,W)}function b(S){_(E=>E.filter((F,L)=>L!==S)),y(E=>E===null||E===S?null:E>S?E-1:E)}return ne?o.jsxs("div",{className:"flex items-center justify-center h-full gap-3 text-slate-400",children:[o.jsx(Ce,{className:"animate-spin",size:22}),o.jsx("span",{className:"text-sm",children:"Loading dataset…"})]}):o.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-slate-200 bg-white shrink-0",children:[o.jsxs("button",{onClick:async()=>{await Ye(),e()},className:"flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800 transition",children:[o.jsx(dg,{size:15}),"Datasets"]}),o.jsx("span",{className:"text-slate-300",children:"/"}),o.jsx("h1",{className:"text-sm font-semibold text-slate-800",children:t.name}),o.jsxs("span",{className:"text-xs text-slate-400",children:[r," frame",r!==1?"s":""]}),o.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[o.jsx("div",{className:"flex items-center border border-slate-200 rounded-lg p-0.5",children:[["edit","Edit"],["severity","Severity"]].map(([S,E])=>o.jsx("button",{onClick:async()=>{S==="severity"&&await Ye(),j(S)},className:`text-xs px-3 py-1 rounded-md transition ${N===S?"bg-brand-600 text-white":"text-slate-500 hover:text-slate-700"}`,children:E},S))}),te&&o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-red-600",children:[o.jsx(lt,{size:13}),te]})]})]}),N==="severity"?o.jsx(KT,{datasetId:t.id,classes:c}):o.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[o.jsx(AT,{frames:s,total:r,selectedFrame:d,onSelect:Ge,tagFilter:w,onTagFilterChange:B,tubeFilter:T,onTubeFilterChange:O,hasMore:a,loadingMore:pe,onLoadMore:ge}),o.jsx(IT,{frame:d,annotations:R?[]:h,modelAnnotations:v,classes:c,tool:C,selectedAnnIdx:k,selectedModelIdx:p,saving:V,predictingFrame:z,onToolChange:q,onAdd:Us,onChange:se,onDelete:me,onSelect:x,onModelApprove:Ne,onModelRemove:b,onTagChange:tt,onTubeTypeChange:xs,onPredict:Pt,onPrev:Et,onNext:ms,hasPrev:ut>0,hasNext:ute(null)}):o.jsx(UT,{onSelect:e})}const s_=["endoscope","stainless_steel","plastic","other"];function ZT({color:t}){return o.jsx("span",{className:"inline-block w-4 h-4 rounded border border-slate-600",style:{backgroundColor:t??"#94a3b8"}})}function Mp({checked:t,onChange:e}){return o.jsx("button",{onClick:()=>e(!t),className:`relative w-8 h-4 rounded-full transition-colors ${t?"bg-brand-500":"bg-slate-600"}`,children:o.jsx("span",{className:`absolute top-0.5 left-0.5 w-3 h-3 rounded-full bg-white shadow transition-transform ${t?"translate-x-4":""}`})})}function eP(){const[t,e]=m.useState([]),[s,n]=m.useState(!0),[r,i]=m.useState(""),[a,l]=m.useState("all"),[c,u]=m.useState(!1),[d,f]=m.useState(!1),[h,g]=m.useState(!1),[v,_]=m.useState([]),[k,x]=m.useState(!0),[p,y]=m.useState(!1),[N,j]=m.useState({user_id:"",role:"marker"}),[w,B]=m.useState({device_type:"endoscope",name:"",display_name:"",color:"#94a3b8",sort_order:0});async function T(){n(!0),i("");try{const D=await Vh(null,!0);e(D)}catch{i("Failed to load classes.")}finally{n(!1)}}async function O(){x(!0);try{const D=await E3();_(D)}catch{i("Failed to load labelling users.")}finally{x(!1)}}m.useEffect(()=>{T(),O()},[]);async function C(D){if(D.preventDefault(),!!w.name.trim()){g(!0);try{await k6({device_type:w.device_type,name:w.name.trim(),display_name:w.display_name.trim()||null,color:w.color||null,sort_order:Number(w.sort_order)||0}),B({device_type:"endoscope",name:"",display_name:"",color:"#94a3b8",sort_order:0}),f(!1),await T()}catch(R){i((R==null?void 0:R.message)??"Failed to create class.")}finally{g(!1)}}}async function q(D){try{await E6(D.id,{is_active:!D.is_active}),e(R=>R.map(U=>U.id===D.id?{...U,is_active:!U.is_active}:U))}catch{i("Failed to update class.")}}async function V(D){if(window.confirm(`Delete class "${D.name}"? This will fail if annotations reference it.`))try{await N6(D.id),e(R=>R.filter(U=>U.id!==D.id))}catch(R){i((R==null?void 0:R.message)??"Failed to delete class (may be in use).")}}async function I(D){if(D.preventDefault(),!!N.user_id){y(!0);try{await N3({user_id:Number(N.user_id),role:N.role}),j({user_id:"",role:"marker"}),await O()}catch(R){i((R==null?void 0:R.message)??"Failed to add labelling user.")}finally{y(!1)}}}async function ne(D){try{const R=await Cy(D.user_id,{is_active:!D.is_active});_(U=>U.map(z=>z.user_id===R.user_id?R:z))}catch(R){i((R==null?void 0:R.message)??"Failed to update labelling user.")}}async function X(D,R){try{const U=await Cy(D.user_id,{role:R});_(z=>z.map(G=>G.user_id===U.user_id?U:G))}catch(U){i((U==null?void 0:U.message)??"Failed to update labelling user role.")}}const pe=t.filter(D=>!(a!=="all"&&D.device_type!==a||!c&&!D.is_active));return o.jsxs("div",{className:"flex flex-col h-full bg-slate-900 text-white overflow-auto p-6 gap-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-semibold text-slate-100",children:"Annotation Classes"}),o.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:"Manage per-device-type annotation classes used in the labelling UI."})]}),o.jsxs("button",{onClick:()=>f(D=>!D),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium bg-brand-600 hover:bg-brand-500 text-white transition`,children:[o.jsx(fb,{size:15})," Add Class"]})]}),r&&o.jsxs("div",{className:"flex items-center gap-2 text-red-400 bg-red-900/20 border border-red-800/40 rounded-lg px-4 py-3 text-sm",children:[o.jsx(lt,{size:14,className:"shrink-0"}),r,o.jsx("button",{onClick:()=>i(""),className:"ml-auto text-red-500 hover:text-red-300",children:"x"})]}),d&&o.jsxs("form",{onSubmit:C,className:"bg-slate-800 rounded-xl border border-slate-700/50 p-4 grid grid-cols-2 gap-3",children:[o.jsx("p",{className:"col-span-2 text-xs font-semibold uppercase tracking-widest text-slate-400 mb-1",children:"New Class"}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-slate-500 block mb-1",children:"Device type *"}),o.jsx("select",{value:w.device_type,onChange:D=>B(R=>({...R,device_type:D.target.value})),className:"w-full text-sm bg-slate-700 border border-slate-600 rounded-lg px-3 py-1.5 text-slate-200",children:s_.map(D=>o.jsx("option",{value:D,children:D},D))})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-slate-500 block mb-1",children:"Internal name * (snake_case)"}),o.jsx("input",{required:!0,value:w.name,onChange:D=>B(R=>({...R,name:D.target.value})),placeholder:"e.g. deformation",className:"w-full text-sm bg-slate-700 border border-slate-600 rounded-lg px-3 py-1.5 text-slate-200 placeholder-slate-500"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-slate-500 block mb-1",children:"Display name"}),o.jsx("input",{value:w.display_name,onChange:D=>B(R=>({...R,display_name:D.target.value})),placeholder:"e.g. Deformation",className:"w-full text-sm bg-slate-700 border border-slate-600 rounded-lg px-3 py-1.5 text-slate-200 placeholder-slate-500"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-slate-500 block mb-1",children:"Sort order"}),o.jsx("input",{type:"number",value:w.sort_order,onChange:D=>B(R=>({...R,sort_order:D.target.value})),className:"w-full text-sm bg-slate-700 border border-slate-600 rounded-lg px-3 py-1.5 text-slate-200"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-slate-500 block mb-1",children:"Color"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"color",value:w.color,onChange:D=>B(R=>({...R,color:D.target.value})),className:"w-8 h-8 rounded cursor-pointer bg-transparent border-0"}),o.jsx("span",{className:"text-xs text-slate-400 font-mono",children:w.color})]})]}),o.jsxs("div",{className:"col-span-2 flex justify-end gap-2 pt-1",children:[o.jsx("button",{type:"button",onClick:()=>f(!1),className:"px-3 py-1.5 text-sm rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition",children:"Cancel"}),o.jsxs("button",{type:"submit",disabled:h||!w.name.trim(),className:`flex items-center gap-1.5 px-4 py-1.5 text-sm rounded-lg font-medium bg-brand-600 hover:bg-brand-500 text-white transition disabled:opacity-40`,children:[h&&o.jsx(Ce,{className:"animate-spin",size:13}),"Create"]})]})]}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx("div",{className:"flex rounded-lg overflow-hidden border border-slate-700",children:["all",...s_].map(D=>o.jsx("button",{onClick:()=>l(D),className:`px-3 py-1.5 text-xs font-medium capitalize transition ${a===D?"bg-brand-600 text-white":"text-slate-400 hover:text-white hover:bg-slate-700"}`,children:D},D))}),o.jsxs("label",{className:"flex items-center gap-2 text-xs text-slate-400 cursor-pointer select-none ml-auto",children:[o.jsx(Mp,{checked:c,onChange:u}),"Show inactive"]})]}),s?o.jsxs("div",{className:"flex items-center justify-center py-16 text-slate-500 gap-2",children:[o.jsx(Ce,{className:"animate-spin",size:20})," Loading..."]}):pe.length===0?o.jsxs("div",{className:"text-center py-16 text-slate-600 text-sm",children:["No classes found. ",a!=="all"&&"Try changing the filter."]}):o.jsx("div",{className:"rounded-xl border border-slate-700/50 overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"bg-slate-800 text-left",children:[o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"ID"}),o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Name"}),o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Display name"}),o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Device type"}),o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Color"}),o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500 text-center",children:"Order"}),o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500 text-center",children:"Active"}),o.jsx("th",{className:"px-4 py-3"})]})}),o.jsx("tbody",{className:"divide-y divide-slate-800",children:pe.map(D=>o.jsxs("tr",{className:`transition hover:bg-slate-800/50 ${D.is_active?"":"opacity-50"}`,children:[o.jsxs("td",{className:"px-4 py-3 text-slate-500 tabular-nums",children:["#",D.id]}),o.jsx("td",{className:"px-4 py-3 font-mono text-slate-300 text-xs",children:D.name}),o.jsx("td",{className:"px-4 py-3 text-slate-400",children:D.display_name??o.jsx("span",{className:"text-slate-700",children:"—"})}),o.jsx("td",{className:"px-4 py-3",children:o.jsx("span",{className:"capitalize text-slate-400",children:D.device_type})}),o.jsx("td",{className:"px-4 py-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ZT,{color:D.color}),o.jsx("span",{className:"text-xs font-mono text-slate-500",children:D.color??"—"})]})}),o.jsx("td",{className:"px-4 py-3 text-center text-slate-400 tabular-nums",children:D.sort_order}),o.jsx("td",{className:"px-4 py-3 text-center",children:o.jsx(Mp,{checked:D.is_active,onChange:()=>q(D)})}),o.jsx("td",{className:"px-4 py-3 text-right",children:o.jsx("button",{onClick:()=>V(D),title:"Delete class",className:"text-slate-600 hover:text-red-400 transition",children:o.jsx(sd,{size:14})})})]},D.id))})]})}),o.jsxs("div",{className:"pt-4 border-t border-slate-800 space-y-4",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-semibold text-slate-100",children:"Labelling Users"}),o.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:"Manage the users dataset used for job assignment and labelling access."})]}),o.jsxs("form",{onSubmit:I,className:"bg-slate-800 rounded-xl border border-slate-700/50 p-4 grid grid-cols-3 gap-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-slate-500 block mb-1",children:"VerifyAI user ID *"}),o.jsx("input",{type:"number",required:!0,min:"1",value:N.user_id,onChange:D=>j(R=>({...R,user_id:D.target.value})),className:"w-full text-sm bg-slate-700 border border-slate-600 rounded-lg px-3 py-1.5 text-slate-200"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-slate-500 block mb-1",children:"Role *"}),o.jsxs("select",{value:N.role,onChange:D=>j(R=>({...R,role:D.target.value})),className:"w-full text-sm bg-slate-700 border border-slate-600 rounded-lg px-3 py-1.5 text-slate-200",children:[o.jsx("option",{value:"marker",children:"Marker"}),o.jsx("option",{value:"reviewer",children:"Reviewer"})]})]}),o.jsx("div",{className:"flex items-end justify-end",children:o.jsxs("button",{type:"submit",disabled:p||!N.user_id,className:"flex items-center gap-1.5 px-4 py-1.5 text-sm rounded-lg font-medium bg-brand-600 hover:bg-brand-500 text-white transition disabled:opacity-40",children:[p&&o.jsx(Ce,{className:"animate-spin",size:13}),"Add User"]})})]}),k?o.jsxs("div",{className:"flex items-center justify-center py-10 text-slate-500 gap-2",children:[o.jsx(Ce,{className:"animate-spin",size:20})," Loading users..."]}):o.jsx("div",{className:"rounded-xl border border-slate-700/50 overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"bg-slate-800 text-left",children:[o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"User"}),o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Email"}),o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500",children:"Role"}),o.jsx("th",{className:"px-4 py-3 text-xs font-semibold uppercase tracking-wider text-slate-500 text-center",children:"Active"})]})}),o.jsx("tbody",{className:"divide-y divide-slate-800",children:v.map(D=>o.jsxs("tr",{className:D.is_active?"":"opacity-50",children:[o.jsxs("td",{className:"px-4 py-3 text-slate-300",children:[o.jsx("div",{className:"font-medium",children:D.full_name||`User #${D.user_id}`}),o.jsxs("div",{className:"text-xs text-slate-500",children:["ID ",D.user_id]})]}),o.jsx("td",{className:"px-4 py-3 text-slate-400",children:D.email??o.jsx("span",{className:"text-slate-700",children:"—"})}),o.jsx("td",{className:"px-4 py-3",children:o.jsxs("select",{value:D.role,onChange:R=>void X(D,R.target.value),className:"text-xs bg-slate-700 border border-slate-600 rounded px-2 py-1 text-slate-200",children:[o.jsx("option",{value:"marker",children:"Marker"}),o.jsx("option",{value:"reviewer",children:"Reviewer"})]})}),o.jsx("td",{className:"px-4 py-3 text-center",children:o.jsx(Mp,{checked:D.is_active,onChange:()=>void ne(D)})})]},D.user_id))})]})})]})]})}const tP=new Set(["system-admin","network-admin"]);function sP(){const{user:t}=wn();return o.jsx(Yx,{to:tP.has(t==null?void 0:t.user_type)?"overview":"jobs",replace:!0})}function nP(){return o.jsx(fj,{children:o.jsxs(Zk,{children:[o.jsx(rs,{path:"/login",element:o.jsx(a3,{})}),o.jsx(rs,{element:o.jsx(hj,{}),children:o.jsxs(rs,{path:"/app",element:o.jsx(c3,{}),children:[o.jsx(rs,{index:!0,element:o.jsx(sP,{})}),o.jsx(rs,{path:"overview",element:o.jsx(u3,{})}),o.jsx(rs,{path:"videos",element:o.jsx(S3,{})}),o.jsx(rs,{path:"jobs",element:o.jsx(mT,{})}),o.jsx(rs,{path:"datasets",element:o.jsx(XT,{})}),o.jsx(rs,{path:"admin",element:o.jsx(eP,{})})]})}),o.jsx(rs,{path:"*",element:o.jsx(Yx,{to:"/login",replace:!0})})]})})}Vp.createRoot(document.getElementById("root")).render(o.jsx(Re.StrictMode,{children:o.jsx(oE,{children:o.jsx(nP,{})})}));