var L_=Object.defineProperty;var F_=(t,n,a)=>n in t?L_(t,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[n]=a;var zo=(t,n,a)=>F_(t,typeof n!="symbol"?n+"":n,a);function D_(t,n){for(var a=0;ao[c]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))o(c);new MutationObserver(c=>{for(const u of c)if(u.type==="childList")for(const h of u.addedNodes)h.tagName==="LINK"&&h.rel==="modulepreload"&&o(h)}).observe(document,{childList:!0,subtree:!0});function a(c){const u={};return c.integrity&&(u.integrity=c.integrity),c.referrerPolicy&&(u.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?u.credentials="include":c.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function o(c){if(c.ep)return;c.ep=!0;const u=a(c);fetch(c.href,u)}})();function $_(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var cu={exports:{}},ci={},du={exports:{}},Qe={};/** * @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 gx;function I_(){if(gx)return Qe;gx=1;var t=Symbol.for("react.element"),n=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),c=Symbol.for("react.profiler"),u=Symbol.for("react.provider"),h=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),v=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),j=Symbol.iterator;function w(q){return q===null||typeof q!="object"?null:(q=j&&q[j]||q["@@iterator"],typeof q=="function"?q:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,y={};function g(q,J,le){this.props=q,this.context=J,this.refs=y,this.updater=le||_}g.prototype.isReactComponent={},g.prototype.setState=function(q,J){if(typeof q!="object"&&typeof q!="function"&&q!=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,q,J,"setState")},g.prototype.forceUpdate=function(q){this.updater.enqueueForceUpdate(this,q,"forceUpdate")};function p(){}p.prototype=g.prototype;function k(q,J,le){this.props=q,this.context=J,this.refs=y,this.updater=le||_}var R=k.prototype=new p;R.constructor=k,S(R,g.prototype),R.isPureReactComponent=!0;var C=Array.isArray,E=Object.prototype.hasOwnProperty,P={current:null},F={key:!0,ref:!0,__self:!0,__source:!0};function I(q,J,le){var ke,Ce={},Ae=null,Z=null;if(J!=null)for(ke in J.ref!==void 0&&(Z=J.ref),J.key!==void 0&&(Ae=""+J.key),J)E.call(J,ke)&&!F.hasOwnProperty(ke)&&(Ce[ke]=J[ke]);var fe=arguments.length-2;if(fe===1)Ce.children=le;else if(1>>1,J=W[q];if(0>>1;qc(Ce,ne))Aec(Z,Ce)?(W[q]=Z,W[Ae]=ne,q=Ae):(W[q]=Ce,W[ke]=ne,q=ke);else if(Aec(Z,ne))W[q]=Z,W[Ae]=ne,q=Ae;else break e}}return se}function c(W,se){var ne=W.sortIndex-se.sortIndex;return ne!==0?ne:W.id-se.id}if(typeof performance=="object"&&typeof performance.now=="function"){var u=performance;t.unstable_now=function(){return u.now()}}else{var h=Date,m=h.now();t.unstable_now=function(){return h.now()-m}}var x=[],v=[],N=1,j=null,w=3,_=!1,S=!1,y=!1,g=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function R(W){for(var se=a(v);se!==null;){if(se.callback===null)o(v);else if(se.startTime<=W)o(v),se.sortIndex=se.expirationTime,n(x,se);else break;se=a(v)}}function C(W){if(y=!1,R(W),!S)if(a(x)!==null)S=!0,U(E);else{var se=a(v);se!==null&&ae(C,se.startTime-W)}}function E(W,se){S=!1,y&&(y=!1,p(I),I=-1),_=!0;var ne=w;try{for(R(se),j=a(x);j!==null&&(!(j.expirationTime>se)||W&&!O());){var q=j.callback;if(typeof q=="function"){j.callback=null,w=j.priorityLevel;var J=q(j.expirationTime<=se);se=t.unstable_now(),typeof J=="function"?j.callback=J:j===a(x)&&o(x),R(se)}else o(x);j=a(x)}if(j!==null)var le=!0;else{var ke=a(v);ke!==null&&ae(C,ke.startTime-se),le=!1}return le}finally{j=null,w=ne,_=!1}}var P=!1,F=null,I=-1,M=5,$=-1;function O(){return!(t.unstable_now()-$W||125q?(W.sortIndex=ne,n(v,W),a(x)===null&&W===a(v)&&(y?(p(I),I=-1):y=!0,ae(C,ne-q))):(W.sortIndex=J,n(x,W),S||_||(S=!0,U(E))),W},t.unstable_shouldYield=O,t.unstable_wrapCallback=function(W){var se=w;return function(){var ne=w;w=se;try{return W.apply(this,arguments)}finally{w=ne}}}})(hu)),hu}var bx;function B_(){return bx||(bx=1,mu.exports=U_()),mu.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 Nx;function H_(){if(Nx)return is;Nx=1;var t=Em(),n=B_();function a(s){for(var r="https://reactjs.org/docs/error-decoder.html?invariant="+s,l=1;l"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),x=Object.prototype.hasOwnProperty,v=/^[: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]*$/,N={},j={};function w(s){return x.call(j,s)?!0:x.call(N,s)?!1:v.test(s)?j[s]=!0:(N[s]=!0,!1)}function _(s,r,l,d){if(l!==null&&l.type===0)return!1;switch(typeof r){case"function":case"symbol":return!0;case"boolean":return d?!1:l!==null?!l.acceptsBooleans:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function S(s,r,l,d){if(r===null||typeof r>"u"||_(s,r,l,d))return!0;if(d)return!1;if(l!==null)switch(l.type){case 3:return!r;case 4:return r===!1;case 5:return isNaN(r);case 6:return isNaN(r)||1>r}return!1}function y(s,r,l,d,f,b,D){this.acceptsBooleans=r===2||r===3||r===4,this.attributeName=d,this.attributeNamespace=f,this.mustUseProperty=l,this.propertyName=s,this.type=r,this.sanitizeURL=b,this.removeEmptyString=D}var g={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){g[s]=new y(s,0,!1,s,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var r=s[0];g[r]=new y(r,1,!1,s[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(s){g[s]=new y(s,2,!1,s.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){g[s]=new y(s,2,!1,s,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(s){g[s]=new y(s,3,!1,s.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(s){g[s]=new y(s,3,!0,s,null,!1,!1)}),["capture","download"].forEach(function(s){g[s]=new y(s,4,!1,s,null,!1,!1)}),["cols","rows","size","span"].forEach(function(s){g[s]=new y(s,6,!1,s,null,!1,!1)}),["rowSpan","start"].forEach(function(s){g[s]=new y(s,5,!1,s.toLowerCase(),null,!1,!1)});var p=/[\-:]([a-z])/g;function k(s){return s[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(s){var r=s.replace(p,k);g[r]=new y(r,1,!1,s,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(s){var r=s.replace(p,k);g[r]=new y(r,1,!1,s,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(s){var r=s.replace(p,k);g[r]=new y(r,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(s){g[s]=new y(s,1,!1,s.toLowerCase(),null,!1,!1)}),g.xlinkHref=new y("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(s){g[s]=new y(s,1,!1,s.toLowerCase(),null,!0,!0)});function R(s,r,l,d){var f=g.hasOwnProperty(r)?g[r]:null;(f!==null?f.type!==0:d||!(2Q||f[D]!==b[Q]){var X=` `+f[D].replace(" at new "," at ");return s.displayName&&X.includes("")&&(X=X.replace("",s.displayName)),X}while(1<=D&&0<=Q);break}}}finally{le=!1,Error.prepareStackTrace=l}return(s=s?s.displayName||s.name:"")?J(s):""}function Ce(s){switch(s.tag){case 5:return J(s.type);case 16:return J("Lazy");case 13:return J("Suspense");case 19:return J("SuspenseList");case 0:case 2:case 15:return s=ke(s.type,!1),s;case 11:return s=ke(s.type.render,!1),s;case 1:return s=ke(s.type,!0),s;default:return""}}function Ae(s){if(s==null)return null;if(typeof s=="function")return s.displayName||s.name||null;if(typeof s=="string")return s;switch(s){case F:return"Fragment";case P:return"Portal";case M:return"Profiler";case I:return"StrictMode";case z:return"Suspense";case Y:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case O:return(s.displayName||"Context")+".Consumer";case $:return(s._context.displayName||"Context")+".Provider";case L:var r=s.render;return s=s.displayName,s||(s=r.displayName||r.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case G:return r=s.displayName||null,r!==null?r:Ae(s.type)||"Memo";case U:r=s._payload,s=s._init;try{return Ae(s(r))}catch{}}return null}function Z(s){var r=s.type;switch(s.tag){case 24:return"Cache";case 9:return(r.displayName||"Context")+".Consumer";case 10:return(r._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return s=r.render,s=s.displayName||s.name||"",r.displayName||(s!==""?"ForwardRef("+s+")":"ForwardRef");case 7:return"Fragment";case 5:return r;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Ae(r);case 8:return r===I?"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 r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r}return null}function fe(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function re(s){var r=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(r==="checkbox"||r==="radio")}function Ee(s){var r=re(s)?"checked":"value",l=Object.getOwnPropertyDescriptor(s.constructor.prototype,r),d=""+s[r];if(!s.hasOwnProperty(r)&&typeof l<"u"&&typeof l.get=="function"&&typeof l.set=="function"){var f=l.get,b=l.set;return Object.defineProperty(s,r,{configurable:!0,get:function(){return f.call(this)},set:function(D){d=""+D,b.call(this,D)}}),Object.defineProperty(s,r,{enumerable:l.enumerable}),{getValue:function(){return d},setValue:function(D){d=""+D},stopTracking:function(){s._valueTracker=null,delete s[r]}}}}function nt(s){s._valueTracker||(s._valueTracker=Ee(s))}function ct(s){if(!s)return!1;var r=s._valueTracker;if(!r)return!0;var l=r.getValue(),d="";return s&&(d=re(s)?s.checked?"true":"false":s.value),s=d,s!==l?(r.setValue(s),!0):!1}function Ut(s){if(s=s||(typeof document<"u"?document:void 0),typeof s>"u")return null;try{return s.activeElement||s.body}catch{return s.body}}function Yt(s,r){var l=r.checked;return ne({},r,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:l??s._wrapperState.initialChecked})}function Ns(s,r){var l=r.defaultValue==null?"":r.defaultValue,d=r.checked!=null?r.checked:r.defaultChecked;l=fe(r.value!=null?r.value:l),s._wrapperState={initialChecked:d,initialValue:l,controlled:r.type==="checkbox"||r.type==="radio"?r.checked!=null:r.value!=null}}function ws(s,r){r=r.checked,r!=null&&R(s,"checked",r,!1)}function Sn(s,r){ws(s,r);var l=fe(r.value),d=r.type;if(l!=null)d==="number"?(l===0&&s.value===""||s.value!=l)&&(s.value=""+l):s.value!==""+l&&(s.value=""+l);else if(d==="submit"||d==="reset"){s.removeAttribute("value");return}r.hasOwnProperty("value")?Ir(s,r.type,l):r.hasOwnProperty("defaultValue")&&Ir(s,r.type,fe(r.defaultValue)),r.checked==null&&r.defaultChecked!=null&&(s.defaultChecked=!!r.defaultChecked)}function $r(s,r,l){if(r.hasOwnProperty("value")||r.hasOwnProperty("defaultValue")){var d=r.type;if(!(d!=="submit"&&d!=="reset"||r.value!==void 0&&r.value!==null))return;r=""+s._wrapperState.initialValue,l||r===s.value||(s.value=r),s.defaultValue=r}l=s.name,l!==""&&(s.name=""),s.defaultChecked=!!s._wrapperState.initialChecked,l!==""&&(s.name=l)}function Ir(s,r,l){(r!=="number"||Ut(s.ownerDocument)!==s)&&(l==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+l&&(s.defaultValue=""+l))}var Ss=Array.isArray;function tn(s,r,l,d){if(s=s.options,r){r={};for(var f=0;f"+r.valueOf().toString()+"",r=_a.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;r.firstChild;)s.appendChild(r.firstChild)}});function Yn(s,r){if(r){var l=s.firstChild;if(l&&l===s.lastChild&&l.nodeType===3){l.nodeValue=r;return}}s.textContent=r}var Cn={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},Sl=["Webkit","ms","Moz","O"];Object.keys(Cn).forEach(function(s){Sl.forEach(function(r){r=r+s.charAt(0).toUpperCase()+s.substring(1),Cn[r]=Cn[s]})});function Mr(s,r,l){return r==null||typeof r=="boolean"||r===""?"":l||typeof r!="number"||r===0||Cn.hasOwnProperty(s)&&Cn[s]?(""+r).trim():r+"px"}function Cl(s,r){s=s.style;for(var l in r)if(r.hasOwnProperty(l)){var d=l.indexOf("--")===0,f=Mr(l,r[l],d);l==="float"&&(l="cssFloat"),d?s.setProperty(l,f):s[l]=f}}var Lc=ne({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 ba(s,r){if(r){if(Lc[s]&&(r.children!=null||r.dangerouslySetInnerHTML!=null))throw Error(a(137,s));if(r.dangerouslySetInnerHTML!=null){if(r.children!=null)throw Error(a(60));if(typeof r.dangerouslySetInnerHTML!="object"||!("__html"in r.dangerouslySetInnerHTML))throw Error(a(61))}if(r.style!=null&&typeof r.style!="object")throw Error(a(62))}}function Zn(s,r){if(s.indexOf("-")===-1)return typeof r.is=="string";switch(s){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 kl=null;function El(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var Na=null,Cs=null,nn=null;function ks(s){if(s=Ql(s)){if(typeof Na!="function")throw Error(a(280));var r=s.stateNode;r&&(r=eo(r),Na(s.stateNode,s.type,r))}}function Al(s){Cs?nn?nn.push(s):nn=[s]:Cs=s}function Rl(){if(Cs){var s=Cs,r=nn;if(nn=Cs=null,ks(s),r)for(s=0;s>>=0,s===0?32:31-(Dc(s)/$c|0)|0}var nr=64,Fl=4194304;function ce(s){switch(s&-s){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 s&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return s&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return s}}function xe(s,r){var l=s.pendingLanes;if(l===0)return 0;var d=0,f=s.suspendedLanes,b=s.pingedLanes,D=l&268435455;if(D!==0){var Q=D&~f;Q!==0?d=ce(Q):(b&=D,b!==0&&(d=ce(b)))}else D=l&~f,D!==0?d=ce(D):b!==0&&(d=ce(b));if(d===0)return 0;if(r!==0&&r!==d&&(r&f)===0&&(f=d&-d,b=r&-r,f>=b||f===16&&(b&4194240)!==0))return r;if((d&4)!==0&&(d|=l&16),r=s.entangledLanes,r!==0)for(s=s.entanglements,r&=d;0l;l++)r.push(s);return r}function ot(s,r,l){s.pendingLanes|=r,r!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,r=31-It(r),s[r]=l}function lt(s,r){var l=s.pendingLanes&~r;s.pendingLanes=r,s.suspendedLanes=0,s.pingedLanes=0,s.expiredLanes&=r,s.mutableReadLanes&=r,s.entangledLanes&=r,r=s.entanglements;var d=s.eventTimes;for(s=s.expirationTimes;0=Ol),ch=" ",dh=!1;function uh(s,r){switch(s){case"keyup":return Ey.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function mh(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Fa=!1;function Ry(s,r){switch(s){case"compositionend":return mh(r);case"keypress":return r.which!==32?null:(dh=!0,ch);case"textInput":return s=r.data,s===ch&&dh?null:s;default:return null}}function Py(s,r){if(Fa)return s==="compositionend"||!Hc&&uh(s,r)?(s=Ta(),Pn=ps=Et=null,Fa=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-s};s=d}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=jh(l)}}function _h(s,r){return s&&r?s===r?!0:s&&s.nodeType===3?!1:r&&r.nodeType===3?_h(s,r.parentNode):"contains"in s?s.contains(r):s.compareDocumentPosition?!!(s.compareDocumentPosition(r)&16):!1:!1}function bh(){for(var s=window,r=Ut();r instanceof s.HTMLIFrameElement;){try{var l=typeof r.contentWindow.location.href=="string"}catch{l=!1}if(l)s=r.contentWindow;else break;r=Ut(s.document)}return r}function Wc(s){var r=s&&s.nodeName&&s.nodeName.toLowerCase();return r&&(r==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||r==="textarea"||s.contentEditable==="true")}function zy(s){var r=bh(),l=s.focusedElem,d=s.selectionRange;if(r!==l&&l&&l.ownerDocument&&_h(l.ownerDocument.documentElement,l)){if(d!==null&&Wc(l)){if(r=d.start,s=d.end,s===void 0&&(s=r),"selectionStart"in l)l.selectionStart=r,l.selectionEnd=Math.min(s,l.value.length);else if(s=(r=l.ownerDocument||document)&&r.defaultView||window,s.getSelection){s=s.getSelection();var f=l.textContent.length,b=Math.min(d.start,f);d=d.end===void 0?b:Math.min(d.end,f),!s.extend&&b>d&&(f=d,d=b,b=f),f=yh(l,b);var D=yh(l,d);f&&D&&(s.rangeCount!==1||s.anchorNode!==f.node||s.anchorOffset!==f.offset||s.focusNode!==D.node||s.focusOffset!==D.offset)&&(r=r.createRange(),r.setStart(f.node,f.offset),s.removeAllRanges(),b>d?(s.addRange(r),s.extend(D.node,D.offset)):(r.setEnd(D.node,D.offset),s.addRange(r)))}}for(r=[],s=l;s=s.parentNode;)s.nodeType===1&&r.push({element:s,left:s.scrollLeft,top:s.scrollTop});for(typeof l.focus=="function"&&l.focus(),l=0;l=document.documentMode,Da=null,qc=null,Hl=null,Qc=!1;function Nh(s,r,l){var d=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;Qc||Da==null||Da!==Ut(d)||(d=Da,"selectionStart"in d&&Wc(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Hl&&Bl(Hl,d)||(Hl=d,d=Yi(qc,"onSelect"),0za||(s.current=ld[za],ld[za]=null,za--)}function dt(s,r){za++,ld[za]=s.current,s.current=r}var mr={},Ht=ur(mr),ss=ur(!1),Gr=mr;function Ua(s,r){var l=s.type.contextTypes;if(!l)return mr;var d=s.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===r)return d.__reactInternalMemoizedMaskedChildContext;var f={},b;for(b in l)f[b]=r[b];return d&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=r,s.__reactInternalMemoizedMaskedChildContext=f),f}function ns(s){return s=s.childContextTypes,s!=null}function to(){mt(ss),mt(Ht)}function Mh(s,r,l){if(Ht.current!==mr)throw Error(a(168));dt(Ht,r),dt(ss,l)}function Oh(s,r,l){var d=s.stateNode;if(r=r.childContextTypes,typeof d.getChildContext!="function")return l;d=d.getChildContext();for(var f in d)if(!(f in r))throw Error(a(108,Z(s)||"Unknown",f));return ne({},l,d)}function so(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||mr,Gr=Ht.current,dt(Ht,s),dt(ss,ss.current),!0}function zh(s,r,l){var d=s.stateNode;if(!d)throw Error(a(169));l?(s=Oh(s,r,Gr),d.__reactInternalMemoizedMergedChildContext=s,mt(ss),mt(Ht),dt(Ht,s)):mt(ss),dt(ss,l)}var Ln=null,no=!1,id=!1;function Uh(s){Ln===null?Ln=[s]:Ln.push(s)}function Zy(s){no=!0,Uh(s)}function hr(){if(!id&&Ln!==null){id=!0;var s=0,r=Re;try{var l=Ln;for(Re=1;s>=D,f-=D,Fn=1<<32-It(r)+f|l<Ge?(Pt=He,He=null):Pt=He.sibling;var tt=pe(ie,He,oe[Ge],we);if(tt===null){He===null&&(He=Pt);break}s&&He&&tt.alternate===null&&r(ie,He),te=b(tt,te,Ge),Be===null?Me=tt:Be.sibling=tt,Be=tt,He=Pt}if(Ge===oe.length)return l(ie,He),ht&&qr(ie,Ge),Me;if(He===null){for(;GeGe?(Pt=He,He=null):Pt=He.sibling;var br=pe(ie,He,tt.value,we);if(br===null){He===null&&(He=Pt);break}s&&He&&br.alternate===null&&r(ie,He),te=b(br,te,Ge),Be===null?Me=br:Be.sibling=br,Be=br,He=Pt}if(tt.done)return l(ie,He),ht&&qr(ie,Ge),Me;if(He===null){for(;!tt.done;Ge++,tt=oe.next())tt=ve(ie,tt.value,we),tt!==null&&(te=b(tt,te,Ge),Be===null?Me=tt:Be.sibling=tt,Be=tt);return ht&&qr(ie,Ge),Me}for(He=d(ie,He);!tt.done;Ge++,tt=oe.next())tt=Pe(He,ie,Ge,tt.value,we),tt!==null&&(s&&tt.alternate!==null&&He.delete(tt.key===null?Ge:tt.key),te=b(tt,te,Ge),Be===null?Me=tt:Be.sibling=tt,Be=tt);return s&&He.forEach(function(T_){return r(ie,T_)}),ht&&qr(ie,Ge),Me}function _t(ie,te,oe,we){if(typeof oe=="object"&&oe!==null&&oe.type===F&&oe.key===null&&(oe=oe.props.children),typeof oe=="object"&&oe!==null){switch(oe.$$typeof){case E:e:{for(var Me=oe.key,Be=te;Be!==null;){if(Be.key===Me){if(Me=oe.type,Me===F){if(Be.tag===7){l(ie,Be.sibling),te=f(Be,oe.props.children),te.return=ie,ie=te;break e}}else if(Be.elementType===Me||typeof Me=="object"&&Me!==null&&Me.$$typeof===U&&qh(Me)===Be.type){l(ie,Be.sibling),te=f(Be,oe.props),te.ref=Kl(ie,Be,oe),te.return=ie,ie=te;break e}l(ie,Be);break}else r(ie,Be);Be=Be.sibling}oe.type===F?(te=ta(oe.props.children,ie.mode,we,oe.key),te.return=ie,ie=te):(we=To(oe.type,oe.key,oe.props,null,ie.mode,we),we.ref=Kl(ie,te,oe),we.return=ie,ie=we)}return D(ie);case P:e:{for(Be=oe.key;te!==null;){if(te.key===Be)if(te.tag===4&&te.stateNode.containerInfo===oe.containerInfo&&te.stateNode.implementation===oe.implementation){l(ie,te.sibling),te=f(te,oe.children||[]),te.return=ie,ie=te;break e}else{l(ie,te);break}else r(ie,te);te=te.sibling}te=ru(oe,ie.mode,we),te.return=ie,ie=te}return D(ie);case U:return Be=oe._init,_t(ie,te,Be(oe._payload),we)}if(Ss(oe))return De(ie,te,oe,we);if(se(oe))return $e(ie,te,oe,we);io(ie,oe)}return typeof oe=="string"&&oe!==""||typeof oe=="number"?(oe=""+oe,te!==null&&te.tag===6?(l(ie,te.sibling),te=f(te,oe),te.return=ie,ie=te):(l(ie,te),te=nu(oe,ie.mode,we),te.return=ie,ie=te),D(ie)):l(ie,te)}return _t}var Ga=Qh(!0),Kh=Qh(!1),oo=ur(null),co=null,Wa=null,hd=null;function fd(){hd=Wa=co=null}function xd(s){var r=oo.current;mt(oo),s._currentValue=r}function pd(s,r,l){for(;s!==null;){var d=s.alternate;if((s.childLanes&r)!==r?(s.childLanes|=r,d!==null&&(d.childLanes|=r)):d!==null&&(d.childLanes&r)!==r&&(d.childLanes|=r),s===l)break;s=s.return}}function qa(s,r){co=s,hd=Wa=null,s=s.dependencies,s!==null&&s.firstContext!==null&&((s.lanes&r)!==0&&(rs=!0),s.firstContext=null)}function Ds(s){var r=s._currentValue;if(hd!==s)if(s={context:s,memoizedValue:r,next:null},Wa===null){if(co===null)throw Error(a(308));Wa=s,co.dependencies={lanes:0,firstContext:s}}else Wa=Wa.next=s;return r}var Qr=null;function gd(s){Qr===null?Qr=[s]:Qr.push(s)}function Xh(s,r,l,d){var f=r.interleaved;return f===null?(l.next=l,gd(r)):(l.next=f.next,f.next=l),r.interleaved=l,$n(s,d)}function $n(s,r){s.lanes|=r;var l=s.alternate;for(l!==null&&(l.lanes|=r),l=s,s=s.return;s!==null;)s.childLanes|=r,l=s.alternate,l!==null&&(l.childLanes|=r),l=s,s=s.return;return l.tag===3?l.stateNode:null}var fr=!1;function vd(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Yh(s,r){s=s.updateQueue,r.updateQueue===s&&(r.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,effects:s.effects})}function In(s,r){return{eventTime:s,lane:r,tag:0,payload:null,callback:null,next:null}}function xr(s,r,l){var d=s.updateQueue;if(d===null)return null;if(d=d.shared,(et&2)!==0){var f=d.pending;return f===null?r.next=r:(r.next=f.next,f.next=r),d.pending=r,$n(s,l)}return f=d.interleaved,f===null?(r.next=r,gd(d)):(r.next=f.next,f.next=r),d.interleaved=r,$n(s,l)}function uo(s,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194240)!==0)){var d=r.lanes;d&=s.pendingLanes,l|=d,r.lanes=l,Ue(s,l)}}function Zh(s,r){var l=s.updateQueue,d=s.alternate;if(d!==null&&(d=d.updateQueue,l===d)){var f=null,b=null;if(l=l.firstBaseUpdate,l!==null){do{var D={eventTime:l.eventTime,lane:l.lane,tag:l.tag,payload:l.payload,callback:l.callback,next:null};b===null?f=b=D:b=b.next=D,l=l.next}while(l!==null);b===null?f=b=r:b=b.next=r}else f=b=r;l={baseState:d.baseState,firstBaseUpdate:f,lastBaseUpdate:b,shared:d.shared,effects:d.effects},s.updateQueue=l;return}s=l.lastBaseUpdate,s===null?l.firstBaseUpdate=r:s.next=r,l.lastBaseUpdate=r}function mo(s,r,l,d){var f=s.updateQueue;fr=!1;var b=f.firstBaseUpdate,D=f.lastBaseUpdate,Q=f.shared.pending;if(Q!==null){f.shared.pending=null;var X=Q,de=X.next;X.next=null,D===null?b=de:D.next=de,D=X;var ge=s.alternate;ge!==null&&(ge=ge.updateQueue,Q=ge.lastBaseUpdate,Q!==D&&(Q===null?ge.firstBaseUpdate=de:Q.next=de,ge.lastBaseUpdate=X))}if(b!==null){var ve=f.baseState;D=0,ge=de=X=null,Q=b;do{var pe=Q.lane,Pe=Q.eventTime;if((d&pe)===pe){ge!==null&&(ge=ge.next={eventTime:Pe,lane:0,tag:Q.tag,payload:Q.payload,callback:Q.callback,next:null});e:{var De=s,$e=Q;switch(pe=r,Pe=l,$e.tag){case 1:if(De=$e.payload,typeof De=="function"){ve=De.call(Pe,ve,pe);break e}ve=De;break e;case 3:De.flags=De.flags&-65537|128;case 0:if(De=$e.payload,pe=typeof De=="function"?De.call(Pe,ve,pe):De,pe==null)break e;ve=ne({},ve,pe);break e;case 2:fr=!0}}Q.callback!==null&&Q.lane!==0&&(s.flags|=64,pe=f.effects,pe===null?f.effects=[Q]:pe.push(Q))}else Pe={eventTime:Pe,lane:pe,tag:Q.tag,payload:Q.payload,callback:Q.callback,next:null},ge===null?(de=ge=Pe,X=ve):ge=ge.next=Pe,D|=pe;if(Q=Q.next,Q===null){if(Q=f.shared.pending,Q===null)break;pe=Q,Q=pe.next,pe.next=null,f.lastBaseUpdate=pe,f.shared.pending=null}}while(!0);if(ge===null&&(X=ve),f.baseState=X,f.firstBaseUpdate=de,f.lastBaseUpdate=ge,r=f.shared.interleaved,r!==null){f=r;do D|=f.lane,f=f.next;while(f!==r)}else b===null&&(f.shared.lanes=0);Yr|=D,s.lanes=D,s.memoizedState=ve}}function Jh(s,r,l){if(s=r.effects,r.effects=null,s!==null)for(r=0;rl?l:4,s(!0);var d=Nd.transition;Nd.transition={};try{s(!1),r()}finally{Re=l,Nd.transition=d}}function jf(){return $s().memoizedState}function s_(s,r,l){var d=jr(s);if(l={lane:d,action:l,hasEagerState:!1,eagerState:null,next:null},yf(s))_f(r,l);else if(l=Xh(s,r,l,d),l!==null){var f=Kt();Js(l,s,d,f),bf(l,r,d)}}function n_(s,r,l){var d=jr(s),f={lane:d,action:l,hasEagerState:!1,eagerState:null,next:null};if(yf(s))_f(r,f);else{var b=s.alternate;if(s.lanes===0&&(b===null||b.lanes===0)&&(b=r.lastRenderedReducer,b!==null))try{var D=r.lastRenderedState,Q=b(D,l);if(f.hasEagerState=!0,f.eagerState=Q,Qs(Q,D)){var X=r.interleaved;X===null?(f.next=f,gd(r)):(f.next=X.next,X.next=f),r.interleaved=f;return}}catch{}finally{}l=Xh(s,r,f,d),l!==null&&(f=Kt(),Js(l,s,d,f),bf(l,r,d))}}function yf(s){var r=s.alternate;return s===pt||r!==null&&r===pt}function _f(s,r){Jl=xo=!0;var l=s.pending;l===null?r.next=r:(r.next=l.next,l.next=r),s.pending=r}function bf(s,r,l){if((l&4194240)!==0){var d=r.lanes;d&=s.pendingLanes,l|=d,r.lanes=l,Ue(s,l)}}var vo={readContext:Ds,useCallback:Vt,useContext:Vt,useEffect:Vt,useImperativeHandle:Vt,useInsertionEffect:Vt,useLayoutEffect:Vt,useMemo:Vt,useReducer:Vt,useRef:Vt,useState:Vt,useDebugValue:Vt,useDeferredValue:Vt,useTransition:Vt,useMutableSource:Vt,useSyncExternalStore:Vt,useId:Vt,unstable_isNewReconciler:!1},r_={readContext:Ds,useCallback:function(s,r){return mn().memoizedState=[s,r===void 0?null:r],s},useContext:Ds,useEffect:uf,useImperativeHandle:function(s,r,l){return l=l!=null?l.concat([s]):null,po(4194308,4,ff.bind(null,r,s),l)},useLayoutEffect:function(s,r){return po(4194308,4,s,r)},useInsertionEffect:function(s,r){return po(4,2,s,r)},useMemo:function(s,r){var l=mn();return r=r===void 0?null:r,s=s(),l.memoizedState=[s,r],s},useReducer:function(s,r,l){var d=mn();return r=l!==void 0?l(r):r,d.memoizedState=d.baseState=r,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:r},d.queue=s,s=s.dispatch=s_.bind(null,pt,s),[d.memoizedState,s]},useRef:function(s){var r=mn();return s={current:s},r.memoizedState=s},useState:cf,useDebugValue:Rd,useDeferredValue:function(s){return mn().memoizedState=s},useTransition:function(){var s=cf(!1),r=s[0];return s=t_.bind(null,s[1]),mn().memoizedState=s,[r,s]},useMutableSource:function(){},useSyncExternalStore:function(s,r,l){var d=pt,f=mn();if(ht){if(l===void 0)throw Error(a(407));l=l()}else{if(l=r(),Rt===null)throw Error(a(349));(Xr&30)!==0||nf(d,r,l)}f.memoizedState=l;var b={value:l,getSnapshot:r};return f.queue=b,uf(af.bind(null,d,b,s),[s]),d.flags|=2048,si(9,rf.bind(null,d,b,l,r),void 0,null),l},useId:function(){var s=mn(),r=Rt.identifierPrefix;if(ht){var l=Dn,d=Fn;l=(d&~(1<<32-It(d)-1)).toString(32)+l,r=":"+r+"R"+l,l=ei++,0<\/script>",s=s.removeChild(s.firstChild)):typeof d.is=="string"?s=D.createElement(l,{is:d.is}):(s=D.createElement(l),l==="select"&&(D=s,d.multiple?D.multiple=!0:d.size&&(D.size=d.size))):s=D.createElementNS(s,l),s[dn]=r,s[ql]=d,Bf(s,r,!1,!1),r.stateNode=s;e:{switch(D=Zn(l,d),l){case"dialog":ut("cancel",s),ut("close",s),f=d;break;case"iframe":case"object":case"embed":ut("load",s),f=d;break;case"video":case"audio":for(f=0;fZa&&(r.flags|=128,d=!0,ni(b,!1),r.lanes=4194304)}else{if(!d)if(s=ho(D),s!==null){if(r.flags|=128,d=!0,l=s.updateQueue,l!==null&&(r.updateQueue=l,r.flags|=4),ni(b,!0),b.tail===null&&b.tailMode==="hidden"&&!D.alternate&&!ht)return Gt(r),null}else 2*at()-b.renderingStartTime>Za&&l!==1073741824&&(r.flags|=128,d=!0,ni(b,!1),r.lanes=4194304);b.isBackwards?(D.sibling=r.child,r.child=D):(l=b.last,l!==null?l.sibling=D:r.child=D,b.last=D)}return b.tail!==null?(r=b.tail,b.rendering=r,b.tail=r.sibling,b.renderingStartTime=at(),r.sibling=null,l=xt.current,dt(xt,d?l&1|2:l&1),r):(Gt(r),null);case 22:case 23:return eu(),d=r.memoizedState!==null,s!==null&&s.memoizedState!==null!==d&&(r.flags|=8192),d&&(r.mode&1)!==0?(ys&1073741824)!==0&&(Gt(r),r.subtreeFlags&6&&(r.flags|=8192)):Gt(r),null;case 24:return null;case 25:return null}throw Error(a(156,r.tag))}function m_(s,r){switch(cd(r),r.tag){case 1:return ns(r.type)&&to(),s=r.flags,s&65536?(r.flags=s&-65537|128,r):null;case 3:return Qa(),mt(ss),mt(Ht),bd(),s=r.flags,(s&65536)!==0&&(s&128)===0?(r.flags=s&-65537|128,r):null;case 5:return yd(r),null;case 13:if(mt(xt),s=r.memoizedState,s!==null&&s.dehydrated!==null){if(r.alternate===null)throw Error(a(340));Va()}return s=r.flags,s&65536?(r.flags=s&-65537|128,r):null;case 19:return mt(xt),null;case 4:return Qa(),null;case 10:return xd(r.type._context),null;case 22:case 23:return eu(),null;case 24:return null;default:return null}}var bo=!1,Wt=!1,h_=typeof WeakSet=="function"?WeakSet:Set,Le=null;function Xa(s,r){var l=s.ref;if(l!==null)if(typeof l=="function")try{l(null)}catch(d){vt(s,r,d)}else l.current=null}function Bd(s,r,l){try{l()}catch(d){vt(s,r,d)}}var Gf=!1;function f_(s,r){if(ed=lr,s=bh(),Wc(s)){if("selectionStart"in s)var l={start:s.selectionStart,end:s.selectionEnd};else e:{l=(l=s.ownerDocument)&&l.defaultView||window;var d=l.getSelection&&l.getSelection();if(d&&d.rangeCount!==0){l=d.anchorNode;var f=d.anchorOffset,b=d.focusNode;d=d.focusOffset;try{l.nodeType,b.nodeType}catch{l=null;break e}var D=0,Q=-1,X=-1,de=0,ge=0,ve=s,pe=null;t:for(;;){for(var Pe;ve!==l||f!==0&&ve.nodeType!==3||(Q=D+f),ve!==b||d!==0&&ve.nodeType!==3||(X=D+d),ve.nodeType===3&&(D+=ve.nodeValue.length),(Pe=ve.firstChild)!==null;)pe=ve,ve=Pe;for(;;){if(ve===s)break t;if(pe===l&&++de===f&&(Q=D),pe===b&&++ge===d&&(X=D),(Pe=ve.nextSibling)!==null)break;ve=pe,pe=ve.parentNode}ve=Pe}l=Q===-1||X===-1?null:{start:Q,end:X}}else l=null}l=l||{start:0,end:0}}else l=null;for(td={focusedElem:s,selectionRange:l},lr=!1,Le=r;Le!==null;)if(r=Le,s=r.child,(r.subtreeFlags&1028)!==0&&s!==null)s.return=r,Le=s;else for(;Le!==null;){r=Le;try{var De=r.alternate;if((r.flags&1024)!==0)switch(r.tag){case 0:case 11:case 15:break;case 1:if(De!==null){var $e=De.memoizedProps,_t=De.memoizedState,ie=r.stateNode,te=ie.getSnapshotBeforeUpdate(r.elementType===r.type?$e:Xs(r.type,$e),_t);ie.__reactInternalSnapshotBeforeUpdate=te}break;case 3:var oe=r.stateNode.containerInfo;oe.nodeType===1?oe.textContent="":oe.nodeType===9&&oe.documentElement&&oe.removeChild(oe.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(a(163))}}catch(we){vt(r,r.return,we)}if(s=r.sibling,s!==null){s.return=r.return,Le=s;break}Le=r.return}return De=Gf,Gf=!1,De}function ri(s,r,l){var d=r.updateQueue;if(d=d!==null?d.lastEffect:null,d!==null){var f=d=d.next;do{if((f.tag&s)===s){var b=f.destroy;f.destroy=void 0,b!==void 0&&Bd(r,l,b)}f=f.next}while(f!==d)}}function No(s,r){if(r=r.updateQueue,r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&s)===s){var d=l.create;l.destroy=d()}l=l.next}while(l!==r)}}function Hd(s){var r=s.ref;if(r!==null){var l=s.stateNode;switch(s.tag){case 5:s=l;break;default:s=l}typeof r=="function"?r(s):r.current=s}}function Wf(s){var r=s.alternate;r!==null&&(s.alternate=null,Wf(r)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(r=s.stateNode,r!==null&&(delete r[dn],delete r[ql],delete r[ad],delete r[Xy],delete r[Yy])),s.stateNode=null,s.return=null,s.dependencies=null,s.memoizedProps=null,s.memoizedState=null,s.pendingProps=null,s.stateNode=null,s.updateQueue=null}function qf(s){return s.tag===5||s.tag===3||s.tag===4}function Qf(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||qf(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Vd(s,r,l){var d=s.tag;if(d===5||d===6)s=s.stateNode,r?l.nodeType===8?l.parentNode.insertBefore(s,r):l.insertBefore(s,r):(l.nodeType===8?(r=l.parentNode,r.insertBefore(s,l)):(r=l,r.appendChild(s)),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=Ji));else if(d!==4&&(s=s.child,s!==null))for(Vd(s,r,l),s=s.sibling;s!==null;)Vd(s,r,l),s=s.sibling}function Gd(s,r,l){var d=s.tag;if(d===5||d===6)s=s.stateNode,r?l.insertBefore(s,r):l.appendChild(s);else if(d!==4&&(s=s.child,s!==null))for(Gd(s,r,l),s=s.sibling;s!==null;)Gd(s,r,l),s=s.sibling}var Mt=null,Ys=!1;function pr(s,r,l){for(l=l.child;l!==null;)Kf(s,r,l),l=l.sibling}function Kf(s,r,l){if(qt&&typeof qt.onCommitFiberUnmount=="function")try{qt.onCommitFiberUnmount(Ur,l)}catch{}switch(l.tag){case 5:Wt||Xa(l,r);case 6:var d=Mt,f=Ys;Mt=null,pr(s,r,l),Mt=d,Ys=f,Mt!==null&&(Ys?(s=Mt,l=l.stateNode,s.nodeType===8?s.parentNode.removeChild(l):s.removeChild(l)):Mt.removeChild(l.stateNode));break;case 18:Mt!==null&&(Ys?(s=Mt,l=l.stateNode,s.nodeType===8?rd(s.parentNode,l):s.nodeType===1&&rd(s,l),Rn(s)):rd(Mt,l.stateNode));break;case 4:d=Mt,f=Ys,Mt=l.stateNode.containerInfo,Ys=!0,pr(s,r,l),Mt=d,Ys=f;break;case 0:case 11:case 14:case 15:if(!Wt&&(d=l.updateQueue,d!==null&&(d=d.lastEffect,d!==null))){f=d=d.next;do{var b=f,D=b.destroy;b=b.tag,D!==void 0&&((b&2)!==0||(b&4)!==0)&&Bd(l,r,D),f=f.next}while(f!==d)}pr(s,r,l);break;case 1:if(!Wt&&(Xa(l,r),d=l.stateNode,typeof d.componentWillUnmount=="function"))try{d.props=l.memoizedProps,d.state=l.memoizedState,d.componentWillUnmount()}catch(Q){vt(l,r,Q)}pr(s,r,l);break;case 21:pr(s,r,l);break;case 22:l.mode&1?(Wt=(d=Wt)||l.memoizedState!==null,pr(s,r,l),Wt=d):pr(s,r,l);break;default:pr(s,r,l)}}function Xf(s){var r=s.updateQueue;if(r!==null){s.updateQueue=null;var l=s.stateNode;l===null&&(l=s.stateNode=new h_),r.forEach(function(d){var f=N_.bind(null,s,d);l.has(d)||(l.add(d),d.then(f,f))})}}function Zs(s,r){var l=r.deletions;if(l!==null)for(var d=0;df&&(f=D),d&=~b}if(d=f,d=at()-d,d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3e3>d?3e3:4320>d?4320:1960*p_(d/1960))-d,10s?16:s,vr===null)var d=!1;else{if(s=vr,vr=null,Eo=0,(et&6)!==0)throw Error(a(331));var f=et;for(et|=4,Le=s.current;Le!==null;){var b=Le,D=b.child;if((Le.flags&16)!==0){var Q=b.deletions;if(Q!==null){for(var X=0;Xat()-Qd?Jr(s,0):qd|=l),ls(s,r)}function cx(s,r){r===0&&((s.mode&1)===0?r=1:(r=Fl,Fl<<=1,(Fl&130023424)===0&&(Fl=4194304)));var l=Kt();s=$n(s,r),s!==null&&(ot(s,r,l),ls(s,l))}function b_(s){var r=s.memoizedState,l=0;r!==null&&(l=r.retryLane),cx(s,l)}function N_(s,r){var l=0;switch(s.tag){case 13:var d=s.stateNode,f=s.memoizedState;f!==null&&(l=f.retryLane);break;case 19:d=s.stateNode;break;default:throw Error(a(314))}d!==null&&d.delete(r),cx(s,l)}var dx;dx=function(s,r,l){if(s!==null)if(s.memoizedProps!==r.pendingProps||ss.current)rs=!0;else{if((s.lanes&l)===0&&(r.flags&128)===0)return rs=!1,d_(s,r,l);rs=(s.flags&131072)!==0}else rs=!1,ht&&(r.flags&1048576)!==0&&Bh(r,ao,r.index);switch(r.lanes=0,r.tag){case 2:var d=r.type;_o(s,r),s=r.pendingProps;var f=Ua(r,Ht.current);qa(r,l),f=Sd(null,r,d,s,f,l);var b=Cd();return r.flags|=1,typeof f=="object"&&f!==null&&typeof f.render=="function"&&f.$$typeof===void 0?(r.tag=1,r.memoizedState=null,r.updateQueue=null,ns(d)?(b=!0,so(r)):b=!1,r.memoizedState=f.state!==null&&f.state!==void 0?f.state:null,vd(r),f.updater=jo,r.stateNode=f,f._reactInternals=r,Td(r,d,s,l),r=$d(null,r,d,!0,b,l)):(r.tag=0,ht&&b&&od(r),Qt(null,r,f,l),r=r.child),r;case 16:d=r.elementType;e:{switch(_o(s,r),s=r.pendingProps,f=d._init,d=f(d._payload),r.type=d,f=r.tag=S_(d),s=Xs(d,s),f){case 0:r=Dd(null,r,d,s,l);break e;case 1:r=$f(null,r,d,s,l);break e;case 11:r=Pf(null,r,d,s,l);break e;case 14:r=Tf(null,r,d,Xs(d.type,s),l);break e}throw Error(a(306,d,""))}return r;case 0:return d=r.type,f=r.pendingProps,f=r.elementType===d?f:Xs(d,f),Dd(s,r,d,f,l);case 1:return d=r.type,f=r.pendingProps,f=r.elementType===d?f:Xs(d,f),$f(s,r,d,f,l);case 3:e:{if(If(r),s===null)throw Error(a(387));d=r.pendingProps,b=r.memoizedState,f=b.element,Yh(s,r),mo(r,d,null,l);var D=r.memoizedState;if(d=D.element,b.isDehydrated)if(b={element:d,isDehydrated:!1,cache:D.cache,pendingSuspenseBoundaries:D.pendingSuspenseBoundaries,transitions:D.transitions},r.updateQueue.baseState=b,r.memoizedState=b,r.flags&256){f=Ka(Error(a(423)),r),r=Mf(s,r,d,l,f);break e}else if(d!==f){f=Ka(Error(a(424)),r),r=Mf(s,r,d,l,f);break e}else for(js=dr(r.stateNode.containerInfo.firstChild),vs=r,ht=!0,Ks=null,l=Kh(r,null,d,l),r.child=l;l;)l.flags=l.flags&-3|4096,l=l.sibling;else{if(Va(),d===f){r=Mn(s,r,l);break e}Qt(s,r,d,l)}r=r.child}return r;case 5:return ef(r),s===null&&ud(r),d=r.type,f=r.pendingProps,b=s!==null?s.memoizedProps:null,D=f.children,sd(d,f)?D=null:b!==null&&sd(d,b)&&(r.flags|=32),Df(s,r),Qt(s,r,D,l),r.child;case 6:return s===null&&ud(r),null;case 13:return Of(s,r,l);case 4:return jd(r,r.stateNode.containerInfo),d=r.pendingProps,s===null?r.child=Ga(r,null,d,l):Qt(s,r,d,l),r.child;case 11:return d=r.type,f=r.pendingProps,f=r.elementType===d?f:Xs(d,f),Pf(s,r,d,f,l);case 7:return Qt(s,r,r.pendingProps,l),r.child;case 8:return Qt(s,r,r.pendingProps.children,l),r.child;case 12:return Qt(s,r,r.pendingProps.children,l),r.child;case 10:e:{if(d=r.type._context,f=r.pendingProps,b=r.memoizedProps,D=f.value,dt(oo,d._currentValue),d._currentValue=D,b!==null)if(Qs(b.value,D)){if(b.children===f.children&&!ss.current){r=Mn(s,r,l);break e}}else for(b=r.child,b!==null&&(b.return=r);b!==null;){var Q=b.dependencies;if(Q!==null){D=b.child;for(var X=Q.firstContext;X!==null;){if(X.context===d){if(b.tag===1){X=In(-1,l&-l),X.tag=2;var de=b.updateQueue;if(de!==null){de=de.shared;var ge=de.pending;ge===null?X.next=X:(X.next=ge.next,ge.next=X),de.pending=X}}b.lanes|=l,X=b.alternate,X!==null&&(X.lanes|=l),pd(b.return,l,r),Q.lanes|=l;break}X=X.next}}else if(b.tag===10)D=b.type===r.type?null:b.child;else if(b.tag===18){if(D=b.return,D===null)throw Error(a(341));D.lanes|=l,Q=D.alternate,Q!==null&&(Q.lanes|=l),pd(D,l,r),D=b.sibling}else D=b.child;if(D!==null)D.return=b;else for(D=b;D!==null;){if(D===r){D=null;break}if(b=D.sibling,b!==null){b.return=D.return,D=b;break}D=D.return}b=D}Qt(s,r,f.children,l),r=r.child}return r;case 9:return f=r.type,d=r.pendingProps.children,qa(r,l),f=Ds(f),d=d(f),r.flags|=1,Qt(s,r,d,l),r.child;case 14:return d=r.type,f=Xs(d,r.pendingProps),f=Xs(d.type,f),Tf(s,r,d,f,l);case 15:return Lf(s,r,r.type,r.pendingProps,l);case 17:return d=r.type,f=r.pendingProps,f=r.elementType===d?f:Xs(d,f),_o(s,r),r.tag=1,ns(d)?(s=!0,so(r)):s=!1,qa(r,l),wf(r,d,f),Td(r,d,f,l),$d(null,r,d,!0,s,l);case 19:return Uf(s,r,l);case 22:return Ff(s,r,l)}throw Error(a(156,r.tag))};function ux(s,r){return Gs(s,r)}function w_(s,r,l,d){this.tag=s,this.key=l,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=r,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=d,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ms(s,r,l,d){return new w_(s,r,l,d)}function su(s){return s=s.prototype,!(!s||!s.isReactComponent)}function S_(s){if(typeof s=="function")return su(s)?1:0;if(s!=null){if(s=s.$$typeof,s===L)return 11;if(s===G)return 14}return 2}function _r(s,r){var l=s.alternate;return l===null?(l=Ms(s.tag,r,s.key,s.mode),l.elementType=s.elementType,l.type=s.type,l.stateNode=s.stateNode,l.alternate=s,s.alternate=l):(l.pendingProps=r,l.type=s.type,l.flags=0,l.subtreeFlags=0,l.deletions=null),l.flags=s.flags&14680064,l.childLanes=s.childLanes,l.lanes=s.lanes,l.child=s.child,l.memoizedProps=s.memoizedProps,l.memoizedState=s.memoizedState,l.updateQueue=s.updateQueue,r=s.dependencies,l.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext},l.sibling=s.sibling,l.index=s.index,l.ref=s.ref,l}function To(s,r,l,d,f,b){var D=2;if(d=s,typeof s=="function")su(s)&&(D=1);else if(typeof s=="string")D=5;else e:switch(s){case F:return ta(l.children,f,b,r);case I:D=8,f|=8;break;case M:return s=Ms(12,l,r,f|2),s.elementType=M,s.lanes=b,s;case z:return s=Ms(13,l,r,f),s.elementType=z,s.lanes=b,s;case Y:return s=Ms(19,l,r,f),s.elementType=Y,s.lanes=b,s;case ae:return Lo(l,f,b,r);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case $:D=10;break e;case O:D=9;break e;case L:D=11;break e;case G:D=14;break e;case U:D=16,d=null;break e}throw Error(a(130,s==null?s:typeof s,""))}return r=Ms(D,l,r,f),r.elementType=s,r.type=d,r.lanes=b,r}function ta(s,r,l,d){return s=Ms(7,s,d,r),s.lanes=l,s}function Lo(s,r,l,d){return s=Ms(22,s,d,r),s.elementType=ae,s.lanes=l,s.stateNode={isHidden:!1},s}function nu(s,r,l){return s=Ms(6,s,null,r),s.lanes=l,s}function ru(s,r,l){return r=Ms(4,s.children!==null?s.children:[],s.key,r),r.lanes=l,r.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},r}function C_(s,r,l,d,f){this.tag=r,this.containerInfo=s,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ye(0),this.expirationTimes=Ye(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ye(0),this.identifierPrefix=d,this.onRecoverableError=f,this.mutableSourceEagerHydrationData=null}function au(s,r,l,d,f,b,D,Q,X){return s=new C_(s,r,l,Q,X),r===1?(r=1,b===!0&&(r|=8)):r=0,b=Ms(3,null,null,r),s.current=b,b.stateNode=s,b.memoizedState={element:d,isDehydrated:l,cache:null,transitions:null,pendingSuspenseBoundaries:null},vd(b),s}function k_(s,r,l){var d=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),uu.exports=H_(),uu.exports}var Sx;function V_(){if(Sx)return Uo;Sx=1;var t=fg();return Uo.createRoot=t.createRoot,Uo.hydrateRoot=t.hydrateRoot,Uo}var G_=V_();/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W_=t=>t==null?void 0:t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */function q_(t,n,a=[]){if(n==null)throw new Error("[lucide]: iconNode is required when icon name is used");return{name:W_(t),size:24,node:n,...a.length>0?{aliases:a}:{}}}/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q_=t=>{let n="",a=!1;for(const o of t){if(o==="-"||o==="_"||o<=" "){a=n.length>0;continue}n.length===0?n+=o.toLowerCase():n+=a?o.toUpperCase():o,a=!1}return n};/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K_=t=>{const n=Q_(t);return n.charAt(0).toUpperCase()+n.slice(1)};/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sm=(...t)=>t.filter((n,a,o)=>!!n&&n.trim()!==""&&o.indexOf(n)===a).join(" ").trim();/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sa={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"};/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */function fu(t){return t!=null}function X_(t,n={}){var w,_;const a=n.attributeNames??{},o=S=>a[S]??S,c=t.size??t.width??sa.width,u=t.size??t.height??sa.height,h=((w=t.aliases)==null?void 0:w.filter(S=>typeof S=="string"&&S.trim()!=="").map(S=>`lucide-${S}`))??[],m=[...t.name?[`lucide-${t.name}`]:[],...h],x=((_=n.className)==null?void 0:_.split(" ").filter(Boolean))??[],v=n.includeDefaultClasses===!1?sm(...x):sm("lucide",...m,...x),N=n.absoluteStrokeWidth?Number(n.strokeWidth??sa["stroke-width"])*Number(t.size??t.width??sa.width)/Number(n.size??n.width??sa.width):n.strokeWidth??sa["stroke-width"];return["svg",{...Object.entries(sa).reduce((S,[y,g])=>(S[o(y)]=g,S),{}),..."color"in n&&n.color&&{[o("stroke")]:n.color},..."size"in n&&fu(n.size)&&{[o("width")]:n.size,[o("height")]:n.size},..."width"in n&&fu(n.width)&&{[o("width")]:n.width},..."height"in n&&fu(n.height)&&{[o("height")]:n.height},[o("stroke-width")]:N,...v&&{[o("class")]:v},[o("viewBox")]:`0 0 ${c} ${u}`,...n.hasA11yProp===!1?{[o("aria-hidden")]:"true"}:{},..."attributes"in n&&n.attributes},t.node.map(S=>{const[y,g,p]=S,k=n.nonScalingStroke?{[o("vector-effect")]:"non-scaling-stroke",...g}:g;return p?[y,k,p]:[y,k]})]}/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */function Y_(t,n={}){return X_(t,{...n,attributeNames:{...n.attributeNames,class:"className","stroke-width":"strokeWidth","stroke-linecap":"strokeLinecap","stroke-linejoin":"strokeLinejoin","vector-effect":"vectorEffect"}})}/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z_=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},J_=i.createContext({}),eb=()=>i.useContext(J_),tb=i.forwardRef(({color:t,size:n,width:a,height:o,strokeWidth:c,absoluteStrokeWidth:u,nonScalingStroke:h,className:m="",children:x,iconNode:v=[],icon:N={node:v,aliases:[],size:24},...j},w)=>{const{size:_=24,strokeWidth:S=2,absoluteStrokeWidth:y=!1,nonScalingStroke:g=!1,color:p="currentColor",className:k=""}=eb()??{},R=!!x||Z_(j),[C,E,P=[]]=Y_(N,{color:t??p,width:a??n??_,height:o??n??_,strokeWidth:c??S,absoluteStrokeWidth:u??y,nonScalingStroke:h??g,className:sm(k,m),hasA11yProp:R,attributes:j});return i.createElement(C,{ref:w,...E},[...P.map(([F,I])=>i.createElement(F,I)),...Array.isArray(x)?x:[x]])});/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */function st(t,n=[],a=[]){const o=typeof t=="string"?q_(t,n,a):t,c=i.forwardRef(({className:u,...h},m)=>i.createElement(tb,{ref:m,icon:o,className:u,...h}));return o.name&&(c.displayName=K_(o.name)),c}/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xg={name:"activity",size:24,node:[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]};xg.node;const sb=st(xg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pg={name:"arrow-right",size:24,node:[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]};pg.node;const Am=st(pg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gg={name:"badge-check",size:24,node:[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m16 9-5.5 5.5L8 12",key:"xofnsj"}]],aliases:["verified"]};gg.node;const vg=st(gg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jg={name:"ban",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}]]};jg.node;const nb=st(jg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yg={name:"boxes",size:24,node:[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]]};yg.node;const rb=st(yg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _g={name:"calculator",size:24,node:[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]};_g.node;const ab=st(_g);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bg={name:"chart-line",size:24,node:[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]],aliases:["line-chart"]};bg.node;const Ng=st(bg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wg={name:"chevron-down",size:24,node:[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]};wg.node;const Sg=st(wg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cg={name:"circle-dot",size:24,node:[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]};Cg.node;const lb=st(Cg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kg={name:"circle-pause",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]],aliases:["pause-circle"]};kg.node;const ib=st(kg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eg={name:"clipboard-list",size:24,node:[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]};Eg.node;const Ag=st(Eg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rg={name:"clock-3",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]]};Rg.node;const ob=st(Rg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pg={name:"clock",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]]};Pg.node;const cb=st(Pg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tg={name:"database",size:24,node:[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]};Tg.node;const Rm=st(Tg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lg={name:"earth",size:24,node:[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],aliases:["globe-2"]};Lg.node;const db=st(Lg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fg={name:"file-code-corner",size:24,node:[["path",{d:"M4 12.15V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2h-3.35",key:"1wthlu"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m5 16-3 3 3 3",key:"331omg"}],["path",{d:"m9 22 3-3-3-3",key:"lsp7cz"}]],aliases:["file-code-2"]};Fg.node;const ub=st(Fg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dg={name:"file-text",size:24,node:[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]};Dg.node;const $g=st(Dg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ig={name:"inbox",size:24,node:[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 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",key:"oot6mr"}]]};Ig.node;const mb=st(Ig);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mg={name:"landmark",size:24,node:[["path",{d:"M10 18v-7",key:"wt116b"}],["path",{d:"M11.119 2.205a2 2 0 0 1 1.762 0l7.84 3.846A.5.5 0 0 1 20.5 7h-17a.5.5 0 0 1-.22-.949z",key:"yxxwt6"}],["path",{d:"M14 18v-7",key:"vav6t3"}],["path",{d:"M18 18v-7",key:"aexdmj"}],["path",{d:"M3 22h18",key:"8prr45"}],["path",{d:"M6 18v-7",key:"1ivflk"}]]};Mg.node;const nm=st(Mg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Og={name:"layers",size:24,node:[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],aliases:["layers-3"]};Og.node;const hb=st(Og);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zg={name:"map-pin",size:24,node:[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]};zg.node;const fb=st(zg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ug={name:"message-square",size:24,node:[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]]};Ug.node;const xb=st(Ug);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bg={name:"moon",size:24,node:[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]]};Bg.node;const pb=st(Bg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hg={name:"network",size:24,node:[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]};Hg.node;const Vg=st(Hg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gg={name:"scan-text",size:24,node:[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 8h8",key:"1jbsf9"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h6",key:"1vyc9m"}]]};Gg.node;const gb=st(Gg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wg={name:"search",size:24,node:[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]};Wg.node;const qg=st(Wg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qg={name:"settings",size:24,node:[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]};Qg.node;const vb=st(Qg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kg={name:"shield-check",size:24,node:[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]};Kg.node;const Xg=st(Kg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yg={name:"sun",size:24,node:[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]};Yg.node;const jb=st(Yg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zg={name:"user-round",size:24,node:[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],aliases:["user-2"]};Zg.node;const yb=st(Zg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jg={name:"wallet",size:24,node:[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]};Jg.node;const _b=st(Jg);/** * @license lucide-react v1.51.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ev={name:"x",size:24,node:[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]};ev.node;const bb=st(ev),Nb="/api";class ul extends Error{constructor(a,o,c,u){super(a);zo(this,"status");zo(this,"code");zo(this,"detail");this.name="ApiError",this.status=o,this.code=c,this.detail=u}}async function Ai(t,n,a,o){const c=await fetch(`${Nb}${n}`,{method:t,credentials:"include",headers:{"Content-Type":"application/json",...o??{}},body:a===void 0?void 0:JSON.stringify(a)});if(!c.ok){const u=await c.json().catch(()=>({}));throw new ul(u.message??`${t} ${n} failed: ${c.status}`,c.status,u.code??null,u.detail??null)}return c.status===204?null:c.json()}const he=(t,n)=>Ai("GET",t,void 0,n),be=(t,n,a)=>Ai("POST",t,n,a),Ri=(t,n,a)=>Ai("PUT",t,n,a),pl=(t,n,a)=>Ai("PATCH",t,n,a),Pm=(t,n,a)=>Ai("DELETE",t,a,n);function wb(t){return he("/ingestion/health")}function Sb(){return he("/connectors")}function Cb(t){return be("/ingestion/runs",{})}const kb=["PASS","WARNING","HOLD","FAILED","OVERRIDE"],qn="/v1/quality",Pi="/v1/audit",zt=t=>({"x-subscriber-tier":t.tier,"x-user-role":t.role,"x-user-id":t.user_id}),Ti=t=>{const n=new URLSearchParams;for(const[o,c]of Object.entries(t))c!=null&&c!==""&&n.set(o,String(c));const a=n.toString();return a?`?${a}`:""},Pr=encodeURIComponent,Eb=(t,n)=>he(`${qn}/lines${Ti(n)}`,zt(t)),Ab=(t,n,a)=>be(`${qn}/lines/${Pr(n)}/overrides`,a,zt(t)),Rb=(t,n)=>he(`${qn}/scores${Ti(n)}`,zt(t)),Pb=(t,n)=>he(`${qn}/dashboard${Ti({cycle:n})}`,zt(t)),Tb=(t,n)=>be(`${qn}/regression/runs`,n,zt(t)),Lb=(t,n)=>he(`${qn}/regression/runs/${Pr(n)}`,zt(t)),Fb=(t,n)=>be(`${qn}/regression/suite/exclusions`,n,zt(t)),Db=(t,n)=>he(`${qn}/releases/${Pr(n)}`,zt(t)),$b=(t,n)=>be(`${qn}/releases/${Pr(n)}/signatures`,{},zt(t)),Ib=(t,n)=>he(`${Pi}/entries${Ti(n)}`,zt(t)),Mb=t=>be(`${Pi}/verifications`,{},zt(t)),Ob=(t,n)=>be(`${Pi}/exports`,n,zt(t)),zb=(t,n)=>he(`${Pi}/exports/${Pr(n)}`,zt(t)),Ub=(t,n)=>be(`${Pi}/reconciliations`,n,zt(t)),Bb=(t,n,a)=>he(`/v1/opportunity-cards/${Pr(n)}/provenance${Ti({metric:a})}`,zt(t)),Hb=(t,n,a="json")=>be(`/v1/opportunity-cards/${Pr(n)}/provenance/exports`,{format:a},zt(t)),Vb=(t,n,a)=>be(`/v1/ingestion/windows/${Pr(n)}/decision`,a,zt(t));function tv(t){var n,a,o="";if(typeof t=="string"||typeof t=="number")o+=t;else if(typeof t=="object")if(Array.isArray(t)){var c=t.length;for(n=0;n{const a=new Array(t.length+n.length);for(let o=0;o({classGroupId:t,validator:n}),nv=(t=new Map,n=null,a)=>({nextPart:t,validators:n,classGroupId:a}),oc="-",Cx=[],qb="arbitrary..",Qb=t=>{const n=Xb(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:o}=t;return{getClassGroupId:h=>{if(h.startsWith("[")&&h.endsWith("]"))return Kb(h);const m=h.split(oc),x=m[0]===""&&m.length>1?1:0;return rv(m,x,n)},getConflictingClassGroupIds:(h,m)=>{if(m){const x=o[h],v=a[h];return x?v?Gb(v,x):x:v||Cx}return a[h]||Cx}}},rv=(t,n,a)=>{if(t.length-n===0)return a.classGroupId;const c=t[n],u=a.nextPart.get(c);if(u){const v=rv(t,n+1,u);if(v)return v}const h=a.validators;if(h===null)return;const m=n===0?t.join(oc):t.slice(n).join(oc),x=h.length;for(let v=0;vt.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const n=t.slice(1,-1),a=n.indexOf(":"),o=n.slice(0,a);return o?qb+o:void 0})(),Xb=t=>{const{theme:n,classGroups:a}=t;return Yb(a,n)},Yb=(t,n)=>{const a=nv();for(const o in t){const c=t[o];Tm(c,a,o,n)}return a},Tm=(t,n,a,o)=>{const c=t.length;for(let u=0;u{if(typeof t=="string"){Jb(t,n,a);return}if(typeof t=="function"){e0(t,n,a,o);return}t0(t,n,a,o)},Jb=(t,n,a)=>{const o=t===""?n:av(n,t);o.classGroupId=a},e0=(t,n,a,o)=>{if(s0(t)){Tm(t(o),n,a,o);return}n.validators===null&&(n.validators=[]),n.validators.push(Wb(a,t))},t0=(t,n,a,o)=>{const c=Object.entries(t),u=c.length;for(let h=0;h{let a=t;const o=n.split(oc),c=o.length;for(let u=0;u"isThemeGetter"in t&&t.isThemeGetter===!0,n0=t=>{if(t<1)return{get:()=>{},set:()=>{}};let n=0,a=Object.create(null),o=Object.create(null);const c=(u,h)=>{a[u]=h,n++,n>t&&(n=0,o=a,a=Object.create(null))};return{get(u){let h=a[u];if(h!==void 0)return h;if((h=o[u])!==void 0)return c(u,h),h},set(u,h){u in a?a[u]=h:c(u,h)}}},rm="!",kx=":",r0=[],Ex=(t,n,a,o,c)=>({modifiers:t,hasImportantModifier:n,baseClassName:a,maybePostfixModifierPosition:o,isExternal:c}),a0=t=>{const{prefix:n,experimentalParseClassName:a}=t;let o=c=>{const u=[];let h=0,m=0,x=0,v;const N=c.length;for(let y=0;yx?v-x:void 0;return Ex(u,_,w,S)};if(n){const c=n+kx,u=o;o=h=>h.startsWith(c)?u(h.slice(c.length)):Ex(r0,!1,h,void 0,!0)}if(a){const c=o;o=u=>a({className:u,parseClassName:c})}return o},l0=t=>{const n=new Map;return t.orderSensitiveModifiers.forEach((a,o)=>{n.set(a,1e6+o)}),a=>{const o=[];let c=[];for(let u=0;u0&&(c.sort(),o.push(...c),c=[]),o.push(h)):c.push(h)}return c.length>0&&(c.sort(),o.push(...c)),o}},i0=t=>({cache:n0(t.cacheSize),parseClassName:a0(t),sortModifiers:l0(t),postfixLookupClassGroupIds:o0(t),...Qb(t)}),o0=t=>{const n=Object.create(null),a=t.postfixLookupClassGroups;if(a)for(let o=0;o{const{parseClassName:a,getClassGroupId:o,getConflictingClassGroupIds:c,sortModifiers:u,postfixLookupClassGroupIds:h}=n,m=[],x=t.trim().split(c0);let v="";for(let N=x.length-1;N>=0;N-=1){const j=x[N],{isExternal:w,modifiers:_,hasImportantModifier:S,baseClassName:y,maybePostfixModifierPosition:g}=a(j);if(w){v=j+(v.length>0?" "+v:v);continue}let p=!!g,k;if(p){const F=y.substring(0,g);k=o(F);const I=k&&h[k]?o(y):void 0;I&&I!==k&&(k=I,p=!1)}else k=o(y);if(!k){if(!p){v=j+(v.length>0?" "+v:v);continue}if(k=o(y),!k){v=j+(v.length>0?" "+v:v);continue}p=!1}const R=_.length===0?"":_.length===1?_[0]:u(_).join(":"),C=S?R+rm:R,E=C+k;if(m.indexOf(E)>-1)continue;m.push(E);const P=c(k,p);for(let F=0;F0?" "+v:v)}return v},u0=(...t)=>{let n=0,a,o,c="";for(;n{if(typeof t=="string")return t;let n,a="";for(let o=0;o{let a,o,c,u;const h=x=>{const v=n.reduce((N,j)=>j(N),t());return a=i0(v),o=a.cache.get,c=a.cache.set,u=m,m(x)},m=x=>{const v=o(x);if(v)return v;const N=d0(x,a);return c(x,N),N};return u=h,(...x)=>u(u0(...x))},h0=[],Ct=t=>{const n=a=>a[t]||h0;return n.isThemeGetter=!0,n.themeKey=t,n},iv=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,ov=/^\((?:(\w[\w-]*):)?(.+)\)$/i,f0=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,x0=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,p0=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,g0=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix|color|light-dark)\(.+\)$/,v0=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,j0=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Nr=t=>f0.test(t),qe=t=>!!t&&!Number.isNaN(Number(t)),fn=t=>!!t&&Number.isInteger(Number(t)),xu=t=>t.endsWith("%")&&qe(t.slice(0,-1)),zn=t=>x0.test(t),cv=()=>!0,y0=t=>p0.test(t)&&!g0.test(t),Lm=()=>!1,_0=t=>v0.test(t),b0=t=>j0.test(t),N0=t=>!Te(t)&&!Fe(t),w0=t=>t.startsWith("@container")&&(t[10]==="/"&&t[11]!==void 0||t[11]==="s"&&t[16]!==void 0&&t.startsWith("-size/",10)||t[11]==="n"&&t[18]!==void 0&&t.startsWith("-normal/",10)),S0=t=>Tr(t,mv,Lm),Te=t=>iv.test(t),na=t=>Tr(t,hv,y0),Ax=t=>Tr(t,L0,qe),C0=t=>Tr(t,xv,cv),k0=t=>Tr(t,fv,Lm),Rx=t=>Tr(t,dv,Lm),E0=t=>Tr(t,uv,b0),Bo=t=>Tr(t,pv,_0),Fe=t=>ov.test(t),di=t=>xa(t,hv),A0=t=>xa(t,fv),Px=t=>xa(t,dv),R0=t=>xa(t,mv),P0=t=>xa(t,uv),Ho=t=>xa(t,pv,!0),T0=t=>xa(t,xv,!0),Tr=(t,n,a)=>{const o=iv.exec(t);return o?o[1]?n(o[1]):a(o[2]):!1},xa=(t,n,a=!1)=>{const o=ov.exec(t);return o?o[1]?n(o[1]):a:!1},dv=t=>t==="position"||t==="percentage",uv=t=>t==="image"||t==="url",mv=t=>t==="length"||t==="size"||t==="bg-size",hv=t=>t==="length",L0=t=>t==="number",fv=t=>t==="family-name",xv=t=>t==="number"||t==="weight",pv=t=>t==="shadow",F0=()=>{const t=Ct("color"),n=Ct("font"),a=Ct("text"),o=Ct("font-weight"),c=Ct("tracking"),u=Ct("leading"),h=Ct("breakpoint"),m=Ct("container"),x=Ct("spacing"),v=Ct("radius"),N=Ct("shadow"),j=Ct("inset-shadow"),w=Ct("text-shadow"),_=Ct("drop-shadow"),S=Ct("blur"),y=Ct("perspective"),g=Ct("aspect"),p=Ct("ease"),k=Ct("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],C=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],E=()=>[...C(),Fe,Te],P=()=>["auto","hidden","clip","visible","scroll"],F=()=>["auto","contain","none"],I=()=>[Fe,Te,x],M=()=>[Nr,"full","auto",...I()],$=()=>[fn,"none","subgrid",Fe,Te],O=()=>["auto",{span:["full",fn,Fe,Te]},fn,Fe,Te],L=()=>[fn,"auto",Fe,Te],z=()=>["auto","min","max","fr",Fe,Te],Y=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],G=()=>["start","end","center","stretch","center-safe","end-safe"],U=()=>["auto",...I()],ae=()=>[Nr,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...I()],W=()=>[m,Nr,"screen","full","dvw","lvw","svw","min","max","fit",...I()],se=()=>[Nr,"screen","full","lh","dvh","lvh","svh","min","max","fit",...I()],ne=()=>[t,Fe,Te],q=()=>[...C(),Px,Rx,{position:[Fe,Te]}],J=()=>["no-repeat",{repeat:["","x","y","space","round"]}],le=()=>["auto","cover","contain",R0,S0,{size:[Fe,Te]}],ke=()=>[xu,di,na],Ce=()=>["","none","full",v,Fe,Te],Ae=()=>["",qe,di,na],Z=()=>["solid","dashed","dotted","double"],fe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],re=()=>[qe,xu,Px,Rx],Ee=()=>["","none",S,Fe,Te],nt=()=>["none",qe,Fe,Te],ct=()=>["none",qe,Fe,Te],Ut=()=>[qe,Fe,Te],Yt=()=>[Nr,"full",...I()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[zn],breakpoint:[zn],color:[cv],container:[zn],"drop-shadow":[zn],ease:["in","out","in-out"],font:[N0],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[zn],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[zn],shadow:[zn],spacing:["px",qe],text:[zn],"text-shadow":[zn],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Nr,Te,Fe,g]}],container:["container"],"container-type":[{"@container":["","normal","size",Fe,Te]}],"container-named":[w0],columns:[{columns:[qe,"auto",Te,Fe,m]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:E()}],overflow:[{overflow:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:M()}],"inset-x":[{"inset-x":M()}],"inset-y":[{"inset-y":M()}],start:[{"inset-s":M(),start:M()}],end:[{"inset-e":M(),end:M()}],"inset-bs":[{"inset-bs":M()}],"inset-be":[{"inset-be":M()}],top:[{top:M()}],right:[{right:M()}],bottom:[{bottom:M()}],left:[{left:M()}],visibility:["visible","invisible","collapse"],z:[{z:[fn,"auto",Fe,Te]}],basis:[{basis:[Nr,"full","auto",m,...I()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[qe,Nr,"auto","initial","none",Te]}],grow:[{grow:["",qe,Fe,Te]}],shrink:[{shrink:["",qe,Fe,Te]}],order:[{order:[fn,"first","last","none",Fe,Te]}],"grid-cols":[{"grid-cols":$()}],"col-start-end":[{col:O()}],"col-start":[{"col-start":L()}],"col-end":[{"col-end":L()}],"grid-rows":[{"grid-rows":$()}],"row-start-end":[{row:O()}],"row-start":[{"row-start":L()}],"row-end":[{"row-end":L()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":z()}],"auto-rows":[{"auto-rows":z()}],gap:[{gap:I()}],"gap-x":[{"gap-x":I()}],"gap-y":[{"gap-y":I()}],"justify-content":[{justify:[...Y(),"normal"]}],"justify-items":[{"justify-items":[...G(),"normal"]}],"justify-self":[{"justify-self":["auto",...G()]}],"align-content":[{content:["normal",...Y()]}],"align-items":[{items:[...G(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...G(),{baseline:["","last"]}]}],"place-content":[{"place-content":Y()}],"place-items":[{"place-items":[...G(),"baseline"]}],"place-self":[{"place-self":["auto",...G()]}],p:[{p:I()}],px:[{px:I()}],py:[{py:I()}],ps:[{ps:I()}],pe:[{pe:I()}],pbs:[{pbs:I()}],pbe:[{pbe:I()}],pt:[{pt:I()}],pr:[{pr:I()}],pb:[{pb:I()}],pl:[{pl:I()}],m:[{m:U()}],mx:[{mx:U()}],my:[{my:U()}],ms:[{ms:U()}],me:[{me:U()}],mbs:[{mbs:U()}],mbe:[{mbe:U()}],mt:[{mt:U()}],mr:[{mr:U()}],mb:[{mb:U()}],ml:[{ml:U()}],"space-x":[{"space-x":I()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":I()}],"space-y-reverse":["space-y-reverse"],size:[{size:ae()}],"inline-size":[{inline:["auto",...W()]}],"min-inline-size":[{"min-inline":["auto",...W()]}],"max-inline-size":[{"max-inline":["none",...W()]}],"block-size":[{block:["auto",...se()]}],"min-block-size":[{"min-block":["auto",...se()]}],"max-block-size":[{"max-block":["none",...se()]}],w:[{w:[m,"screen",...ae()]}],"min-w":[{"min-w":[m,"screen","none",...ae()]}],"max-w":[{"max-w":[m,"screen","none","prose",{screen:[h]},...ae()]}],h:[{h:["screen","lh",...ae()]}],"min-h":[{"min-h":["screen","lh","none",...ae()]}],"max-h":[{"max-h":["screen","lh","none",...ae()]}],"font-size":[{text:["base",a,di,na]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,T0,C0]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",xu,Te]}],"font-family":[{font:[A0,k0,n]}],"font-features":[{"font-features":[Te]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[c,Fe,Te]}],"line-clamp":[{"line-clamp":[qe,"none",Fe,Ax]}],leading:[{leading:["none",u,...I()]}],"list-image":[{"list-image":["none",Fe,Te]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Fe,Te]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:ne()}],"text-color":[{text:ne()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Z(),"wavy"]}],"text-decoration-thickness":[{decoration:[qe,"from-font","auto",Fe,na]}],"text-decoration-color":[{decoration:ne()}],"underline-offset":[{"underline-offset":[qe,"auto",Fe,Te]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:I()}],"tab-size":[{tab:[fn,Fe,Te]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Fe,Te]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Fe,Te]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:q()}],"bg-repeat":[{bg:J()}],"bg-size":[{bg:le()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},fn,Fe,Te],radial:["",Fe,Te],conic:["",fn,Fe,Te]},P0,E0]}],"bg-color":[{bg:ne()}],"gradient-from-pos":[{from:ke()}],"gradient-via-pos":[{via:ke()}],"gradient-to-pos":[{to:ke()}],"gradient-from":[{from:ne()}],"gradient-via":[{via:ne()}],"gradient-to":[{to:ne()}],rounded:[{rounded:Ce()}],"rounded-s":[{"rounded-s":Ce()}],"rounded-e":[{"rounded-e":Ce()}],"rounded-t":[{"rounded-t":Ce()}],"rounded-r":[{"rounded-r":Ce()}],"rounded-b":[{"rounded-b":Ce()}],"rounded-l":[{"rounded-l":Ce()}],"rounded-ss":[{"rounded-ss":Ce()}],"rounded-se":[{"rounded-se":Ce()}],"rounded-ee":[{"rounded-ee":Ce()}],"rounded-es":[{"rounded-es":Ce()}],"rounded-tl":[{"rounded-tl":Ce()}],"rounded-tr":[{"rounded-tr":Ce()}],"rounded-br":[{"rounded-br":Ce()}],"rounded-bl":[{"rounded-bl":Ce()}],"border-w":[{border:Ae()}],"border-w-x":[{"border-x":Ae()}],"border-w-y":[{"border-y":Ae()}],"border-w-s":[{"border-s":Ae()}],"border-w-e":[{"border-e":Ae()}],"border-w-bs":[{"border-bs":Ae()}],"border-w-be":[{"border-be":Ae()}],"border-w-t":[{"border-t":Ae()}],"border-w-r":[{"border-r":Ae()}],"border-w-b":[{"border-b":Ae()}],"border-w-l":[{"border-l":Ae()}],"divide-x":[{"divide-x":Ae()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Ae()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Z(),"hidden","none"]}],"divide-style":[{divide:[...Z(),"hidden","none"]}],"border-color":[{border:ne()}],"border-color-x":[{"border-x":ne()}],"border-color-y":[{"border-y":ne()}],"border-color-s":[{"border-s":ne()}],"border-color-e":[{"border-e":ne()}],"border-color-bs":[{"border-bs":ne()}],"border-color-be":[{"border-be":ne()}],"border-color-t":[{"border-t":ne()}],"border-color-r":[{"border-r":ne()}],"border-color-b":[{"border-b":ne()}],"border-color-l":[{"border-l":ne()}],"divide-color":[{divide:ne()}],"outline-style":[{outline:[...Z(),"none","hidden"]}],"outline-offset":[{"outline-offset":[qe,Fe,Te]}],"outline-w":[{outline:["",qe,di,na]}],"outline-color":[{outline:ne()}],shadow:[{shadow:["","inner","none",N,Ho,Bo]}],"shadow-color":[{shadow:ne()}],"inset-shadow":[{"inset-shadow":["none",j,Ho,Bo]}],"inset-shadow-color":[{"inset-shadow":ne()}],"ring-w":[{ring:Ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:ne()}],"ring-offset-w":[{"ring-offset":[qe,na]}],"ring-offset-color":[{"ring-offset":ne()}],"inset-ring-w":[{"inset-ring":Ae()}],"inset-ring-color":[{"inset-ring":ne()}],"text-shadow":[{"text-shadow":["none",w,Ho,Bo]}],"text-shadow-color":[{"text-shadow":ne()}],opacity:[{opacity:[qe,Fe,Te]}],"mix-blend":[{"mix-blend":[...fe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":fe()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[qe]}],"mask-image-linear-from-pos":[{"mask-linear-from":re()}],"mask-image-linear-to-pos":[{"mask-linear-to":re()}],"mask-image-linear-from-color":[{"mask-linear-from":ne()}],"mask-image-linear-to-color":[{"mask-linear-to":ne()}],"mask-image-t-from-pos":[{"mask-t-from":re()}],"mask-image-t-to-pos":[{"mask-t-to":re()}],"mask-image-t-from-color":[{"mask-t-from":ne()}],"mask-image-t-to-color":[{"mask-t-to":ne()}],"mask-image-r-from-pos":[{"mask-r-from":re()}],"mask-image-r-to-pos":[{"mask-r-to":re()}],"mask-image-r-from-color":[{"mask-r-from":ne()}],"mask-image-r-to-color":[{"mask-r-to":ne()}],"mask-image-b-from-pos":[{"mask-b-from":re()}],"mask-image-b-to-pos":[{"mask-b-to":re()}],"mask-image-b-from-color":[{"mask-b-from":ne()}],"mask-image-b-to-color":[{"mask-b-to":ne()}],"mask-image-l-from-pos":[{"mask-l-from":re()}],"mask-image-l-to-pos":[{"mask-l-to":re()}],"mask-image-l-from-color":[{"mask-l-from":ne()}],"mask-image-l-to-color":[{"mask-l-to":ne()}],"mask-image-x-from-pos":[{"mask-x-from":re()}],"mask-image-x-to-pos":[{"mask-x-to":re()}],"mask-image-x-from-color":[{"mask-x-from":ne()}],"mask-image-x-to-color":[{"mask-x-to":ne()}],"mask-image-y-from-pos":[{"mask-y-from":re()}],"mask-image-y-to-pos":[{"mask-y-to":re()}],"mask-image-y-from-color":[{"mask-y-from":ne()}],"mask-image-y-to-color":[{"mask-y-to":ne()}],"mask-image-radial":[{"mask-radial":[Fe,Te]}],"mask-image-radial-from-pos":[{"mask-radial-from":re()}],"mask-image-radial-to-pos":[{"mask-radial-to":re()}],"mask-image-radial-from-color":[{"mask-radial-from":ne()}],"mask-image-radial-to-color":[{"mask-radial-to":ne()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":C()}],"mask-image-conic-pos":[{"mask-conic":[qe]}],"mask-image-conic-from-pos":[{"mask-conic-from":re()}],"mask-image-conic-to-pos":[{"mask-conic-to":re()}],"mask-image-conic-from-color":[{"mask-conic-from":ne()}],"mask-image-conic-to-color":[{"mask-conic-to":ne()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:q()}],"mask-repeat":[{mask:J()}],"mask-size":[{mask:le()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Fe,Te]}],filter:[{filter:["","none",Fe,Te]}],blur:[{blur:Ee()}],brightness:[{brightness:[qe,Fe,Te]}],contrast:[{contrast:[qe,Fe,Te]}],"drop-shadow":[{"drop-shadow":["","none",_,Ho,Bo]}],"drop-shadow-color":[{"drop-shadow":ne()}],grayscale:[{grayscale:["",qe,Fe,Te]}],"hue-rotate":[{"hue-rotate":[qe,Fe,Te]}],invert:[{invert:["",qe,Fe,Te]}],saturate:[{saturate:[qe,Fe,Te]}],sepia:[{sepia:["",qe,Fe,Te]}],"backdrop-filter":[{"backdrop-filter":["","none",Fe,Te]}],"backdrop-blur":[{"backdrop-blur":Ee()}],"backdrop-brightness":[{"backdrop-brightness":[qe,Fe,Te]}],"backdrop-contrast":[{"backdrop-contrast":[qe,Fe,Te]}],"backdrop-grayscale":[{"backdrop-grayscale":["",qe,Fe,Te]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[qe,Fe,Te]}],"backdrop-invert":[{"backdrop-invert":["",qe,Fe,Te]}],"backdrop-opacity":[{"backdrop-opacity":[qe,Fe,Te]}],"backdrop-saturate":[{"backdrop-saturate":[qe,Fe,Te]}],"backdrop-sepia":[{"backdrop-sepia":["",qe,Fe,Te]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":I()}],"border-spacing-x":[{"border-spacing-x":I()}],"border-spacing-y":[{"border-spacing-y":I()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Fe,Te]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[qe,"initial",Fe,Te]}],ease:[{ease:["linear","initial",p,Fe,Te]}],delay:[{delay:[qe,Fe,Te]}],animate:[{animate:["none",k,Fe,Te]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,Fe,Te]}],"perspective-origin":[{"perspective-origin":E()}],rotate:[{rotate:nt()}],"rotate-x":[{"rotate-x":nt()}],"rotate-y":[{"rotate-y":nt()}],"rotate-z":[{"rotate-z":nt()}],scale:[{scale:ct()}],"scale-x":[{"scale-x":ct()}],"scale-y":[{"scale-y":ct()}],"scale-z":[{"scale-z":ct()}],"scale-3d":["scale-3d"],skew:[{skew:Ut()}],"skew-x":[{"skew-x":Ut()}],"skew-y":[{"skew-y":Ut()}],transform:[{transform:[Fe,Te,"","none","gpu","cpu"]}],"transform-origin":[{origin:E()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Yt()}],"translate-x":[{"translate-x":Yt()}],"translate-y":[{"translate-y":Yt()}],"translate-z":[{"translate-z":Yt()}],"translate-none":["translate-none"],zoom:[{zoom:[fn,Fe,Te]}],accent:[{accent:ne()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:ne()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Fe,Te]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":ne()}],"scrollbar-track-color":[{"scrollbar-track":ne()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mbs":[{"scroll-mbs":I()}],"scroll-mbe":[{"scroll-mbe":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pbs":[{"scroll-pbs":I()}],"scroll-pbe":[{"scroll-pbe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Fe,Te]}],fill:[{fill:["none",...ne()]}],"stroke-w":[{stroke:[qe,di,na,Ax]}],stroke:[{stroke:["none",...ne()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["start","end","right","left"],"inset-y":["inset-bs","inset-be","top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["ps","pe","pr","pl"],py:["pbs","pbe","pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["ms","me","mr","ml"],my:["mbs","mbe","mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-s","border-w-e","border-w-r","border-w-l"],"border-w-y":["border-w-bs","border-w-be","border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-s","border-color-e","border-color-r","border-color-l"],"border-color-y":["border-color-bs","border-color-be","border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-ms","scroll-me","scroll-mr","scroll-ml"],"scroll-my":["scroll-mbs","scroll-mbe","scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-ps","scroll-pe","scroll-pr","scroll-pl"],"scroll-py":["scroll-pbs","scroll-pbe","scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},D0=m0(F0);function gv(...t){return D0(sv(t))}var Fm=fg(),$0=Object.defineProperty,Dm=(t,n)=>$0(t,"name",{value:n,configurable:!0});function am(t,n){if(typeof t=="function")return t(n);t!=null&&(t.current=n)}Dm(am,"setRef");function vv(...t){return n=>{let a=!1;const o=t.map(c=>{const u=am(c,n);return!a&&typeof u=="function"&&(a=!0),u});if(a)return()=>{for(let c=0;cI0(t,"name",{value:n,configurable:!0});function Li(t){const n=i.forwardRef((a,o)=>{let{children:c,...u}=a,h=null,m=!1;const x=[];lm(c)&&typeof Vo=="function"&&(c=Vo(c._payload)),i.Children.forEach(c,w=>{var _;if(Nv(w)){m=!0;const S=w;let y="child"in S.props?S.props.child:S.props.children;lm(y)&&typeof Vo=="function"&&(y=Vo(y._payload)),h=O0(S,y),x.push((_=h==null?void 0:h.props)==null?void 0:_.children)}else x.push(w)}),h?h=i.cloneElement(h,void 0,x):!m&&i.Children.count(c)===1&&i.isValidElement(c)&&(h=c);const v=h?bv(h):void 0,N=_n(o,v);if(!h){if(c||c===0)throw new Error(m?B0(t):U0(t));return c}const j=_v(u,h.props??{});return h.type!==i.Fragment&&(j.ref=o?N:v),i.cloneElement(h,j)});return n.displayName=`${t}.Slot`,n}en(Li,"createSlot");var jv=Li("Slot"),yv=Symbol.for("radix.slottable");function M0(t){const n=en(a=>"child"in a?a.children(a.child):a.children,"Slottable");return n.displayName=`${t}.Slottable`,n.__radixId=yv,n}en(M0,"createSlottable");var O0=en((t,n)=>{if("child"in t.props){const a=t.props.child;return i.isValidElement(a)?i.cloneElement(a,void 0,t.props.children(a.props.children)):null}return i.isValidElement(n)?n:null},"getSlottableElementFromSlottable");function _v(t,n){const a={...n};for(const o in n){const c=t[o],u=n[o];/^on[A-Z]/.test(o)?c&&u?a[o]=(...m)=>{const x=u(...m);return c(...m),x}:c&&(a[o]=c):o==="style"?a[o]={...c,...u}:o==="className"&&(a[o]=[c,u].filter(Boolean).join(" "))}return{...t,...a}}en(_v,"mergeProps");function bv(t){var o,c;let n=(o=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:o.get,a=n&&"isReactWarning"in n&&n.isReactWarning;return a?t.ref:(n=(c=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:c.get,a=n&&"isReactWarning"in n&&n.isReactWarning,a?t.props.ref:t.props.ref||t.ref)}en(bv,"getElementRef");function Nv(t){return i.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===yv}en(Nv,"isSlottable");var z0=Symbol.for("react.lazy");function lm(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===z0&&"_payload"in t&&wv(t._payload)}en(lm,"isLazyComponent");function wv(t){return typeof t=="object"&&t!==null&&"then"in t}en(wv,"isPromiseLike");var U0=en(t=>`${t} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),B0=en(t=>`${t} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Vo=Ei[" use ".trim().toString()],H0=Object.defineProperty,V0=(t,n)=>H0(t,"name",{value:n,configurable:!0}),G0=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],bn=G0.reduce((t,n)=>{const a=Li(`Primitive.${n}`),o=i.forwardRef((c,u)=>{const{asChild:h,...m}=c,x=h?a:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(x,{...m,ref:u})});return o.displayName=`Primitive.${n}`,{...t,[n]:o}},{});function Sv(t,n){t&&Fm.flushSync(()=>t.dispatchEvent(n))}V0(Sv,"dispatchDiscreteCustomEvent");var W0=Object.defineProperty,Os=(t,n)=>W0(t,"name",{value:n,configurable:!0});function q0(t,n){const a=i.createContext(n);a.displayName=t+"Context";const o=Os(u=>{const{children:h,...m}=u,x=i.useMemo(()=>m,Object.values(m));return e.jsx(a.Provider,{value:x,children:h})},"Provider");o.displayName=t+"Provider";function c(u,h={}){const{optional:m=!1}=h,x=i.useContext(a);if(x)return x;if(n!==void 0)return n;if(!m)throw new Error(`\`${u}\` must be used within \`${t}\``)}return Os(c,"useContext"),[o,c]}Os(q0,"createContext");function vc(t,n=[]){let a=[];function o(u,h){const m=i.createContext(h);m.displayName=u+"Context";const x=a.length;a=[...a,h];const v=Os(j=>{var p;const{scope:w,children:_,...S}=j,y=((p=w==null?void 0:w[t])==null?void 0:p[x])||m,g=i.useMemo(()=>S,Object.values(S));return e.jsx(y.Provider,{value:g,children:_})},"Provider");v.displayName=u+"Provider";function N(j,w,_={}){var p;const{optional:S=!1}=_,y=((p=w==null?void 0:w[t])==null?void 0:p[x])||m,g=i.useContext(y);if(g)return g;if(h!==void 0)return h;if(!S)throw new Error(`\`${j}\` must be used within \`${u}\``)}return Os(N,"useContext"),[v,N]}Os(o,"createContext");const c=Os(()=>{const u=a.map(h=>i.createContext(h));return Os(function(m){const x=(m==null?void 0:m[t])||u;return i.useMemo(()=>({[`__scope${t}`]:{...m,[t]:x}}),[m,x])},"useScope")},"createScope");return c.scopeName=t,[o,Cv(c,...n)]}Os(vc,"createContextScope");function Cv(...t){const n=t[0];if(t.length===1)return n;const a=Os(()=>{const o=t.map(c=>({useScope:c(),scopeName:c.scopeName}));return Os(function(u){const h=o.reduce((m,{useScope:x,scopeName:v})=>{const j=x(u)[`__scope${v}`];return{...m,...j}},{});return i.useMemo(()=>({[`__scope${n.scopeName}`]:h}),[h])},"useComposedScopes")},"createScope");return a.scopeName=n.scopeName,a}Os(Cv,"composeContextScopes");var Q0=Object.defineProperty,gl=(t,n)=>Q0(t,"name",{value:n,configurable:!0}),kv=!!(typeof window<"u"&&window.document&&window.document.createElement);function zs(t,n,{checkForDefaultPrevented:a=!0}={}){return gl(function(c){if(t==null||t(c),a===!1||!c||!c.defaultPrevented)return n==null?void 0:n(c)},"handleEvent")}gl(zs,"composeEventHandlers");function K0(t){var n;if(!kv)throw new Error("Cannot access window outside of the DOM");return((n=t==null?void 0:t.ownerDocument)==null?void 0:n.defaultView)??window}gl(K0,"getOwnerWindow");function im(t){if(!kv)throw new Error("Cannot access document outside of the DOM");return(t==null?void 0:t.ownerDocument)??document}gl(im,"getOwnerDocument");function Ev(t,n=!1){const{activeElement:a}=im(t);if(!(a!=null&&a.nodeName))return null;if(Av(a)&&a.contentDocument)return Ev(a.contentDocument.body,n);if(n){const o=a.getAttribute("aria-activedescendant");if(o){const c=im(a).getElementById(o);if(c)return c}}return a}gl(Ev,"getActiveElement");function Av(t){return t.tagName==="IFRAME"}gl(Av,"isFrame");var Us=globalThis!=null&&globalThis.document?i.useLayoutEffect:()=>{},X0=Object.defineProperty,Y0=(t,n)=>X0(t,"name",{value:n,configurable:!0}),Tx=Ei[" useEffectEvent ".trim().toString()],Lx=Ei[" useInsertionEffect ".trim().toString()];function Rv(t){if(typeof Tx=="function")return Tx(t);const n=i.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof Lx=="function"?Lx(()=>{n.current=t}):Us(()=>{n.current=t}),i.useMemo(()=>((...a)=>{var o;return(o=n.current)==null?void 0:o.call(n,...a)}),[])}Y0(Rv,"useEffectEvent");var Z0=Object.defineProperty,Fi=(t,n)=>Z0(t,"name",{value:n,configurable:!0}),J0=Ei[" useInsertionEffect ".trim().toString()]||Us;function $m({prop:t,defaultProp:n,onChange:a=Fi(()=>{},"onChange"),caller:o}){const[c,u,h]=Pv({defaultProp:n,onChange:a}),m=t!==void 0,x=m?t:c,v=i.useCallback(N=>{var j;if(m){const w=Tv(N)?N(t):N;w!==t&&((j=h.current)==null||j.call(h,w))}else u(N)},[m,t,u,h]);return[x,v]}Fi($m,"useControllableState");function Pv({defaultProp:t,onChange:n}){const[a,o]=i.useState(t),c=i.useRef(a),u=i.useRef(n);return J0(()=>{u.current=n},[n]),i.useEffect(()=>{var h;c.current!==a&&((h=u.current)==null||h.call(u,a),c.current=a)},[a,c]),[a,o,u]}Fi(Pv,"useUncontrolledState");function Tv(t){return typeof t=="function"}Fi(Tv,"isFunction");var Fx=Symbol("RADIX:SYNC_STATE");function eN(t,n,a,o){const{prop:c,defaultProp:u,onChange:h,caller:m}=n,x=c!==void 0,v=Rv(h),N=[{...a,state:u}];o&&N.push(o);const[j,w]=i.useReducer((g,p)=>{if(p.type===Fx)return{...g,state:p.state};const k=t(g,p);return x&&!Object.is(k.state,g.state)&&v(k.state),k},...N),_=j.state,S=i.useRef(_);i.useEffect(()=>{S.current!==_&&(S.current=_,x||v(_))},[_,S,x]);const y=i.useMemo(()=>c!==void 0?{...j,state:c}:j,[j,c]);return i.useEffect(()=>{x&&!Object.is(c,j.state)&&w({type:Fx,state:c})},[c,j.state,x]),[y,w]}Fi(eN,"useControllableStateReducer");var tN=Object.defineProperty,Gn=(t,n)=>tN(t,"name",{value:n,configurable:!0});function Lv(t,n){return i.useReducer((a,o)=>n[a][o]??a,t)}Gn(Lv,"useStateMachine");var Di=Gn(t=>{const{present:n,children:a}=t,o=Fv(n),c=typeof a=="function"?a({present:o.isPresent}):i.Children.only(a),u=Dv(o.ref,$v(c));return typeof a=="function"||o.isPresent?i.cloneElement(c,{ref:u}):null},"Presence");function Fv(t){const[n,a]=i.useState(),o=i.useRef(null),c=i.useRef(t),u=i.useRef("none"),h=i.useRef(void 0),m=t?"mounted":"unmounted",[x,v]=Lv(m,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return i.useEffect(()=>{x==="mounted"?(u.current=h.current??il(o.current),h.current=void 0):u.current="none"},[x]),Us(()=>{const N=o.current,j=c.current;if(j!==t){const _=u.current,S=il(N);t?(h.current=S,v("MOUNT")):S==="none"||(N==null?void 0:N.display)==="none"?v("UNMOUNT"):v(j&&_!==S?"ANIMATION_OUT":"UNMOUNT"),c.current=t}},[t,v]),Us(()=>{if(n){let N;const j=n.ownerDocument.defaultView??window,w=Gn(S=>{const g=il(o.current).includes(CSS.escape(S.animationName));if(S.target===n&&g&&(v("ANIMATION_END"),!c.current)){const p=n.style.animationFillMode;n.style.animationFillMode="forwards",N=j.setTimeout(()=>{n.style.animationFillMode==="forwards"&&(n.style.animationFillMode=p)})}},"handleAnimationEnd"),_=Gn(S=>{S.target===n&&(u.current=il(o.current))},"handleAnimationStart");return n.addEventListener("animationstart",_),n.addEventListener("animationcancel",w),n.addEventListener("animationend",w),()=>{j.clearTimeout(N),n.removeEventListener("animationstart",_),n.removeEventListener("animationcancel",w),n.removeEventListener("animationend",w)}}else v("ANIMATION_END")},[n,v]),{isPresent:["mounted","unmountSuspended"].includes(x),ref:i.useCallback(N=>{if(N){const j=getComputedStyle(N);o.current=j,h.current=il(j)}else o.current=null;a(N)},[])}}Gn(Fv,"usePresence");function om(t,n){if(typeof t=="function")return t(n);t!=null&&(t.current=n)}Gn(om,"setRef");function Dv(...t){const n=i.useRef(t);return n.current=t,i.useCallback(a=>{const o=n.current;let c=!1;const u=o.map(h=>{const m=om(h,a);return!c&&typeof m=="function"&&(c=!0),m});if(c)return()=>{for(let h=0;hsN(t,"name",{value:n,configurable:!0}),rN=Ei[" useId ".trim().toString()]||(()=>{}),aN=0;function ji(t){const[n,a]=i.useState(rN());return Us(()=>{t||a(o=>o??String(aN++))},[t]),t||(n?`radix-${n}`:"")}nN(ji,"useId");var lN=Object.defineProperty,iN=(t,n)=>lN(t,"name",{value:n,configurable:!0});function ua(t){const n=i.useRef(t);return i.useEffect(()=>{n.current=t}),i.useMemo(()=>((...a)=>{var o;return(o=n.current)==null?void 0:o.call(n,...a)}),[])}iN(ua,"useCallbackRef");var oN=Object.defineProperty,Tt=(t,n)=>oN(t,"name",{value:n,configurable:!0}),cm="dismissableLayer.update",cN="dismissableLayer.pointerDownOutside",dN="dismissableLayer.focusOutside",Dx,Iv=i.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Mv=i.forwardRef(Tt(function(n,a){const{disableOutsidePointerEvents:o=!1,deferPointerDownOutside:c=!1,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:x,onDismiss:v,...N}=n,j=i.useContext(Iv),[w,_]=i.useState(null),S=(w==null?void 0:w.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,y]=i.useState({}),g=_n(a,_),p=Array.from(j.layers),[k]=[...j.layersWithOutsidePointerEventsDisabled].slice(-1),R=k?p.indexOf(k):-1,C=w?p.indexOf(w):-1,E=j.layersWithOutsidePointerEventsDisabled.size>0,P=C>=R,F=i.useRef(!1),I=zv(L=>{h==null||h(L),x==null||x(L),L.defaultPrevented||v==null||v()},{ownerDocument:S,deferPointerDownOutside:c,isDeferredPointerDownOutsideRef:F,dismissableSurfaces:j.dismissableSurfaces,shouldHandlePointerDownOutside:i.useCallback(L=>{if(!(L instanceof Node))return!1;const z=[...j.branches].some(Y=>Y.contains(L));return P&&!z},[j.branches,P])}),M=Uv(L=>{if(c&&F.current)return;const z=L.target;[...j.branches].some(G=>G.contains(z))||(m==null||m(L),x==null||x(L),L.defaultPrevented||v==null||v())},S),$=w?C===p.length-1:!1,O=ua(L=>{L.key==="Escape"&&(u==null||u(L),!L.defaultPrevented&&v&&(L.preventDefault(),v()))});return i.useEffect(()=>{if($)return S.addEventListener("keydown",O,{capture:!0}),()=>S.removeEventListener("keydown",O,{capture:!0})},[S,$,O]),i.useEffect(()=>{if(w)return o&&(j.layersWithOutsidePointerEventsDisabled.size===0&&(Dx=S.body.style.pointerEvents,S.body.style.pointerEvents="none"),j.layersWithOutsidePointerEventsDisabled.add(w)),j.layers.add(w),dm(),()=>{o&&(j.layersWithOutsidePointerEventsDisabled.delete(w),j.layersWithOutsidePointerEventsDisabled.size===0&&(S.body.style.pointerEvents=Dx))}},[w,S,o,j]),i.useEffect(()=>()=>{w&&(j.layers.delete(w),j.layersWithOutsidePointerEventsDisabled.delete(w),dm())},[w,j]),i.useEffect(()=>{const L=Tt(()=>y({}),"handleUpdate");return document.addEventListener(cm,L),()=>document.removeEventListener(cm,L)},[]),e.jsx(bn.div,{...N,ref:g,style:{pointerEvents:E?P?"auto":"none":void 0,...n.style},onFocusCapture:zs(n.onFocusCapture,M.onFocusCapture),onBlurCapture:zs(n.onBlurCapture,M.onBlurCapture),onPointerDownCapture:zs(n.onPointerDownCapture,I.onPointerDownCapture)})},"DismissableLayer"));function Ov(){const t=i.useContext(Iv),[n,a]=i.useState(null);return i.useEffect(()=>{if(n)return t.dismissableSurfaces.add(n),()=>{t.dismissableSurfaces.delete(n)}},[n,t.dismissableSurfaces]),a}Tt(Ov,"useDismissableLayerSurface");var uN=Tt(()=>!0,"IS_TRUE");function zv(t,n){const{ownerDocument:a=globalThis==null?void 0:globalThis.document,deferPointerDownOutside:o=!1,isDeferredPointerDownOutsideRef:c,dismissableSurfaces:u,shouldHandlePointerDownOutside:h=uN}=n,m=ua(t),x=i.useRef(!1),v=i.useRef(!1),N=i.useRef(new Map),j=i.useRef(()=>{});return i.useEffect(()=>{function w(){v.current=!1,c.current=!1,N.current.clear()}Tt(w,"resetOutsideInteraction");function _(){return Array.from(N.current.values()).some(Boolean)}Tt(_,"isOutsideInteractionIntercepted");function S(R){if(!v.current)return;const C=R.target;C instanceof Node&&[...u].some(P=>P.contains(C))||N.current.set(R.type,!0),R.type==="click"&&window.setTimeout(()=>{v.current&&j.current()},0)}Tt(S,"handleInteractionCapture");function y(R){v.current&&N.current.set(R.type,!1)}Tt(y,"handleInteractionBubble");const g=Tt(R=>{if(R.target&&!x.current){let C=function(){a.removeEventListener("click",j.current);const P=_();w(),P||Im(cN,m,E,{discrete:!0})};if(Tt(C,"handleAndDispatchPointerDownOutsideEvent"),!h(R.target)){a.removeEventListener("click",j.current),w(),x.current=!1;return}const E={originalEvent:R};v.current=!0,c.current=o&&R.button===0,N.current.clear(),!o||R.button!==0?C():(a.removeEventListener("click",j.current),j.current=C,a.addEventListener("click",j.current,{once:!0}))}else a.removeEventListener("click",j.current),w();x.current=!1},"handlePointerDown"),p=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const R of p)a.addEventListener(R,S,!0),a.addEventListener(R,y);const k=window.setTimeout(()=>{a.addEventListener("pointerdown",g)},0);return()=>{window.clearTimeout(k),a.removeEventListener("pointerdown",g),a.removeEventListener("click",j.current);for(const R of p)a.removeEventListener(R,S,!0),a.removeEventListener(R,y)}},[a,m,o,c,u,h]),{onPointerDownCapture:Tt(()=>x.current=!0,"onPointerDownCapture")}}Tt(zv,"usePointerDownOutside");function Uv(t,n=globalThis==null?void 0:globalThis.document){const a=ua(t),o=i.useRef(!1);return i.useEffect(()=>{const c=Tt(u=>{u.target&&!o.current&&Im(dN,a,{originalEvent:u},{discrete:!1})},"handleFocus");return n.addEventListener("focusin",c),()=>n.removeEventListener("focusin",c)},[n,a]),{onFocusCapture:Tt(()=>o.current=!0,"onFocusCapture"),onBlurCapture:Tt(()=>o.current=!1,"onBlurCapture")}}Tt(Uv,"useFocusOutside");function dm(){const t=new CustomEvent(cm);document.dispatchEvent(t)}Tt(dm,"dispatchUpdate");function Im(t,n,a,{discrete:o}){const c=a.originalEvent.target,u=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:a});n&&c.addEventListener(t,n,{once:!0}),o?Sv(c,u):c.dispatchEvent(u)}Tt(Im,"handleAndDispatchCustomEvent");var mN=Object.defineProperty,Xt=(t,n)=>mN(t,"name",{value:n,configurable:!0}),pu="focusScope.autoFocusOnMount",gu="focusScope.autoFocusOnUnmount",$x={bubbles:!1,cancelable:!0},Bv=i.forwardRef(Xt(function(n,a){const{loop:o=!1,trapped:c=!1,onMountAutoFocus:u,onUnmountAutoFocus:h,...m}=n,[x,v]=i.useState(null),N=ua(u),j=ua(h),w=i.useRef(null),_=_n(a,v),S=i.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;i.useEffect(()=>{if(c){let g=function(C){if(S.paused||!x)return;const E=C.target;x.contains(E)?w.current=E:Bn(w.current,{select:!0})},p=function(C){if(S.paused||!x)return;const E=C.relatedTarget;E!==null&&(x.contains(E)||Bn(w.current,{select:!0}))},k=function(C){if(document.activeElement===document.body)for(const P of C)P.removedNodes.length>0&&Bn(x)};Xt(g,"handleFocusIn"),Xt(p,"handleFocusOut"),Xt(k,"handleMutations"),document.addEventListener("focusin",g),document.addEventListener("focusout",p);const R=new MutationObserver(k);return x&&R.observe(x,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",p),R.disconnect()}}},[c,x,S.paused]),i.useEffect(()=>{if(x){Ix.add(S);const g=document.activeElement;if(!x.contains(g)){const k=new CustomEvent(pu,$x);x.addEventListener(pu,N),x.dispatchEvent(k),k.defaultPrevented||(Hv(Qv(Mm(x)),{select:!0}),document.activeElement===g&&Bn(x))}return()=>{x.removeEventListener(pu,N),setTimeout(()=>{const k=new CustomEvent(gu,$x);x.addEventListener(gu,j),x.dispatchEvent(k),k.defaultPrevented||Bn(g??document.body,{select:!0}),x.removeEventListener(gu,j),Ix.remove(S)},0)}}},[x,N,j,S]);const y=i.useCallback(g=>{if(!o&&!c||S.paused)return;const p=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,k=document.activeElement;if(p&&k){const R=g.currentTarget,[C,E]=Vv(R);C&&E?!g.shiftKey&&k===E?(g.preventDefault(),o&&Bn(C,{select:!0})):g.shiftKey&&k===C&&(g.preventDefault(),o&&Bn(E,{select:!0})):k===R&&g.preventDefault()}},[o,c,S.paused]);return e.jsx(bn.div,{tabIndex:-1,...m,ref:_,onKeyDown:y})},"FocusScope"));function Hv(t,{select:n=!1}={}){const a=document.activeElement;for(const o of t)if(Bn(o,{select:n}),document.activeElement!==a)return}Xt(Hv,"focusFirst");function Vv(t){const n=Mm(t),a=um(n,t),o=um(n.reverse(),t);return[a,o]}Xt(Vv,"getTabbableEdges");function Mm(t){const n=[],a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:Xt(o=>{const c=o.tagName==="INPUT"&&o.type==="hidden";return o.disabled||o.hidden||c?NodeFilter.FILTER_SKIP:o.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;a.nextNode();)n.push(a.currentNode);return n}Xt(Mm,"getTabbableCandidates");function um(t,n){const a=typeof n.checkVisibility=="function"&&n.checkVisibility({checkVisibilityCSS:!0});for(const o of t)if(!(a?!o.checkVisibility({checkVisibilityCSS:!0}):Gv(o,{upTo:n})))return o}Xt(um,"findVisible");function Gv(t,{upTo:n}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(n!==void 0&&t===n)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}Xt(Gv,"isHidden");function Wv(t){return t instanceof HTMLInputElement&&"select"in t}Xt(Wv,"isSelectableInput");function Bn(t,{select:n=!1}={}){if(t&&t.focus){const a=document.activeElement;t.focus({preventScroll:!0}),t!==a&&Wv(t)&&n&&t.select()}}Xt(Bn,"focus");var Ix=qv();function qv(){let t=[];return{add(n){const a=t[0];n!==a&&(a==null||a.pause()),t=mm(t,n),t.unshift(n)},remove(n){var a;t=mm(t,n),(a=t[0])==null||a.resume()}}}Xt(qv,"createFocusScopesStack");function mm(t,n){const a=[...t],o=a.indexOf(n);return o!==-1&&a.splice(o,1),a}Xt(mm,"arrayRemove");function Qv(t){return t.filter(n=>n.tagName!=="A")}Xt(Qv,"removeLinks");var hN=Object.defineProperty,fN=(t,n)=>hN(t,"name",{value:n,configurable:!0}),Kv=i.forwardRef(fN(function(n,a){var x;const{container:o,...c}=n,[u,h]=i.useState(!1);Us(()=>h(!0),[]);const m=o||u&&((x=globalThis==null?void 0:globalThis.document)==null?void 0:x.body);return m?Fm.createPortal(e.jsx(bn.div,{...c,ref:a}),m):null},"Portal")),xN=Object.defineProperty,Om=(t,n)=>xN(t,"name",{value:n,configurable:!0}),Go=0,xn=null;function pN(t){return jc(),t.children}Om(pN,"FocusGuards");function jc(){i.useEffect(()=>{xn||(xn={start:hm(),end:hm()});const{start:t,end:n}=xn;return document.body.firstElementChild!==t&&document.body.insertAdjacentElement("afterbegin",t),document.body.lastElementChild!==n&&document.body.insertAdjacentElement("beforeend",n),Go++,()=>{Go===1&&(xn==null||xn.start.remove(),xn==null||xn.end.remove(),xn=null),Go=Math.max(0,Go-1)}},[])}Om(jc,"useFocusGuards");function hm(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}Om(hm,"createFocusGuard");var gn=function(){return gn=Object.assign||function(n){for(var a,o=1,c=arguments.length;o"u")return LN;var n=FN(t),a=document.documentElement.clientWidth,o=window.innerWidth;return{left:n[0],top:n[1],right:n[2],gap:Math.max(0,o-a+n[2]-n[0])}},$N=Jv(),ml="data-scroll-locked",IN=function(t,n,a,o){var c=t.left,u=t.top,h=t.right,m=t.gap;return a===void 0&&(a="margin"),` .`.concat(vN,` { overflow: hidden `).concat(o,`; padding-right: `).concat(m,"px ").concat(o,`; } body[`).concat(ml,`] { overflow: hidden `).concat(o,`; overscroll-behavior: contain; `).concat([n&&"position: relative ".concat(o,";"),a==="margin"&&` padding-left: `.concat(c,`px; padding-top: `).concat(u,`px; padding-right: `).concat(h,`px; margin-left:0; margin-top:0; margin-right: `).concat(m,"px ").concat(o,`; `),a==="padding"&&"padding-right: ".concat(m,"px ").concat(o,";")].filter(Boolean).join(""),` } .`).concat(nc,` { right: `).concat(m,"px ").concat(o,`; } .`).concat(rc,` { margin-right: `).concat(m,"px ").concat(o,`; } .`).concat(nc," .").concat(nc,` { right: 0 `).concat(o,`; } .`).concat(rc," .").concat(rc,` { margin-right: 0 `).concat(o,`; } body[`).concat(ml,`] { `).concat(jN,": ").concat(m,`px; } `)},Ox=function(){var t=parseInt(document.body.getAttribute(ml)||"0",10);return isFinite(t)?t:0},MN=function(){i.useEffect(function(){return document.body.setAttribute(ml,(Ox()+1).toString()),function(){var t=Ox()-1;t<=0?document.body.removeAttribute(ml):document.body.setAttribute(ml,t.toString())}},[])},ON=function(t){var n=t.noRelative,a=t.noImportant,o=t.gapMode,c=o===void 0?"margin":o;MN();var u=i.useMemo(function(){return DN(c)},[c]);return i.createElement($N,{styles:IN(u,!n,c,a?"":"!important")})},fm=!1;if(typeof window<"u")try{var Wo=Object.defineProperty({},"passive",{get:function(){return fm=!0,!0}});window.addEventListener("test",Wo,Wo),window.removeEventListener("test",Wo,Wo)}catch{fm=!1}var el=fm?{passive:!1}:!1,zN=function(t){return t.tagName==="TEXTAREA"},ej=function(t,n){if(!(t instanceof Element))return!1;var a=window.getComputedStyle(t);return a[n]!=="hidden"&&!(a.overflowY===a.overflowX&&!zN(t)&&a[n]==="visible")},UN=function(t){return ej(t,"overflowY")},BN=function(t){return ej(t,"overflowX")},zx=function(t,n){var a=n.ownerDocument,o=n;do{typeof ShadowRoot<"u"&&o instanceof ShadowRoot&&(o=o.host);var c=tj(t,o);if(c){var u=sj(t,o),h=u[1],m=u[2];if(h>m)return!0}o=o.parentNode}while(o&&o!==a.body);return!1},HN=function(t){var n=t.scrollTop,a=t.scrollHeight,o=t.clientHeight;return[n,a,o]},VN=function(t){var n=t.scrollLeft,a=t.scrollWidth,o=t.clientWidth;return[n,a,o]},tj=function(t,n){return t==="v"?UN(n):BN(n)},sj=function(t,n){return t==="v"?HN(n):VN(n)},GN=function(t,n){return t==="h"&&n==="rtl"?-1:1},WN=function(t,n,a,o,c){var u=GN(t,window.getComputedStyle(n).direction),h=u*o,m=a.target,x=n.contains(m),v=!1,N=h>0,j=0,w=0;do{if(!m)break;var _=sj(t,m),S=_[0],y=_[1],g=_[2],p=y-g-u*S;(S||p)&&tj(t,m)&&(j+=p,w+=S);var k=m.parentNode;m=k&&k.nodeType===Node.DOCUMENT_FRAGMENT_NODE?k.host:k}while(!x&&m!==document.body||x&&(n.contains(m)||n===m));return(N&&Math.abs(j)<1||!N&&Math.abs(w)<1)&&(v=!0),v},qo=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},Ux=function(t){return[t.deltaX,t.deltaY]},Bx=function(t){return t&&"current"in t?t.current:t},qN=function(t,n){return t[0]===n[0]&&t[1]===n[1]},QN=function(t){return` .block-interactivity-`.concat(t,` {pointer-events: none;} .allow-interactivity-`).concat(t,` {pointer-events: all;} `)},KN=0,tl=[];function XN(t){var n=i.useRef([]),a=i.useRef([0,0]),o=i.useRef(),c=i.useState(KN++)[0],u=i.useState(Jv)[0],h=i.useRef(t);i.useEffect(function(){h.current=t},[t]),i.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(c));var y=gN([t.lockRef.current],(t.shards||[]).map(Bx),!0).filter(Boolean);return y.forEach(function(g){return g.classList.add("allow-interactivity-".concat(c))}),function(){document.body.classList.remove("block-interactivity-".concat(c)),y.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(c))})}}},[t.inert,t.lockRef.current,t.shards]);var m=i.useCallback(function(y,g){if("touches"in y&&y.touches.length===2||y.type==="wheel"&&y.ctrlKey)return!h.current.allowPinchZoom;var p=qo(y),k=a.current,R="deltaX"in y?y.deltaX:k[0]-p[0],C="deltaY"in y?y.deltaY:k[1]-p[1],E,P=y.target,F=Math.abs(R)>Math.abs(C)?"h":"v";if("touches"in y&&F==="h"&&P.type==="range")return!1;var I=window.getSelection(),M=I&&I.anchorNode,$=M?M===P||M.contains(P):!1;if($)return!1;var O=zx(F,P);if(!O)return!0;if(O?E=F:(E=F==="v"?"h":"v",O=zx(F,P)),!O)return!1;if(!o.current&&"changedTouches"in y&&(R||C)&&(o.current=E),!E)return!0;var L=o.current||E;return WN(L,g,y,L==="h"?R:C)},[]),x=i.useCallback(function(y){var g=y;if(!(!tl.length||tl[tl.length-1]!==u)){var p="deltaY"in g?Ux(g):qo(g),k=n.current.filter(function(E){return E.name===g.type&&(E.target===g.target||g.target===E.shadowParent)&&qN(E.delta,p)})[0];if(k&&k.should){g.cancelable&&g.preventDefault();return}if(!k){var R=(h.current.shards||[]).map(Bx).filter(Boolean).filter(function(E){return E.contains(g.target)}),C=R.length>0?m(g,R[0]):!h.current.noIsolation;C&&g.cancelable&&g.preventDefault()}}},[]),v=i.useCallback(function(y,g,p,k){var R={name:y,delta:g,target:p,should:k,shadowParent:YN(p)};n.current.push(R),setTimeout(function(){n.current=n.current.filter(function(C){return C!==R})},1)},[]),N=i.useCallback(function(y){a.current=qo(y),o.current=void 0},[]),j=i.useCallback(function(y){v(y.type,Ux(y),y.target,m(y,t.lockRef.current))},[]),w=i.useCallback(function(y){v(y.type,qo(y),y.target,m(y,t.lockRef.current))},[]);i.useEffect(function(){return tl.push(u),t.setCallbacks({onScrollCapture:j,onWheelCapture:j,onTouchMoveCapture:w}),document.addEventListener("wheel",x,el),document.addEventListener("touchmove",x,el),document.addEventListener("touchstart",N,el),function(){tl=tl.filter(function(y){return y!==u}),document.removeEventListener("wheel",x,el),document.removeEventListener("touchmove",x,el),document.removeEventListener("touchstart",N,el)}},[]);var _=t.removeScrollBar,S=t.inert;return i.createElement(i.Fragment,null,S?i.createElement(u,{styles:QN(c)}):null,_?i.createElement(ON,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function YN(t){for(var n=null;t!==null;)t instanceof ShadowRoot&&(n=t.host,t=t.host),t=t.parentNode;return n}const ZN=CN(Zv,XN);var zm=i.forwardRef(function(t,n){return i.createElement(yc,gn({},t,{ref:n,sideCar:ZN}))});zm.classNames=yc.classNames;var JN=function(t){if(typeof document>"u")return null;var n=Array.isArray(t)?t[0]:t;return n.ownerDocument.body},sl=new WeakMap,Qo=new WeakMap,Ko={},_u=0,nj=function(t){return t&&(t.host||nj(t.parentNode))},ew=function(t,n){return n.map(function(a){if(t.contains(a))return a;var o=nj(a);return o&&t.contains(o)?o:(console.error("aria-hidden",a,"in not contained inside",t,". Doing nothing"),null)}).filter(function(a){return!!a})},tw=function(t,n,a,o){var c=ew(n,Array.isArray(t)?t:[t]);Ko[a]||(Ko[a]=new WeakMap);var u=Ko[a],h=[],m=new Set,x=new Set(c),v=function(j){!j||m.has(j)||(m.add(j),v(j.parentNode))};c.forEach(v);var N=function(j){!j||x.has(j)||Array.prototype.forEach.call(j.children,function(w){if(m.has(w))N(w);else try{var _=w.getAttribute(o),S=_!==null&&_!=="false",y=(sl.get(w)||0)+1,g=(u.get(w)||0)+1;sl.set(w,y),u.set(w,g),h.push(w),y===1&&S&&Qo.set(w,!0),g===1&&w.setAttribute(a,"true"),S||w.setAttribute(o,"true")}catch(p){console.error("aria-hidden: cannot operate on ",w,p)}})};return N(n),m.clear(),_u++,function(){h.forEach(function(j){var w=sl.get(j)-1,_=u.get(j)-1;sl.set(j,w),u.set(j,_),w||(Qo.has(j)||j.removeAttribute(o),Qo.delete(j)),_||j.removeAttribute(a)}),_u--,_u||(sl=new WeakMap,sl=new WeakMap,Qo=new WeakMap,Ko={})}},rj=function(t,n,a){a===void 0&&(a="data-aria-hidden");var o=Array.from(Array.isArray(t)?t:[t]),c=JN(t);return c?(o.push.apply(o,Array.from(c.querySelectorAll("[aria-live], script"))),tw(o,c,a,"aria-hidden")):function(){return null}},sw=Object.defineProperty,Bs=(t,n)=>sw(t,"name",{value:n,configurable:!0}),Um="Dialog",[aj,m3]=vc(Um),[nw,Nn]=aj(Um),rw=Bs(t=>{const{__scopeDialog:n,children:a,open:o,defaultOpen:c,onOpenChange:u,modal:h=!0}=t,m=i.useRef(null),x=i.useRef(null),[v,N]=$m({prop:o,defaultProp:c??!1,onChange:u,caller:Um}),[j,w]=i.useState(0),[_,S]=i.useState(0);return e.jsx(nw,{scope:n,triggerRef:m,contentRef:x,contentId:ji(),titleId:ji(),descriptionId:ji(),titlePresent:j>0,descriptionPresent:_>0,setTitleCount:w,setDescriptionCount:S,open:v,onOpenChange:N,onOpenToggle:i.useCallback(()=>N(y=>!y),[N]),modal:h,children:a})},"Dialog"),lj="DialogPortal",[aw,ij]=aj(lj,{forceMount:void 0}),lw=Bs(t=>{const{__scopeDialog:n,forceMount:a,children:o,container:c}=t,u=Nn(lj,n);return e.jsx(aw,{scope:n,forceMount:a,children:i.Children.map(o,h=>e.jsx(Di,{present:a||u.open,children:e.jsx(Kv,{asChild:!0,container:c,children:h})}))})},"DialogPortal"),xm="DialogOverlay",iw=i.forwardRef(Bs(function(n,a){const o=ij(xm,n.__scopeDialog),{forceMount:c=o.forceMount,...u}=n,h=Nn(xm,n.__scopeDialog);return h.modal?e.jsx(Di,{present:c||h.open,children:e.jsx(cw,{...u,ref:a})}):null},"DialogOverlay")),ow=Li("DialogOverlay.RemoveScroll"),cw=i.forwardRef(Bs(function(n,a){const{__scopeDialog:o,...c}=n,u=Nn(xm,o),h=Ov(),m=_n(a,h);return e.jsx(zm,{as:ow,allowPinchZoom:!0,shards:[u.contentRef],children:e.jsx(bn.div,{"data-state":Bm(u.open),...c,ref:m,style:{pointerEvents:"auto",...c.style}})})},"DialogOverlayImpl")),bi="DialogContent",dw=i.forwardRef(Bs(function(n,a){const o=ij(bi,n.__scopeDialog),{forceMount:c=o.forceMount,...u}=n,h=Nn(bi,n.__scopeDialog);return e.jsx(Di,{present:c||h.open,children:h.modal?e.jsx(uw,{...u,ref:a}):e.jsx(mw,{...u,ref:a})})},"DialogContent")),uw=i.forwardRef(Bs(function(n,a){const o=Nn(bi,n.__scopeDialog),c=i.useRef(null),u=_n(a,o.contentRef,c);return i.useEffect(()=>{const h=c.current;if(h)return rj(h)},[]),e.jsx(oj,{...n,ref:u,trapFocus:o.open,disableOutsidePointerEvents:o.open,onCloseAutoFocus:zs(n.onCloseAutoFocus,h=>{var m;h.preventDefault(),(m=o.triggerRef.current)==null||m.focus()}),onPointerDownOutside:zs(n.onPointerDownOutside,h=>{const m=h.detail.originalEvent,x=m.button===0&&m.ctrlKey===!0;(m.button===2||x)&&h.preventDefault()}),onFocusOutside:zs(n.onFocusOutside,h=>h.preventDefault())})},"DialogContentModal")),mw=i.forwardRef(Bs(function(n,a){const o=Nn(bi,n.__scopeDialog),c=i.useRef(!1),u=i.useRef(!1);return e.jsx(oj,{...n,ref:a,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:h=>{var m,x;(m=n.onCloseAutoFocus)==null||m.call(n,h),h.defaultPrevented||(c.current||(x=o.triggerRef.current)==null||x.focus(),h.preventDefault()),c.current=!1,u.current=!1},onInteractOutside:h=>{var v,N;(v=n.onInteractOutside)==null||v.call(n,h),h.defaultPrevented||(c.current=!0,h.detail.originalEvent.type==="pointerdown"&&(u.current=!0));const m=h.target;((N=o.triggerRef.current)==null?void 0:N.contains(m))&&h.preventDefault(),h.detail.originalEvent.type==="focusin"&&u.current&&h.preventDefault()}})},"DialogContentNonModal")),oj=i.forwardRef(Bs(function(n,a){const{__scopeDialog:o,trapFocus:c,onOpenAutoFocus:u,onCloseAutoFocus:h,...m}=n,x=Nn(bi,o);return jc(),e.jsx(e.Fragment,{children:e.jsx(Bv,{asChild:!0,loop:!0,trapped:c,onMountAutoFocus:u,onUnmountAutoFocus:h,children:e.jsx(Mv,{role:"dialog",id:x.contentId,"aria-describedby":x.descriptionPresent?x.descriptionId:void 0,"aria-labelledby":x.titlePresent?x.titleId:void 0,"data-state":Bm(x.open),...m,ref:a,deferPointerDownOutside:!0,onDismiss:()=>x.onOpenChange(!1)})})})},"DialogContentImpl")),hw="DialogTitle",fw=i.forwardRef(Bs(function(n,a){const{__scopeDialog:o,...c}=n,u=Nn(hw,o),{setTitleCount:h}=u;return Us(()=>(h(m=>m+1),()=>h(m=>m-1)),[h]),e.jsx(bn.h2,{id:u.titleId,...c,ref:a})},"DialogTitle")),xw="DialogDescription",pw=i.forwardRef(Bs(function(n,a){const{__scopeDialog:o,...c}=n,u=Nn(xw,o),{setDescriptionCount:h}=u;return Us(()=>(h(m=>m+1),()=>h(m=>m-1)),[h]),e.jsx(bn.p,{id:u.descriptionId,...c,ref:a})},"DialogDescription")),gw="DialogClose",vw=i.forwardRef(Bs(function(n,a){const{__scopeDialog:o,...c}=n,u=Nn(gw,o);return e.jsx(bn.button,{type:"button",...c,ref:a,onClick:zs(n.onClick,()=>u.onOpenChange(!1))})},"DialogClose"));function Bm(t){return t?"open":"closed"}Bs(Bm,"getState");var jw=Object.defineProperty,yw=(t,n)=>jw(t,"name",{value:n,configurable:!0});function cj(t){const[n,a]=i.useState(void 0);return Us(()=>{if(t){a({width:t.offsetWidth,height:t.offsetHeight});const o=new ResizeObserver(c=>{if(!Array.isArray(c)||!c.length)return;const u=c[0];let h,m;if("borderBoxSize"in u){const x=u.borderBoxSize,v=Array.isArray(x)?x[0]:x;h=v.inlineSize,m=v.blockSize}else h=t.offsetWidth,m=t.offsetHeight;a({width:h,height:m})});return o.observe(t,{box:"border-box"}),()=>o.unobserve(t)}else a(void 0)},[t]),n}yw(cj,"useSize");const _w=["top","right","bottom","left"],Er=Math.min,Hn=Math.max,cc=Math.round,Xo=Math.floor,Vn=t=>({x:t,y:t}),bw={left:"right",right:"left",bottom:"top",top:"bottom"};function dj(t,n,a){return Hn(t,Er(n,a))}function Wn(t,n){return typeof t=="function"?t(n):t}function Ar(t){return t.split("-")[0]}function vl(t){return t.split("-")[1]}function Hm(t){return t==="x"?"y":"x"}function Vm(t){return t==="y"?"height":"width"}function vn(t){const n=t[0];return n==="t"||n==="b"?"y":"x"}function Gm(t){return Hm(vn(t))}function Nw(t,n,a){a===void 0&&(a=!1);const o=vl(t),c=Gm(t),u=Vm(c);let h=c==="x"?o===(a?"end":"start")?"right":"left":o==="start"?"bottom":"top";return n.reference[u]>n.floating[u]&&(h=dc(h)),[h,dc(h)]}function ww(t){const n=dc(t);return[pm(t),n,pm(n)]}function pm(t){return t.includes("start")?t.replace("start","end"):t.replace("end","start")}const Hx=["left","right"],Vx=["right","left"],Sw=["top","bottom"],Cw=["bottom","top"];function kw(t,n,a){switch(t){case"top":case"bottom":return a?n?Vx:Hx:n?Hx:Vx;case"left":case"right":return n?Sw:Cw;default:return[]}}function Ew(t,n,a,o){const c=vl(t);let u=kw(Ar(t),a==="start",o);return c&&(u=u.map(h=>h+"-"+c),n&&(u=u.concat(u.map(pm)))),u}function dc(t){const n=Ar(t);return bw[n]+t.slice(n.length)}function Aw(t){var n,a,o,c;return{top:(n=t.top)!=null?n:0,right:(a=t.right)!=null?a:0,bottom:(o=t.bottom)!=null?o:0,left:(c=t.left)!=null?c:0}}function uj(t){return typeof t!="number"?Aw(t):{top:t,right:t,bottom:t,left:t}}function uc(t){const{x:n,y:a,width:o,height:c}=t;return{width:o,height:c,top:a,left:n,right:n+o,bottom:a+c,x:n,y:a}}function Gx(t,n,a){let{reference:o,floating:c}=t;const u=vn(n),h=Gm(n),m=Vm(h),x=Ar(n),v=u==="y",N=o.x+o.width/2-c.width/2,j=o.y+o.height/2-c.height/2,w=o[m]/2-c[m]/2;let _;switch(x){case"top":_={x:N,y:o.y-c.height};break;case"bottom":_={x:N,y:o.y+o.height};break;case"right":_={x:o.x+o.width,y:j};break;case"left":_={x:o.x-c.width,y:j};break;default:_={x:o.x,y:o.y}}const S=vl(n);return S&&(_[h]+=w*(S==="end"?1:-1)*(a&&v?-1:1)),_}async function Rw(t,n){var a;n===void 0&&(n={});const{x:o,y:c,platform:u,rects:h,elements:m,strategy:x}=t,{boundary:v="clippingAncestors",rootBoundary:N="viewport",elementContext:j="floating",altBoundary:w=!1,padding:_=0}=Wn(n,t),S=uj(_),g=m[w?j==="floating"?"reference":"floating":j],p=uc(await u.getClippingRect({element:(a=await(u.isElement==null?void 0:u.isElement(g)))==null||a?g:g.contextElement||await(u.getDocumentElement==null?void 0:u.getDocumentElement(m.floating)),boundary:v,rootBoundary:N,strategy:x})),k=j==="floating"?{x:o,y:c,width:h.floating.width,height:h.floating.height}:h.reference,R=await(u.getOffsetParent==null?void 0:u.getOffsetParent(m.floating)),C=await(u.isElement==null?void 0:u.isElement(R))&&await(u.getScale==null?void 0:u.getScale(R))||{x:1,y:1},E=uc(u.convertOffsetParentRelativeRectToViewportRelativeRect?await u.convertOffsetParentRelativeRectToViewportRelativeRect({elements:m,rect:k,offsetParent:R,strategy:x}):k);return{top:(p.top-E.top+S.top)/C.y,bottom:(E.bottom-p.bottom+S.bottom)/C.y,left:(p.left-E.left+S.left)/C.x,right:(E.right-p.right+S.right)/C.x}}const Pw=50,Tw=async(t,n,a)=>{const{placement:o="bottom",strategy:c="absolute",middleware:u=[],platform:h}=a,m=h.detectOverflow?h:{...h,detectOverflow:Rw},x=await(h.isRTL==null?void 0:h.isRTL(n));let v=await h.getElementRects({reference:t,floating:n,strategy:c}),{x:N,y:j}=Gx(v,o,x),w=o,_=0;const S={};for(let y=0;y({name:"arrow",options:t,async fn(n){const{x:a,y:o,placement:c,rects:u,platform:h,elements:m,middlewareData:x}=n,{element:v,padding:N=0}=Wn(t,n)||{};if(v==null)return{};const j=uj(N),w={x:a,y:o},_=Gm(c),S=Vm(_),y=await h.getDimensions(v),g=_==="y",p=g?"top":"left",k=g?"bottom":"right",R=g?"clientHeight":"clientWidth",C=u.reference[S]+u.reference[_]-w[_]-u.floating[S],E=w[_]-u.reference[_],P=await(h.getOffsetParent==null?void 0:h.getOffsetParent(v));let F=P?P[R]:0;(!F||!await(h.isElement==null?void 0:h.isElement(P)))&&(F=m.floating[R]||u.floating[S]);const I=C/2-E/2,M=F/2-y[S]/2-1,$=Er(j[p],M),O=Er(j[k],M),L=F-y[S]-O,z=F/2-y[S]/2+I,Y=dj($,z,L),G=!x.arrow&&vl(c)!=null&&z!==Y&&u.reference[S]/2-(z<$?$:O)-y[S]/2<0,U=G?z<$?z-$:z-L:0;return{[_]:w[_]+U,data:{[_]:Y,centerOffset:z-Y-U,...G&&{alignmentOffset:U}},reset:G}}}),Fw=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(n){var a,o;const{placement:c,middlewareData:u,rects:h,initialPlacement:m,platform:x,elements:v}=n,{mainAxis:N=!0,crossAxis:j=!0,fallbackPlacements:w,fallbackStrategy:_="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:y=!0,...g}=Wn(t,n);if((a=u.arrow)!=null&&a.alignmentOffset)return{};const p=Ar(c),k=vn(m),R=Ar(m)===m,C=await(x.isRTL==null?void 0:x.isRTL(v.floating)),E=w||(R||!y?[dc(m)]:ww(m)),P=S!=="none";!w&&P&&E.push(...Ew(m,y,S,C));const F=[m,...E],I=await x.detectOverflow(n,g),M=[];let $=((o=u.flip)==null?void 0:o.overflows)||[];if(N&&M.push(I[p]),j){const Y=Nw(c,h,C);M.push(I[Y[0]],I[Y[1]])}if($=[...$,{placement:c,overflows:M}],!M.every(Y=>Y<=0)){var O,L;const Y=(((O=u.flip)==null?void 0:O.index)||0)+1,G=F[Y];if(G&&(!(j==="alignment"?k!==vn(G):!1)||$.every(W=>vn(W.placement)===k?W.overflows[0]>0:!0)))return{data:{index:Y,overflows:$},reset:{placement:G}};let U=(L=$.filter(ae=>ae.overflows[0]<=0).sort((ae,W)=>ae.overflows[1]-W.overflows[1])[0])==null?void 0:L.placement;if(!U)switch(_){case"bestFit":{var z;const ae=(z=$.filter(W=>{if(P){const se=vn(W.placement);return se===k||se==="y"}return!0}).map(W=>[W.placement,W.overflows.filter(se=>se>0).reduce((se,ne)=>se+ne,0)]).sort((W,se)=>W[1]-se[1])[0])==null?void 0:z[0];ae&&(U=ae);break}case"initialPlacement":U=m;break}if(c!==U)return{reset:{placement:U}}}return{}}}};function Wx(t,n){return{top:t.top-n.height,right:t.right-n.width,bottom:t.bottom-n.height,left:t.left-n.width}}function qx(t){return _w.some(n=>t[n]>=0)}const Dw=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(n){const{rects:a,platform:o}=n,{strategy:c="referenceHidden",...u}=Wn(t,n);switch(c){case"referenceHidden":{const h=await o.detectOverflow(n,{...u,elementContext:"reference"}),m=Wx(h,a.reference);return{data:{referenceHiddenOffsets:m,referenceHidden:qx(m)}}}case"escaped":{const h=await o.detectOverflow(n,{...u,altBoundary:!0}),m=Wx(h,a.floating);return{data:{escapedOffsets:m,escaped:qx(m)}}}default:return{}}}}},mj=new Set(["left","top"]);async function $w(t,n){const{placement:a,platform:o,elements:c}=t,u=await(o.isRTL==null?void 0:o.isRTL(c.floating)),h=Ar(a),m=vl(a),x=vn(a)==="y",v=mj.has(h)?-1:1,N=u&&x?-1:1,j=Wn(n,t);let{mainAxis:w,crossAxis:_,alignmentAxis:S}=typeof j=="number"?{mainAxis:j,crossAxis:0,alignmentAxis:null}:{mainAxis:j.mainAxis||0,crossAxis:j.crossAxis||0,alignmentAxis:j.alignmentAxis};return m&&typeof S=="number"&&(_=m==="end"?S*-1:S),x?{x:_*N,y:w*v}:{x:w*v,y:_*N}}const Iw=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(n){var a,o;const{x:c,y:u,placement:h,middlewareData:m}=n,x=await $w(n,t);return h===((a=m.offset)==null?void 0:a.placement)&&(o=m.arrow)!=null&&o.alignmentOffset?{}:{x:c+x.x,y:u+x.y,data:{...x,placement:h}}}}},Mw=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(n){const{x:a,y:o,placement:c,platform:u}=n,{mainAxis:h=!0,crossAxis:m=!1,limiter:x={fn:k=>{let{x:R,y:C}=k;return{x:R,y:C}}},...v}=Wn(t,n),N={x:a,y:o},j=await u.detectOverflow(n,v),w=vn(c),_=Hm(w);let S=N[_],y=N[w];const g=(k,R)=>dj(R+j[k==="y"?"top":"left"],R,R-j[k==="y"?"bottom":"right"]);h&&(S=g(_,S)),m&&(y=g(w,y));const p=x.fn({...n,[_]:S,[w]:y});return{...p,data:{x:p.x-a,y:p.y-o,enabled:{[_]:h,[w]:m}}}}}},Ow=function(t){return t===void 0&&(t={}),{options:t,fn(n){var a,o;const{x:c,y:u,placement:h,rects:m,middlewareData:x}=n,{offset:v=0,mainAxis:N=!0,crossAxis:j=!0}=Wn(t,n),w={x:c,y:u},_=vn(h),S=Hm(_);let y=w[S],g=w[_];const p=Wn(v,n),k=typeof p=="number"?{mainAxis:p,crossAxis:0}:{mainAxis:(a=p.mainAxis)!=null?a:0,crossAxis:(o=p.crossAxis)!=null?o:0};if(N){const E=S==="y"?"height":"width",P=m.reference[S]-m.floating[E]+k.mainAxis,F=m.reference[S]+m.reference[E]-k.mainAxis;yF&&(y=F)}if(j){var R,C;const E=S==="y"?"width":"height",P=mj.has(Ar(h)),F=m.reference[_]-m.floating[E]+(P&&((R=x.offset)==null?void 0:R[_])||0)+(P?0:k.crossAxis),I=m.reference[_]+m.reference[E]+(P?0:((C=x.offset)==null?void 0:C[_])||0)-(P?k.crossAxis:0);gI&&(g=I)}return{[S]:y,[_]:g}}}},zw=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(n){const{placement:a,rects:o,platform:c,elements:u}=n,{apply:h=()=>{},...m}=Wn(t,n),x=await c.detectOverflow(n,m),v=Ar(a),N=vl(a),j=vn(a)==="y",{width:w,height:_}=o.floating;let S,y;v==="top"||v==="bottom"?(S=v,y=N===(await(c.isRTL==null?void 0:c.isRTL(u.floating))?"start":"end")?"left":"right"):(y=v,S=N==="end"?"top":"bottom");const g=_-x.top-x.bottom,p=w-x.left-x.right,k=Er(_-x[S],g),R=Er(w-x[y],p),C=n.middlewareData.shift,E=!C;let P=k,F=R;C!=null&&C.enabled.x&&(F=p),C!=null&&C.enabled.y&&(P=g),E&&!N&&(j?F=w-2*Hn(x.left,x.right):P=_-2*Hn(x.top,x.bottom)),await h({...n,availableWidth:F,availableHeight:P});const I=await c.getDimensions(u.floating);return w!==I.width||_!==I.height?{reset:{rects:!0}}:{}}}};function _c(){return typeof window<"u"}function jl(t){return hj(t)?(t.nodeName||"").toLowerCase():"#document"}function ds(t){var n;return(t==null||(n=t.ownerDocument)==null?void 0:n.defaultView)||window}function Qn(t){var n;return(n=(hj(t)?t.ownerDocument:t.document)||window.document)==null?void 0:n.documentElement}function hj(t){return _c()?t instanceof Node||t instanceof ds(t).Node:!1}function jn(t){return _c()?t instanceof Element||t instanceof ds(t).Element:!1}function Lr(t){return _c()?t instanceof HTMLElement||t instanceof ds(t).HTMLElement:!1}function Qx(t){return!_c()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof ds(t).ShadowRoot}function bc(t){const{overflow:n,overflowX:a,overflowY:o,display:c}=yn(t);return/auto|scroll|overlay|hidden|clip/.test(n+o+a)&&c!=="inline"&&c!=="contents"}function Uw(t){return/^(table|td|th)$/.test(jl(t))}function Nc(t){try{if(t.matches(":popover-open"))return!0}catch{}try{return t.matches(":modal")}catch{return!1}}const Bw=/transform|translate|scale|rotate|perspective|filter/,Hw=/paint|layout|strict|content/,ra=t=>!!t&&t!=="none";let bu;function Wm(t){const n=jn(t)?yn(t):t;return ra(n.transform)||ra(n.translate)||ra(n.scale)||ra(n.rotate)||ra(n.perspective)||!qm()&&(ra(n.backdropFilter)||ra(n.filter))||Bw.test(n.willChange||"")||Hw.test(n.contain||"")}function Vw(t){let n=ma(t);for(;Lr(n)&&!Ni(n);){if(Wm(n))return n;if(Nc(n))return null;n=ma(n)}return null}function qm(){return bu==null&&(bu=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),bu}function Ni(t){return/^(html|body|#document)$/.test(jl(t))}function yn(t){return ds(t).getComputedStyle(t)}function wc(t){return jn(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function ma(t){if(jl(t)==="html")return t;const n=t.assignedSlot||t.parentNode||Qx(t)&&t.host||Qn(t);return Qx(n)?n.host:n}function fj(t){const n=ma(t);return Ni(n)?(t.ownerDocument||t).body:Lr(n)&&bc(n)?n:fj(n)}function wi(t,n,a){var o;n===void 0&&(n=[]),a===void 0&&(a=!0);const c=fj(t),u=c===((o=t.ownerDocument)==null?void 0:o.body),h=ds(c);if(u){const m=gm(h);return n.concat(h,h.visualViewport||[],bc(c)?c:[],m&&a?wi(m):[])}else return n.concat(c,wi(c,[],a))}function gm(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function xj(t){const n=yn(t);let a=parseFloat(n.width)||0,o=parseFloat(n.height)||0;const c=Lr(t),u=c?t.offsetWidth:a,h=c?t.offsetHeight:o,m=cc(a)!==u||cc(o)!==h;return m&&(a=u,o=h),{width:a,height:o,$:m}}function Qm(t){return jn(t)?t:t.contextElement}function hl(t){const n=Qm(t);if(!Lr(n))return Vn(1);const a=n.getBoundingClientRect(),{width:o,height:c,$:u}=xj(n);let h=(u?cc(a.width):a.width)/o,m=(u?cc(a.height):a.height)/c;return(!h||!Number.isFinite(h))&&(h=1),(!m||!Number.isFinite(m))&&(m=1),{x:h,y:m}}const Gw=Vn(0);function pj(t){const n=ds(t);return!qm()||!n.visualViewport?Gw:{x:n.visualViewport.offsetLeft,y:n.visualViewport.offsetTop}}function Ww(t,n,a){return n===void 0&&(n=!1),!!a&&n&&a===ds(t)}function ha(t,n,a,o){n===void 0&&(n=!1),a===void 0&&(a=!1);const c=t.getBoundingClientRect(),u=Qm(t);let h=Vn(1);n&&(o?jn(o)&&(h=hl(o)):h=hl(t));const m=Ww(u,a,o)?pj(u):Vn(0);let x=(c.left+m.x)/h.x,v=(c.top+m.y)/h.y,N=c.width/h.x,j=c.height/h.y;if(u&&o){const w=ds(u),_=jn(o)?ds(o):o;let S=w,y=gm(S);for(;y&&_!==S;){const g=hl(y),p=y.getBoundingClientRect(),k=yn(y),R=p.left+(y.clientLeft+parseFloat(k.paddingLeft))*g.x,C=p.top+(y.clientTop+parseFloat(k.paddingTop))*g.y;x*=g.x,v*=g.y,N*=g.x,j*=g.y,x+=R,v+=C,S=ds(y),y=gm(S)}}return uc({width:N,height:j,x,y:v})}function Sc(t,n){const a=wc(t).scrollLeft;return n?n.left+a:ha(Qn(t)).left+a}function gj(t,n){const a=t.getBoundingClientRect(),o=a.left+n.scrollLeft-Sc(t,a),c=a.top+n.scrollTop;return{x:o,y:c}}function qw(t){let{elements:n,rect:a,offsetParent:o,strategy:c}=t;const u=c==="fixed",h=Qn(o),m=n?Nc(n.floating):!1;if(o===h||m&&u)return a;let x={scrollLeft:0,scrollTop:0},v=Vn(1);const N=Vn(0),j=Lr(o);if((j||!u)&&((jl(o)!=="body"||bc(h))&&(x=wc(o)),j)){const _=ha(o);v=hl(o),N.x=_.x+o.clientLeft,N.y=_.y+o.clientTop}const w=h&&!j&&!u?gj(h,x):Vn(0);return{width:a.width*v.x,height:a.height*v.y,x:a.x*v.x-x.scrollLeft*v.x+N.x+w.x,y:a.y*v.y-x.scrollTop*v.y+N.y+w.y}}function Qw(t){return t.getClientRects?Array.from(t.getClientRects()):[]}function Kw(t){const n=wc(t),a=t.ownerDocument.body,o=Hn(t.scrollWidth,t.clientWidth,a.scrollWidth,a.clientWidth),c=Hn(t.scrollHeight,t.clientHeight,a.scrollHeight,a.clientHeight);let u=-n.scrollLeft+Sc(t);const h=-n.scrollTop;return yn(a).direction==="rtl"&&(u+=Hn(t.clientWidth,a.clientWidth)-o),{width:o,height:c,x:u,y:h}}const Xw=25;function Yw(t,n,a){a===void 0&&(a="viewport");const o=a==="layoutViewport",c=ds(t),u=Qn(t),h=c.visualViewport;let m=u.clientWidth,x=u.clientHeight,v=0,N=0;if(h){const w=!qm()||n==="fixed";o?w||(v=-h.offsetLeft,N=-h.offsetTop):(m=h.width,x=h.height,w&&(v=h.offsetLeft,N=h.offsetTop))}if(Sc(u)<=0){const w=u.ownerDocument,_=w.body,S=getComputedStyle(_),y=w.compatMode==="CSS1Compat"&&parseFloat(S.marginLeft)+parseFloat(S.marginRight)||0,g=Math.abs(u.clientWidth-_.clientWidth-y),p=getComputedStyle(u).scrollbarGutter==="stable both-edges"?g/2:g;p<=Xw&&(m-=p)}return{width:m,height:x,x:v,y:N}}function Zw(t,n){const a=ha(t,!0,n==="fixed"),o=a.top+t.clientTop,c=a.left+t.clientLeft,u=hl(t),h=t.clientWidth*u.x,m=t.clientHeight*u.y,x=c*u.x,v=o*u.y;return{width:h,height:m,x,y:v}}function Kx(t,n,a){let o;if(n==="viewport"||n==="layoutViewport")o=Yw(t,a,n);else if(n==="document")o=Kw(Qn(t));else if(jn(n))o=Zw(n,a);else{const c=pj(t);o={x:n.x-c.x,y:n.y-c.y,width:n.width,height:n.height}}return uc(o)}function Jw(t,n){const a=n.get(t);if(a)return a;let o=wi(t,[],!1).filter(m=>jn(m)&&jl(m)!=="body"),c=null;const u=yn(t).position==="fixed";let h=u?ma(t):t;for(;jn(h)&&!Ni(h);){const m=yn(h),x=Wm(h),v=c?c.position:u?"fixed":"";!x&&(v==="fixed"||v==="absolute"&&m.position==="static")?o=o.filter(j=>j!==h):c=m,h=ma(h)}return n.set(t,o),o}function e2(t){let{element:n,boundary:a,rootBoundary:o,strategy:c}=t;const h=[...a==="clippingAncestors"?Nc(n)?[]:Jw(n,this._c):[].concat(a),o],m=Kx(n,h[0],c);let x=m.top,v=m.right,N=m.bottom,j=m.left;for(let w=1;w{m(!1,1e-7)},1e3)}F=!1}try{o=new IntersectionObserver(I,{...P,root:u.ownerDocument})}catch{o=new IntersectionObserver(I,P)}o.observe(t)}const x=ds(t),v=()=>m(a);return x.addEventListener("resize",v),m(!0),()=>{x.removeEventListener("resize",v),h()}}function i2(t,n,a,o){o===void 0&&(o={});const{ancestorScroll:c=!0,ancestorResize:u=!0,elementResize:h=typeof ResizeObserver=="function",layoutShift:m=typeof IntersectionObserver=="function",animationFrame:x=!1}=o,v=Qm(t),N=c||u?[...v?wi(v):[],...n?wi(n):[]]:[];N.forEach(p=>{c&&p.addEventListener("scroll",a),u&&p.addEventListener("resize",a)});const j=v&&m?l2(v,a,u):null;let w=-1,_=null;h&&(_=new ResizeObserver(p=>{let[k]=p;k&&k.target===v&&_&&n&&(_.unobserve(n),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=_)==null||R.observe(n)})),a()}),v&&!x&&_.observe(v),n&&_.observe(n));let S,y=x?ha(t):null;x&&g();function g(){const p=ha(t);y&&!jj(y,p)&&a(),y=p,S=requestAnimationFrame(g)}return a(),()=>{var p;N.forEach(k=>{c&&k.removeEventListener("scroll",a),u&&k.removeEventListener("resize",a)}),j==null||j(),(p=_)==null||p.disconnect(),_=null,x&&cancelAnimationFrame(S)}}const o2=Iw,c2=Mw,d2=Fw,u2=zw,m2=Dw,Yx=Lw,h2=Ow,f2=(t,n,a)=>{const o=new Map,c=a??{},u={...a2,...c.platform,_c:o};return Tw(t,n,{...c,platform:u})};var x2=typeof document<"u",p2=function(){},ac=x2?i.useLayoutEffect:p2;function mc(t,n){if(t===n)return!0;if(typeof t!=typeof n)return!1;if(typeof t=="function"&&t.toString()===n.toString())return!0;let a,o,c;if(t&&n&&typeof t=="object"){if(Array.isArray(t)){if(a=t.length,a!==n.length)return!1;for(o=a;o--!==0;)if(!mc(t[o],n[o]))return!1;return!0}if(c=Object.keys(t),a=c.length,a!==Object.keys(n).length)return!1;for(o=a;o--!==0;)if(!{}.hasOwnProperty.call(n,c[o]))return!1;for(o=a;o--!==0;){const u=c[o];if(!(u==="_owner"&&t.$$typeof)&&!mc(t[u],n[u]))return!1}return!0}return t!==t&&n!==n}function yj(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function Zx(t,n){const a=yj(t);return Math.round(n*a)/a}function wu(t){const n=i.useRef(t);return ac(()=>{n.current=t}),n}function g2(t){t===void 0&&(t={});const{placement:n="bottom",strategy:a="absolute",middleware:o=[],platform:c,elements:{reference:u,floating:h}={},transform:m=!0,whileElementsMounted:x,open:v}=t,[N,j]=i.useState({x:0,y:0,strategy:a,placement:n,middlewareData:{},isPositioned:!1}),[w,_]=i.useState(o);mc(w,o)||_(o);const[S,y]=i.useState(null),[g,p]=i.useState(null),k=i.useCallback(W=>{W!==P.current&&(P.current=W,y(W))},[]),R=i.useCallback(W=>{W!==F.current&&(F.current=W,p(W))},[]),C=u||S,E=h||g,P=i.useRef(null),F=i.useRef(null),I=i.useRef(N),M=x!=null,$=wu(x),O=wu(c),L=wu(v),z=i.useCallback(()=>{if(!P.current||!F.current)return;const W={placement:n,strategy:a,middleware:w};O.current&&(W.platform=O.current),f2(P.current,F.current,W).then(se=>{const ne={...se,isPositioned:L.current!==!1};Y.current&&!mc(I.current,ne)&&(I.current=ne,Fm.flushSync(()=>{j(ne)}))})},[w,n,a,O,L]);ac(()=>{v===!1&&I.current.isPositioned&&(I.current.isPositioned=!1,j(W=>({...W,isPositioned:!1})))},[v]);const Y=i.useRef(!1);ac(()=>(Y.current=!0,()=>{Y.current=!1}),[]),ac(()=>{if(C&&(P.current=C),E&&(F.current=E),C&&E){if($.current)return $.current(C,E,z);z()}},[C,E,z,$,M]);const G=i.useMemo(()=>({reference:P,floating:F,setReference:k,setFloating:R}),[k,R]),U=i.useMemo(()=>({reference:C,floating:E}),[C,E]),ae=i.useMemo(()=>{const W={position:a,left:0,top:0};if(!U.floating)return W;const se=Zx(U.floating,N.x),ne=Zx(U.floating,N.y);return m?{...W,transform:"translate("+se+"px, "+ne+"px)",...yj(U.floating)>=1.5&&{willChange:"transform"}}:{position:a,left:se,top:ne}},[a,m,U.floating,N.x,N.y]);return i.useMemo(()=>({...N,update:z,refs:G,elements:U,floatingStyles:ae}),[N,z,G,U,ae])}const v2=t=>{function n(a){return{}.hasOwnProperty.call(a,"current")}return{name:"arrow",options:t,fn(a){const{element:o,padding:c}=typeof t=="function"?t(a):t;return o&&n(o)?o.current!=null?Yx({element:o.current,padding:c}).fn(a):{}:o?Yx({element:o,padding:c}).fn(a):{}}}},j2=(t,n)=>{const a=o2(t);return{name:a.name,fn:a.fn,options:[t,n]}},y2=(t,n)=>{const a=c2(t);return{name:a.name,fn:a.fn,options:[t,n]}},_2=(t,n)=>({fn:h2(t).fn,options:[t,n]}),b2=(t,n)=>{const a=d2(t);return{name:a.name,fn:a.fn,options:[t,n]}},N2=(t,n)=>{const a=u2(t);return{name:a.name,fn:a.fn,options:[t,n]}},w2=(t,n)=>{const a=m2(t);return{name:a.name,fn:a.fn,options:[t,n]}},S2=(t,n)=>{const a=v2(t);return{name:a.name,fn:a.fn,options:[t,n]}};var C2=Object.defineProperty,kr=(t,n)=>C2(t,"name",{value:n,configurable:!0}),_j="Popper",[bj,Nj]=vc(_j),[k2,wj]=bj(_j),E2=kr(t=>{const{__scopePopper:n,children:a}=t,[o,c]=i.useState(null),[u,h]=i.useState(void 0);return e.jsx(k2,{scope:n,anchor:o,onAnchorChange:c,placementState:u,setPlacementState:h,children:a})},"Popper"),A2="PopperAnchor",R2=i.forwardRef(kr(function(n,a){const{__scopePopper:o,virtualRef:c,...u}=n,h=wj(A2,o),m=i.useRef(null),x=h.onAnchorChange,v=i.useCallback(y=>{m.current=y,y&&x(y)},[x]),N=_n(a,v),j=i.useRef(null);i.useEffect(()=>{if(!c)return;const y=j.current;j.current=c.current,y!==j.current&&x(j.current)});const w=h.placementState&&Cc(h.placementState),_=w==null?void 0:w[0],S=w==null?void 0:w[1];return c?null:e.jsx(bn.div,{"data-radix-popper-side":_,"data-radix-popper-align":S,...u,ref:N})},"PopperAnchor")),Sj="PopperContent",[P2,h3]=bj(Sj),T2=i.forwardRef(kr(function(n,a){var re,Ee,nt,ct,Ut,Yt,Ns;const{__scopePopper:o,side:c="bottom",sideOffset:u=0,align:h="center",alignOffset:m=0,arrowPadding:x=0,avoidCollisions:v=!0,collisionBoundary:N=[],collisionPadding:j=0,sticky:w="partial",hideWhenDetached:_=!1,updatePositionStrategy:S="optimized",onPlaced:y,...g}=n,p=wj(Sj,o),[k,R]=i.useState(null),C=_n(a,R),[E,P]=i.useState(null),F=cj(E),I=(F==null?void 0:F.width)??0,M=(F==null?void 0:F.height)??0,$=c+(h!=="center"?"-"+h:""),O=typeof j=="number"?j:{top:0,right:0,bottom:0,left:0,...j},L=Array.isArray(N)?N:[N],z=L.length>0,Y={padding:O,boundary:L.filter(Cj),altBoundary:z},{refs:G,floatingStyles:U,placement:ae,isPositioned:W,middlewareData:se}=g2({strategy:"fixed",placement:$,whileElementsMounted:kr((...ws)=>i2(...ws,{animationFrame:S==="always"}),"whileElementsMounted"),elements:{reference:p.anchor},middleware:[j2({mainAxis:u+M,alignmentAxis:m}),v&&y2({mainAxis:!0,crossAxis:!1,limiter:w==="partial"?_2():void 0,...Y}),v&&b2({...Y}),N2({...Y,apply:kr(({elements:ws,rects:Sn,availableWidth:$r,availableHeight:Ir})=>{const{width:Ss,height:tn}=Sn.reference,sn=ws.floating.style;sn.setProperty("--radix-popper-available-width",`${$r}px`),sn.setProperty("--radix-popper-available-height",`${Ir}px`),sn.setProperty("--radix-popper-anchor-width",`${Ss}px`),sn.setProperty("--radix-popper-anchor-height",`${tn}px`)},"apply")}),E&&S2({element:E,padding:x}),L2({arrowWidth:I,arrowHeight:M}),_&&w2({strategy:"referenceHidden",...Y,boundary:z?Y.boundary:void 0})]}),ne=p.setPlacementState;Us(()=>(ne(ae),()=>{ne(void 0)}),[ae,ne]);const[q,J]=Cc(ae),le=ua(y);Us(()=>{W&&(le==null||le())},[W,le]);const ke=(re=se.arrow)==null?void 0:re.x,Ce=(Ee=se.arrow)==null?void 0:Ee.y,Ae=((nt=se.arrow)==null?void 0:nt.centerOffset)!==0,[Z,fe]=i.useState();return Us(()=>{k&&fe(window.getComputedStyle(k).zIndex)},[k]),e.jsx("div",{ref:G.setFloating,"data-radix-popper-content-wrapper":"",style:{...U,transform:W?U.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Z,"--radix-popper-transform-origin":[(ct=se.transformOrigin)==null?void 0:ct.x,(Ut=se.transformOrigin)==null?void 0:Ut.y].join(" "),...((Yt=se.hide)==null?void 0:Yt.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:n.dir,children:e.jsx(P2,{scope:o,placedSide:q,placedAlign:J,onArrowChange:P,arrowX:ke,arrowY:Ce,shouldHideArrow:Ae,children:e.jsx(bn.div,{"data-side":q,"data-align":J,...g,ref:C,style:{...g.style,animation:W?(Ns=g.style)==null?void 0:Ns.animation:"none"}})})})},"PopperContent"));function Cj(t){return t!==null}kr(Cj,"isNotNull");var L2=kr(t=>({name:"transformOrigin",options:t,fn(n){var g,p,k;const{placement:a,rects:o,middlewareData:c}=n,h=((g=c.arrow)==null?void 0:g.centerOffset)!==0,m=h?0:t.arrowWidth,x=h?0:t.arrowHeight,[v,N]=Cc(a),j={start:"0%",center:"50%",end:"100%"}[N],w=(((p=c.arrow)==null?void 0:p.x)??0)+m/2,_=(((k=c.arrow)==null?void 0:k.y)??0)+x/2;let S="",y="";return v==="bottom"?(S=h?j:`${w}px`,y=`${-x}px`):v==="top"?(S=h?j:`${w}px`,y=`${o.floating.height+x}px`):v==="right"?(S=`${-x}px`,y=h?j:`${_}px`):v==="left"&&(S=`${o.floating.width+x}px`,y=h?j:`${_}px`),{data:{x:S,y}}}}),"transformOrigin");function Cc(t){const[n,a="center"]=t.split("-");return[n,a]}kr(Cc,"getSideAndAlignFromPlacement");var F2=E2,D2=R2,$2=T2,I2=Object.defineProperty,Fr=(t,n)=>I2(t,"name",{value:n,configurable:!0}),Km="Popover",[kj,f3]=vc(Km,[Nj]),Xm=Nj(),[M2,yl]=kj(Km),O2=Fr(t=>{const{__scopePopover:n,children:a,open:o,defaultOpen:c,onOpenChange:u,modal:h=!1}=t,m=Xm(n),x=i.useRef(null),[v,N]=i.useState(!1),[j,w]=$m({prop:o,defaultProp:c??!1,onChange:u,caller:Km});return e.jsx(F2,{...m,children:e.jsx(M2,{scope:n,contentId:ji(),triggerRef:x,open:j,onOpenChange:w,onOpenToggle:i.useCallback(()=>w(_=>!_),[w]),hasCustomAnchor:v,onCustomAnchorAdd:i.useCallback(()=>N(!0),[]),onCustomAnchorRemove:i.useCallback(()=>N(!1),[]),modal:h,children:a})})},"Popover"),z2="PopoverTrigger",U2=i.forwardRef(Fr(function(n,a){const{__scopePopover:o,...c}=n,u=yl(z2,o),h=Xm(o),m=_n(a,u.triggerRef),x=e.jsx(bn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":u.open,"aria-controls":u.open?u.contentId:void 0,"data-state":Ym(u.open),...c,ref:m,onClick:zs(n.onClick,u.onOpenToggle)});return u.hasCustomAnchor?x:e.jsx(D2,{asChild:!0,...h,children:x})},"PopoverTrigger")),Ej="PopoverPortal",[B2,H2]=kj(Ej,{forceMount:void 0}),V2=Fr(t=>{const{__scopePopover:n,forceMount:a,children:o,container:c}=t,u=yl(Ej,n);return e.jsx(B2,{scope:n,forceMount:a,children:e.jsx(Di,{present:a||u.open,children:e.jsx(Kv,{asChild:!0,container:c,children:o})})})},"PopoverPortal"),Si="PopoverContent",G2=i.forwardRef(Fr(function(n,a){const o=H2(Si,n.__scopePopover),{forceMount:c=o.forceMount,...u}=n,h=yl(Si,n.__scopePopover);return e.jsx(Di,{present:c||h.open,children:h.modal?e.jsx(q2,{...u,ref:a}):e.jsx(Q2,{...u,ref:a})})},"PopoverContent")),W2=Li("PopoverContent.RemoveScroll"),q2=i.forwardRef(Fr(function(n,a){const o=yl(Si,n.__scopePopover),c=i.useRef(null),u=_n(a,c),h=i.useRef(!1);return i.useEffect(()=>{const m=c.current;if(m)return rj(m)},[]),e.jsx(zm,{as:W2,allowPinchZoom:!0,children:e.jsx(Aj,{...n,ref:u,trapFocus:o.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:zs(n.onCloseAutoFocus,m=>{var x;m.preventDefault(),h.current||(x=o.triggerRef.current)==null||x.focus()}),onPointerDownOutside:zs(n.onPointerDownOutside,m=>{const x=m.detail.originalEvent,v=x.button===0&&x.ctrlKey===!0,N=x.button===2||v;h.current=N},{checkForDefaultPrevented:!1}),onFocusOutside:zs(n.onFocusOutside,m=>m.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),Q2=i.forwardRef(Fr(function(n,a){const o=yl(Si,n.__scopePopover),c=i.useRef(!1),u=i.useRef(!1);return e.jsx(Aj,{...n,ref:a,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:h=>{var m,x;(m=n.onCloseAutoFocus)==null||m.call(n,h),h.defaultPrevented||(c.current||(x=o.triggerRef.current)==null||x.focus(),h.preventDefault()),c.current=!1,u.current=!1},onInteractOutside:h=>{var v,N;(v=n.onInteractOutside)==null||v.call(n,h),h.defaultPrevented||(c.current=!0,h.detail.originalEvent.type==="pointerdown"&&(u.current=!0));const m=h.target;((N=o.triggerRef.current)==null?void 0:N.contains(m))&&h.preventDefault(),h.detail.originalEvent.type==="focusin"&&u.current&&h.preventDefault()}})},"PopoverContentNonModal")),Aj=i.forwardRef(Fr(function(n,a){const{__scopePopover:o,trapFocus:c,onOpenAutoFocus:u,onCloseAutoFocus:h,disableOutsidePointerEvents:m,onEscapeKeyDown:x,onPointerDownOutside:v,onFocusOutside:N,onInteractOutside:j,...w}=n,_=yl(Si,o),S=Xm(o);return jc(),e.jsx(Bv,{asChild:!0,loop:!0,trapped:c,onMountAutoFocus:u,onUnmountAutoFocus:h,children:e.jsx(Mv,{asChild:!0,disableOutsidePointerEvents:m,onInteractOutside:j,onEscapeKeyDown:x,onPointerDownOutside:v,onFocusOutside:N,onDismiss:()=>_.onOpenChange(!1),deferPointerDownOutside:!0,children:e.jsx($2,{"data-state":Ym(_.open),role:"dialog",id:_.contentId,...S,...w,ref:a,style:{...w.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})},"PopoverContentImpl"));function Ym(t){return t?"open":"closed"}Fr(Ym,"getState");var K2=O2,X2=U2,Y2=V2,Z2=G2;const Jx=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,ep=sv,Zm=(t,n)=>a=>{var o;if((n==null?void 0:n.variants)==null)return ep(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:c,defaultVariants:u}=n,h=Object.keys(c).map(v=>{const N=a==null?void 0:a[v],j=u==null?void 0:u[v];if(N===null)return null;const w=Jx(N)||Jx(j);return c[v][w]}),m=a&&Object.entries(a).reduce((v,N)=>{let[j,w]=N;return w===void 0||(v[j]=w),v},{}),x=n==null||(o=n.compoundVariants)===null||o===void 0?void 0:o.reduce((v,N)=>{let{class:j,className:w,..._}=N;return Object.entries(_).every(S=>{let[y,g]=S;return Array.isArray(g)?g.includes({...u,...m}[y]):{...u,...m}[y]===g})?[...v,j,w]:v},[]);return ep(t,h,x,a==null?void 0:a.class,a==null?void 0:a.className)},J2=Zm("inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-md border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 [&>svg]:pointer-events-none [&>svg]:size-3",{variants:{variant:{default:"bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"bg-destructive text-destructive-foreground [a&]:hover:bg-destructive/90",outline:"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",ghost:"[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",link:"text-primary underline-offset-4 [a&]:hover:underline",success:"bg-success/10 text-success",warning:"bg-warning/10 text-warning",info:"bg-info/10 text-info",danger:"bg-destructive/10 text-destructive",accent:"bg-primary/10 text-primary","success-solid":"bg-success text-primary-foreground","warning-solid":"bg-warning text-primary-foreground","danger-solid":"bg-destructive text-destructive-foreground","info-solid":"bg-info text-primary-foreground"}},defaultVariants:{variant:"default"}});function V({className:t,variant:n="default",asChild:a=!1,...o}){const c=a?jv:"span";return e.jsx(c,{"data-slot":"badge","data-variant":n,className:gv(J2({variant:n}),t),...o})}const e1={green:{variant:"success",label:"OK"},amber:{variant:"warning",label:"DEGRADED"},red:{variant:"danger-solid",label:"DOWN"}};function t1({status:t}){const{variant:n,label:a}=e1[t];return e.jsx(V,{variant:n,children:a})}const Su=t=>`${Math.round(t*100)}%`,s1=t=>t?t.slice(0,16).replace("T"," "):"—",ol="border-b px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",aa=`${ol} text-right`,cl="border-b p-2 text-[13px]",la=`${cl} text-right tabular-nums`;function n1({sources:t}){return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[900px] text-[13px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-muted-foreground",children:[e.jsx("th",{className:ol,children:"Source"}),e.jsx("th",{className:ol,children:"Tier"}),e.jsx("th",{className:ol,children:"Status"}),e.jsx("th",{className:aa,children:"Rows"}),e.jsx("th",{className:aa,children:"Ingested / baseline"}),e.jsx("th",{className:aa,children:"Coverage"}),e.jsx("th",{className:aa,children:"Latency"}),e.jsx("th",{className:aa,children:"High"}),e.jsx("th",{className:aa,children:"Med"}),e.jsx("th",{className:aa,children:"Low"}),e.jsx("th",{className:ol,children:"Last success"}),e.jsx("th",{className:ol,children:"Signals"})]})}),e.jsx("tbody",{children:t.map(n=>e.jsxs("tr",{className:"border-t",children:[e.jsxs("td",{className:cl,children:[e.jsx("div",{className:"font-semibold",children:n.sourceName}),e.jsx("div",{className:"text-xs text-muted-foreground",children:n.error??n.prefix??n.source})]}),e.jsxs("td",{className:cl,children:["T",n.tier]}),e.jsx("td",{className:cl,children:e.jsx(t1,{status:n.status})}),e.jsx("td",{className:la,children:n.rowCount.toLocaleString()}),e.jsxs("td",{className:la,children:[n.ingested.toLocaleString()," / ",n.expected_baseline.toLocaleString()]}),e.jsx("td",{className:`${la} ${r1(n)}`,children:n.coverage_pct===null?"—":`${n.coverage_pct}%`}),e.jsxs("td",{className:la,children:[n.latencyMs," ms"]}),e.jsx("td",{className:la,children:Su(n.flagRates.high)}),e.jsx("td",{className:la,children:Su(n.flagRates.medium)}),e.jsx("td",{className:`${la} ${n.flagRates.low>.5?"text-destructive":""}`,children:Su(n.flagRates.low)}),e.jsx("td",{className:`${cl} text-xs text-muted-foreground`,children:s1(n.last_success_at)}),e.jsx("td",{className:cl,children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[n.last_http_status!==null&&n.last_http_status!==200&&e.jsxs(Yo,{tone:"red",children:["HTTP ",n.last_http_status]}),n.retry_schedule.length>0&&e.jsxs(Yo,{tone:"red",children:["retry +",n.retry_schedule.map(a=>`${a.in_hours}h`).join("/+")]}),n.schema_drift_suspected&&e.jsx(Yo,{tone:"red",children:"SCHEMA_DRIFT_SUSPECTED"}),n.unexpected_vintage&&e.jsxs(Yo,{tone:"amber",children:["vintage held: ",n.unexpected_vintage]})]})})]},n.source))})]})})}function r1(t){return t.status==="red"?"text-destructive":t.coverage_pct!==null&&t.coverage_pct<90?"text-warning":""}function Yo({children:t,tone:n}){return e.jsx("span",{className:`whitespace-nowrap rounded-md px-1.5 py-px text-[11px] ${n==="red"?"bg-destructive/10 text-destructive":"bg-warning/10 text-warning"}`,children:t})}const it="/v1/graph",pa="/v1/cas/dimensions/industrial-base",Ke=t=>({"x-subscriber-tier":t.tier,"x-user-role":t.role,"x-user-id":t.user_id,...t.org_name?{"x-org-name":t.org_name}:{}}),ga=t=>{const n=new URLSearchParams;for(const[o,c]of Object.entries(t))c!=null&&c!==""&&n.set(o,String(c));const a=n.toString();return a?`?${a}`:""},Ft=encodeURIComponent,Rj=t=>he(`${it}/health`,Ke(t)),a1=t=>he(`${it}/schema/changelog`,Ke(t)),l1=t=>he(`${it}/completeness`,Ke(t)),i1=t=>he(`${it}/validation-report`,Ke(t)),Pj=t=>he(`${it}/snapshots`,Ke(t)),o1=["AAPI_FILING","JO_DECREE","ONS_SURVEY","ANALYST_MANUAL","MEDIA_REPORT"],c1=["annual_capacity_tonnes_or_units","capacity_utilization_pct","workforce_headcount","energy_consumption_mwh","export_volume_usd","primary_wilaya","utilization_note"],_l=(t,n)=>he(`${it}/anchor-firms${ga({q:n})}`,Ke(t)),d1=(t,n)=>he(`${it}/anchor-firms/${Ft(n)}/profile`,Ke(t)),u1=(t,n,a)=>pl(`${it}/anchor-firms/${Ft(n)}/profile`,a,Ke(t)),m1=(t,n,a)=>be(`${it}/anchor-firms/${Ft(n)}/products`,a,Ke(t)),h1=(t,n,a,o)=>Pm(`${it}/anchor-firms/${Ft(n)}/products/${Ft(a)}`,Ke(t),o),f1=(t,n)=>he(`${it}/anchor-firms/${Ft(n)}/change-history`,Ke(t)),x1=(t,n,a,o)=>be(`${it}/anchor-firms/${Ft(n)}/change-history/${Ft(a)}/revert`,{revert_reason:o},Ke(t)),p1=(t,n,a={})=>he(`${it}/anchor-firms/${Ft(n)}/suppliers${ga(a)}`,Ke(t)),g1=(t,n)=>he(`${it}/anchor-firms/${Ft(n)}/supplier-counts`,Ke(t)),v1=t=>he(`${it}/uploads/template`,Ke(t)),j1=(t,n)=>be(`${it}/uploads`,n,Ke(t)),y1=(t,n,a={})=>he(`${it}/anchor-firms/${Ft(n)}/input-gaps${ga({...a})}`,Ke(t)),_1=(t,n,a={})=>be(`${it}/anchor-firms/input-gaps/batch`,{firm_ids:n,...a},Ke(t)),tp=(t,n,a={})=>he(`${it}/anchor-firms/${Ft(n)}/ecosystem${ga(a)}`,Ke(t)),b1=(t,n)=>he(`${it}/anchor-firms/${Ft(n)}/ecosystem/export`,Ke(t)),Tj=t=>he(`${it}/ingestion/runs`,Ke(t)),N1=(t,n)=>he(`${it}/ingestion/ai-jobs${ga({run_id:n})}`,Ke(t)),w1=(t,n)=>be(`${it}/ingestion/trigger`,{quarterly_cycle_label:n},Ke(t)),S1=(t,n={})=>he(`${it}/ingestion/conflicts${ga(n)}`,Ke(t)),Lj=(t,n={})=>he(`${it}/review-items${ga(n)}`,Ke(t)),C1=(t,n,a)=>be(`${it}/review-items/${Ft(n)}/resolve`,a,Ke(t)),k1=(t,n)=>be(`${it}/refresh/trigger`,{quarterly_cycle_label:n},Ke(t)),E1=(t,n)=>he(`${it}/refresh/runs/${Ft(n)}/report`,Ke(t)),A1=(t,n,a)=>be(`${it}/refresh/runs/${Ft(n)}/certify`,a,Ke(t)),R1=(t,n)=>be(`${it}/refresh/runs/${Ft(n)}/retry`,{},Ke(t)),oa=["chapter_overlap","wilaya_colocation","input_overlap","supplier_density","upstream_gap"],P1=t=>he(`${pa}/config`,Ke(t)),T1=t=>he(`${pa}/config/changelog`,Ke(t)),L1=(t,n)=>be(`${pa}/config/preview`,{weights:n},Ke(t)),F1=(t,n)=>Ri(`${pa}/config`,n,Ke(t)),Fj=t=>be(`${pa}/compute`,{},Ke(t)),D1=t=>he(`${pa}/concordance`,Ke(t)),$1=t=>he(`${pa}/lines`,Ke(t)),I1=(t,n)=>he(`/v1/opportunity-cards/${Ft(n)}/anchor-proximity`,Ke(t)),sp={tier:"1",role:"ml_engineer",user_id:"console-ops"};function M1(){var h;const[t,n]=i.useState(null),[a,o]=i.useState(null),[c,u]=i.useState("");return i.useEffect(()=>{Promise.all([Rj(sp),Pj(sp)]).then(([m,x])=>{n(m),o(x.snapshots[0]??null)}).catch(m=>u(m instanceof Error?m.message:"unavailable"))},[]),e.jsxs("section",{className:"mt-4 flex flex-wrap items-center gap-4 rounded-xl border bg-card p-4 text-sm","aria-label":"Anchor-firm graph status",children:[e.jsx("strong",{children:"Anchor-firm graph"}),c?e.jsx("span",{className:"text-destructive",children:c}):t?e.jsxs(e.Fragment,{children:[e.jsx(V,{variant:t.db_status==="UP"?"success":"danger",children:t.db_status}),e.jsxs("span",{className:"tabular-nums",children:[t.node_count.toLocaleString("en-US")," nodes · ",t.relationship_count.toLocaleString("en-US")," relationships"]}),e.jsxs("span",{className:"text-muted-foreground",children:["schema ",t.last_schema_version]}),e.jsxs("span",{className:"text-muted-foreground",children:["last ingestion ",((h=t.last_ingestion_timestamp)==null?void 0:h.slice(0,16).replace("T"," "))??"—"]}),e.jsxs("span",{className:"text-muted-foreground",children:["certified ",a?`${a.quarterly_cycle_label} (${a.certification_type})`:"—"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"loading…"})]})}function ue({label:t,value:n,tone:a}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:t}),e.jsx("div",{className:`text-sm font-semibold ${a==="error"?"text-destructive":a==="ok"?"text-success":"text-foreground"}`,children:n})]})}function H({children:t,tone:n}){return e.jsx("section",{className:`mt-4 rounded-xl border bg-card p-4 ${n==="error"?"text-destructive":"text-muted-foreground"}`,children:t})}const Dj=48,wn=(t,n=0)=>{const a=new Int32Array(t.length);for(let o=0;o{const n=new Int32Array(t.length+1);for(let a=0;a{const n=new Int32Array(t.length);let a=0;for(let o=0;o>>1^-(c&1),n[o]=a}return n},O1=384,z1=[],ca=kc(wn("E0500002005282000000002000150000020021820000011200000003022202000300004200120000200420001200021200301200010400162000010000220021010:2192001200220012000220012000200200200400010200040000000000400200108200110100000022010313000162002000020020012020080213000228200000000082000000000120002000120020020040101020300130001001010")),U1=kc(wn(":11111111211111119311546544411119731869:671397415686432441111111111161114151214313433415:78311132233313187211117221449443411141111151152226611131111112212518142224214215421421542142424242516171151615616347111111111197911327451111111111111111111113134714133513411111311111111111111111111112444411111342312715245411117:3")),B1="@containerabcdefghinlmoprstunderlineviawzccentlignnimatespectuto-colsrowsaglorightnessckdrop-sisbcontrastfiltergrayscalehue-rotateinvertopacityslurrightnessaturateepia-coniclinearpositionradialsizeockurrderttom-belrstxyespacing-xyaretoursorlnt-umnsendspantartainentrasteividerop-shadowurationcorationlay-xyasendillexontromlter-featuresstretchapr-xyayscaleidow-colsrowsue-rotatedentlinesetvert-beringsxyeshadoweiadingftnest-clamp-imageabein-lrstxyskx--b-coniclpositionrsizet-x-y-fromto-fromto-inearfromto-fromto-adialfromto-fromtofromtofromtofromtoblockhinlinew-screenesblockhinlinewbjectpacityrutlinederigin-offsetbelrstxyesrspective-originaceholderioghtng-offsettateundedw-xyz-belrstlreseslr-endspantartaturatecepiahizekewpace-taleroll-xyz-barmpbelrstxyesbelrstxyes-thumbrackadowrink-xyxyartrokeabextora-shadowpckingnsformitionlate-xyz-offsetill-changeoom",H1=(()=>{const t=ca.length-1,n=new Int32Array(t);for(let c=t-1;c>=0;c--){let u=1,h=c+1;for(let m=ca[c];mE?F@03263243255B:032523853:0325B:8GA032542HE?3257D>032585:0325B:;0328B:032"),q1=wn("012113445661666666789111:5;;;;;;;;444;;;:62999<1161=62>>?61:21@ABCD4446996:64E:::;:?::64:F114GHHIHHHHIHH1HH1HH1HHHHHH::EEJ4444::EE4444441691;644444114244444:;K6666555555555555555999666664444444444444444444444226?6:66644L9M?D:111::::6DE199"),Q1=Rr("020200202020020020020020020020200200200200200200200002020202001003040106000200200200200200200200200200200200200200200200200200200200200200200200200200200200020020020020020020002020200202002002002002002002002002002020002002020020200220200200200200200200200200200200020020020000200020002000200200200020020020002000200200200020020202002020202000200200020022000200200020020002002000200220002002000200W0Z00020020002002020002002000200g0j0002002000200200020020002002000200200020020002000200002000002002002002002000200020000200002002002002002002002020020020200200200200200200200200202020020020020020020020020002002002020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020002002002002002002000200200200200200200200200200020202020002000200020002002002002000020200200"),K1=(()=>{const t=new Int32Array(319).fill(-1),n=Rr("02422242:222222242224222242442222222422222244442242226224222426222422442462222422622222222626222462242622422622422424242422222222422222222242422222222222222222622442224222222222222224424442262222222222222222222226224222424242422224422422422222"),a=Rr("02222222222222222222202222222222222222222222221422222222222222222222222222222222222Y\\222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222221422222222222222222222222222222222222222Ŀł222222222222222222");for(let o=0;o{const n=t.split(" "),a=n.shift();for(let o=0;oʶ22ʷʺʷ2ʸʷ42ʴ2ʓ22>621422ɶ222ɹɼɷɺɷɺ22ɱ42222ɨ2ɧ26622ɘɓ244ƸƵ222]d24242ǖǓƚÄȫ2263ȨȥȨ2222222ǣ222222222222222222ǂƽ2ƾƵ2222222422222ƜƑ22222222222222222222144Ŧţ22Ţş222222222222222222222ĸ2ı68ĦģĦɡŰ4Ġ«®ĝ822ĔđĔ2ē2222622"),Z1=Rr("02222222222222222222222222222222222222222222222222222222222222222202022222222222EH2200IL021042222Y\\222IL0cf2e10j2222U00X202[^2y0000120|{~‚22…ˆ‡:22|22222222222G000q†OVI00000}š2›>40000ŒB00000I¨©000¬00000000000000021M®­00°“000000000000000000000–222›HGHa1º222¿2À2222ÉÌ000­°2±"),$j=new Int32Array(995),Ij=new Int32Array(995),Mj=new Int32Array(995);let vm="";const jm=new Int32Array(1038);{const t=new Map;let n=0,a=0;for(let o=0;oF@286¦2@H2D266226FB22B2>BD\\6N22222Z222D222p"),eS=kc(wn("1::24444432:442:44:44>222222:44:4421322511111311111114")),tS=Rr("2Š4A;33N=C@H4A;33N=C@<27;83:;8393NQ:3NQʰ222ˉºŴŽ2R2=18cƴÅҜ=cĞÛC1ƈǝȈ:ħ25=11D3A@4=<1;1DEr25;11B3?<6;:371BCn9@7=<8192>2E121@9@EHE@9>2T25511<398454131<=V25511<398454131<=„ƧNž2Đå242L222290000f22500ɛ000ǘ222"),sS=wn("ij"),nS=wn("—"),rS=wn("1"),aS="* ** after backdrop before details-content file first-letter first-line marker placeholder selection";var lS={GROUP_COUNT:O1,customValidatorNames:z1,edgeStart:ca,labelStart:U1,labelText:B1,edgeTarget:H1,nodeGroup:V1,nodeVlist:K1,vlistPat:G1,vlistOps:W1,vlistRef:q1,vlistGroup:Q1,litAnchor:$j,litGroup:Ij,litPool:Mj,poolOffsets:jm,poolText:vm,adjGid:J1,adjStart:eS,adjTgt:tS,patGid:sS,patTgt:nS,postfixLookupGroups:rS,orderSensitiveModifiers:aS};const iS="line"in new Error,pn=-1,ia=-1,Cu=(t,n,a)=>{let o=2166136261;for(let c=n;c{const o=a-n;let c=Math.imul(o,2654435761)^t.charCodeAt(n);if(o>3){const u=o>>2,h=o>>1;c=Math.imul(c^t.charCodeAt(n+1)<<8^t.charCodeAt(n+2)<<16^t.charCodeAt(n+u),2246822507),c=Math.imul(c^t.charCodeAt(n+h)<<8^t.charCodeAt(n+h+u)<<16^t.charCodeAt(a-3),3266489909),c^=t.charCodeAt(a-2)<<8^t.charCodeAt(a-1)<<16;for(let m=n+3,x=a-4;m>>15|0},oS=(t,n,a={})=>{const{GROUP_COUNT:o,edgeStart:c,labelStart:u,labelText:h,edgeTarget:m,nodeGroup:x,nodeVlist:v,vlistPat:N,vlistOps:j,vlistRef:w,vlistGroup:_,litAnchor:S,litGroup:y,litPool:g,poolOffsets:p,poolText:k,adjGid:R,adjStart:C,adjTgt:E,patGid:P,patTgt:F,postfixLookupGroups:I,customValidatorNames:M,orderSensitiveModifiers:$}=t,O=new Int32Array(o).fill(-1);for(let ce=0;ceL&&(L=xe)}let z=32;for(;z<2*(1+L+P.length);)z<<=1;const Y=new Int32Array(w.length+1);for(let ce=0;ceW&&(W=xe);const Ne=k.charCodeAt(p[g[ce]*2]);(Ne===91||Ne===40)&&(se=!1)}let ne=1;for(;ne{let We=(Cu(xe,Ne,Oe)^Math.imul(ce,2654435761)|0)&ne-1;const Ve=Oe-Ne;for(;;){const Ye=q[We];if(Ye===-1)return-1;if(S[Ye]===ce&&p[g[Ye]*2+1]===Ve){const ot=p[g[Ye]*2];let lt=!0;for(let Ue=0;Ue{throw new Error("cn: missing validator "+ce)}),fe=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,re=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Ee=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,nt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;let ct=0,Ut=-1,Yt=-1,Ns=-1,ws=-1;const Sn=ce=>ce>=97&&ce<=122||ce>=65&&ce<=90||ce>=48&&ce<=57||ce===95,$r=ce=>/\s/.test(String.fromCharCode(ce)),Ir=(ce,xe,Ne)=>{if(ct=0,Ut=-1,Ne-xe<3)return;const Oe=ce.charCodeAt(xe),We=ce.charCodeAt(Ne-1);if(Oe===91&&We===93)ct=1;else if(Oe===40&&We===41)ct=2;else return;Ns=xe+1,ws=Ne-1;let Ve=xe+1;if(Sn(ce.charCodeAt(Ve))){for(Ve++;Ve{if(Ne-xe!==Oe.length)return!1;for(let We=0;We!!ce&&!Number.isNaN(Number(ce)),Oi=(ce,xe,Ne)=>{if(Ne-xe<11||!Ss(ce,xe,xe+10,"@container"))return!1;if(ce.charCodeAt(xe+10)===47)return Ne-xe>=12;const Oe=ce.charCodeAt(xe+11);return Oe===115&&Ne-xe>=17&&Ss(ce,xe+10,xe+16,"-size/")||Oe===110&&Ne-xe>=19&&Ss(ce,xe+10,xe+18,"-normal/")},zi=[1,1,1,1,1,1,1,1,2,2,2,2,2,2,2],Ui="length|number|number weight|family-name|position percentage|length size bg-size|image url|shadow|length|family-name|position percentage|length size bg-size|image url|shadow|number weight".split("|").map(ce=>ce.split(" ")),wl=[2,3,1,0,0,0,4,5,0,0,0,0,0,1,1],_a=(ce,xe,Ne,Oe)=>{if(ce>=10){if(ce>=25)return Z[ce-25](xe.slice(Ne,Oe));const We=ce-10;if(ct!==zi[We])return!1;if(Ut>=0){for(const Ve of Ui[We])if(Ss(xe,Ut,Yt,Ve))return!0;return!1}switch(wl[We]){case 0:return!1;case 1:return!0;case 2:{const Ve=xe.slice(Ns,ws);return fe.test(Ve)&&!re.test(Ve)}case 3:return ya(xe.slice(Ns,ws));case 4:return nt.test(xe.slice(Ns,ws));default:return Ee.test(xe.slice(Ns,ws))}}switch(ce){case 0:return!0;case 1:return ct===0;case 2:return ct===1;case 3:return ct===2;case 4:return tn.test(xe.slice(Ne,Oe));case 5:return ya(xe.slice(Ne,Oe));case 6:{const We=xe.slice(Ne,Oe);return!!We&&Number.isInteger(Number(We))}case 7:return Oe>Ne&&xe.charCodeAt(Oe-1)===37&&ya(xe.slice(Ne,Oe-1));case 8:return sn.test(xe.slice(Ne,Oe));default:return Oi(xe,Ne,Oe)}},Bi=new Set(typeof $=="string"?$.split(" "):$),Yn=(ce,xe,Ne,Oe,We,Ve)=>{const Ye=Cu(xe,Ne,Oe)^(We?2654435769:0)|0;let ot=ce.get(Ye);if(ot!==void 0)e:for(let Re=0;Re{const Ne=[];let Oe=0,We=0,Ve=0;for(let Ue=0;Ue1){const Ue=[];let Re=[];for(const Je of Ne)Je.charCodeAt(0)===91||Bi.has(Je)?(Re.length&&(Ue.push(...Re.sort()),Re=[]),Ue.push(Je)):Re.push(Je);Re.length&&Ue.push(...Re.sort()),Ye=Ue.join(":")}const ot=xe?Ye+" !":Ye;let lt=Sl.get(ot);return lt===void 0&&Sl.set(ot,lt=Mr++),lt};let ba=new Map,Zn=o;const kl=o+4096,El=()=>Zn++,Na=2097152,Cs=8192,nn=new Int32Array(Cs),ks=new Array(Cs).fill(null),Al=new Int32Array(Cs),Rl=new Int32Array(Cs),Pl=new Uint8Array(Cs);let Tl=0;const wa=(ce,xe,Ne,Oe,We,Ve,Ye,ot)=>{let lt=ce;if(ks[ce]!==null)if(ks[ce|1]===null)lt=ce|1;else if((Tl++&3)===0)lt=ce|Tl>>2&1;else return;ks[lt]=xe.slice(Ne,Oe),nn[lt]=We,Al[lt]=Ve,Rl[lt]=Ye,Pl[lt]=ot},Ll=()=>ks.fill(null);let $t=256,Jn=[new Int32Array($t),new Int32Array($t),new Int32Array($t),new Int32Array($t)],[Es,er,As,kn]=Jn,rn=new Uint8Array($t),an=new Uint8Array($t);const Fc=()=>{$t*=2,Jn=Jn.map(xe=>{const Ne=new Int32Array($t);return Ne.set(xe),Ne}),[Es,er,As,kn]=Jn;const ce=new Uint8Array($t);ce.set(rn),rn=ce,an=new Uint8Array($t)};let tr=64,Or=new Int32Array(tr),us=new Int32Array(tr);const Sa=new Int32Array(o);let Vs=2048,Hi=21,Ca=new Float64Array(Vs),zr=new Int32Array(Vs),Gs=0;const ka=(ce,xe)=>{if(ce===0&&xe>>Hi;for(;zr[Oe]===Gs;){if(Ca[Oe]===Ne)return 1;Oe=Oe+1&Vs-1}return Ca[Oe]=Ne,zr[Oe]=Gs,0},Ea=(ce,xe,Ne,Oe,We)=>{if(Ne-xe>=2&&ce.charCodeAt(xe)===91&&ce.charCodeAt(Ne-1)===93){let Ve=-1;for(let Ye=xe+1;Ye=0&&x[Oe]>=0)return x[Oe];for(let Ve=We-1;Ve>=0;Ve--){const Ye=us[Ve];if(Ye>Ne)continue;const ot=Or[Ve],lt=Ne-Ye;if(ae[ot]===1&<>0&<<=W){const jt=ce.charCodeAt(Ye);if(se===!1||jt!==91&&jt!==40){const qs=J(ot,ce,Ye,Ne);if(qs>=0)return qs}}const Ue=v[ot];if(Ue<0)continue;const Re=w[Ue],Je=N[Re],gt=N[Re+1];if(Je===gt)continue;Ir(ce,Ye,Ne);const bt=Y[Ue]-Je;for(let jt=Je;jt{const xe=ce.length;let Ne=0,Oe=0,We=!1;(Mr>Cl||Cn.size>Cl)&&(Cn=new Map,Sl=new Map,Mr=2,Ll()),Zn>kl&&(ba=new Map,Zn=o,Ll());let Ve=0;for(;Ve=9&&Ue<=13||Ue>=160&&$r(Ue)){Ue!==32&&(We=!0),Ve++;continue}const Re=Ve;let Je=0;for(;Ve=9&&Ue<=13){We=!0;break}}else if(Ue>=160&&$r(Ue)){We=!0;break}Je=Math.imul(Je^Ue,16777619),Ve++}const gt=Ve,bt=gt-Re;Ne===$t&&Fc();const jt=Ne++;Es[jt]=Re,er[jt]=gt,Oe+=bt,Je^=Math.imul(bt,2654435761);const qs=Je^Je>>>15|0,ms=qs&8190;{let rt=-1;if(nn[ms]===qs&&ks[ms]!==null&&ks[ms].length===bt?rt=ms:nn[ms|1]===qs&&ks[ms|1]!==null&&ks[ms|1].length===bt&&(rt=ms|1),rt>=0){const ts=ks[rt];let Et=!0;for(let ps=0;ps=on?Jt+1:on;let kt=ar,yt=gt,Br=!1,Dl=0;yt>kt&&ce.charCodeAt(yt-1)===33?(Br=!0,yt--):yt>kt&&ce.charCodeAt(kt)===33&&(Br=!0,kt++,Dl=1);let hs=-1;Ps>ar&&(hs=Ps+Dl,hs>=yt&&(hs=-1));let $l=kt;yt-kt>1&&ce.charCodeAt(kt)===45&&($l=kt+1);let fs=0,xs=0,An=0,Gi=-1,Bt=0;(v[0]>=0||ae[0]===1)&&(Or[0]=0,us[0]=$l,Bt=1);let Rn=ia,cn=0;for(let rt=$l;rt=0&&(v[Et]>=0||ae[Et]===1)&&rt+1=0)if(Pa=!0,es=Ea(ce,kt,hs,Rn,cn),es!==pn&&es=Jt?Br?1:0:Yn(Cn,ce,on,Jt,Br?1:0,rt=>Lc(rt,Br)),As[jt]=es,rn[jt]=ir,kn[jt]=Hr),wa(ms,ce,Re,gt,qs,es,Hr,ir)}if(Ne===0)return"";if(Ne===1)return Es[0]===0&&er[0]===xe?ce:ce.slice(Es[0],er[0]);if(Ne*z>Vs){for(;Ne*z>Vs;)Vs<<=1,Hi--;Ca=new Float64Array(Vs),zr=new Int32Array(Vs)}if(Mr>=Na||Zn>=Na)throw new Error("cn: too many distinct classes in one merge");Gs=Gs+1|0,Gs===0&&(Sa.fill(0),zr.fill(0),Gs=1);let Ye=!1;for(let Ue=Ne-1;Ue>=0;Ue--){const Re=As[Ue];if(Re===pn){an[Ue]=1;continue}const Je=kn[Ue];if(ka(Je,Re)===1){an[Ue]=0,Ye=!0;continue}if(an[Ue]=1,Re=0)for(let bt=C[gt];bt0&&(ot+=" "),ot+=ce.slice(Ue,Re),lt=Je}return ot},at=16384,Ws=new Int32Array(at*2);let sr=0,Zt=1,ln=Object.create(null),Vi=Object.create(null),En=new Map,Ur=new Map,qt=0,Ra=0;const It=()=>{sr^=at,Zt=Zt+1|0,Ra=0},Dc=ce=>{let xe=ln[ce];if(xe!==void 0)return xe;const Ne=lc(ce,0,ce.length),Oe=(Ne&16383)+sr,We=Ws[Oe]===(Ne^Zt)||Ws[Oe^at]===(Ne^Zt-1);return We&&(xe=Vi[ce],xe!==void 0)?(ln[ce]=xe,xe):(xe=Aa(ce),We?(ln[ce]=xe,++qt>le&&(qt=0,Vi=ln,ln=Object.create(null),It())):(Ws[Oe]=Ne^Zt,++Ra>at&&It()),xe)},$c=ce=>{let xe=En.get(ce);if(xe!==void 0)return xe;const Ne=lc(ce,0,ce.length),Oe=(Ne&16383)+sr,We=Ws[Oe]===(Ne^Zt)||Ws[Oe^at]===(Ne^Zt-1);return We&&(xe=Ur.get(ce),xe!==void 0)?(En.set(ce,xe),xe):(xe=Aa(ce),We?(En.set(ce,xe),++qt>le&&(qt=0,Ur=En,En=new Map,It())):(Ws[Oe]=Ne^Zt,++Ra>at&&It()),xe)},Ic=ce=>{const xe=lc(ce,0,ce.length),Ne=(xe&16383)+sr;return Ws[Ne]===(xe^Zt)||Ws[Ne^at]===(xe^Zt-1)?!0:(Ws[Ne]=xe^Zt,++Ra>at&&It(),!1)},nr=le===0?Aa:iS?ce=>{const xe=En.get(ce);return xe!==void 0?xe:$c(ce)}:Dc;return{merge:function(){return arguments.length===1&&typeof arguments[0]=="string"?nr(arguments[0]):nr(dS.apply(null,arguments))},mergeString:nr,seenBefore:le===0?()=>!1:Ic,mergeUncached:Aa}},hc=(t,n)=>{if(!t)return"";if(typeof t=="string")return t;let a="";if(typeof t.length=="number"&&(!n||Array.isArray(t))){const o=t;for(let c=0;c{let a="";for(let o=0;o{const a=n===void 0?()=>!0:n.seenBefore,o=n===void 0?t:n.mergeUncached;let c=new Map,u=new Map,h=0,m=null,x=null,v=[],N=[],j=0;const w=(p,k,R)=>{x===null&&(x=new Array(ku).fill(""),v=new Array(ku).fill(""),N=new Array(ku).fill(""));const C=lc(p,0,p.length)&4094;if(x[C]===p&&v[C]===k)return N[C];if(x[C|1]===p&&v[C|1]===k)return N[C|1];const E=t(R?k+" "+p:p),P=x[C]===""?C:C|(x[C|1]===""?1:j++&1);return x[P]=p,v[P]=k,N[P]=E,E},_=(p,k,R,C)=>{let E=0;if(k){if(k!==p.a0)return!1;E=1}if(R){if(R!==(E===0?p.a0:p.a1))return!1;E++}if(C){if(C!==(E===0?p.a0:E===1?p.a1:p.a2))return!1;E++}return E===p.t},S=(p,k)=>{const R=p.a;let C=0;for(let E=0;E{const R=p.length,C=m===null?null:m.n;if(!k){if(C!==null&&S(C,p))return m=C,C.r;if(m!==null&&m!==C&&S(m,p))return m.r}let E="",P=-1,F=0,I=!1;for(let O=0;O0){M.skip--,m=null;let L=E;for(let z=P+1;zrp&&(M.miss=rp,M.skip=mS,M.e.length=0,M.at=0);const z=M.e;z.length1e3&&(h=0,u=c,c=new Map)}return m!==null&&m!==$&&(m.n=$),m=$,$.r},g=p=>Array.isArray(p)?y(p.slice(),!1):t(hc(p,!0));return function(p,k,R){const C=arguments.length;if((C|1)===3){const F=m;if(F!==null){const I=F.n;if(I!==null&&_(I,p,k,R))return m=I,I.r;if(F!==I&&_(F,p,k,R))return F.r}if(C===2&&typeof k=="string"&&k!==""){const I=c.get(p);if(I!==void 0&&I.skip>0)return I.skip--,m=null,w(k,p,!0)}return y([p,k,R],!0)}if(C===1)return typeof p=="string"?t(p):g(p);const E=m;if(E!==null){const F=E.n;if(F!==null){const I=F.a;let M=0,$=!0;for(let O=0;Osvg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function K({className:t,variant:n="default",size:a="default",asChild:o=!1,...c}){const u=o?jv:"button";return e.jsx(u,{"data-slot":"button","data-variant":n,"data-size":a,className:gv(fS({variant:n,size:a,className:t})),...c})}function xS({identity:t}){const[n,a]=i.useState(!1),[o,c]=i.useState(!1),[u,h]=i.useState(null),[m,x]=i.useState(""),[v,N]=i.useState(!1),[j,w]=i.useState(""),[_,S]=i.useState(()=>Date.now()),y=o?"error":n?u!==null&&u.totalRows===0?"empty":"ok":"loading",g=i.useCallback(async()=>wb(),[]),p=i.useCallback(F=>{h(F),a(!0),c(!1)},[]),k=i.useCallback(F=>{x(F instanceof Error?F.message:"Unknown error"),c(!0),a(!1)},[]);i.useEffect(()=>{let F=!0;return g().then(I=>{F&&p(I)},I=>{F&&k(I)}),()=>{F=!1}},[g,p,k]);const R=i.useCallback(()=>(a(!1),c(!1),g().then(p,k)),[g,p,k]);i.useEffect(()=>{const F=setInterval(()=>S(Date.now()),3e4);return()=>clearInterval(F)},[]);const C=i.useCallback(async()=>{N(!0);try{await Cb(),await R()}catch(F){x(F instanceof Error?F.message:"Trigger failed"),c(!0)}finally{N(!1)}},[R]),E=async()=>{if(u)try{const F=await Vb(t,u.window.cycle,{decision:"PROCEED",justification:`all ${u.window.total} sources complete for ${u.window.cycle} (recorded from the console)`});w(`recorded PROCEED for ${u.window.cycle} (audit entry ${F.sequence})`),await R()}catch(F){w(F instanceof Error?F.message:"the decision was refused")}},P=u?{green:u.sources.filter(F=>F.status==="green").length,amber:u.sources.filter(F=>F.status==="amber").length,red:u.sources.filter(F=>F.status==="red").length}:null;return e.jsxs("div",{children:[e.jsx(Se,{title:"Ingestion Health",description:"Multi-source trade-data pipeline · reporter Algeria (12) · quarterly cadence",actions:e.jsx(K,{size:"sm",onClick:C,disabled:v,children:v?"Running…":"Run quarterly pull"})}),e.jsx(M1,{}),y==="ok"&&u&&u.platform_outage&&e.jsxs("div",{role:"alert",className:"mt-4 rounded-lg border border-destructive/50 bg-destructive/10 px-3.5 py-2.5 font-semibold text-destructive",children:["Platform-wide outage — every source is failing. One incident, not ",u.sourcesTotal,"; the retry ladder runs per source below."]}),y==="loading"&&e.jsx(H,{children:"Loading ingestion health…"}),y==="error"&&e.jsxs(H,{tone:"error",children:["Could not load ingestion health: ",m,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void R(),children:"Retry"})})]}),y==="empty"&&e.jsxs(H,{children:["No data ingested for ",e.jsx("strong",{children:u==null?void 0:u.period})," yet. Trigger a quarterly pull to populate the raw data lake."]}),y==="ok"&&u&&P&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"my-4 flex flex-wrap gap-3",children:[e.jsx(B,{className:"min-w-[150px] flex-[1_1_150px] p-4",children:e.jsx(ue,{label:"Period",value:u.period})}),e.jsx(B,{className:"min-w-[150px] flex-[1_1_150px] p-4",children:e.jsx(ue,{label:"Connectors up",value:`${u.sourcesOperational}/${u.sourcesTotal}`})}),e.jsx(B,{className:"min-w-[150px] flex-[1_1_150px] p-4",children:e.jsx(ue,{label:"Rows ingested",value:u.totalRows.toLocaleString()})}),e.jsx(B,{className:"min-w-[150px] flex-[1_1_150px] p-4",children:e.jsx(ue,{label:"Conflicts flagged",value:String(u.conflictCount)})}),e.jsx(B,{className:"min-w-[150px] flex-[1_1_150px] p-4",children:e.jsx(ue,{label:"Quarterly SLA (<4h)",value:u.slaMet?"Met":"Breached",tone:u.slaMet?"ok":"error"})}),e.jsx(B,{className:"min-w-[150px] flex-[1_1_150px] p-4",children:e.jsx(ue,{label:"RAG (green/amber/red)",value:`${P.green} / ${P.amber} / ${P.red}`,tone:P.red>0?"error":P.amber>0?void 0:"ok"})})]}),e.jsx(gS,{window:u.window,now:_,onProceed:()=>void E(),canDecide:pS(t)}),j&&e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:j}),e.jsx(B,{className:"overflow-hidden py-0",children:e.jsx(n1,{sources:u.sources})})]})]})}function pS(t){return t.role==="chief_economist"||t.role==="head_of_industrial_intelligence"||t.role==="platform_admin"}function gS({window:t,now:n,onProceed:a,canDecide:o}){const c=Math.max(0,(new Date(t.deadline).getTime()-n)/36e5),u=t.sources_done>=t.total,h=t.total===0?0:Math.round(t.sources_done/t.total*100);return e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-3",children:[e.jsxs("h2",{className:"text-sm font-semibold",children:["72-hour refresh window — ",t.cycle]}),e.jsx("span",{className:c<=0?"text-sm font-semibold text-destructive":"text-sm font-semibold text-foreground",children:c<=0?"window expired":`${c.toFixed(1)} h remaining`}),e.jsx("span",{className:"grow"}),u&&!t.decision&&o&&e.jsx(K,{type:"button",size:"sm",onClick:a,children:"Proceed to quality checks"})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("span",{className:"h-2 flex-1 overflow-hidden rounded bg-muted",children:e.jsx("span",{className:u?"block h-2 bg-success":"block h-2 bg-warning",style:{width:`${h}%`}})}),e.jsxs("span",{className:"text-xs tabular-nums text-muted-foreground",children:[t.sources_done,"/",t.total," sources complete"]})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Opened ",t.opened_at.slice(0,16).replace("T"," ")," · deadline ",t.deadline.slice(0,16).replace("T"," ")," · ","decision:"," ",t.decision?e.jsx("strong",{children:t.decision.decision}):e.jsx("em",{children:"none recorded"}),t.decision&&e.jsxs(e.Fragment,{children:[" by ",t.decision.by," at ",t.decision.at.slice(0,16).replace("T"," ")," (audited)"]})]})]})})}function je({className:t,...n}){return e.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:e.jsx("table",{"data-slot":"table",className:ft("w-full caption-bottom text-sm",t),...n})})}function _e({className:t,...n}){return e.jsx("thead",{"data-slot":"table-header",className:ft("[&_tr]:border-b",t),...n})}function ye({className:t,...n}){return e.jsx("tbody",{"data-slot":"table-body",className:ft("[&_tr:last-child]:border-0",t),...n})}function ee({className:t,...n}){return e.jsx("tr",{"data-slot":"table-row",className:ft("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",t),...n})}function T({className:t,...n}){return e.jsx("th",{"data-slot":"table-head",className:ft("h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...n})}function A({className:t,...n}){return e.jsx("td",{"data-slot":"table-cell",className:ft("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...n})}function vS(){const[t,n]=i.useState("loading"),[a,o]=i.useState(null),[c,u]=i.useState("");return i.useEffect(()=>{Sb().then(h=>{o(h),n("ok")}).catch(h=>{u(h instanceof Error?h.message:"Unknown error"),n("error")})},[]),t==="loading"?e.jsx(H,{children:"Loading connector manifests…"}):t==="error"?e.jsxs(H,{tone:"error",children:["Could not load connectors: ",c]}):a?e.jsxs("div",{children:[e.jsx(Se,{title:"Connector Manifests",description:"Nine sources · lower tier wins on conflict (DGD/ALCES → UN Comtrade → partner mirrors → aggregators → macro).",meta:e.jsxs(e.Fragment,{children:["classification ",a.classification," · mode ",a.live?"live":"fixture (sandbox)"]})}),e.jsx(B,{className:"mt-4 overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Tier"}),e.jsx(T,{children:"Source"}),e.jsx(T,{children:"Kind"}),e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Endpoint / license"})]})}),e.jsx(ye,{children:a.connectors.map(h=>e.jsxs(ee,{children:[e.jsxs(A,{children:["T",h.tier]}),e.jsx(A,{className:"font-semibold",children:h.name}),e.jsx(A,{children:h.kind}),e.jsx(A,{children:h.providesHs6?"yes":"macro"}),e.jsxs(A,{children:[e.jsx("div",{className:"font-mono text-xs",children:h.endpoint}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.license})]})]},h.id))})]})})]}):e.jsx(H,{children:"No connectors configured."})}function Oj(t){return{"x-subscriber-tier":t}}function jS(t,n){return he(`/dictionary/cycles/${encodeURIComponent(t)}/summary`,Oj(n))}function yS(t,n){return he(`/dictionary/cycles/${encodeURIComponent(t)}/lines`,Oj(n))}function _S(t){return he(`/tda10-lines/daps-coverage?cycle=${encodeURIComponent(t)}`)}function bS(){return he("/schema-changelog")}function NS(t){return be(`/dictionary/cycles/${encodeURIComponent(t)}/build`)}const wS={HIGH:"success",MEDIUM:"warning",LOW:"danger",NO_DATA:"secondary"};function SS({tier:t}){return e.jsx(V,{variant:wS[t],className:"whitespace-nowrap",children:t.replace("_"," ")})}const CS={ok:"text-success",warn:"text-warning",error:"text-destructive"};function ze({label:t,value:n,tone:a,hint:o,className:c}){return e.jsxs("div",{className:ft("min-w-[150px] flex-[1_1_150px] rounded-lg border bg-card px-4 py-3",c),children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:t}),e.jsx("div",{className:ft("mt-1 text-[22px] leading-tight font-semibold",a&&CS[a]),children:n}),o?e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:o}):null]})}function Ci({icon:t,title:n,hint:a,action:o,className:c}){return e.jsxs("div",{className:ft("flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed px-6 py-12 text-center",c),children:[t?e.jsx(t,{size:20,className:"text-muted-foreground/70","aria-hidden":!0}):null,e.jsx("p",{className:"text-sm font-medium",children:n}),a?e.jsx("p",{className:"max-w-sm text-xs text-muted-foreground",children:a}):null,o?e.jsx("div",{className:"mt-2",children:o}):null]})}function Ie({className:t,children:n,...a}){return e.jsxs("div",{className:ft("relative",t),children:[e.jsx("select",{"data-slot":"native-select",className:ft("h-9 w-full appearance-none rounded-md border border-input bg-transparent px-3 pr-8 text-sm text-foreground transition-[color,box-shadow] outline-none","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50","dark:bg-input/30"),...a,children:n}),e.jsx(Sg,{size:14,"aria-hidden":!0,className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground"})]})}const nl="2025-Q1";function kS(){const[t,n]=i.useState("1"),[a,o]=i.useState(null),[c,u]=i.useState([]),[h,m]=i.useState(null),[x,v]=i.useState(null),[N,j]=i.useState(null),[w,_]=i.useState(""),[S,y]=i.useState(!1),[g,p]=i.useState(null),[k,R]=i.useState(null),C=k===t?"error":g!==t?"loading":a!==null&&(a.run_status==="not_built"||c.length===0)?"empty":"ok",E=i.useCallback(async()=>{const[$,O,L,z]=await Promise.all([jS(nl,t),yS(nl,t),_S(nl),bS()]);return{s:$,lines:O.lines,d:L,sc:z}},[t]),P=i.useCallback($=>{o($.s),u($.lines),m($.d),v($.sc),p(t),R(null)},[t]),F=i.useCallback($=>{_($ instanceof Error?$.message:"Unknown error"),R(t),p(null)},[t]),I=i.useCallback(()=>(p(null),R(null),E().then(P,F)),[E,P,F]);i.useEffect(()=>{let $=!0;return E().then(O=>{$&&P(O)},O=>{$&&F(O)}),()=>{$=!1}},[E,P,F]);const M=i.useCallback(async()=>{y(!0);try{await NS(nl),await I()}catch($){_($ instanceof Error?$.message:"Build failed"),R(t),p(null)}finally{y(!1)}},[t,I]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Canonical Product Dictionary",description:"HS6 authoritative values · TDA-10 DAPS crosswalk",meta:e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"cycle"}),e.jsx("span",{className:"font-mono",children:nl}),e.jsx("span",{children:a?`schema ${a.schema_version}`:null})]}),actions:e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:["Subscriber tier",e.jsxs(Ie,{value:t,onChange:$=>n($.target.value),"aria-label":"Subscriber tier",className:"w-28",children:[e.jsx("option",{value:"1",children:"Tier 1"}),e.jsx("option",{value:"2",children:"Tier 2"}),e.jsx("option",{value:"3",children:"Tier 3"}),e.jsx("option",{value:"admin",children:"Admin"})]})]}),e.jsx(K,{size:"sm",onClick:M,disabled:S,children:S?"Building…":"Build cycle"})]})}),C==="loading"&&e.jsx(H,{children:"Loading canonical dictionary…"}),C==="error"&&e.jsxs(H,{tone:"error",children:["Could not load the dictionary: ",w,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void I(),children:"Retry"})})]}),C==="empty"&&e.jsx(Ci,{icon:Rm,title:`No canonical dictionary built for ${nl}`,hint:"Build the cycle to reconcile the ingested sources into the authoritative HS6 layer.",action:e.jsx(K,{size:"sm",onClick:M,disabled:S,children:S?"Building…":"Build cycle"})}),C==="ok"&&a&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"my-4 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"Whitelist codes",value:String(a.total_whitelist_codes)}),e.jsx(ze,{label:"With data",value:String(a.codes_with_data),tone:"ok"}),e.jsx(ze,{label:"Zero-trade",value:String(a.codes_zero_trade)}),e.jsx(ze,{label:"No data",value:String(a.codes_no_data),tone:a.codes_no_data>0?"warn":"ok"}),e.jsx(ze,{label:"Coverage",value:`${Math.round(a.coverage_pct*100)}%`}),e.jsx(ze,{label:"Conflicts",value:String(a.conflict_count),tone:a.conflict_count>0?"warn":"ok"}),e.jsx(ze,{label:"Schema",value:a.schema_version})]}),h&&e.jsx(B,{className:"mb-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"DAPS TDA-10 crosswalk"}),e.jsxs("div",{className:"flex flex-wrap gap-6 text-sm",children:[e.jsx(ue,{label:"Active lines",value:`${h.active_daps10_count} / ${h.expected_daps10_count} expected`}),e.jsx(ue,{label:"Count status",value:h.count_status,tone:h.count_status==="OK"?"ok":"error"}),e.jsx(ue,{label:"Crosswalk coverage",value:`${h.crosswalk_coverage_pct}%`}),e.jsx(ue,{label:"Coverage floor",value:h.coverage_status,tone:h.coverage_status==="OK"?"ok":"error"})]})]})}),e.jsxs("h2",{className:"mb-3 mt-4 text-base font-semibold",children:["Reconciled lines (",c.length,")"]}),e.jsx(B,{className:"overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Description"}),e.jsx(T,{className:"text-right",children:"Value (USD)"}),e.jsx(T,{children:"Confidence"}),e.jsx(T,{children:"Winning source"}),e.jsx(T,{className:"text-right",children:"Conflict Δ"}),e.jsx(T,{children:"Rule"})]})}),e.jsx(ye,{children:c.map($=>e.jsxs(ee,{onClick:()=>j($),className:"cursor-pointer",children:[e.jsx(A,{className:"font-mono text-xs",children:$.hs6_code}),e.jsx(A,{children:$.product_description_en}),e.jsx(A,{className:"text-right tabular-nums",children:AS($)}),e.jsx(A,{children:e.jsx(SS,{tier:$.confidence_tier})}),e.jsx(A,{children:$.winning_source??"—"}),e.jsxs(A,{className:$.analyst_review_triggered?"text-right tabular-nums text-destructive":"text-right tabular-nums",children:[$.conflict_delta_usd===null?"—":`$${$.conflict_delta_usd.toLocaleString("en-US")}`,$.analyst_review_triggered?" ⚑":""]}),e.jsx(A,{className:"text-xs text-muted-foreground",children:$.resolution_rule})]},$.hs6_code))})]})}),N&&e.jsx(ES,{line:N,onClose:()=>j(null)}),x&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:["Schema changelog · active ",x.active_version]}),e.jsx("ul",{className:"list-disc pl-5 text-sm text-muted-foreground",children:x.entries.map($=>e.jsxs("li",{children:[e.jsx("strong",{children:$.backward_compatibility_rating})," · ",$.affected_table,$.affected_column?`.${$.affected_column}`:""," — ",$.change_description]},$.migration_id))})]})})]})]})}function ES({line:t,onClose:n}){return e.jsxs(B,{className:"mt-4 gap-3 border-2 border-foreground p-4",children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsxs("h2",{className:"text-base font-semibold",children:[t.hs6_code," · ",t.product_description_en]}),e.jsx(K,{size:"xs",onClick:n,children:"Close"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsx(ue,{label:"Français",value:t.product_description_fr}),e.jsx(ue,{label:"العربية",value:t.product_description_ar}),e.jsx(ue,{label:"Confidence score",value:t.confidence_score.toFixed(2)}),e.jsx(ue,{label:"Vintage",value:t.vintage_date??"—"}),e.jsx(ue,{label:"Zero-trade",value:t.zero_trade_flag?"yes":"no"}),e.jsx(ue,{label:"No-data",value:t.no_data_flag?"yes":"no"})]}),t.data_absence_reason&&e.jsx("p",{className:"text-sm text-warning",children:t.data_absence_reason}),e.jsx("h3",{className:"text-sm font-semibold",children:"Source precedence chain"}),t.source_precedence_chain.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No competing sources visible at this subscriber tier."}):e.jsx(je,{children:e.jsx(ye,{children:t.source_precedence_chain.map(a=>e.jsxs(ee,{children:[e.jsxs(A,{className:a.source===t.winning_source?"font-bold":void 0,children:[a.source," (tier ",a.source_tier,")"]}),e.jsx(A,{className:"text-right tabular-nums",children:a.value_usd===null?"—":`$${a.value_usd.toLocaleString("en-US")}`})]},a.source))})}),!t.conflict_report_available&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Full conflict-log report requires Tier 1 / admin access."})]})}function AS(t){return t.no_data_flag?"no data":t.authoritative_value_usd===null?"—":`$${t.authoritative_value_usd.toLocaleString("en-US")}`}const RS=["AGRO_FOOD","PETROCHEMICALS","PHARMACEUTICALS","ELECTRICAL_EQUIPMENT","STEEL_METALS","CONSTRUCTION_MATERIALS","TEXTILES","MACHINERY"],lp=["LT_2M","2M_10M","10M_50M","50M_200M","GT_200M"],yi={LT_2M:"< $2M","2M_10M":"$2M–$10M","10M_50M":"$10M–$50M","50M_200M":"$50M–$200M",GT_200M:"> $200M"},Jm=t=>({"x-subscriber-tier":t});function PS(t){const n=new URLSearchParams;for(const[o,c]of Object.entries(t))c===void 0||c===""||c===!1||n.set(o,String(c));const a=n.toString();return a?`?${a}`:""}const TS=t=>be("/v1/card-batches",{cycle_id:t,trigger_source:"operator_console"}),LS=()=>he("/v1/card-batches"),FS=(t,n)=>he(`/v1/opportunity-cards${PS(t)}`,Jm(n)),DS=(t,n)=>he(`/v1/opportunity-cards/${encodeURIComponent(t)}`,Jm(n)),$S=(t,n)=>he(`/v1/opportunity-cards/${encodeURIComponent(t)}/document`,Jm(n)),IS=(t,n)=>he(`/v1/opportunity-cards/deltas/${t}${n?"?material_only=true":""}`);function Xe(t){return t===null?"—":`$${t.toLocaleString("en-US")}`}function me({className:t,type:n,...a}){return e.jsx("input",{type:n,"data-slot":"input",className:ft("h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",t),...a})}function MS({onOpen:t}){const[n,a]=i.useState("1"),[o,c]=i.useState({page:1}),[u,h]=i.useState(null),[m,x]=i.useState(""),[v,N]=i.useState(null),[j,w]=i.useState(null),_=`${o.page??1}|${o.sector??""}|${o.capex_bracket_min??""}|${o.capex_bracket_max??""}|${o.wilaya??""}|${o.min_cas_score??""}|${o.include_historical??!1}|${n}`,S=j===_?"error":v===_?u!==null&&u.total_count===0?"empty":"ok":"loading",y=i.useCallback(async()=>FS(o,n),[o,n]),g=i.useCallback(C=>{h(C),N(_),w(null)},[_]),p=i.useCallback(C=>{x(C instanceof Error?C.message:"Unknown error"),w(_),N(null)},[_]);i.useEffect(()=>{let C=!0;return y().then(E=>{C&&g(E)},E=>{C&&p(E)}),()=>{C=!1}},[y,g,p]);const k=i.useCallback(()=>(N(null),w(null),y().then(g,p)),[y,g,p]),R=(C,E)=>c(P=>({...P,[C]:E,page:1}));return e.jsxs("div",{children:[e.jsx(Se,{title:"Opportunity Card Catalog",description:"CAS ≥ 60 investment cards · filter by sector, CAPEX bracket & wilaya",actions:e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:["Subscriber tier",e.jsxs(Ie,{value:n,onChange:C=>a(C.target.value),"aria-label":"Subscriber tier",className:"w-36",children:[e.jsx("option",{value:"1",children:"Tier 1"}),e.jsx("option",{value:"2",children:"Tier 2"}),e.jsx("option",{value:"3",children:"Tier 3 (Advisory)"}),e.jsx("option",{value:"admin",children:"Admin"})]})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(ui,{label:"Sector",children:e.jsxs(Ie,{value:o.sector??"",onChange:C=>R("sector",C.target.value),className:"w-36",children:[e.jsx("option",{value:"",children:"All sectors"}),RS.map(C=>e.jsx("option",{value:C,children:C},C))]})}),e.jsx(ui,{label:"CAPEX min",children:e.jsxs(Ie,{value:o.capex_bracket_min??"",onChange:C=>R("capex_bracket_min",C.target.value),className:"w-32",children:[e.jsx("option",{value:"",children:"Any"}),lp.map(C=>e.jsx("option",{value:C,children:yi[C]},C))]})}),e.jsx(ui,{label:"CAPEX max",children:e.jsxs(Ie,{value:o.capex_bracket_max??"",onChange:C=>R("capex_bracket_max",C.target.value),className:"w-32",children:[e.jsx("option",{value:"",children:"Any"}),lp.map(C=>e.jsx("option",{value:C,children:yi[C]},C))]})}),e.jsx(ui,{label:"Wilaya code",children:e.jsx(me,{value:o.wilaya??"",onChange:C=>R("wilaya",C.target.value),placeholder:"e.g. DZ-23",className:"w-32"})}),e.jsx(ui,{label:"Min CAS",children:e.jsx(me,{value:o.min_cas_score??"",onChange:C=>R("min_cas_score",C.target.value),placeholder:"60",className:"w-20"})}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:o.include_historical??!1,onChange:C=>R("include_historical",C.target.checked),className:"size-4 accent-primary"}),"Include historical"]}),e.jsx(K,{variant:"ghost",size:"sm",onClick:()=>c({page:1}),children:"Clear"})]})}),S==="loading"&&e.jsx(H,{children:"Loading catalog…"}),S==="error"&&e.jsxs(H,{tone:"error",children:["Could not load the catalog: ",m,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void k(),children:"Retry"})})]}),S==="empty"&&e.jsx(Ci,{icon:hb,title:"No cards match these filters",hint:"Trigger a batch on the Batch Pipeline tab, or widen the filters."}),S==="ok"&&u&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mb-2 mt-4 text-sm text-muted-foreground",children:[e.jsx("strong",{className:"font-semibold text-foreground",children:u.total_count})," result",u.total_count===1?"":"s"," · cycle ",u.cycle_id??"—"," · page ",u.page,"/",u.total_pages]}),e.jsx(B,{className:"overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Product"}),e.jsx(T,{children:"Sector"}),e.jsx(T,{className:"text-right",children:"CAS"}),e.jsx(T,{children:"CAPEX"}),e.jsx(T,{children:"Top wilaya"}),e.jsx(T,{className:"text-right",children:"Import (USD)"}),e.jsx(T,{children:"DAPS"})]})}),e.jsx(ye,{children:u.results.map(C=>e.jsxs(ee,{onClick:()=>t(`${C.hs6_code}@${C.cas_cycle_id}`),className:"cursor-pointer",children:[e.jsx(A,{className:"font-mono text-xs",children:C.hs6_code}),e.jsx(A,{children:C.product_name_en}),e.jsx(A,{children:e.jsx(V,{variant:"secondary",children:C.sector})}),e.jsx(A,{className:"text-right font-semibold tabular-nums",children:C.cas_score}),e.jsx(A,{children:yi[C.capex_bracket]}),e.jsxs(A,{children:[C.top_wilaya_name_fr??"—",C.top_wilaya_rank?` (#${C.top_wilaya_rank})`:""]}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(C.import_value_usd)}),e.jsx(A,{children:C.daps_applicable?e.jsx(V,{variant:C.daps_expiry_imminent?"warning":"success",children:C.daps_expiry_imminent?"expiring":"yes"}):e.jsx(V,{variant:"secondary",children:"none"})})]},C.hs6_code+C.cas_cycle_id))})]})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx(K,{variant:"outline",size:"sm",disabled:!u.prev_page,onClick:()=>u.prev_page&&R("page",u.prev_page),children:"← Prev"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Page ",u.page," of ",u.total_pages]}),e.jsx(K,{variant:"outline",size:"sm",disabled:!u.next_page,onClick:()=>u.next_page&&R("page",u.next_page),children:"Next →"})]})]})]})}function ui({label:t,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:[t,n]})}function _i({className:t,...n}){return e.jsx("pre",{"data-slot":"pre",className:ft("max-h-[480px] overflow-auto whitespace-pre-wrap rounded-lg border bg-muted p-3 font-mono text-xs leading-relaxed",t),...n})}const xl="Upgrade to Tier 1 Institutional for full data access.";function da({value:t,locked:n,children:a}){return n&&t==null?e.jsxs("span",{title:xl,"aria-label":xl,className:"whitespace-nowrap text-muted-foreground",children:["🔒 ",e.jsx("span",{className:"text-[11px]",children:"Tier 1"})]}):e.jsx(e.Fragment,{children:a??(t==null?"—":String(t))})}const OS={ONS_SURVEY:"ONS survey",PUBLIC_DISCLOSURE:"Disclosure",AAPI_FILING:"AAPI filing",JO_DECREE:"JO decree",TRADE_INFERENCE:"Trade inference",ANALYST_UPLOAD:"Analyst upload",ANALYST_MANUAL:"Analyst",MEDIA_REPORT:"Media"};function Ec({citation:t}){if(!t)return e.jsx("span",{className:"text-muted-foreground",children:"—"});const n=typeof t=="string"?{source_type:"",source_document_id:t}:t,a=[n.source_document_id,n.page_number?`p. ${n.page_number}`:null,n.temporal_mismatch?`fiscal year ${n.fiscal_period} (not quarterly)`:null,n.publication_date].filter(Boolean).join(" · ");return e.jsxs("span",{title:a,className:"inline-flex items-center gap-1 whitespace-nowrap rounded-md bg-muted px-1.5 py-px text-[11px] text-foreground",children:["📄 ",OS[n.source_type]??(n.source_type||n.source_document_id),n.temporal_mismatch&&e.jsx("span",{className:"text-warning",children:"FY"})]})}const wr="border-b px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",Un="border-b p-2 text-[13px]";function zj({cardId:t,tier:n}){const a=n==="admin"?"1":n,[o,c]=i.useState(null),[u,h]=i.useState(""),[m,x]=i.useState(null),[v,N]=i.useState(null),[j,w]=i.useState(null),_=`${a}:${t}`,S=j===_?"error":v===_?"ok":"loading",y=i.useCallback(()=>I1({tier:a,role:"subscriber",user_id:"console"},t),[t,a]),g=i.useCallback(R=>{c(R),h(""),N(_),w(null)},[_]),p=i.useCallback(R=>{h(R instanceof Error?R.message:"Failed"),w(_),N(null)},[_]);i.useEffect(()=>{let R=!0;return y().then(C=>{R&&g(C)},C=>{R&&p(C)}),()=>{R=!1}},[y,g,p]);const k=a==="3";return e.jsxs("section",{className:"mt-4 rounded-xl border bg-card p-4","aria-label":"Anchor firm proximity",children:[e.jsxs("header",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsx("h2",{className:"mb-3 text-[15px] font-semibold tracking-wide",children:"Anchor Firm Proximity"}),o&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["snapshot ",o.snapshot_id??"—"," · updated ",o.last_updated_timestamp.slice(0,16).replace("T"," ")]})]}),S==="loading"&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading anchor-firm linkage…"}),S==="error"&&e.jsx("div",{className:"text-sm text-destructive",children:u}),S==="ok"&&o&&(!o.available||o.anchor_firm_proximity.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:o.greenfield_message??"No anchor firm linkage identified."}):e.jsxs(e.Fragment,{children:[o.critical_gap_banner&&e.jsxs("div",{role:"alert",className:"mb-3 flex items-center gap-3 rounded-lg border border-warning/40 bg-warning/10 px-3.5 py-2.5",children:[e.jsx("span",{className:"text-[22px]","aria-hidden":!0,children:"🛡️"}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold",children:["CRITICAL GAP — ",o.critical_gap_banner.anchor_firm_name]}),e.jsxs("div",{className:"text-[13px]",children:[e.jsx("span",{className:"font-bold text-destructive",children:o.critical_gap_banner.label})," · ","annual imports ",e.jsx(da,{value:o.critical_gap_banner.import_value_usd,locked:k,children:Xe(o.critical_gap_banner.import_value_usd)})]})]})]}),e.jsxs("div",{className:"mb-2 flex flex-wrap gap-1.5",children:[o.import_exposed_input_badge&&!k&&e.jsx(V,{variant:"warning",children:"Import-Exposed Input"}),o.compliance_51_49_flag&&e.jsx(V,{variant:"secondary",children:"51/49 rule applies to JV structures"}),o.requires_analyst_rereview&&e.jsx(V,{variant:"danger",children:"Re-review required (severity moved ≥ 5)"})]}),e.jsxs("table",{className:"w-full text-[13px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-muted-foreground",children:[e.jsx("th",{className:wr,children:"Rank"}),e.jsx("th",{className:wr,children:"Anchor"}),e.jsx("th",{className:wr,children:"Sector"}),e.jsx("th",{className:wr,children:"Proximity"}),e.jsx("th",{className:wr,children:o.labels.gap_severity.en??"Gap severity"}),e.jsx("th",{className:wr,children:"Annual demand"}),e.jsx("th",{className:wr,children:"DAPS"}),e.jsx("th",{className:wr,children:"Source"})]})}),e.jsx("tbody",{children:o.anchor_firm_proximity.map(R=>e.jsxs(i.Fragment,{children:[e.jsxs("tr",{onClick:()=>x(m===R.anchor_firm_id?null:R.anchor_firm_id),className:"cursor-pointer border-t",children:[e.jsx("td",{className:Un,children:R.rank}),e.jsxs("td",{className:Un,children:[e.jsx("div",{className:"font-semibold",children:R.anchor_firm_name.fr}),e.jsx("div",{dir:"rtl",className:"text-xs text-muted-foreground",children:R.anchor_firm_name.ar})]}),e.jsx("td",{className:Un,children:R.sector}),e.jsx("td",{className:`${Un} tabular-nums`,children:R.proximity_score.toFixed(2)}),e.jsx("td",{className:Un,children:e.jsx(V,{variant:R.gap_severity_score>=80?"danger":R.gap_severity_score>=50?"warning":"secondary",children:R.gap_severity_score.toFixed(0)})}),e.jsx("td",{className:Un,children:R.estimated_annual_demand_volume===null?"—":`${R.estimated_annual_demand_volume.toLocaleString("en-US")} ${R.demand_unit??""}`}),e.jsx("td",{className:Un,children:o.daps_protection?`${o.daps_protection.duty_rate_pct}%`:"—"}),e.jsx("td",{className:Un,children:e.jsx(Ec,{citation:R.source_citation})})]}),m===R.anchor_firm_id&&e.jsx("tr",{children:e.jsxs("td",{colSpan:8,className:`${Un} bg-muted/50 text-xs`,children:["Supply path: ",R.relationship_type==="SUPPLIES_INPUT"?`this line is an imported input of ${R.anchor_firm_name.en}`:`${R.anchor_firm_name.en} buys this line's output`," · ",R.current_local_supplier_count??0," domestic supplier(s)"," · ","imports ",e.jsx(da,{value:R.import_value_usd,locked:k,children:Xe(R.import_value_usd)}),R.capex_bracket_estimate&&e.jsxs(e.Fragment,{children:[" · CAPEX bracket ",R.capex_bracket_estimate]})]})})]},R.anchor_firm_id))})]}),o.daps_protection&&e.jsxs("p",{className:"m-0 mt-2 text-xs text-muted-foreground",children:[o.labels.daps.en??"DAPS",": ",o.daps_protection.duty_rate_pct,"% (",o.daps_protection.daps_protection_level,") — ",o.daps_protection.jo_citation??"citation pending"]}),(o.notes??[]).map(R=>e.jsxs("p",{className:"m-0 mt-1 text-xs text-muted-foreground",children:["ℹ ",R]},R)),k&&e.jsxs("p",{className:"m-0 mt-2 text-xs text-muted-foreground",children:["🔒 ",o.tier_restriction_message??xl]})]}))]})}function zS(t){const n=new Map(t.map(o=>[o.id,{node:o,children:[]}])),a=[];for(const o of n.values()){let c=!1;for(const u of o.node.derivedFrom??[]){const h=n.get(u);h&&(h.children.push(o),c=!0)}c||a.push(o)}return a}const ip=150;function US({nodes:t}){const n=i.useMemo(()=>zS(t),[t]),[a,o]=i.useState(t.length<=ip);return t.length===0?e.jsx("p",{className:"text-[13px] text-muted-foreground",children:"No lineage records for this selection."}):e.jsxs("div",{children:[t.length>ip&&e.jsx(K,{type:"button",variant:"outline",size:"xs","aria-expanded":a,onClick:()=>o(c=>!c),className:"mb-2",children:a?"Collapse lineage":`Show lineage (${t.length} records)`}),a&&e.jsx("ul",{className:"m-0 list-none p-0 text-[13px]",children:n.map(c=>e.jsx(Uj,{tree:c,depth:0},c.node.id))})]})}function Uj({tree:t,depth:n}){const[a,o]=i.useState(n<2),c=t.node;return e.jsxs("li",{className:n===0?"ml-0 pl-0":"ml-1 border-l pl-4",children:[e.jsxs("div",{className:"flex items-baseline gap-1.5 py-px",children:[t.children.length>0&&e.jsx("button",{type:"button","aria-expanded":a,"aria-label":`${a?"Collapse":"Expand"} ${c.label??c.id}`,onClick:()=>o(u=>!u),className:"w-3 cursor-pointer border-0 bg-transparent p-0 text-[11px] text-primary",children:a?"▾":"▸"}),e.jsx("code",{className:"text-[11px] text-muted-foreground",children:c.id}),c.label&&e.jsx("span",{children:c.label})]}),a&&t.children.map(u=>e.jsx(Uj,{tree:u,depth:n+1},u.node.id))]})}const Bj=t=>t===null?"NONE":t>=80?"HIGH":t>=60?"MODERATE":"LOW",BS={HIGH:"success",MODERATE:"warning",LOW:"danger",NONE:"secondary"};function Hj({score:t}){const n=Bj((t==null?void 0:t.composite_score)??null),a=t!=null&&t.score_components?`coverage ${t.score_components.coverage} · agreement ${t.score_components.agreement} · confidence ${t.score_components.confidence} · continuity ${t.score_components.continuity}`:"no quality score for this line yet",o=(t==null?void 0:t.composite_score)===null||t===null?"no score":`quality ${t.composite_score}`;return e.jsx(V,{variant:BS[n],title:a,className:"whitespace-nowrap",children:o})}function HS({score:t,vintage:n}){return!t||Bj(t.composite_score)!=="LOW"?null:e.jsxs("div",{role:"alert",className:"mb-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-[13px] text-foreground",children:[e.jsxs("strong",{className:"text-destructive",children:["Low data quality (",t.composite_score,"/100)"]})," for this line at vintage ",n," — treat the figures with care and consult the provenance tab before relying on them."]})}const VS="Figures are provenanced to a data vintage; mid-cycle reads answer from the last completed quarter.",mi="border-b px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",hi="border-b p-2 text-[13px]";function GS({cardId:t,identity:n}){const[a,o]=i.useState(null),[c,u]=i.useState(""),[h,m]=i.useState(""),[x,v]=i.useState(""),[N,j]=i.useState(null),[w,_]=i.useState(null),S=`${t}:${h}`,y=w===S?"error":N===S?"ok":"loading",g=i.useCallback(()=>Bb(n,t,h||void 0),[t,n,h]),p=i.useCallback(C=>{o(C),u(""),j(S),_(null)},[S]),k=i.useCallback(C=>{u(C instanceof Error?C.message:"Failed"),_(S),j(null)},[S]);i.useEffect(()=>{let C=!0;return g().then(E=>{C&&p(E)},E=>{C&&k(E)}),()=>{C=!1}},[g,p,k]);const R=async C=>{try{const E=await Hb(n,t,C);v(E.missing>0?`${C} export produced (${E.filename}) — PARTIAL: ${E.missing} numeric field${E.missing===1?"":"s"} without provenance are listed in the report`:`${C} export produced (${E.filename}) — complete`)}catch{v(`${C} export failed`)}};return n.tier!=="1"&&n.tier!=="admin"?e.jsxs("section",{className:"mt-4 rounded-xl border bg-card p-4",children:[e.jsx("h2",{className:"mb-3 text-[15px] font-semibold tracking-wide",children:"Data provenance"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Full provenance — sources, conflicts, lineage and coverage — requires a Tier 1 subscription."})]}):e.jsxs("section",{className:"mt-4 rounded-xl border bg-card p-4","aria-label":"Data provenance",children:[e.jsxs("header",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsx("h2",{className:"mb-3 text-[15px] font-semibold tracking-wide",children:"Data provenance"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"text-xs text-muted-foreground",children:["Metric"," ",e.jsx(me,{value:h,onChange:C=>m(C.target.value),placeholder:"all metrics","aria-label":"Metric filter",className:"h-8 w-40 text-xs"})]}),e.jsx(K,{type:"button",variant:"outline",size:"xs",onClick:()=>void R("json"),children:"Export JSON"}),e.jsx(K,{type:"button",variant:"outline",size:"xs",onClick:()=>void R("report"),children:"Export report"})]})]}),e.jsx("p",{className:"mb-2.5 mt-1 text-xs text-muted-foreground",children:VS}),x&&e.jsx("p",{className:"m-0 text-xs text-success",children:x}),y==="loading"&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading provenance…"}),y==="error"&&e.jsx("div",{className:"text-sm text-destructive",children:c.includes("CARD_UNDER_REVIEW")?"This card is under review — provenance is served for published cards.":c}),y==="ok"&&a&&e.jsx(WS,{view:a})]})}function WS({view:t}){const n=(a,o)=>e.jsxs("h3",{className:"mb-1.5 mt-3.5 text-sm font-semibold",children:[a,". ",o]});return e.jsxs("div",{children:[n(1,"Sources"),t.sources.length===0?e.jsx(Zo,{children:"No source records for this selection."}):e.jsxs("table",{className:"w-full text-[13px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-muted-foreground",children:[e.jsx("th",{className:mi,children:"Source"}),e.jsx("th",{className:mi,children:"Records"}),e.jsx("th",{className:mi,children:"Used"}),e.jsx("th",{className:mi,children:"Excluded"}),e.jsx("th",{className:mi,children:"Last ingestion"})]})}),e.jsx("tbody",{children:t.sources.map(a=>e.jsxs("tr",{className:"border-t",children:[e.jsxs("td",{className:hi,children:[a.source_name," ",e.jsx("code",{className:"text-[11px] text-muted-foreground",children:a.source_id})]}),e.jsx("td",{className:`${hi} tabular-nums`,children:a.records}),e.jsx("td",{className:`${hi} tabular-nums`,children:a.used}),e.jsx("td",{className:`${hi} tabular-nums`,children:a.excluded}),e.jsx("td",{className:hi,children:a.last_ingestion.slice(0,16).replace("T"," ")})]},a.source_id))})]}),n(2,"Quality summary"),e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[e.jsx(Hj,{score:t.quality.score}),e.jsx(V,{variant:t.quality.statuses.some(a=>a.verdict==="HOLD"||a.verdict==="FAILED")?"danger":"success",children:t.quality.statuses.length===0?"no gate statuses at this vintage":`${t.quality.statuses.length} line status${t.quality.statuses.length===1?"":"es"}`})]}),n(3,"Conflict resolutions"),t.conflicts.length===0?e.jsx(Zo,{children:"No conflicts at this selection."}):e.jsx("ul",{className:"m-0 list-disc pl-4.5 text-[13px]",children:t.conflicts.map(a=>e.jsxs("li",{children:[e.jsx("code",{className:"text-[11px]",children:a.provenance_id})," (",a.source_id,") — ",a.summary]},a.provenance_id))}),n(4,"CAS lineage"),t.cas_lineage.length===0?e.jsx(Zo,{children:"No CAS-input records for this selection."}):e.jsx("ul",{className:"m-0 list-disc pl-4.5 text-[13px]",children:t.cas_lineage.map(a=>e.jsxs("li",{children:[a.metric," = ",a.value??"—"," ",e.jsx("code",{className:"text-[11px] text-muted-foreground",children:a.provenance_id}),a.derived_from.length>0&&` · derives from ${a.derived_from.length}`]},a.provenance_id))}),t.line&&e.jsx(US,{nodes:qS(t)}),n(5,"Model assumptions"),t.model_assumptions.length===0?e.jsx(Zo,{children:"None."}):e.jsx("ul",{className:"m-0 list-disc pl-4.5 text-[13px]",children:t.model_assumptions.map(a=>e.jsxs("li",{children:[a.field," = ",a.value,a.provenance_id?` — ${a.provenance_id}`:" — no provenance record"]},a.field))}),n(6,"Coverage"),e.jsxs("p",{className:"m-0 mb-1.5 text-[13px]",children:[t.coverage.resolved,"/",t.coverage.total," numeric fields resolved",t.coverage.missing.length>0&&e.jsxs("span",{className:"text-warning",children:[" — ",t.coverage.missing.length," without a provenance record"]})]}),t.coverage.missing.length>0&&e.jsx("ul",{className:"m-0 list-disc pl-4.5 text-xs text-warning",children:t.coverage.missing.map(a=>e.jsxs("li",{children:[a.field," = ",a.value]},a.field))}),e.jsxs("p",{className:"m-0 mt-2.5 text-xs text-muted-foreground",children:["Audit log: ",t.audit_summary.entry_count," entries, latest sequence ",t.audit_summary.latest_sequence]})]})}function qS(t){const n=new Map;for(const a of t.cas_lineage)n.set(a.provenance_id,{id:a.provenance_id,label:a.metric,derivedFrom:a.derived_from});for(const a of t.coverage.fields)a.provenance_id&&!n.has(a.provenance_id)&&n.set(a.provenance_id,{id:a.provenance_id,label:a.field});for(const a of[...n.values()])for(const o of a.derivedFrom??[])n.has(o)||n.set(o,{id:o});return[...n.values()]}const Zo=({children:t})=>e.jsx("p",{className:"text-sm text-muted-foreground",children:t});function QS({cardId:t,tier:n}){var F;const[a,o]=i.useState(t?"loading":"empty"),[c,u]=i.useState(n),[h,m]=i.useState(t??""),[x,v]=i.useState(null),[N,j]=i.useState(null),[w,_]=i.useState(""),[S,y]=i.useState("overview"),[g,p]=i.useState({cardId:t,tier:c});(g.cardId!==t||g.tier!==c)&&(p({cardId:t,tier:c}),t&&(m(t),o("loading"),j(null)));const k=i.useCallback(async I=>I?DS(I,c):null,[c]),R=i.useCallback(I=>{v(I),o("ok")},[]),C=i.useCallback(I=>{_(I instanceof Error?I.message:"Unknown error"),o("error")},[]);i.useEffect(()=>{if(!t)return;let I=!0;return k(t).then(M=>{I&&M&&R(M)},M=>{I&&C(M)}),()=>{I=!1}},[t,k,R,C]);const E=i.useCallback(async()=>{if(!h){o("empty");return}o("loading"),j(null);try{const I=await k(h);I&&R(I)}catch(I){C(I)}},[h,k,R,C]),P=i.useCallback(async()=>{try{j(await $S(h,c))}catch(I){_(I instanceof Error?I.message:"Document unavailable")}},[h,c]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Card Detail",description:"Full DFI-grade card · trilingual cited thesis",actions:e.jsxs(e.Fragment,{children:[e.jsx(me,{value:h,onChange:I=>m(I.target.value),placeholder:"720839@2025-Q1","aria-label":"Card id",className:"w-45"}),e.jsxs(Ie,{value:c,onChange:I=>u(I.target.value),"aria-label":"Subscriber tier",className:"w-32",children:[e.jsx("option",{value:"1",children:"Tier 1"}),e.jsx("option",{value:"2",children:"Tier 2"}),e.jsx("option",{value:"3",children:"Tier 3"}),e.jsx("option",{value:"admin",children:"Admin"})]}),e.jsx(K,{size:"sm",onClick:()=>void E(),children:"Load"})]})}),a==="loading"&&e.jsx(H,{children:"Loading card…"}),a==="empty"&&e.jsxs(H,{children:["Enter a card id (e.g. ",e.jsx("code",{children:"720839@2025-Q1"}),") or open one from the catalog."]}),a==="error"&&e.jsxs(H,{tone:"error",children:[w,c==="3"&&e.jsx("p",{className:"text-sm",children:"Tier 3 (Advisory) cannot access full card JSON — only the watermarked document. Switch to Tier 1/2."}),e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void E(),children:"Retry"})})]}),a==="ok"&&x&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{className:"text-base font-semibold",children:[x.hs6_code," · ",x.product_name_en]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(V,{variant:x.status==="GENERATED"?"success":x.status==="SUPERSEDED"?"secondary":"danger",children:x.status}),e.jsxs(V,{variant:"secondary",children:["CAS ",x.cas_score]}),e.jsx(Hj,{score:x.data_quality??null}),e.jsx(V,{variant:"secondary",children:x.sector_classification.sector_code}),e.jsx(V,{variant:"secondary",children:yi[x.capex_classification.bracket]})]})]}),x.sector_classification.boundary_ambiguity&&e.jsxs("p",{className:"mt-2 text-sm text-warning",children:["⚑ Sector boundary ambiguity — candidates ",x.sector_classification.boundary_ambiguity.candidates.join(" / ")," (",x.sector_classification.boundary_ambiguity.rule,")"]})]})}),e.jsx(HS,{score:x.data_quality??null,vintage:((F=x.data_quality)==null?void 0:F.vintage_quarter)??x.cycle_id}),e.jsx("div",{role:"tablist","aria-label":"Card sections",className:"mt-4 flex gap-1",children:["overview","provenance"].map(I=>e.jsx("button",{type:"button",role:"tab","aria-selected":S===I,onClick:()=>y(I),className:`cursor-pointer rounded-t-lg border px-3.5 py-1.5 text-sm transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none ${S===I?"border-b-2 border-b-primary bg-card":"bg-muted hover:bg-accent"}`,children:I==="overview"?"Overview":"Data provenance"},I))}),S==="provenance"?e.jsx(GS,{cardId:x.card_id,identity:KS(c)}):e.jsxs(e.Fragment,{children:[e.jsx(zj,{cardId:x.card_id,tier:c}),e.jsxs("div",{className:"mt-4 grid grid-cols-[repeat(auto-fit,minmax(280px,1fr))] gap-4",children:[e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"CAPEX classification"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(ue,{label:"Bracket",value:yi[x.capex_classification.bracket]}),e.jsx(ue,{label:"Midpoint",value:Xe(x.capex_classification.estimated_capex_usd_midpoint)}),e.jsx(ue,{label:"Model",value:x.capex_classification.capex_model_id}),x.capex_classification.data_quality_flag&&e.jsx(ue,{label:"Data quality",value:x.capex_classification.data_quality_flag,tone:"error"})]}),e.jsx("p",{className:"mt-2 break-words text-xs text-muted-foreground",children:x.capex_classification.formula})]})}),e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"Tariff & DAPS"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(ue,{label:"MFN",value:`${x.tariff_status.mfn_rate_percent}% (${x.tariff_status.mfn_rate_vintage_date})`}),e.jsx(ue,{label:"DAPS",value:x.tariff_status.daps_applicable?`${x.tariff_status.daps_rate_percent}% · exp ${x.tariff_status.daps_expiry_date??"open"}`:"none"}),e.jsx(ue,{label:"AfCFTA",value:x.tariff_status.afcfta_applicable?`${x.tariff_status.afcfta_preferential_rate_percent}% (adv ${x.tariff_status.afcfta_cost_advantage_pct}%)`:"n/a"})]}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:x.tariff_status.flags.map(I=>e.jsx(V,{variant:I.includes("IMMINENT")||I.includes("STALE")?"warning":"secondary",children:I},I))})]})})]}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"Wilaya siting shortlist"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Rank"}),e.jsx(T,{children:"Wilaya"}),e.jsx(T,{children:"Score"}),e.jsx(T,{children:"Binding constraint"})]})}),e.jsx(ye,{children:x.wilaya_shortlist.map(I=>e.jsxs(ee,{children:[e.jsx(A,{children:["🥇","🥈","🥉"][I.rank-1]??I.rank}),e.jsxs(A,{children:[I.wilaya_name_fr," ",e.jsx("span",{className:"font-mono text-muted-foreground",children:I.wilaya_code})]}),e.jsx(A,{className:"tabular-nums",children:I.composite_siting_score}),e.jsx(A,{children:I.enabling_constraint_tag})]},I.wilaya_code))})]})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"Value-creation thesis (trilingual, cited)"}),e.jsxs("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-4",children:[e.jsx(Eu,{title:"English",text:x.value_creation_thesis.en,words:x.value_creation_thesis.word_count_en}),e.jsx(Eu,{title:"Français",text:x.value_creation_thesis.fr,words:x.value_creation_thesis.word_count_fr}),e.jsx(Eu,{title:"العربية",text:x.value_creation_thesis.ar,words:x.value_creation_thesis.word_count_ar,rtl:!0})]}),x.value_creation_thesis.applies_5149&&e.jsx("p",{className:"mt-3 rounded-lg bg-warning/10 p-2.5 text-sm text-warning",children:"⚖ 51/49 rule: foreign investors must hold a minority equity position ≤ 49% (Law 22-18, Art. 4)."})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-base font-semibold",children:["Source citation appendix (",x.citations.length,")"]}),e.jsx(K,{size:"sm",onClick:()=>void P(),children:"Render document"})]}),e.jsx("ul",{className:"m-0 ps-[18px] text-sm text-foreground",children:x.citations.map(I=>e.jsxs("li",{children:[e.jsx("code",{children:I.citation_id})," — ",I.table_name,".",I.field_name," = ",String(I.value_used)," (source ",I.source,")"]},I.citation_id))}),N&&e.jsxs("div",{className:"mt-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Template ",N.template_version," · integrity ",N.integrity_ok?"✓":"✗",N.watermarked?" · WATERMARKED":""]}),e.jsx(_i,{className:"mt-1",children:N.content})]})]})})]})]})]})}function KS(t){return{tier:t,role:"subscriber",user_id:"console"}}function Eu({title:t,text:n,words:a,rtl:o}){return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 text-xs text-muted-foreground",children:[t," · ",a," words"]}),e.jsx("p",{dir:o?"rtl":"ltr",className:`m-0 text-sm ${o?"text-right":"text-start"}`,children:n})]})}function XS(){const[t,n]=i.useState("loading"),[a,o]=i.useState([]),[c,u]=i.useState("2025-Q1"),[h,m]=i.useState(!1),[x,v]=i.useState(""),N=i.useCallback(async()=>{const{jobs:y}=await LS();return y},[]),j=i.useCallback(y=>{o(y),n(y.length===0?"empty":"ok")},[]),w=i.useCallback(y=>{v(y instanceof Error?y.message:"Unknown error"),n("error")},[]);i.useEffect(()=>{let y=!0;return N().then(g=>{y&&j(g)},g=>{y&&w(g)}),()=>{y=!1}},[N,j,w]);const _=i.useCallback(()=>(n("loading"),N().then(j,w)),[N,j,w]),S=i.useCallback(async()=>{m(!0),v("");try{await TS(c),await _()}catch(y){v(y instanceof Error?y.message:"Trigger failed"),n("error")}finally{m(!1)}},[c,_]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Batch Pipeline",description:"Trigger & monitor per-cycle card generation",actions:e.jsxs(e.Fragment,{children:[e.jsx(me,{value:c,onChange:y=>u(y.target.value),placeholder:"2025-Q1","aria-label":"Cycle",className:"w-32"}),e.jsx(K,{size:"sm",onClick:()=>void S(),disabled:h,children:h?"Running…":"Trigger batch"})]})}),t==="loading"&&e.jsx(H,{children:"Loading pipeline jobs…"}),t==="error"&&e.jsxs(H,{tone:"error",children:[x,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void _(),children:"Retry"})})]}),t==="empty"&&e.jsxs(H,{children:["No batches have run yet. Enter a cycle (e.g. ",e.jsx("code",{children:"2025-Q1"}),") and click ",e.jsx("em",{children:"Trigger batch"}),"."]}),t==="ok"&&e.jsxs(e.Fragment,{children:[a[0]&&e.jsxs("section",{className:"my-4 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"Latest cycle",value:a[0].cycle_id}),e.jsx(ze,{label:"Eligible",value:String(a[0].eligible_hs6_count)}),e.jsx(ze,{label:"Generated",value:String(a[0].total_generated_success),tone:"ok"}),e.jsx(ze,{label:"Failed",value:String(a[0].total_generated_failed),tone:a[0].total_generated_failed>0?"error":"ok"}),e.jsx(ze,{label:"SLA",value:a[0].sla_breached?"BREACHED":"within",tone:a[0].sla_breached?"error":"ok"})]}),e.jsxs("h2",{className:"mb-3 mt-4 text-base font-semibold",children:["Batch jobs (",a.length,")"]}),e.jsx(B,{className:"overflow-hidden py-0",children:e.jsxs(je,{className:"min-w-[640px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Cycle"}),e.jsx(T,{children:"Status"}),e.jsx(T,{className:"text-right",children:"Eligible"}),e.jsx(T,{className:"text-right",children:"OK"}),e.jsx(T,{className:"text-right",children:"Failed"}),e.jsx(T,{className:"text-right",children:"Elapsed"}),e.jsx(T,{children:"Warnings"})]})}),e.jsx(ye,{children:a.map(y=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:y.cycle_id}),e.jsx(A,{children:e.jsx(V,{variant:y.status==="COMPLETED"?"success":y.status==="FAILED"?"danger":"warning",children:y.status})}),e.jsx(A,{className:"text-right tabular-nums",children:y.eligible_hs6_count}),e.jsx(A,{className:"text-right tabular-nums",children:y.total_generated_success}),e.jsx(A,{className:"text-right tabular-nums",children:y.total_generated_failed}),e.jsxs(A,{className:"text-right tabular-nums",children:[y.elapsed_ms??"—"," ms"]}),e.jsx(A,{children:y.warnings.length?y.warnings.map(g=>e.jsx(V,{variant:"warning",children:g},g)):e.jsx("span",{className:"text-muted-foreground",children:"none"})})]},y.job_id))})]})})]})]})}const YS={CAS_SCORE_MOVEMENT:"CAS score",CAPEX_BRACKET_CHANGE:"CAPEX bracket",TARIFF_RATE_CHANGE:"Tariff / DAPS",WILAYA_SITING_CHANGE:"Wilaya siting",THESIS_SUBSTANTIVE_UPDATE:"Thesis"};function ZS(){const[t,n]=i.useState("2025-Q2"),[a,o]=i.useState(!0),[c,u]=i.useState(null),[h,m]=i.useState(""),[x,v]=i.useState(null),[N,j]=i.useState(null),w=`${t}|${a}`,_=N===w?"error":x!==w?"loading":c!==null&&c.changes.length===0&&c.new_cards.length===0?"empty":"ok",S=i.useCallback(async()=>await IS(t,a),[t,a]),y=i.useCallback(k=>{u(k),v(w),j(null)},[w]),g=i.useCallback(k=>{m(k instanceof Error?k.message:"Unknown error"),j(w),v(null)},[w]),p=i.useCallback(()=>(v(null),j(null),S().then(y,g)),[S,y,g]);return i.useEffect(()=>{let k=!0;return S().then(R=>{k&&y(R)},R=>{k&&g(R)}),()=>{k=!1}},[S,y,g]),e.jsxs("div",{children:[e.jsx(Se,{title:"Delta Review",description:"Material changes between consecutive quarterly runs",actions:e.jsxs(e.Fragment,{children:[e.jsx(me,{value:t,onChange:k=>n(k.target.value),placeholder:"2025-Q2","aria-label":"Cycle",className:"w-32"}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:a,onChange:k=>o(k.target.checked),className:"size-4 accent-primary"})," Material only"]}),e.jsx(K,{size:"sm",onClick:()=>void p(),children:"Load"})]})}),_==="loading"&&e.jsx(H,{children:"Loading delta report…"}),_==="error"&&e.jsxs(H,{tone:"error",children:[h,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void p(),children:"Retry"})})]}),_==="empty"&&e.jsxs(H,{children:["No changes for ",t,". Generate two consecutive cycles (e.g. 2025-Q1 then 2025-Q2) on the Batch Pipeline tab."]}),_==="ok"&&c&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mb-2 mt-4 text-sm text-muted-foreground",children:c.cycle_id_prior?e.jsxs(e.Fragment,{children:["Comparing ",e.jsx("strong",{children:c.cycle_id_prior})," → ",e.jsx("strong",{children:c.cycle_id_current})]}):e.jsxs(e.Fragment,{children:["Baseline cycle ",e.jsx("strong",{children:c.cycle_id_current})," (no prior)"]})}),c.new_cards.length>0&&e.jsx(B,{className:"mb-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:["New opportunity cards (",c.new_cards.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:c.new_cards.map(k=>e.jsxs(V,{variant:"success",children:[k," · NEW_CARD"]},k))})]})}),e.jsxs("h2",{className:"mb-3 mt-4 text-base font-semibold",children:["Changed fields (",c.changes.length,")"]}),e.jsx(B,{className:"overflow-hidden py-0",children:e.jsxs(je,{className:"min-w-[720px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Field"}),e.jsx(T,{children:"Prior"}),e.jsx(T,{children:"Current"}),e.jsx(T,{children:"Δ"}),e.jsx(T,{children:"Materiality"})]})}),e.jsx(ye,{children:c.changes.map(k=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:k.hs6_code}),e.jsx(A,{children:YS[k.change_type]??k.change_type}),e.jsx(A,{children:e.jsx("code",{children:op(k.prior_value)})}),e.jsx(A,{children:e.jsx("code",{children:op(k.current_value)})}),e.jsx(A,{children:k.change_magnitude===null?"—":k.change_magnitude}),e.jsx(A,{children:e.jsx(V,{variant:k.materiality_flag==="MATERIAL"?"danger":"secondary",children:k.materiality_flag})})]},k.delta_id))})]})})]})]})}function op(t){return t==null?"—":typeof t=="object"?JSON.stringify(t):String(t)}function JS(t){return{"x-subscriber-tier":t}}function eC(){return he("/regulatory/rules")}function tC(t){return he(`/regulatory/rules/${encodeURIComponent(t)}/audit-trail`)}function sC(t){return be(`/regulatory/rules/${encodeURIComponent(t)}/submit-for-review`)}function cp(t,n,a){return be(`/regulatory/rules/${encodeURIComponent(t)}/reviews`,a,{"x-reviewer-role":n})}function nC(t,n){return be("/compliance/determinations/evaluate",{items:t},JS(n))}function rC(t){const n=t?`?impact_band=${encodeURIComponent(t)}`:"";return he(`/compliance/changelog${n}`)}function aC(){return be("/regulatory/journal-officiel/scraper-runs/trigger")}function lC(){return he("/regulatory/journal-officiel/scraper-runs")}const iC={DRAFT:"secondary",UNDER_REVIEW:"warning",APPROVED:"success",REJECTED:"danger",SUPERSEDED:"info",EXPIRED:"secondary"};function dp({status:t}){return e.jsx(V,{variant:iC[t],children:t})}function fa({className:t,...n}){return e.jsx("textarea",{"data-slot":"textarea",className:ft("flex min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base transition-[color,box-shadow] outline-none placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",t),...n})}function oC(){const[t,n]=i.useState([]),[a,o]=i.useState(null),[c,u]=i.useState("ALGERIAN_LEGAL_EXPERT"),[h,m]=i.useState(""),[x,v]=i.useState(""),[N,j]=i.useState(!1),[w,_]=i.useState(""),[S,y]=i.useState(!1),[g,p]=i.useState(!1),k=g?"error":S?t.length===0?"empty":"ok":"loading",R=i.useCallback(async()=>(await eC()).rules,[]),C=i.useCallback(M=>{n(M),y(!0),p(!1)},[]),E=i.useCallback(M=>{v(M instanceof Error?M.message:"Load failed"),p(!0),y(!1)},[]),P=i.useCallback(()=>(y(!1),p(!1),R().then(C,E)),[R,C,E]);i.useEffect(()=>{let M=!0;return R().then($=>{M&&C($)},$=>{M&&E($)}),()=>{M=!1}},[R,C,E]);const F=i.useCallback(async M=>{_("");try{o(await tC(M))}catch($){v($ instanceof Error?$.message:"Could not load audit trail"),p(!0),y(!1)}},[]),I=i.useCallback(async(M,$)=>{j(!0),_("");try{await M(),_($),await P(),a&&await F(a.rule.rule_id)}catch(O){_(O instanceof Error?O.message:"Action failed")}finally{j(!1)}},[P,F,a]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Regulatory Rule Workbench",description:"Versioned Algerian regulatory rules with peer-review approval. No rule reaches production scoring until an Algerian legal expert approves it; mining rules require a second, distinct mining-law expert."}),k==="loading"&&e.jsx(Jo,{children:"Loading rule corpus…"}),k==="error"&&e.jsxs(Jo,{tone:"error",children:[x,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void P(),children:"Retry"})})]}),k==="empty"&&e.jsx(Jo,{children:"No regulatory rules encoded yet."}),k==="ok"&&e.jsxs("div",{className:"flex flex-wrap items-start gap-4",children:[e.jsx("div",{className:"min-w-0 flex-[1_1_420px]",children:e.jsx(B,{className:"overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Version"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Effective"}),e.jsx(T,{children:"Citation"})]})}),e.jsx(ye,{children:t.map(M=>e.jsxs(ee,{onClick:()=>void F(M.rule_id),className:(a==null?void 0:a.rule.rule_id)===M.rule_id?"cursor-pointer bg-accent":"cursor-pointer",children:[e.jsx(A,{children:M.rule_type}),e.jsx(A,{children:M.version_number}),e.jsx(A,{children:e.jsx(dp,{status:M.status})}),e.jsx(A,{children:M.effective_date}),e.jsx(A,{children:M.journal_officiel_reference??"—"})]},M.rule_id))})]})})}),e.jsxs("aside",{className:"min-w-0 flex-[1_1_360px]",children:[!a&&e.jsx(Jo,{children:"Select a rule to inspect its version chain and run peer review."}),a&&e.jsxs(B,{className:"mt-4 gap-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("strong",{children:[a.rule.rule_type," · v",a.rule.version_number]}),e.jsx(dp,{status:a.rule.status})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["hash ",a.rule.payload_hash.slice(0,16),"… · lineage ",a.supersession_lineage.length," version(s)"]}),a.rule.rule_type==="MINING"&&e.jsx("p",{className:"rounded-lg bg-warning/10 px-2.5 py-1.5 text-sm text-warning",children:"Mining rule — requires approval by a distinct ALGERIAN_LEGAL_EXPERT and MINING_LAW_EXPERT."}),e.jsx("h4",{className:"text-sm font-semibold",children:"Version chain"}),e.jsx("ol",{className:"list-decimal pl-5 text-sm",children:a.version_chain.map(M=>e.jsxs("li",{className:"mb-1",children:[e.jsx("strong",{children:M.status})," · ",M.actor_role," · ",new Date(M.created_at).toLocaleString(),M.notes?` — ${M.notes}`:""]},M.version_id))}),e.jsxs("h4",{className:"text-sm font-semibold",children:["Approvals (",a.approvals.length,")"]}),a.approvals.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No approvals recorded."}),a.approvals.map(M=>e.jsxs("div",{className:"mb-1 text-sm",children:[M.decision," · ",M.approver_role," · ",M.approver_user_id]},M.approval_id)),e.jsx("h4",{className:"text-sm font-semibold",children:"Peer review"}),a.rule.status==="DRAFT"&&e.jsx(K,{size:"sm",disabled:N,onClick:()=>void I(()=>sC(a.rule.rule_id),"Submitted for review."),children:"Submit for review"}),a.rule.status==="UNDER_REVIEW"&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("label",{className:"text-xs text-muted-foreground",children:["Reviewer role"," ",e.jsxs(Ie,{value:c,onChange:M=>u(M.target.value),"aria-label":"Reviewer role",children:[e.jsx("option",{value:"ALGERIAN_LEGAL_EXPERT",children:"Algerian legal expert"}),e.jsx("option",{value:"MINING_LAW_EXPERT",children:"Mining-law expert"}),e.jsx("option",{value:"admin",children:"Admin"})]})]}),e.jsx(fa,{placeholder:"Review notes (≥ 50 characters for an approval)",value:h,onChange:M=>m(M.target.value),"aria-label":"Review notes"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{size:"sm",disabled:N,onClick:()=>void I(()=>cp(a.rule.rule_id,c,{reviewer_user_id:`${c}-user`,decision:"APPROVE",notes:h,cited_sources:[a.rule.journal_officiel_reference??"JO"]}),"Approval recorded."),children:"Approve"}),e.jsx(K,{variant:"destructive",size:"sm",disabled:N,onClick:()=>void I(()=>cp(a.rule.rule_id,c,{reviewer_user_id:`${c}-user`,decision:"REJECT",notes:h,cited_sources:[]}),"Rejection recorded."),children:"Reject"})]})]}),w&&e.jsx("p",{className:"rounded-lg bg-primary/10 px-2.5 py-1.5 text-sm text-primary",role:"status",children:w})]})]})]})]})}function Jo({children:t,tone:n}){return e.jsx("div",{className:n==="error"?"mt-4 rounded-xl border border-destructive/50 bg-destructive/10 p-4 text-destructive":"mt-4 rounded-xl border bg-card p-4 text-foreground",role:n==="error"?"alert":void 0,children:t})}const cC={COMPLIANT:{variant:"success",label:"COMPLIANT"},FLAGGED_5149:{variant:"danger-solid",label:"FLAGGED 51/49"},ZONE_EXCEPTION:{variant:"warning",label:"ZONE EXCEPTION"},STRUCTURAL_COMPLEXITY:{variant:"warning",label:"STRUCTURAL COMPLEXITY"},PENDING_LEGAL_REVIEW:{variant:"info",label:"PENDING LEGAL REVIEW"}};function dC({status:t}){const{variant:n,label:a}=cC[t];return e.jsx(V,{variant:n,className:"whitespace-nowrap",children:a})}const up=[{entity_id:"jv-49",hs6_code:"720610",sector_type:"MANUFACTURING",foreign_equity_pct:49},{entity_id:"jv-4901",hs6_code:"720610",sector_type:"MANUFACTURING",foreign_equity_pct:49.01},{entity_id:"greenfield-100",hs6_code:"720610",sector_type:"MANUFACTURING",foreign_equity_pct:100},{entity_id:"freezone-60",hs6_code:"720610",sector_type:"MANUFACTURING",foreign_equity_pct:60,zone_id:"FZ-OR"},{entity_id:"mining-jv-55",hs6_code:"720610",sector_type:"MINING",foreign_equity_pct:55},{entity_id:"pref-shares",hs6_code:"720610",sector_type:"MANUFACTURING",foreign_equity_pct:49,preference_shares_control:!0}];function uC(){const[t,n]=i.useState("idle"),[a,o]=i.useState("1"),[c,u]=i.useState([]),[h,m]=i.useState(""),[x,v]=i.useState("80"),[N,j]=i.useState(""),[w,_]=i.useState("MANUFACTURING"),S=i.useCallback(async g=>{n("loading");try{const p=await nC(g,a);u(p.determinations),n(p.determinations.length===0?"empty":"ok")}catch(p){m(p instanceof Error?p.message:"Evaluation failed"),n("error")}},[a]),y=i.useCallback(()=>{const g=Number(x);if(!Number.isFinite(g)||g<0||g>100){m("Foreign equity % must be between 0 and 100"),n("error");return}S([{entity_id:"custom",hs6_code:"720610",sector_type:w,foreign_equity_pct:g,zone_id:N||void 0}])},[x,w,N,S]);return e.jsxs("div",{children:[e.jsx(Se,{title:"51/49 Compliance-Flag Explorer",description:"Evaluate investment structures against Algeria's foreign-equity hard constraint. Foreign majority onshore is blocked; free-zone and mining ceilings override where an approved rule permits.",actions:e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:["Subscriber tier",e.jsxs(Ie,{value:a,onChange:g=>o(g.target.value),"aria-label":"Subscriber tier",children:[e.jsx("option",{value:"1",children:"Tier 1 (full)"}),e.jsx("option",{value:"2",children:"Tier 2 (masked)"}),e.jsx("option",{value:"3",children:"Tier 3 (masked)"}),e.jsx("option",{value:"admin",children:"Admin"})]})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(Au,{label:"Foreign equity %",children:e.jsx(me,{value:x,onChange:g=>v(g.target.value),inputMode:"decimal","aria-label":"Foreign equity percent",className:"w-32"})}),e.jsx(Au,{label:"Sector",children:e.jsxs(Ie,{value:w,onChange:g=>_(g.target.value),"aria-label":"Sector",children:[e.jsx("option",{value:"MANUFACTURING",children:"Manufacturing"}),e.jsx("option",{value:"MINING",children:"Mining"})]})}),e.jsx(Au,{label:"Free zone (optional)",children:e.jsxs(Ie,{value:N,onChange:g=>j(g.target.value),"aria-label":"Free zone",children:[e.jsx("option",{value:"",children:"— none (onshore) —"}),e.jsx("option",{value:"FZ-OR",children:"Oran Free Zone (ceiling 66%)"}),e.jsx("option",{value:"FZ-AN",children:"Annaba Free Zone (ceiling 100%)"})]})}),e.jsx(K,{size:"sm",onClick:y,children:"Evaluate structure"}),e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void S(up),children:"Run the 6-case battery"})]})}),t==="idle"&&e.jsx(ec,{children:"Enter a structure or run the battery to see 51/49 determinations."}),t==="loading"&&e.jsx(ec,{children:"Evaluating…"}),t==="error"&&e.jsxs(ec,{tone:"error",children:[h,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void S(up),children:"Retry battery"})})]}),t==="empty"&&e.jsx(ec,{children:"No determinations returned."}),t==="ok"&&e.jsxs("div",{children:[e.jsx(B,{className:"mt-4 overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Entity"}),e.jsx(T,{children:"Equity %"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Reason"}),e.jsx(T,{children:"Ceiling"}),e.jsx(T,{children:"Frameworks"})]})}),e.jsx(ye,{children:c.map(g=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:g.entity_id??"—"}),e.jsx(A,{children:g.hs6_code??"—"}),e.jsx(A,{children:e.jsx(dC,{status:g.compliance_status})}),e.jsx(A,{children:g.reason_code??"—"}),e.jsx(A,{children:g.applied_ceiling_pct!=null?`${g.applied_ceiling_pct}%`:"—"}),e.jsx(A,{children:g.applicable_regulatory_frameworks.join(", ")})]},g.determination_id))})]})}),c.filter(g=>g.compliance_status==="FLAGGED_5149"&&g.rule_text_i18n).map(g=>{var p,k,R;return e.jsxs(B,{className:"mt-4 gap-2 border-destructive/40 p-4",children:[e.jsxs("strong",{className:"text-destructive",children:["51/49 rule — ",g.entity_id]}),e.jsx("p",{className:"mb-1 mt-2",children:(p=g.rule_text_i18n)==null?void 0:p.en}),e.jsx("p",{className:"my-1",dir:"ltr",children:(k=g.rule_text_i18n)==null?void 0:k.fr}),e.jsx("p",{className:"my-1 text-start",dir:"rtl",children:(R=g.rule_text_i18n)==null?void 0:R.ar}),g.alternatives&&g.alternatives.length>0&&e.jsx("ul",{className:"my-2 list-disc pl-5",children:g.alternatives.map(C=>e.jsx("li",{children:C},C))})]},`i18n-${g.determination_id}`)})]})]})}function Au({label:t,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:[t,n]})}function ec({children:t,tone:n}){return e.jsx("div",{className:n==="error"?"mt-4 rounded-xl border border-destructive/50 bg-destructive/10 p-4 text-destructive":"mt-4 rounded-xl border bg-card p-4 text-foreground",role:n==="error"?"alert":void 0,children:t})}const mC={HIGH:"danger",MEDIUM:"warning",LOW:"secondary"};function hC(){const[t,n]=i.useState(""),[a,o]=i.useState([]),[c,u]=i.useState(0),[h,m]=i.useState([]),[x,v]=i.useState(""),[N,j]=i.useState(!1),[w,_]=i.useState(null),[S,y]=i.useState(null),g=S===t?"error":w===t?a.length===0?"empty":"ok":"loading",p=i.useCallback(async()=>{const[F,I]=await Promise.all([rC(t||void 0),lC()]);return{changes:F.changes,total:F.total,runs:I.runs}},[t]),k=i.useCallback(F=>{o(F.changes),u(F.total),m(F.runs),_(t),y(null)},[t]),R=i.useCallback(F=>{v(F instanceof Error?F.message:"Load failed"),y(t),_(null)},[t]);i.useEffect(()=>{let F=!0;return p().then(I=>{F&&k(I)},I=>{F&&R(I)}),()=>{F=!1}},[p,k,R]);const C=i.useCallback(()=>(_(null),y(null),p().then(k,R)),[p,k,R]),E=i.useCallback(async()=>{j(!0);try{await aC(),await C()}catch(F){v(F instanceof Error?F.message:"Scraper failed"),y(t),_(null)}finally{j(!1)}},[t,C]),P=h[h.length-1];return e.jsxs("div",{children:[e.jsx(Se,{title:"Regulatory Change-Log",description:"Every legislative change, its impact band, and the lines it re-scored — the append-only delta ledger DFI clients cite in appraisal documents.",actions:e.jsx(K,{size:"sm",onClick:()=>void E(),disabled:N,children:N?"Detecting…":"Run Journal Officiel detection"})}),P&&e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"Gazettes detected",value:String(P.gazette_issues_detected)}),e.jsx(ze,{label:"Rules drafted",value:String(P.rules_drafted),tone:"ok"}),e.jsx(ze,{label:"Lines re-scored",value:String(P.rescore_summary.total_lines_enqueued)}),e.jsx(ze,{label:"Low-OCR / ambiguous",value:`${P.low_ocr_sections} / ${P.ambiguities}`,tone:P.ambiguities>0?"warn":void 0})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Impact band:"}),["","HIGH","MEDIUM","LOW"].map(F=>e.jsx(K,{variant:t===F?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>n(F),children:F||"All"},F||"all")),e.jsxs("span",{className:"ms-auto text-sm text-muted-foreground",children:[c," result",c===1?"":"s"]})]}),g==="loading"&&e.jsx(Ru,{children:"Loading change-log…"}),g==="error"&&e.jsxs(Ru,{tone:"error",children:[x,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void C(),children:"Retry"})})]}),g==="empty"&&e.jsx(Ru,{children:"No regulatory changes recorded for this filter. Run a Journal Officiel detection cycle to materialise deltas from the latest gazette batch."}),g==="ok"&&e.jsx(B,{className:"mt-4 overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Date"}),e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Change"}),e.jsx(T,{children:"Impact"}),e.jsx(T,{children:"Lines"}),e.jsx(T,{children:"Citation"})]})}),e.jsx(ye,{children:a.map(F=>e.jsxs(ee,{children:[e.jsx(A,{children:F.event_date}),e.jsx(A,{children:F.rule_type}),e.jsx(A,{children:F.change_type}),e.jsx(A,{children:e.jsx(V,{variant:mC[F.impact_band],children:F.impact_band})}),e.jsx(A,{className:"text-right tabular-nums",children:F.affected_hs6_count}),e.jsx(A,{children:F.source_citation})]},F.change_id))})]})})]})}function Ru({children:t,tone:n}){return e.jsx("div",{className:n==="error"?"mt-4 rounded-xl border border-destructive/50 bg-destructive/10 p-4 text-destructive":"mt-4 rounded-xl border bg-card p-4 text-foreground",role:n==="error"?"alert":void 0,children:t})}const bs=t=>({"x-subscriber-tier":t});function fC(t){const n=new URLSearchParams;for(const[o,c]of Object.entries(t))c==null||c===""||c===!1||n.set(o,String(c));const a=n.toString();return a?`?${a}`:""}const xC=(t,n)=>be("/v1/financial-models",t,bs(n)),pC=(t,n)=>he(`/v1/financial-models?cycle_id=${encodeURIComponent(t)}`,bs(n)),gC=(t,n)=>he(`/v1/financial-models/${encodeURIComponent(t)}`,bs(n)),vC=(t,n)=>he(`/v1/financial-models/${encodeURIComponent(t)}/document`,bs(n)),jC=(t,n)=>he(`/v1/financial-models/eligible?cycle_id=${encodeURIComponent(t)}`,bs(n)),yC=(t,n,a)=>be(`/v1/financial-models/${encodeURIComponent(t)}/monte-carlo`,n,bs(a)),_C=(t,n)=>he(`/v1/capex-benchmarks${fC(t)}`,bs(n)),bC=(t,n)=>be("/v1/capex-benchmarks",t,bs(n)),NC=(t,n,a)=>Ri(`/v1/capex-benchmarks/${encodeURIComponent(t)}`,n,bs(a)),wC=(t,n)=>he(`/v1/capex-benchmarks/${encodeURIComponent(t)}/history`,bs(n)),SC=(t,n)=>be("/v1/pipeline/validate-models",t,bs(n)),CC=(t,n)=>he(`/v1/model-validations?cycle_id=${encodeURIComponent(t)}`,bs(n)),kC=(t,n)=>he(`/v1/delta-reports/quarterly?cycle_id=${encodeURIComponent(t)}`,bs(n));function EC({data:t}){const n=[...t].sort((o,c)=>o.rank-c.rank),a=Math.max(1e-9,...n.map(o=>Math.abs(o.prcc_value)));return e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:n.map(o=>{const c=Math.abs(o.prcc_value)/a*100,u=o.prcc_value>=0;return e.jsxs("div",{style:{fontSize:13},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:2},children:[e.jsxs("span",{style:{color:"#333"},children:["#",o.rank," ",o.variable_name]}),e.jsxs("span",{style:{color:"#888",fontFamily:"ui-monospace, monospace"},children:["PRCC ",o.prcc_value.toFixed(2)," · IRR ",o.irr_impact_low_percent.toFixed(1),"%…",o.irr_impact_high_percent.toFixed(1),"%"]})]}),e.jsx("div",{style:{background:"#f0f0f0",borderRadius:6,height:14,overflow:"hidden"},children:e.jsx("div",{style:{width:`${c}%`,height:"100%",background:u?"#1e7e34":"#b3261e"}})})]},o.variable_name)})})}function AC({tier:t="1"}){const[n,a]=i.useState("2025-Q1"),[o,c]=i.useState([]),[u,h]=i.useState([]),[m,x]=i.useState(""),[v,N]=i.useState(!1),[j,w]=i.useState(""),[_,S]=i.useState(null),[y,g]=i.useState(null),[p,k]=i.useState(null),R=`${n}|${t}`,C=p===R?"error":y!==R?"loading":o.length===0?"empty":"ok",E=i.useCallback(async()=>{const[{models:O},L]=await Promise.all([pC(n,t),jC(n,t)]);return{ms:O,elig:L.eligible}},[n,t]),P=i.useCallback(({ms:O,elig:L})=>{c(O),h(L),x(z=>{var Y;return z&&L.some(G=>G.hs6_code===z)?z:((Y=L[0])==null?void 0:Y.hs6_code)??""}),w(""),g(R),k(null)},[R]),F=i.useCallback(O=>{w(O instanceof Error?O.message:"Unknown error"),k(R),g(null)},[R]),I=i.useCallback(()=>(g(null),k(null),E().then(P,F)),[E,P,F]);i.useEffect(()=>{let O=!0;return E().then(L=>{O&&P(L)},L=>{O&&F(L)}),()=>{O=!1}},[E,P,F]);const M=i.useCallback(async()=>{if(m){N(!0),w("");try{const O=await xC({hs6_code:m,cycle_id:n},t);S(O),await I()}catch(O){w(O instanceof Error?O.message:"Generate failed")}finally{N(!1)}}},[m,n,t,I]),$=i.useCallback(async O=>{w("");try{S(await gC(O,t))}catch(L){w(L instanceof Error?L.message:"Could not load model")}},[t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Financial Models",description:"Generate & inspect per-HS6 financial models (CAPEX, IRR, Monte Carlo)",actions:e.jsxs(e.Fragment,{children:[e.jsx(me,{value:n,onChange:O=>a(O.target.value),placeholder:"2025-Q1","aria-label":"Cycle",className:"w-30"}),e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void I(),children:"Reload"})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Eligible HS6",e.jsxs(Ie,{value:m,onChange:O=>x(O.target.value),"aria-label":"Eligible HS6",className:"min-w-80",children:[u.length===0&&e.jsx("option",{value:"",children:"No eligible HS6 for this cycle"}),u.map(O=>e.jsxs("option",{value:O.hs6_code,children:[O.hs6_code," · ",O.product_name_en," (CAS ",O.cas_score,", #",O.rank,")"]},O.hs6_code))]})]}),e.jsx(K,{onClick:()=>void M(),disabled:v||!m,size:"sm",children:v?"Generating…":"Generate model"})]})}),C==="loading"&&e.jsx(H,{children:"Loading financial models…"}),C==="error"&&e.jsxs(H,{tone:"error",children:[j,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void I(),size:"sm",children:"Retry"})})]}),C==="empty"&&e.jsxs(H,{children:["No models generated for cycle ",e.jsx("code",{children:n}),". Pick an eligible HS6 above and click ",e.jsx("em",{children:"Generate model"}),"."]}),j&&C==="ok"&&e.jsx(H,{tone:"error",children:j}),C==="ok"&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Models · cycle ",n," (",o.length,")"]}),e.jsxs(je,{className:"min-w-[720px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Product"}),e.jsx(T,{children:"Status"}),e.jsx(T,{className:"text-right",children:"CAPEX"}),e.jsx(T,{className:"text-right",children:"IRR"}),e.jsx(T,{className:"text-right",children:"Payback"}),e.jsx(T,{children:"Confidence"})]})}),e.jsx(ye,{children:o.map(O=>e.jsxs(ee,{onClick:()=>void $(O.job_id),className:`cursor-pointer${(_==null?void 0:_.job_id)===O.job_id?" bg-muted":""}`,children:[e.jsx(A,{className:"font-mono text-xs",children:O.hs6_code}),e.jsx(A,{children:O.product_name_en}),e.jsx(A,{children:e.jsx(V,{variant:O.status==="COMPLETE"?"success":O.status==="FAILED"?"danger":"warning",children:O.status})}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(O.capex_usd_total)}),e.jsxs(A,{className:"text-right tabular-nums",children:[O.irr_percent.toFixed(1),"%"]}),e.jsxs(A,{className:"text-right tabular-nums",children:[O.payback_period_years.toFixed(1)," yr"]}),e.jsx(A,{children:e.jsx(V,{variant:O.model_confidence_flag==="OK"?"success":"warning",children:O.model_confidence_flag})})]},O.job_id))})]})]}),_&&e.jsx(RC,{model:_,tier:t})]})]})}function RC({model:t,tier:n}){const[a,o]=i.useState(null),[c,u]=i.useState(null),[h,m]=i.useState("10000"),[x,v]=i.useState(""),[N,j]=i.useState(!1),[w,_]=i.useState(!1),[S,y]=i.useState(""),g=[1,2,3,4,5],p=P=>t[`revenue_usd_annual_year${P}`],k=P=>t[`opex_usd_annual_year${P}`],R=t.capex_breakdown,C=i.useCallback(async()=>{j(!0),y("");try{const P={iteration_count:Number(h)||1e4};x.trim()!==""&&(P.seed=Number(x)),o(await yC(t.job_id,P,n))}catch(P){y(P instanceof Error?P.message:"Monte Carlo failed")}finally{j(!1)}},[h,x,t.job_id,n]),E=i.useCallback(async()=>{_(!0),y("");try{u(await vC(t.job_id,n))}catch(P){y(P instanceof Error?P.message:"Document fetch failed")}finally{_(!1)}},[t.job_id,n]);return e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{className:"text-base font-semibold",children:[t.hs6_code," · ",t.product_name_en]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(V,{variant:t.status==="COMPLETE"?"success":"warning",children:t.status}),e.jsx(V,{variant:t.model_confidence_flag==="OK"?"success":"warning",children:t.model_confidence_flag}),t.daps_protection_flag&&e.jsxs(V,{variant:"warning",children:["DAPS ",t.daps_duty_rate_percent,"%"]}),t.equity_structure.fifty_one_forty_nine_flag&&e.jsx(V,{variant:"secondary",children:"51/49"})]})]}),e.jsxs("section",{className:"my-3 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"CAPEX total",value:Xe(t.capex_usd_total)}),e.jsx(ze,{label:"IRR",value:`${t.irr_percent.toFixed(1)}%`}),e.jsx(ze,{label:"Payback",value:`${t.payback_period_years.toFixed(1)} yr`}),e.jsx(ze,{label:"WACC",value:`${t.wacc_assumption_percent.toFixed(1)}%`}),e.jsx(ze,{label:"Citations",value:String(t.source_citations.length)})]}),e.jsx("h3",{className:"my-2 text-sm font-semibold",children:"5-year pro-forma (USD)"}),e.jsxs(je,{className:"min-w-[560px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Line"}),g.map(P=>e.jsxs(T,{className:"text-right",children:["Year ",P]},P))]})}),e.jsxs(ye,{children:[e.jsxs(ee,{children:[e.jsx(A,{children:"Revenue"}),g.map(P=>e.jsx(A,{className:"text-right tabular-nums",children:Xe(p(P))},P))]}),e.jsxs(ee,{children:[e.jsx(A,{children:"OPEX"}),g.map(P=>e.jsxs(A,{className:"text-right tabular-nums",children:["(",Xe(k(P)),")"]},P))]}),e.jsxs(ee,{className:"font-bold",children:[e.jsx(A,{children:"EBITDA (implied)"}),g.map(P=>e.jsx(A,{className:"text-right tabular-nums",children:Xe(p(P)-k(P))},P))]})]})]}),e.jsx("h3",{className:"mb-2 mt-4 text-sm font-semibold",children:"CAPEX breakdown"}),e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsx(ue,{label:"Civil works",value:Xe(R.civil_works_usd)}),e.jsx(ue,{label:"Machinery & equipment",value:Xe(R.machinery_equipment_usd)}),e.jsx(ue,{label:"Installation & commissioning",value:Xe(R.installation_commissioning_usd)}),e.jsx(ue,{label:"Working capital",value:Xe(R.working_capital_usd)}),e.jsx(ue,{label:"Contingency",value:Xe(R.contingency_usd)})]}),e.jsx("h3",{className:"mb-2 mt-4 text-sm font-semibold",children:"Regulatory & equity"}),e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsx(ue,{label:"DAPS protection",value:t.daps_protection_flag?`Yes (${t.daps_duty_rate_percent}%)`:"No",tone:t.daps_protection_flag?"ok":void 0}),e.jsx(ue,{label:"51/49 rule",value:t.equity_structure.fifty_one_forty_nine_flag?"Applies":"Does not apply"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.equity_structure.irr_impact_note}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.revenue_sensitivity_note}),t.data_quality_warnings.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs("h3",{className:"my-2 text-sm font-semibold",children:["Data-quality warnings (",t.data_quality_warnings.length,")"]}),t.data_quality_warnings.map((P,F)=>e.jsxs("div",{className:"mb-1 text-sm",children:[e.jsx(V,{variant:"warning",children:P.confidence_tier})," ",e.jsx("strong",{children:P.field})," — ",P.recommended_review_note]},`${P.field}-${F}`))]}),S&&e.jsx(H,{tone:"error",children:S}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-end gap-3",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Iterations",e.jsx(me,{value:h,onChange:P=>m(P.target.value),className:"w-25"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Seed (optional)",e.jsx(me,{value:x,onChange:P=>v(P.target.value),placeholder:"—",className:"w-25"})]}),e.jsx(K,{onClick:()=>void C(),disabled:N,size:"sm",children:N?"Running…":"Run Monte Carlo"}),e.jsx(K,{variant:"outline",onClick:()=>void E(),disabled:w,size:"sm",children:w?"Loading…":"View document"})]}),a&&e.jsx(PC,{run:a}),c&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"my-2 text-sm font-semibold",children:["Document ",c.watermarked&&e.jsx(V,{variant:"warning",children:"watermarked"})," ",e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:c.document_integrity_hash})]}),c.sections.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sections: ",c.sections.join(" · ")]}),e.jsx(_i,{className:"mt-1",children:c.content})]})]})})}function PC({run:t}){const n=t.irr_distribution,a=t.payback_distribution;return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"my-2 text-sm font-semibold",children:["Monte Carlo · ",t.iteration_count.toLocaleString("en-US")," iterations · seed ",t.seed_value,t.custom_scenario_flag&&e.jsxs(e.Fragment,{children:[" ",e.jsx(V,{variant:"secondary",children:"custom scenario"})]})]}),e.jsxs("div",{className:"mb-3 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"IRR P10",value:`${n.p10_percent.toFixed(1)}%`}),e.jsx(ze,{label:"IRR P50",value:`${n.p50_percent.toFixed(1)}%`}),e.jsx(ze,{label:"IRR P90",value:`${n.p90_percent.toFixed(1)}%`}),e.jsx(ze,{label:"Payback P50",value:`${a.p50_years.toFixed(1)} yr`})]}),t.irr_local_majority_partner&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["IRR (local majority partner): P10 ",t.irr_local_majority_partner.p10_percent.toFixed(1),"% · P50 ",t.irr_local_majority_partner.p50_percent.toFixed(1),"% · P90 ",t.irr_local_majority_partner.p90_percent.toFixed(1),"%"]}),e.jsx("h4",{className:"mb-2 mt-3 text-sm font-medium",children:"Tornado — sensitivity ranking"}),e.jsx(EC,{data:t.tornado_chart_data}),t.downside_risk_note&&e.jsxs("p",{className:"mt-3 text-sm text-warning",children:[t.downside_risk_note,t.capital_at_risk_dzd_estimate!==null&&e.jsxs(e.Fragment,{children:[" · Capital at risk ≈ ",t.capital_at_risk_dzd_estimate.toLocaleString("en-US")," DZD"]})]})]})}const Pu={sector:"",hs4_group:"",capex_bracket_usd:{min:0,max:0},unit_cost_usd:0,unit_of_measure:"",source_citation:"",source_type:"",source_date:"",confidence_tier:"MEDIUM",geographic_reference:""};function TC({tier:t="1"}){const[n,a]=i.useState({}),[o,c]=i.useState([]),[u,h]=i.useState(0),[m,x]=i.useState(""),[v,N]=i.useState(Pu),[j,w]=i.useState(null),[_,S]=i.useState(!1),[y,g]=i.useState(null),[p,k]=i.useState(null),[R,C]=i.useState(null),E=`${n.sector??""}|${n.is_active??""}|${t}`,P=R===E?"error":p===E?o.length===0?"empty":"ok":"loading",F=i.useCallback(async()=>{const{records:G,total:U}=await _C(n,t);return{rs:G,t:U}},[n,t]),I=i.useCallback(G=>{c(G.rs),h(G.t),x(""),k(E),C(null)},[E]),M=i.useCallback(G=>{x(G instanceof Error?G.message:"Unknown error"),C(E),k(null)},[E]);i.useEffect(()=>{let G=!0;return F().then(U=>{G&&I(U)},U=>{G&&M(U)}),()=>{G=!1}},[F,I,M]);const $=i.useCallback(()=>(k(null),C(null),x(""),F().then(I,M)),[F,I,M]),O=i.useCallback(async()=>{S(!0),x("");try{j?await NC(j.benchmark_record_id,v,t):await bC(v,t),N(Pu),w(null),await $()}catch(G){x(G instanceof Error?G.message:"Save failed")}finally{S(!1)}},[v,j,t,$]),L=i.useCallback(G=>{w(G),N({sector:G.sector,hs4_group:G.hs4_group,capex_bracket_usd:{...G.capex_bracket_usd},unit_cost_usd:G.unit_cost_usd,unit_of_measure:G.unit_of_measure,source_citation:G.source_citation,source_type:G.source_type,source_date:G.source_date,confidence_tier:G.confidence_tier,geographic_reference:G.geographic_reference}),window.scrollTo({top:0,behavior:"smooth"})},[]),z=i.useCallback(async G=>{x("");try{const{history:U}=await wC(G.benchmark_record_id,t);g({id:G.benchmark_record_id,chain:U})}catch(U){x(U instanceof Error?U.message:"History fetch failed")}},[t]),Y=(G,U)=>N(ae=>({...ae,[G]:U}));return e.jsxs("div",{children:[e.jsx(Se,{title:"CAPEX Benchmark",description:"Register of unit-cost benchmarks used by the modeling engine · immutable versioning"}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:j?`New version of ${j.benchmark_record_id} (v${j.version})`:"Create benchmark"}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(_s,{label:"Sector",children:e.jsx(me,{value:v.sector,onChange:G=>Y("sector",G.target.value),className:"w-44"})}),e.jsx(_s,{label:"HS4 group",children:e.jsx(me,{value:v.hs4_group,onChange:G=>Y("hs4_group",G.target.value),className:"w-24"})}),e.jsx(_s,{label:"Bracket min",children:e.jsx(me,{value:String(v.capex_bracket_usd.min),onChange:G=>Y("capex_bracket_usd",{...v.capex_bracket_usd,min:Number(G.target.value)||0}),className:"w-28"})}),e.jsx(_s,{label:"Bracket max",children:e.jsx(me,{value:String(v.capex_bracket_usd.max),onChange:G=>Y("capex_bracket_usd",{...v.capex_bracket_usd,max:Number(G.target.value)||0}),className:"w-28"})}),e.jsx(_s,{label:"Unit cost USD",children:e.jsx(me,{value:String(v.unit_cost_usd),onChange:G=>Y("unit_cost_usd",Number(G.target.value)||0),className:"w-28"})}),e.jsx(_s,{label:"Unit of measure",children:e.jsx(me,{value:v.unit_of_measure,onChange:G=>Y("unit_of_measure",G.target.value),placeholder:"per tonne",className:"w-44"})}),e.jsx(_s,{label:"Geographic ref",children:e.jsx(me,{value:v.geographic_reference,onChange:G=>Y("geographic_reference",G.target.value),placeholder:"DZ",className:"w-24"})}),e.jsx(_s,{label:"Source citation",children:e.jsx(me,{value:v.source_citation,onChange:G=>Y("source_citation",G.target.value),className:"w-44"})}),e.jsx(_s,{label:"Source type",children:e.jsx(me,{value:v.source_type,onChange:G=>Y("source_type",G.target.value),className:"w-30"})}),e.jsx(_s,{label:"Source date",children:e.jsx(me,{value:v.source_date,onChange:G=>Y("source_date",G.target.value),placeholder:"2025-01-01",className:"w-30"})}),e.jsx(_s,{label:"Confidence",children:e.jsxs(Ie,{value:v.confidence_tier,onChange:G=>Y("confidence_tier",G.target.value),"aria-label":"Confidence tier",children:[e.jsx("option",{value:"HIGH",children:"HIGH"}),e.jsx("option",{value:"MEDIUM",children:"MEDIUM"}),e.jsx("option",{value:"LOW",children:"LOW"})]})}),e.jsx(K,{onClick:()=>void O(),disabled:_,size:"sm",children:_?"Saving…":j?"Save new version":"Create"}),j&&e.jsx(K,{variant:"outline",onClick:()=>{w(null),N(Pu)},size:"sm",children:"Cancel"})]})]}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(_s,{label:"Sector filter",children:e.jsx(me,{value:n.sector??"",onChange:G=>a(U=>({...U,sector:G.target.value})),className:"w-44"})}),e.jsx(_s,{label:"Active",children:e.jsxs(Ie,{value:n.is_active??"",onChange:G=>a(U=>({...U,is_active:G.target.value})),"aria-label":"Active filter",children:[e.jsx("option",{value:"",children:"Any"}),e.jsx("option",{value:"true",children:"Active"}),e.jsx("option",{value:"false",children:"Superseded"})]})}),e.jsx(K,{variant:"outline",onClick:()=>a({}),size:"sm",children:"Clear"})]})}),P==="loading"&&e.jsx(H,{children:"Loading benchmarks…"}),P==="error"&&e.jsxs(H,{tone:"error",children:[m,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void $(),size:"sm",children:"Retry"})})]}),P==="empty"&&e.jsx(H,{children:"No benchmarks match these filters. Create one above."}),m&&P==="ok"&&e.jsx(H,{tone:"error",children:m}),P==="ok"&&e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Benchmarks (",u,")"]}),e.jsxs(je,{className:"min-w-[820px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Sector"}),e.jsx(T,{children:"HS4"}),e.jsx(T,{className:"text-right",children:"Unit cost"}),e.jsx(T,{children:"UoM"}),e.jsx(T,{children:"Confidence"}),e.jsx(T,{className:"text-right",children:"Ver"}),e.jsx(T,{children:"Active"}),e.jsx(T,{children:"Actions"})]})}),e.jsx(ye,{children:o.map(G=>e.jsxs(ee,{children:[e.jsx(A,{children:G.sector}),e.jsx(A,{className:"font-mono text-xs",children:G.hs4_group}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(G.unit_cost_usd)}),e.jsx(A,{children:G.unit_of_measure}),e.jsx(A,{children:e.jsx(V,{variant:G.confidence_tier==="HIGH"?"success":G.confidence_tier==="LOW"?"danger":"warning",children:G.confidence_tier})}),e.jsx(A,{className:"text-right tabular-nums",children:G.version}),e.jsx(A,{children:G.is_active?e.jsx(V,{variant:"success",children:"active"}):e.jsx(V,{variant:"secondary",children:"superseded"})}),e.jsx(A,{children:e.jsxs("div",{className:"flex gap-1.5",children:[G.is_active&&e.jsx(K,{variant:"outline",size:"xs",onClick:()=>L(G),children:"New version"}),e.jsx(K,{variant:"outline",size:"xs",onClick:()=>void z(G),children:"History"})]})})]},G.benchmark_record_id))})]})]}),y&&e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("div",{className:"flex items-center justify-between px-4",children:[e.jsxs("h2",{className:"text-base font-semibold",children:["Version chain · ",y.id]}),e.jsx(K,{variant:"outline",size:"xs",onClick:()=>g(null),children:"Close"})]}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Ver"}),e.jsx(T,{className:"text-right",children:"Unit cost"}),e.jsx(T,{children:"Confidence"}),e.jsx(T,{children:"Active"}),e.jsx(T,{children:"Supersedes"}),e.jsx(T,{children:"Created"})]})}),e.jsx(ye,{children:y.chain.map(G=>e.jsxs(ee,{children:[e.jsx(A,{children:G.version}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(G.unit_cost_usd)}),e.jsx(A,{children:e.jsx(V,{variant:G.confidence_tier==="HIGH"?"success":G.confidence_tier==="LOW"?"danger":"warning",children:G.confidence_tier})}),e.jsx(A,{children:G.is_active?e.jsx(V,{variant:"success",children:"active"}):e.jsx(V,{variant:"secondary",children:"superseded"})}),e.jsx(A,{className:"font-mono text-xs",children:G.supersedes_benchmark_id??"—"}),e.jsx(A,{className:"text-xs text-muted-foreground",children:G.created_at})]},G.benchmark_record_id+G.version))})]})]})]})}function _s({label:t,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:[t,n]})}function LC({status:t,blocking:n}){return e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(V,{variant:t==="PASS"?"success":"danger-solid",children:t}),n&&e.jsx(V,{variant:"warning",children:"BLOCKING PIPELINE"})]})}function FC({tier:t="1"}){const[n,a]=i.useState("2025-Q1"),[o,c]=i.useState([]),[u,h]=i.useState(!1),[m,x]=i.useState(""),[v,N]=i.useState(null),[j,w]=i.useState(null),_=`${t}|${n}`,S=j===_?"error":v===_?o.length===0?"empty":"ok":"loading",y=i.useCallback(async()=>{const{reports:C}=await CC(n,t);return C},[n,t]),g=i.useCallback(C=>{c(C),x(""),N(_),w(null)},[_]),p=i.useCallback(C=>{x(C instanceof Error?C.message:"Unknown error"),w(_),N(null)},[_]);i.useEffect(()=>{let C=!0;return y().then(E=>{C&&g(E)},E=>{C&&p(E)}),()=>{C=!1}},[y,g,p]);const k=i.useCallback(()=>(N(null),w(null),y().then(g,p)),[y,g,p]),R=i.useCallback(async()=>{h(!0),x("");try{await SC({cycle_id:n},t),await k()}catch(C){x(C instanceof Error?C.message:"Validation failed")}finally{h(!1)}},[n,t,k]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Model Validation",description:"Benchmark-validate generated models; FAIL can block the pipeline",actions:e.jsxs(e.Fragment,{children:[e.jsx(me,{value:n,onChange:C=>a(C.target.value),placeholder:"2025-Q1","aria-label":"Cycle",className:"w-30"}),e.jsx(K,{onClick:()=>void R(),disabled:u,size:"sm",children:u?"Validating…":"Run validation"})]})}),S==="loading"&&e.jsx(H,{children:"Loading validation reports…"}),S==="error"&&e.jsxs(H,{tone:"error",children:[m,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void k(),size:"sm",children:"Retry"})})]}),S==="empty"&&e.jsxs(H,{children:["No validation reports for cycle ",e.jsx("code",{children:n}),". Click ",e.jsx("em",{children:"Run validation"}),"."]}),m&&S==="ok"&&e.jsx(H,{tone:"error",children:m}),S==="ok"&&o.map(C=>e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4",children:[e.jsxs("h2",{className:"text-base font-semibold",children:["Report ",C.report_id," · ",C.validation_timestamp]}),e.jsx(LC,{status:C.overall_validation_status,blocking:C.blocking_pipeline})]}),e.jsxs(je,{className:"min-w-[760px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{className:"text-right",children:"Gen IRR"}),e.jsx(T,{className:"text-right",children:"Bench IRR"}),e.jsx(T,{className:"text-right",children:"Δ IRR"}),e.jsx(T,{className:"text-right",children:"Gen PB"}),e.jsx(T,{className:"text-right",children:"Bench PB"}),e.jsx(T,{className:"text-right",children:"Δ PB%"}),e.jsx(T,{children:"Status"})]})}),e.jsx(ye,{children:C.per_sector_results.map(E=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:E.hs6_code}),e.jsxs(A,{className:"text-right tabular-nums",children:[E.generated_irr_percent.toFixed(1),"%"]}),e.jsxs(A,{className:"text-right tabular-nums",children:[E.benchmark_irr_percent.toFixed(1),"%"]}),e.jsxs(A,{className:"text-right tabular-nums",children:[E.deviation_irr_percent.toFixed(1),"%"]}),e.jsx(A,{className:"text-right tabular-nums",children:E.generated_payback_years.toFixed(1)}),e.jsx(A,{className:"text-right tabular-nums",children:E.benchmark_payback_years.toFixed(1)}),e.jsxs(A,{className:"text-right tabular-nums",children:[E.deviation_payback_percent.toFixed(1),"%"]}),e.jsx(A,{children:e.jsx(V,{variant:E.sector_status==="PASS"?"success":"danger",children:E.sector_status})})]},E.hs6_code))})]}),e.jsxs("p",{className:"px-4 text-xs text-muted-foreground",children:["Benchmark model versions: ",Object.entries(C.benchmark_model_versions_used).map(([E,P])=>`${E}=v${P}`).join(" · ")||"—"]})]},C.report_id))]})}function DC({tier:t="1"}){const[n,a]=i.useState("2025-Q1"),[o,c]=i.useState(null),[u,h]=i.useState(""),[m,x]=i.useState(null),[v,N]=i.useState(null),j=`${n}|${t}`,w=v===j?"error":m!==j?"loading":"ok",_=i.useCallback(async()=>await kC(n,t),[n,t]),S=i.useCallback(p=>{c(p),x(j),N(null)},[j]),y=i.useCallback(p=>{h(p instanceof Error?p.message:"Unknown error"),N(j),x(null)},[j]),g=i.useCallback(()=>(x(null),N(null),_().then(S,y)),[_,S,y]);return i.useEffect(()=>{let p=!0;return _().then(k=>{p&&S(k)},k=>{p&&y(k)}),()=>{p=!1}},[_,S,y]),e.jsxs("div",{children:[e.jsx(Se,{title:"Financial Delta",description:"Quarter-over-quarter movements in the financial-model set",actions:e.jsxs(e.Fragment,{children:[e.jsx(me,{value:n,onChange:p=>a(p.target.value),placeholder:"2025-Q1","aria-label":"Cycle",className:"w-30"}),e.jsx(K,{onClick:()=>void g(),size:"sm",children:"Load"})]})}),w==="loading"&&e.jsx(H,{children:"Loading delta report…"}),w==="error"&&e.jsxs(H,{tone:"error",children:[u,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void g(),size:"sm",children:"Retry"})})]}),w==="ok"&&o&&e.jsxs(e.Fragment,{children:[o.is_first_cycle&&e.jsxs(H,{children:[e.jsx("strong",{children:"First cycle."})," No prior cycle to compare against (",o.previous_cycle_id??"none","); all sections are empty by design."]}),e.jsxs("section",{className:"my-4 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"New entrants",value:String(o.new_entrants.length),tone:"ok"}),e.jsx(ze,{label:"Exits",value:String(o.exits.length),tone:o.exits.length>0?"warn":void 0}),e.jsx(ze,{label:"CAS moves",value:String(o.cas_score_movements.length)}),e.jsx(ze,{label:"IRR changes",value:String(o.irr_changes.length)}),e.jsx(ze,{label:"Payback changes",value:String(o.payback_changes.length)}),e.jsx(ze,{label:"DAPS changes",value:String(o.daps_changes.length),tone:o.daps_changes.length>0?"warn":void 0})]}),o.metadata.data_integrity_warnings.length>0&&e.jsxs(H,{tone:"error",children:[e.jsxs("strong",{children:["Data-integrity warnings (",o.metadata.data_integrity_warnings.length,")"]}),e.jsx("ul",{className:"mt-2 pl-[18px]",children:o.metadata.data_integrity_warnings.map((p,k)=>e.jsx("li",{className:"text-sm",children:p},k))})]}),e.jsxs("p",{className:"my-3 text-xs text-muted-foreground",children:["Report ",o.delta_report_id," · cycle ",o.cycle_id," · prev ",o.previous_cycle_id??"—"," · computed ",o.computed_at]}),e.jsx(rl,{title:"New entrants",rows:o.new_entrants}),e.jsx(rl,{title:"Exits",rows:o.exits}),e.jsx(rl,{title:"CAS score movements",rows:o.cas_score_movements}),e.jsx(rl,{title:"IRR changes",rows:o.irr_changes}),e.jsx(rl,{title:"Payback changes",rows:o.payback_changes}),e.jsx(rl,{title:"DAPS changes",rows:o.daps_changes})]})]})}function rl({title:t,rows:n}){const a=n.length>0?Object.keys(n[0]):[];return e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:[t," ",e.jsx(V,{variant:"secondary",children:n.length})]}),n.length===0?e.jsx("p",{className:"px-4 text-sm text-muted-foreground",children:"No changes."}):e.jsxs(je,{className:"min-w-[480px]",children:[e.jsx(_e,{children:e.jsx(ee,{children:a.map(o=>e.jsx(T,{children:o},o))})}),e.jsx(ye,{children:n.map((o,c)=>e.jsx(ee,{children:a.map(u=>e.jsx(A,{children:$C(o[u])},u))},c))})]})]})}function $C(t){return t==null?"—":typeof t=="object"?JSON.stringify(t):String(t)}const bl=t=>({"x-subscriber-tier":t}),IC=(t,n,a)=>be(`/v1/bom/generate/${encodeURIComponent(t)}`,{pipeline_run_id:n},bl(a)),MC=(t,n,a)=>he(`/v1/bom/${encodeURIComponent(t)}/current?pipeline_run_id=${encodeURIComponent(n)}`,bl(a)),OC=(t,n,a,o)=>be(`/v1/bom/${encodeURIComponent(t)}/cif-compute`,{pipeline_run_id:n,destination_port:a},bl(o)),zC=(t,n,a)=>{const o=new URLSearchParams;return o.set("equipment_category",n.equipment_category),n.supplier_tier&&o.set("supplier_tier",n.supplier_tier),o.set("pipeline_run_id",n.pipeline_run_id),he(`/v1/bom/${encodeURIComponent(t)}/supplier-alternatives?${o.toString()}`,bl(a))},UC=(t,n)=>be("/v1/bom/suppliers/ingest",{pipeline_run_id:t},bl(n)),BC=(t,n)=>he(`/v1/bom/suppliers/coverage-report?pipeline_run_id=${encodeURIComponent(t)}`,bl(n)),HC=["CN_TR","EU","DE_IT_JP"],ym=t=>t==null?"—":`${t.toFixed(1)}%`;function VC({tier:t="1"}){const[n,a]=i.useState("empty"),[o,c]=i.useState("2025-Q1"),[u,h]=i.useState("294200"),[m,x]=i.useState(null),[v,N]=i.useState(!1),[j,w]=i.useState(""),_=i.useCallback(async()=>{N(!0),a("loading"),w("");try{const y=await IC(u,o,t);x(y),a("ok")}catch(y){w(y instanceof Error?y.message:"Generate failed"),a("error")}finally{N(!1)}},[u,o,t]),S=i.useCallback(async()=>{N(!0),a("loading"),w("");try{const y=await MC(u,o,t);x(y),a("ok")}catch(y){const g=y instanceof Error?y.message:"Reload failed";/404|not found/i.test(g)?(x(null),a("empty")):(w(g),a("error"))}finally{N(!1)}},[u,o,t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"BoM Generation",description:"Generate & inspect the three-tier equipment Bill of Materials per HS6"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Cycle / pipeline run",e.jsx(me,{value:o,onChange:y=>c(y.target.value),placeholder:"2025-Q1",className:"w-35"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["HS6",e.jsx(me,{value:u,onChange:y=>h(y.target.value),placeholder:"294200",className:"w-35"})]}),e.jsx(K,{onClick:()=>void _(),disabled:v||!u,size:"sm",children:v?"Working…":"Generate BoM"}),e.jsx(K,{variant:"outline",onClick:()=>void S(),disabled:v||!u,size:"sm",children:"Reload"})]})}),n==="loading"&&e.jsx(H,{children:"Generating three-tier BoM…"}),n==="error"&&e.jsxs(H,{tone:"error",children:[j,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void S(),size:"sm",children:"Retry"})})]}),n==="empty"&&e.jsxs(H,{children:["No BoM for HS6 ",e.jsx("code",{children:u})," in run ",e.jsx("code",{children:o})," yet. Click ",e.jsx("em",{children:"Generate BoM"})," to build one."]}),n==="ok"&&m&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4",children:[e.jsxs("h2",{className:"text-base font-semibold",children:[m.hs6_code," · ",m.product_name.en]}),e.jsx(V,{variant:m.status==="COMPLETE"?"success":m.status==="FAILED"?"danger":"warning",children:m.status})]}),e.jsxs("h3",{className:"px-4 text-sm font-semibold",children:["CAPEX reconciliation (tolerance ",m.reconciliation.tolerance_pct,"%)"]}),e.jsxs(je,{className:"min-w-[560px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Tier"}),e.jsx(T,{className:"text-right",children:"BoM CAPEX"}),e.jsx(T,{className:"text-right",children:"Model CAPEX"}),e.jsx(T,{className:"text-right",children:"Deviation"}),e.jsx(T,{children:"Status"})]})}),e.jsx(ye,{children:Object.entries(m.reconciliation.per_tier).map(([y,g])=>e.jsx(GC,{tierKey:y,recon:g},y))})]})]}),HC.map(y=>e.jsx(WC,{tierKey:y,out:m.tiers[y]},y))]})]})}function GC({tierKey:t,recon:n}){const a=n.status==="PASS";return e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:n.supplier_tier??t}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(n.bom_capex_usd)}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(n.model_capex_usd)}),e.jsx(A,{className:"text-right tabular-nums",children:ym(n.deviation_pct)}),e.jsx(A,{children:e.jsx(V,{variant:a?"success":"danger",children:a?"PASS":"FAIL"})})]})}function WC({tierKey:t,out:n}){return e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4",children:[e.jsxs("h2",{className:"text-base font-semibold",children:[t," · ",n.supplier_tier," (",n.summary_totals.total_items_count," items)"]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(V,{variant:n.status==="COMPLETE"?"success":"warning",children:n.status}),e.jsxs(V,{variant:"secondary",children:["landed ",Xe(n.summary_totals.total_landed_usd)]})]})]}),e.jsxs(je,{className:"min-w-[820px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Category"}),e.jsx(T,{children:"Supplier"}),e.jsx(T,{className:"text-right",children:"FOB Oran"}),e.jsx(T,{className:"text-right",children:"CIF Algiers"}),e.jsx(T,{className:"text-right",children:"Landed"}),e.jsx(T,{className:"text-right",children:"TDA duty"}),e.jsx(T,{className:"text-right",children:"DAPS"}),e.jsx(T,{className:"text-right",children:"Lead (wk)"}),e.jsx(T,{children:"Coverage"})]})}),e.jsxs(ye,{children:[n.equipment_line_items.map((a,o)=>e.jsxs(ee,{children:[e.jsx(A,{children:a.equipment_category}),e.jsx(A,{children:a.supplier_name??"—"}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(a.fob_oran_usd)}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(a.cif_algiers_usd)}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(a.landed_cost_usd)}),e.jsx(A,{className:"text-right tabular-nums",children:ym(a.tda_duty_rate)}),e.jsx(A,{className:"text-right tabular-nums",children:ym(a.daps_rate)}),e.jsx(A,{className:"text-right tabular-nums",children:a.lead_time_weeks==null?"—":a.lead_time_weeks}),e.jsx(A,{children:a.coverage_flag?e.jsx(V,{variant:"warning",children:a.coverage_flag}):e.jsx(V,{variant:"success",children:"OK"})})]},`${a.equipment_category}-${a.hs6_equipment_code}-${o}`)),n.equipment_line_items.length===0&&e.jsx(ee,{children:e.jsx(A,{colSpan:9,className:"text-muted-foreground",children:"No line items for this tier."})})]})]})]})}function qC({tier:t="admin"}){const[n,a]=i.useState("2025-Q1"),[o,c]=i.useState(null),[u,h]=i.useState(null),[m,x]=i.useState(!1),[v,N]=i.useState(""),[j,w]=i.useState(null),[_,S]=i.useState(null),y=`${n}|${t}`,g=_===y?"error":j===y?o!==null&&o.opportunities.length===0?"empty":"ok":"loading",p=i.useCallback(async()=>BC(n,t),[n,t]),k=i.useCallback(P=>{c(P),N(""),w(y),S(null)},[y]),R=i.useCallback(P=>{N(P instanceof Error?P.message:"Unknown error"),S(y),w(null)},[y]),C=i.useCallback(()=>(w(null),S(null),N(""),p().then(k,R)),[p,k,R]);i.useEffect(()=>{let P=!0;return p().then(F=>{P&&k(F)},F=>{P&&R(F)}),()=>{P=!1}},[p,k,R]);const E=i.useCallback(async()=>{x(!0),N("");try{h(await UC(n,t)),await C()}catch(P){N(P instanceof Error?P.message:"Ingest failed")}finally{x(!1)}},[n,t,C]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Supplier Corpus",description:"Seed / re-ingest the supplier corpus and review tier coverage",actions:e.jsxs(e.Fragment,{children:[e.jsx(me,{value:n,onChange:P=>a(P.target.value),placeholder:"2025-Q1","aria-label":"Cycle",className:"w-35"}),e.jsx(K,{variant:"outline",onClick:()=>void C(),size:"sm",children:"Reload"})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-4",children:[e.jsx(K,{onClick:()=>void E(),disabled:m,size:"sm",children:m?"Ingesting…":"Seed / re-ingest corpus"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Runs the supplier connectors for run ",e.jsx("code",{children:n}),"."]})]})}),v&&e.jsx(H,{tone:"error",children:v}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"my-4 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"Staged",value:String(u.staged_count)}),e.jsx(ze,{label:"Promoted",value:String(u.promoted_count),tone:"ok"}),e.jsx(ze,{label:"Rejected",value:String(u.rejected_count),tone:u.rejected_count>0?"warn":void 0}),e.jsx(ze,{label:"Conflicts",value:String(u.conflict_count),tone:u.conflict_count>0?"warn":void 0})]}),u.connector_failures.length>0&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Connector failures (",u.connector_failures.length,")"]}),e.jsx("div",{className:"flex flex-col gap-1 px-4",children:u.connector_failures.map((P,F)=>e.jsxs("div",{className:"text-sm",children:[e.jsx(V,{variant:"danger",children:P.event})," ",e.jsx("strong",{children:P.connector_id})," — ",P.source]},`${P.connector_id}-${F}`))})]})]}),g==="loading"&&e.jsx(H,{children:"Loading coverage report…"}),g==="error"&&e.jsxs(H,{tone:"error",children:[v,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void C(),size:"sm",children:"Retry"})})]}),g==="empty"&&e.jsxs(H,{children:["No coverage opportunities for run ",e.jsx("code",{children:n}),". Seed the corpus above."]}),g==="ok"&&o&&e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Coverage report · cycle ",o.cycle_id," (",o.opportunities.length,")"]}),e.jsxs(je,{className:"min-w-[720px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Per-tier active count"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Below-threshold categories"})]})}),e.jsx(ye,{children:o.opportunities.map(P=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:P.hs6_code}),e.jsx(A,{children:Object.entries(P.per_tier).map(([F,I])=>e.jsxs("span",{className:"mr-2.5",children:[e.jsx("strong",{children:F}),": ",I.active_count," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",I.data_vintage_age_days,"d)"]})]},F))}),e.jsx(A,{children:e.jsx(V,{variant:P.coverage_status==="FULL"?"success":P.coverage_status==="EMPTY"?"danger":"warning",children:P.coverage_status})}),e.jsx(A,{children:P.below_threshold_categories.length>0?P.below_threshold_categories.join(", "):"—"})]},P.hs6_code))})]})]})]})}const QC=["ORAN","ALGIERS","ANNABA","DJEN_DJEN"],mp=t=>t==null?"—":`${t.toFixed(1)}%`;function KC({tier:t="1"}){const[n,a]=i.useState("empty"),[o,c]=i.useState("294200"),[u,h]=i.useState("2025-Q1"),[m,x]=i.useState("ALGIERS"),[v,N]=i.useState(null),[j,w]=i.useState(!1),[_,S]=i.useState(""),y=i.useCallback(async()=>{w(!0),a("loading"),S("");try{const g=await OC(o,u,m,t);N(g),a(Object.keys(g.tiers).length===0?"empty":"ok")}catch(g){S(g instanceof Error?g.message:"Compute failed"),a("error")}finally{w(!1)}},[o,u,m,t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Landed-Cost / CIF",description:"Compute per-tier CIF and landed cost to a destination port"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["HS6",e.jsx(me,{value:o,onChange:g=>c(g.target.value),placeholder:"294200",className:"w-35"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Cycle / pipeline run",e.jsx(me,{value:u,onChange:g=>h(g.target.value),placeholder:"2025-Q1",className:"w-35"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Destination port",e.jsx(Ie,{value:m,onChange:g=>x(g.target.value),"aria-label":"Destination port",className:"min-w-35",children:QC.map(g=>e.jsx("option",{value:g,children:g},g))})]}),e.jsx(K,{onClick:()=>void y(),disabled:j||!o,size:"sm",children:j?"Computing…":"Compute"})]})}),n==="loading"&&e.jsx(H,{children:"Computing CIF & landed cost…"}),n==="error"&&e.jsxs(H,{tone:"error",children:[_,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void y(),size:"sm",children:"Retry"})})]}),n==="empty"&&e.jsxs(H,{children:["Enter an HS6 and port, then click ",e.jsx("em",{children:"Compute"})," to see per-tier landed costs."]}),n==="ok"&&v&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("h2",{className:"px-4 text-base font-semibold",children:[v.hs6_code," · into ",v.destination_port]})}),Object.entries(v.tiers).map(([g,p])=>e.jsx(XC,{tierKey:g,lines:p},g))]})]})}function XC({tierKey:t,lines:n}){return e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:[t," (",n.length," items)"]}),e.jsxs(je,{className:"min-w-[760px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Category"}),e.jsx(T,{className:"text-right",children:"CIF"}),e.jsx(T,{className:"text-right",children:"Landed USD"}),e.jsx(T,{className:"text-right",children:"Landed DZD"}),e.jsx(T,{className:"text-right",children:"TDA duty"}),e.jsx(T,{className:"text-right",children:"DAPS"}),e.jsx(T,{children:"Flags"})]})}),e.jsxs(ye,{children:[n.map((a,o)=>e.jsxs(ee,{children:[e.jsx(A,{children:a.equipment_category}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(a.cif_usd)}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(a.landed_cost_usd)}),e.jsx(A,{className:"text-right tabular-nums",children:a.landed_cost_dzd.toLocaleString("en-US")}),e.jsx(A,{className:"text-right tabular-nums",children:mp(a.tda_duty_rate)}),e.jsx(A,{className:"text-right tabular-nums",children:mp(a.daps_rate)}),e.jsx(A,{children:a.flags.length>0?e.jsx(V,{variant:"warning",children:a.flags.join(", ")}):"—"})]},`${a.equipment_category}-${a.supplier_id}-${o}`)),n.length===0&&e.jsx(ee,{children:e.jsx(A,{colSpan:7,className:"text-muted-foreground",children:"No line items for this tier."})})]})]})]})}const hp=["production_line_machinery","utilities_infrastructure","quality_control_lab","material_handling"],YC=["all","CN_TR","EU","DE_IT_JP"];function ZC({tier:t="1"}){const[n,a]=i.useState("empty"),[o,c]=i.useState("294200"),[u,h]=i.useState("2025-Q1"),[m,x]=i.useState(hp[0]),[v,N]=i.useState("all"),[j,w]=i.useState(null),[_,S]=i.useState(!1),[y,g]=i.useState(""),p=i.useCallback(async()=>{S(!0),a("loading"),g("");try{const k=await zC(o,{equipment_category:m,supplier_tier:v==="all"?void 0:v,pipeline_run_id:u},t);w(k),a(k.alternatives.length===0?"empty":"ok")}catch(k){g(k instanceof Error?k.message:"Lookup failed"),a("error")}finally{S(!1)}},[o,u,m,v,t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Supplier Alternatives",description:"Ranked alternative suppliers per equipment category"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["HS6",e.jsx(me,{value:o,onChange:k=>c(k.target.value),placeholder:"294200",className:"w-32"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Cycle / pipeline run",e.jsx(me,{value:u,onChange:k=>h(k.target.value),placeholder:"2025-Q1",className:"w-32"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Equipment category",e.jsx(Ie,{value:m,onChange:k=>x(k.target.value),"aria-label":"Equipment category",className:"min-w-56",children:hp.map(k=>e.jsx("option",{value:k,children:k},k))})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Supplier tier",e.jsx(Ie,{value:v,onChange:k=>N(k.target.value),"aria-label":"Supplier tier",className:"min-w-30",children:YC.map(k=>e.jsx("option",{value:k,children:k},k))})]}),e.jsx(K,{onClick:()=>void p(),disabled:_||!o,size:"sm",children:_?"Searching…":"Find alternatives"})]})}),n==="loading"&&e.jsx(H,{children:"Finding alternatives…"}),n==="error"&&e.jsxs(H,{tone:"error",children:[y,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void p(),size:"sm",children:"Retry"})})]}),n==="empty"&&e.jsx(H,{children:j?e.jsxs(e.Fragment,{children:["No alternatives found for ",e.jsx("code",{children:m}),"."]}):e.jsxs(e.Fragment,{children:["Pick an equipment category and click ",e.jsx("em",{children:"Find alternatives"}),"."]})}),j&&(n==="ok"||n==="empty")&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{className:"text-base font-semibold",children:[j.hs6_code," · ",j.equipment_category]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(V,{variant:j.single_source_risk_flag?"danger":"success",children:j.single_source_risk_flag?"SINGLE-SOURCE RISK":"multi-source"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[j.returned_count," of ",j.total_available]})]})]}),j.risk_description&&e.jsx("p",{className:"text-sm text-destructive",children:j.risk_description}),j.coverage_warning&&e.jsxs("p",{className:"text-sm text-warning",children:["Coverage warning · tier ",e.jsx("strong",{children:j.coverage_warning.supplier_tier}),":"," ",j.coverage_warning.available," available (minimum ",j.coverage_warning.minimum,", shortfall ",j.coverage_warning.shortfall,")."]})]})}),n==="ok"&&j&&e.jsx(B,{className:"mt-4 overflow-hidden py-0",children:e.jsxs(je,{className:"min-w-[960px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Supplier"}),e.jsx(T,{children:"Origin"}),e.jsx(T,{children:"Tier"}),e.jsx(T,{className:"text-right",children:"FOB"}),e.jsx(T,{className:"text-right",children:"CIF Algiers"}),e.jsx(T,{className:"text-right",children:"Lead (wk)"}),e.jsx(T,{className:"text-right",children:"MOQ"}),e.jsx(T,{children:"Payment"}),e.jsx(T,{children:"Incoterm"}),e.jsx(T,{className:"text-right",children:"Score"}),e.jsx(T,{className:"text-right",children:"DAPS"})]})}),e.jsx(ye,{children:j.alternatives.map(k=>e.jsxs(ee,{children:[e.jsx(A,{children:k.supplier_name}),e.jsx(A,{children:k.country_of_origin}),e.jsx(A,{className:"font-mono text-xs",children:k.supplier_tier}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(k.fob_price_usd)}),e.jsx(A,{className:"text-right tabular-nums",children:Xe(k.cif_algiers_usd)}),e.jsxs(A,{className:"text-right tabular-nums",children:[k.lead_time_weeks,k.lead_time_staleness_flag&&e.jsxs(e.Fragment,{children:[" ",e.jsx(V,{variant:"warning",children:"stale"})]})]}),e.jsx(A,{className:"text-right tabular-nums",children:k.moq}),e.jsx(A,{children:k.payment_terms}),e.jsx(A,{children:k.incoterm}),e.jsx(A,{className:"text-right tabular-nums",children:k.composite_procurement_score.toFixed(3)}),e.jsxs(A,{className:"text-right tabular-nums",children:[k.daps_flag.daps_rate_percent.toFixed(1),"%"]})]},k.supplier_id))})]})})]})}const va=t=>({"x-subscriber-tier":t}),Vj=t=>({"x-user-role":t});function JC(t){const n=new URLSearchParams;for(const[o,c]of Object.entries(t))c==null||c===""||c===!1||n.set(o,String(c));const a=n.toString();return a?`?${a}`:""}const ek=(t,n,a)=>he(`/v1/hs6-lines/${encodeURIComponent(t)}/afcfta-preferential-rates?version=${encodeURIComponent(n)}`,va(a)),tk=(t,n,a)=>he(`/v1/hs6-lines/${encodeURIComponent(t)}/afcfta-preferential-summary?version=${encodeURIComponent(n)}`,va(a)),sk=(t,n,a)=>he(`/v1/hs6-lines/${encodeURIComponent(t)}/afcfta-tam?version=${encodeURIComponent(n)}`,va(a)),nk=(t,n,a)=>he(`/v1/hs6-lines/${encodeURIComponent(t)}/afcfta-headroom?version=${encodeURIComponent(n)}`,va(a)),rk=(t,n)=>he(`/v1/hs6-lines/afcfta-filter${JC(t)}`,va(n)),ak=(t,n)=>be("/v1/subscriber/watchlist",t,va(n)),lk=(t,n)=>he(`/v1/subscriber/watchlist/delta-alerts?subscriber_id=${encodeURIComponent(t)}`,va(n)),ik=(t,n)=>he(`/v1/afcfta/coverage-audit?version=${encodeURIComponent(t)}`,Vj(n)),ok=t=>he("/v1/afcfta/coverage-audit/history",Vj(t)),fp="2025-Q1",Tu=(t,n=2)=>t==null?"—":t.toFixed(n),Lu=t=>t==null?"—":`${t.toFixed(1)}%`;function ck({tier:t="1"}){const[n,a]=i.useState("empty"),[o,c]=i.useState("720839"),[u,h]=i.useState(fp),[m,x]=i.useState(null),[v,N]=i.useState(!1),[j,w]=i.useState(""),_=i.useCallback(async()=>{N(!0),a("loading"),w("");try{const S=await nk(o,u,t);x(S),a("ok")}catch(S){w(S instanceof Error?S.message:"Load failed"),a("error")}finally{N(!1)}},[o,u,t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"AfCFTA Headroom Explorer",description:"Export-market headroom, top markets & source lineage per HS6"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["HS6",e.jsx(me,{value:o,onChange:S=>c(S.target.value),placeholder:"720839",className:"w-35"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Schedule version",e.jsx(me,{value:u,onChange:S=>h(S.target.value),placeholder:fp,className:"w-35"})]}),e.jsx(K,{onClick:()=>void _(),disabled:v||!o,size:"sm",children:v?"Loading…":"Load"})]})}),n==="loading"&&e.jsxs(H,{children:["Loading headroom for ",e.jsx("code",{children:o}),"…"]}),n==="error"&&e.jsxs(H,{tone:"error",children:[j,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void _(),size:"sm",children:"Retry"})})]}),n==="empty"&&e.jsxs(H,{children:["Enter an HS6 and click ",e.jsx("em",{children:"Load"})," to explore its AfCFTA headroom."]}),n==="ok"&&m&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("h2",{className:"text-base font-semibold",children:m.hs6_code}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(V,{variant:"secondary",children:m.confidence_tier}),e.jsxs(V,{variant:"secondary",children:["config ",m.config_version]}),e.jsx(V,{variant:"secondary",children:m.data_environment})]})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-[repeat(auto-fit,minmax(140px,1fr))] gap-4",children:[e.jsx(ue,{label:"Headroom (USD M)",value:Tu(m.headroom_usd_millions)}),e.jsx(ue,{label:"Headroom sub-score",value:Tu(m.headroom_sub_score)}),e.jsx(ue,{label:"Preferential countries",value:m.preferential_country_count}),e.jsx(ue,{label:"Duty-free countries",value:m.duty_free_country_count}),e.jsx(ue,{label:"CAGR (5yr)",value:Lu(m.cagr_5yr)}),e.jsx(ue,{label:"Reference year",value:m.reference_year??"—"})]})]})}),m.flags.length>0&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Flags"}),e.jsx("div",{className:"px-4",children:e.jsx("ul",{className:"pl-[18px]",children:m.flags.map(S=>e.jsxs("li",{className:"mb-1 text-sm",children:[e.jsx("strong",{children:S.flag_code})," — ",S.flag_description,S.affected_countries.length>0&&e.jsxs("span",{className:"text-muted-foreground",children:[" (",S.affected_countries.join(", "),")"]})]},S.flag_code))})})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Top 3 markets"}),e.jsxs(je,{className:"min-w-[620px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Country"}),e.jsx(T,{children:"ISO3"}),e.jsx(T,{className:"text-right",children:"TAM share"}),e.jsx(T,{className:"text-right",children:"TAM (USD M)"}),e.jsx(T,{className:"text-right",children:"Pref. rate"}),e.jsx(T,{children:"Vintage"})]})}),e.jsxs(ye,{children:[m.top_3_markets.map(S=>e.jsxs(ee,{children:[e.jsx(A,{children:S.country_name}),e.jsx(A,{className:"font-mono text-xs",children:S.country_iso3}),e.jsx(A,{className:"text-right tabular-nums",children:Lu(S.tam_share_pct)}),e.jsx(A,{className:"text-right tabular-nums",children:Tu(S.tam_usd_millions)}),e.jsx(A,{className:"text-right tabular-nums",children:Lu(S.preferential_rate)}),e.jsx(A,{children:S.schedule_vintage_date??"—"})]},S.country_iso3)),m.top_3_markets.length===0&&e.jsx(ee,{children:e.jsx(A,{colSpan:6,className:"text-muted-foreground",children:"No markets."})})]})]})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Sources"}),e.jsxs("div",{className:"px-4",children:[e.jsxs("ul",{className:"pl-[18px]",children:[m.sources.map(S=>e.jsxs("li",{className:"mb-1 text-sm",children:[e.jsx("strong",{children:S.source_name??S.source_id}),S.reference_year!=null&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ref ",S.reference_year]}),S.ingestion_timestamp&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ingested ",S.ingestion_timestamp]})]},S.source_id)),m.sources.length===0&&e.jsx("li",{className:"text-sm text-muted-foreground",children:"No sources."})]}),e.jsxs("p",{className:"mb-0 text-xs text-muted-foreground",children:["Generated ",m.generated_at]})]})]})]})]})}const xp="2025-Q1",Fu=t=>t==null?"—":`${t.toFixed(1)}%`;function dk({tier:t="1"}){const[n,a]=i.useState("empty"),[o,c]=i.useState("720839"),[u,h]=i.useState(xp),[m,x]=i.useState(null),[v,N]=i.useState(null),[j,w]=i.useState(!1),[_,S]=i.useState(""),y=i.useCallback(async()=>{w(!0),a("loading"),S("");try{const[g,p]=await Promise.all([ek(o,u,t),tk(o,u,t)]);x(g),N(p),a(g.results.length===0?"empty":"ok")}catch(g){S(g instanceof Error?g.message:"Load failed"),a("error")}finally{w(!1)}},[o,u,t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Preferential Rates",description:"AfCFTA preferential vs MFN tariff rates per HS6"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["HS6",e.jsx(me,{value:o,onChange:g=>c(g.target.value),placeholder:"720839",className:"w-35"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Schedule version",e.jsx(me,{value:u,onChange:g=>h(g.target.value),placeholder:xp,className:"w-35"})]}),e.jsx(K,{onClick:()=>void y(),disabled:j||!o,size:"sm",children:j?"Loading…":"Load"})]})}),n==="loading"&&e.jsxs(H,{children:["Loading preferential rates for ",e.jsx("code",{children:o}),"…"]}),n==="error"&&e.jsxs(H,{tone:"error",children:[_,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void y(),size:"sm",children:"Retry"})})]}),n==="empty"&&e.jsx(H,{children:m?e.jsxs(e.Fragment,{children:["No preferential rates for ",e.jsx("code",{children:o}),"."]}):e.jsxs(e.Fragment,{children:["Enter an HS6 and click ",e.jsx("em",{children:"Load"}),"."]})}),v&&(n==="ok"||n==="empty")&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Access summary · ",v.hs6_code]}),e.jsx("div",{className:"px-4",children:e.jsxs("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(140px,1fr))] gap-4",children:[e.jsx(ue,{label:"Preferential access",value:v.preferential_access_count}),e.jsx(ue,{label:"Duty-free",value:v.duty_free_count}),e.jsx(ue,{label:"Zero margin",value:v.zero_margin_count}),e.jsx(ue,{label:"Suspended",value:v.suspended_count}),e.jsx(ue,{label:"Schedule missing",value:v.schedule_missing_count}),e.jsx(ue,{label:"Algeria pending",value:v.algeria_pending_count})]})})]}),(m==null?void 0:m.daps_context)&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 px-4",children:[e.jsxs(V,{variant:m.daps_context.applicable?"warning":"secondary",children:["DAPS ",m.daps_context.applicable?"applicable":"n/a"]}),e.jsx("span",{className:"text-sm",children:m.daps_context.note}),m.daps_context.applicable&&e.jsxs("span",{className:"text-sm text-warning",children:["(",m.daps_context.daps_rate_percent.toFixed(1),"%)"]})]})}),n==="ok"&&m&&e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Countries"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[m.returned_count," of ",m.total_count,m.tier_limit_applied&&" · tier limit applied"]})]}),e.jsxs(je,{className:"min-w-[900px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Country"}),e.jsx(T,{children:"ISO3"}),e.jsx(T,{className:"text-right",children:"Pref. rate"}),e.jsx(T,{className:"text-right",children:"MFN rate"}),e.jsx(T,{className:"text-right",children:"Margin"}),e.jsx(T,{children:"Duty-free"}),e.jsx(T,{children:"RoO"}),e.jsx(T,{children:"Vintage"})]})}),e.jsx(ye,{children:m.results.map(g=>e.jsxs(ee,{children:[e.jsx(A,{children:g.country_name}),e.jsx(A,{className:"font-mono text-xs",children:g.country_iso3}),e.jsx(A,{className:"text-right tabular-nums",children:Fu(g.preferential_rate)}),e.jsx(A,{className:"text-right tabular-nums",children:Fu(g.mfn_rate)}),e.jsx(A,{className:"text-right tabular-nums",children:Fu(g.tariff_margin)}),e.jsx(A,{children:g.duty_free?e.jsx(V,{variant:"success",children:"duty-free"}):e.jsx(V,{variant:"secondary",children:"no"})}),e.jsxs(A,{children:[g.rules_of_origin_flag?e.jsx(V,{variant:"warning",children:"RoO"}):e.jsx(V,{variant:"success",children:"OK"}),g.rules_of_origin_note&&e.jsx("span",{className:"ml-1.5 text-muted-foreground",children:g.rules_of_origin_note})]}),e.jsx(A,{children:g.schedule_vintage_date})]},g.country_iso3))})]})]})]})}const pp="2025-Q1",gp=(t,n=2)=>t==null?"—":t.toFixed(n),Du=t=>t==null?"—":`${t.toFixed(1)}%`;function uk({tier:t="1"}){const[n,a]=i.useState("empty"),[o,c]=i.useState("720839"),[u,h]=i.useState(pp),[m,x]=i.useState(null),[v,N]=i.useState(!1),[j,w]=i.useState(""),_=i.useCallback(async()=>{N(!0),a("loading"),w("");try{const S=await sk(o,u,t);x(S),a("ok")}catch(S){w(S instanceof Error?S.message:"Load failed"),a("error")}finally{N(!1)}},[o,u,t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Market Sizing",description:"AfCFTA Total Addressable Market (TAM) per HS6"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["HS6",e.jsx(me,{value:o,onChange:S=>c(S.target.value),placeholder:"720839",className:"w-35"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Schedule version",e.jsx(me,{value:u,onChange:S=>h(S.target.value),placeholder:pp,className:"w-35"})]}),e.jsx(K,{onClick:()=>void _(),disabled:v||!o,size:"sm",children:v?"Loading…":"Load"})]})}),n==="loading"&&e.jsxs(H,{children:["Sizing market for ",e.jsx("code",{children:o}),"…"]}),n==="error"&&e.jsxs(H,{tone:"error",children:[j,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void _(),size:"sm",children:"Retry"})})]}),n==="empty"&&e.jsxs(H,{children:["Enter an HS6 and click ",e.jsx("em",{children:"Load"})," to size its AfCFTA market."]}),n==="ok"&&m&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("h2",{className:"text-base font-semibold",children:m.hs6_code}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(V,{variant:"secondary",children:m.confidence_tier}),e.jsxs(V,{variant:"secondary",children:["config ",m.config_version]})]})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-[repeat(auto-fit,minmax(150px,1fr))] gap-4",children:[e.jsx(ue,{label:"TAM (USD M)",value:gp(m.tam_usd_millions)}),e.jsx(ue,{label:"Reference year",value:m.reference_year??"—"}),e.jsx(ue,{label:"Coverage countries",value:m.coverage_country_count}),e.jsx(ue,{label:"Excluded",value:m.excluded_count}),e.jsx(ue,{label:"CAGR (5yr)",value:m.cagr_insufficient_data?"insufficient data":Du(m.cagr_5yr)}),e.jsx(ue,{label:"Concentration",value:m.concentration?`${m.concentration.iso3} · ${m.concentration.share_pct.toFixed(1)}%`:"—"})]}),m.coverage_message&&e.jsxs("p",{className:"mb-0 text-sm text-warning",children:[e.jsx(V,{variant:"warning",children:"LOW_COVERAGE"})," ",m.coverage_message]}),m.flags.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:m.flags.map(S=>e.jsx(V,{variant:"warning",children:S},S))})]})}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Top markets"}),e.jsxs(je,{className:"min-w-[560px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"ISO3"}),e.jsx(T,{className:"text-right",children:"TAM share"}),e.jsx(T,{className:"text-right",children:"TAM (USD M)"}),e.jsx(T,{className:"text-right",children:"Pref. rate"}),e.jsx(T,{children:"Vintage"})]})}),e.jsxs(ye,{children:[m.top_markets.map(S=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:S.country_iso3}),e.jsx(A,{className:"text-right tabular-nums",children:Du(S.tam_share_pct)}),e.jsx(A,{className:"text-right tabular-nums",children:gp(S.tam_usd_millions)}),e.jsx(A,{className:"text-right tabular-nums",children:Du(S.preferential_rate)}),e.jsx(A,{children:S.schedule_vintage_date??"—"})]},S.country_iso3)),m.top_markets.length===0&&e.jsx(ee,{children:e.jsx(A,{colSpan:5,className:"text-muted-foreground",children:"No markets."})})]})]})]})]})]})}const vp="2025-Q1",jp="demo-user",yp=(t,n=2)=>t==null?"—":t.toFixed(n),mk=t=>t==null?"—":`${t.toFixed(1)}%`,$u=t=>{if(t.trim()==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0};function hk({tier:t="1"}){const[n,a]=i.useState("empty"),[o,c]=i.useState(vp),[u,h]=i.useState(""),[m,x]=i.useState(""),[v,N]=i.useState(""),[j,w]=i.useState(!1),[_,S]=i.useState(null),[y,g]=i.useState(!1),[p,k]=i.useState(""),[R,C]=i.useState("720839"),[E,P]=i.useState(""),[F,I]=i.useState(null),M=i.useCallback(async()=>{g(!0),a("loading"),k("");try{const L={version:o,min_tam:$u(u),min_preferential_count:$u(m),min_headroom_score:$u(v),duty_free_only:j||void 0},z=await rk(L,t);S(z),a(z.results.length===0?"empty":"ok")}catch(L){k(L instanceof Error?L.message:"Filter failed"),a("error")}finally{g(!1)}},[o,u,m,v,j,t]),$=i.useCallback(async()=>{P("");try{await ak({hs6:R,subscriber_id:jp},t),P(`Watching ${R}.`)}catch(L){P(L instanceof Error?L.message:"Watch failed")}},[R,t]),O=i.useCallback(async()=>{P("");try{const L=await lk(jp,t);I(L),L.alerts.length===0&&P("No delta alerts.")}catch(L){P(L instanceof Error?L.message:"Delta alerts failed")}},[t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"AfCFTA Dashboard",description:"Filter export-market opportunities & track watchlist deltas"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Schedule version",e.jsx(me,{value:o,onChange:L=>c(L.target.value),placeholder:vp,className:"w-30"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Min TAM (USD M)",e.jsx(me,{type:"number",value:u,onChange:L=>h(L.target.value),className:"w-30"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Min pref. count",e.jsx(me,{type:"number",value:m,onChange:L=>x(L.target.value),className:"w-30"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Min headroom score",e.jsx(me,{type:"number",value:v,onChange:L=>N(L.target.value),className:"w-30"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:L=>w(L.target.checked),className:"size-4 accent-primary"}),"Duty-Free Only"]}),e.jsx(K,{onClick:()=>void M(),disabled:y,size:"sm",children:y?"Applying…":"Apply"})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Watchlist HS6",e.jsx(me,{value:R,onChange:L=>C(L.target.value),placeholder:"720839",className:"w-35"})]}),e.jsx(K,{variant:"outline",onClick:()=>void $(),disabled:!R,size:"sm",children:"Watch"}),e.jsx(K,{variant:"outline",onClick:()=>void O(),size:"sm",children:"Delta Alerts"}),E&&e.jsx("span",{className:"text-sm text-muted-foreground",children:E})]})}),F&&F.alerts.length>0&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Delta alerts (",F.alerts.length,")"]}),e.jsx("div",{className:"px-4",children:e.jsx("ul",{className:"pl-[18px]",children:F.alerts.map((L,z)=>e.jsxs("li",{className:"mb-1 text-sm",children:[e.jsx("strong",{children:L.hs6_code})," · ",L.alert_type," — ",L.message]},`${L.hs6_code}-${z}`))})})]}),n==="loading"&&e.jsx(H,{children:"Applying filters…"}),n==="error"&&e.jsxs(H,{tone:"error",children:[p,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void M(),size:"sm",children:"Retry"})})]}),n==="empty"&&e.jsx(H,{children:_?e.jsx(e.Fragment,{children:"No HS6 lines match the current filters."}):e.jsxs(e.Fragment,{children:["Set filters and click ",e.jsx("em",{children:"Apply"}),"."]})}),n==="ok"&&_&&e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Results"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.count," lines"]})]}),e.jsxs(je,{className:"min-w-[980px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Product"}),e.jsx(T,{className:"text-right",children:"Headroom (USD M)"}),e.jsx(T,{className:"text-right",children:"Sub-score"}),e.jsx(T,{className:"text-right",children:"Pref."}),e.jsx(T,{className:"text-right",children:"Duty-free"}),e.jsx(T,{className:"text-right",children:"CAGR"}),e.jsx(T,{children:"Confidence"}),e.jsx(T,{className:"text-right",children:"CAS"}),e.jsx(T,{className:"text-right",children:"TAM vintage"}),e.jsx(T,{children:"Flags"}),e.jsx(T,{children:"Delta"})]})}),e.jsx(ye,{children:_.results.map(L=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:L.hs6_code}),e.jsx(A,{children:L.product_description}),e.jsx(A,{className:"text-right tabular-nums",children:yp(L.headroom_usd_millions)}),e.jsx(A,{className:"text-right tabular-nums",children:yp(L.headroom_sub_score)}),e.jsx(A,{className:"text-right tabular-nums",children:L.preferential_country_count}),e.jsx(A,{className:"text-right tabular-nums",children:L.duty_free_country_count}),e.jsx(A,{className:"text-right tabular-nums",children:mk(L.cagr_5yr)}),e.jsx(A,{children:e.jsx(V,{variant:"secondary",children:L.confidence_tier})}),e.jsx(A,{className:"text-right tabular-nums",children:L.cas_score==null?"—":L.cas_score.toFixed(1)}),e.jsx(A,{className:"text-right tabular-nums",children:L.tam_vintage_year??"—"}),e.jsx(A,{children:L.flags.length===0?"—":L.flags.map(z=>e.jsx(V,{variant:"warning",children:z},z))}),e.jsx(A,{children:L.delta_flag?e.jsx(V,{variant:"warning",children:"Δ"}):"—"})]},L.hs6_code))})]})]})]})}const _p="2025-Q1",bp="chief_economist",Np=t=>{const n=t.toUpperCase();return n.includes("READY")||n==="PASS"?"success":n.includes("NOT")||n.includes("FAIL")||n.includes("BLOCK")?"danger":"warning"},Iu=t=>t===void 0?e.jsx(V,{variant:"secondary",children:"—"}):e.jsx(V,{variant:t?"success":"danger",children:t?"PASS":"FAIL"});function fk(){const[t,n]=i.useState("empty"),[a,o]=i.useState(_p),[c,u]=i.useState(null),[h,m]=i.useState(null),[x,v]=i.useState(!1),[N,j]=i.useState(""),w=i.useCallback(async()=>{v(!0),n("loading"),j("");try{const p=await ik(a,bp);u(p),n("ok")}catch(p){j(p instanceof Error?p.message:"Audit failed"),n("error")}finally{v(!1)}},[a]),_=i.useCallback(async()=>{j("");try{const p=await ok(bp);m(p.history)}catch(p){j(p instanceof Error?p.message:"History failed"),n("error")}},[]),S=c==null?void 0:c.report_data.criterion_1,y=c==null?void 0:c.report_data.criterion_2,g=c==null?void 0:c.report_data.criterion_3;return e.jsxs("div",{children:[e.jsx(Se,{title:"Coverage Audit",description:"AfCFTA schedule readiness across the three coverage criteria"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Schedule version",e.jsx(me,{value:a,onChange:p=>o(p.target.value),placeholder:_p,className:"w-35"})]}),e.jsx(K,{onClick:()=>void w(),disabled:x||!a,size:"sm",children:x?"Running…":"Run Audit"}),e.jsx(K,{variant:"outline",onClick:()=>void _(),size:"sm",children:"History"})]})}),t==="loading"&&e.jsxs(H,{children:["Running coverage audit for ",e.jsx("code",{children:a}),"…"]}),t==="error"&&e.jsxs(H,{tone:"error",children:[N,e.jsx("div",{className:"mt-3",children:e.jsx(K,{onClick:()=>void w(),size:"sm",children:"Retry"})})]}),t==="empty"&&e.jsxs(H,{children:["Enter a schedule version and click ",e.jsx("em",{children:"Run Audit"}),"."]}),t==="ok"&&c&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 px-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Readiness status · ",c.schedule_version]}),e.jsx("div",{className:"mt-1",children:e.jsx(V,{variant:Np(c.readiness_status),children:c.readiness_status})})]}),e.jsxs("div",{className:"text-right text-xs text-muted-foreground",children:[e.jsxs("div",{children:["run ",c.run_id]}),e.jsxs("div",{children:["generated ",c.generated_at]}),c.report_data.data_freshness&&e.jsxs("div",{children:["freshness ",c.report_data.data_freshness]})]})]})}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Criterion 1 · Country coverage ",Iu(S==null?void 0:S.target_met)]}),S!=null&&S.missing_countries&&S.missing_countries.length>0?e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"mb-1 text-xs text-muted-foreground",children:["Missing countries (",S.missing_countries.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:S.missing_countries.map(p=>e.jsx(V,{variant:"danger",children:p},p))})]}):e.jsx("p",{className:"px-4 text-sm text-muted-foreground",children:"No missing countries."})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Criterion 2 · Data coverage ",Iu(y==null?void 0:y.pass)]}),e.jsx("div",{className:"px-4",children:e.jsx(ue,{label:"Coverage",value:(y==null?void 0:y.coverage_pct)==null?"—":`${y.coverage_pct.toFixed(1)}%`})})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Criterion 3 · Card completeness ",Iu(g==null?void 0:g.pass)]}),g!=null&&g.incomplete_cards&&g.incomplete_cards.length>0?e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"mb-1 text-xs text-muted-foreground",children:["Incomplete cards (",g.incomplete_cards.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:g.incomplete_cards.map(p=>e.jsx(V,{variant:"warning",children:p},p))})]}):e.jsx("p",{className:"px-4 text-sm text-muted-foreground",children:"No incomplete cards."})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Remediation"}),e.jsxs(je,{className:"min-w-[640px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Criterion"}),e.jsx(T,{children:"Gap"}),e.jsx(T,{children:"Action"}),e.jsx(T,{className:"text-right",children:"Effort (h)"})]})}),e.jsxs(ye,{children:[c.remediation.map((p,k)=>e.jsxs(ee,{children:[e.jsx(A,{children:p.criterion}),e.jsx(A,{children:p.gap}),e.jsx(A,{children:p.action}),e.jsx(A,{className:"text-right tabular-nums",children:p.effort_person_hours})]},`${p.criterion}-${k}`)),c.remediation.length===0&&e.jsx(ee,{children:e.jsx(A,{colSpan:4,className:"text-muted-foreground",children:"No remediation items."})})]})]})]})]}),h&&e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Audit history (",h.length,")"]}),e.jsxs(je,{className:"min-w-[560px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Run"}),e.jsx(T,{children:"Version"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Generated"})]})}),e.jsxs(ye,{children:[h.map(p=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:p.run_id}),e.jsx(A,{children:p.schedule_version}),e.jsx(A,{children:e.jsx(V,{variant:Np(p.readiness_status),children:p.readiness_status})}),e.jsx(A,{children:p.generated_at})]},p.run_id)),h.length===0&&e.jsx(ee,{children:e.jsx(A,{colSpan:4,className:"text-muted-foreground",children:"No prior runs."})})]})]})]})]})}function xk(t){return{"x-subscriber-tier":t}}const wp=()=>be("/v1/cas-config/seed-activate"),pk=()=>he("/v1/cas/scoring-runs"),gk=(t,n)=>be("/v1/cas/scoring-runs",{data_cutoff_date:t,scenario:n}),vk=(t,n,a)=>he(`/v1/cas/scores/${t}`,xk(n)),jk=t=>he(`/v1/cas/scoring-runs/${t}/scores`),yk=t=>he(`/v1/cas/scoring-runs/${t}/benchmark-validation-report`),_k=t=>he(`/v1/cas/scoring-runs/${t}/delta-report`),Sp="2025-03-31",Lt=new Intl.NumberFormat("en-US",{maximumFractionDigits:2});function bk(){const[t,n]=i.useState("loading"),[a,o]=i.useState("1"),[c,u]=i.useState(null),[h,m]=i.useState(null),[x,v]=i.useState([]),[N,j]=i.useState(null),[w,_]=i.useState(null),[S,y]=i.useState(null),[g,p]=i.useState(""),[k,R]=i.useState(!1),C=i.useCallback(async()=>{const O=(await wp()).active,{runs:L}=await pk(),z=L.find(ae=>ae.status==="COMPLETED"||ae.status==="SLA_BREACH")??L[0]??null;if(!z)return{config:O,run:null,scores:[],concordance:null,delta:null};const[Y,G,U]=await Promise.all([jk(z.id),yk(z.id).catch(()=>null),_k(z.id).catch(()=>null)]);return{config:O,run:z,scores:Y.scores,concordance:G,delta:U}},[]),E=i.useCallback($=>{u($.config),m($.run),v($.scores),j($.concordance),_($.delta),n($.scores.length===0?"empty":"ok")},[]),P=i.useCallback($=>{p($ instanceof Error?$.message:"Unknown error"),n("error")},[]);i.useEffect(()=>{let $=!0;return C().then(O=>{$&&E(O)},O=>{$&&P(O)}),()=>{$=!1}},[C,E,P]);const F=i.useCallback(()=>(n("loading"),C().then(E,P)),[C,E,P]),I=i.useCallback(async $=>{R(!0);try{await wp(),await gk($==="shifted"?"2025-06-30":Sp,$),await F()}catch(O){p(O instanceof Error?O.message:"Scoring run failed"),n("error")}finally{R(!1)}},[F]),M=i.useCallback(async $=>{try{y(await vk($,a))}catch(O){p(O instanceof Error?O.message:"Failed to load line")}},[a]);return e.jsxs("div",{children:[e.jsx(Se,{title:"CAS Scoring Engine",description:"Six-dimension Comparative Advantage Score · AAPI / FNI investment intelligence",actions:e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:["Subscriber tier",e.jsxs(Ie,{value:a,onChange:$=>o($.target.value),"aria-label":"Subscriber tier",children:[e.jsx("option",{value:"1",children:"Tier 1 · Institutional"}),e.jsx("option",{value:"2",children:"Tier 2 · Advisory"}),e.jsx("option",{value:"3",children:"Tier 3 · Basic"})]})]}),e.jsx(K,{size:"sm",onClick:()=>void I(),disabled:k,children:k?"Running…":"Run scoring"}),e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void I("shifted"),disabled:k,children:"Run shifted quarter"})]})}),t==="loading"&&e.jsx(Rk,{}),t==="error"&&e.jsxs("div",{role:"alert",className:"mt-4 rounded-xl border border-destructive/50 bg-card p-5 text-destructive",children:[e.jsx("strong",{children:"Something went wrong."}),e.jsx("div",{className:"mt-1.5 text-sm",children:g}),e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void F(),children:"Retry"})})]}),t==="empty"&&e.jsxs(B,{className:"mt-4 gap-3 p-5",children:[e.jsx("strong",{children:"No scoring run yet."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trigger a quarterly scoring run to compute CAS scores for the product universe."}),e.jsx("div",{children:e.jsxs(K,{size:"sm",onClick:()=>void I(),disabled:k,children:["Run scoring for ",Sp]})})]}),t==="ok"&&e.jsxs("div",{className:"mt-4 grid gap-4",children:[c&&e.jsx(Nk,{config:c}),h&&e.jsx(wk,{run:h,concordance:N}),N&&e.jsx(Sk,{report:N}),e.jsx(Ck,{scores:x,onOpen:$=>void M($)}),w&&e.jsx(kk,{report:w})]}),S&&e.jsx(Ek,{score:S,tier:a,onClose:()=>y(null)})]})}function Nk({config:t}){return e.jsxs(B,{className:"gap-3 p-5",children:[e.jsx($i,{children:"Active configuration"}),e.jsxs("div",{className:"flex flex-wrap items-baseline gap-6",children:[e.jsx(cs,{label:"Version",value:t.version_string}),e.jsx(cs,{label:"Status",value:t.status}),e.jsx(cs,{label:"Effective",value:t.effective_date_start}),e.jsx(cs,{label:"SHA-256",value:t.config_sha256.slice(0,12)+"…",mono:!0})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("div",{className:"flex w-min gap-2",children:t.config_payload.dimensions.map(n=>e.jsxs("span",{className:"whitespace-nowrap rounded-full bg-muted px-2.5 py-1 text-xs text-muted-foreground",children:[n.dimension_id," · ",Lt.format(n.weight)]},n.dimension_id))})})]})}function wk({run:t,concordance:n}){return e.jsxs(B,{className:"gap-3 p-5",children:[e.jsx($i,{children:"Scoring run manifest"}),e.jsxs("div",{className:"flex flex-wrap items-baseline gap-6",children:[e.jsx(cs,{label:"Cutoff",value:t.data_cutoff_date}),e.jsx(cs,{label:"Status",value:e.jsx(Ak,{status:t.status})}),e.jsx(cs,{label:"Lines scored",value:Lt.format(t.totals.lines_scored)}),e.jsx(cs,{label:"High confidence",value:Lt.format(t.totals.lines_high_confidence)}),e.jsx(cs,{label:"Skipped (missing)",value:Lt.format(t.totals.lines_skipped_missing)}),e.jsx(cs,{label:"Coverage",value:`${Lt.format(t.coverage_pct)}%`}),n&&e.jsx(cs,{label:"Concordance",value:`${Lt.format(n.overall_concordance_rate)}%`})]})]})}function Sk({report:t}){const n=t.validation_status==="PASS";return e.jsxs(B,{className:"gap-3 p-5",children:[e.jsx($i,{children:"Benchmark concordance (expert validation)"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(V,{variant:n?"success":"danger",children:[n?"PASS":"FAIL"," · ≥",t.gate_threshold_pct,"% gate"]}),e.jsx(cs,{label:"Rate",value:`${Lt.format(t.overall_concordance_rate)}%`}),e.jsx(cs,{label:"Concordant",value:`${t.concordant_count}/${t.concordant_count+t.discordant_count}`}),e.jsx(cs,{label:"Certificate",value:t.certificate_sha256.slice(0,12)+"…",mono:!0})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("div",{className:"flex w-min gap-2",children:Object.entries(t.per_dimension_mae).map(([a,o])=>e.jsxs("span",{className:"whitespace-nowrap rounded-full bg-muted px-2.5 py-1 text-xs text-muted-foreground",children:["MAE ",a,": ",Lt.format(o)]},a))})})]})}function Ck({scores:t,onOpen:n}){return e.jsxs(B,{className:"gap-3 p-5",children:[e.jsxs($i,{children:["Per-line CAS scores (",t.length,")"]}),e.jsxs(je,{className:"min-w-[640px]",children:[e.jsx(_e,{children:e.jsx(ee,{children:["HS6","Product","CAS","Confidence","51/49",""].map(a=>e.jsx(T,{className:a==="CAS"?"text-right":void 0,children:a},a))})}),e.jsx(ye,{children:t.map(a=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs tabular-nums",children:a.hs6_code}),e.jsx(A,{children:a.hs6_description.en}),e.jsx(A,{className:"text-right font-semibold tabular-nums",children:Lt.format(a.composite_cas_score)}),e.jsx(A,{children:e.jsx(Gj,{tier:a.confidence_tier})}),e.jsx(A,{children:e.jsx(Wj,{status:a.compliance_status})}),e.jsx(A,{children:e.jsx(K,{size:"xs",onClick:()=>n(a.hs6_code),children:"Breakdown"})})]},a.hs6_code))})]})]})}function kk({report:t}){const n=t.changes.filter(c=>c.threshold_crossed==="ABOVE_60"),a=t.changes.filter(c=>c.threshold_crossed==="BELOW_60"),o=t.changes.filter(c=>c.threshold_crossed===null);return e.jsxs(B,{className:"gap-3 p-5",children:[e.jsx($i,{children:"Quarter-over-quarter delta report"}),t.changes.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No material changes vs the prior quarter."}):e.jsxs("div",{className:"grid gap-3",children:[e.jsx(Mu,{title:"New Opportunities (crossed 60 upward)",variant:"success",changes:n}),e.jsx(Mu,{title:"Deteriorating (crossed 60 downward)",variant:"danger",changes:a}),e.jsx(Mu,{title:"Other material movers",variant:"secondary",changes:o})]})]})}function Mu({title:t,variant:n,changes:a}){return a.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5",children:e.jsx(V,{variant:n,children:t})}),e.jsx("ul",{className:"list-disc pl-5",children:a.map(o=>e.jsxs("li",{className:"mb-1 text-sm",children:[e.jsx("strong",{children:o.hs6_code}),": ",Lt.format(o.prior_value)," → ",Lt.format(o.current_value)," (Δ ",Lt.format(o.composite_delta),")",o.dimension_drivers.length>0&&e.jsxs("span",{className:"text-muted-foreground",children:[" · driven by ",o.dimension_drivers.map(c=>c.dimension_id).join(", ")]})]},o.hs6_code))})]})}function Ek({score:t,tier:n,onClose:a}){const o=t.legal_structure_warning;return e.jsx("div",{className:"fixed inset-0 z-50 flex justify-end bg-black/35",role:"dialog","aria-label":`CAS breakdown for ${t.hs6_code}`,children:e.jsxs("div",{className:"h-full w-[min(560px,100%)] overflow-y-auto bg-card p-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:[t.hs6_code," · ",Lt.format(t.composite_cas_score)," CAS"]}),e.jsx(K,{size:"xs",onClick:a,"aria-label":"Close",children:"Close"})]}),e.jsxs("p",{dir:"auto",className:"mt-1 text-sm text-muted-foreground",children:[t.hs6_description.en," · ",t.hs6_description.fr]}),e.jsx("p",{dir:"rtl",className:"text-base",children:t.hs6_description.ar}),e.jsxs("div",{className:`${kp(o.compliance_status==="NON_COMPLIANT"?"danger":"warn")} mb-3`,children:[e.jsxs("strong",{children:["51/49 rule (",o.rule_id,")"]})," — max foreign equity ",o.max_foreign_equity_pct,"% ·"," ",e.jsx(Wj,{status:o.compliance_status}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:o.journal_officiel_reference})]}),t.delta_vs_prior_quarter&&e.jsxs("div",{className:"mb-3 text-sm text-muted-foreground",children:["Δ vs prior quarter: ",Lt.format(t.delta_vs_prior_quarter.composite_delta)," ",t.delta_vs_prior_quarter.threshold_crossed?`(${t.delta_vs_prior_quarter.threshold_crossed})`:""]}),n==="3"&&e.jsx("div",{className:`${kp("neutral")} mb-3`,children:"Tier 3 access: raw sub-indicator values and source citations are masked. Upgrade for full provenance."}),e.jsx("div",{className:"grid gap-2.5",children:t.dimensions.map(c=>e.jsxs("div",{className:"rounded-xl border p-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("strong",{className:"text-sm",children:c.dimension_id}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["weight ",Lt.format(c.dimension_weight)," · sub-score ",Lt.format(c.dimension_sub_score)," · ",e.jsx(Gj,{tier:c.confidence_tier})]})]}),e.jsxs(je,{className:"min-w-[420px]",children:[e.jsx(_e,{children:e.jsx(ee,{children:["Indicator","Raw","Normalized","Source"].map(u=>e.jsx(T,{children:u},u))})}),e.jsx(ye,{children:c.sub_indicators.map(u=>e.jsxs(ee,{children:[e.jsx(A,{children:u.indicator_id}),e.jsx(A,{children:u.raw_value===null?Cp(u.restricted_field_reason):Lt.format(u.raw_value)}),e.jsx(A,{children:u.normalized_value===null?"—":Lt.format(u.normalized_value)}),e.jsx(A,{children:u.source??Cp(u.restricted_field_reason)})]},u.indicator_id))})]})]},c.dimension_id))})]})})}function Cp(t){return t==="TIER3_ACCESS_LIMIT"?"🔒 masked":"—"}function $i({children:t}){return e.jsx("h2",{className:"mb-2.5 text-base font-semibold",children:t})}function cs({label:t,value:n,mono:a}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:t}),e.jsx("div",{className:a?"text-base font-semibold font-mono":"text-base font-semibold",children:n})]})}function Ak({status:t}){const n=t==="COMPLETED"?"success":t==="FAILED"||t==="VALIDATION_FAILED"?"danger":"warning";return e.jsx(V,{variant:n,children:t})}function Gj({tier:t}){const n=t==="HIGH"?"success":t==="MISSING"?"danger":"warning";return e.jsx(V,{variant:n,children:t})}function Wj({status:t}){const n=t==="COMPLIANT"?"success":t==="NON_COMPLIANT"?"danger":"secondary";return e.jsx(V,{variant:n,children:t.replace(/_/g," ")})}function Rk(){return e.jsx("div",{className:"mt-4 grid gap-3",children:[0,1,2].map(t=>e.jsx("div",{className:"h-[72px] rounded-xl border bg-muted","aria-hidden":!0},t))})}function kp(t){return`rounded-xl p-3 text-sm ${t==="danger"?"bg-destructive/10 text-destructive":t==="warn"?"bg-warning/10 text-warning":t==="ok"?"bg-success/10 text-success":"bg-muted text-muted-foreground"}`}const Ac=t=>({"x-subscriber-tier":t}),Pk=t=>({"x-user-role":t});function Rc(t){const n=new URLSearchParams;for(const[o,c]of Object.entries(t))c==null||c===""||c===!1||n.set(o,String(c));const a=n.toString();return a?`?${a}`:""}const Pc=()=>he("/v1/geo-siting/sectors"),Tk=(t,n,a)=>he(`/v1/geo-siting/scores${Rc({sector_code:t,cycle_id:n})}`,Ac(a)),Lk=(t,n,a)=>he(`/v1/geo-siting/wilayas/${encodeURIComponent(t)}${Rc({sector_code:n})}`,Ac(a)),Fk=(t,n,a,o)=>he(`/v1/geo-siting/zone-registry${Rc({wilaya_code:t,sector_code:n,foreign_majority:a?"1":""})}`,Ac(o)),Dk=(t,n,a)=>he(`/v1/geo-siting/logistics/compare${Rc({wilayas:t.join(","),sector_code:n})}`,Ac(a)),$k=t=>be("/v1/geo-siting/wilaya-recommendations/recompute",t),Ik=()=>he("/v1/geo-siting/pipeline-runs/latest/status"),Mk=(t,n)=>be("/v1/geo-siting/pipeline-runs",{cycle_id:t},Pk(n)),fc=["#ffffcc","#fed976","#fd8d3c","#f03b20","#bd0026"];function Ok(t,n){let a=0;for(;a=n[a];)a++;return a}function zk({tier:t="1"}){const[n,a]=i.useState([]),[o,c]=i.useState("AGRO_FOOD"),[u,h]=i.useState(null),[m,x]=i.useState(""),[v,N]=i.useState(0),[j,w]=i.useState(null),[_,S]=i.useState(null),[y,g]=i.useState(null),[p,k]=i.useState(null),R=`${o}|${t}`,C=p===R?"error":y!==R?"loading":u!==null&&u.wilayas.length===0?"empty":"ok";i.useEffect(()=>{Pc().then($=>a($.sectors)).catch(()=>{})},[]);const E=i.useCallback(async()=>await Tk(o,void 0,t),[o,t]),P=i.useCallback($=>{h($),w(null),g(R),k(null)},[R]),F=i.useCallback($=>{x($ instanceof Error?$.message:"Load failed"),k(R),g(null)},[R]),I=i.useCallback(()=>(g(null),k(null),E().then(P,F)),[E,P,F]);i.useEffect(()=>{let $=!0;return E().then(O=>{$&&P(O)},O=>{$&&F(O)}),()=>{$=!1}},[E,P,F]);const M=i.useCallback(async $=>{try{w(await Lk($,o,t))}catch{}},[o,t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Wilaya Siting Map",description:"Composite siting score across the 48 wilayas, by industrial sector (Epic 9).",meta:u!=null&&u.cycle_id?e.jsx("span",{className:"font-mono",children:u.cycle_id}):void 0}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(Ep,{label:"Sector",children:e.jsx(Ie,{value:o,onChange:$=>c($.target.value),"aria-label":"Sector filter",children:(n.length?n:[o]).map($=>e.jsx("option",{value:$,children:$},$))})}),e.jsx(Ep,{label:"Min score highlight (CAS-siting proxy)",children:e.jsx(me,{type:"number",min:0,max:100,value:v,onChange:$=>N(Number($.target.value)),className:"w-30"})}),e.jsx(K,{size:"sm",onClick:()=>void I(),children:"Reload"})]})}),C==="loading"&&e.jsx(H,{children:"Loading wilaya scores…"}),C==="error"&&e.jsxs(H,{tone:"error",children:[m,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void I(),children:"Retry"})})]}),C==="empty"&&e.jsx(H,{children:"No scores available — run the geo pipeline first."}),C==="ok"&&u&&u.static_export&&e.jsxs(H,{children:[e.jsx("strong",{children:u.watermark}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Tier 3 receives a static, non-interactive export. ",e.jsx("a",{href:u.upgrade_url??"#",children:"Upgrade"})," for the interactive map."]})]}),C==="ok"&&u&&!u.static_export&&e.jsxs("div",{className:"mt-4 flex flex-wrap gap-4",children:[e.jsx(B,{className:"flex-[1_1_560px] overflow-x-auto py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[o," — ",u.wilayas.length," wilayas"]}),e.jsx(Uk,{wilayas:u.wilayas,breaks:u.quantile.breaks,casMin:v,corridor:new Set,onHover:S,onSelect:$=>void M($)}),e.jsx(Bk,{breaks:u.quantile.breaks,method:u.quantile.method}),_&&e.jsxs("div",{role:"status",className:"mt-2 text-sm text-foreground",children:[e.jsx("strong",{children:_.wilaya_name_fr})," ",e.jsx("span",{dir:"rtl",children:_.wilaya_name_ar})," — ",_.composite_score,"/100 (rank ",_.rank,")",_.data_quality_flags.includes("LOW_CONFIDENCE")&&e.jsx(V,{variant:"warning",children:"Low confidence"}),_.resource_proximity_multiplier>1&&e.jsxs(V,{variant:"success",children:["Corridor ×",_.resource_proximity_multiplier]})]})]})}),e.jsx(B,{className:"flex-[1_1_320px] py-4",children:e.jsxs("div",{className:"px-4",children:[!j&&e.jsx("p",{className:"text-muted-foreground",children:"Click a wilaya to view its score breakdown and AAPI zones."}),j&&e.jsx(Hk,{detail:j})]})})]})]})}function Ep({label:t,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:[t,n]})}function Uk({wilayas:t,breaks:n,casMin:a,corridor:o,onHover:c,onSelect:u}){const N=Math.ceil(t.length/5);return e.jsxs("svg",{width:560,height:N*70,role:"img","aria-label":"Wilaya choropleth",className:"max-w-full",children:[e.jsx("defs",{children:e.jsxs("pattern",{id:"lowconf",width:"6",height:"6",patternUnits:"userSpaceOnUse",patternTransform:"rotate(45)",children:[e.jsx("rect",{width:"6",height:"6",fill:"transparent"}),e.jsx("line",{x1:"0",y1:"0",x2:"0",y2:"6",className:"stroke-muted-foreground",strokeWidth:"1.5"})]})}),t.map((j,w)=>{const _=w%5*112,S=Math.floor(w/5)*70,y=j.data_quality_flags.includes("LOW_CONFIDENCE"),g=j.resource_proximity_multiplier>1||o.has(j.wilaya_code),p=fc[Ok(j.composite_score,n)]??fc[0];return e.jsxs("g",{transform:`translate(${_},${S})`,className:"cursor-pointer",onMouseEnter:()=>c(j),onMouseLeave:()=>c(null),onClick:()=>u(j.wilaya_code),children:[e.jsx("title",{children:`${j.wilaya_name_fr} — ${j.composite_score}/100`}),e.jsx("rect",{width:104,height:62,rx:6,fill:p,className:g?"stroke-primary":"stroke-border",strokeWidth:g?2:1,strokeDasharray:g?"4 3":void 0}),y&&e.jsx("rect",{width:104,height:62,rx:6,fill:"url(#lowconf)"}),j.composite_score>=a&&a>0&&e.jsx("rect",{x:2,y:2,width:100,height:58,rx:4,fill:"none",className:"stroke-foreground",strokeWidth:2}),e.jsx("text",{x:104/2,y:62/2-4,textAnchor:"middle",fontSize:12,fontWeight:600,className:"fill-foreground",children:j.wilaya_code}),e.jsx("text",{x:104/2,y:62/2+14,textAnchor:"middle",fontSize:12,className:"fill-foreground/80",children:j.composite_score})]},j.wilaya_code)})]})}function Bk({breaks:t,method:n}){const a=["low",...t.map(o=>`≥ ${o}`)];return e.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Score (",n,"):"]}),fc.map((o,c)=>e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"h-3 w-4 rounded-sm border",style:{background:o}}),a[c]]},o)),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"h-3 w-4 rounded-sm border",style:{background:"url(#lowconf) var(--muted)"}}),"Low confidence"]})]})}function Hk({detail:t}){var o,c;const n=t.score,a=Object.entries(n.sub_scores);return e.jsxs("div",{children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[n.wilaya_name_fr," ",e.jsx("span",{dir:"rtl",className:"font-normal text-muted-foreground",children:n.wilaya_name_ar})]}),e.jsxs("div",{className:"text-xl font-bold",children:[n.composite_score,e.jsx("span",{className:"text-sm text-muted-foreground",children:"/100"})]}),e.jsx("div",{className:"mt-3",children:a.map(([u,h])=>e.jsxs("div",{className:"mb-1.5",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:u}),e.jsx("span",{children:h.value==null?"—":Math.round(h.value*100)})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted",children:e.jsx("div",{className:"h-2 rounded-full",style:{width:`${(h.value??0)*100}%`,background:fc[2]}})})]},u))}),e.jsxs("h3",{className:"mb-1.5 mt-3.5 text-sm",children:["AAPI zones (",((o=t.zones)==null?void 0:o.result_count)??0,")"]}),(((c=t.zones)==null?void 0:c.zones)??[]).map(u=>e.jsxs("div",{className:"mb-1 text-xs",children:[u.zone_name_fr," ",e.jsx(V,{variant:"secondary",children:u.zone_type})," ",u.available_ha," ha",u.flags.map(h=>e.jsx(V,{variant:h.includes("SUSPENDED")||h.includes("OCCUPIED")?"danger":"warning",children:h},h))]},u.zone_id))]})}function Vk({tier:t="1"}){const[n,a]=i.useState("idle"),[o,c]=i.useState("DZ-23"),[u,h]=i.useState(""),[m,x]=i.useState(!1),[v,N]=i.useState([]),[j,w]=i.useState(null),[_,S]=i.useState("");i.useEffect(()=>{Pc().then(g=>N(g.sectors)).catch(()=>{})},[]);const y=i.useCallback(async()=>{a("loading"),S("");try{const g=await Fk(o.trim(),u||void 0,m,t);w(g),a(g.zones.length===0?"empty":"ok")}catch(g){S(g instanceof Error?g.message:"Load failed"),a("error")}},[o,u,m,t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"AAPI Zone Registry",description:"Query eligible AAPI zones by wilaya and sector, with Law 23-17 and 51/49 flags (US-9.4)."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(Ap,{label:"Wilaya code",children:e.jsx(me,{value:o,onChange:g=>c(g.target.value),placeholder:"DZ-23",className:"w-30"})}),e.jsx(Ap,{label:"Sector",children:e.jsxs(Ie,{value:u,onChange:g=>h(g.target.value),"aria-label":"Sector",children:[e.jsx("option",{value:"",children:"Any"}),v.map(g=>e.jsx("option",{value:g,children:g},g))]})}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:m,onChange:g=>x(g.target.checked),className:"size-4 accent-primary"})," Foreign-majority (51/49)"]}),e.jsx(K,{size:"sm",onClick:()=>void y(),children:"Query"})]})}),n==="idle"&&e.jsx(H,{children:"Enter a wilaya code and query the registry."}),n==="loading"&&e.jsx(H,{children:"Loading zones…"}),n==="error"&&e.jsxs(H,{tone:"error",children:[_,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void y(),children:"Retry"})})]}),n==="empty"&&e.jsx(H,{children:"No eligible zones for this wilaya/sector."}),n==="ok"&&j&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[j.wilaya_code," — ",j.result_count," zones"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Source: ",j.ingestion_metadata.source_file_name," · schema ",j.ingestion_metadata.schema_version]}),e.jsxs(je,{className:"min-w-[760px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Zone"}),e.jsx(T,{children:"Type"}),e.jsx(T,{className:"text-right",children:"Available ha"}),e.jsx(T,{className:"text-right",children:"Occupancy"}),e.jsx(T,{children:"Law 23-17"}),e.jsx(T,{children:"Flags"})]})}),e.jsx(ye,{children:j.zones.map(g=>e.jsxs(ee,{children:[e.jsxs(A,{children:[g.zone_name_fr,e.jsx("div",{dir:"rtl",className:"text-xs text-muted-foreground",children:g.zone_name_ar})]}),e.jsx(A,{children:e.jsx(V,{variant:"secondary",children:g.zone_type})}),e.jsx(A,{className:"text-right tabular-nums",children:g.available_ha}),e.jsxs(A,{className:"text-right tabular-nums",children:[g.occupancy_rate_pct,"%"]}),e.jsx(A,{children:e.jsx(V,{variant:g.law_23_17_status==="active"?"success":g.law_23_17_status==="suspended"?"danger":"warning",children:g.law_23_17_status})}),e.jsx(A,{children:g.flags.length===0?"—":g.flags.map(p=>e.jsx(V,{variant:p.includes("SUSPENDED")||p.includes("OCCUPIED")?"danger":"warning",children:p},p))})]},g.zone_id))})]})]})})]})}function Ap({label:t,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:[t,n]})}function Gk(){const[t,n]=i.useState("idle"),[a,o]=i.useState("CARD-DEMO"),[c,u]=i.useState(82),[h,m]=i.useState("STEEL_METALS"),[x,v]=i.useState(!0),[N,j]=i.useState([]),[w,_]=i.useState(null),[S,y]=i.useState("");i.useEffect(()=>{Pc().then(p=>j(p.sectors)).catch(()=>{})},[]);const g=i.useCallback(async()=>{n("loading"),y("");try{const p=await $k({card_id:a,cas_score:c,sector_code:h,foreign_majority:x});_(p),n("ok")}catch(p){y(p instanceof Error?p.message:"Failed"),n("error")}},[a,c,h,x]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Top-3 Wilaya Siting Recommendations",description:"Ranked block for a CAS ≥ 60 card, with corridor boost and 51/49 flag (US-9.2)."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(Ou,{label:"Card id",children:e.jsx(me,{value:a,onChange:p=>o(p.target.value),className:"w-35"})}),e.jsx(Ou,{label:"CAS",children:e.jsx(me,{type:"number",value:c,onChange:p=>u(Number(p.target.value)),className:"w-20"})}),e.jsx(Ou,{label:"Sector",children:e.jsx(Ie,{value:h,onChange:p=>m(p.target.value),"aria-label":"Sector",children:(N.length?N:[h]).map(p=>e.jsx("option",{value:p,children:p},p))})}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:p=>v(p.target.checked),className:"size-4 accent-primary"})," Foreign-majority"]}),e.jsx(K,{size:"sm",onClick:()=>void g(),children:"Compute"})]})}),t==="idle"&&e.jsx(H,{children:"Enter a card and compute its siting block."}),t==="loading"&&e.jsx(H,{children:"Computing…"}),t==="error"&&e.jsx(H,{tone:"error",children:S}),t==="ok"&&w&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[w.card_id," · ",w.sector_code," · cycle ",w.cycle_id]}),w.version_mismatch&&e.jsx(V,{variant:"warning",children:"VERSION_MISMATCH"}),w.insufficient_slots.length>0&&e.jsxs(V,{variant:"warning",children:[w.insufficient_slots.length," INSUFFICIENT_SITING_DATA"]}),e.jsx("div",{className:"mt-3 grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-4",children:w.recommendations.map(p=>e.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("strong",{children:["#",p.rank," ",p.wilaya_name_fr]}),e.jsx("span",{className:"font-bold",children:p.composite_siting_score})]}),e.jsx("div",{dir:"rtl",className:"text-xs text-muted-foreground",children:p.wilaya_name_ar}),e.jsxs("div",{className:"mt-1.5",children:[p.resource_proximity_multiplier>1&&e.jsxs(V,{variant:"success",children:["Corridor ×",p.resource_proximity_multiplier]}),e.jsxs(V,{variant:p.equity_compliance_flag==="TRIGGERED"?"danger":"secondary",children:["51/49 ",p.equity_compliance_flag]})]}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:p.sector_resource_proximity_narrative.en}),e.jsx("p",{dir:"rtl",className:"text-xs text-muted-foreground",children:p.sector_resource_proximity_narrative.ar}),e.jsxs("div",{className:"mt-1.5 text-xs text-muted-foreground",children:["AAPI: ",p.aapi_zone_eligibility.total_available_ha," ha · ",p.aapi_zone_eligibility.zone_types_present.join(", ")||"none"]})]},p.wilaya_code))})]})})]})}function Ou({label:t,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:[t,n]})}function Wk({tier:t="1"}){const[n,a]=i.useState("DZ-18,DZ-06"),[o,c]=i.useState("PHARMACEUTICALS"),[u,h]=i.useState([]),[m,x]=i.useState(null),[v,N]=i.useState(""),[j,w]=i.useState(null),[_,S]=i.useState(null),y=`${n}|${o}|${t}`,g=_===y?"error":j!==y?"loading":m!==null&&m.wilayas.length===0?"empty":"ok";i.useEffect(()=>{Pc().then(E=>h(E.sectors)).catch(()=>{})},[]);const p=i.useCallback(async()=>{const E=n.split(",").map(P=>P.trim()).filter(Boolean);return await Dk(E,o,t)},[n,o,t]),k=i.useCallback(E=>{x(E),w(y),S(null)},[y]),R=i.useCallback(E=>{N(E instanceof Error?E.message:"Load failed"),S(y),w(null)},[y]),C=i.useCallback(()=>(w(null),S(null),p().then(k,R)),[p,k,R]);return i.useEffect(()=>{let E=!0;return p().then(P=>{E&&k(P)},P=>{E&&R(P)}),()=>{E=!1}},[p,k,R]),e.jsxs("div",{children:[e.jsx(Se,{title:"Logistics Access Comparison",description:"Port proximity, throughput, road/rail and DGD customs sub-scores, side by side (US-9.5)."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(Rp,{label:"Wilayas (comma-separated)",children:e.jsx(me,{value:n,onChange:E=>a(E.target.value),className:"w-50"})}),e.jsx(Rp,{label:"Sector",children:e.jsx(Ie,{value:o,onChange:E=>c(E.target.value),"aria-label":"Sector",children:(u.length?u:[o]).map(E=>e.jsx("option",{value:E,children:E},E))})}),e.jsx(K,{size:"sm",onClick:()=>void C(),children:"Compare"})]})}),g==="loading"&&e.jsx(H,{children:"Loading logistics…"}),g==="error"&&e.jsxs(H,{tone:"error",children:[v,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void C(),children:"Retry"})})]}),g==="empty"&&e.jsx(H,{children:"No logistics scores for these wilayas."}),g==="ok"&&m&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:o}),e.jsxs(je,{className:"min-w-[720px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Wilaya"}),e.jsx(T,{className:"text-right",children:"Composite"}),e.jsx(T,{className:"text-right",children:"Proximity"}),e.jsx(T,{className:"text-right",children:"Throughput"}),e.jsx(T,{className:"text-right",children:"Connectivity"}),e.jsx(T,{className:"text-right",children:"Customs"}),e.jsx(T,{children:"Nearest port"})]})}),e.jsx(ye,{children:m.wilayas.map(E=>e.jsxs(ee,{children:[e.jsxs(A,{children:[E.wilaya_name_fr,E.capacity_expansion_flag&&e.jsx(V,{variant:"success",children:"Expansion"}),E.data_quality_flags.includes("LOW_CONFIDENCE")&&e.jsx(V,{variant:"warning",children:"Low conf"})]}),e.jsx(A,{className:"text-right font-semibold tabular-nums",children:E.composite_logistics_score}),e.jsx(A,{className:"text-right tabular-nums",children:tc(E.components.proximity)}),e.jsx(A,{className:"text-right tabular-nums",children:tc(E.components.throughput)}),e.jsx(A,{className:"text-right tabular-nums",children:tc(E.components.connectivity)}),e.jsx(A,{className:"text-right tabular-nums",children:tc(E.components.customs)}),e.jsxs(A,{children:[E.nearest_port_code," (",E.nearest_port_distance_km," km)",E.second_nearest_port_code&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",E.second_nearest_port_code]})]})]},E.wilaya_code))})]})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"Trade-off"}),e.jsx("p",{className:"text-sm",children:m.trade_off_summary.en}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m.trade_off_summary.fr})]})})]})]})}function Rp({label:t,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:[t,n]})}function tc(t){return t==null?"—":`${Math.round(t*100)}`}function qk({role:t="platform_admin"}){const[n,a]=i.useState("2026-Q2"),[o,c]=i.useState(null),[u,h]=i.useState(""),[m,x]=i.useState(!1),[v,N]=i.useState(!1),[j,w]=i.useState(!1),_=j?"error":v?o&&o.pipeline_run_id?"ok":"empty":"loading",S=i.useCallback(()=>Ik(),[]),y=i.useCallback(E=>{c(E),N(!0),w(!1)},[]),g=i.useCallback(E=>{h(E instanceof Error?E.message:"Load failed"),w(!0),N(!1)},[]),p=i.useCallback(()=>(N(!1),w(!1),S().then(y,g)),[S,y,g]);i.useEffect(()=>{let E=!0;return S().then(P=>{E&&y(P)},P=>{E&&g(P)}),()=>{E=!1}},[S,y,g]);const k=i.useCallback(async()=>{x(!0),h("");try{const E=await Mk(n.trim(),t);c(E),N(!0),w(!1)}catch(E){h(E instanceof Error?E.message:"Pipeline trigger failed"),w(!0),N(!1)}finally{x(!1)}},[n,t]),R=o?(o.duration_ms/1e3).toFixed(1):"0",C=o?o.expected_count===void 0||o.score_count>=o.expected_count:!1;return e.jsxs("div",{children:[e.jsx(Se,{title:"Geo-Siting Pipeline Health",description:"Latest quarterly siting-pipeline run: per-source ingest status, scoring coverage and versions (US-9.1)."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Cycle",e.jsx(me,{value:n,onChange:E=>a(E.target.value),placeholder:"2026-Q2",className:"w-30"})]}),e.jsx(K,{size:"sm",onClick:()=>void k(),disabled:m,children:m?"Running…":"Run pipeline"}),e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void p(),children:"Refresh latest"})]})}),_==="loading"&&e.jsx(H,{children:"Loading pipeline status…"}),_==="error"&&e.jsxs(H,{tone:"error",children:[u,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void p(),children:"Retry"})})]}),_==="empty"&&e.jsx(H,{children:"No pipeline runs recorded yet — trigger a cycle above."}),_==="ok"&&o&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(Sr,{label:"Status",children:e.jsx(V,{variant:o.status==="SUCCESS"||o.status==="COMPLETED"?"success":o.status==="FAILED"?"danger":"warning",children:o.status})}),e.jsx(Sr,{label:"Cycle",children:o.cycle_id}),e.jsx(Sr,{label:"Scores",children:e.jsxs("span",{className:C?"text-success":"text-destructive",children:[o.score_count,o.expected_count!==void 0?` / ${o.expected_count}`:""]})}),e.jsx(Sr,{label:"Low-confidence",children:o.low_confidence_count}),e.jsx(Sr,{label:"Null sub-scores",children:o.null_sub_score_count}),e.jsxs(Sr,{label:"Duration",children:[R,"s"]}),e.jsx(Sr,{label:"Config v",children:o.config_version}),e.jsx(Sr,{label:"Methodology",children:o.methodology_version})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"Source ingest status"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Run ",o.pipeline_run_id," · started ",o.started_at," · finished ",o.finished_at]}),o.sources.length===0?e.jsx(H,{children:"No per-source records for this run."}):e.jsxs(je,{className:"min-w-[420px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Source"}),e.jsx(T,{children:"Status"})]})}),e.jsx(ye,{children:o.sources.map(E=>e.jsxs(ee,{children:[e.jsx(A,{children:E.source}),e.jsx(A,{children:e.jsx(V,{variant:E.status==="OK"||E.status==="SUCCESS"?"success":E.status==="FAILED"?"danger":"warning",children:E.status})})]},E.source))})]})]})})]})]})}function Sr({label:t,children:n}){return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:t}),e.jsx("span",{className:"text-base font-semibold",children:n})]})}const Hs="/v1/dashboard",Nl=t=>({"x-subscriber-tier":t}),ja=t=>({"x-org-role":t.org_role,"x-org-id":t.org_id,"x-user-id":t.user_id,"x-display-name":t.display_name}),Qk=(t,n)=>({...Nl(t),...ja(n)});function eh(t){const n=new URLSearchParams;for(const[o,c]of Object.entries(t))c==null||c===""||c===!1||n.set(o,String(c));const a=n.toString();return a?`?${a}`:""}const Kk=(t,n)=>he(`${Hs}/opportunity-cards${eh(t)}`,Nl(n)),Xk=(t,n)=>he(`${Hs}/opportunity-cards/${encodeURIComponent(t)}/detail`,Nl(n)),Yk=(t,n)=>he(`${Hs}/delta-feed${eh(t)}`,Nl(n)),Zk=(t,n)=>he(`${Hs}/cas-trend/${encodeURIComponent(t)}`,Nl(n)),Jk=(t,n,a)=>he(`${Hs}/search${eh({q:t,locale:a})}`,Nl(n)),eE=t=>he(`${Hs}/filter-presets`,ja(t)),tE=(t,n)=>be(`${Hs}/filter-presets`,t,ja(n)),sE=(t,n,a)=>be(`${Hs}/export-jobs`,{filter_state:t},Qk(n,a)),nE=t=>he(`${Hs}/admin/seats`,ja(t)),rE=(t,n)=>be(`${Hs}/admin/seats`,t,ja(n)),aE=(t,n,a)=>pl(`${Hs}/admin/seats/${t}`,{role:n},ja(a)),lE=(t,n)=>Pm(`${Hs}/admin/seats/${t}`,ja(n)),iE=["","AGRO_FOOD","PHARMACEUTICALS","PETROCHEMICALS","STEEL_METALS","ELECTRICAL_EQUIPMENT","MACHINERY","TEXTILES","CONSTRUCTION_MATERIALS"],oE=t=>t==="green"?"success":t==="amber"?"warning":"danger",cE=t=>t==="HIGH"?"success":t==="MODERATE"?"warning":"danger";function dE({tier:t,identity:n,onOpen:a}){var W;const[o,c]=i.useState(""),[u,h]=i.useState("60"),[m,x]=i.useState(""),[v,N]=i.useState(!1),[j,w]=i.useState(null),[_,S]=i.useState(null),[y,g]=i.useState(""),[p,k]=i.useState(""),[R,C]=i.useState(null),[E,P]=i.useState(null),F=`${o}|${u}|${m}|${v}`,I=E===F?"error":R===F?"ok":"loading",M=i.useCallback(()=>{const se={};return o&&(se.sector=o),u&&(se.cas_min=Number(u)),m&&(se.min_quality=Number(m)),v&&(se.afcfta_only=!0),se},[o,u,m,v]),$=i.useCallback(async()=>Kk(M(),t),[M,t]),O=i.useCallback(se=>{w(se),g(""),C(F),P(null)},[F]),L=i.useCallback(se=>{g(se instanceof Error?se.message:"Failed"),P(F),C(null)},[F]),z=i.useCallback(()=>(C(null),P(null),$().then(O,L)),[$,O,L]),Y=i.useCallback(()=>{eE(n).then(S).catch(()=>{})},[n]);i.useEffect(()=>{let se=!0;return $().then(ne=>{se&&O(ne)},ne=>{se&&L(ne)}),Y(),()=>{se=!1}},[$,O,L,Y]);const G=async()=>{const se=window.prompt("Preset name");if(se)try{await tE({preset_name:se,filter_state:M(),sharing_scope:"team"},n),k(`Saved preset "${se}"`),Y()}catch(ne){k(ne instanceof Error?ne.message:"Save failed")}},U=async()=>{try{const se=await sE(M(),t,n);k(`Export ${se.job_status}: ${se.card_count} card(s)`)}catch(se){k(se instanceof Error?se.message:"Export failed")}},ae=se=>{c(String(se.sector??"")),h(se.cas_min!==void 0?String(se.cas_min):""),x(se.min_quality!==void 0?String(se.min_quality):""),N(!!se.afcfta_only)};return e.jsxs("div",{children:[e.jsx(Se,{title:"Opportunity Cards Dashboard",description:"Compound filter over CAS-scored, regulation-checked opportunity cards (US-10.1)."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(zu,{label:"Sector",children:e.jsx(Ie,{value:o,onChange:se=>c(se.target.value),"aria-label":"Sector",children:iE.map(se=>e.jsx("option",{value:se,children:se||"Any"},se))})}),e.jsx(zu,{label:"Min CAS",children:e.jsx(me,{type:"number",value:u,onChange:se=>h(se.target.value),className:"w-24"})}),e.jsx(zu,{label:"Min quality (US-18.4)",children:e.jsx(me,{type:"number",value:m,onChange:se=>x(se.target.value),placeholder:"any",className:"w-24"})}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:se=>N(se.target.checked),className:"size-4 accent-primary"})," AfCFTA only"]}),e.jsx(K,{size:"sm",onClick:()=>void z(),children:"Apply Filters"}),e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void G(),children:"Save Preset"}),e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void U(),children:"Export JSON"})]})}),_&&(_.my_presets.length>0||_.team_presets.length>0)&&e.jsx(B,{className:"mt-3 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("div",{className:"mb-1.5 text-xs text-muted-foreground",children:"Filter presets"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[..._.my_presets,..._.team_presets].map(se=>e.jsx("button",{onClick:()=>ae(se.filter_state),className:"cursor-pointer rounded-full bg-muted px-3 py-1 text-xs text-foreground transition-colors hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",title:`by ${se.created_by_display_name}`,children:se.preset_name},se.preset_id))})]})}),p&&e.jsx(H,{children:p}),I==="loading"&&e.jsx(H,{children:"Loading opportunity cards…"}),I==="error"&&e.jsx(H,{tone:"error",children:y}),I==="ok"&&j&&j.total_matched_count===0&&e.jsx(H,{children:((W=j.empty_state)==null?void 0:W.message)??(m?"No results match your quality filter.":"No cards match these filters.")}),I==="ok"&&j&&j.total_matched_count>0&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[j.total_matched_count," result(s) · cycle ",j.cycle_id," · ",j.query_duration_ms," ms",m&&e.jsx("span",{className:"ml-2",children:e.jsxs(V,{variant:"secondary",children:["min quality ≥ ",m]})})]}),j.truncated_banner&&e.jsx(V,{variant:"warning",children:j.truncated_banner}),e.jsx("div",{className:"mt-3 grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-4",children:j.results.map(se=>e.jsxs("button",{onClick:()=>a(se.card_id),className:"cursor-pointer rounded-xl border bg-card p-4 text-start shadow-sm transition-colors hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",children:[e.jsxs("div",{className:"flex items-center justify-between gap-1.5",children:[e.jsx("strong",{className:"font-mono text-sm",children:se.hs6_code}),e.jsxs("span",{className:"flex gap-1",children:[se.data_quality&&se.data_quality.composite_score!==null&&e.jsxs(V,{variant:cE(se.data_quality.quality_band),children:["Q ",se.data_quality.composite_score]}),e.jsxs(V,{variant:oE(se.cas_band),children:["CAS ",se.cas_score]})]})]}),e.jsx("div",{className:"mt-1 text-sm",children:se.product_name_fr}),e.jsx("div",{dir:"rtl",lang:"ar",className:"text-xs text-muted-foreground",children:se.product_name_ar}),e.jsxs("div",{className:"mt-1.5 text-xs text-muted-foreground",children:[se.sector," · ",se.capex_bracket," · ",e.jsx("span",{className:"tabular-nums",children:Xe(se.capex_midpoint_usd)})]}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1",children:[se.daps_applicable&&e.jsxs(V,{variant:"warning",children:["DAPS ",se.daps_rate_percent??"","%"]}),se.afcfta_applicable&&e.jsx(V,{variant:"success",children:"AfCFTA"}),se.top_wilaya_name_fr&&e.jsx(V,{variant:"secondary",children:se.top_wilaya_name_fr})]})]},se.card_id))})]})})]})}function zu({label:t,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:[t,n]})}const uE=t=>t==="MARKET_DEPTH_ALERT"?"warning":t==="TARIFF_REGIME_CHANGE"?"danger":"secondary";function mE({tier:t}){const[n,a]=i.useState(""),[o,c]=i.useState(!1),[u,h]=i.useState(null),[m,x]=i.useState(""),[v,N]=i.useState(null),[j,w]=i.useState(null),_=`${t}|${n}|${o?"band":"all"}`,S=j===_?"error":v===_?"ok":"loading",y=i.useCallback(async()=>Yk({direction:n,band_change_only:o},t),[n,o,t]),g=i.useCallback(R=>{h(R),x(""),N(_),w(null)},[_]),p=i.useCallback(R=>{x(R instanceof Error?R.message:"Failed"),w(_),N(null)},[_]);i.useEffect(()=>{let R=!0;return y().then(C=>{R&&g(C)},C=>{R&&p(C)}),()=>{R=!1}},[y,g,p]);const k=i.useCallback(()=>(N(null),w(null),y().then(g,p)),[y,g,p]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Quarterly Delta-Change Feed",description:"HS6 lines whose CAS band changed or moved materially since the prior cycle (US-10.2)."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Direction",e.jsxs(Ie,{value:n,onChange:R=>a(R.target.value),children:[e.jsx("option",{value:"",children:"Any"}),e.jsx("option",{value:"improved",children:"Improved"}),e.jsx("option",{value:"deteriorated",children:"Deteriorated"})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:R=>c(R.target.checked),className:"size-4 accent-primary"})," Band changes only"]}),e.jsx(K,{size:"sm",onClick:()=>void k(),children:"Refresh"})]})}),S==="loading"&&e.jsx(H,{children:"Loading delta feed…"}),S==="error"&&e.jsx(H,{tone:"error",children:m}),S==="ok"&&u&&u.entries.length===0&&e.jsx(H,{children:"No material changes this cycle."}),S==="ok"&&u&&u.entries.length>0&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[u.total_count," change(s) · ",u.prior_cycle_id," → ",u.current_cycle_id]}),u.few_changes_note&&e.jsx(V,{variant:"secondary",children:u.few_changes_note}),e.jsxs(je,{className:"mt-3",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Product"}),e.jsx(T,{children:"Δ"}),e.jsx(T,{children:"Band"}),e.jsx(T,{children:"Driver"}),e.jsx(T,{children:"Flags"})]})}),e.jsx(ye,{children:u.entries.map(R=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:R.hs6_code}),e.jsxs(A,{children:[R.product_name_fr,e.jsx("div",{dir:"rtl",lang:"ar",className:"text-[11px] text-muted-foreground",children:R.product_name_ar})]}),e.jsxs(A,{className:`font-bold tabular-nums ${R.score_delta>=0?"text-success":"text-destructive"}`,children:[R.score_delta>=0?"+":"",R.score_delta]}),e.jsx(A,{children:e.jsx(V,{variant:R.band_changed?"warning":"secondary",children:R.band_transition})}),e.jsxs(A,{className:"tabular-nums",children:[R.driving_sub_dimension," (",R.driving_sub_dimension_delta>=0?"+":"",R.driving_sub_dimension_delta,")"]}),e.jsxs(A,{children:[R.flags.map(C=>e.jsx(V,{variant:uE(C),children:C},C)),R.change_type==="new_entry"&&e.jsx(V,{variant:"success",children:"NEW"})]})]},R.hs6_code))})]})]})})]})}function hE({tier:t}){const[n,a]=i.useState("idle"),[o,c]=i.useState("100199"),[u,h]=i.useState(null),[m,x]=i.useState(""),v=i.useCallback(async()=>{a("loading"),x("");try{h(await Zk(o.trim(),t)),a("ok")}catch(N){x(N instanceof Error?N.message:"Failed"),a("error")}},[o,t]);return e.jsxs("div",{children:[e.jsx(Se,{title:"CAS Score Trend",description:"Composite CAS across up to four quarterly cycles with exogenous-event annotations (US-10.4)."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["HS6",e.jsx(me,{value:o,onChange:N=>c(N.target.value),className:"w-30"})]}),e.jsx(K,{size:"sm",onClick:()=>void v(),children:"Show Trend"})]})}),n==="idle"&&e.jsx(H,{children:"Enter an HS6 code to view its CAS trajectory."}),n==="loading"&&e.jsx(H,{children:"Loading trend…"}),n==="error"&&e.jsx(H,{tone:"error",children:m}),n==="ok"&&u&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[u.hs6_code," · ",u.product_name_fr]}),u.data_vintage_warning&&e.jsxs(V,{variant:"warning",children:["Only ",u.available_cycles," of ",u.window_size," cycles available"]}),e.jsx("div",{className:"mt-4 flex h-40 items-end gap-2",children:u.cycles.map(N=>e.jsxs("div",{className:"flex flex-1 flex-col items-center gap-1",children:[e.jsx("div",{className:"text-xs font-bold",children:N.composite_score}),e.jsx("div",{title:`${N.cas_band}`,className:"w-3/5 rounded-sm",style:{height:`${N.composite_score}%`,background:N.cas_band==="green"?"var(--success)":N.cas_band==="amber"?"var(--warning)":"var(--destructive)"}}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:N.quarter_label}),N.composite_delta_vs_prior!==null&&e.jsxs("div",{className:`text-[11px] ${N.composite_delta_vs_prior>=0?"text-success":"text-destructive"}`,children:[N.composite_delta_vs_prior>=0?"+":"",N.composite_delta_vs_prior]})]},N.cycle_id))}),u.annotations.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"mb-1.5 text-xs text-muted-foreground",children:"Event annotations"}),u.annotations.map(N=>e.jsxs("div",{className:"mb-1",children:[e.jsx(V,{variant:"secondary",children:N.effective_cycle})," ",e.jsx("span",{className:"text-sm",children:N.event_label.en})]},N.annotation_id))]})]})})]})}const fE=t=>t==="green"?"success":t==="amber"?"warning":"danger";function xE({tier:t,onOpen:n}){var w;const[a,o]=i.useState("idle"),[c,u]=i.useState(""),[h,m]=i.useState(null),[x,v]=i.useState(""),N=i.useRef(null),j=i.useCallback(async _=>{if(!_.trim()){o("idle"),m(null);return}o("loading"),v("");try{m(await Jk(_.trim(),t)),o("ok")}catch(S){v(S instanceof Error?S.message:"Failed"),o("error")}},[t]);return i.useEffect(()=>(N.current&&clearTimeout(N.current),N.current=setTimeout(()=>void j(c),300),()=>{N.current&&clearTimeout(N.current)}),[c,j]),e.jsxs("div",{children:[e.jsx(Se,{title:"Opportunity Search",description:"Free-text search across FR/EN/AR product names + translation memory (US-10.5)."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsx("div",{className:"px-4",children:e.jsx(me,{value:c,onChange:_=>u(_.target.value),placeholder:"e.g. acier, principe actif, 300490…","aria-label":"Search products"})})}),a==="loading"&&e.jsx(H,{children:"Searching…"}),a==="error"&&e.jsx(H,{tone:"error",children:x}),a==="ok"&&h&&h.results.length===0&&e.jsxs(H,{children:[(w=h.empty_state)==null?void 0:w.message," ",h.did_you_mean&&e.jsxs(e.Fragment,{children:["· Did you mean ",e.jsx("strong",{children:h.did_you_mean}),"?"]}),h.empty_state&&e.jsx("div",{className:"mt-1.5",children:h.empty_state.suggestions.map(_=>e.jsx(V,{variant:"secondary",children:_},_))})]}),a==="ok"&&h&&h.results.length>0&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[h.total_count," result(s)",h.mode==="hs6_code"?" · HS6 match":""]}),h.truncated&&h.truncated_banner&&e.jsx(V,{variant:"warning",children:h.truncated_banner}),h.did_you_mean&&e.jsxs("div",{className:"my-1.5 text-sm",children:["Did you mean ",e.jsx("strong",{children:h.did_you_mean}),"?"]}),e.jsx("div",{className:"mt-2 flex flex-col gap-2",children:h.results.map(_=>e.jsxs("button",{onClick:()=>n(_.card_id),className:"flex cursor-pointer items-center justify-between gap-3 rounded-xl border bg-card p-4 text-start shadow-sm transition-colors hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{children:[e.jsx("strong",{className:"font-mono text-sm",children:_.hs6_code})," · ",_.product_name_fr," ",e.jsxs("span",{className:"text-muted-foreground",children:["/ ",_.product_name_en]})]}),e.jsx("div",{dir:"rtl",lang:"ar",className:"text-xs text-muted-foreground",children:_.product_name_ar})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[_.terminology_match&&e.jsx(V,{variant:"success",children:"Terminology Match"}),e.jsxs(V,{variant:fE(_.cas_band),children:["CAS ",_.cas_score]})]})]},_.card_id))})]})})]})}const Pp=["read_only_analyst","full_analyst","org_admin"],pE=t=>t==="active"?"success":t==="invited"?"warning":"secondary";function gE({identity:t}){const[n,a]=i.useState(null),[o,c]=i.useState(""),[u,h]=i.useState(""),[m,x]=i.useState("full_analyst"),[v,N]=i.useState(""),[j,w]=i.useState(null),[_,S]=i.useState(null),y=_===t?"error":j===t?"ok":"loading",g=i.useCallback(async()=>nE(t),[t]),p=i.useCallback(F=>{a(F),c(""),w(t),S(null)},[t]),k=i.useCallback(F=>{c(F instanceof Error?F.message:"Failed"),S(t),w(null)},[t]),R=i.useCallback(()=>(w(null),S(null),g().then(p,k)),[g,p,k]);i.useEffect(()=>{let F=!0;return g().then(I=>{F&&p(I)},I=>{F&&k(I)}),()=>{F=!1}},[g,p,k]);const C=async()=>{if(u.trim())try{await rE({invitation_email:u.trim(),role:m},t),N(`Invited ${u}`),h(""),R()}catch(F){N(F instanceof Error?F.message:"Invite failed")}},E=async(F,I)=>{try{await aE(F,I,t),R()}catch(M){N(M instanceof Error?M.message:"Role change failed")}},P=async F=>{try{const I=await lE(F,t);N(`Removed seat · ${I.archived_presets} preset(s) archived`),R()}catch(I){N(I instanceof Error?I.message:"Remove failed")}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Seat & Role Administration",description:"Manage your organisation's contracted seats and role permissions (US-10.8)."}),y==="loading"&&e.jsx(H,{children:"Loading seats…"}),y==="error"&&e.jsx(H,{tone:"error",children:o}),v&&e.jsx(H,{children:v}),y==="ok"&&n&&e.jsxs(e.Fragment,{children:[n.near_limit_warning&&e.jsxs(H,{tone:"error",children:["Warning: your organisation is within ",n.warn_threshold," seat(s) of its contracted limit of ",n.contracted_seat_limit,"."]}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-4 px-4",children:[e.jsx(Uu,{label:"Contracted",value:n.contracted_seat_limit}),e.jsx(Uu,{label:"Assigned",value:n.seats_assigned}),e.jsx(Uu,{label:"Remaining",value:n.seats_remaining})]})}),e.jsx(B,{className:"mt-3 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsx(Tp,{label:"Invite email",children:e.jsx(me,{value:u,onChange:F=>h(F.target.value),className:"w-50"})}),e.jsx(Tp,{label:"Role",children:e.jsx(Ie,{value:m,onChange:F=>x(F.target.value),"aria-label":"Invite role",children:Pp.map(F=>e.jsx("option",{value:F,children:F},F))})}),e.jsx(K,{size:"sm",onClick:()=>void C(),disabled:n.seats_remaining<=0,children:"Invite Analyst"})]})}),e.jsx(B,{className:"mt-3 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"Seat holders"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Name"}),e.jsx(T,{children:"Email"}),e.jsx(T,{children:"Role"}),e.jsx(T,{children:"Status"}),e.jsx(T,{})]})}),e.jsx(ye,{children:n.items.map(F=>e.jsxs(ee,{children:[e.jsx(A,{children:F.display_name}),e.jsx(A,{children:F.email}),e.jsx(A,{children:e.jsx(Ie,{value:F.role,onChange:I=>void E(F.seat_id,I.target.value),"aria-label":`Role for ${F.display_name}`,disabled:F.seat_status==="inactive",children:Pp.map(I=>e.jsx("option",{value:I,children:I},I))})}),e.jsx(A,{children:e.jsx(V,{variant:pE(F.seat_status),children:F.seat_status})}),e.jsx(A,{children:F.seat_status!=="inactive"&&e.jsx(K,{variant:"destructive",size:"sm",onClick:()=>void P(F.seat_id),children:"Remove"})})]},F.seat_id))})]})]})})]})]})}function Uu({label:t,value:n}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:t}),e.jsx("div",{className:"text-2xl font-bold",children:n})]})}function Tp({label:t,children:n}){return e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:[t,n]})}const _m={cas_score:"CAS Score",financial_model_summary:"Financial Model",capex_opex_scenarios:"CAPEX / OPEX",bom_summary:"Equipment BoM",regulatory_roadmap:"Regulatory Roadmap",wilaya_siting:"Wilaya Siting",legal_structure:"51/49 Legal Structure",afcfta_export_markets:"AfCFTA Markets",source_citations:"Sources"};function vE({cardId:t,tier:n}){const[a,o]=i.useState(null),[c,u]=i.useState(""),[h,m]=i.useState(null),[x,v]=i.useState(null),N=t?x===t?"error":h===t?"ok":"loading":"idle",j=i.useCallback(async()=>t?Xk(t,n):null,[t,n]),w=i.useCallback(g=>{o(g),u(""),m(t),v(null)},[t]),_=i.useCallback(g=>{u(g instanceof Error?g.message:"Failed"),v(t),m(null)},[t]);if(i.useEffect(()=>{let g=!0;return j().then(p=>{g&&p&&w(p)},p=>{g&&_(p)}),()=>{g=!1}},[j,w,_]),N==="idle")return e.jsx(H,{children:"Open a card from the dashboard or search to see its full nine-section view."});if(N==="loading")return e.jsx(H,{children:"Loading card detail…"});if(N==="error")return e.jsx(H,{tone:"error",children:c});if(!a)return e.jsx(H,{children:"Not found."});const S=a.sections,y=S.legal_structure;return e.jsxs("div",{children:[e.jsx(Se,{title:e.jsxs(e.Fragment,{children:[a.hs6_code," · ",a.product_name.fr]}),description:e.jsx("span",{dir:"rtl",lang:"ar",children:a.product_name.ar}),meta:e.jsxs(e.Fragment,{children:["Full opportunity card · cycle ",e.jsx("span",{className:"font-mono",children:a.cycle_id})," · band ",a.cas_band," (US-10.3)"]})}),e.jsx("nav",{"aria-label":"Card sections",className:"sticky top-0 z-10 flex flex-wrap gap-2 border-b bg-card py-2",children:Object.keys(_m).map(g=>e.jsx("a",{href:`#sec-${g}`,className:"rounded-full border px-2.5 py-0.5 text-xs text-muted-foreground no-underline transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",children:_m[g]},g))}),a.generation_cycle_note&&e.jsx(H,{children:a.generation_cycle_note}),e.jsxs("div",{id:"sec-legal_structure",className:"mt-4 rounded-xl border-2 border-destructive bg-destructive/10 p-4",children:[e.jsx("strong",{className:"text-destructive",children:"51/49 Foreign-Equity Rule (mandatory)"}),e.jsx("p",{className:"mt-1.5",children:y.mandatory_warning.fr}),e.jsx("p",{className:"mt-0.5 text-muted-foreground",children:y.mandatory_warning.en}),e.jsx("p",{dir:"rtl",className:"mt-0.5 text-muted-foreground",children:y.mandatory_warning.ar}),e.jsxs("div",{className:"mt-1.5 text-xs text-muted-foreground",children:[y.recommended_vehicle," · ",y.legal_provision_citation]})]}),e.jsx(Cr,{id:"cas_score",children:e.jsx(jE,{v:S.cas_score})}),e.jsx(zj,{cardId:a.card_id,tier:n}),e.jsx(Cr,{id:"financial_model_summary",children:e.jsx(_i,{className:"break-words",children:Bu(S.financial_model_summary)})}),e.jsx(Cr,{id:"capex_opex_scenarios",children:e.jsx(yE,{v:S.capex_opex_scenarios})}),e.jsx(Cr,{id:"bom_summary",children:e.jsx(_i,{className:"break-words",children:Bu(S.bom_summary)})}),e.jsx(Cr,{id:"regulatory_roadmap",children:e.jsx(_E,{v:S.regulatory_roadmap})}),e.jsx(Cr,{id:"wilaya_siting",children:e.jsx(bE,{v:S.wilaya_siting})}),e.jsx(Cr,{id:"afcfta_export_markets",children:e.jsx(_i,{className:"break-words",children:Bu(S.afcfta_export_markets)})}),e.jsx(Cr,{id:"source_citations",children:e.jsx(NE,{v:S.source_citations})})]})}function Cr({id:t,children:n}){return e.jsx(B,{className:"mt-4 py-4",id:`sec-${t}`,children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:_m[t]}),n]})})}function jE({v:t}){const n=t;return e.jsxs("div",{children:[e.jsxs(V,{variant:n.band==="green"?"success":n.band==="amber"?"warning":"danger",children:["Composite ",n.composite]}),e.jsx("div",{className:"mt-3 grid grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-2",children:Object.entries(n.sub_dimensions).map(([a,o])=>e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:a}),e.jsx("div",{className:"font-bold",children:o})]},a))})]})}function yE({v:t}){const n=t;return e.jsx("div",{className:"flex flex-wrap gap-6",children:["bear","base","bull"].map(a=>e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:a.toUpperCase()}),e.jsxs("div",{children:["CAPEX ",Xe(n.capex_usd[a])]}),e.jsxs("div",{children:["OPEX/yr ",Xe(n.opex_usd_annual[a])]})]},a))})}function _E({v:t}){const n=t;return e.jsx("ol",{className:"m-0 ps-[18px]",children:n.steps.map(a=>e.jsxs("li",{className:"mb-1.5",children:[e.jsx("strong",{children:a.step})," — ",a.authority," · ~",a.estimated_weeks,"w · ",a.legal_instrument]},a.step))})}function bE({v:t}){const n=t;return e.jsx("div",{className:"flex flex-wrap gap-3",children:n.map(a=>e.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[e.jsxs("strong",{children:["#",a.rank," ",a.wilaya_name_fr]}),e.jsx("div",{dir:"rtl",className:"text-xs text-muted-foreground",children:a.wilaya_name_ar}),e.jsx("div",{className:"font-bold",children:a.composite_siting_score})]},a.rank))})}function NE({v:t}){const n=t;return e.jsx("ul",{className:"m-0 ps-[18px]",children:n.map(a=>e.jsxs("li",{children:[e.jsx("strong",{children:a.source_id}),a.fields.length?` — ${a.fields.join(", ")}`:""]},a.source_id))})}function Bu(t){return JSON.stringify(t,null,2)}const Kn="/v1/dfi",fl=[{label:"AfDB (Tier 1)",client_id:"client-afdb-0001",client_secret:"sandbox-secret-afdb-tier1-0001"},{label:"AFD (Tier 2)",client_id:"client-afd-0002",client_secret:"sandbox-secret-afd-tier2-0002"},{label:"Advisory (Tier 3)",client_id:"client-advisory-0003",client_secret:"sandbox-secret-advisory-tier3-0003"},{label:"Platform Admin",client_id:"client-platform-admin",client_secret:"sandbox-secret-platform-admin-0000"}],Dr=t=>({Authorization:`Bearer ${t}`}),th=(t,n)=>be(`${Kn}/auth/token`,{grant_type:"client_credentials",client_id:t,client_secret:n}),wE=(t,n,a)=>he(`${Kn}/hs6-lines/${n}/cas-score`,Dr(t)),qj=(t,n)=>{const a=new URLSearchParams(n).toString();return he(`${Kn}/opportunity-cards${a?`?${a}`:""}`,Dr(t))},SE=t=>he(`${Kn}/sectors`,Dr(t)),Lp=t=>he(`${Kn}/admin/subscribers`,Dr(t)),CE=(t,n)=>be(`${Kn}/admin/subscribers`,n,Dr(t)),kE=(t,n)=>he(`${Kn}/admin/api-keys?subscriber_id=${encodeURIComponent(n)}`,Dr(t)),EE=(t,n)=>be(`${Kn}/admin/api-keys`,{subscriber_id:n},Dr(t)),AE=(t,n)=>Pm(`${Kn}/admin/api-keys/${encodeURIComponent(n)}`,Dr(t)),RE=[{method:"POST",path:"/api/v1/dfi/auth/token",scope:"—",summary:"OAuth 2.0 client-credentials → JWT"},{method:"GET",path:"/api/v1/dfi/auth/jwks",scope:"—",summary:"JWK set (token verification key)"},{method:"POST",path:"/api/v1/dfi/auth/rotate-secret",scope:"any",summary:"Rotate the caller’s client secret"},{method:"POST",path:"/api/v1/dfi/auth/revoke",scope:"any/admin",summary:"Revoke a token / client"},{method:"GET",path:"/api/v1/dfi/hs6-lines/{hs6}/cas-score",scope:"tierN:cas:read",summary:"CAS score with per-field citations"},{method:"GET",path:"/api/v1/dfi/opportunity-cards",scope:"tierN:cards:read",summary:"Paginated opportunity cards"},{method:"GET",path:"/api/v1/dfi/opportunity-cards/{card_id}",scope:"tierN:cards:read",summary:"One opportunity card"},{method:"GET",path:"/api/v1/dfi/sectors",scope:"tierN:cards:read",summary:"Sector taxonomy"},{method:"GET",path:"/api/v1/dfi/capex-brackets",scope:"tierN:cards:read",summary:"CAPEX bracket config"},{method:"POST",path:"/api/v1/dfi/admin/subscribers",scope:"admin",summary:"Provision a subscriber + credentials"},{method:"POST",path:"/api/v1/dfi/admin/api-keys",scope:"admin",summary:"Create an API key"},{method:"POST",path:"/api/v1/dfi/integrations/aapi-portal/push",scope:"admin",summary:"Push cards to the AAPI portal"}];function PE(){const[t,n]=i.useState(fl[0].client_id),[a,o]=i.useState(null),[c,u]=i.useState("idle"),[h,m]=i.useState(""),[x,v]=i.useState("151530"),[N,j]=i.useState(null),[w,_]=i.useState("idle"),[S,y]=i.useState(""),[g,p]=i.useState(null),[k,R]=i.useState("idle"),[C,E]=i.useState(""),P=i.useCallback(async()=>{const M=fl.find($=>$.client_id===t);if(M){u("loading"),m(""),j(null),_("idle"),p(null),R("idle");try{o(await th(M.client_id,M.client_secret)),u("ok")}catch($){m($ instanceof Error?$.message:"Token request failed"),u("error")}}},[t]),F=i.useCallback(async()=>{if(a){_("loading"),y("");try{j(await wE(a.access_token,x.trim())),_("ok")}catch(M){y(M instanceof Error?M.message:"CAS query failed"),_("error")}}},[a,x]),I=i.useCallback(async()=>{if(a){R("loading"),E("");try{p(await qj(a.access_token,{page:"1",page_size:"5"})),R("ok")}catch(M){E(M instanceof Error?M.message:"Card query failed"),R("error")}}},[a]);return e.jsxs("div",{children:[e.jsx(Se,{title:"DFI Developer Portal",description:"OAuth 2.0 client-credentials, per-field source citations, and the full documented endpoint catalogue for Tier 1–3 API consumers (Epic 12)"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Sandbox credential",e.jsx(Ie,{value:t,onChange:M=>n(M.target.value),"aria-label":"Sandbox credential",children:fl.map(M=>e.jsx("option",{value:M.client_id,children:M.label},M.client_id))})]}),e.jsx(K,{size:"sm",onClick:()=>void P(),children:"Request access token"})]})}),c==="loading"&&e.jsx(H,{children:"Requesting token…"}),c==="error"&&e.jsx(H,{tone:"error",children:h}),c==="ok"&&a&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Access token"}),e.jsxs("div",{className:"flex flex-wrap gap-5 px-4",children:[e.jsx(al,{label:"Type",children:a.token_type}),e.jsxs(al,{label:"Expires in",children:[a.expires_in,"s"]}),e.jsxs(al,{label:"JTI",children:[a.jti.slice(0,8),"…"]})]}),e.jsx("p",{className:"px-4 text-xs text-muted-foreground",children:"Granted scopes:"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 px-4",children:a.scope.split(" ").map(M=>e.jsx(V,{variant:"info",children:M},M))})]}),a&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Try it — CAS score"}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["HS6",e.jsx(me,{value:x,onChange:M=>v(M.target.value),className:"w-30","aria-label":"HS6 code"})]}),e.jsx(K,{size:"sm",onClick:()=>void F(),children:"GET /cas-score"})]}),w==="loading"&&e.jsx(H,{children:"Querying…"}),w==="error"&&e.jsx(H,{tone:"error",children:S}),w==="ok"&&N&&e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-5",children:[e.jsx(al,{label:"Composite CAS",children:N.composite_cas_score}),e.jsx(al,{label:"Cycle",children:N.cas_version}),e.jsx(al,{label:"Low-confidence",children:N.low_confidence_flag?"yes":"no"})]}),e.jsxs(je,{className:"min-w-[480px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Dimension"}),e.jsx(T,{className:"text-right",children:"Raw"}),e.jsx(T,{className:"text-right",children:"Weight"}),e.jsx(T,{children:"Confidence"}),e.jsx(T,{className:"text-right",children:"Citations"})]})}),e.jsx(ye,{children:Object.entries(N.dimensions).map(([M,$])=>e.jsxs(ee,{children:[e.jsx(A,{children:M}),e.jsx(A,{className:"text-right tabular-nums",children:$.raw_score}),e.jsx(A,{className:"text-right tabular-nums",children:$.weight}),e.jsx(A,{children:e.jsx(V,{variant:$.confidence_level==="high"?"success":$.confidence_level==="low"?"danger":"warning",children:$.confidence_level})}),e.jsx(A,{className:"text-right tabular-nums",children:$.source_citations.length})]},M))})]})]})]}),a&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Try it — Opportunity cards"}),e.jsx("div",{className:"px-4",children:e.jsx(K,{size:"sm",onClick:()=>void I(),children:"GET /opportunity-cards"})}),k==="loading"&&e.jsx(H,{children:"Querying…"}),k==="error"&&e.jsx(H,{tone:"error",children:C}),k==="ok"&&g&&(g.cards.length===0?e.jsx(H,{children:"No published cards for this cycle."}):e.jsxs("p",{className:"px-4 text-sm text-foreground",children:[g.meta.total_cards," cards · cycle ",g.meta.cycle," · first: ",e.jsx("strong",{children:g.cards[0].hs6_code})," (",g.cards[0].sector,") CAS ",g.cards[0].composite_cas_score,g.cards[0].watermark_required?" · watermarked":""]}))]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Endpoint catalogue"}),e.jsxs(je,{className:"min-w-[560px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Method"}),e.jsx(T,{children:"Path"}),e.jsx(T,{children:"Scope"}),e.jsx(T,{children:"Summary"})]})}),e.jsx(ye,{children:RE.map(M=>e.jsxs(ee,{children:[e.jsx(A,{children:e.jsx(V,{variant:M.method==="GET"?"info":"warning",children:M.method})}),e.jsx(A,{className:"font-mono text-xs",children:M.path}),e.jsx(A,{children:M.scope}),e.jsx(A,{children:M.summary})]},`${M.method} ${M.path}`))})]})]})]})}function al({label:t,children:n}){return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:t}),e.jsx("span",{className:"text-[15px] font-semibold",children:n})]})}const Fp={client_id:"client-platform-admin",client_secret:"sandbox-secret-platform-admin-0000"};function TE(){const[t,n]=i.useState(null),[a,o]=i.useState(""),[c,u]=i.useState([]),[h,m]=i.useState(!1),[x,v]=i.useState(!1),[N,j]=i.useState("IsDB"),[w,_]=i.useState("1"),[S,y]=i.useState(null),[g,p]=i.useState(""),[k,R]=i.useState([]),[C,E]=i.useState(null),[P,F]=i.useState(""),I=x?"error":h?c.length>0?"ok":"empty":"loading",M=i.useCallback(async()=>{const ae=(await th(Fp.client_id,Fp.client_secret)).access_token,W=await Lp(ae);return{token:ae,subs:W.subscribers}},[]),$=i.useCallback(ae=>{n(ae.token),u(ae.subs),o(""),m(!0),v(!1)},[]),O=i.useCallback(ae=>{o(ae instanceof Error?ae.message:"Admin bootstrap failed"),v(!0),m(!1)},[]);i.useEffect(()=>{let ae=!0;return M().then(W=>{ae&&$(W)},W=>{ae&&O(W)}),()=>{ae=!1}},[M,$,O]);const L=i.useCallback(()=>(o(""),m(!1),v(!1),M().then($,O)),[M,$,O]),z=i.useCallback(async()=>{if(t){o(""),y(null);try{const ae=await CE(t,{institution_code:N.trim(),tier:Number(w)});y({client_id:ae.client_id,client_secret:ae.client_secret}),u((await Lp(t)).subscribers)}catch(ae){o(ae instanceof Error?ae.message:"Provisioning failed")}}},[t,N,w]),Y=i.useCallback(async ae=>{if(t){p(ae),E(null),F("");try{R((await kE(t,ae)).keys)}catch(W){F(W instanceof Error?W.message:"Key load failed")}}},[t]),G=i.useCallback(async()=>{if(!(!t||!g)){F("");try{const ae=await EE(t,g);E(ae.api_key),await Y(g)}catch(ae){F(ae instanceof Error?ae.message:"Create failed")}}},[t,g,Y]),U=i.useCallback(async ae=>{if(t)try{await AE(t,ae),await Y(g)}catch(W){F(W instanceof Error?W.message:"Revoke failed")}},[t,g,Y]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Admin — API Credentials",description:"Onboard Tier-1 DFI subscribers, provision OAuth credentials, and administer API keys (Epic 12, US-12.1)"}),I==="loading"&&e.jsx(H,{children:"Authenticating as platform admin…"}),I==="error"&&e.jsxs(H,{tone:"error",children:[a,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void L(),children:"Retry"})})]}),(I==="ok"||I==="empty")&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Institution",e.jsx(me,{value:N,onChange:ae=>j(ae.target.value),className:"w-35","aria-label":"Institution code"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Tier",e.jsxs(Ie,{value:w,onChange:ae=>_(ae.target.value),"aria-label":"Tier",children:[e.jsx("option",{value:"1",children:"1"}),e.jsx("option",{value:"2",children:"2"}),e.jsx("option",{value:"3",children:"3"})]})]}),e.jsx(K,{size:"sm",onClick:()=>void z(),children:"Provision subscriber"})]})}),a&&e.jsx(H,{tone:"error",children:a}),S&&e.jsxs(B,{className:"mt-4 gap-2 border-success py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Credential issued — shown once"}),e.jsxs("p",{className:"px-4 font-mono text-sm",children:["client_id: ",S.client_id]}),e.jsxs("p",{className:"px-4 font-mono text-sm",children:["client_secret: ",S.client_secret]}),e.jsx("p",{className:"px-4 text-xs text-destructive",children:"Deliver via encrypted channel. The secret is stored only as a hash and cannot be shown again."})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Subscribers"}),c.length===0?e.jsx(H,{children:"No subscribers yet — provision one above."}):e.jsxs(je,{className:"min-w-[520px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Institution"}),e.jsx(T,{children:"Tier"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Keys"})]})}),e.jsx(ye,{children:c.map(ae=>e.jsxs(ee,{children:[e.jsx(A,{children:ae.institution_code}),e.jsx(A,{className:"text-right tabular-nums",children:String(ae.tier)}),e.jsx(A,{children:e.jsx(V,{variant:ae.subscription_status==="ACTIVE"?"success":"warning",children:ae.subscription_status})}),e.jsx(A,{children:e.jsx(K,{variant:"secondary",size:"xs",onClick:()=>void Y(ae.subscriber_id),children:"Manage keys"})})]},ae.subscriber_id))})]})]}),g&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["API keys — ",g]}),e.jsx("div",{className:"px-4",children:e.jsx(K,{size:"sm",onClick:()=>void G(),children:"Create API key"})}),P&&e.jsx(H,{tone:"error",children:P}),C&&e.jsxs("p",{className:"px-4 font-mono text-sm text-success",children:["New key (shown once): ",C]}),k.length===0?e.jsx(H,{children:"No API keys for this subscriber."}):e.jsxs(je,{className:"mt-2 min-w-[420px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Key"}),e.jsx(T,{children:"Created"}),e.jsx(T,{children:"Status"}),e.jsx(T,{})]})}),e.jsx(ye,{children:k.map(ae=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:ae.key_id}),e.jsx(A,{children:ae.created_at.slice(0,10)}),e.jsx(A,{children:e.jsx(V,{variant:ae.revoked_at?"danger":"success",children:ae.revoked_at?"REVOKED":"ACTIVE"})}),e.jsx(A,{children:!ae.revoked_at&&e.jsx(K,{variant:"destructive",size:"xs",onClick:()=>void U(ae.key_id),children:"Revoke"})})]},ae.key_id))})]})]})]})]})}function LE(){const[t,n]=i.useState(fl[0].client_id),[a,o]=i.useState(null),[c,u]=i.useState([]),[h,m]=i.useState(""),[x,v]=i.useState(""),[N,j]=i.useState("5"),[w,_]=i.useState(1),[S,y]=i.useState(null),[g,p]=i.useState("idle"),[k,R]=i.useState(""),C=i.useCallback(async()=>{const P=fl.find(F=>F.client_id===t);if(P){p("loading"),R(""),y(null),_(1);try{const F=(await th(P.client_id,P.client_secret)).access_token;o(F);try{u((await SE(F)).sectors)}catch{u([])}p("idle")}catch(F){R(F instanceof Error?F.message:"Connect failed"),p("error")}}},[t]),E=i.useCallback(async P=>{if(!a)return;p("loading"),R("");const F={page:String(P),page_size:N};h&&(F.sector=h),x&&(F.cas_min=x);try{const I=await qj(a,F);y(I),_(P),p(I.cards.length?"ok":"empty")}catch(I){R(I instanceof Error?I.message:"Feed query failed"),p("error")}},[a,h,x,N]);return e.jsxs("div",{children:[e.jsx(Se,{title:"DFI Data Feed",description:"Configure and preview the programmatic opportunity-card feed with tier-gated financial + AfCFTA fields (Epic 12, US-12.3)"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Subscriber",e.jsx(Ie,{value:t,onChange:P=>n(P.target.value),"aria-label":"Subscriber",children:fl.filter(P=>P.client_id!=="client-platform-admin").map(P=>e.jsx("option",{value:P.client_id,children:P.label},P.client_id))})]}),e.jsx(K,{size:"sm",onClick:()=>void C(),children:"Connect"})]})}),a&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Sector",e.jsxs(Ie,{value:h,onChange:P=>m(P.target.value),"aria-label":"Sector filter",children:[e.jsx("option",{value:"",children:"(any)"}),c.map(P=>e.jsx("option",{value:P,children:P},P))]})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["CAS min",e.jsx(me,{value:x,onChange:P=>v(P.target.value),className:"w-22",placeholder:"60","aria-label":"CAS minimum"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Page size",e.jsx(me,{value:N,onChange:P=>j(P.target.value),className:"w-17","aria-label":"Page size"})]}),e.jsx(K,{size:"sm",onClick:()=>void E(1),children:"Run feed"})]})}),g==="loading"&&e.jsx(H,{children:"Querying feed…"}),g==="error"&&e.jsx(H,{tone:"error",children:k}),g==="empty"&&e.jsx(H,{children:"No cards match this filter — relax the CAS floor or clear the sector."}),g==="ok"&&S&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"mt-4 flex-row flex-wrap items-center gap-5 px-4 py-4",children:[e.jsxs("span",{className:"text-sm text-foreground",children:[S.meta.total_cards," cards · page ",S.meta.current_page,"/",S.meta.total_pages," · cycle ",S.meta.cycle]}),e.jsx(K,{variant:"outline",size:"sm",disabled:!S.meta.prev_page_url,onClick:()=>void E(w-1),children:"Prev"}),e.jsx(K,{variant:"outline",size:"sm",disabled:!S.meta.next_page_url,onClick:()=>void E(w+1),children:"Next"})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Feed page"}),e.jsxs(je,{className:"min-w-[640px]",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Sector"}),e.jsx(T,{className:"text-right",children:"CAS"}),e.jsx(T,{children:"DAPS"}),e.jsx(T,{children:"Financial"}),e.jsx(T,{className:"text-right",children:"AfCFTA"})]})}),e.jsx(ye,{children:S.cards.map(P=>{const F=P.financial_model_summary,I=F==null?"—":"access"in F?"locked":`IRR ${String(F.irr_p50??"—")}%`;return e.jsxs(ee,{children:[e.jsxs(A,{children:[P.hs6_code,P.watermark_required&&e.jsx(V,{variant:"warning",children:"watermark"})]}),e.jsx(A,{children:P.sector}),e.jsx(A,{className:"text-right tabular-nums",children:P.composite_cas_score}),e.jsx(A,{children:P.daps_duty_flag?e.jsxs(V,{variant:"danger",children:[P.daps_duty_rate_pct??"?","%"]}):"—"}),e.jsx(A,{children:I}),e.jsx(A,{className:"text-right tabular-nums",children:P.afcfta_headroom_estimate?Xe(Number(P.afcfta_headroom_estimate.estimated_annual_export_potential_usd??0)):"—"})]},P.card_id)})})]})]})]})]})}const Tc="/v1/report-generation",sh={"x-pipeline-scope":"pipeline-internal"},FE={"x-subscriber-tier":"1"},DE=t=>be(`${Tc}/trilingual-jobs`,t,sh),Qj=t=>he(`${Tc}/trilingual-jobs/${encodeURIComponent(t)}`,sh),$E=(t,n)=>he(`${Tc}/trilingual-jobs/${encodeURIComponent(t)}/languages/${n}`,sh),IE=(t=1)=>he(`${Tc}/trilingual-jobs?status=SLA_BREACH&page=${t}`,FE),Dp={card_id:"card-300490-2025Q1",cas_score:72,hs6_code:"300490",wilaya_ids:["16","31"],capex_bracket:"25-50M",irr_p50:.19,source_citations:[{source_id:"UN_COMTRADE"},{source_id:"DGD_ALCES"}],analyst_approval_timestamp:"2026-08-14T09:00:00.000Z",schema_version:2,cycle_id:"2025-Q1",product_name_en:"Medicaments, packaged for retail sale",product_name_fr:"Médicaments conditionnés pour la vente au détail",product_name_ar:"أدوية معبأة للبيع بالتجزئة",equity_structure:{foreign_majority_flag:!0},daps_flags:[{hs6_code:"300490",protection_level:60,duty_rate:15,tda10_resolution_code:"TDA-3004900010"}]};function ME(t){return t==="COMPLETED"?"success":t==="SLA_BREACH"||t==="FAILED"?"danger":t==="IN_PROGRESS"||t==="QUEUED"?"warning":"secondary"}function OE({onOpen:t}){const[n,a]=i.useState("idle"),[o,c]=i.useState(Dp.card_id),[u,h]=i.useState("72"),[m,x]=i.useState([]),[v,N]=i.useState(""),j=i.useCallback(async _=>{const S=await Promise.all(_.map(y=>Qj(y)));x(S)},[]),w=i.useCallback(async()=>{a("loading"),N("");try{const _=await DE({...Dp,card_id:o.trim(),cas_score:Number(u)}),S=Array.from(new Set([_.job_id,...m.map(y=>y.job_id)]));await j(S),a("ok")}catch(_){N(_ instanceof Error?_.message:"Submission failed"),a("error")}},[o,u,m,j]);return e.jsxs("div",{children:[e.jsx(Se,{title:"Trilingual Report Generation",description:"Submit a finalized opportunity card to fan out French / English / Arabic rendering in parallel (US-11.1). Generation returns 202; poll each job for status."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4",children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["Card id",e.jsx(me,{value:o,onChange:_=>c(_.target.value),className:"w-55"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-xs text-muted-foreground",children:["CAS score (≥ 60)",e.jsx(me,{value:u,onChange:_=>h(_.target.value),className:"w-25"})]}),e.jsx(K,{size:"sm",onClick:()=>void w(),disabled:n==="loading",children:n==="loading"?"Submitting…":"Generate trilingual report"}),m.length>0&&e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void j(m.map(_=>_.job_id)),children:"Refresh"})]})}),n==="idle"&&e.jsx(H,{children:"Submit the sample card, or edit the id / CAS score. A CAS below 60 is rejected (422)."}),n==="loading"&&m.length===0&&e.jsx(H,{children:"Submitting…"}),n==="error"&&e.jsx(H,{tone:"error",children:v}),m.length===0&&n==="ok"&&e.jsx(H,{children:"No jobs yet."}),m.length>0&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:[m.length," job(s)"]}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Job"}),e.jsx(T,{className:"text-right",children:"v"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Languages"}),e.jsx(T,{className:"text-right",children:"Elapsed"}),e.jsx(T,{children:"Vintage"}),e.jsx(T,{})]})}),e.jsx(ye,{children:m.map(_=>e.jsxs(ee,{children:[e.jsxs(A,{className:"font-mono text-xs",children:[_.job_id.slice(0,18),"…",_.superseded&&e.jsx(V,{variant:"secondary",children:"superseded"})]}),e.jsx(A,{className:"text-right tabular-nums",children:_.version}),e.jsxs(A,{children:[e.jsx(V,{variant:ME(_.status),children:_.status}),_.sla_breach&&e.jsx(V,{variant:"danger",children:"SLA"})]}),e.jsx(A,{children:_.languages.map(S=>`${S.language_code}:${S.status==="RENDERED"?"✓":S.status}`).join(" · ")}),e.jsxs(A,{className:"text-right tabular-nums",children:[_.elapsed_seconds,"s"]}),e.jsx(A,{children:_.source_card_version_stamp}),e.jsx(A,{children:e.jsx(K,{size:"xs",onClick:()=>t(_.job_id),children:"Open"})})]},_.job_id))})]})]})]})}const $p=["fr","en","ar"],zE={fr:"Français",en:"English",ar:"العربية"};function UE({jobId:t}){var y;const[n,a]=i.useState(null),[o,c]=i.useState({}),[u,h]=i.useState(""),[m,x]=i.useState(null),[v,N]=i.useState(null),j=t?v===t?"error":m===t?"ok":"loading":"idle",w=i.useCallback(async()=>{if(!t)return null;const g=await Qj(t),p=await Promise.all($p.map(k=>$E(t,k)));return{st:g,arts:p}},[t]),_=i.useCallback(g=>{a(g.st),c(Object.fromEntries(g.arts.map(p=>[p.language_code,p]))),h(""),x(t),N(null)},[t]),S=i.useCallback(g=>{h(g instanceof Error?g.message:"Failed to load"),N(t),x(null)},[t]);return i.useEffect(()=>{let g=!0;return w().then(p=>{g&&p&&_(p)},p=>{g&&S(p)}),()=>{g=!1}},[w,_,S]),t?e.jsxs("div",{children:[e.jsx(Se,{title:`Trilingual Report — ${t.slice(0,20)}…`,description:"Three parallel language renderings from a single source, with glossary-locked terminology and RTL Arabic (US-11.2/11.5)"}),j==="loading"&&e.jsx(H,{children:"Loading artifacts…"}),j==="error"&&e.jsx(H,{tone:"error",children:u}),j==="ok"&&n&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"mt-4 flex-row flex-wrap items-center gap-2 px-4 py-4",children:[e.jsx(V,{variant:n.status==="COMPLETED"?"success":n.status==="SLA_BREACH"||n.status==="FAILED"?"danger":"warning",children:n.status}),n.sla_breach&&e.jsxs(V,{variant:"danger",children:["SLA BREACH · slowest ",n.slowest_child_language]}),e.jsxs(V,{variant:"secondary",children:["v",n.version]}),e.jsxs(V,{variant:"secondary",children:["vintage ",n.source_card_version_stamp]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Elapsed ",n.elapsed_seconds,"s · SLA remaining ",n.sla_remaining_seconds,"s"]})]}),e.jsx("section",{className:"mt-4 grid grid-cols-[repeat(auto-fit,minmax(280px,1fr))] gap-4",children:$p.map(g=>{const p=o[g];if(!p)return null;const k=p.text_direction==="rtl";return e.jsxs(B,{className:"gap-2 p-4",dir:p.text_direction,lang:g,children:[e.jsxs("div",{className:`flex items-center justify-between gap-2 ${k?"flex-row-reverse":""}`,children:[e.jsx("h2",{className:"text-base font-semibold",children:zE[g]}),e.jsx(V,{variant:p.status==="RENDERED"?"success":"danger",children:p.status})]}),k&&p.rtl_integrity_ok!==null&&e.jsx("div",{className:"mb-2",children:e.jsx(V,{variant:p.rtl_integrity_ok?"success":"danger",children:p.rtl_integrity_ok?"RTL ✓":"RTL failed"})}),e.jsx("div",{className:"flex flex-col gap-2",children:p.segments.map((R,C)=>e.jsxs("p",{dir:R.dir,className:`text-sm leading-normal ${R.dir==="rtl"?"text-right":"text-left"} ${R.callout?"rounded-lg border-2 border-destructive bg-destructive/10 p-2.5 font-bold":""}`,children:[R.callout&&e.jsxs("span",{className:"block text-[11px] text-destructive",children:["⚠ ",R.callout]}),R.text]},C))}),e.jsxs("div",{className:"mt-2.5 text-xs text-muted-foreground",children:[p.total_glossary_substitutions_count," glossary term(s) locked · ",p.glossary_version]})]},g)})}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Glossary substitution log (French)"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Term"}),e.jsx(T,{children:"Source"}),e.jsx(T,{children:"Target"})]})}),e.jsx(ye,{children:(((y=o.fr)==null?void 0:y.term_substitution_log)??[]).map((g,p)=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:g.term_id}),e.jsx(A,{children:g.source_language_token}),e.jsx(A,{children:g.target_language_token})]},p))})]})]})]})]}):e.jsx(H,{children:"Open a job from the Generation Jobs tab to view its trilingual artifacts."})}function BE(){const[t,n]=i.useState(null),[a,o]=i.useState(""),[c,u]=i.useState(!1),[h,m]=i.useState(!1),x=h?"error":c?"ok":"loading",v=i.useCallback(async()=>IE(1),[]),N=i.useCallback(_=>{n(_),o(""),u(!0),m(!1)},[]),j=i.useCallback(_=>{o(_ instanceof Error?_.message:"Failed"),m(!0),u(!1)},[]),w=i.useCallback(()=>(u(!1),m(!1),v().then(N,j)),[v,N,j]);return i.useEffect(()=>{let _=!0;return v().then(S=>{_&&N(S)},S=>{_&&j(S)}),()=>{_=!1}},[v,N,j]),e.jsxs("div",{children:[e.jsx(Se,{title:"SLA Breach Monitor",description:"Trilingual jobs that exceeded the 6-hour SLA (Tier 1 / Chief Economist, US-11.7). Identify systemic bottlenecks by language or cycle.",actions:e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void w(),children:"Refresh"})}),x==="loading"&&e.jsx(H,{children:"Loading breaches…"}),x==="error"&&e.jsx(H,{tone:"error",children:a}),x==="ok"&&t&&t.results.length===0&&e.jsx(H,{children:"No SLA breaches — every trilingual job met the 6-hour deadline. ✓"}),x==="ok"&&t&&t.results.length>0&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:[t.total_count," breach(es)"]}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Card"}),e.jsx(T,{className:"text-right",children:"CAS"}),e.jsx(T,{children:"Slowest language"}),e.jsx(T,{children:"Elapsed"}),e.jsx(T,{children:"Cycle"})]})}),e.jsx(ye,{children:t.results.map(_=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:_.card_id}),e.jsx(A,{className:"text-right tabular-nums",children:_.cas_score_at_submission}),e.jsx(A,{children:e.jsx(V,{variant:"danger",children:_.slowest_child_language??"—"})}),e.jsx(A,{className:"tabular-nums",children:_.total_elapsed_seconds!==null?`${Math.round(_.total_elapsed_seconds/3600)}h (${_.total_elapsed_seconds}s)`:"—"}),e.jsx(A,{children:_.quarterly_cycle_stamp})]},_.job_id))})]})]})]})}const Ii=t=>({"x-user-role":t}),Kj=()=>he("/v1/contracts",Ii("contract-manager")),HE=t=>be("/v1/contracts/provision",t,Ii("contract-manager")),VE=(t,n)=>be(`/v1/contracts/${t}/named-users`,{users:n}),GE=t=>he(`/v1/contracts/${t}/provisioning-status`),WE=t=>be("/v1/invoices/generate",t,Ii("finance-admin")),Ip=t=>he(`/v1/contracts/${t}/invoices`),qE=(t,n)=>pl(`/v1/invoices/${t}/status`,n,Ii("finance-admin")),QE=()=>he("/v1/feature-flags/definitions"),KE=(t,n)=>pl(`/v1/admin/feature-flags/${t}`,n,Ii("platform_admin"));function XE(){const[t,n]=i.useState("Islamic Development Bank"),[a,o]=i.useState("96000"),[c,u]=i.useState("isdb.org"),[h,m]=i.useState("2"),[x,v]=i.useState("officer@isdb.org"),[N,j]=i.useState(null),[w,_]=i.useState(null),[S,y]=i.useState(!1),[g,p]=i.useState(""),[k,R]=i.useState(""),C=async()=>{y(!0),R(""),p("");try{const I=await HE({subscriber_legal_name:t,annual_fee_usd:Number(a),payment_terms:"NET-60",contract_start_date:"2027-01-01",contract_end_date:"2027-12-31",assigned_csm:"K. Meddour",tier:"tier-1-institutional",registered_domains:c.split(",").map(M=>M.trim()).filter(Boolean),seat_count:Number(h),document_base64:btoa(`SANDBOX-CONTRACT-${t}-${Date.now()}`),billing_contact:`ap@${c.split(",")[0].trim()}`});j(I),p(`Provisioning opened — contract ${I.contract_id.slice(0,8)}… (SLA clock started at ${I.t_zero}).`)}catch(I){R(I instanceof Error?I.message:"Provisioning failed")}finally{y(!1)}},E=async()=>{if(N){y(!0),R("");try{const I=x.split(",").map($=>({email:$.trim(),role_name:"afdb_analyst"})).filter($=>$.email),M=await VE(N.contract_id,I);p(`Named users submitted (${M.users??I.length}); provisioning ${M.status}.`)}catch(I){R(I instanceof Error?I.message:"Submission failed")}finally{y(!1)}}},P=i.useCallback(()=>N?GE(N.contract_id).then(_).catch(()=>{}):Promise.resolve(),[N]);i.useEffect(()=>{if(!N)return;P();const I=setInterval(()=>void P(),6e4);return()=>clearInterval(I)},[N,P]);const F=w?Math.min(100,w.hours_elapsed/w.sla_hours*100):0;return e.jsxs("div",{children:[e.jsx(Se,{title:"Provisioning Console",description:"Initiate Tier-1 access provisioning against the 24-hour SLA (US-13.1). Upload a countersigned contract, confirm metadata, then submit the named-user list."}),g&&e.jsx(H,{children:g}),k&&e.jsx(H,{tone:"error",children:k}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"1 · Contract metadata"}),e.jsxs("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-2.5 px-4",children:[e.jsx(fi,{label:"Subscriber legal name",children:e.jsx(me,{"aria-label":"name",value:t,onChange:I=>n(I.target.value)})}),e.jsx(fi,{label:"Annual fee (USD, 48000–120000)",children:e.jsx(me,{"aria-label":"fee",value:a,onChange:I=>o(I.target.value)})}),e.jsx(fi,{label:"Registered domains (comma-sep)",children:e.jsx(me,{"aria-label":"domains",value:c,onChange:I=>u(I.target.value)})}),e.jsx(fi,{label:"Seat count",children:e.jsx(me,{"aria-label":"seats",value:h,onChange:I=>m(I.target.value)})})]}),e.jsx("div",{className:"px-4",children:e.jsx(K,{size:"sm",onClick:()=>void C(),disabled:S,children:"Initiate Provisioning"})})]}),N&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"2 · Named users"}),e.jsx("div",{className:"px-4",children:e.jsx(fi,{label:"User emails (comma-sep; domain must match contract)",children:e.jsx(me,{"aria-label":"emails",value:x,onChange:I=>v(I.target.value)})})}),e.jsx("div",{className:"px-4",children:e.jsx(K,{size:"sm",onClick:()=>void E(),disabled:S,children:"Submit Named Users"})})]}),w&&e.jsxs(B,{className:"mt-4 gap-2 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["3 · Provisioning SLA tracker ",e.jsx(V,{variant:w.sla_status==="SLA_BREACHED"?"danger":w.sla_status==="SLA_MET"?"success":"warning",children:w.sla_status})]}),e.jsxs("p",{className:"px-4 text-sm text-muted-foreground",children:[w.hours_elapsed.toFixed(2)," of ",w.sla_hours," hours elapsed · status ",w.status]}),e.jsx("div",{className:"px-4",children:e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-muted",role:"progressbar","aria-valuenow":Math.round(F),"aria-valuemin":0,"aria-valuemax":100,children:e.jsx("div",{className:"h-full",style:{width:`${F}%`,background:F>=100?"var(--destructive)":"var(--success)"}})})}),e.jsxs("p",{className:"mt-2 px-4 text-xs text-muted-foreground",children:["Steps: ",w.completed_steps.join(" → ")]}),e.jsx("div",{className:"px-4",children:e.jsx(K,{size:"sm",onClick:()=>void P(),children:"Refresh"})})]})]})}function fi({label:t,children:n}){return e.jsxs("label",{className:"block text-sm",children:[e.jsx("span",{className:"mb-1 block text-muted-foreground",children:t}),n]})}const YE=t=>t==="SLA_MET"?"success":t==="SLA_BREACHED"?"danger":"warning";function ZE(){const[t,n]=i.useState("loading"),[a,o]=i.useState(null),[c,u]=i.useState("ALL"),[h,m]=i.useState(""),x=i.useCallback(async()=>Kj(),[]),v=i.useCallback(_=>{o(_),n("ok")},[]),N=i.useCallback(_=>{m(_ instanceof Error?_.message:"Failed"),n("error")},[]);i.useEffect(()=>{let _=!0;return x().then(S=>{_&&v(S)},S=>{_&&N(S)}),()=>{_=!1}},[x,v,N]);const j=i.useCallback(()=>(n("loading"),m(""),x().then(v,N)),[x,v,N]),w=((a==null?void 0:a.contracts)??[]).filter(_=>c==="ALL"||_.sla_status===c);return e.jsxs("div",{children:[e.jsx(Se,{title:"Contract Status Dashboard",description:"Institutional subscriber contracts: 24-hour provisioning SLA, seat count, next invoice due, and invoice status (US-13.1). Read-only for BD; Finance edits invoices.",actions:e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void j(),children:"Refresh"})}),e.jsxs("div",{className:"my-3 flex items-center gap-2",children:[e.jsx("label",{htmlFor:"sla",className:"text-sm text-muted-foreground",children:"SLA status"}),e.jsx(Ie,{id:"sla",value:c,onChange:_=>u(_.target.value),children:["ALL","IN_PROGRESS","SLA_MET","SLA_BREACHED"].map(_=>e.jsx("option",{value:_,children:_},_))})]}),t==="loading"&&e.jsx(H,{children:"Loading contracts…"}),t==="error"&&e.jsx(H,{tone:"error",children:h}),t==="ok"&&w.length===0&&e.jsx(H,{children:"No contracts match this filter."}),t==="ok"&&w.length>0&&e.jsxs(B,{className:"mt-2 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:[w.length," contract(s)"]}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Subscriber"}),e.jsx(T,{children:"Tier"}),e.jsx(T,{className:"text-right",children:"Seats"}),e.jsx(T,{className:"text-right",children:"Annual (USD)"}),e.jsx(T,{children:"SLA"}),e.jsx(T,{children:"Provisioning"}),e.jsx(T,{children:"Next invoice due"}),e.jsx(T,{children:"Invoice"})]})}),e.jsx(ye,{children:w.map(_=>e.jsxs(ee,{children:[e.jsx(A,{children:_.subscriber_legal_name}),e.jsx(A,{children:_.tier}),e.jsx(A,{className:"text-right tabular-nums",children:_.seat_count}),e.jsxs(A,{className:"text-right tabular-nums",children:["$",Number(_.annual_fee_usd).toLocaleString()]}),e.jsx(A,{children:e.jsx(V,{variant:YE(_.sla_status),children:_.sla_status})}),e.jsx(A,{children:_.provisioning_status}),e.jsx(A,{children:_.next_invoice_due_date}),e.jsx(A,{children:e.jsx(V,{variant:_.invoice_status==="PAID"?"success":_.invoice_status==="OVERDUE"?"danger":"secondary",children:_.invoice_status})})]},_.contract_id))})]})]})]})}function JE(){const[t,n]=i.useState([]),[a,o]=i.useState(""),[c,u]=i.useState("IsDB-PO-2027-1"),[h,m]=i.useState(!0),[x,v]=i.useState([]),[N,j]=i.useState(null),[w,_]=i.useState(!1),[S,y]=i.useState(""),[g,p]=i.useState(""),[k,R]=i.useState(null),[C,E]=i.useState(null),P=C===a?"error":k===a?"ok":"loading",F=i.useCallback(async()=>{const z=await Kj();return{contracts:z.contracts,firstId:z.contracts.length&&!a?z.contracts[0].contract_id:null}},[a]),I=i.useCallback(z=>{n(z.contracts),z.firstId&&o(z.firstId),p(""),R(a),E(null)},[a]),M=i.useCallback(z=>{p(z instanceof Error?z.message:"Failed"),E(a),R(null)},[a]);i.useEffect(()=>{let z=!0;return F().then(Y=>{z&&I(Y)},Y=>{z&&M(Y)}),()=>{z=!1}},[F,I,M]);const $=i.useCallback(async z=>{if(z)try{v((await Ip(z)).invoices)}catch{}},[]);i.useEffect(()=>{if(!a)return;let z=!0;return Ip(a).then(Y=>{z&&v(Y.invoices)}).catch(()=>{}),()=>{z=!1}},[a]);const O=async()=>{if(a){_(!0),p(""),y("");try{const z=await WE({contract_id:a,billing_period_start:"2027-01-01",billing_period_end:"2027-12-31",po_number:c,dzd_equivalent:h});j(z),y(z.is_duplicate?`Invoice ${z.invoice_number} already exists for this period.`:`Generated ${z.invoice_number} — due ${z.payment_due_date}.`),await $(a)}catch(z){p(z instanceof Error?z.message:"Generation failed")}finally{_(!1)}}},L=async(z,Y,G={})=>{_(!0),p("");try{await qE(z,{action:Y,...G}),y(`Invoice ${Y.replace("_"," ")} done.`),await $(a)}catch(U){p(U instanceof Error?U.message:"Action failed")}finally{_(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Invoice Generation",description:"Net-60 institutional invoicing with Bank-of-Algeria DZD stamping and SWIFT wire instructions (US-13.2). Idempotent per contract + billing period."}),S&&e.jsx(H,{children:S}),g&&e.jsx(H,{tone:"error",children:g}),P==="loading"&&e.jsx(H,{children:"Loading contracts…"}),P==="error"&&!g&&e.jsx(H,{tone:"error",children:"Failed to load."}),P==="ok"&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Generate"}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2.5 px-4",children:[e.jsx(Mp,{label:"Contract",children:e.jsx(Ie,{"aria-label":"contract",value:a,onChange:z=>o(z.target.value),className:"min-w-60",children:t.map(z=>e.jsxs("option",{value:z.contract_id,children:[z.subscriber_legal_name," (",z.tier,")"]},z.contract_id))})}),e.jsx(Mp,{label:"PO number",children:e.jsx(me,{"aria-label":"po",value:c,onChange:z=>u(z.target.value)})}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx("input",{type:"checkbox",checked:h,onChange:z=>m(z.target.checked),className:"size-4 accent-primary"})," Include DZD equivalent"]}),e.jsx(K,{size:"sm",onClick:()=>void O(),disabled:w||!a,children:"Generate Invoice"})]})]}),N&&e.jsxs(B,{className:"mt-4 gap-1 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Preview · ",N.invoice_number," ",e.jsx(V,{variant:N.status==="PAID"?"success":N.status==="OVERDUE"?"danger":"secondary",children:N.status})]}),e.jsxs("p",{className:"px-4",children:["Net ",`$${Number(N.net_amount_usd).toLocaleString()}`," · due ",N.payment_due_date," · PO ",N.po_number]}),N.dzd_equivalent_amount&&e.jsxs("p",{className:"px-4 text-sm text-muted-foreground",children:["DZD ",Number(N.dzd_equivalent_amount).toLocaleString()," @ ",N.fx_rate_used," (",N.fx_rate_source,", ",N.fx_rate_date,")"]})]}),x.length>0&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Invoices for this contract"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Number"}),e.jsx(T,{children:"Status"}),e.jsx(T,{className:"text-right",children:"Total"}),e.jsx(T,{children:"Due"}),e.jsx(T,{children:"Actions"})]})}),e.jsx(ye,{children:x.map(z=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:z.invoice_number}),e.jsx(A,{children:e.jsx(V,{variant:z.status==="PAID"?"success":z.status==="OVERDUE"?"danger":z.status==="VOID"?"secondary":"warning",children:z.status})}),e.jsxs(A,{className:"text-right tabular-nums",children:["$",Number(z.total_amount_usd).toLocaleString()]}),e.jsx(A,{children:z.payment_due_date}),e.jsx(A,{children:e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(K,{size:"xs",onClick:()=>void L(z.invoice_id,"approve_send"),disabled:w,children:"Send"}),e.jsx(K,{size:"xs",onClick:()=>void L(z.invoice_id,"mark_paid",{amount_usd:Number(z.total_amount_usd),value_date:"2027-03-01",bank_ref:"SWIFT-DEMO"}),disabled:w,children:"Mark Paid"})]})})]},z.invoice_id))})]})]})]})}function Mp({label:t,children:n}){return e.jsxs("label",{className:"block text-sm",children:[e.jsx("span",{className:"mb-1 block text-muted-foreground",children:t}),n]})}function e4(){const[t,n]=i.useState(null),[a,o]=i.useState(!1),[c,u]=i.useState(""),[h,m]=i.useState(""),[x,v]=i.useState(!1),[N,j]=i.useState(!1),w=N?"error":x?"ok":"loading",_=i.useCallback(()=>QE(),[]),S=i.useCallback(k=>{n(k),v(!0),j(!1)},[]),y=i.useCallback(k=>{m(k instanceof Error?k.message:"Failed"),j(!0),v(!1)},[]),g=i.useCallback(()=>(v(!1),j(!1),_().then(S,y)),[_,S,y]);i.useEffect(()=>{let k=!0;return _().then(R=>{k&&S(R)},R=>{k&&y(R)}),()=>{k=!1}},[_,S,y]);const p=async(k,R,C)=>{o(!0),m(""),u("");try{await KE(k,{[`tier_${R}_enabled`]:!C}),u(`${k} for tier ${R} → ${C?"disabled":"enabled"} (tier cache invalidated).`),await g()}catch(E){m(E instanceof Error?E.message:"Update failed")}finally{o(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Feature-Flag Admin",description:"Per-tier feature gates enforced at the API layer (US-13.3). Toggling a cell bulk-invalidates that tier's permission cache within 30s.",actions:e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void g(),children:"Refresh"})}),c&&e.jsx(H,{children:c}),w==="loading"&&e.jsx(H,{children:"Loading feature flags…"}),w==="error"&&e.jsx(H,{tone:"error",children:h}),w==="ok"&&t&&t.definitions.length===0&&e.jsx(H,{children:"No feature flags defined."}),w==="ok"&&t&&t.definitions.length>0&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Tier × feature matrix"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Feature"}),e.jsx(T,{children:"Tier 1"}),e.jsx(T,{children:"Tier 2"}),e.jsx(T,{children:"Tier 3"})]})}),e.jsx(ye,{children:t.definitions.map(k=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:k.flag_key}),[1,2,3].map(R=>{const C=R===1?k.tier_1_enabled:R===2?k.tier_2_enabled:k.tier_3_enabled;return e.jsx(A,{children:e.jsx("button",{"aria-label":`${k.flag_key} tier ${R}`,onClick:()=>void p(k.flag_key,R,C),disabled:a,className:"cursor-pointer border-none bg-transparent p-0",children:e.jsx(V,{variant:C?"success":"secondary",children:C?"ON":"off"})})},R)})]},k.flag_key))})]})]}),w==="ok"&&t&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Route → flag map"}),t.route_map.length===0?e.jsx(H,{children:"No route mappings — all routes default-open."}):e.jsx("div",{className:"px-4",children:e.jsx("ul",{className:"list-disc pl-4 text-sm text-muted-foreground",children:t.route_map.map(k=>e.jsxs("li",{children:[e.jsxs("code",{children:[k.method," ",k.pattern]})," → ",e.jsx("strong",{children:k.flag})]},`${k.method} ${k.pattern}`))})})]})]})}const Xn="/v1/delta",t4=t=>({"x-subscriber-tier":t}),Xj=t=>{const n=new URLSearchParams;for(const[o,c]of Object.entries(t))c!=null&&c!==""&&n.set(o,c);const a=n.toString();return a?`?${a}`:""},s4=t=>be(`${Xn}/pipeline/runs`,{cycle_id:t,trigger_source:"console"}),n4=t=>he(`${Xn}/pipeline/runs/${encodeURIComponent(t)}`),r4=t=>be(`${Xn}/cycles/${encodeURIComponent(t)}/digest`),a4=(t,n={})=>he(`${Xn}/cycles/${encodeURIComponent(t)}/changes${Xj(n)}`),l4=t=>he(`${Xn}/cycles/${encodeURIComponent(t)}/card-badges`),i4=(t,n,a={})=>he(`${Xn}/hs6-lines/${encodeURIComponent(t)}/delta-history${Xj(a)}`,t4(n)),o4=t=>he(`${Xn}/monitoring/${encodeURIComponent(t)}/sla`),c4=t=>he(`${Xn}/monitoring/${encodeURIComponent(t)}/digest-report`),d4=()=>he(`${Xn}/monitoring/regression`),u4={CAS_CHANGE:{variant:"warning",label:"CAS"},TARIFF_ALERT:{variant:"danger",label:"Tariff"},REGULATORY_UPDATE:{variant:"secondary",label:"Regulatory"},IMPORT_SIGNAL:{variant:"secondary",label:"Import"},THRESHOLD_CROSSED:{variant:"success",label:"Threshold"}},m4=["","CAS_SCORE_CHANGE","BAND_CHANGE","IMPORT_VALUE_MOVEMENT","TARIFF_CHANGE","REGULATORY_RULE_CHANGE","THRESHOLD_CROSSED_UPWARD"];function h4({cycle:t="2025-Q2"}){const[n,a]=i.useState(""),[o,c]=i.useState(!0),[u,h]=i.useState([]),[m,x]=i.useState(null),[v,N]=i.useState(null),[j,w]=i.useState(""),[_,S]=i.useState(!1),[y,g]=i.useState(null),[p,k]=i.useState(null),R=`${t}|${n}|${o}`,C=p===R?"error":y!==R?"loading":u.length===0?"empty":"ok",E=i.useCallback(async()=>{const[$,O]=await Promise.all([a4(t,{delta_type:n||void 0,material_only:o?"true":void 0}),l4(t).catch(()=>null)]),L=await n4(t).catch(()=>null);return{ch:$.changes,bg:O,r:L}},[t,n,o]),P=i.useCallback($=>{h($.ch),x($.bg),N($.r),g(R),k(null)},[R]),F=i.useCallback($=>{w($ instanceof Error?$.message:"Load failed"),k(R),g(null)},[R]),I=i.useCallback(()=>(g(null),k(null),E().then(P,F)),[E,P,F]);i.useEffect(()=>{let $=!0;return E().then(O=>{$&&P(O)},O=>{$&&F(O)}),()=>{$=!1}},[E,P,F]);const M=i.useCallback(async()=>{S(!0);try{await s4(t),await I()}catch($){w($ instanceof Error?$.message:"Trigger failed"),k(R),g(null)}finally{S(!1)}},[t,I,R]);return e.jsxs("div",{children:[e.jsx(Se,{title:`Delta Intelligence · ${t}`,description:"Quarter-over-quarter change intelligence — CAS movements, threshold crossings, tariff & regulatory updates, and import-value shifts, from the append-only hash-chained change-log.",actions:e.jsx(K,{size:"sm",onClick:()=>void M(),disabled:_,children:_?"Computing…":"Run delta computation"})}),(v==null?void 0:v.summary)&&e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"Material changes",value:String(v.summary.material_count),tone:"warn"}),e.jsx(ze,{label:"Threshold up / down",value:`${v.summary.threshold_up_count} / ${v.summary.threshold_down_count}`,tone:"ok"}),e.jsx(ze,{label:"Tariff / Regulatory",value:`${v.summary.tariff_changes} / ${v.summary.regulatory_changes}`}),e.jsx(ze,{label:"Records written",value:String(v.summary.records_written)}),v.summary.pre_breach_warning&&e.jsx(ze,{label:"SLA",value:"Pre-breach",tone:"warn"})]}),m&&Object.keys(m.badges).length>0&&e.jsxs("p",{className:"mt-3 text-sm text-muted-foreground",children:[Object.keys(m.badges).length," HS6 line",Object.keys(m.badges).length===1?"":"s"," carry delta badges · fresh as of ",new Date(m.data_freshness_timestamp).toISOString().slice(0,10)]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Type:"}),m4.map($=>e.jsx(K,{variant:n===$?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>a($),children:$?$.replace(/_/g," "):"All"},$||"all")),e.jsxs("label",{className:"ms-2 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:$=>c($.target.checked),className:"size-4 accent-primary"})," Material only"]}),e.jsxs("span",{className:"ms-auto text-sm text-muted-foreground",children:[u.length," result",u.length===1?"":"s"]})]}),C==="loading"&&e.jsx(Hu,{children:"Loading delta change-log…"}),C==="error"&&e.jsxs(Hu,{tone:"error",role:"alert",children:[j,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void I(),children:"Retry"})})]}),C==="empty"&&e.jsx(Hu,{children:"No changes recorded for this filter. Run a delta computation to materialise this cycle’s deltas."}),C==="ok"&&e.jsx(B,{className:"mt-4 overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Badge"}),e.jsx(T,{children:"Δ"}),e.jsx(T,{children:"Band"}),e.jsx(T,{children:"Material"})]})}),e.jsx(ye,{children:u.map(($,O)=>{const L=f4($.delta_type),z=u4[L];return e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:$.hs6_code}),e.jsx(A,{children:$.delta_type}),e.jsx(A,{children:e.jsx(V,{variant:z.variant,"aria-label":`${z.label} change`,children:z.label})}),e.jsx(A,{className:"tabular-nums",children:$.delta_magnitude??"—"}),e.jsx(A,{children:$.current_cas_band??"—"}),e.jsx(A,{"aria-label":$.flagged_material?"material":"not material",children:$.flagged_material?"●":"○"})]},$.id??`${$.hs6_code}-${O}`)})})]})})]})}function f4(t){return t.startsWith("THRESHOLD")?"THRESHOLD_CROSSED":t.startsWith("IMPORT")||t==="NEW_IMPORT_SIGNAL"?"IMPORT_SIGNAL":t.startsWith("TARIFF")||t.startsWith("DAPS")?"TARIFF_ALERT":t.startsWith("REGULATORY")?"REGULATORY_UPDATE":"CAS_CHANGE"}function Hu({children:t,tone:n,role:a}){return e.jsx("div",{className:n==="error"?"mt-4 rounded-xl border border-destructive/50 bg-destructive/10 p-4 text-destructive":"mt-4 rounded-xl border bg-card p-4 text-foreground",role:a,children:t})}function x4({tier:t="1"}){const[n,a]=i.useState("720839"),[o,c]=i.useState("720839"),[u,h]=i.useState(null),[m,x]=i.useState(""),[v,N]=i.useState(null),[j,w]=i.useState(null),_=`${o}|${t}`,S=j===_?"error":v!==_?"loading":u!==null&&u.records.length===0?"empty":"ok",y=i.useCallback(async()=>{if(!/^\d{6}$/.test(o))throw new Error("HS6 must be 6 digits");return await i4(o,t,{page_size:"50"})},[o,t]),g=i.useCallback(R=>{h(R),N(_),w(null)},[_]),p=i.useCallback(R=>{x(R instanceof Error?R.message:"Load failed"),w(_),N(null)},[_]),k=i.useCallback(()=>(N(null),w(null),y().then(g,p)),[y,g,p]);return i.useEffect(()=>{let R=!0;return y().then(C=>{R&&g(C)},C=>{R&&p(C)}),()=>{R=!1}},[y,g,p]),e.jsxs("div",{children:[e.jsx(Se,{title:"Delta Timeline",description:"Every change to an HS6 line across all cycles, oldest first, with gap & duplicate integrity checks.",actions:e.jsxs("form",{onSubmit:R=>{R.preventDefault(),c(n)},noValidate:!0,className:"flex items-center gap-2",children:[e.jsx(me,{value:n,onChange:R=>a(R.target.value),placeholder:"HS6 code","aria-label":"HS6 code",className:"w-40"}),e.jsx(K,{type:"submit",size:"sm",children:"Load history"})]})}),S==="loading"&&e.jsx(Vu,{children:"Loading history…"}),S==="error"&&e.jsxs(Vu,{tone:"error",role:"alert",children:[m,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void k(),children:"Retry"})})]}),S==="empty"&&e.jsxs(Vu,{children:["No delta history recorded for ",o,"."]}),S==="ok"&&u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{children:[u.total_count," record",u.total_count===1?"":"s"]}),e.jsxs("span",{children:["Gaps: ",u.data_integrity.gaps_detected.length?u.data_integrity.gaps_detected.join(", "):"none"]}),e.jsxs("span",{children:["Duplicates: ",u.data_integrity.duplicates_detected?"detected":"none"]})]}),e.jsx("ol",{className:"mt-4 list-none space-y-2.5 p-0",children:u.records.map((R,C)=>e.jsxs("li",{className:"rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"flex flex-wrap justify-between gap-2",children:[e.jsxs("strong",{children:[R.cycle_label??R.cycle_id," · ",R.delta_type]}),e.jsxs("span",{className:"text-muted-foreground",children:["Δ ",R.delta_magnitude??"—"," · band ",R.cas_band_at_time??R.current_cas_band??"—"]})]}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:[R.flagged_material?"material":"audit-only"," · ",R.computation_timestamp]})]},R.id??C))})]})]})}function Vu({children:t,tone:n,role:a}){return e.jsx("div",{className:n==="error"?"mt-4 rounded-xl border border-destructive/50 bg-destructive/10 p-4 text-destructive":"mt-4 rounded-xl border bg-card p-4 text-foreground",role:a,children:t})}const Op={COMPLIANT:"success",BREACHED:"danger",IN_PROGRESS:"warning",PENDING:"secondary"};function p4({cycle:t="2025-Q2"}){const[n,a]=i.useState(null),[o,c]=i.useState(null),[u,h]=i.useState(""),[m,x]=i.useState(null),[v,N]=i.useState(null),j=v===t?"error":m!==t?"loading":n!==null&&n.tasks.length===0?"empty":"ok",w=i.useCallback(async()=>{const[g,p]=await Promise.all([o4(t),d4().catch(()=>null)]);return{p:g,r:p}},[t]),_=i.useCallback(({p:g,r:p})=>{a(g),c(p),x(t),N(null)},[t]),S=i.useCallback(g=>{h(g instanceof Error?g.message:"Load failed"),N(t),x(null)},[t]),y=i.useCallback(()=>(x(null),N(null),w().then(_,S)),[w,_,S]);return i.useEffect(()=>{let g=!0;return w().then(p=>{g&&_(p)},p=>{g&&S(p)}),()=>{g=!1}},[w,_,S]),e.jsxs("div",{children:[e.jsx(Se,{title:`Delta SLA Monitor · ${t}`,description:"Per-task delta-computation SLA (2-hour budget), pre-breach warnings, and the ≥95% classification-accuracy gate."}),j==="loading"&&e.jsx(sc,{children:"Loading SLA status…"}),j==="error"&&e.jsxs(sc,{tone:"error",role:"alert",children:[u,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void y(),children:"Retry"})})]}),j==="empty"&&e.jsx(sc,{children:"No SLA rows for this cycle. Run a delta computation first."}),j==="ok"&&n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"Compliant",value:String(n.performance.compliant_tasks_count),tone:"ok"}),e.jsx(ze,{label:"Breached",value:String(n.performance.breached_tasks_count),tone:n.performance.breached_tasks_count?"warn":void 0}),e.jsx(ze,{label:"p95 duration (ms)",value:String(n.performance.p95_duration_ms)}),o&&e.jsx(ze,{label:"Regression gate",value:`${o.gate} · ${o.accuracy_pct}%`,tone:o.gate==="PASS"?"ok":"warn"})]}),n.pre_breach.length>0&&e.jsxs(sc,{tone:"error",role:"alert",children:["Pre-breach: ",n.pre_breach.map(g=>`${g.task_name} (${g.minutes_remaining}m left)`).join("; ")]}),e.jsx(B,{className:"mt-4 overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Task"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Deadline"}),e.jsx(T,{className:"text-right",children:"Duration (ms)"}),e.jsx(T,{className:"text-right",children:"Rows"})]})}),e.jsx(ye,{children:n.tasks.map((g,p)=>{const k=Op[g.sla_status]??Op.PENDING;return e.jsxs(ee,{children:[e.jsx(A,{children:g.task_name}),e.jsx(A,{children:e.jsx(V,{variant:k,children:g.sla_status})}),e.jsx(A,{children:g.sla_deadline}),e.jsx(A,{className:"text-right tabular-nums",children:g.duration_ms??"—"}),e.jsx(A,{className:"text-right tabular-nums",children:g.rows_processed})]},`${g.task_name}-${p}`)})})]})})]})]})}function sc({children:t,tone:n,role:a}){return e.jsx("div",{className:n==="error"?"mt-4 rounded-xl border border-destructive/50 bg-destructive/10 p-4 text-destructive":"mt-4 rounded-xl border bg-card p-4 text-foreground",role:a,children:t})}const zp={SENT:"success",DELIVERED:"success",FAILED:"danger",QUEUED:"warning"};function g4({cycle:t="2025-Q2"}){const[n,a]=i.useState(null),[o,c]=i.useState(""),[u,h]=i.useState(!1),[m,x]=i.useState(null),[v,N]=i.useState(null),j=v===t?"error":m===t?n!==null&&n.deliveries.length===0?"empty":"ok":"loading",w=i.useCallback(async()=>c4(t),[t]),_=i.useCallback(p=>{a(p),x(t),N(null)},[t]),S=i.useCallback(p=>{c(p instanceof Error?p.message:"Load failed"),N(t),x(null)},[t]);i.useEffect(()=>{let p=!0;return w().then(k=>{p&&_(k)},k=>{p&&S(k)}),()=>{p=!1}},[w,_,S]);const y=i.useCallback(()=>(x(null),N(null),w().then(_,S)),[w,_,S]),g=i.useCallback(async()=>{h(!0);try{await r4(t),await y()}catch(p){c(p instanceof Error?p.message:"Dispatch failed"),N(t),x(null)}finally{h(!1)}},[t,y]);return e.jsxs("div",{children:[e.jsx(Se,{title:`Digest Delivery Report · ${t}`,description:"Per-subscriber trilingual digest delivery and the 4-hour dispatch SLA. Emails are logged as hashes only (ANPDP).",actions:e.jsx(K,{size:"sm",onClick:()=>void g(),disabled:u,children:u?"Dispatching…":"Dispatch digest"})}),j==="loading"&&e.jsx(Gu,{children:"Loading digest report…"}),j==="error"&&e.jsxs(Gu,{tone:"error",role:"alert",children:[o,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void y(),children:"Retry"})})]}),j==="empty"&&e.jsx(Gu,{children:"No digest dispatched for this cycle yet. Dispatch one to populate the delivery ledger."}),j==="ok"&&n&&e.jsxs(e.Fragment,{children:[n.sla_report&&e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"Subscribers",value:String(n.sla_report.total_subscribers)}),e.jsx(ze,{label:"Sent",value:String(n.sla_report.sent_count),tone:"ok"}),e.jsx(ze,{label:"Failed",value:String(n.sla_report.failed_count),tone:n.sla_report.failed_count?"warn":void 0}),e.jsx(ze,{label:"SLA",value:n.sla_report.sla_compliant?"Compliant":"Breach",tone:n.sla_report.sla_compliant?"ok":"warn"})]}),e.jsx(B,{className:"mt-4 overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Subscriber"}),e.jsx(T,{children:"Lang"}),e.jsx(T,{children:"Tier"}),e.jsx(T,{className:"text-right",children:"Items"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Email hash"})]})}),e.jsx(ye,{children:n.deliveries.map(p=>{const k=zp[p.delivery_status]??zp.QUEUED;return e.jsxs(ee,{children:[e.jsx(A,{children:p.subscriber_id}),e.jsxs(A,{dir:p.rtl?"rtl":"ltr",children:[p.preferred_language,p.rtl?" ⟲":""]}),e.jsx(A,{children:p.tier}),e.jsx(A,{className:"text-right tabular-nums",children:p.item_count}),e.jsx(A,{children:e.jsx(V,{variant:k,children:p.delivery_status})}),e.jsx(A,{children:e.jsxs("code",{className:"text-[11px]",children:[p.email_address_hash.slice(0,12),"…"]})})]},p.subscriber_id)})})]})})]})]})}function Gu({children:t,tone:n,role:a}){return e.jsx("div",{className:n==="error"?"mt-4 rounded-xl border border-destructive/50 bg-destructive/10 p-4 text-destructive":"mt-4 rounded-xl border bg-card p-4 text-foreground",role:a,children:t})}const Dt=t=>({"x-aapi-role":t.role,"x-user-id":t.user_id}),v4=(t,n)=>be("/v1/aapi/portal-push",{...n,officer_id:n.officer_id??t.user_id},Dt(t)),j4=t=>he("/v1/aapi/portal-push/queue/pending",Dt(t)),y4=(t,n)=>be("/v1/aapi/investor-inquiries",{...n,officer_id:t.user_id},Dt(t)),_4=(t,n)=>he(`/v1/aapi/investor-inquiries/${n}/matches`,Dt(t)),b4=(t,n="")=>he(`/v1/aapi/linkage-records${n}`,Dt(t)),N4=(t,n,a)=>pl(`/v1/aapi/linkage-records/${n}/status`,{status:a},Dt(t)),w4=t=>be("/v1/aapi/linkage/expiry-sweep",{},Dt(t)),S4=t=>he("/v1/aapi/schema-versions",Dt(t)),C4=(t,n)=>be("/v1/aapi/schema-drift-check",{published_schema:n},Dt(t)),k4=(t,n,a=!1)=>pl(`/v1/aapi/schema-versions/${n}/promote`,{override:a},Dt(t)),E4=t=>he("/v1/aapi/integration-test-plans",Dt(t)),A4=(t,n)=>be("/v1/aapi/integration-test-plans",n,Dt(t)),R4=(t,n)=>be(`/v1/aapi/integration-test-plans/${n}/execute`,{},Dt(t)),P4=(t,n,a)=>Ri(`/v1/aapi/integration-test-plans/${n}/sign-off`,a,Dt(t)),T4=t=>he("/v1/aapi/admin/access-review",Dt(t)),L4=(t,n,a)=>be(`/v1/aapi/admin/users/${n}/roles`,{role_id:a},Dt(t)),F4=(t,n="")=>he(`/v1/aapi/reports/success-fee-attribution${n}`,Dt(t)),D4=(t,n)=>be("/v1/aapi/reports/success-fee-attribution/schedule",{quarter_label:n},Dt(t));function $4({identity:t}){const[n,a]=i.useState(""),[o,c]=i.useState(""),[u,h]=i.useState(""),[m,x]=i.useState(!1),[v,N]=i.useState(!1),[j,w]=i.useState(null),[_,S]=i.useState(""),[y,g]=i.useState([]),p=i.useCallback(()=>j4(t).then(C=>C.dead_letters),[t]);i.useEffect(()=>{let C=!0;return p().then(E=>{C&&g(E)},()=>{}),()=>{C=!1}},[p]);const k=i.useCallback(()=>p().then(C=>g(C),()=>{}),[p]),R=async()=>{N(!0),S(""),w(null);try{const C={card_id:n.trim(),investor_organization_name:o.trim(),override:m};u.trim()&&(C.foreign_equity_share=Number(u),Number(u)>49&&(C.compliance_override="NON_COMPLIANT_REVIEW_REQUIRED")),w(await v4(t,C)),await k()}catch(C){S(C instanceof Error?C.message:"Push failed")}finally{N(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"AAPI Portal Routing",description:"Push a pre-qualified opportunity card (CAS ≥ 60) to the AAPI digital registration portal (US-14.1)"}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Route a card"}),e.jsxs("div",{className:"grid max-w-[460px] gap-2 px-4",children:[e.jsxs("label",{children:["Card ID",e.jsx(me,{value:n,onChange:C=>a(C.target.value),placeholder:"720839@2025-Q1"})]}),e.jsxs("label",{children:["Investor organization",e.jsx(me,{value:o,onChange:C=>c(C.target.value),placeholder:"Maghreb Steel Ventures SPA"})]}),e.jsxs("label",{children:["Foreign equity % (optional)",e.jsx(me,{value:u,onChange:C=>h(C.target.value),placeholder:"49"})]}),e.jsxs("label",{className:"text-sm",children:[e.jsx("input",{type:"checkbox",checked:m,onChange:C=>x(C.target.checked),className:"size-4 accent-primary"})," Override duplicate submission"]}),e.jsx(K,{size:"sm",disabled:v||!n||!o,onClick:()=>void R(),children:v?"Routing…":"Route to AAPI Portal"})]})]}),_&&e.jsx(H,{tone:"error",children:_}),j&&e.jsxs(B,{className:"mt-4 gap-1 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Routed ",e.jsx(V,{variant:j.push_status==="SUBMITTED"?"success":"danger",children:j.push_status})]}),e.jsxs("p",{className:"px-4",children:["Portal reference: ",e.jsx("strong",{children:j.aapi_portal_reference??"—"}),j.provisional?" (provisional)":""]}),e.jsxs("p",{className:"px-4 text-sm text-muted-foreground",children:["Linkage ",j.linkage_id," · attempts ",j.attempts,j.requires_partner?" · 51/49 partner required":""]}),j.compliance_note&&e.jsxs("p",{className:"px-4 text-sm",children:["51/49 note: ",j.compliance_note]})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Retry / dead-letter queue"}),y.length===0?e.jsx(H,{children:"No pending retries — all pushes delivered."}):e.jsx("ul",{className:"list-disc px-8 text-sm",children:y.map((C,E)=>e.jsx("li",{children:JSON.stringify(C)},E))})]})]})}const I4=["AGRO_FOOD","PETROCHEMICALS","PHARMACEUTICALS","ELECTRICAL_EQUIPMENT","STEEL_METALS","CONSTRUCTION_MATERIALS","TEXTILES","MACHINERY"];function M4({identity:t}){const[n,a]=i.useState(""),[o,c]=i.useState(["STEEL_METALS"]),[u,h]=i.useState("1000000"),[m,x]=i.useState("500000000"),[v,N]=i.useState(!1),[j,w]=i.useState(""),[_,S]=i.useState(null),y=p=>c(k=>k.includes(p)?k.filter(R=>R!==p):[...k,p]),g=async()=>{N(!0),w(""),S(null);try{const p=await y4(t,{investor_organization_name:n.trim(),sector_codes:o,capex_bracket_min:Number(u),capex_bracket_max:Number(m)});S(await _4(t,p.inquiry_id))}catch(p){w(p instanceof Error?p.message:"Matching failed")}finally{N(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Investor Inquiry Intake",description:"Enter an inquiry and receive ranked CAS ≥ 60 opportunity cards in seconds (US-14.2)"}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"New inquiry"}),e.jsxs("div",{className:"grid max-w-[520px] gap-2 px-4",children:[e.jsxs("label",{children:["Investor organization",e.jsx(me,{value:n,onChange:p=>a(p.target.value),placeholder:"Maghreb Steel Ventures SPA"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Sectors"}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:I4.map(p=>e.jsx("button",{onClick:()=>y(p),className:"cursor-pointer border-none bg-transparent p-0",children:e.jsx(V,{variant:o.includes(p)?"success":"secondary",children:p})},p))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"flex-1",children:["CAPEX min (USD)",e.jsx(me,{value:u,onChange:p=>h(p.target.value)})]}),e.jsxs("label",{className:"flex-1",children:["CAPEX max (USD)",e.jsx(me,{value:m,onChange:p=>x(p.target.value)})]})]}),e.jsx(K,{size:"sm",disabled:v||!n||o.length===0,onClick:()=>void g(),children:v?"Matching…":"Match opportunity cards"})]})]}),j&&e.jsx(H,{tone:"error",children:j}),_&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Ranked matches ",e.jsx(V,{variant:"secondary",children:_.data_freshness??"—"})," ",_.spans_capex_brackets&&e.jsx(V,{variant:"warning",children:"spans CAPEX brackets"})]}),_.results.length===0?e.jsxs(e.Fragment,{children:[e.jsx(H,{children:"No qualifying opportunity cards meet CAS ≥ 60 for these parameters."}),_.below_threshold_fallback.length>0&&e.jsxs(je,{className:"mt-2",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Card"}),e.jsx(T,{className:"text-right",children:"CAS"}),e.jsx(T,{children:"Label"})]})}),e.jsx(ye,{children:_.below_threshold_fallback.map(p=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:p.card_id}),e.jsx(A,{className:"text-right tabular-nums",children:p.cas_score}),e.jsx(A,{children:p.label})]},p.card_id))})]})]}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Card"}),e.jsx(T,{children:"Sector"}),e.jsx(T,{children:"Wilaya"}),e.jsx(T,{className:"text-right",children:"CAS"}),e.jsx(T,{children:"CAPEX"}),e.jsx(T,{children:"Match"}),e.jsx(T,{children:"51/49"})]})}),e.jsx(ye,{children:_.results.map(p=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:p.card_id}),e.jsx(A,{children:p.sector_classification}),e.jsx(A,{children:p.wilaya_primary??"—"}),e.jsx(A,{className:"text-right tabular-nums",children:p.cas_score}),e.jsx(A,{children:p.capex_bracket}),e.jsx(A,{children:e.jsx("strong",{children:p.match_score})}),e.jsx(A,{children:p.daps_51_49_flag?e.jsx(V,{variant:"warning",children:"yes"}):"—"})]},p.card_id))})]}),e.jsxs("p",{className:"px-4 text-xs text-muted-foreground",children:["match config: ",_.config_version]})]})]})}const O4=["","PENDING_REGISTRATION","REGISTERED","DECLINED","EXPIRED","CANCELLED"];function z4({identity:t}){const[n,a]=i.useState(""),[o,c]=i.useState(null),[u,h]=i.useState(""),[m,x]=i.useState(!1),[v,N]=i.useState(null),[j,w]=i.useState(null),_=(j==null?void 0:j.identity)===t&&j.status===n?"error":(v==null?void 0:v.identity)===t&&v.status===n?"ok":"loading",S=i.useCallback(()=>b4(t,n?`?linkage_status=${n}`:""),[t,n]),y=i.useCallback(E=>{c(E),h(""),N({identity:t,status:n}),w(null)},[t,n]),g=i.useCallback(E=>{h(E instanceof Error?E.message:"Failed"),w({identity:t,status:n}),N(null)},[t,n]);i.useEffect(()=>{let E=!0;return S().then(P=>{E&&y(P)},P=>{E&&g(P)}),()=>{E=!1}},[S,y,g]);const p=i.useCallback(()=>(N(null),w(null),S().then(y,g)),[S,y,g]),k=async(E,P)=>{x(!0);try{await N4(t,E,P),await p()}catch(F){h(F instanceof Error?F.message:"Update failed")}finally{x(!1)}},R=async()=>{x(!0);try{await w4(t),await p()}finally{x(!1)}},C=t.role==="aapi_officer"||t.role==="platform_admin";return e.jsxs("div",{children:[e.jsx(Se,{title:"Linkage Tracker",description:"Every routed opportunity → AAPI registration, hash-chained for success-fee attribution (US-14.3)",actions:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{value:n,onChange:E=>a(E.target.value),"aria-label":"Linkage status",children:O4.map(E=>e.jsx("option",{value:E,children:E||"all statuses"},E))}),C&&e.jsx(K,{size:"sm",disabled:m,onClick:()=>void R(),children:"Run expiry sweep"})]})}),_==="loading"&&e.jsx(H,{children:"Loading linkage ledger…"}),_==="error"&&e.jsx(H,{tone:"error",children:u}),_==="ok"&&o&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(ue,{label:"Routed",value:o.metrics.total_routed}),e.jsx(ue,{label:"Registered",value:o.metrics.total_registered}),e.jsx(ue,{label:"Conversion",value:o.metrics.conversion_rate_pct==null?"—":`${o.metrics.conversion_rate_pct}%`}),e.jsx(ue,{label:"Registered CAPEX",value:Xe(o.metrics.registered_capex_value_usd)}),e.jsx(ue,{label:"Pipeline at risk",value:Xe(o.metrics.pipeline_value_at_risk_usd)})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Records (",o.count,")"]}),o.count===0?e.jsx(H,{children:"No linkage records for this filter."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Investor"}),e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Wilaya"}),e.jsx(T,{children:"CAPEX"}),e.jsx(T,{className:"text-right",children:"CAS@push"}),e.jsx(T,{children:"Current"}),e.jsx(T,{children:"Ref"}),e.jsx(T,{children:"Status"}),C&&e.jsx(T,{})]})}),e.jsx(ye,{children:o.records.map(E=>e.jsxs(ee,{children:[e.jsxs(A,{children:[E.investor_organization_name,E.registered_interest_badge&&e.jsxs(e.Fragment,{children:[" ",e.jsx(V,{variant:"secondary",children:E.registered_interest_badge})]})]}),e.jsx(A,{children:E.hs6_code}),e.jsx(A,{children:E.wilaya_primary??"—"}),e.jsx(A,{children:E.capex_bracket}),e.jsx(A,{className:"text-right tabular-nums",children:E.card_cas_score_at_push}),e.jsxs(A,{children:[E.current_cas_score??"—",E.cas_delta_material&&e.jsxs(V,{variant:"warning",children:["Δ",E.cas_delta]})]}),e.jsx(A,{className:"font-mono text-[11px]",children:E.aapi_portal_reference}),e.jsx(A,{children:e.jsx(V,{variant:E.linkage_status==="REGISTERED"?"success":E.linkage_status==="EXPIRED"?"danger":"secondary",children:E.linkage_status})}),C&&e.jsx(A,{children:E.linkage_status==="PENDING_REGISTRATION"&&!E.masked&&e.jsx(K,{size:"xs",disabled:m,onClick:()=>void k(E.linkage_id,"REGISTERED"),children:"Mark registered"})})]},E.linkage_id))})]})]})]})]})}function U4({identity:t}){const[n,a]=i.useState(null),[o,c]=i.useState(""),[u,h]=i.useState(""),[m,x]=i.useState(!1),[v,N]=i.useState(null),[j,w]=i.useState(null),_=j===t?"error":v===t?"ok":"loading",S=i.useCallback(()=>S4(t),[t]),y=i.useCallback(C=>{a(C),c(""),N(t),w(null)},[t]),g=i.useCallback(C=>{c(C instanceof Error?C.message:"Failed"),w(t),N(null)},[t]);i.useEffect(()=>{let C=!0;return S().then(E=>{C&&y(E)},E=>{C&&g(E)}),()=>{C=!1}},[S,y,g]);const p=i.useCallback(()=>(N(null),w(null),S().then(y,g)),[S,y,g]),k=async()=>{x(!0),h("");try{const C=await C4(t,n!=null&&n.active?{type:"object"}:null);h(C.drift?`Drift detected — ${C.classification}`:`No drift (${C.reason??"match"})`),await p()}catch(C){c(C instanceof Error?C.message:"Drift check failed")}finally{x(!1)}},R=async C=>{x(!0);try{await k4(t,C),await p()}catch(E){c(E instanceof Error?E.message:"Promote failed")}finally{x(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"AAPI Schema Registry",description:"Versioned portal schema with SHA-256 drift detection; every push validates against the active version (US-14.4)",actions:e.jsx(K,{size:"sm",disabled:m,onClick:()=>void k(),children:"Run drift check"})}),u&&e.jsx(H,{children:u}),_==="loading"&&e.jsx(H,{children:"Loading schema versions…"}),_==="error"&&e.jsx(H,{tone:"error",children:o}),_==="ok"&&n&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Versions"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Label"}),e.jsx(T,{children:"Hash"}),e.jsx(T,{children:"Compat"}),e.jsx(T,{children:"Active"}),e.jsx(T,{})]})}),e.jsx(ye,{children:n.versions.map(C=>e.jsxs(ee,{children:[e.jsx(A,{children:C.version_label}),e.jsxs(A,{className:"font-mono text-[11px]",children:[C.sha256_hash.slice(0,12),"…"]}),e.jsx(A,{children:e.jsx(V,{variant:C.backward_compatibility_status==="COMPATIBLE"?"success":C.backward_compatibility_status==="BREAKING_CHANGE"?"danger":"warning",children:C.backward_compatibility_status})}),e.jsx(A,{children:C.is_active?e.jsx(V,{variant:"success",children:"active"}):"—"}),e.jsx(A,{children:!C.is_active&&t.role==="platform_admin"&&e.jsx(K,{size:"xs",disabled:m,onClick:()=>void R(C.version_id),children:"Promote"})})]},C.version_id))})]})]})]})}const Wu=["AGRO_FOOD","PETROCHEMICALS","PHARMACEUTICALS","ELECTRICAL_EQUIPMENT","STEEL_METALS","CONSTRUCTION_MATERIALS","TEXTILES","MACHINERY"],Up=["LT_2M","10M_50M","GT_200M","2M_10M","50M_200M"],Bp=["PUSH_FAILURE","SCHEMA_VALIDATION_FAILURE","DUPLICATE_SUBMISSION","HAPPY_PATH","HAPPY_PATH","HAPPY_PATH","HAPPY_PATH","HAPPY_PATH"];function B4(){const t=Wu.map((n,a)=>({sector_code:n,capex_bracket:Up[a%Up.length],has_51_49_flag:a<2,test_type:Bp[a],expected_outcome:Bp[a]}));return t.push({sector_code:Wu[0],capex_bracket:"LT_2M",has_51_49_flag:!1,test_type:"HAPPY_PATH",expected_outcome:"HAPPY_PATH"}),t.push({sector_code:Wu[1],capex_bracket:"10M_50M",has_51_49_flag:!1,test_type:"HAPPY_PATH",expected_outcome:"HAPPY_PATH"}),t}function H4({identity:t}){const[n,a]=i.useState(null),[o,c]=i.useState(""),[u,h]=i.useState(""),[m,x]=i.useState(!1),[v,N]=i.useState(null),[j,w]=i.useState(null),_=j===t?"error":v===t?"ok":"loading",S=i.useCallback(()=>E4(t),[t]),y=i.useCallback(E=>{a(E),c(""),N(t),w(null)},[t]),g=i.useCallback(E=>{c(E instanceof Error?E.message:"Failed"),w(t),N(null)},[t]);i.useEffect(()=>{let E=!0;return S().then(P=>{E&&y(P)},P=>{E&&g(P)}),()=>{E=!1}},[S,y,g]);const p=i.useCallback(()=>(N(null),w(null),S().then(y,g)),[S,y,g]),k=async()=>{x(!0),c(""),h("");try{const E=await A4(t,{cases:B4(),target_launch_date:"2026-06-01"});h(`Plan ${E.plan_id} created (DRAFT).`),await p()}catch(E){c(E instanceof Error?E.message:"Create failed")}finally{x(!1)}},R=async E=>{x(!0);try{await R4(t,E),await p()}finally{x(!1)}},C=async E=>{x(!0),c("");try{await P4(t,E,{content:`signoff-${E}`,counterpart_name:"AAPI Technical",localize_officer_name:"CEO"}),await p()}catch(P){c(P instanceof Error?P.message:"Sign-off failed (all cases must PASS)")}finally{x(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Integration Test & Sign-Off",description:"Joint AAPI UAT: coverage-gated plans, isolated sandbox execution, tamper-evident sign-off (US-14.5)",actions:e.jsx(K,{size:"sm",disabled:m,onClick:()=>void k(),children:"Create coverage-complete plan"})}),u&&e.jsx(H,{children:u}),_==="loading"&&e.jsx(H,{children:"Loading plans…"}),_==="error"&&e.jsx(H,{tone:"error",children:o}),_==="ok"&&n&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Plans"}),n.plans.length===0?e.jsx(H,{children:"No test plans yet."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Plan"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Sign-off hash"}),e.jsx(T,{})]})}),e.jsx(ye,{children:n.plans.map(E=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-[11px]",children:E.plan_id}),e.jsx(A,{children:e.jsx(V,{variant:E.status==="SIGN_OFF_COMPLETE"?"success":E.status==="FAILED"?"danger":"secondary",children:E.status})}),e.jsx(A,{className:"font-mono text-[11px]",children:E.sign_off_artifact_hash?E.sign_off_artifact_hash.slice(0,12)+"…":"—"}),e.jsx(A,{children:e.jsxs("div",{className:"flex gap-1.5",children:[E.status!=="SIGN_OFF_COMPLETE"&&e.jsx(K,{size:"xs",disabled:m,onClick:()=>void R(E.plan_id),children:"Execute"}),E.status!=="SIGN_OFF_COMPLETE"&&e.jsx(K,{size:"xs",disabled:m,onClick:()=>void C(E.plan_id),children:"Sign off"})]})})]},E.plan_id))})]})]})]})}const V4=["aapi_officer","ceo","afdb_analyst","fni_portfolio_manager"];function G4({identity:t}){const[n,a]=i.useState(null),[o,c]=i.useState(""),[u,h]=i.useState(""),[m,x]=i.useState(""),[v,N]=i.useState("aapi_officer"),[j,w]=i.useState(!1),[_,S]=i.useState(null),[y,g]=i.useState(null),p=y===t?"error":_===t?"ok":"loading",k=i.useCallback(()=>T4(t),[t]),R=i.useCallback(F=>{a(F),c(""),S(t),g(null)},[t]),C=i.useCallback(F=>{c(F instanceof Error?F.message:"Failed"),g(t),S(null)},[t]);i.useEffect(()=>{let F=!0;return k().then(I=>{F&&R(I)},I=>{F&&C(I)}),()=>{F=!1}},[k,R,C]);const E=i.useCallback(()=>(S(null),g(null),k().then(R,C)),[k,R,C]),P=async()=>{w(!0),c(""),h("");try{await L4(t,m.trim(),v),h(`${m} → ${v} (session invalidated).`),x(""),await E()}catch(F){c(F instanceof Error?F.message:"Assign failed")}finally{w(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"AAPI Access Admin",description:"Role provisioning + quarterly access review for Loi 18-07 ANPDP compliance (US-14.6)"}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-2 px-4",children:[e.jsxs("label",{children:["User ID",e.jsx(me,{value:m,onChange:F=>x(F.target.value),placeholder:"officer-nadia"})]}),e.jsxs("label",{children:["Role",e.jsx(Ie,{className:"block",value:v,onChange:F=>N(F.target.value),"aria-label":"Role",children:V4.map(F=>e.jsx("option",{value:F,children:F},F))})]}),e.jsx(K,{size:"sm",disabled:j||!m,onClick:()=>void P(),children:"Assign role"})]})}),u&&e.jsx(H,{children:u}),p==="loading"&&e.jsx(H,{children:"Loading access review…"}),p==="error"&&e.jsx(H,{tone:"error",children:o}),p==="ok"&&n&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Quarterly access review (",n.total_users," users)"]}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"User"}),e.jsx(T,{children:"Role"}),e.jsx(T,{children:"Permissions"}),e.jsx(T,{className:"text-right",children:"Submissions"}),e.jsx(T,{children:"Failed access"})]})}),e.jsx(ye,{children:n.users.map(F=>e.jsxs(ee,{children:[e.jsx(A,{children:F.user_id}),e.jsx(A,{children:e.jsx(V,{variant:"secondary",children:F.role_id})}),e.jsx(A,{className:"text-[11px]",children:F.permissions.join(", ")}),e.jsx(A,{className:"text-right tabular-nums",children:F.routing_submissions}),e.jsx(A,{children:F.failed_access_attempts>0?e.jsx(V,{variant:"danger",children:F.failed_access_attempts}):0})]},F.user_id))})]})]})]})}function W4({identity:t}){const[n,a]=i.useState(null),[o,c]=i.useState(""),[u,h]=i.useState(""),[m,x]=i.useState(!1),[v,N]=i.useState(null),[j,w]=i.useState(null),_=j===t?"error":v===t?"ok":"loading",S=i.useCallback(async()=>F4(t),[t]),y=i.useCallback(R=>{a(R),c(""),N(t),w(null)},[t]),g=i.useCallback(R=>{c(R instanceof Error?R.message:"Failed"),w(t),N(null)},[t]);i.useEffect(()=>{let R=!0;return S().then(C=>{R&&y(C)},C=>{R&&g(C)}),()=>{R=!1}},[S,y,g]);const p=async()=>{x(!0),h("");try{const R=await D4(t,"Q1-2026");h(`Quarterly report ${R.job_id} generated for ${R.quarter_label}.`)}catch(R){c(R instanceof Error?R.message:"Quarterly run failed")}finally{x(!1)}},k=n==null?void 0:n.report;return e.jsxs("div",{children:[e.jsx(Se,{title:"Success-Fee Attribution",description:"Routed → registered conversion + attributed CAPEX underpinning the AAPI success-fee arrangement (US-14.7)",actions:e.jsx(K,{size:"sm",disabled:m,onClick:()=>void p(),children:"Run quarterly report"})}),u&&e.jsx(H,{children:u}),_==="loading"&&e.jsx(H,{children:"Loading attribution…"}),_==="error"&&e.jsx(H,{tone:"error",children:o}),_==="ok"&&k&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(ue,{label:"Routed",value:k.total_inquiries_routed}),e.jsx(ue,{label:"Registered",value:k.total_converted}),e.jsx(ue,{label:"Conversion",value:k.conversion_rate_pct==null?"—":`${k.conversion_rate_pct}%`}),e.jsx(ue,{label:"Registered CAPEX",value:Xe(k.cumulative_capex_registered_usd)}),e.jsx(ue,{label:"Pipeline at risk",value:Xe(k.pipeline_value_at_risk_usd)})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Sector breakdown"}),k.sector_breakdown.length===0?e.jsx(H,{children:"No routed opportunities yet."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Sector (chapter)"}),e.jsx(T,{className:"text-right",children:"Routed"}),e.jsx(T,{className:"text-right",children:"Registered"})]})}),e.jsx(ye,{children:k.sector_breakdown.map(R=>e.jsxs(ee,{children:[e.jsx(A,{children:R.sector_classification}),e.jsx(A,{className:"text-right tabular-nums",children:R.routed_count}),e.jsx(A,{className:"text-right tabular-nums",children:R.registered_count})]},R.sector_classification))})]})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Supporting registered linkages (",k.supporting_linkage_records.length,")"]}),e.jsx("p",{className:"px-4 text-xs text-muted-foreground",children:k.supporting_linkage_records.join(", ")||"none"})]})]}),_==="ok"&&n&&n.async&&e.jsxs(H,{children:["Long-period report queued as job ",n.job_id,"."]})]})}const q4=()=>he("/v1/ocr/health"),Q4=t=>be("/v1/ocr/benchmark/run",{corpus_id:t}),K4=t=>be("/v1/nlp/extract",t),X4=()=>he("/v1/nlp/conflicts"),Y4=()=>he("/v1/schema-registry/regulatory-entity/current"),Z4=()=>he("/v1/schema-registry/regulatory-entity/versions"),J4=()=>he("/v1/gazette-monitor/sources"),eA=()=>be("/v1/gazette-monitor/poll",{}),tA=()=>he("/v1/gazette-monitor/detected-documents"),sA=()=>be("/v1/daps/extract",{}),nA=t=>be("/v1/cas/rescoring/trigger",t),rA=()=>be("/v1/nlp/extract/law-23-17",{}),aA=()=>be("/v1/nlp/extract/mining-law-2025",{}),lA=()=>he("/v1/nlp/document-classifier/classify"),iA=t=>be("/v1/benchmark/run",{corpus_id:t}),oA=()=>he("/v1/benchmark/trend"),cA=()=>he("/v1/translation-memory/terms"),dA=()=>he("/v1/translation-memory/correction-rate"),uA=t=>be("/v1/translation-memory/terms",t);function mA(){const[t,n]=i.useState(null),[a,o]=i.useState(null),[c,u]=i.useState(!1),[h,m]=i.useState(!1),[x,v]=i.useState(""),[N,j]=i.useState(!1),w=h?"error":c?"ok":"loading",_=i.useCallback(async()=>q4(),[]),S=i.useCallback(p=>{n(p),u(!0),m(!1)},[]),y=i.useCallback(p=>{v(p instanceof Error?p.message:"Failed"),m(!0),u(!1)},[]);i.useEffect(()=>{let p=!0;return _().then(k=>{p&&S(k)},k=>{p&&y(k)}),()=>{p=!1}},[_,S,y]);const g=async()=>{j(!0),v("");try{o(await Q4())}catch(p){v(p instanceof Error?p.message:"Benchmark failed")}finally{j(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"OCR Benchmark",description:"Character-error-rate benchmark against the regulatory corpus with a hard CER gate (Epic-16).",actions:e.jsx(K,{size:"sm",disabled:N,onClick:()=>void g(),children:"Run OCR benchmark"})}),w==="loading"&&e.jsx(H,{children:"Loading OCR health…"}),w==="error"&&e.jsx(H,{tone:"error",children:x}),w==="ok"&&t&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Model loaded",value:t.model_loaded?e.jsx(V,{variant:"success",children:"yes"}):e.jsx(V,{variant:"danger",children:"no"})}),e.jsx(ue,{label:"Model version",value:t.model_version}),e.jsx(ue,{label:"OCR config version",value:t.ocr_config_version}),e.jsx(ue,{label:"CER gate",value:t.cer_gate.toFixed(4)})]})}),N&&e.jsx(H,{children:"Running benchmark…"}),a&&e.jsxs(B,{className:"mt-4 gap-4 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Run ",a.run_id]}),e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Aggregate CER",value:a.aggregate_cer.toFixed(4),tone:a.gate_pass?"ok":"error"}),e.jsx(ue,{label:"CER gate",value:a.cer_gate.toFixed(4)}),e.jsx(ue,{label:"Gate",value:e.jsx(V,{variant:a.gate_pass?"success":"danger",children:a.gate_pass?"PASS":"FAIL"})}),e.jsx(ue,{label:"Low-res CER",value:a.low_res_cer.toFixed(4)}),e.jsx(ue,{label:"Total pages",value:a.total_pages})]}),e.jsx("h2",{className:"px-4 text-base font-semibold",children:"By language"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Language"}),e.jsx(T,{className:"text-right",children:"CER"})]})}),e.jsx(ye,{children:Object.entries(a.by_language).map(([p,k])=>e.jsxs(ee,{children:[e.jsx(A,{children:p}),e.jsx(A,{className:"text-right tabular-nums",children:k.toFixed(4)})]},p))})]}),e.jsx("h2",{className:"px-4 text-base font-semibold",children:"By decade"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Decade"}),e.jsx(T,{className:"text-right",children:"CER"})]})}),e.jsx(ye,{children:Object.entries(a.by_decade).map(([p,k])=>e.jsxs(ee,{children:[e.jsx(A,{children:p}),e.jsx(A,{className:"text-right tabular-nums",children:k.toFixed(4)})]},p))})]})]})]})}function hA(){const[t,n]=i.useState([]),[a,o]=i.useState(!1),[c,u]=i.useState(!1),[h,m]=i.useState(""),x=c?"error":a?"ok":"loading",v=i.useCallback(async()=>(await X4()).conflicts,[]),N=i.useCallback(w=>{n(w),o(!0),u(!1)},[]),j=i.useCallback(w=>{m(w instanceof Error?w.message:"Failed"),u(!0),o(!1)},[]);return i.useEffect(()=>{let w=!0;return v().then(_=>{w&&N(_)},_=>{w&&j(_)}),()=>{w=!1}},[v,N,j]),e.jsxs("div",{children:[e.jsx(Se,{title:"Pre-Processing Monitor",description:"Ingest/pre-processing conflicts surfaced by the NLP pipeline (Epic-16)."}),x==="loading"&&e.jsx(H,{children:"Loading conflicts…"}),x==="error"&&e.jsx(H,{tone:"error",children:h}),x==="ok"&&e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Conflicts"}),t.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"No conflicts detected."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Document"}),e.jsx(T,{children:"Detail"}),e.jsx(T,{children:"Created"})]})}),e.jsx(ye,{children:t.map(w=>e.jsxs(ee,{children:[e.jsx(A,{children:e.jsx(V,{variant:"warning",children:w.conflict_type})}),e.jsx(A,{className:"font-mono text-xs",children:w.document_id}),e.jsx(A,{children:w.detail}),e.jsx(A,{className:"text-xs text-muted-foreground",children:w.created_at})]},w.conflict_id))})]})]})]})}function fA(){const[t,n]=i.useState("demo-doc-1"),[a,o]=i.useState(""),[c,u]=i.useState(null),[h,m]=i.useState(""),[x,v]=i.useState(!1),N=async()=>{v(!0),m("");try{u(await K4({document_id:t,text:a}))}catch(j){m(j instanceof Error?j.message:"Extraction failed")}finally{v(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Extraction Review",description:"Run the NLP entity extraction over regulatory text and review the persisted entities, queue, and conflicts (Epic-16)."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-col gap-2 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Document ID"}),e.jsx(me,{className:"flex-1",value:t,onChange:j=>n(j.target.value)})]}),e.jsx(fa,{className:"min-h-[140px]",placeholder:"Paste regulatory text to extract…",value:a,onChange:j=>o(j.target.value),"aria-label":"Regulatory text"}),e.jsx("div",{children:e.jsx(K,{size:"sm",disabled:x||!t||!a,onClick:()=>void N(),children:"Run extraction"})})]})}),x&&e.jsx(H,{children:"Extracting…"}),h&&e.jsx(H,{tone:"error",children:h}),c&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Pipeline run",value:c.pipeline_run_id}),e.jsx(ue,{label:"Extracted",value:c.extracted_count}),e.jsx(ue,{label:"Persisted",value:c.persisted_count}),e.jsx(ue,{label:"TM correction rate",value:c.tm_correction_rate.toFixed(4)})]})}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Entities (",c.entities.length,")"]}),c.entities.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"No entities extracted."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Value"}),e.jsx(T,{className:"text-right",children:"Confidence"})]})}),e.jsx(ye,{children:c.entities.map((j,w)=>e.jsxs(ee,{children:[e.jsx(A,{children:e.jsx(V,{children:j.entity_type})}),e.jsx(A,{children:j.value}),e.jsx(A,{className:"text-right tabular-nums",children:j.confidence!==void 0?j.confidence.toFixed(3):"—"})]},j.entity_id??w))})]})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Review queue (",c.review_queue.length,")"]}),c.review_queue.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"Nothing awaiting review."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Value"}),e.jsx(T,{children:"Reason"})]})}),e.jsx(ye,{children:c.review_queue.map((j,w)=>e.jsxs(ee,{children:[e.jsx(A,{children:j.entity_type??"—"}),e.jsx(A,{children:j.value??"—"}),e.jsx(A,{children:j.reason??"—"})]},j.review_id??w))})]})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Conflicts (",c.conflicts.length,")"]}),c.conflicts.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"No conflicts."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Detail"})]})}),e.jsx(ye,{children:c.conflicts.map(j=>e.jsxs(ee,{children:[e.jsx(A,{children:e.jsx(V,{variant:"warning",children:j.conflict_type})}),e.jsx(A,{children:j.detail})]},j.conflict_id))})]})]})]})]})}function xA(){const[t,n]=i.useState(null),[a,o]=i.useState([]),[c,u]=i.useState(""),[h,m]=i.useState(!1),[x,v]=i.useState(!1),N=x?"error":h?"ok":"loading",j=i.useCallback(async()=>{const[y,g]=await Promise.all([Y4(),Z4()]);return{c:y,v:g.versions}},[]),w=i.useCallback(y=>{n(y.c),o(y.v),u(""),m(!0),v(!1)},[]),_=i.useCallback(y=>{u(y instanceof Error?y.message:"Failed"),v(!0),m(!1)},[]);i.useEffect(()=>{let y=!0;return j().then(g=>{y&&w(g)},g=>{y&&_(g)}),()=>{y=!1}},[j,w,_]);const S=y=>y==="APPROVED"?"success":y==="REJECTED"?"danger":"warning";return e.jsxs("div",{children:[e.jsx(Se,{title:"Regulatory Schema Registry",description:"Versioned regulatory-entity schema with peer-review approval gating (Epic-16)."}),N==="loading"&&e.jsx(H,{children:"Loading schema versions…"}),N==="error"&&e.jsx(H,{tone:"error",children:c}),N==="ok"&&e.jsxs(e.Fragment,{children:[t&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Active version",value:t.schema_version}),e.jsx(ue,{label:"Active",value:t.is_active?e.jsx(V,{variant:"success",children:"active"}):"—"}),e.jsx(ue,{label:"Peer review",value:e.jsx(V,{variant:S(t.peer_review_approval_status),children:t.peer_review_approval_status})})]})}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Versions"}),a.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"No schema versions."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Version"}),e.jsx(T,{children:"Peer review"}),e.jsx(T,{children:"Active"})]})}),e.jsx(ye,{children:a.map(y=>e.jsxs(ee,{children:[e.jsx(A,{children:y.schema_version}),e.jsx(A,{children:e.jsx(V,{variant:S(y.peer_review_approval_status),children:y.peer_review_approval_status})}),e.jsx(A,{children:y.is_active?e.jsx(V,{variant:"success",children:"active"}):"—"})]},y.schema_version))})]})]})]})]})}function pA(){const[t,n]=i.useState([]),[a,o]=i.useState([]),[c,u]=i.useState(""),[h,m]=i.useState(""),[x,v]=i.useState(!1),[N,j]=i.useState(!1),[w,_]=i.useState(!1),S=w?"error":N?"ok":"loading",y=i.useCallback(async()=>{const[C,E]=await Promise.all([J4(),tA()]);return{sources:C.sources,docs:E.documents}},[]),g=i.useCallback(({sources:C,docs:E})=>{n(C),o(E),j(!0),_(!1)},[]),p=i.useCallback(C=>{u(C instanceof Error?C.message:"Failed"),_(!0),j(!1)},[]),k=i.useCallback(()=>(j(!1),_(!1),y().then(g,p)),[y,g,p]);i.useEffect(()=>{let C=!0;return y().then(E=>{C&&g(E)},E=>{C&&p(E)}),()=>{C=!1}},[y,g,p]);const R=async()=>{v(!0),u(""),m("");try{const C=await eA();m(`Polled ${C.polled_sources} sources — ${C.emitted_count} emitted, ${C.duplicates.length} duplicates.`),await k()}catch(C){u(C instanceof Error?C.message:"Poll failed")}finally{v(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Gazette Monitor",description:"Monitored gazette sources with SLA-timed detection lag and high-priority flagging (Epic-16).",actions:e.jsx(K,{size:"sm",disabled:x,onClick:()=>void R(),children:"Poll now"})}),h&&e.jsx(H,{children:h}),S==="loading"&&e.jsx(H,{children:"Loading gazette sources…"}),S==="error"&&e.jsx(H,{tone:"error",children:c}),S==="ok"&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Sources (",t.length,")"]}),t.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"No sources configured."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"URL"}),e.jsx(T,{children:"Type"}),e.jsx(T,{className:"text-right",children:"Interval"}),e.jsx(T,{children:"Enabled"}),e.jsx(T,{children:"Last checked"})]})}),e.jsx(ye,{children:t.map(C=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:C.url}),e.jsx(A,{children:C.source_type}),e.jsxs(A,{className:"text-right tabular-nums",children:[C.poll_interval_seconds,"s"]}),e.jsx(A,{children:C.enabled?e.jsx(V,{variant:"success",children:"on"}):e.jsx(V,{variant:"secondary",children:"off"})}),e.jsx(A,{className:"text-xs text-muted-foreground",children:C.last_checked_at??"—"})]},C.source_id))})]})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Detected documents (",a.length,")"]}),a.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"No documents detected yet."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Document"}),e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Issue"}),e.jsx(T,{children:"Published"}),e.jsx(T,{className:"text-right",children:"Lag"}),e.jsx(T,{children:"SLA"}),e.jsx(T,{children:"Priority"})]})}),e.jsx(ye,{children:a.map(C=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:C.document_id}),e.jsx(A,{children:C.document_type}),e.jsx(A,{children:C.gazette_issue_number??"—"}),e.jsx(A,{className:"text-xs text-muted-foreground",children:C.publication_date??"—"}),e.jsxs(A,{className:"text-right tabular-nums",children:[C.detection_lag_minutes," min"]}),e.jsx(A,{children:e.jsx(V,{variant:C.detection_sla_met?"success":"danger",children:C.detection_sla_met?"met":"breach"})}),e.jsx(A,{children:C.high_priority?e.jsx(V,{variant:"warning",children:"high"}):"—"})]},C.document_id))})]})]})]})]})}function gA(){const[t,n]=i.useState(null),[a,o]=i.useState(""),[c,u]=i.useState(!1),h=async()=>{u(!0),o("");try{n(await sA())}catch(x){o(x instanceof Error?x.message:"DAPS extract failed")}finally{u(!1)}},m=(x,v,N)=>e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:[x," (",N.length,")"]}),e.jsx("div",{className:"px-4",children:N.length===0?e.jsx(H,{children:"None."}):e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-sm",children:N.map((j,w)=>e.jsxs("li",{children:[e.jsx(V,{variant:v,children:x.split(" ")[0]})," ",e.jsx("span",{className:"font-mono text-xs",children:typeof j=="string"?j:JSON.stringify(j)})]},w))})})]});return e.jsxs("div",{children:[e.jsx(Se,{title:"DAPS Coverage",description:"Duty-and-preferential-scheme extraction with line-coverage accounting and an SLA gate (Epic-16).",actions:e.jsx(K,{size:"sm",disabled:c,onClick:()=>void h(),children:"Run DAPS extract"})}),c&&e.jsx(H,{children:"Extracting…"}),a&&e.jsx(H,{tone:"error",children:a}),t&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Total lines",value:t.coverage.total_lines}),e.jsx(ue,{label:"Resolved",value:t.coverage.resolved_count,tone:"ok"}),e.jsx(ue,{label:"Unresolved",value:t.coverage.unresolved_count,tone:t.coverage.unresolved_count>0?"error":void 0}),e.jsx(ue,{label:"Out-of-band",value:t.coverage.out_of_band_count}),e.jsx(ue,{label:"Coverage",value:`${t.coverage.coverage_pct.toFixed(1)}%`}),e.jsx(ue,{label:"SLA",value:e.jsx(V,{variant:t.sla.sla_met?"success":"danger",children:t.sla.sla_met?"met":"breach"})}),e.jsx(ue,{label:"Duration",value:`${t.sla.actual_duration_seconds}s / ${t.sla.sla_threshold_seconds}s`})]})}),m("Resolved lines","success",t.resolved),m("Unresolved lines","danger",t.unresolved),m("Out-of-band lines","warning",t.out_of_band)]})]})}function vA(){const[t,n]=i.useState(null),[a,o]=i.useState(""),[c,u]=i.useState(!1),h=async()=>{u(!0),o("");try{const m={rule_id:"demo-rule-1",affected_hs6_codes:["847130","851712"],change_type:"daps_update",rule_write_at:new Date().toISOString()};n(await nA({event:m,scores:{priorScores:{847130:62},newScores:{847130:58}}}))}catch(m){o(m instanceof Error?m.message:"Trigger failed")}finally{u(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Re-Scoring Audit",description:"Trigger a CAS re-scoring dispatch from a rule-change event and audit scope, SLA, and downstream deltas (Epic-16).",actions:e.jsx(K,{size:"sm",disabled:c,onClick:()=>void h(),children:"Trigger demo re-scoring"})}),c&&e.jsx(H,{children:"Dispatching…"}),a&&e.jsx(H,{tone:"error",children:a}),t&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Dispatch",value:t.dispatch_id}),e.jsx(ue,{label:"Rule",value:t.rule_id}),e.jsx(ue,{label:"Scope tier",value:e.jsx(V,{children:t.scope_tier})}),e.jsx(ue,{label:"Affected HS6",value:t.affected_hs6_count}),e.jsx(ue,{label:"SLA",value:e.jsx(V,{variant:t.sla_met?"success":"danger",children:t.sla_met?"met":"breach"})}),e.jsx(ue,{label:"Latency",value:`${t.dispatch_latency_seconds}s`})]})}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Delta flags (",t.delta_flags.length,")"]}),e.jsx("div",{className:"px-4",children:t.delta_flags.length===0?e.jsx(H,{children:"No delta flags raised."}):e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-sm",children:t.delta_flags.map((m,x)=>e.jsx("li",{className:"font-mono text-xs",children:typeof m=="string"?m:JSON.stringify(m)},x))})})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Card deactivations (",t.card_deactivations.length,")"]}),e.jsx("div",{className:"px-4",children:t.card_deactivations.length===0?e.jsx(H,{children:"No card deactivations."}):e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-sm",children:t.card_deactivations.map((m,x)=>e.jsx("li",{className:"font-mono text-xs",children:typeof m=="string"?m:JSON.stringify(m)},x))})})]})]})]})}function jA(){const[t,n]=i.useState(null),[a,o]=i.useState(null),[c,u]=i.useState(!1),[h,m]=i.useState(!1),[x,v]=i.useState(""),[N,j]=i.useState(!1),w=h?"error":c?"ok":"loading",_=i.useCallback(async()=>lA(),[]),S=i.useCallback(p=>{o(p),u(!0),m(!1)},[]),y=i.useCallback(p=>{v(p instanceof Error?p.message:"Failed"),m(!0),u(!1)},[]);i.useEffect(()=>{let p=!0;return _().then(k=>{p&&S(k)},k=>{p&&y(k)}),()=>{p=!1}},[_,S,y]);const g=async p=>{j(!0),v("");try{n(await(p==="law"?rA():aA()))}catch(k){v(k instanceof Error?k.message:"Extraction failed")}finally{j(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Law / Mining Extraction",description:"Golden-set extraction for Law 23-17 and the 2025 mining-law amendment, recall-gated (Epic-16).",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{size:"sm",disabled:N,onClick:()=>void g("law"),children:"Extract Law 23-17"}),e.jsx(K,{size:"sm",disabled:N,onClick:()=>void g("mining"),children:"Extract Mining 2025"})]})}),w==="loading"&&e.jsx(H,{children:"Loading classifier accuracy…"}),w==="error"&&e.jsx(H,{tone:"error",children:x}),w==="ok"&&a&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Classifier accuracy",value:a.accuracy.toFixed(4),tone:a.gate_pass?"ok":"error"}),e.jsx(ue,{label:"Gate",value:a.gate.toFixed(4)}),e.jsx(ue,{label:"Gate result",value:e.jsx(V,{variant:a.gate_pass?"success":"danger",children:a.gate_pass?"PASS":"FAIL"})})]})}),N&&e.jsx(H,{children:"Extracting…"}),t&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Kind",value:t.kind}),e.jsx(ue,{label:"51/49",value:e.jsx(V,{variant:t.has_51_49_flag?"warning":"secondary",children:t.has_51_49_flag?"flagged":"none"})}),e.jsx(ue,{label:"Foreign equity",value:e.jsx(V,{variant:t.foreign_equity_flag?"warning":"secondary",children:t.foreign_equity_flag?"flagged":"none"})}),e.jsx(ue,{label:"Overall recall",value:t.overall_recall.toFixed(4),tone:t.recall_gate_pass?"ok":"error"}),e.jsx(ue,{label:"Recall gate",value:t.recall_gate.toFixed(4)}),e.jsx(ue,{label:"Gate result",value:e.jsx(V,{variant:t.recall_gate_pass?"success":"danger",children:t.recall_gate_pass?"PASS":"FAIL"})})]})}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Resolved wilayas (",t.resolved_wilayas.length,")"]}),e.jsx("div",{className:"px-4",children:t.resolved_wilayas.length===0?e.jsx(H,{children:"None resolved."}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.resolved_wilayas.map(p=>e.jsx(V,{children:p},p))})})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Entities (",t.entities.length,")"]}),t.entities.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"No entities extracted."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Value"})]})}),e.jsx(ye,{children:t.entities.map((p,k)=>e.jsxs(ee,{children:[e.jsx(A,{children:e.jsx(V,{children:p.entity_type})}),e.jsx(A,{children:p.value})]},p.entity_id??k))})]})]})]})]})}function yA(){const[t,n]=i.useState(null),[a,o]=i.useState(null),[c,u]=i.useState("loading"),[h,m]=i.useState(""),[x,v]=i.useState(!1),N=i.useCallback(async()=>oA(),[]),j=i.useCallback(g=>{n(g),u("ok")},[]),w=i.useCallback(g=>{m(g instanceof Error?g.message:"Failed"),u("error")},[]);i.useEffect(()=>{let g=!0;return N().then(p=>{g&&j(p)},p=>{g&&w(p)}),()=>{g=!1}},[N,j,w]);const _=i.useCallback(()=>(u("loading"),m(""),N().then(j,w)),[N,j,w]),S=async()=>{v(!0),m("");try{o(await iA()),await _()}catch(g){m(g instanceof Error?g.message:"Benchmark failed")}finally{v(!1)}},y=(g,p)=>{if(g.length===0)return null;const k=320,R=60,C=Math.max(p,...g)*1.1||1,E=g.length>1?k/(g.length-1):0,P=g.map((I,M)=>`${M*E},${R-I/C*R}`).join(" "),F=R-p/C*R;return e.jsxs("svg",{width:k,height:R,className:"rounded-lg border border-border bg-muted",children:[e.jsx("line",{x1:0,y1:F,x2:k,y2:F,className:"stroke-destructive",strokeDasharray:"4 3",strokeWidth:1}),e.jsx("polyline",{points:P,fill:"none",className:"stroke-success",strokeWidth:2})]})};return e.jsxs("div",{children:[e.jsx(Se,{title:"Benchmark Trend",description:"Run the pipeline benchmark and track CER / duty-rate recall against thresholds over time (Epic-16).",actions:e.jsx(K,{size:"sm",disabled:x,onClick:()=>void S(),children:"Run benchmark"})}),a&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Last run",value:a.run_id}),e.jsx(ue,{label:"Gate",value:e.jsx(V,{variant:a.gate_pass?"success":"danger",children:a.gate_pass?"PASS":"FAIL"})}),e.jsx(ue,{label:"F1 regression",value:a.f1_regression.toFixed(4)}),e.jsx(ue,{label:"Threshold violations",value:a.threshold_violations.length,tone:a.threshold_violations.length>0?"error":void 0})]})}),x&&e.jsx(H,{children:"Running benchmark…"}),c==="loading"&&e.jsx(H,{children:"Loading trend…"}),c==="error"&&e.jsx(H,{tone:"error",children:h}),c==="ok"&&t&&e.jsxs(B,{className:"mt-4 gap-4 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["CER series (threshold ",t.thresholds.cer.toFixed(4),")"]}),e.jsx("div",{className:"px-4",children:y(t.points.map(g=>g.cer),t.thresholds.cer)}),e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Runs"}),t.points.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"No benchmark runs yet."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Run"}),e.jsx(T,{children:"Timestamp"}),e.jsxs(T,{className:"text-right",children:["CER (≤",t.thresholds.cer.toFixed(4),")"]}),e.jsxs(T,{className:"text-right",children:["Duty recall (≥",t.thresholds.duty_rate_recall.toFixed(4),")"]}),e.jsx(T,{children:"Gate"})]})}),e.jsx(ye,{children:t.points.map(g=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:g.run_id}),e.jsx(A,{className:"text-xs text-muted-foreground",children:g.run_timestamp}),e.jsx(A,{className:g.cer<=t.thresholds.cer?"text-right tabular-nums text-success":"text-right tabular-nums text-destructive",children:g.cer.toFixed(4)}),e.jsx(A,{className:g.duty_rate_recall>=t.thresholds.duty_rate_recall?"text-right tabular-nums text-success":"text-right tabular-nums text-destructive",children:g.duty_rate_recall.toFixed(4)}),e.jsx(A,{children:e.jsx(V,{variant:g.gate_pass?"success":"danger",children:g.gate_pass?"PASS":"FAIL"})})]},g.run_id))})]})]})]})}function _A(){const[t,n]=i.useState(null),[a,o]=i.useState(null),[c,u]=i.useState(""),[h,m]=i.useState(""),[x,v]=i.useState(!1),[N,j]=i.useState(!1),[w,_]=i.useState(!1),[S,y]=i.useState(""),[g,p]=i.useState(""),[k,R]=i.useState(""),[C,E]=i.useState(""),P=w?"error":N?"ok":"loading",F=i.useCallback(async()=>{const[L,z]=await Promise.all([cA(),dA()]);return{t:L,r:z}},[]),I=i.useCallback(L=>{n(L.t),o(L.r),u(""),j(!0),_(!1)},[]),M=i.useCallback(L=>{u(L instanceof Error?L.message:"Failed"),_(!0),j(!1)},[]),$=i.useCallback(()=>(j(!1),_(!1),u(""),F().then(I,M)),[F,I,M]);i.useEffect(()=>{let L=!0;return F().then(z=>{L&&I(z)},z=>{L&&M(z)}),()=>{L=!1}},[F,I,M]);const O=async()=>{v(!0),u(""),m("");try{const L=await uA({arabic_term:S,french_term:g,canonical_schema_value:k,domain:C});m(`Term ${L.term_id} added.`),y(""),p(""),R(""),E(""),await $()}catch(L){u(L instanceof Error?L.message:"Add failed")}finally{v(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Translation Memory",description:"AR/FR glossary that anchors the pipeline to canonical schema values; completeness + correction-rate gated (Epic-16)."}),h&&e.jsx(H,{children:h}),P==="loading"&&e.jsx(H,{children:"Loading translation memory…"}),P==="error"&&e.jsx(H,{tone:"error",children:c}),P==="ok"&&t&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-6 px-4",children:[e.jsx(ue,{label:"Total active",value:t.completeness.total_active}),e.jsx(ue,{label:"Complete",value:e.jsx(V,{variant:t.completeness.complete?"success":"warning",children:t.completeness.complete?"complete":"gaps"})}),a&&e.jsx(ue,{label:"Correction rate",value:a.correction_rate.toFixed(4),tone:a.gate_pass?"ok":"error"}),a&&e.jsx(ue,{label:"Correction gate",value:e.jsx(V,{variant:a.gate_pass?"success":"danger",children:a.gate_pass?"PASS":"FAIL"})})]})}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Completeness by domain"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Domain"}),e.jsx(T,{className:"text-right",children:"Terms"})]})}),e.jsx(ye,{children:Object.entries(t.completeness.by_domain).map(([L,z])=>e.jsxs(ee,{children:[e.jsx(A,{children:L}),e.jsx(A,{className:"text-right tabular-nums",children:z})]},L))})]})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Add term"}),e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(me,{className:"w-44",placeholder:"Arabic term",value:S,onChange:L=>y(L.target.value),dir:"rtl"}),e.jsx(me,{className:"w-44",placeholder:"French term",value:g,onChange:L=>p(L.target.value)}),e.jsx(me,{className:"w-44",placeholder:"Canonical schema value",value:k,onChange:L=>R(L.target.value)}),e.jsx(me,{className:"w-44",placeholder:"Domain",value:C,onChange:L=>E(L.target.value)})]}),e.jsx(K,{size:"sm",disabled:x||!S||!g||!k||!C,onClick:()=>void O(),children:"Add term"})]})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Terms (",t.terms.length,")"]}),t.terms.length===0?e.jsx("div",{className:"px-4",children:e.jsx(H,{children:"No terms yet."})}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Arabic"}),e.jsx(T,{children:"French"}),e.jsx(T,{children:"Canonical"}),e.jsx(T,{children:"Domain"})]})}),e.jsx(ye,{children:t.terms.map(L=>e.jsxs(ee,{children:[e.jsx(A,{dir:"rtl",children:L.arabic_term}),e.jsx(A,{children:L.french_term}),e.jsx(A,{className:"font-mono text-xs",children:L.canonical_schema_value}),e.jsx(A,{children:L.domain})]},L.term_id))})]})]})]})]})}function bA({identity:t}){var $;const[n,a]=i.useState(null),[o,c]=i.useState([]),[u,h]=i.useState(null),[m,x]=i.useState(null),[v,N]=i.useState([]),[j,w]=i.useState(!0),[_,S]=i.useState(null),[y,g]=i.useState(null),[p,k]=i.useState(""),R=t.user_id,C=y===R?"error":_===R?"ok":"loading",E=i.useCallback(async()=>{const[O,L,z,Y,G]=await Promise.all([Rj(t),a1(t),l1(t),i1(t),Pj(t)]);return{h:O,changes:L.changes,completeness:z,validation:Y,snapshots:G.snapshots}},[t]),P=i.useCallback(O=>{a(O.h),c(O.changes),h(O.completeness),x(O.validation),N(O.snapshots),k(""),S(R),g(null)},[R]),F=i.useCallback(O=>{k(O instanceof Error?O.message:"Failed"),g(R),S(null)},[R]);i.useEffect(()=>{let O=!0;return E().then(L=>{O&&P(L)},L=>{O&&F(L)}),()=>{O=!1}},[E,P,F]);const I=i.useCallback(()=>(S(null),g(null),E().then(P,F)),[E,P,F]),M=[...o].sort((O,L)=>(j?-1:1)*O.approved_at.localeCompare(L.approved_at));return e.jsxs("div",{children:[e.jsx(Se,{title:"Graph Health & Schema",description:"Anchor-firm ecosystem graph: status, certified snapshots, schema versions and quality gates (Epic 17).",actions:e.jsx(K,{variant:"outline",size:"sm",onClick:()=>void I(),children:"Refresh"})}),C==="loading"&&e.jsx(H,{children:"Loading graph health… (the first visit builds and certifies the graph)"}),C==="error"&&e.jsx(H,{tone:"error",children:p}),C==="ok"&&n&&u&&m&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(150px,1fr))] gap-4 px-4",children:[e.jsx(ue,{label:"Status",value:e.jsx(V,{variant:n.db_status==="UP"?"success":"danger",children:n.db_status})}),e.jsx(ue,{label:"Nodes",value:n.node_count.toLocaleString("en-US")}),e.jsx(ue,{label:"Relationships",value:n.relationship_count.toLocaleString("en-US")}),e.jsx(ue,{label:"Schema",value:n.last_schema_version}),e.jsx(ue,{label:"Last ingestion",value:(($=n.last_ingestion_timestamp)==null?void 0:$.slice(0,16).replace("T"," "))??"—"}),e.jsx(ue,{label:"Query p99",value:n.query_latency_p99_ms===null?"—":`${n.query_latency_p99_ms.toFixed(1)} ms`,tone:(n.query_latency_p99_ms??0)<=200?"ok":"error"})]})}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Certified snapshots (",v.length,")"]}),v.length===0?e.jsx("div",{className:"px-4 text-sm text-muted-foreground",children:"No certified snapshot yet."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Snapshot"}),e.jsx(T,{children:"Cycle"}),e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Certified by"}),e.jsx(T,{children:"At"}),e.jsx(T,{className:"text-right",children:"Nodes / edges"})]})}),e.jsx(ye,{children:v.map((O,L)=>e.jsxs(ee,{children:[e.jsxs(A,{className:"font-mono text-xs",children:[O.snapshot_id," ",L===0&&e.jsx(V,{variant:"success",children:"current"})]}),e.jsx(A,{children:O.quarterly_cycle_label}),e.jsx(A,{children:O.certification_type}),e.jsx(A,{children:O.certified_by}),e.jsx(A,{className:"text-xs text-muted-foreground",children:O.certification_timestamp.slice(0,16).replace("T"," ")}),e.jsxs(A,{className:"text-right tabular-nums",children:[O.node_count," / ",O.relationship_count]})]},O.snapshot_id))})]})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("div",{className:"flex items-baseline justify-between px-4",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Schema changelog"}),e.jsxs(K,{variant:"link",size:"sm",onClick:()=>w(!j),children:["Sort: ",j?"newest first":"oldest first"]})]}),M.length===0?e.jsx("div",{className:"px-4 text-sm text-muted-foreground",children:"No schema versions."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"From"}),e.jsx(T,{children:"To"}),e.jsx(T,{children:"Changed fields"}),e.jsx(T,{children:"Rationale"}),e.jsx(T,{children:"Approved by"}),e.jsx(T,{children:"At"})]})}),e.jsx(ye,{children:M.map(O=>e.jsxs(ee,{children:[e.jsx(A,{children:O.version_from??"—"}),e.jsx(A,{children:O.version_to}),e.jsx(A,{children:O.changed_fields.join(", ")||"—"}),e.jsx(A,{children:O.rationale}),e.jsx(A,{children:O.approved_by}),e.jsx(A,{className:"text-xs text-muted-foreground",children:O.approved_at.slice(0,10)})]},O.version_to))})]})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Completeness ",e.jsx(V,{variant:u.pass?"success":"danger",children:u.pass?"PASS":"FAIL"})]}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Anchor firm"}),e.jsx(T,{className:"text-right",children:"Tier-1 suppliers"}),e.jsx(T,{className:"text-right",children:"Tier-2 suppliers"}),e.jsx(T,{className:"text-right",children:"Relationships"}),e.jsx(T,{children:"Result"})]})}),e.jsx(ye,{children:u.firms.map(O=>e.jsxs(ee,{children:[e.jsx(A,{children:O.firm_name}),e.jsxs(A,{className:"text-right tabular-nums",children:[O.first_tier_count," ",!O.first_tier_pass&&e.jsx(V,{variant:"danger",children:"below minimum"})]}),e.jsx(A,{className:"text-right tabular-nums",children:O.second_tier_count}),e.jsx(A,{className:"text-right tabular-nums",children:O.relationship_count}),e.jsx(A,{children:e.jsx(V,{variant:O.pass?"success":"danger",children:O.pass?"pass":"fail"})})]},O.anchor_firm_id))})]})]}),e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Validation ",e.jsx(V,{variant:m.pass?"success":"danger",children:m.pass?"PASS":"FAIL"})]}),e.jsxs("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-4 px-4",children:[e.jsx(ue,{label:"Anchor firms",value:m.firm_count}),e.jsx(ue,{label:"Input materials",value:m.input_material_count}),e.jsx(ue,{label:"Supplier countries",value:m.supplier_country_count}),e.jsx(ue,{label:"Input dependencies",value:m.requires_input_count}),e.jsx(ue,{label:"Mandatory fields filled",value:`${m.mandatory_non_null_pct}%`,tone:m.mandatory_non_null_pct===100?"ok":"error"}),e.jsx(ue,{label:"Commodity types",value:`${m.commodity_types_covered.length} covered${m.missing_commodity_types.length?`, missing ${m.missing_commodity_types.join(", ")}`:""}`,tone:m.missing_commodity_types.length?"error":"ok"})]})]})]})]})}const NA={PENDING:{cls:"bg-muted text-muted-foreground",icon:"○"},IN_PROGRESS:{cls:"bg-info/10 text-info",icon:"◐"},COMPLETE:{cls:"bg-success/10 text-success",icon:"●"},FAILED:{cls:"bg-destructive/10 text-destructive",icon:"✕"}},wA={SOURCE_DETECTION:"Source detection",EXTRACTION:"Extraction",CONFLICT_RESOLUTION:"Conflict resolution",GRAPH_WRITE:"Graph write",RECONCILIATION_REPORT:"Reconciliation report"},SA=(t,n,a)=>{if(!t)return"";const o=((n?Date.parse(n):a)-Date.parse(t))/1e3;return o<60?`${o.toFixed(1)} s`:`${Math.floor(o/60)} min ${Math.round(o%60)} s`};function bm({run:t,now:n}){const[a,o]=i.useState(()=>Date.now());i.useEffect(()=>{if(n!==void 0)return;const u=window.setInterval(()=>o(Date.now()),1e3);return()=>window.clearInterval(u)},[n]);const c=n??a;return e.jsx("ol",{className:"m-0 flex list-none flex-wrap gap-2 p-0",children:t.stages.map((u,h)=>{const m=NA[u.status];return e.jsxs("li",{title:u.error??void 0,className:`flex-1 basis-[150px] rounded-[10px] px-2.5 py-2 ${m.cls}`,children:[e.jsxs("div",{className:"text-[11px] opacity-80",children:[h+1,". ",wA[u.stage]??u.stage]}),e.jsxs("div",{className:"text-[13px] font-semibold",children:[m.icon," ",u.status.replace("_"," ")]}),e.jsx("div",{className:"text-[11px]",children:SA(u.started_at,u.ended_at,c)}),u.error&&e.jsx("div",{className:"mt-1 text-[11px]",children:u.error})]},u.stage)})})}const CA=Zm("relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current"}},defaultVariants:{variant:"default"}});function kA({className:t,variant:n,...a}){return e.jsx("div",{"data-slot":"alert",role:"alert",className:ft(CA({variant:n}),t),...a})}function EA({className:t,...n}){return e.jsx("div",{"data-slot":"alert-title",className:ft("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",t),...n})}function AA({className:t,...n}){return e.jsx("div",{"data-slot":"alert-description",className:ft("col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",t),...n})}const RA={SUCCESS:"success",PARTIAL:"warning",FAILED:"danger",RUNNING:"secondary"},PA=["ml_engineer","head_of_industrial_intelligence"];function TA({identity:t}){const[n,a]=i.useState([]),[o,c]=i.useState(null),[u,h]=i.useState([]),[m,x]=i.useState(null),[v,N]=i.useState("Q1-2026"),[j,w]=i.useState(""),[_,S]=i.useState(""),[y,g]=i.useState(null),[p,k]=i.useState(null),R=p===t?"error":y===t?"ok":"loading",C=i.useCallback(async()=>{const[L,z,Y]=await Promise.all([Tj(t),N1(t),_l(t)]);return{runs:L.runs,queue:z,firms:Y.firms}},[t]),E=i.useCallback(L=>{a(L.runs),c(L.queue),h(L.firms),g(t),k(null)},[t]),P=i.useCallback(L=>{w(L instanceof Error?L.message:"Failed"),k(t),g(null)},[t]);i.useEffect(()=>{let L=!0;return C().then(z=>{L&&E(z)},z=>{L&&P(z)}),()=>{L=!1}},[C,E,P]);const F=n.some(L=>L.status==="RUNNING");i.useEffect(()=>{const L=setInterval(()=>void C().then(E,P),F?2e3:6e4);return()=>clearInterval(L)},[C,E,P,F]);const I=i.useCallback(()=>C().then(E,P),[C,E,P]),M=async()=>{w(""),S("");try{const L=await w1(t,v);S(`Ingestion ${L.pipeline_run_id} started for ${L.quarterly_cycle_label}.`),await I()}catch(L){w(L instanceof Error?L.message:"Trigger failed")}},$=n[0],O=PA.includes(t.role);return e.jsxs("div",{children:[e.jsx(Se,{title:"Anchor-Firm Ingestion",description:"ONS surveys, public disclosures, AAPI filings and JO decrees → the anchor-firm graph (Epic 17).",actions:O&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{className:"w-28",value:v,onChange:L=>N(L.target.value),"aria-label":"Quarterly cycle"}),e.jsx(K,{size:"sm",disabled:F,onClick:()=>void M(),children:F?"Run in progress…":"Trigger ingestion"})]})}),_&&e.jsx(H,{children:_}),j&&R==="ok"&&e.jsx(H,{tone:"error",children:j}),R==="loading"&&e.jsx(H,{children:"Loading ingestion runs…"}),R==="error"&&e.jsx(H,{tone:"error",children:j}),R==="ok"&&e.jsxs(e.Fragment,{children:[(o==null?void 0:o.processing_unavailable)&&e.jsxs(kA,{variant:"destructive",className:"mt-4",children:[e.jsx(EA,{children:"Processing service unavailable."}),e.jsxs(AA,{children:[o.stale_queued," document(s) are waiting with no processor claiming them. Runs will finish PARTIAL; readers keep serving the last certified graph."]})]}),($==null?void 0:$.status)==="RUNNING"&&e.jsxs(B,{className:"mt-4 gap-3 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["In progress — ",$.pipeline_run_id]}),e.jsx("div",{className:"px-4",children:e.jsx(bm,{run:$})})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Document-processing queue ",o&&e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["· ",o.processing_mode==="AI_SERVICE"?"ai-service":"in-process fixture processors",o.pipeline_run_id?` · run ${o.pipeline_run_id}`:""]})]}),!o||Object.keys(o.counts).length===0?e.jsx("div",{className:"px-4 text-sm text-muted-foreground",children:"No documents queued yet."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Source type"}),e.jsx(T,{className:"text-right",children:"Queued"}),e.jsx(T,{className:"text-right",children:"Leased"}),e.jsx(T,{className:"text-right",children:"Retrying"}),e.jsx(T,{className:"text-right",children:"Dead"}),e.jsx(T,{className:"text-right",children:"Done"})]})}),e.jsx(ye,{children:Object.entries(o.counts).map(([L,z])=>e.jsxs(ee,{children:[e.jsx(A,{children:L}),e.jsx(A,{className:"text-right tabular-nums",children:z.queued}),e.jsx(A,{className:"text-right tabular-nums",children:z.leased}),e.jsx(A,{className:"text-right tabular-nums",children:z.failed?e.jsx(V,{variant:"warning",children:z.failed}):0}),e.jsx(A,{className:"text-right tabular-nums",children:z.dead?e.jsx(V,{variant:"danger",children:z.dead}):0}),e.jsx(A,{className:"text-right tabular-nums",children:z.done})]},L))})]})]}),e.jsx("section",{className:"mt-4 grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3",children:u.map(L=>{var z;return e.jsx(B,{className:`gap-0 border-l-4 py-4 ${L.data_freshness==="CURRENT"?"border-l-success":"border-l-warning"}`,children:e.jsxs("div",{className:"px-4",children:[e.jsx("div",{className:"font-bold",children:L.name_fr}),e.jsx("div",{dir:"rtl",className:"text-xs text-muted-foreground",children:L.name_ar}),e.jsx("div",{className:"mt-1.5 text-xs",children:L.sector}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["last ingested ",((z=L.last_ingested_at)==null?void 0:z.slice(0,16).replace("T"," "))??"—"]}),e.jsx("div",{className:"mt-1.5",children:e.jsx(V,{variant:L.data_freshness==="CURRENT"?"success":"warning",children:L.data_freshness})})]})},L.id)})}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Run history (",n.length,")"]}),n.length===0?e.jsx("div",{className:"px-4 text-sm text-muted-foreground",children:"No runs yet."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Started ↓"}),e.jsx(T,{children:"Run"}),e.jsx(T,{children:"Kind"}),e.jsx(T,{children:"Cycle"}),e.jsx(T,{className:"text-right",children:"Loaded"}),e.jsx(T,{className:"text-right",children:"Flagged"}),e.jsx(T,{children:"Status"})]})}),e.jsx(ye,{children:[...n].sort((L,z)=>z.started_at.localeCompare(L.started_at)).map(L=>{const z=Object.values(L.summary.flagged??{}).reduce((Y,G)=>Y+G,0);return e.jsxs(i.Fragment,{children:[e.jsxs(ee,{onClick:()=>x(m===L.pipeline_run_id?null:L.pipeline_run_id),className:"cursor-pointer",children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:L.started_at.slice(0,16).replace("T"," ")}),e.jsxs(A,{className:"font-mono text-xs",children:[L.pipeline_run_id,L.replay_of?" (replay)":""]}),e.jsx(A,{children:L.kind}),e.jsx(A,{children:L.quarterly_cycle_label}),e.jsx(A,{className:"text-right tabular-nums",children:L.summary.loaded??"—"}),e.jsx(A,{className:"text-right tabular-nums",children:z||"—"}),e.jsx(A,{children:e.jsx(V,{variant:RA[L.status],children:L.status})})]}),m===L.pipeline_run_id&&e.jsx(ee,{children:e.jsx(A,{colSpan:7,className:"whitespace-normal bg-muted",children:e.jsxs("div",{className:"px-4",children:[e.jsx(bm,{run:L}),e.jsxs("div",{className:"mt-2.5 flex flex-wrap gap-6 text-xs",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Per source"}),Object.entries(L.summary.source_breakdown??{}).map(([Y,G])=>e.jsxs("div",{children:[Y,": ",G]},Y))]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Flagged"}),Object.entries(L.summary.flagged??{}).map(([Y,G])=>e.jsxs("div",{children:[Y,": ",G]},Y))]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Rejected"}),Object.entries(L.summary.rejected??{}).map(([Y,G])=>e.jsxs("div",{children:[Y,": ",G]},Y))]}),L.summary.ocr_validation&&e.jsxs("div",{children:[e.jsx("strong",{children:"Arabic OCR gate"}),e.jsxs("div",{children:[L.summary.ocr_validation.pages," pages · CER ",L.summary.ocr_validation.aggregate_cer??"—"," (gate ",L.summary.ocr_validation.gate,")"]}),e.jsx(V,{variant:L.summary.ocr_validation.passed?"success":"danger",children:L.summary.ocr_validation.passed?"passed":"failed"})]})]}),(L.summary.document_failures??[]).length>0&&e.jsx("div",{className:"mt-2 text-xs text-destructive",children:(L.summary.document_failures??[]).map(Y=>e.jsxs("div",{children:[Y.document_id,": ",Y.error]},Y.document_id))})]})})})]},L.pipeline_run_id)})})]})]})]})]})}function LA({identity:t}){const[n,a]=i.useState([]),[o,c]=i.useState([]),[u,h]=i.useState([]),[m,x]=i.useState("kind"),[v,N]=i.useState({anchor_firm_id:"",field_name:"",from:""}),[j,w]=i.useState(null),[_,S]=i.useState(null),[y,g]=i.useState(""),[p,k]=i.useState(null),R=`${t.user_id}|${v.anchor_firm_id}|${v.field_name}|${v.from}`,C=_===R?"error":j===R?"ok":"loading",E=i.useCallback(async()=>{const[z,Y,G]=await Promise.all([Lj(t,{status:"OPEN"}),S1(t,{anchor_firm_id:v.anchor_firm_id||void 0,field_name:v.field_name||void 0,from:v.from||void 0}),_l(t)]);return{items:z.items,conflicts:Y.conflicts,firms:G.firms}},[t,v]),P=i.useCallback(z=>{a(z.items),c(z.conflicts),h(z.firms),w(R),S(null)},[R]),F=i.useCallback(z=>{g(z instanceof Error?z.message:"Failed"),S(R),w(null)},[R]);i.useEffect(()=>{let z=!0;return E().then(Y=>{z&&P(Y)},Y=>{z&&F(Y)}),()=>{z=!1}},[E,P,F]);const I=i.useCallback(()=>E().then(P,F),[E,P,F]),M=z=>{var Y;return((Y=u.find(G=>G.id===z))==null?void 0:Y.firm_name)??(z||"—")},$=async(z,Y)=>{var U;const G=Y==="ASSIGN"?(U=window.prompt("Assign to (user id)"))==null?void 0:U.trim():void 0;if(!(Y==="ASSIGN"&&!G)){k(z.item_id),g("");try{await C1(t,z.item_id,{decision:Y,...Y==="APPROVE"&&z.kind==="UNVERIFIED"?{confidence_level:"MEDIUM"}:{},...G?{assign_to:G}:{}}),await I()}catch(ae){g(ae instanceof Error?ae.message:"Update failed")}finally{k(null)}}},O=[...n].sort((z,Y)=>m==="kind"?z.kind.localeCompare(Y.kind)||z.recorded_at.localeCompare(Y.recorded_at):m==="firm"?M(z.firm_id).localeCompare(M(Y.firm_id)):Y.recorded_at.localeCompare(z.recorded_at)),L=t.role==="ml_engineer"||t.role==="subscriber";return e.jsxs("div",{children:[e.jsx(Se,{title:"Graph Review Queue",description:"Everything the pipeline would not write on its own — approve, reject or assign. Certification waits until this is empty for the run."}),y&&C==="ok"&&e.jsx(H,{tone:"error",children:y}),C==="loading"&&e.jsx(H,{children:"Loading review items…"}),C==="error"&&e.jsx(H,{tone:"error",children:y}),C==="ok"&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2 px-4",children:[e.jsxs("h2",{className:"text-base font-semibold",children:["Open items (",n.length,")"]}),e.jsxs("label",{className:"text-sm",children:["Sort by ",e.jsxs(Ie,{value:m,onChange:z=>x(z.target.value),"aria-label":"Sort by",children:[e.jsx("option",{value:"kind",children:"reason"}),e.jsx("option",{value:"firm",children:"firm"}),e.jsx("option",{value:"recorded_at",children:"newest"})]})]})]}),O.length===0?e.jsx("div",{className:"px-4 text-success",children:"✓ Queue is empty."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Reason"}),e.jsx(T,{children:"Detail"}),e.jsx(T,{children:"Firm"}),e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Document"}),e.jsx(T,{})]})}),e.jsx(ye,{children:O.map(z=>{var Y;return e.jsxs(ee,{className:p===z.item_id?"opacity-50":void 0,children:[e.jsxs(A,{children:[e.jsx(V,{variant:z.kind==="UNVERIFIED"?"warning":"secondary",children:z.kind}),z.assigned_to&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["assigned to ",z.assigned_to]})]}),e.jsxs(A,{children:[z.reason,(Y=z.fields)!=null&&Y.length?e.jsx("div",{className:"text-xs text-muted-foreground",children:z.fields.join(", ")}):null]}),e.jsx(A,{children:M(z.firm_id)}),e.jsx(A,{children:z.hs6_code??"—"}),e.jsx(A,{className:"font-mono text-xs",children:z.source_document_id??"—"}),e.jsx(A,{children:!L&&e.jsxs(e.Fragment,{children:[e.jsx(K,{size:"xs",disabled:p!==null,onClick:()=>void $(z,"APPROVE"),children:"Approve"})," ",e.jsx(K,{size:"xs",variant:"destructive",disabled:p!==null,onClick:()=>void $(z,"REJECT"),children:"Reject"})," ",e.jsx(K,{size:"xs",variant:"outline",disabled:p!==null,onClick:()=>void $(z,"ASSIGN"),children:"Assign"})]})})]},z.item_id)})})]})]}),e.jsxs(B,{className:"mt-4 gap-3 overflow-hidden py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Conflict-resolution log (",o.length,")"]}),e.jsxs("div",{className:"mb-2.5 flex flex-wrap gap-2 px-4",children:[e.jsxs(Ie,{value:v.anchor_firm_id,onChange:z=>N({...v,anchor_firm_id:z.target.value}),"aria-label":"Firm",children:[e.jsx("option",{value:"",children:"All firms"}),u.map(z=>e.jsx("option",{value:z.id,children:z.firm_name},z.id))]}),e.jsx(me,{className:"w-44",placeholder:"field name",value:v.field_name,onChange:z=>N({...v,field_name:z.target.value})}),e.jsx(me,{className:"w-40",type:"date",value:v.from,onChange:z=>N({...v,from:z.target.value}),"aria-label":"From date"})]}),o.length===0?e.jsx("div",{className:"px-4 text-sm text-muted-foreground",children:"No conflicts match."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Firm"}),e.jsx(T,{children:"Field"}),e.jsx(T,{children:"Winner"}),e.jsx(T,{children:"Loser"}),e.jsx(T,{children:"Rule"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"At"})]})}),e.jsx(ye,{children:o.map(z=>e.jsxs(ee,{children:[e.jsx(A,{children:M(z.anchor_firm_id)}),e.jsx(A,{children:z.field_name}),e.jsxs(A,{children:[z.winning_source,": ",e.jsx("strong",{children:String(z.winning_value)})]}),e.jsxs(A,{children:[z.losing_source,": ",String(z.losing_value)]}),e.jsx(A,{children:z.precedence_rule}),e.jsx(A,{children:e.jsx(V,{variant:z.resolution_status==="PENDING"?"warning":"secondary",children:z.resolution_status})}),e.jsx(A,{className:"text-xs text-muted-foreground",children:z.resolution_timestamp.slice(0,16).replace("T"," ")})]},z.conflict_id))})]})]})]})]})}const FA=["analyst","senior_analyst","chief_economist","head_of_industrial_intelligence"];function DA({identity:t}){const[n,a]=i.useState([]),[o,c]=i.useState(""),[u,h]=i.useState(""),[m,x]=i.useState(null),[v,N]=i.useState([]),[j,w]=i.useState(0),[_,S]=i.useState(""),[y,g]=i.useState(null),[p,k]=i.useState(null),[R,C]=i.useState(!1),E=`${o}|${u}`,P=R||p===E?"error":y===E?"ok":"loading";i.useEffect(()=>{_l(t).then(L=>{a(L.firms),c(z=>{var Y;return z||((Y=L.firms[0])==null?void 0:Y.id)||""})}).catch(L=>{S(L instanceof Error?L.message:"Failed"),C(!0)})},[t]);const F=i.useCallback(async()=>{if(!o)return null;const[L,z]=await Promise.all([g1(t,o),p1(t,o,{tier_level:u?Number(u):void 0,limit:200})]);return{c:L,s:z.suppliers,total:z.total}},[t,o,u]),I=i.useCallback(L=>{x(L.c),N(L.s),w(L.total),S(""),g(E),k(null)},[E]),M=i.useCallback(L=>{S(L instanceof Error?L.message:"Failed"),k(E),g(null)},[E]),$=i.useCallback(()=>(g(null),k(null),S(""),F().then(L=>{L&&I(L)},M)),[F,I,M]);i.useEffect(()=>{let L=!0;return F().then(z=>{L&&z&&I(z)},z=>{L&&M(z)}),()=>{L=!1}},[F,I,M]);const O=t.tier==="3";return e.jsxs("div",{children:[e.jsx(Se,{title:"Supplier Linkage",description:"First- and second-tier suppliers of each anchor firm, with import exposure and DAPS (Epic 17).",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ie,{value:o,onChange:L=>c(L.target.value),"aria-label":"Anchor firm",children:n.map(L=>e.jsx("option",{value:L.id,children:L.firm_name},L.id))}),e.jsxs(Ie,{value:u,onChange:L=>h(L.target.value),"aria-label":"Tier",children:[e.jsx("option",{value:"",children:"All tiers"}),e.jsx("option",{value:"1",children:"Tier 1"}),e.jsx("option",{value:"2",children:"Tier 2"})]})]})}),P==="loading"&&e.jsx(H,{children:"Loading suppliers…"}),P==="error"&&e.jsx(H,{tone:"error",children:_}),P==="ok"&&m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(ze,{label:"Suppliers",value:String(m.total_suppliers)}),e.jsx(ze,{label:"Tier 1",value:String(m.first_tier_count)}),e.jsx(ze,{label:"Tier 2",value:String(m.second_tier_count)}),e.jsx(ze,{label:"Imported inputs",value:String(m.imported_inputs_count),tone:m.imported_inputs_count?"warn":void 0}),e.jsx(ze,{label:"Unverified",value:String(m.unverified_count),tone:m.unverified_count?"warn":"ok"})]}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:["Suppliers (",j,")"]}),v.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No suppliers for this filter."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Supplier"}),e.jsx(T,{children:"Tier"}),e.jsx(T,{children:"Input"}),e.jsx(T,{children:"Origin"}),e.jsx(T,{className:"text-right",children:"Volume (t)"}),e.jsx(T,{className:"text-right",children:"Import value"}),e.jsx(T,{className:"text-right",children:"DAPS"}),e.jsx(T,{children:"Confidence"}),e.jsx(T,{children:"Source"})]})}),e.jsx(ye,{children:v.map(L=>{var z;return e.jsxs(ee,{className:L.status==="ACTIVE"?void 0:"opacity-50",children:[e.jsxs(A,{children:[L.supplier_name,L.inferred&&e.jsx("div",{children:e.jsx(V,{variant:"secondary",children:"Inferred from trade data"})}),L.anchor_count>1&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["serves ",L.anchor_count," anchors · total ",e.jsx(da,{value:L.total_supply_volume_usd,locked:O,children:Xe(L.total_supply_volume_usd)})]})]}),e.jsx(A,{children:L.tier_level}),e.jsxs(A,{children:[L.input_material_name,e.jsx("div",{className:"text-xs text-muted-foreground",children:L.hs6_code??"HS6 unresolved"})]}),e.jsxs(A,{children:[L.supply_origin==="IMPORTED"?e.jsxs(V,{variant:"warning",children:["Imported · ",L.country_of_origin]}):e.jsx(V,{variant:"success",children:"Domestic"}),L.import_restriction_flag&&e.jsx("div",{children:e.jsx(V,{variant:"danger",children:"restricted"})})]}),e.jsx(A,{className:"text-right tabular-nums",children:((z=L.annual_volume_estimate_tonnes)==null?void 0:z.toLocaleString("en-US"))??"—"}),e.jsx(A,{className:"text-right tabular-nums",children:e.jsx(da,{value:L.import_value_usd,locked:O,children:Xe(L.import_value_usd)})}),e.jsx(A,{className:"text-right tabular-nums",children:e.jsx(da,{value:L.DAPS_duty_rate,locked:O,children:L.DAPS_duty_rate===null?"—":`${L.DAPS_duty_rate}%`})}),e.jsx(A,{children:e.jsx(V,{variant:L.confidence_level==="HIGH"?"success":L.confidence_level==="MEDIUM"?"secondary":"warning",children:L.confidence_level==="LOW"?"UNVERIFIED":L.confidence_level})}),e.jsx(A,{children:e.jsx(Ec,{citation:L.source_citation})})]},`${L.supplier_id}-${L.input_material_name}-${L.tier_level}`)})})]})]})})]}),FA.includes(t.role)&&e.jsx($A,{identity:t,onDone:()=>void $()})]})}function $A({identity:t,onDone:n}){const[a,o]=i.useState(null),[c,u]=i.useState(""),[h,m]=i.useState(null),[x,v]=i.useState(""),[N,j]=i.useState(!1);i.useEffect(()=>{v1(t).then(o).catch(()=>o(null))},[t]);const w=a?["row_type",...new Set(Object.values(a.row_types).flat()),...a.citation_fields]:[],_=()=>{const y=new Blob([`${w.join(",")} `],{type:"text/csv"}),g=document.createElement("a");g.href=URL.createObjectURL(y),g.download=`anchor-graph-upload-v${(a==null?void 0:a.template_version)??"1"}.csv`,g.click(),URL.revokeObjectURL(g.href)},S=async()=>{if(a){j(!0),v(""),m(null);try{m(await j1(t,{template_version:a.template_version,csv:c})),n()}catch(y){v(y instanceof Error?y.message:"Upload failed")}finally{j(!1)}}};return e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:["Analyst bulk upload ",a&&e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["· template v",a.template_version," · max ",a.max_rows," rows"]})]}),a?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mb-2 text-sm text-muted-foreground",children:["Row types: ",Object.entries(a.row_types).map(([y,g])=>`${y} (${g.join(", ")})`).join(" · "),". Every row needs a citation (",a.citation_fields.join(", "),"); complete citations load as HIGH, others MEDIUM."]}),e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(K,{variant:"outline",size:"sm",onClick:_,children:"Download template"}),e.jsx(K,{asChild:!0,variant:"outline",size:"sm",children:e.jsxs("label",{children:["Choose CSV",e.jsx("input",{type:"file",accept:".csv,text/csv",className:"hidden",onChange:y=>{var p;const g=(p=y.target.files)==null?void 0:p[0];g&&g.text().then(u)}})]})}),e.jsx(K,{size:"sm",disabled:N||!c.trim(),onClick:()=>void S(),children:N?"Uploading…":"Upload"})]}),e.jsx(fa,{value:c,onChange:y=>u(y.target.value),placeholder:w.join(","),rows:5,className:"font-mono text-xs","aria-label":"CSV rows"}),x&&e.jsx("div",{className:"mt-2 text-destructive",children:x}),h&&e.jsxs("div",{className:"mt-2.5 text-sm",children:[e.jsxs(V,{variant:"success",children:[h.accepted," accepted"]})," ",e.jsxs(V,{variant:h.rejected.length?"danger":"secondary",children:[h.rejected.length," rejected"]}),h.pipeline_run&&e.jsxs("span",{className:"text-muted-foreground",children:[" · incremental run ",h.pipeline_run.pipeline_run_id]}),h.rejected.length>0&&e.jsx("ul",{className:"mt-2 pl-[18px] text-destructive",children:h.rejected.map(y=>e.jsxs("li",{children:["row ",y.row,": ",y.reason]},y.row))})]})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Template unavailable."})]})})}const qu=["LT_2M","2M_10M","10M_50M","50M_200M","GT_200M"];function IA({identity:t}){const[n,a]=i.useState([]),[o,c]=i.useState("ALL"),[u,h]=i.useState(""),[m,x]=i.useState(""),[v,N]=i.useState(""),[j,w]=i.useState("severity"),[_,S]=i.useState([]),[y,g]=i.useState(null),[p,k]=i.useState(null),[R,C]=i.useState(null),[E,P]=i.useState(""),F=`${t.user_id}|${o}|${u}|${m}|${v}|${n.length}`,I=R===F?"error":p===F?"ok":"loading";i.useEffect(()=>{_l(t).then(U=>a(U.firms)).catch(()=>a([]))},[t]);const M=i.useCallback(async()=>{const U={sector:u||void 0,capex_bracket:m||void 0,confidence_level:v||void 0};if(o==="ALL"){if(!n.length)return null;const W=await _1(t,n.map(ne=>ne.id),U),se=new Map;for(const ne of W.gaps){const q=se.get(ne.input_material_id);if(!q)se.set(ne.input_material_id,{...ne,anchors:[ne.anchor_firm_id]});else{const J=[...new Set([...q.anchors,ne.anchor_firm_id])];se.set(ne.input_material_id,ne.gap_severity_score>q.gap_severity_score?{...ne,anchors:J}:{...q,anchors:J})}}return{rows:[...se.values()],meta:W.meta}}const ae=await y1(t,o,{...U,limit:100});return{rows:ae.gaps.map(W=>({...W,anchors:[W.anchor_firm_id]})),meta:ae.meta}},[t,o,n,u,m,v]),$=i.useCallback(U=>{S(U.rows),g(U.meta),k(F),C(null)},[F]),O=i.useCallback(U=>{P(U instanceof Error?U.message:"Failed"),C(F),k(null)},[F]);i.useEffect(()=>{let U=!0;return M().then(ae=>{U&&ae&&$(ae)},ae=>{U&&O(ae)}),()=>{U=!1}},[M,$,O]);const L=U=>{var ae;return((ae=n.find(W=>W.id===U))==null?void 0:ae.firm_name)??U},z=[..._].sort((U,ae)=>j==="severity"?ae.gap_severity_score-U.gap_severity_score:j==="anchor"?L(U.anchors[0]).localeCompare(L(ae.anchors[0]))||ae.gap_severity_score-U.gap_severity_score:qu.indexOf(U.capex_bracket_estimate??"GT_200M")-qu.indexOf(ae.capex_bracket_estimate??"GT_200M")),Y=t.tier==="3",G=[...new Set(n.map(U=>U.sector))];return e.jsxs("div",{children:[e.jsx(Se,{title:"Input Gap Explorer",description:"Inputs the anchor firms import with few or no domestic suppliers — ranked import-substitution opportunities."}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 px-4",children:[e.jsxs(Ie,{value:o,onChange:U=>c(U.target.value),"aria-label":"Anchor firm",children:[e.jsx("option",{value:"ALL",children:"All anchors (batch)"}),n.map(U=>e.jsx("option",{value:U.id,children:U.firm_name},U.id))]}),e.jsxs(Ie,{value:u,onChange:U=>h(U.target.value),"aria-label":"Sector",children:[e.jsx("option",{value:"",children:"Any sector"}),G.map(U=>e.jsx("option",{value:U,children:U},U))]}),e.jsxs(Ie,{value:m,onChange:U=>x(U.target.value),"aria-label":"CAPEX bracket",children:[e.jsx("option",{value:"",children:"Any CAPEX"}),qu.map(U=>e.jsx("option",{value:U,children:U},U))]}),e.jsxs(Ie,{value:v,onChange:U=>N(U.target.value),"aria-label":"Confidence",children:[e.jsx("option",{value:"",children:"Any confidence"}),e.jsx("option",{children:"HIGH"}),e.jsx("option",{children:"MEDIUM"}),e.jsx("option",{children:"LOW"})]}),e.jsxs("label",{className:"ml-auto text-sm",children:["Sort ",e.jsxs(Ie,{value:j,onChange:U=>w(U.target.value),"aria-label":"Sort",children:[e.jsx("option",{value:"severity",children:"severity"}),e.jsx("option",{value:"anchor",children:"anchor"}),e.jsx("option",{value:"capex",children:"CAPEX"})]})]})]})}),(y==null?void 0:y.data_refresh_in_progress)&&e.jsx(H,{children:"A quarterly refresh is in progress — showing the last certified graph."}),(y==null?void 0:y.cached_from)&&e.jsxs(H,{children:["Data temporarily unavailable — showing the last certified snapshot from ",y.cached_from.slice(0,16).replace("T"," "),"."]}),(y==null?void 0:y.data_staleness_warning)&&e.jsxs(H,{children:[y.data_staleness_warning.stale_data_warning?"⚠ STALE_DATA_WARNING — ":"","This anchor's latest survey data is from ",y.data_staleness_warning.stale_since??"an earlier period",y.data_staleness_warning.quarters_behind!==null?` (${y.data_staleness_warning.quarters_behind} quarter(s) behind)`:"","."]}),I==="loading"&&e.jsx(H,{children:"Loading input gaps…"}),I==="error"&&e.jsx(H,{tone:"error",children:E}),I==="ok"&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[z.length," gap(s) ",(y==null?void 0:y.query_ms)!==void 0&&e.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:["· ",y.query_ms.toFixed(1)," ms"]})]}),Y&&e.jsxs("p",{className:"mb-2 text-xs text-muted-foreground",children:["🔒 ",xl]}),z.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No gaps match these filters."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Input"}),e.jsx(T,{children:"Anchor(s)"}),e.jsx(T,{children:"Severity"}),e.jsx(T,{children:"Local suppliers"}),e.jsx(T,{className:"text-right",children:"Import value"}),e.jsx(T,{className:"text-right",children:"Import share"}),e.jsx(T,{className:"text-right",children:"DAPS"}),e.jsx(T,{children:"CAPEX"}),e.jsx(T,{children:"Confidence"})]})}),e.jsx(ye,{children:z.map(U=>e.jsxs(ee,{children:[e.jsxs(A,{children:[e.jsx("div",{className:"font-semibold",children:U.input_material_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[U.current_hs6_code??"HS6 unresolved"," · ",U.commodity_type]}),U.code_reclassification_note&&e.jsx("div",{className:"text-xs text-warning",children:U.code_reclassification_note}),U.restricted_supply_chain&&e.jsx(V,{variant:"danger",children:"restricted supply"})]}),e.jsx(A,{children:U.anchors.map(L).join(", ")}),e.jsxs(A,{children:[e.jsx(V,{variant:U.gap_severity_score>=80?"danger":U.gap_severity_score>=50?"warning":"secondary",children:U.gap_severity_score.toFixed(0)}),U.gap_label==="CRITICAL_GAP"&&e.jsx("div",{className:"text-xs font-bold text-destructive",children:"CRITICAL_GAP"})]}),e.jsx(A,{children:e.jsx("span",{className:U.current_local_supplier_count===0?"font-bold text-destructive":void 0,children:U.current_local_supplier_count})}),e.jsx(A,{className:"text-right tabular-nums",children:e.jsx(da,{value:U.estimated_annual_import_value_usd,locked:Y,children:Xe(U.estimated_annual_import_value_usd)})}),e.jsxs(A,{className:"text-right tabular-nums",children:[(U.import_share*100).toFixed(0),"%"]}),e.jsx(A,{title:U.daps_duty_source_citation??void 0,className:"text-right tabular-nums",children:e.jsxs(da,{value:U.applicable_daps_duty_rate_pct,locked:Y,children:[U.applicable_daps_duty_rate_pct===null?"—":`${U.applicable_daps_duty_rate_pct}%`,U.daps_high_protection_flag&&" 🛡️"]})}),e.jsx(A,{children:U.capex_bracket_estimate??"—"}),e.jsx(A,{children:e.jsx(V,{variant:U.confidence_level==="HIGH"?"success":U.confidence_level==="LOW"?"warning":"secondary",children:U.confidence_level})})]},`${U.input_material_id}-${U.anchors.join()}`))})]})]})})]})}const Nm=(t,n)=>t.name.localeCompare(n.name)||t.id.localeCompare(n.id);function Qu(t,n){return t.tier===0?24:!t.volume||n<=0?6:6+12*Math.sqrt(t.volume/n)}function MA(t,n=640){const a=n/2,o=n/2,c=n*.25,u=n*.42,h=Math.max(0,...t.nodes.map(p=>p.volume??0)),m=t.nodes.find(p=>p.tier===0),x=t.nodes.filter(p=>p.tier===1).sort(Nm),v=t.nodes.filter(p=>p.tier===2).sort(Nm),N=new Map;m&&N.set(m.id,{...m,x:a,y:o,r:Qu(m,h)});const j=new Map;x.forEach((p,k)=>{const R=2*Math.PI*k/Math.max(1,x.length)-Math.PI/2;j.set(p.id,R),N.set(p.id,{...p,x:a+c*Math.cos(R),y:o+c*Math.sin(R),r:Qu(p,h)})});const w=new Map;for(const p of t.edges)j.has(p.to)&&!w.has(p.from)&&w.set(p.from,p.to);const _=new Map;for(const p of v){const k=w.get(p.id)??"";_.set(k,[..._.get(k)??[],p])}const S=2*Math.PI/Math.max(1,x.length);let y=0;for(const[p,k]of _)k.forEach((R,C)=>{const E=j.get(p),P=E===void 0?2*Math.PI*y++/Math.max(1,v.length)-Math.PI/2:E+(k.length===1?0:(C/(k.length-1)-.5)*S*.8);N.set(R.id,{...R,x:a+u*Math.cos(P),y:o+u*Math.sin(P),r:Qu(R,h)})});const g=t.edges.filter(p=>N.has(p.from)&&N.has(p.to)).map(p=>{const k=N.get(p.from),R=N.get(p.to);return{...p,x1:k.x,y1:k.y,x2:R.x,y2:R.y}});return{width:n,height:n,nodes:[...N.values()],edges:g}}function OA(t){return t.tier===0?"#111":t.status!=="ACTIVE"?"#b8bec6":t.supply_origin==="DOMESTIC"?"#1e7e34":t.supply_origin==="IMPORTED"?"#d98a00":"#9aa1a9"}function zA(t,n=5){return t.nodes.filter(a=>a.tier>0).sort((a,o)=>(o.volume??0)-(a.volume??0)||Nm(a,o)).slice(0,n)}function UA({eco:t,selectedId:n,onSelect:a,isDimmed:o,size:c=640}){const u=MA(t,c),h=new Map(t.delta_flags.map(v=>[v.entity_id,v])),m=new Map(u.nodes.map(v=>[v.id,v])),x=c/2;return e.jsxs("svg",{viewBox:`0 0 ${u.width} ${u.height}`,role:"img","aria-label":`Supplier ecosystem of ${t.anchor.name}`,style:{width:"100%",maxWidth:c,height:"auto",background:"#fff"},children:[e.jsx("circle",{cx:x,cy:x,r:c*.25,fill:"none",stroke:"#eef1f4",strokeDasharray:"4 4"}),e.jsx("circle",{cx:x,cy:x,r:c*.42,fill:"none",stroke:"#eef1f4",strokeDasharray:"4 4"}),e.jsx("text",{x,y:x-c*.25-6,textAnchor:"middle",fontSize:10,fill:"#aaa",children:"Tier 1"}),e.jsx("text",{x,y:x-c*.42-6,textAnchor:"middle",fontSize:10,fill:"#aaa",children:"Tier 2"}),u.edges.map(v=>{const N=o(m.get(v.from))||o(m.get(v.to));return e.jsx("line",{x1:v.x1,y1:v.y1,x2:v.x2,y2:v.y2,stroke:v.cycle_detected?"#b3261e":v.confidence_level==="LOW"?"#d0d4d9":"#9aa1a9",strokeWidth:v.cycle_detected?2:1,strokeDasharray:v.confidence_level==="MEDIUM"?"5 3":void 0,opacity:N?.15:.8,children:v.cycle_detected&&e.jsx("title",{children:"Circular relationship detected"})},v.id)}),u.nodes.map(v=>{const N=o(v),j=v.confidence_level==="LOW",w=h.get(v.id);return e.jsxs("g",{transform:`translate(${v.x},${v.y})`,onClick:()=>a(v),style:{cursor:"pointer"},opacity:N?.2:j?.55:1,children:[e.jsx("title",{children:`${v.name}${v.volume?` · ${v.volume.toLocaleString("en-US")} t`:""}${w?` · Updated: severity ${w.previous_gap_severity??"—"} → ${w.current_gap_severity??"—"}`:""}`}),e.jsx("circle",{r:v.r,fill:OA(v),stroke:n===v.id?"#1a56db":"#fff",strokeWidth:n===v.id?3:1.5}),j&&e.jsx("text",{y:4,textAnchor:"middle",fontSize:10,fill:"#fff",children:"⚠"}),w&&e.jsx("circle",{cx:v.r*.8,cy:-v.r*.8,r:4,fill:"#1a56db"}),v.tier===0&&e.jsx("text",{y:v.r+14,textAnchor:"middle",fontSize:12,fontWeight:700,children:v.name})]},v.id)})]})}const Yj="graph.ecosystem.filters",BA=()=>{try{return{origin:"",confidence:"",tier:"",...JSON.parse(sessionStorage.getItem(Yj)??"{}")}}catch{return{origin:"",confidence:"",tier:""}}};function HA(){const t="(max-width: 375px)",[n,a]=i.useState(()=>typeof window<"u"&&window.matchMedia(t).matches);return i.useEffect(()=>{const o=window.matchMedia(t),c=()=>a(o.matches);return o.addEventListener("change",c),()=>o.removeEventListener("change",c)},[]),n}function VA({identity:t,onOpenCard:n}){const[a,o]=i.useState([]),[c,u]=i.useState(""),[h,m]=i.useState(""),[x,v]=i.useState(BA),[N,j]=i.useState(""),w=HA(),[_,S]=i.useState(!w);i.useEffect(()=>{_l(t).then(p=>{o(p.firms),u(k=>{var R;return k||((R=p.firms[0])==null?void 0:R.id)||""})}).catch(p=>j(p instanceof Error?p.message:"Failed"))},[t]),i.useEffect(()=>{try{sessionStorage.setItem(Yj,JSON.stringify(x))}catch{}},[x]);const y=p=>p.tier!==0&&(x.origin!==""&&p.supply_origin!==x.origin||x.confidence!==""&&p.confidence_level!==x.confidence||x.tier!==""&&String(p.tier)!==x.tier),g=t.tier==="1";return e.jsxs("div",{children:[e.jsx(Se,{title:"Supplier Ecosystem",description:"Each anchor firm with its first- and second-tier suppliers (Epic 17).",actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Ie,{value:c,onChange:p=>u(p.target.value),"aria-label":"Anchor firm",children:a.map(p=>e.jsx("option",{value:p.id,children:p.firm_name},p.id))}),g&&e.jsxs(Ie,{value:h,onChange:p=>m(p.target.value),"aria-label":"Compare with",children:[e.jsx("option",{value:"",children:"Compare with…"}),a.filter(p=>p.id!==c).map(p=>e.jsx("option",{value:p.id,children:p.firm_name},p.id))]})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 px-4 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Highlight:"}),e.jsxs(Ie,{value:x.origin,onChange:p=>v({...x,origin:p.target.value}),"aria-label":"Origin",children:[e.jsx("option",{value:"",children:"any origin"}),e.jsx("option",{value:"DOMESTIC",children:"domestic"}),e.jsx("option",{value:"IMPORTED",children:"imported"})]}),e.jsxs(Ie,{value:x.confidence,onChange:p=>v({...x,confidence:p.target.value}),"aria-label":"Confidence",children:[e.jsx("option",{value:"",children:"any confidence"}),e.jsx("option",{children:"HIGH"}),e.jsx("option",{children:"MEDIUM"}),e.jsx("option",{children:"LOW"})]}),e.jsxs(Ie,{value:x.tier,onChange:p=>v({...x,tier:p.target.value}),"aria-label":"Tier",children:[e.jsx("option",{value:"",children:"any tier"}),e.jsx("option",{value:"1",children:"tier 1"}),e.jsx("option",{value:"2",children:"tier 2"})]}),w&&e.jsx(K,{variant:"ghost",size:"sm",onClick:()=>S(!_),children:_?"Show list":"View full graph"})]})}),N&&e.jsx(H,{tone:"error",children:N}),e.jsxs("div",{className:h&&g?"grid grid-cols-[repeat(auto-fit,minmax(420px,1fr))] gap-4":"grid grid-cols-1 gap-4",children:[c&&e.jsx(Hp,{identity:t,firmId:c,isDimmed:y,showGraph:_,onOpenCard:n}),h&&g&&e.jsx(Hp,{identity:t,firmId:h,isDimmed:y,showGraph:_,onOpenCard:n})]})]})}function Hp({identity:t,firmId:n,isDimmed:a,showGraph:o,onOpenCard:c}){const[u,h]=i.useState(null),[m,x]=i.useState(null),[v,N]=i.useState(""),[j,w]=i.useState(!1),[_,S]=i.useState(null),[y,g]=i.useState(null),p=y===n?"error":_===n?"ok":"loading",k=i.useCallback(async()=>tp(t,n),[t,n]),R=i.useCallback(M=>{h(M),x(null),N(""),S(n),g(null)},[n]),C=i.useCallback(M=>{N(M instanceof Error?M.message:"Failed"),g(n),S(null)},[n]);i.useEffect(()=>{let M=!0;return k().then($=>{M&&R($)},$=>{M&&C($)}),()=>{M=!1}},[k,R,C]);const E=async()=>{if(u!=null&&u.next_cursor){w(!0);try{const M=await tp(t,n,{cursor:u.next_cursor}),$=new Set(u.nodes.map(L=>L.id)),O=new Set(u.edges.map(L=>L.id));h({...M,nodes:[...u.nodes,...M.nodes.filter(L=>!$.has(L.id))],edges:[...u.edges,...M.edges.filter(L=>!O.has(L.id))]})}catch(M){N(M instanceof Error?M.message:"Failed")}finally{w(!1)}}},P=async()=>{try{const{svg:M}=await b1(t,n),$=document.createElement("a");$.href=URL.createObjectURL(new Blob([M],{type:"image/svg+xml"})),$.download=`ecosystem-${(u==null?void 0:u.anchor.name)??n}.svg`,$.click(),URL.revokeObjectURL($.href)}catch(M){N(M instanceof Error?M.message:"Export failed")}};if(p==="loading")return e.jsx(H,{children:"Loading ecosystem…"});if(p==="error"||!u)return e.jsx(H,{tone:"error",children:v});const F=u.nodes.filter(M=>M.tier>0),I=F.filter(M=>M.supply_origin==="IMPORTED").length;return e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:u.anchor.name}),e.jsxs(K,{variant:"outline",size:"sm",onClick:()=>void P(),children:["Export SVG",u.tier_policy.watermarkExport?" (watermarked)":""]})]}),u.meta.cached_from&&e.jsxs("div",{role:"status",className:"mb-2 rounded-lg bg-warning/10 px-2.5 py-1.5 text-sm",children:["Data temporarily unavailable — showing last cached view from ",u.meta.cached_from.slice(0,16).replace("T"," ")]}),u.meta.data_refresh_in_progress&&e.jsx("div",{className:"mb-2 text-xs text-muted-foreground",children:"Refresh in progress — showing the last certified graph."}),e.jsxs("div",{className:"mb-3 grid grid-cols-[repeat(auto-fit,minmax(110px,1fr))] gap-3",children:[e.jsx(ue,{label:"Suppliers",value:`${F.length} of ${u.total_suppliers}`}),e.jsx(ue,{label:"Imported",value:I}),e.jsx(ue,{label:"Domestic",value:F.length-I}),e.jsx(ue,{label:"Updated since last refresh",value:u.delta_flags.length})]}),e.jsxs("div",{className:"flex flex-wrap items-start gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-[2_1_360px]",children:[o?e.jsx(UA,{eco:u,selectedId:(m==null?void 0:m.id)??null,onSelect:x,isDimmed:a}):e.jsx("ol",{className:"m-0 pl-[18px]",children:zA(u).map(M=>{var $;return e.jsxs("li",{className:"mb-1.5 cursor-pointer",onClick:()=>x(M),children:[M.name," ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["tier ",M.tier," · ",(($=M.volume)==null?void 0:$.toLocaleString("en-US"))??"—"," t"]})]},M.id)})}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx("span",{style:{color:"#1e7e34"},children:"●"})," domestic"]}),e.jsxs("span",{children:[e.jsx("span",{style:{color:"#d98a00"},children:"●"})," imported"]}),e.jsxs("span",{children:[e.jsx("span",{style:{color:"#b8bec6"},children:"●"})," inactive"]}),e.jsx("span",{children:"- - MEDIUM"}),e.jsx("span",{children:"⚠ LOW (unverified)"}),e.jsxs("span",{children:[e.jsx("span",{style:{color:"#1a56db"},children:"●"})," updated"]}),e.jsx("span",{style:{color:"#b3261e"},children:"— supply cycle"})]}),u.next_cursor!==null&&e.jsx(K,{size:"sm",className:"mt-2.5",disabled:j,onClick:()=>void E(),children:j?"Loading…":"Load more"})]}),e.jsxs("aside",{className:"flex-[1_1_220px] border-l border-border pl-3 text-sm","aria-label":"Selected node",children:[m?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"font-bold",children:m.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.label," · tier ",m.tier]}),e.jsxs("div",{className:"mt-2 grid gap-1.5",children:[e.jsx(ue,{label:"Volume",value:m.volume===null?"—":`${m.volume.toLocaleString("en-US")} t`}),e.jsx(ue,{label:"Origin",value:m.supply_origin??"—"}),e.jsx(ue,{label:"Confidence",value:m.confidence_level??"—"}),e.jsx(ue,{label:"Status",value:m.status}),m.gap&&e.jsx(ue,{label:"Gap severity",value:e.jsxs(V,{variant:m.gap.gap_severity_score>=80?"danger":"warning",children:[m.gap.gap_severity_score.toFixed(0),m.gap.gap_label?` · ${m.gap.gap_label}`:""]})})]}),m.opportunity_card_id&&c&&e.jsx(K,{size:"sm",className:"mt-2.5",onClick:()=>c(m.opportunity_card_id),children:"View Opportunity Card"})]}):e.jsx("div",{className:"text-muted-foreground",children:"Select a node to see its details."}),u.tier_policy.message&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["🔒 ",u.tier_policy.message??xl]})]})]})]})})}const GA=["ml_engineer","chief_economist","head_of_industrial_intelligence"],WA={chapter_overlap:"Chapter",wilaya_colocation:"Wilaya",input_overlap:"Input",supplier_density:"Suppliers",upstream_gap:"Upstream gap"};function Ku({value:t,max:n=100,width:a=120}){const o=Math.max(0,Math.min(1,t/n)),c=t>=70?"var(--success)":t>=40?"var(--warning)":"var(--destructive)";return e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 overflow-hidden rounded bg-muted",style:{width:a},children:e.jsx("span",{className:"block h-full",style:{width:`${o*100}%`,background:c}})}),e.jsx("span",{className:"text-xs font-semibold",children:t.toFixed(1)})]})}function qA({identity:t}){var M,$,O,L,z,Y;const[n,a]=i.useState([]),[o,c]=i.useState(null),[u,h]=i.useState(""),[m,x]=i.useState(null),[v,N]=i.useState(null),[j,w]=i.useState(null),[_,S]=i.useState(""),[y,g]=i.useState(""),p=t.user_id,k=j===p?"error":v===p?"ok":"loading",R=i.useCallback(async()=>{const[G,U]=await Promise.all([$1(t),D1(t)]);return{lines:G.lines,concordance:U}},[t]),C=i.useCallback(G=>{a(G.lines),c(G.concordance),S(""),N(p),w(null)},[p]),E=i.useCallback(G=>{S(G instanceof Error?G.message:"Failed"),w(p),N(null)},[p]);i.useEffect(()=>{let G=!0;return R().then(U=>{G&&C(U)},U=>{G&&E(U)}),()=>{G=!1}},[R,C,E]);const P=async()=>{g(""),S("");try{await Fj(t),g("Scores recomputed and recorded for the certified cycle.")}catch(G){S(G instanceof Error?G.message:"Compute failed")}},F=t.tier==="3",I=n.filter(G=>!u||G.hs6_code.startsWith(u.trim()));return e.jsxs("div",{children:[e.jsx(Se,{title:"Industrial-Base Scores",description:e.jsxs(e.Fragment,{children:["CAS ",e.jsx("code",{children:"existing_industrial_base"})," per HS6 line, computed from the certified anchor-firm graph."]}),actions:GA.includes(t.role)&&e.jsx(K,{size:"sm",onClick:()=>void P(),children:"Compute & record scores"})}),y&&e.jsx(H,{children:y}),_&&k==="ok"&&e.jsx(H,{tone:"error",children:_}),k==="loading"&&e.jsx(H,{children:"Loading scores…"}),k==="error"&&e.jsx(H,{tone:"error",children:_}),k==="ok"&&e.jsxs(e.Fragment,{children:[(o==null?void 0:o.available)&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(150px,1fr))] gap-4 px-4",children:[e.jsx(ue,{label:"Expert-benchmark concordance",value:`${o.concordance_rate}%`,tone:o.gate_pass?"ok":"error"}),e.jsx(ue,{label:"Within tolerance",value:`${o.within} / ${o.lines} lines (±${o.tolerance_points})`}),e.jsx(ue,{label:"Gate",value:e.jsx(V,{variant:o.gate_pass?"success":"danger",children:o.gate_pass?"PASS":`FAIL (needs ${o.gate_pct}%)`})})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:["Lines (",I.length,")"]}),e.jsx(me,{placeholder:"Filter HS6…",value:u,onChange:G=>h(G.target.value),"aria-label":"Filter HS6",className:"w-36"})]}),F&&e.jsxs("p",{className:"mb-2 text-xs text-muted-foreground",children:["🔒 ",xl]}),I.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No scored lines."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Sub-score"}),!F&&e.jsxs(e.Fragment,{children:[e.jsx(T,{children:"Nearest anchor"}),e.jsx(T,{children:"Components"}),e.jsx(T,{children:"Suppliers"})]}),e.jsx(T,{children:"Confidence"}),!F&&e.jsx(T,{})]})}),e.jsx(ye,{children:I.map(G=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:G.hs6_code}),e.jsx(A,{children:e.jsx(Ku,{value:G.raw_score})}),!F&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{children:[G.nearest_anchor_firm_name??e.jsx("span",{className:"text-muted-foreground",children:"no linkage"}),(G.contributing_anchors??[]).length>1&&e.jsx("div",{className:"text-xs text-muted-foreground",children:G.contributing_anchors.map(U=>`${U.name} ${U.proximity.toFixed(2)}`).join(" · ")})]}),e.jsx(A,{children:G.components&&oa.map(U=>e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:"w-[72px] text-muted-foreground",children:WA[U]}),e.jsx(Ku,{value:G.components[U]*100,width:60})]},U))}),e.jsx(A,{children:G.counts?e.jsx(Ku,{value:Math.min(10,G.counts.supplier_density_count),max:10,width:60}):"—"})]}),e.jsxs(A,{children:[e.jsx(V,{variant:G.confidence_level==="HIGH"?"success":G.confidence_level==="LOW"?"warning":"secondary",children:G.confidence_level}),G.flags.includes("low_data_confidence_warning")&&e.jsx("div",{children:e.jsx(V,{variant:"warning",children:"low data confidence"})}),G.flags.includes("CACHED_DATA")&&e.jsx("div",{children:e.jsx(V,{variant:"warning",children:"cached"})})]}),!F&&e.jsx(A,{children:e.jsx(K,{variant:"outline",size:"xs",onClick:()=>x(G),children:"View source"})})]},G.hs6_code))})]})]})})]}),m&&e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":`Source of ${m.hs6_code}`,onClick:()=>x(null),className:"fixed inset-0 z-10 flex items-center justify-center bg-black/30",children:e.jsx(B,{onClick:G=>G.stopPropagation(),className:"max-h-[80vh] w-[90%] max-w-[560px] overflow-y-auto py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:["Source — HS6 ",m.hs6_code]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2.5 text-sm",children:[e.jsx(ue,{label:"Algorithm",value:m.algorithm_version??"—"}),e.jsx(ue,{label:"Cycle",value:m.quarterly_cycle_label??"—"}),e.jsx(ue,{label:"Snapshot",value:m.snapshot_id??"—"}),e.jsx(ue,{label:"Queried at",value:((M=m.graph_query_timestamp)==null?void 0:M.slice(0,19).replace("T"," "))??"—"}),e.jsx(ue,{label:"Config",value:m.config_version_id??"—"}),e.jsx(ue,{label:"Source",value:m.source??"—"})]}),e.jsxs("p",{className:"mb-1 mt-2.5 text-xs text-muted-foreground",children:["Nodes (",(($=m.source_citation_json)==null?void 0:$.node_ids.length)??0,")"]}),e.jsx("code",{className:"break-all text-[11px]",children:((O=m.source_citation_json)==null?void 0:O.node_ids.join(", "))||"—"}),e.jsxs("p",{className:"mb-1 mt-2.5 text-xs text-muted-foreground",children:["Edges (",((L=m.source_citation_json)==null?void 0:L.edge_ids.length)??0,")"]}),e.jsx("code",{className:"break-all text-[11px]",children:((z=m.source_citation_json)==null?void 0:z.edge_ids.join(", "))||"—"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["query hash ",(Y=m.source_citation_json)==null?void 0:Y.query_hash]}),e.jsx(K,{size:"sm",className:"mt-2",onClick:()=>x(null),children:"Close"})]})})})]})}const QA=.001,Vp={chapter_overlap:"Chapter overlap",wilaya_colocation:"Wilaya co-location",input_overlap:"Input overlap",supplier_density:"Supplier density",upstream_gap:"Upstream gap"};function KA({identity:t}){const[n,a]=i.useState(null),[o,c]=i.useState([]),[u,h]=i.useState(null),[m,x]=i.useState(null),[v,N]=i.useState(""),[j,w]=i.useState(null),[_,S]=i.useState(null),[y,g]=i.useState(""),[p,k]=i.useState(""),[R,C]=i.useState(!1),E=t.user_id,P=_===E?"error":j===E?"ok":"loading",F=i.useCallback(async()=>{const[U,ae]=await Promise.all([P1(t),T1(t)]);return{config:U,changes:ae.changes,weights:Object.fromEntries(oa.map(W=>[W,String(U.weights[W])]))}},[t]),I=i.useCallback(U=>{a(U.config),c(U.changes),h(U.weights),g(""),w(E),S(null)},[E]),M=i.useCallback(U=>{g(U instanceof Error?U.message:"Failed"),S(E),w(null)},[E]);i.useEffect(()=>{if(t.role!=="chief_economist")return;let U=!0;return F().then(ae=>{U&&I(ae)},ae=>{U&&M(ae)}),()=>{U=!1}},[F,I,M,t.role]);const $=i.useCallback(()=>(w(null),S(null),F().then(I,M)),[F,I,M]),O=i.useMemo(()=>u?Object.fromEntries(oa.map(U=>[U,Number(u[U])])):null,[u]),L=O?oa.reduce((U,ae)=>U+(Number.isFinite(O[ae])?O[ae]:NaN),0):NaN,z=O!==null&&oa.every(U=>Number.isFinite(O[U])&&O[U]>=0&&O[U]<=1)&&Math.abs(L-1)<=QA;if(i.useEffect(()=>{if(!z||!O)return;const U=setTimeout(()=>{L1(t,O).then(x).catch(()=>x(null))},400);return()=>clearTimeout(U)},[t,z,O]),t.role!=="chief_economist")return null;const Y=async()=>{if(O){C(!0),g(""),k("");try{await F1(t,{weights:O,rationale:v}),await Fj(t),k("Weights saved and the industrial-base re-score queued."),N(""),await $()}catch(U){g(U instanceof Error?U.message:"Save failed")}finally{C(!1)}}},G=m?[...m.lines].sort((U,ae)=>Math.abs(ae.delta)-Math.abs(U.delta)).slice(0,20):[];return e.jsxs("div",{children:[e.jsx(Se,{title:"Industrial-Base Methodology",description:e.jsxs(e.Fragment,{children:["Component weights of the CAS ",e.jsx("code",{children:"existing_industrial_base"})," dimension (chief economist only)."]})}),p&&e.jsx(H,{children:p}),y&&P==="ok"&&e.jsx(H,{tone:"error",children:y}),P==="loading"&&e.jsx(H,{children:"Loading methodology…"}),P==="error"&&e.jsx(H,{tone:"error",children:y}),P==="ok"&&n&&u&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:["Weights ",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["· active ",n.id," · ",n.algorithm_version]})]}),e.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(150px,1fr))] gap-3",children:oa.map(U=>e.jsxs("label",{className:"text-sm",children:[Vp[U],e.jsx(me,{className:"mt-1",type:"number",min:0,max:1,step:.01,value:u[U],onChange:ae=>h({...u,[U]:ae.target.value})})]},U))}),e.jsxs("p",{className:"mt-2.5 text-sm",children:["Sum: ",e.jsx("strong",{className:z?"text-success":"text-destructive",children:Number.isFinite(L)?L.toFixed(3):"—"})," ",z?e.jsx(V,{variant:"success",children:"valid"}):e.jsx(V,{variant:"danger",children:"must equal 1.00"})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(me,{className:"w-auto flex-[1_1_300px]",placeholder:"Rationale (required)",value:v,onChange:U=>N(U.target.value)}),e.jsx(K,{size:"sm",disabled:!z||!v.trim()||R,onClick:()=>void Y(),children:R?"Saving…":"Save & Queue Re-score"})]})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:["Impact preview ",m&&e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["· ",m.affected_hs6_count," line(s) change"]})]}),z?m?e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{className:"text-right",children:"Current"}),e.jsx(T,{className:"text-right",children:"Proposed"}),e.jsx(T,{className:"text-right",children:"Δ"})]})}),e.jsx(ye,{children:G.map(U=>e.jsxs(ee,{children:[e.jsx(A,{className:"font-mono text-xs",children:U.hs6_code}),e.jsx(A,{className:"text-right tabular-nums",children:U.current_score.toFixed(1)}),e.jsx(A,{className:"text-right tabular-nums",children:U.proposed_score.toFixed(1)}),e.jsxs(A,{className:`text-right font-semibold tabular-nums ${U.delta>0?"text-success":U.delta<0?"text-destructive":"text-muted-foreground"}`,children:[U.delta>0?"+":"",U.delta.toFixed(2)]})]},U.hs6_code))})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Computing…"}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Enter weights that sum to 1.00 to preview."})]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:["Changelog (",o.length,")"]}),o.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Default weights — never changed."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"When"}),e.jsx(T,{children:"By"}),e.jsx(T,{children:"Change"}),e.jsx(T,{children:"Rationale"}),e.jsx(T,{className:"text-right",children:"Lines"})]})}),e.jsx(ye,{children:o.map(U=>e.jsxs(ee,{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:U.changed_at.slice(0,16).replace("T"," ")}),e.jsx(A,{children:U.changed_by}),e.jsx(A,{className:"text-xs",children:oa.filter(ae=>U.old_weights_json[ae]!==U.new_weights_json[ae]).map(ae=>`${Vp[ae]} ${U.old_weights_json[ae]} → ${U.new_weights_json[ae]}`).join("; ")}),e.jsx(A,{children:U.rationale}),e.jsx(A,{className:"text-right tabular-nums",children:U.affected_hs6_count??"—"})]},U.changed_at))})]})]})})]})]})}const XA=["ml_engineer","head_of_industrial_intelligence"];function YA({identity:t}){const[n,a]=i.useState([]),[o,c]=i.useState(""),[u,h]=i.useState(null),[m,x]=i.useState(0),[v,N]=i.useState("Q2-2026"),[j,w]=i.useState({certifier_name:"",certification_note:""}),[_,S]=i.useState(null),[y,g]=i.useState(null),[p,k]=i.useState(null),[R,C]=i.useState(""),[E,P]=i.useState(""),[F,I]=i.useState(!1),M=`${t.user_id}|${o}`,$=p===M?"error":y===M?"ok":"loading",O=i.useCallback(async()=>{var Ae;const q=(await Tj(t)).runs.filter(Z=>Z.kind==="REFRESH"),J=o&&q.some(Z=>Z.pipeline_run_id===o)?o:((Ae=q[0])==null?void 0:Ae.pipeline_run_id)??"",le=q.find(Z=>Z.pipeline_run_id===J),[ke,Ce]=await Promise.all([J&&(le==null?void 0:le.status)!=="RUNNING"?E1(t,J).catch(()=>null):Promise.resolve(null),Lj(t,{status:"OPEN"})]);return{r:q,id:J,rep:ke,openItems:Ce.items.filter(Z=>Z.pipeline_run_id===J).length}},[t,o]),L=i.useCallback(q=>{a(q.r),c(q.id),h(q.rep),x(q.openItems),g(M),k(null)},[M]),z=i.useCallback(q=>{C(q instanceof Error?q.message:"Failed"),k(M),g(null)},[M]);i.useEffect(()=>{let q=!0;return O().then(J=>{q&&L(J)},J=>{q&&z(J)}),()=>{q=!1}},[O,L,z]);const Y=i.useCallback(()=>O().then(L,z),[O,L,z]),G=n.find(q=>q.pipeline_run_id===o)??null,U=(G==null?void 0:G.status)==="RUNNING";i.useEffect(()=>{if(!U)return;const q=setInterval(()=>void Y(),2e3);return()=>clearInterval(q)},[U,Y]);const ae=async(q,J)=>{I(!0),C(""),P("");try{await q(),P(J),await Y()}catch(le){C(le instanceof Error?le.message:"Action failed")}finally{I(!1)}},W=XA.includes(t.role),se=t.role==="head_of_industrial_intelligence",ne=!!u&&!u.certification&&m===0&&j.certifier_name.trim()!==""&&j.certification_note.trim()!=="";return e.jsxs("div",{children:[e.jsx(Se,{title:"Graph Refresh & Certification",description:"Quarterly refresh of the anchor-firm graph; CAS only reads it once certified.",actions:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.length>1&&e.jsx(Ie,{value:o,onChange:q=>c(q.target.value),"aria-label":"Run",children:n.map(q=>e.jsxs("option",{value:q.pipeline_run_id,children:[q.quarterly_cycle_label," · ",q.pipeline_run_id]},q.pipeline_run_id))}),W&&e.jsxs(e.Fragment,{children:[e.jsx(me,{value:v,onChange:q=>N(q.target.value),"aria-label":"Cycle",className:"w-28"}),e.jsx(K,{size:"sm",disabled:F||U,onClick:()=>void ae(()=>k1(t,v),`Refresh for ${v} started.`),children:"Start refresh"})]})]})}),E&&e.jsx(H,{children:E}),R&&$==="ok"&&e.jsx(H,{tone:"error",children:R}),$==="loading"&&e.jsx(H,{children:"Loading refresh runs…"}),$==="error"&&e.jsx(H,{tone:"error",children:R}),$==="ok"&&!G&&e.jsx(H,{children:"No quarterly refresh has run yet."}),$==="ok"&&G&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[G.quarterly_cycle_label," ",e.jsx(V,{variant:G.status==="SUCCESS"?"success":G.status==="FAILED"?"danger":G.status==="PARTIAL"?"warning":"secondary",children:G.status})]}),G.status==="FAILED"&&W&&e.jsx(K,{variant:"destructive",size:"sm",disabled:F,onClick:()=>void ae(()=>R1(t,G.pipeline_run_id),"Retry started from the failed stage."),children:"Retry from failed stage"})]}),e.jsx(bm,{run:G})]})}),u&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"Reconciliation report"}),e.jsxs("div",{className:"mb-3 grid grid-cols-[repeat(auto-fit,minmax(140px,1fr))] gap-3",children:[e.jsx(ue,{label:"Nodes",value:`${u.total_nodes_before} → ${u.total_nodes_after}`}),e.jsx(ue,{label:"Relationships",value:`${u.total_relationships_before} → ${u.total_relationships_after}`}),e.jsx(ue,{label:"Material changes",value:u.material_changes_flagged,tone:u.material_changes_flagged?"error":void 0}),e.jsx(ue,{label:"Open review items",value:m,tone:m?"error":"ok"}),e.jsx(ue,{label:"Duration",value:`${u.pipeline_duration_seconds.toFixed(1)} s`})]}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Change type"}),e.jsx(T,{className:"text-right",children:"Count"}),e.jsx(T,{})]})}),e.jsx(ye,{children:Object.entries(u.changes_by_type).map(([q,J])=>e.jsxs(i.Fragment,{children:[e.jsxs(ee,{className:J?"cursor-pointer":void 0,onClick:()=>J&&S(_===q?null:q),children:[e.jsx(A,{children:q}),e.jsx(A,{className:"text-right tabular-nums",children:J}),e.jsx(A,{className:"text-xs text-primary",children:J?_===q?"hide":"show":""})]}),_===q&&e.jsx(ee,{children:e.jsx(A,{colSpan:3,className:"bg-muted/50",children:e.jsx("ul",{className:"m-0 max-h-60 overflow-y-auto pl-[18px] text-xs",children:u.changes.filter(le=>le.change_type===q).map((le,ke)=>e.jsxs("li",{children:[le.label_or_type," ",e.jsx("code",{children:le.entity_id}),le.field_name?` · ${le.field_name}: ${JSON.stringify(le.old_value)} → ${JSON.stringify(le.new_value)}`:"",le.material&&e.jsxs(e.Fragment,{children:[" ",e.jsxs(V,{variant:"danger",children:["material",le.material_reason?` · ${le.material_reason}`:""]})]})]},`${le.entity_id}-${le.field_name??""}-${ke}`))})})})]},q))})]})]})}),u&&e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"Certification"}),u.certification?e.jsxs("div",{children:[e.jsx(V,{variant:"success",children:"Certified"})," by ",u.certification.certifier_name," on ",u.certification.certified_at.slice(0,16).replace("T"," ")," — snapshot ",e.jsx("code",{children:u.certification.snapshot_id}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u.certification.certification_note})]}):se?e.jsxs(e.Fragment,{children:[m>0&&e.jsxs("p",{className:"mt-0 text-sm text-warning",children:[m," review item(s) for this run must be resolved first (Graph Review Queue)."]}),e.jsxs("div",{className:"grid max-w-[520px] gap-2",children:[e.jsx(me,{placeholder:"Certifier name",value:j.certifier_name,onChange:q=>w({...j,certifier_name:q.target.value})}),e.jsx(fa,{className:"min-h-[70px]",placeholder:"Certification note",value:j.certification_note,onChange:q=>w({...j,certification_note:q.target.value}),"aria-label":"Certification note"}),e.jsx(K,{size:"sm",className:"bg-success text-background hover:bg-success/90",disabled:!ne||F,onClick:()=>void ae(()=>A1(t,G.pipeline_run_id,j),"Certified — CAS now reads this snapshot."),children:"Certify and Release to CAS"})]})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Only the Head of Industrial Intelligence can certify a refresh."})]})})]})]})}const ZA=["senior_analyst","chief_economist"],JA=["analyst","senior_analyst","chief_economist","head_of_industrial_intelligence"],eR=1800*1e3,xi={annual_capacity_tonnes_or_units:{fr:"Capacité annuelle",ar:"الطاقة السنوية"},capacity_utilization_pct:{fr:"Taux d'utilisation (%)",ar:"نسبة الاستغلال"},workforce_headcount:{fr:"Effectif",ar:"عدد العمال"},energy_consumption_mwh:{fr:"Consommation énergétique (MWh)",ar:"استهلاك الطاقة"},export_volume_usd:{fr:"Exportations (USD)",ar:"الصادرات"},primary_wilaya:{fr:"Wilaya principale",ar:"الولاية الرئيسية"},utilization_note:{fr:"Note d'utilisation",ar:"ملاحظة"}},tR={INGESTION:"border-l-muted-foreground",ANALYST_EDIT:"border-l-primary",REVERT:"border-l-warning",MANUAL_ADD:"border-l-success",MANUAL_INACTIVATION:"border-l-destructive"},ic=()=>({source_type:"",source_document_id:"",publication_date:""}),wm=t=>!!(t.source_type&&t.source_document_id.trim()&&t.publication_date),Sm=t=>`graph.profile.draft.${t}`,sR=t=>{try{const n=JSON.parse(localStorage.getItem(Sm(t))??"null");return n&&Date.now()-n.savedAt<=eR?n:null}catch{return null}};function nR({identity:t}){const[n,a]=i.useState([]),[o,c]=i.useState(""),[u,h]=i.useState(null),[m,x]=i.useState([]),[v,N]=i.useState("overview"),[j,w]=i.useState(""),[_,S]=i.useState(""),[y,g]=i.useState([]),[p,k]=i.useState(null),[R,C]=i.useState(null),[E,P]=i.useState(!1),F=E||R===o?"error":p===o?"ok":"loading";i.useEffect(()=>{_l(t).then(Y=>{a(Y.firms),c(G=>{var U;return G||((U=Y.firms[0])==null?void 0:U.id)||""})}).catch(Y=>{w(Y instanceof Error?Y.message:"Failed"),P(!0)})},[t]);const I=i.useCallback(async()=>{if(!o)return null;const[Y,G]=await Promise.all([d1(t,o),f1(t,o)]);return{p:Y,h:G.changes}},[t,o]),M=i.useCallback(Y=>{h(Y.p),x(Y.h),k(o),C(null)},[o]),$=i.useCallback(Y=>{w(Y instanceof Error?Y.message:"Failed"),C(o),k(null)},[o]);i.useEffect(()=>{let Y=!0;return I().then(G=>{Y&&G&&M(G)},G=>{Y&&$(G)}),()=>{Y=!1}},[I,M,$]);const O=i.useCallback(()=>(k(null),C(null),w(""),I().then(Y=>{Y&&M(Y)},$)),[I,M,$]),L=async(Y,G)=>{const U=Y.affected_opportunity_card_ids??[];U.length&&g(U),S(G),await O()},z=JA.includes(t.role);return e.jsxs("div",{children:[e.jsx(Se,{title:"Anchor-Firm Profiles",description:e.jsxs(e.Fragment,{children:["Profils des entreprises d'ancrage · ",e.jsx("span",{dir:"rtl",children:"ملفات المؤسسات الرائدة"})]})}),_&&e.jsx(H,{children:_}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-start gap-4",children:[e.jsx(B,{className:"flex-[0_1_220px] py-4","aria-label":"Anchor firms",children:e.jsx("div",{className:"px-4",children:n.map(Y=>{var G;return e.jsxs("button",{onClick:()=>{c(Y.id),N("overview"),g([])},className:`mb-1 block w-full cursor-pointer rounded-lg px-2.5 py-2 text-left ${Y.id===o?"bg-accent":"bg-transparent"}`,children:[e.jsxs("div",{className:"font-semibold",children:[Y.name_fr,Y.data_freshness!=="CURRENT"&&e.jsx("span",{title:"stale data",className:"text-warning",children:" ●"})]}),e.jsx("div",{dir:"rtl",className:"text-xs text-muted-foreground",children:Y.name_ar}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((G=Y.last_ingested_at)==null?void 0:G.slice(0,10))??"—"})]},Y.id)})})}),e.jsxs("div",{className:"min-w-0 flex-[1_1_480px]",children:[F==="loading"&&e.jsx(H,{children:"Loading profile…"}),F==="error"&&e.jsx(H,{tone:"error",children:j}),F==="ok"&&u&&e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsxs("h2",{className:"mb-3 text-base font-semibold",children:[u.firm.name_fr," ",e.jsx("span",{dir:"rtl",className:"font-normal text-muted-foreground",children:u.firm.name_ar}),u.firm.has_low_confidence_fields&&e.jsx("span",{title:"some fields are LOW confidence",className:"text-warning",children:" ●"})]}),y.length>0&&e.jsx("span",{className:"animate-pulse",children:e.jsxs(V,{variant:"warning",children:["PENDING_RESCORE · ",y.length," card(s)"]})})]}),e.jsx("nav",{className:"mb-3 flex gap-1 border-b",children:[["overview","Aperçu"],["products","Lignes de produits"],["inputs","Intrants fournisseurs"],["history","Historique"]].map(([Y,G])=>e.jsx("button",{onClick:()=>N(Y),className:`cursor-pointer border-b-2 bg-transparent px-2.5 py-1.5 ${v===Y?"border-b-foreground font-bold":"border-b-transparent font-normal"}`,children:G},Y))}),v==="overview"&&e.jsx(rR,{identity:t,firmId:o,profile:u,canEdit:z,onChanged:L}),v==="products"&&e.jsx(lR,{identity:t,firmId:o,firmName:u.firm.name_fr,lines:u.product_lines,canEdit:z,onChanged:L}),v==="inputs"&&(u.supplier_inputs.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No input dependencies recorded."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Intrant"}),e.jsx(T,{children:"Route"}),e.jsx(T,{children:"Pays"}),e.jsx(T,{children:"Régime"})]})}),e.jsx(ye,{children:u.supplier_inputs.map((Y,G)=>e.jsxs(ee,{children:[e.jsx(A,{children:Y.input}),e.jsx(A,{children:Y.sourcing_route}),e.jsx(A,{children:Y.sourcing_country_iso3??"—"}),e.jsx(A,{children:Y.tariff_regime})]},`${Y.input}-${G}`))})]})),v==="history"&&e.jsx(iR,{identity:t,firmId:o,rows:m,onChanged:L})]})})]})]})]})}function Cm({value:t,onChange:n}){return e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(Ie,{value:t.source_type,onChange:a=>n({...t,source_type:a.target.value}),"aria-label":"Citation source type",children:[e.jsx("option",{value:"",children:"Source type…"}),o1.map(a=>e.jsx("option",{value:a,children:a},a))]}),e.jsx(me,{className:"w-48",placeholder:"Document id / reference",value:t.source_document_id,onChange:a=>n({...t,source_document_id:a.target.value})}),e.jsx(me,{className:"w-[150px]",type:"date",value:t.publication_date,onChange:a=>n({...t,publication_date:a.target.value}),"aria-label":"Publication date"})]})}function rR({identity:t,firmId:n,profile:a,canEdit:o,onChanged:c}){var C,E;const u=sR(n),[h,m]=i.useState(null),[x,v]=i.useState(!!u),[N,j]=i.useState(null),[w,_]=i.useState(null),[S,y]=i.useState(""),[g,p]=i.useState(!1);i.useEffect(()=>{if(h)try{localStorage.setItem(Sm(n),JSON.stringify({...h,savedAt:Date.now()}))}catch{}},[h,n]);const k=()=>{m(null);try{localStorage.removeItem(Sm(n))}catch{}},R=async(P={})=>{var M,$;if(!h)return;const F=a.fields[h.field],I=typeof(F==null?void 0:F.value)=="number"||h.field!=="primary_wilaya"&&h.field!=="utilization_note";p(!0),y("");try{const O=await u1(t,n,{field_name:h.field,new_value:I&&h.value.trim()!==""?Number(h.value):h.value,lock_version:a.lock_version,source_citation:h.citation,change_note:h.note||void 0,...P});k(),j(null),_(null),await c(O,`${((M=xi[h.field])==null?void 0:M.fr)??h.field} updated.`)}catch(O){if(O instanceof ul&&O.code==="HIGH_DEVIATION_CONFIRMATION_REQUIRED"){const L=O.detail;j({old:L==null?void 0:L.old_value,next:L==null?void 0:L.new_value})}else O instanceof ul&&O.code==="SUPERSEDED_SOURCE"?_(String((($=O.detail)==null?void 0:$.superseded_by)??"")):O instanceof ul&&O.code==="STALE_LOCK_VERSION"?y(`${O.message}. Reload the profile and re-apply your change.`):y(O instanceof Error?O.message:"Save failed")}finally{p(!1)}};return e.jsxs("div",{children:[x&&u&&e.jsxs("div",{role:"status",className:"mb-2.5 rounded-lg bg-primary/10 px-3 py-2 text-sm",children:["Unsaved edit of ",e.jsx("strong",{children:((C=xi[u.field])==null?void 0:C.fr)??u.field})," from ",new Date(u.savedAt).toLocaleTimeString(),"."," ",e.jsx("button",{className:"cursor-pointer border-none bg-transparent text-primary",onClick:()=>{m(u),v(!1)},children:"Restore"}),e.jsx("button",{className:"cursor-pointer border-none bg-transparent text-muted-foreground",onClick:()=>{v(!1),k()},children:"Discard"})]}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Champ"}),e.jsx(T,{children:"Valeur"}),e.jsx(T,{children:"Confiance"}),e.jsx(T,{children:"Source"}),e.jsx(T,{})]})}),e.jsx(ye,{children:c1.map(P=>{var I,M;const F=a.fields[P];return e.jsxs(ee,{children:[e.jsxs(A,{children:[((I=xi[P])==null?void 0:I.fr)??P,e.jsx("div",{dir:"rtl",className:"text-xs text-muted-foreground",children:(M=xi[P])==null?void 0:M.ar})]}),e.jsxs(A,{children:[(F==null?void 0:F.value)===null||(F==null?void 0:F.value)===void 0?"—":typeof F.value=="number"?F.value.toLocaleString("fr-FR"):String(F.value)," ",(F==null?void 0:F.unit)??""]}),e.jsx(A,{children:F&&e.jsx(V,{variant:F.confidence_level==="LOW"?"warning":F.confidence_level==="HIGH"?"success":"secondary",children:F.confidence_level})}),e.jsx(A,{children:e.jsx(Ec,{citation:F==null?void 0:F.source_citation})}),e.jsx(A,{children:o&&e.jsx(K,{variant:"outline",size:"xs",onClick:()=>m({firmId:n,field:P,value:(F==null?void 0:F.value)===null||(F==null?void 0:F.value)===void 0?"":String(F.value),citation:ic(),note:"",savedAt:Date.now()}),children:"Modifier"})})]},P)})})]}),h&&e.jsxs("div",{className:"mt-3 grid gap-2 rounded-lg border p-3",children:[e.jsxs("strong",{className:"text-sm",children:["Modifier · ",((E=xi[h.field])==null?void 0:E.fr)??h.field]}),e.jsx(me,{value:h.value,onChange:P=>m({...h,value:P.target.value}),"aria-label":"New value"}),e.jsx(Cm,{value:h.citation,onChange:P=>m({...h,citation:P})}),e.jsx(me,{placeholder:"Change note (optional)",value:h.note,onChange:P=>m({...h,note:P.target.value})}),w!==null&&e.jsxs("div",{className:"text-sm text-warning",children:["This source is superseded by ",e.jsx("code",{children:w}),"."," ",e.jsx(K,{size:"xs",className:"bg-warning text-background hover:bg-warning/90",disabled:g,onClick:()=>void R({confirm_superseded_citation:!0}),children:"Use it anyway"})]}),S&&e.jsx("div",{className:"text-sm text-destructive",children:S}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{size:"sm",disabled:g||!wm(h.citation)||h.value.trim()==="",onClick:()=>void R(),children:"Enregistrer"}),e.jsx(K,{variant:"outline",size:"sm",onClick:k,children:"Annuler"})]})]}),N&&h&&e.jsx(aR,{old:N.old,next:N.next,busy:g,onCancel:()=>j(null),onConfirm:P=>void R({discrepancy_note:P})})]})}function aR({old:t,next:n,busy:a,onCancel:o,onConfirm:c}){const[u,h]=i.useState("");return e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"High deviation warning",className:"fixed inset-0 z-10 flex items-center justify-center bg-black/30",children:e.jsx(B,{className:"w-[90%] max-w-[460px] py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"⚠ HIGH_DEVIATION_WARNING"}),e.jsxs("p",{className:"text-sm",children:["The new value ",e.jsx("strong",{children:String(n)})," deviates strongly from the current ",e.jsx("strong",{children:String(t)}),". Explain the discrepancy to continue."]}),e.jsx(fa,{className:"min-h-[70px]",value:u,onChange:m=>h(m.target.value),placeholder:"Discrepancy note (required)","aria-label":"Discrepancy note"}),e.jsxs("div",{className:"mt-2.5 flex gap-2",children:[e.jsx(K,{size:"sm",disabled:a||!u.trim(),onClick:()=>c(u),children:"Confirm change"}),e.jsx(K,{variant:"outline",size:"sm",onClick:o,children:"Cancel"})]})]})})})}function lR({identity:t,firmId:n,firmName:a,lines:o,canEdit:c,onChanged:u}){const[h,m]=i.useState(!1),[x,v]=i.useState({hs6_code:"",description:"",wilaya:"",estimated_annual_production:"",unit:"t",citation:ic()}),[N,j]=i.useState(null),[w,_]=i.useState(""),[S,y]=i.useState(ic()),[g,p]=i.useState(""),[k,R]=i.useState(!1),C=async()=>{var P;R(!0),p("");try{const F=await m1(t,n,{hs6_code:x.hs6_code,description:x.description,wilaya:x.wilaya,estimated_annual_production:Number(x.estimated_annual_production),unit:x.unit,source_citation:x.citation});m(!1),await u(F,`Product line ${x.hs6_code} added.`)}catch(F){const I=F instanceof ul?(P=F.detail)==null?void 0:P.successors:void 0;p(`${F instanceof Error?F.message:"Failed"}${I!=null&&I.length?` — use ${I.join(" or ")}`:""}`)}finally{R(!1)}},E=async()=>{if(N){R(!0),p("");try{const P=await h1(t,n,N.hs6_code,{source_citation:S,inactivation_reason:w});j(null),await u(P,`Product line ${N.hs6_code} inactivated.`)}catch(P){p(P instanceof Error?P.message:"Failed")}finally{R(!1)}}};return e.jsxs("div",{children:[o.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No product lines."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Description"}),e.jsx(T,{children:"Wilaya"}),e.jsx(T,{children:"Statut"}),e.jsx(T,{children:"Source"}),e.jsx(T,{})]})}),e.jsx(ye,{children:o.map(P=>e.jsxs(ee,{className:P.status==="ACTIVE"?void 0:"opacity-50",children:[e.jsx(A,{className:"font-mono text-xs",children:P.hs6_code}),e.jsx(A,{children:P.description}),e.jsx(A,{children:P.wilaya_code}),e.jsx(A,{children:e.jsx(V,{variant:P.status==="ACTIVE"?"success":"secondary",children:P.status})}),e.jsx(A,{children:e.jsx(Ec,{citation:{source_type:P.source_type,source_document_id:P.source_document_id}})}),e.jsx(A,{children:c&&P.status==="ACTIVE"&&e.jsx(K,{variant:"outline",size:"xs",className:"text-destructive",onClick:()=>{j(P),_(""),y(ic())},children:"Inactiver"})})]},`${P.hs6_code}-${P.wilaya_code}`))})]}),c&&!h&&e.jsx(K,{size:"sm",className:"mt-2.5",onClick:()=>m(!0),children:"+ Ajouter une ligne"}),h&&e.jsxs("div",{className:"mt-3 grid gap-2 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(me,{className:"w-[90px]",placeholder:"HS6",value:x.hs6_code,onChange:P=>v({...x,hs6_code:P.target.value})}),e.jsx(me,{className:"w-auto flex-1",placeholder:"Description",value:x.description,onChange:P=>v({...x,description:P.target.value})}),e.jsx(me,{className:"w-[70px]",placeholder:"Wilaya",value:x.wilaya,onChange:P=>v({...x,wilaya:P.target.value})}),e.jsx(me,{className:"w-[120px]",placeholder:"Annual production",value:x.estimated_annual_production,onChange:P=>v({...x,estimated_annual_production:P.target.value})}),e.jsx(me,{className:"w-[60px]",value:x.unit,onChange:P=>v({...x,unit:P.target.value}),"aria-label":"Unit"})]}),e.jsx(Cm,{value:x.citation,onChange:P=>v({...x,citation:P})}),g&&e.jsx("div",{className:"text-sm text-destructive",children:g}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{size:"sm",disabled:k||!/^\d{6}$/.test(x.hs6_code)||!x.description.trim()||!x.wilaya.trim()||!wm(x.citation),onClick:()=>void C(),children:"Ajouter"}),e.jsx(K,{variant:"outline",size:"sm",onClick:()=>m(!1),children:"Annuler"})]})]}),N&&e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Confirm inactivation",className:"fixed inset-0 z-10 flex items-center justify-center bg-black/30",children:e.jsx(B,{className:"w-[90%] max-w-[480px] py-4",children:e.jsxs("div",{className:"grid gap-2 px-4",children:[e.jsx("h2",{className:"mb-3 text-base font-semibold",children:"Inactivate product line?"}),e.jsxs("p",{className:"m-0 text-sm",children:[e.jsx("strong",{children:a})," · HS6 ",e.jsx("code",{children:N.hs6_code})," · ",N.description]}),e.jsx(me,{placeholder:"Reason (required)",value:w,onChange:P=>_(P.target.value)}),e.jsx(Cm,{value:S,onChange:y}),g&&e.jsx("div",{className:"text-sm text-destructive",children:g}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{variant:"destructive",size:"sm",disabled:k||!w.trim()||!wm(S),onClick:()=>void E(),children:"Inactivate"}),e.jsx(K,{variant:"outline",size:"sm",onClick:()=>j(null),children:"Cancel"})]})]})})})]})}function iR({identity:t,firmId:n,rows:a,onChanged:o}){const[c,u]=i.useState(""),h=ZA.includes(t.role),m=async v=>{var j;const N=(j=window.prompt(`Revert ${v.field_name}? Reason:`))==null?void 0:j.trim();if(N){u("");try{await o(await x1(t,n,v.change_id,N),`${v.field_name} reverted.`)}catch(w){u(w instanceof Error?w.message:"Revert failed")}}},x=[...a].sort((v,N)=>N.changed_at.localeCompare(v.changed_at));return x.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No changes recorded."}):e.jsxs("div",{children:[c&&e.jsx("div",{className:"mb-2 text-sm text-destructive",children:c}),e.jsx("ol",{className:"m-0 list-none p-0",children:x.map(v=>e.jsxs("li",{className:`mb-2 border-l-[3px] px-2.5 py-1.5 text-sm ${tR[v.change_type]??"border-l-muted-foreground"}`,children:[e.jsxs("div",{className:"flex flex-wrap justify-between gap-2",children:[e.jsxs("span",{children:[e.jsx(V,{variant:"secondary",children:v.change_type})," ",e.jsx("strong",{children:v.field_name})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v.changed_at.slice(0,16).replace("T"," ")," · ",v.changed_by]})]}),e.jsxs("div",{className:"mt-0.5 break-all text-xs",children:[JSON.stringify(v.old_value)," → ",JSON.stringify(v.new_value)]}),(v.change_note||v.discrepancy_note)&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:[v.change_note,v.discrepancy_note?` · discrepancy: ${v.discrepancy_note}`:""]}),v.change_type==="ANALYST_EDIT"&&e.jsx(K,{variant:"outline",size:"xs",className:"mt-1",disabled:!h,title:h?void 0:"Only a senior analyst or the chief economist can revert",onClick:()=>void m(v),children:"Revert"})]},v.change_id))})]})}const oR={PASS:"border-l-success",WARNING:"border-l-warning",HOLD:"border-l-destructive",FAILED:"border-l-destructive",OVERRIDE:"border-l-primary"},cR=[["90–100",t=>t>=90],["80–89",t=>t>=80],["60–79",t=>t>=60],["< 60",()=>!0]];function dR(){const t=new Date;return`${t.getUTCFullYear()}-Q${Math.floor(t.getUTCMonth()/3)+1}`}function uR({identity:t}){const[n,a]=i.useState(dR()),[o,c]=i.useState(null),[u,h]=i.useState(""),[m,x]=i.useState([]),[v,N]=i.useState(""),[j,w]=i.useState(null),[_,S]=i.useState(null),y=`${n}|${v}`,g=_===y?"error":j===y?"ok":"loading",p=i.useCallback(async(E,P)=>{const[F,I]=await Promise.all([Pb(t,E),Rb(t,{vintage:E,...P?{sector:P}:{}})]);return{d:F,scores:I.scores}},[t]),k=i.useCallback(E=>{c(E.d),x(E.scores),h(""),w(y),S(null)},[y]),R=i.useCallback(E=>{h(E instanceof Error?E.message:"Failed"),S(y),w(null)},[y]),C=i.useCallback(()=>{w(null),S(null),p(n,v).then(k,R)},[p,k,R,n,v]);return i.useEffect(()=>{let E=!0;return p(n,v).then(P=>{E&&k(P)},P=>{E&&R(P)}),()=>{E=!1}},[p,k,R,n,v]),e.jsxs("div",{children:[e.jsx(Se,{title:"Quality Dashboard",description:"Gate statuses, scores and conflicts for a cycle",actions:e.jsxs("label",{className:"text-sm",children:["Cycle"," ",e.jsx(me,{value:n,onChange:E=>a(E.target.value),placeholder:"2026-Q4",className:"w-[120px]"})]})}),g==="loading"&&e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard…"}),g==="error"&&e.jsxs("div",{role:"alert",className:"mt-3 rounded-lg border border-destructive/40 bg-destructive/10 p-3",children:[u," ",e.jsx(K,{type:"button",size:"sm",onClick:C,className:"ml-2",children:"Retry"})]}),g==="ok"&&o&&e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-2.5 text-sm font-semibold",children:["Status counts — ",o.vintage,o.refresh_in_progress?" · refresh in progress (last completed vintage)":""]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[kb.map(E=>e.jsxs("div",{className:`rounded-lg border-l-4 bg-muted px-4 py-2 ${oR[E]}`,children:[e.jsx("div",{className:"text-xl font-bold",children:o.statuses.counts[E]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:E})]},E)),e.jsxs("div",{className:"rounded-lg bg-muted px-4 py-2",children:[e.jsxs("div",{className:"text-xl font-bold",children:[(o.statuses.hold_share*100).toFixed(1),"%"]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["hold share (",o.statuses.lines," lines)"]})]}),e.jsxs("div",{className:"rounded-lg bg-muted px-4 py-2",children:[e.jsx("div",{className:"mt-1.5 text-sm font-semibold",children:o.release.state}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"release"})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(320px,1fr))] gap-4",children:[e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-2.5 text-sm font-semibold",children:"Pass rate per check"}),Object.entries(o.pass_rates).map(([E,P])=>e.jsxs("div",{className:"grid grid-cols-[130px_1fr_48px] items-center gap-2 py-0.5 text-sm",children:[e.jsx("span",{children:E}),e.jsx("span",{className:"h-2 overflow-hidden rounded-sm bg-muted",children:e.jsx("span",{className:"block h-2",style:{width:`${Math.round(P*100)}%`,background:P>=.95?"var(--success)":"var(--warning)"}})}),e.jsxs("span",{className:"text-right tabular-nums",children:[(P*100).toFixed(0),"%"]})]},E))]})}),e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-2.5 text-sm font-semibold",children:"Trend vs three prior quarters"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Vintage"}),e.jsx(T,{className:"text-right",children:"Average score"}),e.jsx(T,{className:"text-right",children:"Scores"})]})}),e.jsx(ye,{children:o.trend.map(E=>e.jsxs(ee,{children:[e.jsx(A,{children:E.vintage}),e.jsx(A,{className:"text-right tabular-nums",children:E.average_score??"—"}),e.jsx(A,{className:"text-right tabular-nums",children:E.scores})]},E.vintage))})]})]})}),e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-2.5 text-sm font-semibold",children:"Conflict statistics"}),e.jsxs("p",{className:"my-1 text-xl font-bold",children:[o.conflicts.all_sources_disagree," all-sources-disagree"]}),e.jsxs("p",{className:"m-0 text-sm text-muted-foreground",children:[o.conflicts.cross_source_findings," cross-source findings"]})]})})]}),e.jsx(mR,{vintage:o.vintage,scores:m,sector:v,onSector:N,onReload:C}),e.jsx(hR,{identity:t,cycle:o.vintage,overrides:o.overrides}),o.overrides.length===0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No overrides recorded for ",o.vintage,"."]})]})]})}function mR(t){const{vintage:n,scores:a,sector:o,onSector:c,onReload:u}=t,h=a.filter(x=>x.composite_score!==null).map(x=>x.composite_score),m=[...a].filter(x=>x.composite_score!==null).sort((x,v)=>(x.composite_score??0)-(v.composite_score??0)).slice(0,20);return e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-2.5 text-sm font-semibold",children:["Scores at ",n]}),e.jsxs("div",{className:"mb-2.5 flex items-center gap-2",children:[e.jsxs("label",{className:"text-sm",children:["Sector"," ",e.jsx(me,{value:o,onChange:x=>c(x.target.value),placeholder:"all sectors",className:"w-[140px]"})]}),e.jsx(K,{type:"button",size:"xs",variant:"outline",onClick:u,children:"Apply"})]}),h.length===0?e.jsxs("p",{className:"text-sm text-muted-foreground",children:["No scores at this vintage",o?` for sector ${o}`:"","."]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap items-end gap-2.5",children:cR.map(([x,v])=>{const N=h.filter(v).length;return e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-[72px] rounded-sm",style:{height:Math.max(4,Math.round(N/h.length*80)),background:x==="< 60"?"var(--destructive)":x==="60–79"?"var(--warning)":"var(--success)"}}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x}),e.jsx("div",{className:"text-sm font-semibold",children:N})]},x)})}),e.jsx("h3",{className:"mb-1.5 mt-3.5 text-sm font-semibold",children:"20 lowest lines"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{className:"text-right",children:"Score"}),e.jsx(T,{children:"Band"}),e.jsx(T,{children:"Weights"})]})}),e.jsx(ye,{children:m.map(x=>e.jsxs(ee,{children:[e.jsx(A,{children:e.jsx("code",{children:x.hs6_code})}),e.jsx(A,{className:`text-right font-semibold tabular-nums ${(x.composite_score??0)<60?"text-destructive":""}`,children:x.composite_score}),e.jsx(A,{children:x.quality_band??"—"}),e.jsx(A,{children:x.weights_version})]},`${x.hs6_code}@${x.vintage}`))})]})]})]})})}function hR(t){const{identity:n,cycle:a,overrides:o}=t,[c,u]=i.useState(null),[h,m]=i.useState({}),[x,v]=i.useState("");i.useEffect(()=>{let j=!0;return Eb(n,{cycle:a,verdict:"HOLD"}).then(w=>{j&&u(w.lines)}).catch(()=>{j&&u([])}),()=>{j=!1}},[n,a]);const N=async j=>{try{await Ab(n,j.hs6_code,{cycle:a,stage:j.stage,metric:j.metric,justification:h[`${j.hs6_code}:${j.metric}`]??""}),v(`overridden ${j.hs6_code}:${j.metric}`),u(w=>(w??[]).filter(_=>_!==j))}catch(w){v(w instanceof Error?w.message:"override failed")}};return e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-2.5 text-sm font-semibold",children:"HOLD drill-down"}),x&&e.jsx("p",{className:"text-xs text-success",children:x}),c===null?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading holds…"}):c.length===0?e.jsxs("p",{className:"text-sm text-muted-foreground",children:["No HOLD lines at ",a,"."]}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Stage"}),e.jsx(T,{children:"Metric"}),e.jsx(T,{children:"Override"})]})}),e.jsx(ye,{children:c.map(j=>{const w=`${j.hs6_code}:${j.metric}`;return e.jsxs(ee,{children:[e.jsx(A,{children:e.jsx("code",{children:j.hs6_code})}),e.jsx(A,{children:j.stage}),e.jsx(A,{children:j.metric}),e.jsxs(A,{children:[e.jsx(me,{value:h[w]??"",onChange:_=>m(S=>({...S,[w]:_.target.value})),placeholder:"justification","aria-label":`Override justification for ${w}`,className:"w-[200px]"}),e.jsx(K,{type:"button",size:"xs",className:"ml-1.5",onClick:()=>void N(j),children:"Override"})]})]},w)})})]}),o.length>0&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Already overridden: ",o.map(j=>`${j.hs6_code}@${j.stage}`).join(", ")]})]})})}const fR={DRAFT:"secondary",TESTED_PASS:"success",TESTED_FAIL:"danger",SIGNED_ONCE:"warning",CERTIFIED:"success",BLOCKED:"danger",SUPERSEDED:"secondary"};function xR(){const t=new Date;return`${t.getUTCFullYear()}-Q${Math.floor(t.getUTCMonth()/3)+1}`}function pR({identity:t}){const[n,a]=i.useState(xR()),[o,c]=i.useState(null),[u,h]=i.useState(null),[m,x]=i.useState(""),[v,N]=i.useState(""),[j,w]=i.useState(""),[_,S]=i.useState(null),[y,g]=i.useState(null),p=y===n?"error":_===n?"ok":"loading",k=i.useCallback(async $=>{const O=await Db(t,$),L=O.run_id?await Lb(t,O.run_id).catch(()=>null):null;return{r:O,rep:L}},[t]),R=i.useCallback($=>{c($.r),h($.rep),x(""),S(n),g(null)},[n]),C=i.useCallback($=>{x($ instanceof Error?$.message:"Failed"),g(n),S(null)},[n]),E=i.useCallback(()=>{S(null),g(null),k(n).then(R,C)},[k,R,C,n]);i.useEffect(()=>{let $=!0;return k(n).then(O=>{$&&R(O)},O=>{$&&C(O)}),()=>{$=!1}},[k,R,C,n]);const P=async()=>{N("running the regression suite on an isolated copy…");try{const $=await Tb(t,{cycle:n,kind:"RELEASE"});h($),N(`regression run ${$.run_id}: ${$.verdict} (detection ${($.detection_rate*100).toFixed(1)}%)`),E()}catch($){N($ instanceof Error?$.message:"the regression run failed")}},F=async()=>{try{const $=await $b(t,n);c($),N(`signed by ${t.user_id} (${t.role})`)}catch($){N($ instanceof Error?$.message:"signing refused")}},I=async $=>{try{await Fb(t,{injection_id:$,justification:j}),N(`excluded ${$}`)}catch(O){N(O instanceof Error?O.message:"exclusion refused")}},M=o?fR[o.state]:null;return e.jsxs("div",{children:[e.jsx(Se,{title:"Release Certification",description:"Regression suite, missed errors and the two signatures",actions:e.jsxs("label",{className:"text-sm",children:["Cycle"," ",e.jsx(me,{value:n,onChange:$=>a($.target.value),className:"w-[120px]"})]})}),p==="loading"&&e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading release…"}),p==="error"&&e.jsx("p",{className:"mt-4 text-destructive",children:m}),p==="ok"&&o&&e.jsxs("div",{className:"mt-4 grid gap-4",children:[e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[M&&e.jsx(V,{variant:M,children:o.state}),e.jsxs("span",{className:"text-sm",children:["hold share ",(o.hold_share*100).toFixed(1),"%"]}),e.jsx("span",{className:`text-sm font-semibold ${o.promotable?"text-success":"text-destructive"}`,children:o.promotable?"promotable":"not promotable"}),e.jsx("span",{className:"flex-1"}),e.jsx(K,{type:"button",variant:"outline",size:"xs",onClick:()=>void P(),children:"Run regression suite"}),e.jsx(K,{type:"button",variant:"outline",size:"xs",onClick:()=>void F(),children:"Sign this release"})]}),v&&e.jsx("p",{className:"m-0 mt-2 text-xs text-muted-foreground",children:v}),e.jsx("h3",{className:"mb-1.5 mt-3.5 text-sm font-semibold",children:"Signature slots (two distinct people)"}),e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"#"}),e.jsx(T,{children:"Signer"}),e.jsx(T,{children:"Role"}),e.jsx(T,{children:"At"})]})}),e.jsx(ye,{children:[0,1].map($=>{const O=o.signatures[$];return e.jsxs(ee,{children:[e.jsx(A,{className:"tabular-nums",children:$+1}),e.jsx(A,{children:(O==null?void 0:O.user_id)??e.jsx("em",{className:"text-muted-foreground",children:"awaiting signature"})}),e.jsx(A,{children:(O==null?void 0:O.role)??"—"}),e.jsx(A,{children:O?O.at.slice(0,16).replace("T"," "):"—"})]},$)})})]})]})}),e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-2.5 text-sm font-semibold",children:"Regression report"}),u?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-sm",children:[e.jsxs("span",{children:["verdict ",e.jsx("strong",{className:u.verdict==="PASS"?"text-success":"text-destructive",children:u.verdict})]}),e.jsxs("span",{children:["detected ",u.detected,"/",u.injected," (",(u.detection_rate*100).toFixed(1),"%)"]}),e.jsxs("span",{children:["false positives ",u.false_positives," (",(u.false_positive_rate*100).toFixed(1),"%)"]}),e.jsxs("span",{children:["stage ",u.stage]})]}),e.jsxs("h3",{className:"mb-1.5 mt-3.5 text-sm font-semibold",children:["Missed errors (",u.missed.length,")"]}),u.missed.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"None — the suite caught every injection."}):e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Injection"}),e.jsx(T,{children:"HS6"}),e.jsx(T,{children:"Category"}),e.jsx(T,{children:"Exclude (chief)"})]})}),e.jsx(ye,{children:u.missed.map($=>e.jsxs(ee,{children:[e.jsx(A,{children:e.jsx("code",{children:$.injection_id})}),e.jsx(A,{children:$.hs6_code}),e.jsx(A,{children:$.category}),e.jsxs(A,{children:[e.jsx(me,{value:j,onChange:O=>w(O.target.value),placeholder:"justification",className:"w-[180px]"}),e.jsx(K,{type:"button",variant:"outline",size:"xs",className:"ml-1.5",onClick:()=>void I($.injection_id),children:"Exclude"})]})]},$.injection_id))})]}),e.jsx("h3",{className:"mb-1.5 mt-3.5 text-sm font-semibold",children:"Systematic gaps"}),u.systematic_gaps.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"None."}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:u.systematic_gaps.map($=>e.jsx("span",{className:"rounded-sm bg-destructive/10 px-2 py-0.5 text-xs text-destructive",children:$},$))}),u.uncovered_check_rules.length>0&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Uncovered check rules: ",u.uncovered_check_rules.join(", ")]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No regression run for this cycle yet — run the suite above."})]})})]})]})}function gR({identity:t}){const[n,a]=i.useState(""),[o,c]=i.useState(1),[u,h]=i.useState(null),[m,x]=i.useState(null),[v,N]=i.useState(null),[j,w]=i.useState(!1),[_,S]=i.useState(""),[y,g]=i.useState(null),[p,k]=i.useState(""),[R,C]=i.useState(""),E=i.useCallback(O=>{let L=!0;return Ib(t,O).then(z=>{L&&(h(z.entries),x({matched:z.matched,total:z.total,next_page:z.next_page}))}).catch(()=>{L&&h([])}),()=>{L=!1}},[t]);i.useEffect(()=>{E({page:o,...n?{entity_id:n}:{}})},[E,o,n]);const P=async()=>{w(!0);try{N(await Mb(t))}catch{C("verification failed")}finally{w(!1)}},F=async()=>{try{const O=await Ob(t,n?{entity_id:n}:{});S(O.export_id),C(`export ${O.export_id} produced (${O.total_entries} entries, ${O.pages} pages)`)}catch{C("export failed")}},I=async()=>{try{g(await zb(t,_))}catch{C(`no export ${_}`)}},M=async()=>{try{await Ub(t,{restore_point:p,justification:`restore point ${p} reconciled by ${t.user_id}`}),C(`reconciliation recorded for ${p}`)}catch(O){C(O instanceof Error?O.message:"reconciliation refused")}},$=t.role==="platform_admin";return e.jsxs("div",{children:[e.jsx(Se,{title:"Audit Log",description:"Hash-chained, tamper-evident; every mutation is a new link",actions:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(me,{value:n,onChange:O=>{a(O.target.value),c(1)},placeholder:"filter by entity id",className:"w-[180px]"}),e.jsx(K,{type:"button",size:"xs",onClick:()=>void P(),disabled:j,children:j?"Verifying…":"Verify chain"}),e.jsx(K,{type:"button",variant:"outline",size:"xs",onClick:()=>void F(),children:"Export"})]})}),R&&e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:R}),v&&e.jsx("div",{role:"status",className:`mt-3 rounded-lg border p-3.5 ${v.ok?"border-success/40 bg-success/10":"border-destructive/40 bg-destructive/10"}`,children:v.ok?e.jsxs("strong",{className:"text-success",children:["Chain OK — ",v.checked," entries verified"]}):e.jsxs("strong",{className:"text-destructive",children:["Chain BROKEN",v.first_break?` at entry ${v.first_break.sequence} (${v.first_break.event_id}, ${v.first_break.timestamp})`:" — head hash mismatch"]})}),e.jsx(B,{className:"mt-4 py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsxs("h2",{className:"mb-2.5 text-sm font-semibold",children:["Entries",m?` — ${m.matched} matched of ${m.total}`:""]}),u===null?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading entries…"}):u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No entries match."}):e.jsxs(je,{className:"min-w-[720px] text-xs",children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"#"}),e.jsx(T,{children:"Type"}),e.jsx(T,{children:"Actor"}),e.jsx(T,{children:"Entity"}),e.jsx(T,{children:"At"}),e.jsx(T,{children:"Chain hash"})]})}),e.jsx(ye,{children:u.map(O=>e.jsxs(ee,{children:[e.jsx(A,{className:"tabular-nums",children:O.sequence}),e.jsx(A,{children:O.event_type}),e.jsx(A,{children:O.actor}),e.jsxs(A,{children:[O.affected_entity_type,":",O.affected_entity_id]}),e.jsx(A,{children:O.timestamp.slice(0,16).replace("T"," ")}),e.jsx(A,{children:e.jsxs("code",{className:"text-[10px]",children:[O.chain_hash.slice(0,12),"…"]})})]},O.event_id))})]}),m&&e.jsxs("div",{className:"mt-2 flex gap-2",children:[e.jsx(K,{type:"button",variant:"outline",size:"xs",onClick:()=>c(O=>Math.max(1,O-1)),disabled:o===1,children:"Previous"}),e.jsx(K,{type:"button",variant:"outline",size:"xs",onClick:()=>c(O=>O+1),disabled:!m.next_page,children:"Next"}),e.jsxs("span",{className:"self-center text-xs text-muted-foreground",children:["page ",o]})]})]})}),e.jsxs("div",{className:"mt-4 grid grid-cols-[repeat(auto-fit,minmax(320px,1fr))] gap-4",children:[e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-2.5 text-sm font-semibold",children:"Exports"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{value:_,onChange:O=>S(O.target.value),placeholder:"export id",className:"w-auto flex-1"}),e.jsx(K,{type:"button",variant:"outline",size:"xs",onClick:()=>void I(),disabled:!_,children:"Fetch"})]}),y&&e.jsxs("div",{className:"mt-2.5 text-xs",children:[e.jsxs("p",{className:"m-0 mb-1",children:[e.jsx("strong",{children:y.report.cover.title})," — ",y.total_entries," entries, anchored at sequence ",y.chain_anchor.head_sequence]}),e.jsxs("p",{className:"m-0 text-muted-foreground",children:["Verification: ",y.report.verification_instructions[0]]})]})]})}),e.jsx(B,{className:"py-4",children:e.jsxs("div",{className:"px-4",children:[e.jsx("h2",{className:"mb-2.5 text-sm font-semibold",children:"Reconciliation (platform admin)"}),$?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"After a legitimate restore from backup, record the restore point — the chain break is explained, never erased."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{value:p,onChange:O=>k(O.target.value),placeholder:"restore point (e.g. backup-2026-07-01)",className:"w-auto flex-1"}),e.jsx(K,{type:"button",variant:"outline",size:"xs",onClick:()=>void M(),disabled:!p.trim(),children:"Record"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Only the platform admin records a chain-break reconciliation."})]})})]})]})}const Ze=t=>({"x-user-role":t.role,"x-user-id":t.user_id}),vR=["under-2m","2m-10m","10m-50m","50m-200m","over-200m"],jR=["AAPI","FNI","AfDB","AFD","EU","private"],yR=(t,n)=>be("/v1/mandate/intake",n,Ze(t)),_R=(t,n)=>Ri("/v1/mandate/intake/draft",n,Ze(t)),bR=t=>he(`/v1/mandate/intake/draft/${encodeURIComponent(t.user_id)}`,Ze(t)).catch(n=>{if(n instanceof Error&&"status"in n&&n.status===404)return null;throw n}),NR=(t,n)=>he(`/v1/mandate/hs6-lookup?q=${encodeURIComponent(n)}`,Ze(t)),wR=(t,n=!1)=>he(`/v1/mandate/pipeline${n?"?include_archived=true":""}`,Ze(t)),SR=t=>he("/v1/mandate/pipeline/workload",Ze(t)),CR=t=>be("/v1/mandate/pipeline/export",{},Ze(t)),kR=(t,n,a)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/approval`,a?{dzd_rate:a}:{},Ze(t)),Gp=(t,n,a)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/reassignment`,a,Ze(t)),ER=(t,n,a)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/sections/${encodeURIComponent(a)}/complete`,{},Ze(t)),Zj=(t,n,a)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/cancel`,a,Ze(t)),xc=["client-initiated","scope-dispute","force-majeure"],AR=["HTA","HTB","HTB+","industrial-special"],RR=["available","constrained","under-development"],PR=(t,n)=>he(`/v1/mandate/mandates/${encodeURIComponent(n)}/assumption-audit-trail`,Ze(t)),TR=(t,n)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/freeze`,{},Ze(t)),LR=(t,n,a)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/overrides`,a,Ze(t)),FR=(t,n,a)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/parameterization-lock`,{daps_acknowledgements:a},Ze(t)),DR=(t,n,a)=>Ri(`/v1/mandate/mandates/${encodeURIComponent(n)}/brand`,a,Ze(t)),$R=(t,n)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/brand/application`,{},Ze(t)),IR=t=>he("/v1/mandate/revenue/dashboard",Ze(t)),MR=(t,n)=>he(`/v1/mandate/revenue/mandates/${encodeURIComponent(n)}`,Ze(t)),OR=(t,n,a)=>be(`/v1/mandate/revenue/mandates/${encodeURIComponent(n)}/payments`,{invoice_id:a},Ze(t)),zR=(t,n)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/deliver`,{},Ze(t)),UR=(t,n)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/first-draft-ready`,{},Ze(t)),BR=(t,n)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/send-to-delivery`,{},Ze(t)),HR=(t,n,a,o)=>be(`/v1/mandate/mandates/${encodeURIComponent(n)}/portal-token`,{reviewer:a,reason:o},Ze(t)),VR=t=>be("/v1/mandate/revenue/export",{},Ze(t)),nh=t=>Uint8Array.from(Array.isArray(t.bytes)?t.bytes:Object.values(t.bytes)),Wp=(t,n)=>he(`/v1/mandate/scrs/${encodeURIComponent(n)}`,Ze(t)),qp=(t,n={})=>{const a=new URLSearchParams;n.status&&a.set("status",n.status),n.limit!==void 0&&a.set("limit",String(n.limit)),n.cursor&&a.set("cursor",n.cursor);const o=a.toString();return he(`/v1/mandate/scrs${o?`?${o}`:""}`,Ze(t))},GR=(t,n,a,o)=>be(`/v1/mandate/scrs/${encodeURIComponent(n)}/decision`,o!==void 0?{decision:a,reason:o}:{decision:a},Ze(t)),WR=["terminology-error","grammar-error","missing-source-content","tone-ministerial"],qR=.05,Xu=.1,QR=t=>he("/v1/mandate/arabic/quality",Ze(t)),Qp=t=>he("/v1/mandate/tm",Ze(t)),Kp=t=>he("/v1/mandate/tm/feedback",Ze(t)),KR=(t,n,a,o)=>be(`/v1/mandate/tm/feedback/${encodeURIComponent(n)}/resolve`,{decision:a},Ze(t)),XR=(t,n)=>he(`/v1/mandate/arabic/summaries/${encodeURIComponent(n)}`,Ze(t)),YR=(t,n,a)=>be(`/v1/mandate/arabic/summaries/${encodeURIComponent(n)}/flags`,{flags:a},Ze(t)),ZR=(t,n)=>be(`/v1/mandate/arabic/summaries/${encodeURIComponent(n)}/complete`,{mandate_ref:n},Ze(t)),Xp={client_org:"AAPI",requester:{name:"",email:""},hs6_lines:[],capex_bracket:"2m-10m",wilaya_preferences:[],strategic_context:"",deadline:"",arabic_summary:!1};function JR(t,n){const o=Math.max(t-1,0)*3e3;return{baseStudyUsd:25e3,additionalLineFeesUsd:o,capexAdjustmentUsd:0,arabicSummaryUsd:n?2e3:0,totalUsd:25e3+o+(n?2e3:0)}}const ll=t=>`$${t.toLocaleString("en-US")}`;function eP({identity:t}){var $,O;const[n,a]=i.useState(Xp),[o,c]=i.useState(""),[u,h]=i.useState(null),[m,x]=i.useState(""),[v,N]=i.useState(""),[j,w]=i.useState(""),[_,S]=i.useState(!1),[y,g]=i.useState(null),[p,k]=i.useState(""),R=i.useRef(!1);i.useEffect(()=>{let L=!0;return bR(t).then(z=>{!L||!z||(R.current=!0,a(z),k(z.wilaya_preferences.join(", ")),N("Draft restored from your last session."))}),()=>{L=!1}},[t]),i.useEffect(()=>{if(!R.current||n===Xp)return;const L=setTimeout(()=>{_R(t,n).then(z=>N(`Draft autosaved at ${new Date(z.saved_at).toLocaleTimeString()} — expires in ${z.expires_minutes} min.`),z=>N(z instanceof Error?`Draft save failed: ${z.message}`:""))},1200);return()=>clearTimeout(L)},[n,t]);const C=(L,z)=>a(Y=>({...Y,[L]:z})),E=async()=>{x(""),h(null);try{h(await NR(t,o))}catch(L){x(L instanceof Error?L.message:"Lookup failed")}},P=L=>{!/^\d{6}$/.test(L)||n.hs6_lines.includes(L)||(C("hs6_lines",[...n.hs6_lines,L]),h(null),c(""))},F=async()=>{S(!0),w(""),g(null);try{g(await yR(t,{...n,wilaya_preferences:p.split(",").map(L=>Number(L.trim())).filter(L=>Number.isInteger(L)&&L>=1&&L<=58)}))}catch(L){w(L instanceof Error?L.message:"Submission failed")}finally{S(!1)}},I=JR(n.hs6_lines.length,n.arabic_summary),M=n.requester.name.trim()!==""&&n.requester.email.trim()!==""&&n.hs6_lines.length>0&&n.deadline!=="";return e.jsxs("div",{children:[e.jsx(Se,{title:"Mandate Intake",description:"Submit a bespoke pre-feasibility study mandate (US-19.1) — fee itemised live, draft autosaved for 20 minutes"}),v&&e.jsx(H,{children:v}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-2",children:[e.jsxs(B,{className:"gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Requester & scope"}),e.jsxs("div",{className:"grid gap-2 px-4",children:[e.jsxs("label",{className:"text-sm",children:["Client organisation",e.jsx(Ie,{value:n.client_org,onChange:L=>C("client_org",L.target.value),children:jR.map(L=>e.jsx("option",{value:L,children:L},L))})]}),e.jsxs("label",{className:"text-sm",children:["Requester name",e.jsx(me,{value:n.requester.name,onChange:L=>C("requester",{...n.requester,name:L.target.value}),placeholder:"Farida Benali"})]}),e.jsxs("label",{className:"text-sm",children:["Requester email",e.jsx(me,{value:n.requester.email,onChange:L=>C("requester",{...n.requester,email:L.target.value}),placeholder:"f.benali@aapi.dz"})]}),e.jsxs("label",{className:"text-sm",children:["CAPEX bracket",e.jsx(Ie,{value:n.capex_bracket,onChange:L=>C("capex_bracket",L.target.value),children:vR.map(L=>e.jsx("option",{value:L,children:L},L))})]}),e.jsxs("label",{className:"text-sm",children:["Wilaya preferences (comma-separated 1–58)",e.jsx(me,{value:p,onChange:L=>k(L.target.value),placeholder:"16, 31, 9"})]}),e.jsxs("label",{className:"text-sm",children:["Strategic context (≤500 chars)",e.jsx("textarea",{value:n.strategic_context,onChange:L=>C("strategic_context",L.target.value),rows:3,maxLength:500,className:"mt-1 w-full rounded-md border border-border bg-secondary px-2 py-1.5 text-sm text-foreground"})]}),e.jsxs("label",{className:"text-sm",children:["Requested deadline (≥10 business days out)",e.jsx(me,{type:"date",value:n.deadline,onChange:L=>C("deadline",L.target.value)})]}),e.jsxs("label",{className:"text-sm",children:[e.jsx("input",{type:"checkbox",checked:n.arabic_summary,onChange:L=>C("arabic_summary",L.target.checked),className:"size-4 accent-primary"})," Arabic executive summary (+$2,000)"]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(B,{className:"gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"HS6 lines"}),e.jsxs("div",{className:"grid gap-2 px-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{value:o,onChange:L=>c(L.target.value),placeholder:"e.g. 720610"}),e.jsx(K,{size:"sm",variant:"outline",disabled:o.trim().length<2,onClick:()=>void E(),children:"Look up"})]}),m&&e.jsx("p",{className:"text-sm text-destructive",children:m}),u&&e.jsx("div",{className:"rounded-md border border-border bg-secondary/50 p-3 text-sm",children:!u.found||(($=u.descriptor)==null?void 0:$.status)!=="ACTIVE"?e.jsxs("div",{className:"rounded-md border border-warning/40 bg-warning/10 p-2 text-warning",children:[e.jsx("strong",{children:u.code})," is ",u.found?(O=u.descriptor)==null?void 0:O.status:"not in the catalogue",".",u.reclassified_to.length>0&&e.jsxs("div",{className:"mt-1",children:["Reclassified to: ",u.reclassified_to.map(L=>e.jsxs("button",{type:"button",onClick:()=>P(L),className:"mx-1 rounded border border-warning/50 px-1.5 py-0.5 font-mono text-xs hover:bg-warning/20",children:["use ",L]},L))]}),/^\d{6}$/.test(u.code)&&e.jsxs("button",{type:"button",onClick:()=>P(u.code),className:"mt-1 rounded border border-warning/50 px-1.5 py-0.5 font-mono text-xs hover:bg-warning/20",children:["use ",u.code," anyway"]})]}):e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-xs text-muted-foreground",children:u.descriptor.code}),e.jsx("div",{children:u.descriptor.labelFr??"—"}),e.jsx("div",{dir:"rtl",lang:"ar",className:"text-muted-foreground",children:u.descriptor.labelAr??"—"})]}),e.jsx(K,{size:"sm",onClick:()=>P(u.descriptor.code),children:"Add line"})]})}),n.hs6_lines.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No lines yet — look up a code to add the first."}):e.jsx("ul",{className:"flex flex-wrap gap-1.5",children:n.hs6_lines.map(L=>e.jsxs("li",{className:"flex items-center gap-1 rounded-md border border-border bg-secondary px-2 py-1 font-mono text-xs",children:[L,e.jsx("button",{type:"button","aria-label":`Remove ${L}`,onClick:()=>C("hs6_lines",n.hs6_lines.filter(z=>z!==L)),className:"text-muted-foreground hover:text-destructive",children:"×"})]},L))})]})]}),e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Fee preview (US-19.1 AC8)"}),e.jsxs("dl",{className:"grid gap-1 px-4 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Base study"}),e.jsx("dd",{children:ll(I.baseStudyUsd)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("dt",{className:"text-muted-foreground",children:["Additional lines (",Math.max(n.hs6_lines.length-1,0)," × $3,000)"]}),e.jsx("dd",{children:ll(I.additionalLineFeesUsd)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"CAPEX adjustment"}),e.jsx("dd",{children:ll(I.capexAdjustmentUsd)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Arabic summary"}),e.jsx("dd",{children:ll(I.arabicSummaryUsd)})]}),e.jsxs("div",{className:"mt-1 flex justify-between border-t border-border pt-1 font-semibold",children:[e.jsx("dt",{children:"Total"}),e.jsx("dd",{children:ll(I.totalUsd)})]})]})]})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3",children:[e.jsx(K,{disabled:_||!M,onClick:()=>void F(),children:_?"Submitting…":"Submit intake"}),n.hs6_lines.length>5&&e.jsxs(V,{variant:"warning",children:["complex — ",n.hs6_lines.length," lines"]})]}),j&&e.jsx(H,{tone:"error",children:j}),y&&e.jsxs(B,{className:"mt-4 gap-2 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Mandate opened — ",e.jsx("span",{className:"font-mono",children:y.mandate.mandate_ref})]}),e.jsxs("p",{className:"px-4 text-sm",children:["Fee ",e.jsx("strong",{children:ll(y.fee.totalUsd)})," · first draft due ",e.jsx("strong",{children:new Date(y.mandate.sla.first_draft_due).toLocaleDateString()})]}),y.capacity_hold&&e.jsx("div",{className:"mx-4 rounded-md border border-warning/40 bg-warning/10 p-2 text-sm text-warning",children:y.capacity_warning}),e.jsx("p",{className:"px-4 text-sm text-muted-foreground",children:"Track it on the Pipeline Kanban — the operations manager approves scope next."})]})]})}function tP(t){switch(t){case"mandate_requester":return"requester";case"mandate_ops_manager":case"platform_admin":return"ops";case"senior_analyst":return"seniorAnalyst";case"finance_officer":return"finance";case"arabic_reviewer":return"reviewer";default:return null}}const ki={CAPACITY_HOLD:"Capacity hold — the roster is at its concurrent-mandate ceiling; review analyst availability before approving.",ANALYST_UNASSIGNED:"An unassigned line cannot be sealed — its section has no owner, and the first draft waits for every section.",SECTIONS_INCOMPLETE:"The first draft waits for every line — seal the outstanding section(s) first.",COMMENTS_OPEN:"Client comments are still open — resolve them before closing the review so nothing is lost.",SLA_BREACHED:"The first-draft SLA has lapsed — decide today; every business day compounds the breach."},sP=t=>t.hs6_lines.filter(n=>!t.analysts[n]).length,nP=t=>t.hs6_lines.filter(n=>!t.completed_lines.includes(n)).length;function rP(t){return[{key:"approve-scope",label:"Approve the scope — freeze and invoice 50%",actor:"ops",tab:"man-kanban",order:0,blockedBy:t.capacity_hold?{code:"CAPACITY_HOLD",sentence:ki.CAPACITY_HOLD}:void 0},{key:"await-approval",label:"Awaiting scope approval from operations",actor:"requester",tab:"",order:1}]}function aP(t){const n=sP(t);return[{key:"lock-parameters",label:"Finish parameterization and lock the assumptions",actor:"seniorAnalyst",tab:"man-workbench",order:0,blockedBy:n>0?{code:"ANALYST_UNASSIGNED",sentence:`${n} line${n===1?"":"s"} unassigned — ${ki.ANALYST_UNASSIGNED}`}:void 0},{key:"watch-parameterization",label:"Analyst is parameterizing the frozen scope",actor:"ops",tab:"",order:1}]}function lP(t){const n=nP(t);return[{key:"seal-sections",label:`Seal ${n} line section${n===1?"":"s"} — the draft gate`,actor:"seniorAnalyst",tab:"man-kanban",order:0,blockedBy:n===0?{code:"SECTIONS_INCOMPLETE",sentence:"Every section is sealed — release the first draft instead."}:void 0},{key:"release-draft",label:"Release the first draft to client review",actor:"seniorAnalyst",tab:"man-kanban",order:1,blockedBy:n>0?{code:"SECTIONS_INCOMPLETE",sentence:`${n} section${n===1?"":"s"} still unsealed — ${ki.SECTIONS_INCOMPLETE}`}:void 0},{key:"watch-analysis",label:`Analysis in progress — first draft due in ${t.remaining_business_days} business day${t.remaining_business_days===1?"":"s"}`,actor:"ops",tab:"",order:2,blockedBy:t.urgency==="red"?{code:"SLA_BREACHED",sentence:ki.SLA_BREACHED}:void 0}]}function iP(t){const n=t.comment_due?`; the window closes ${new Date(t.comment_due).toLocaleDateString()}`:"";return[{key:"send-to-delivery",label:"Send to delivery — close the review",actor:"ops",tab:"man-kanban",order:0,blockedBy:t.unresolved_comments>0?{code:"COMMENTS_OPEN",sentence:`${t.unresolved_comments} comment${t.unresolved_comments===1?"":"s"} open${n} — ${ki.COMMENTS_OPEN}`}:void 0},{key:"resolve-comments",label:"Resolve the client comments in the portal",actor:"reviewer",tab:"",order:1}]}function oP(){return[{key:"assemble-package",label:"Final-package assembly — the 4-hour budget is running",actor:"ops",tab:"man-kanban",order:0},{key:"await-final-invoice",label:"The final 50% invoice fires on delivery completion",actor:"finance",tab:"",order:1}]}function cP(){return[{key:"settle-payment",label:"Record the final payment and settle the contract",actor:"finance",tab:"man-revenue",order:0},{key:"archive",label:"Delivered — nothing further on the pipeline",actor:"ops",tab:"",order:1}]}function dP(){return[{key:"closed",label:"Cancelled — visible here for the audit trail only",actor:"ops",tab:"",order:0}]}const Yu={intake:rP,parameterization:aP,analysis:lP,review:iP,delivery:oP,delivered:cP,cancelled:dP};function Yp(t,n){var h;const a=((h=Yu[t.status])==null?void 0:h.call(Yu,t))??[],o=t.scr_pending?[{key:"decide-scr",label:`Decide the pending scope change — ${t.mandate_ref}'s clock is paused`,actor:"ops",tab:"scr-queue",order:-1},...a]:a,c=n===null?[]:o.filter(m=>m.actor===n),u=o.filter(m=>m.actor!==n);return[...c.sort((m,x)=>m.order-x.order),...u.sort((m,x)=>m.order-x.order)]}const uP=3e4,Zp=t=>`$${t.toLocaleString("en-US")}`;function pi({value:t,onChange:n,options:a,placeholder:o,emptyLabel:c}){const[u,h]=i.useState(""),[m,x]=i.useState(!1),v=()=>{x(!1),h("")},N=a.filter(j=>j.id.toLowerCase().includes(u.trim().toLowerCase()));return e.jsxs("div",{className:"relative",children:[e.jsx(me,{value:m?u:t,placeholder:o,onFocus:()=>{x(!0),h("")},onBlur:()=>window.setTimeout(v,150),onChange:j=>{x(!0),h(j.target.value)},onKeyDown:j=>{j.key==="Enter"&&N[0]&&(n(N[0].id),v()),j.key==="Escape"&&v()}}),m&&e.jsx("div",{className:"absolute z-10 mt-1 max-h-44 w-full overflow-auto rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md",children:N.length===0?e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:c}):N.map(j=>e.jsxs("button",{type:"button",onMouseDown:w=>w.preventDefault(),onClick:()=>{n(j.id),v()},className:`flex w-full items-center justify-between gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-secondary ${j.id===t?"font-semibold":""}`,children:[e.jsx("span",{className:"font-mono text-xs",children:j.id}),j.hint&&e.jsx("span",{className:"text-xs text-muted-foreground",children:j.hint})]},j.id))})]})}const mP={green:"border-l border-l-success/70",amber:"border-l border-l-warning/70",red:"border-l border-l-destructive"};function Jp(t){try{const n=new URL(t);return`${window.location.origin}${n.pathname}${n.search}`}catch{return t}}function eg({card:t}){if(t.sla_paused)return e.jsx(V,{variant:"warning",children:"SLA paused — SCR pending"});const n=t.urgency==="red"?"danger":t.urgency==="amber"?"warning":"success",a=t.remaining_business_days<0?`breached ${-t.remaining_business_days} bd`:`${t.remaining_business_days} bd left`;return e.jsx(V,{variant:n,children:a})}function hP({action:t}){return t?e.jsxs("div",{className:"mt-2 border-t border-border/70 pt-2",children:[e.jsx("div",{className:"line-clamp-2 text-xs font-medium text-foreground",children:t.label}),t.blockedBy&&e.jsx("div",{className:"mt-0.5 line-clamp-2 text-xs text-warning",children:t.blockedBy.sentence})]}):null}function fP({actions:t,persona:n,onNavigateTab:a}){if(t.length===0)return null;const o=t.filter(u=>u.actor===n),c=t.filter(u=>u.actor!==n);return e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"What's next"}),e.jsxs("ol",{className:"grid gap-1.5 px-3",children:[o.map((u,h)=>e.jsxs("li",{className:"rounded-md border border-primary/30 bg-primary/5 px-2.5 py-1.5",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(lb,{size:14,className:"mt-0.5 shrink-0 text-primary","aria-hidden":!0}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:u.label}),u.blockedBy&&e.jsx("div",{className:"mt-0.5 text-xs text-warning",children:u.blockedBy.sentence}),u.tab&&u.tab!=="man-kanban"&&a&&e.jsxs("button",{type:"button",onClick:()=>a(u.tab),className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",children:["Go there ",e.jsx(Am,{size:11})]})]})]}),h===0&&e.jsx("span",{className:"sr-only",children:"your first action"})]},u.key)),c.length>0&&e.jsx("li",{className:"pt-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Others on this mandate"}),c.map(u=>e.jsxs("li",{className:"flex items-start gap-2 px-2.5 py-1 text-xs text-muted-foreground",children:[e.jsx("span",{"aria-hidden":!0,className:"mt-1 size-1 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsxs("span",{className:"min-w-0",children:[u.label," ",e.jsxs("span",{className:"text-muted-foreground/70",children:["· ",u.actor]}),u.blockedBy&&e.jsx("span",{className:"block text-warning/90",children:u.blockedBy.sentence})]})]},u.key))]})]})}function xP({identity:t,onNavigateTab:n}){const[a,o]=i.useState(null),[c,u]=i.useState({}),[h,m]=i.useState([]),[x,v]=i.useState(""),[N,j]=i.useState(null),[w,_]=i.useState(""),[S,y]=i.useState(""),[g,p]=i.useState(""),[k,R]=i.useState({from:"",to:"",line:""}),[C,E]=i.useState(""),[P,F]=i.useState(xc[0]),[I,M]=i.useState(""),[$,O]=i.useState(!1),[L,z]=i.useState(""),[Y,G]=i.useState(""),[U,ae]=i.useState("first-draft"),[W,se]=i.useState(null),ne=tP(t.role),q=t.role==="mandate_ops_manager"||t.role==="platform_admin",J=i.useCallback(()=>Promise.all([wR(t),SR(t)]).then(([Z,fe])=>{o(Z),u(fe.workload),m(fe.analysts)},Z=>v(Z instanceof Error?Z.message:"Board load failed")),[t]);i.useEffect(()=>{let Z=!0;const fe=()=>{Z&&J()};J();const re=setInterval(fe,uP);return()=>{Z=!1,clearInterval(re)}},[J]);const le=(a==null?void 0:a.columns.flatMap(Z=>Z.cards).find(Z=>Z.mandate_ref===N))??null,ke=le?Yp(le,ne):[],Ce=async(Z,fe)=>{_(""),y("");try{return await Z(),await J(),fe&&y(fe),!0}catch(re){return _(re instanceof Error?re.message:"Action failed"),!1}},Ae=async()=>{_(""),O(!0),z("");try{const Z=await CR(t);z(Z.certification);for(const fe of Z.documents){const re=new Blob([nh(fe)],{type:fe.content_type}),Ee=URL.createObjectURL(re),nt=document.createElement("a");nt.href=Ee,nt.download=fe.filename,nt.click(),URL.revokeObjectURL(Ee)}}catch(Z){_(Z instanceof Error?Z.message:"Export failed")}finally{O(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Pipeline Kanban",description:"Five columns · 10-business-day first-draft SLA · auto-refresh every 30 s",meta:a?e.jsx(e.Fragment,{children:e.jsxs("span",{children:[a.columns.reduce((Z,fe)=>Z+fe.cards.length,0)," active"]})}):void 0,actions:e.jsxs(e.Fragment,{children:[(t.role==="mandate_ops_manager"||t.role==="platform_admin")&&e.jsx(K,{size:"sm",variant:"outline",disabled:$,onClick:()=>void Ae(),children:$?"Exporting…":"Export board (PDF + CSV)"}),Object.keys(c).length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Object.entries(c).map(([Z,fe])=>e.jsxs(V,{variant:fe>4?"warning":"secondary",children:[Z,": ",fe]},Z))})]})}),(a==null?void 0:a.capacity.warning)&&e.jsx("div",{className:"mt-3 rounded-md border border-warning/40 bg-warning/10 p-3 text-sm text-warning",role:"alert",children:a.capacity.warning}),L&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",role:"status",children:L}),x&&e.jsx(H,{tone:"error",children:x}),a&&e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-3 xl:grid-cols-5",children:a.columns.map(Z=>e.jsxs("section",{"aria-label":Z.status,children:[e.jsxs("h2",{className:"mb-2 flex items-center justify-between text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:[Z.status,e.jsx("span",{children:Z.cards.length})]}),e.jsxs("div",{className:"grid gap-2",children:[Z.cards.map(fe=>{const re=Yp(fe,ne).find(Ee=>Ee.actor===ne);return e.jsxs("button",{type:"button",onClick:()=>{j(fe.mandate_ref),_(""),y(""),se(null);const Ee=[...new Set(Object.values(fe.analysts))];R({from:Ee.length===1?Ee[0]:"",to:"",line:""}),E(Ee.length===1?Ee[0]:"")},className:`rounded-lg border border-border bg-card p-3 text-left text-sm transition-colors hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none ${mP[fe.urgency]}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono text-xs",children:fe.mandate_ref}),e.jsx(eg,{card:fe})]}),e.jsx("div",{className:"mt-1 font-medium",children:fe.client_org}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[fe.hs6_line_count," lines · ",fe.capex_bracket," · ",Zp(fe.fee_total_usd)]}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1",children:[fe.complex&&e.jsx(V,{variant:"danger-solid",children:"P0 complex"}),fe.capacity_hold&&e.jsx(V,{variant:"warning",children:"Capacity hold"}),fe.scr_pending&&e.jsx(V,{variant:"warning",children:"SCR pending"}),fe.scope_extended&&e.jsx(V,{variant:"success",children:"Scope extended"}),fe.unresolved_comments>0&&e.jsxs(V,{variant:"warning",children:[fe.unresolved_comments," comments"]})]}),e.jsx(hP,{action:re})]},fe.mandate_ref)}),Z.cards.length===0&&e.jsx("div",{className:"rounded-lg border border-dashed border-border p-3 text-center text-xs text-muted-foreground",children:"empty"})]})]},Z.status))}),le&&e.jsxs("div",{className:"fixed inset-0 z-50",children:[e.jsx("button",{type:"button","aria-label":"Close detail drawer",className:"absolute inset-0 bg-black/60",onClick:()=>j(null)}),e.jsxs("aside",{className:"absolute inset-y-0 right-0 w-full max-w-md overflow-y-auto border-l border-border bg-card p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-mono text-base font-semibold",children:le.mandate_ref}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[le.client_org," · ",le.status]})]}),e.jsx(K,{size:"sm",variant:"outline",onClick:()=>j(null),children:"Close"})]}),e.jsxs("dl",{className:"mt-3 grid grid-cols-2 gap-x-3 gap-y-1 text-sm",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Scope"}),e.jsxs("dd",{children:[le.hs6_line_count," lines · ",le.capex_bracket]}),e.jsx("dt",{className:"text-muted-foreground",children:"Fee"}),e.jsx("dd",{children:Zp(le.fee_total_usd)}),e.jsx("dt",{className:"text-muted-foreground",children:"Deadline"}),e.jsx("dd",{children:new Date(le.deadline).toLocaleDateString()}),e.jsx("dt",{className:"text-muted-foreground",children:"First draft due"}),e.jsx("dd",{children:new Date(le.first_draft_due).toLocaleDateString()}),le.status==="review"&&le.comment_due&&e.jsxs(e.Fragment,{children:[e.jsx("dt",{className:"text-muted-foreground",children:"Comment window"}),e.jsx("dd",{children:new Date(le.comment_due).toLocaleDateString()})]})]}),e.jsx("div",{className:"mt-2",children:e.jsx(eg,{card:le})}),le.scr_pending&&e.jsxs("div",{className:"mt-3 rounded-md border border-warning/40 bg-warning/10 p-3 text-sm text-warning",role:"alert",children:["A scope change is pending — this mandate's clock is paused until operations decides it.",n&&e.jsx("button",{type:"button",onClick:()=>n("scr-queue"),className:"mt-1 block font-medium underline focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",children:"Open the SCR queue"})]}),e.jsx(fP,{actions:ke,persona:ne,onNavigateTab:n}),le.status==="intake"&&e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Approve scope (US-19.1 AC5)"}),e.jsxs("div",{className:"grid gap-2 px-3",children:[e.jsxs("label",{className:"text-sm",children:["DZD rate (optional)",e.jsx(me,{value:g,onChange:Z=>p(Z.target.value),placeholder:"240.5"})]}),e.jsx(K,{size:"sm",onClick:()=>void Ce(()=>kR(t,le.mandate_ref,g.trim()?{rate:Number(g),at:new Date().toISOString()}:void 0),"Scope approved — frozen, 50% invoice emitted to Finance."),children:"Approve — freeze & invoice 50%"}),le.capacity_hold&&e.jsx("p",{className:"text-xs text-warning",children:"Capacity hold — the roster is at its ceiling; review analyst availability before approving (the call stays yours)."})]})]}),le.status==="parameterization"&&e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Assign analysts to every line (US-20.4)"}),e.jsx("ul",{className:"grid gap-1.5 px-3",children:le.hs6_lines.map(Z=>{const fe=le.analysts[Z];return e.jsxs("li",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"font-mono text-xs",children:Z}),q?e.jsx(pi,{value:fe??"",placeholder:"assign an analyst…",emptyLabel:"no analysts on the roster",onChange:re=>{re!==fe&&Ce(()=>Gp(t,le.mandate_ref,{from_analyst:fe??"(unassigned)",to_analyst:re,hs6_line:Z}),`Line ${Z} assigned to ${re}.`)},options:h.map(re=>({id:re,hint:`${c[re]??0} active`}))}):fe?e.jsx(V,{variant:"secondary",children:fe}):e.jsx(V,{variant:"warning",children:"unassigned"})]},Z)})}),(()=>{const Z=le.hs6_lines.filter(fe=>!le.analysts[fe]).length;return Z>0?e.jsxs("p",{className:"px-3 text-xs text-warning",children:[Z," of ",le.hs6_lines.length," lines still unassigned — an unassigned line cannot be sealed, and the first draft waits for every section."]}):e.jsx("p",{className:"px-3 text-xs text-muted-foreground",children:"Every line has an owner — the analyst can lock parameters in the workbench."})})()]}),le.status==="analysis"&&e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Analysis sections (US-19.8 AC7)"}),t.role==="senior_analyst"&&e.jsxs("div",{className:"grid gap-1.5 px-3",children:[e.jsxs("label",{className:"text-sm",children:["Acting as",e.jsx(pi,{value:C,placeholder:"which analyst you are",emptyLabel:"no analysts on the roster",onChange:E,options:h.map(Z=>({id:Z,hint:`${c[Z]??0} active`}))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The seal is owner-only — the section rejects anyone but the line's assigned analyst."})]}),e.jsx("ul",{className:"grid gap-1.5 px-3",children:le.hs6_lines.map(Z=>{const fe=le.completed_lines.includes(Z),re=le.analysts[Z],Ee=t.role==="platform_admin"?t:{...t,user_id:C};return e.jsxs("li",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsxs("span",{className:"font-mono text-xs",children:[Z," ",re?`· ${re}`:"· unassigned"]}),fe?e.jsx(V,{variant:"success",children:"sealed"}):e.jsx(K,{size:"sm",variant:"outline",disabled:!re||!Ee.user_id,onClick:()=>void Ce(()=>ER(Ee,le.mandate_ref,Z),`Line ${Z}'s analysis section sealed.`),children:"Complete section"})]},Z)})}),e.jsxs("p",{className:"px-3 text-xs text-muted-foreground",children:["The first draft waits for every line — ",le.hs6_lines.length-le.completed_lines.length," outstanding."]})]}),(le.status==="analysis"||le.status==="review")&&e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Pipeline advance (US-19.5 AC1 / US-19.6 AC9)"}),e.jsx("div",{className:"grid gap-2 px-3",children:le.status==="analysis"?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:le.hs6_lines.length-le.completed_lines.length?`${le.hs6_lines.length-le.completed_lines.length} line section(s) still unsealed — the release gate refuses an incomplete draft.`:"Every line sealed — the draft can be released to review."}),e.jsx(K,{size:"sm",onClick:()=>void Ce(()=>UR(t,le.mandate_ref),"First draft released — the mandate is in review; mint a portal link below for the client."),children:"First draft ready"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:le.unresolved_comments>0?`${le.unresolved_comments} client comment(s) still open${le.comment_due?` — the window closes ${new Date(le.comment_due).toLocaleDateString()}`:""}; resolve them before closing the review.`:"Comments resolved — the explicit exit is open."}),e.jsx(K,{size:"sm",onClick:()=>void Ce(()=>BR(t,le.mandate_ref),"Sent to delivery — final-package assembly clock started."),children:"Send to delivery"})]})})]}),["review","delivery","delivered"].includes(le.status)&&e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Client portal link (US-19.5 AC1)"}),e.jsxs("div",{className:"grid gap-2 px-3",children:[e.jsxs("label",{className:"text-sm",children:["Reviewer",e.jsx(me,{value:Y,onChange:Z=>G(Z.target.value),placeholder:"who receives the one-time link"})]}),e.jsxs("label",{className:"text-sm",children:["Reason",e.jsxs(Ie,{value:U,onChange:Z=>ae(Z.target.value),children:[e.jsx("option",{value:"first-draft",children:"first-draft"}),e.jsx("option",{value:"reissue-after-review",children:"reissue-after-review"})]})]}),e.jsx(K,{size:"sm",disabled:!Y.trim(),onClick:()=>void Ce(async()=>{const Z=Y.trim(),fe=Z.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"reviewer",re=await HR(t,le.mandate_ref,{user_id:`rev_${fe}`,name:Z},U);se(re)}),children:"Issue one-time link"}),W&&e.jsxs(H,{children:[e.jsxs("div",{className:"text-xs",children:["One-time link — expires ",new Date(W.expires_at).toLocaleString(),", shown only here:"]}),e.jsx("a",{className:"mt-1 block break-all font-mono text-xs underline",href:Jp(W.access_link),target:"_blank",rel:"noreferrer",children:Jp(W.access_link)}),e.jsx("div",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:W.access_link})]})]})]}),e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Reassign analyst (US-19.4 AC4)"}),e.jsxs("div",{className:"grid gap-2 px-3",children:[e.jsxs("label",{className:"text-sm",children:["From",e.jsx(pi,{value:k.from,placeholder:"pick the outgoing analyst",emptyLabel:"no analysts on the roster",onChange:Z=>R(fe=>({...fe,from:Z,to:fe.to===Z?"":fe.to})),options:h.map(Z=>({id:Z,hint:`${c[Z]??0} active`}))})]}),e.jsxs("label",{className:"text-sm",children:["To",e.jsx(pi,{value:k.to,placeholder:"pick the incoming analyst",emptyLabel:"no other analysts on the roster",onChange:Z=>R(fe=>({...fe,to:Z})),options:h.filter(Z=>Z!==k.from).map(Z=>({id:Z,hint:`${c[Z]??0} active`}))})]}),e.jsxs("label",{className:"text-sm",children:["HS6 line (optional — partial reassignment, empty = whole mandate)",e.jsx(pi,{value:k.line,placeholder:"all lines",emptyLabel:"no lines on this mandate",onChange:Z=>R(fe=>({...fe,line:Z})),options:((le==null?void 0:le.hs6_lines)??[]).map(Z=>({id:Z,hint:le!=null&&le.analysts[Z]?`→ ${le.analysts[Z]}`:"unassigned"}))})]}),e.jsx(K,{size:"sm",disabled:!k.from||!k.to,onClick:()=>void Ce(()=>Gp(t,le.mandate_ref,{from_analyst:k.from,to_analyst:k.to,hs6_line:k.line||null}),`Reassigned ${k.line?`line ${k.line}`:"the whole mandate"} to ${k.to}.`).then(Z=>{Z&&R({from:k.to,to:"",line:""})}),children:"Reassign"})]})]}),e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Cancel mandate (US-19.6 AC9)"}),e.jsxs("div",{className:"grid gap-2 px-3",children:[e.jsxs("label",{className:"text-sm",children:["Reason",e.jsx(Ie,{value:P,onChange:Z=>F(Z.target.value),children:xc.map(Z=>e.jsx("option",{value:Z,children:Z},Z))})]}),e.jsxs("label",{className:"text-sm",children:["Note",e.jsx(me,{value:I,onChange:Z=>M(Z.target.value),placeholder:"context for the audit trail"})]}),e.jsxs(K,{size:"sm",variant:"outline",onClick:()=>void Ce(()=>Zj(t,le.mandate_ref,{reason:P,note:I||null})),children:[e.jsx(nb,{size:13})," Cancel mandate"]})]})]}),w&&e.jsx(H,{tone:"error",children:w}),S&&e.jsx(H,{children:S})]})]})]})}function pP({identity:t}){var Ce,Ae;const[n,a]=i.useState(""),[o,c]=i.useState(null),[u,h]=i.useState(""),[m,x]=i.useState(""),[v,N]=i.useState(!1),[j,w]=i.useState(null),[_,S]=i.useState(null),[y,g]=i.useState(""),[p,k]=i.useState(""),[R,C]=i.useState(""),[E,P]=i.useState(""),[F,I]=i.useState(""),[M,$]=i.useState(""),[O,L]=i.useState(null),[z,Y]=i.useState(new Set),[G,U]=i.useState(""),[ae,W]=i.useState(""),se=i.useCallback(async Z=>{h(""),c(null),w(null),S(null),L(null),Y(new Set),U(""),W("");try{c(await PR(t,Z)),x(Z)}catch(fe){if(fe instanceof ul&&fe.code==="FREEZE_NOT_FOUND"){x(Z);return}x(""),h(fe instanceof Error?fe.message:"Load failed")}},[t]),ne=async()=>{N(!0),h("");try{w(await TR(t,n)),await se(n)}catch(Z){h(Z instanceof Error?Z.message:"Freeze failed")}finally{N(!1)}},q=async()=>{if(_){N(!0),h(""),L(null);try{L(await LR(t,m,{hs6:_.hs6,rationale:y,overrides:{...p&&{sonelgaz_tier:p},...R&&{gara_djebillet:{state:R,rationale:E}},...F!==""&&{import_adjustment:{percent:Number(F),source_citation:M}}}})),await se(m)}catch(Z){h(Z instanceof Error?Z.message:"Override failed")}finally{N(!1)}}},J=async()=>{N(!0),U("");try{await FR(t,m,[...z]),await se(m),W("Parameterization locked — the mandate is now in analysis.")}catch(Z){U(Z instanceof Error?Z.message:"Lock failed")}finally{N(!1)}},le=(o==null?void 0:o.lines.filter(Z=>Z.daps.high_protection))??[],ke=le.every(Z=>z.has(Z.hs6));return e.jsxs("div",{children:[e.jsx(Se,{title:"Analysis Workbench",description:"Freeze the analysis basis, apply audited overrides, then lock parameterization (US-19.2)"}),e.jsx(B,{className:"mt-4 gap-2 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-2 px-4",children:[e.jsx(me,{className:"max-w-64",value:n,onChange:Z=>a(Z.target.value),placeholder:"MND-2026-0001"}),e.jsx(K,{size:"sm",variant:"outline",disabled:!n,onClick:()=>void se(n),children:"Load mandate"}),m&&e.jsx(K,{size:"sm",disabled:v,onClick:()=>void ne(),children:"Freeze snapshot"})]})}),u&&e.jsx(H,{tone:"error",children:u}),j&&e.jsxs(H,{children:["Snapshot ",j.snapshot_id," v",j.version," frozen in ",j.elapsed_ms," ms — ",j.line_count," lines."]}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 rounded-md border border-border bg-secondary/50 p-3 text-sm",children:[e.jsx("strong",{children:"Analysis based on frozen data:"})," snapshot ",e.jsx("span",{className:"font-mono",children:o.freeze.snapshot_id})," v",o.freeze.version,", accepted ",new Date(o.freeze.acceptance_timestamp).toLocaleString()," (cycle ",o.freeze.cycle,"). Overrides and scoring run against this vintage only."]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-2",children:[e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Frozen lines"}),e.jsx("ul",{className:"grid gap-1.5 px-4",children:o.lines.map(Z=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{S(Z),L(null),g(""),k(""),C(""),P(""),I(""),$("")},className:`flex w-full items-center justify-between gap-2 rounded-md border px-2.5 py-1.5 text-left text-sm transition-colors ${(_==null?void 0:_.hs6)===Z.hs6?"border-primary bg-primary/10":"border-border hover:bg-accent"}`,children:[e.jsx("span",{className:"font-mono text-xs",children:Z.hs6}),e.jsxs("span",{className:"flex items-center gap-2",children:[Z.daps.high_protection&&e.jsxs(V,{variant:"warning",children:["DAPS ",Z.daps.rate_pct,"%"]}),Z.current_score!==null&&e.jsxs(V,{variant:"secondary",children:["CAS ",Z.current_score.toFixed(1)]}),Z.overrides.length>0&&e.jsxs(V,{variant:"success",children:[Z.overrides.length," override",Z.overrides.length>1?"s":""]})]})]})},Z.hs6))})]}),e.jsxs(B,{className:"gap-2 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Overrides ",_?`— ${_.hs6}`:""]}),_?e.jsxs("div",{className:"grid gap-2 px-4",children:[e.jsxs("label",{className:"text-sm",children:["Sonelgaz tier",e.jsxs(Ie,{value:p,onChange:Z=>k(Z.target.value),className:"mt-1","aria-label":"Sonelgaz tier",children:[e.jsx("option",{value:"",children:"unchanged"}),AR.map(Z=>e.jsx("option",{value:Z,children:Z},Z))]})]}),e.jsxs("label",{className:"text-sm",children:["Gara Djebillet state",e.jsxs(Ie,{value:R,onChange:Z=>C(Z.target.value),className:"mt-1","aria-label":"Gara Djebillet state",children:[e.jsx("option",{value:"",children:"unchanged"}),RR.map(Z=>e.jsx("option",{value:Z,children:Z},Z))]})]}),R&&e.jsxs("label",{className:"text-sm",children:["Gara rationale (≥50 chars)",e.jsx(me,{value:E,onChange:Z=>P(Z.target.value)})]}),e.jsxs("label",{className:"text-sm",children:["Import adjustment % (−100…+100)",e.jsx(me,{value:F,onChange:Z=>I(Z.target.value),placeholder:"−15"})]}),F!==""&&e.jsxs("label",{className:"text-sm",children:["Source citation (mandatory)",e.jsx(me,{value:M,onChange:Z=>$(Z.target.value),placeholder:"Journal Officiel n°…"})]}),e.jsxs("label",{className:"text-sm",children:["Rationale (mandatory — audit trail)",e.jsx(me,{value:y,onChange:Z=>g(Z.target.value)})]}),e.jsx(K,{size:"sm",disabled:v||!y.trim(),onClick:()=>void q(),children:"Apply override"}),O&&e.jsxs("div",{className:"rounded-md border border-border bg-secondary/50 p-2.5 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{children:["CAS ",((Ce=O.baseline)==null?void 0:Ce.score.toFixed(1))??"—"]}),e.jsx("span",{"aria-hidden":!0,children:"→"}),e.jsx("span",{className:"font-semibold",children:((Ae=O.overridden)==null?void 0:Ae.score.toFixed(1))??"—"}),O.delta!==null&&e.jsxs(V,{variant:O.delta<0?"danger":"success",children:["Δ ",O.delta>0?"+":"",O.delta.toFixed(1)]})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Recorded by ",O.record.applied_by," at ",new Date(O.record.applied_at).toLocaleString(),"."]})]})]}):e.jsx("p",{className:"px-4 text-sm text-muted-foreground",children:"Pick a frozen line to apply overrides."})]})]}),e.jsxs(B,{className:"mt-4 gap-2 border-warning/40 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"DAPS > 50% acknowledgement — non-dismissible (AC9)"}),e.jsxs("div",{className:"grid gap-1.5 px-4",children:[le.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No high-DAPS lines on this mandate — the lock stands unguarded."}):le.map(Z=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:z.has(Z.hs6),className:"size-4 accent-primary",onChange:fe=>Y(re=>{const Ee=new Set(re);return fe.target.checked?Ee.add(Z.hs6):Ee.delete(Z.hs6),Ee})}),e.jsx("span",{className:"font-mono text-xs",children:Z.hs6})," — duty ",Z.daps.rate_pct,"% acknowledged for this study"]},Z.hs6)),e.jsxs("div",{className:"mt-2 flex items-center gap-3",children:[e.jsx(K,{size:"sm",disabled:v||!ke,onClick:()=>void J(),children:"Lock parameterization"}),!ke&&e.jsx("span",{className:"text-xs text-warning",children:"Every high-DAPS line needs its acknowledgement before the lock."}),ae&&e.jsx("span",{className:"text-xs text-success",children:ae})]})]}),G&&e.jsx("div",{className:"mx-4 mt-2 rounded-md border border-destructive/40 bg-destructive/10 p-2 text-sm text-destructive",children:G})]})]})]})}const gP=5*1024*1024,vP=2*1024*1024,jP=new Set(["image/png","image/svg+xml"]),tg=/^#[0-9a-fA-F]{6}$/;async function sg(t,n,a){if(!jP.has(t.type))throw new Error(`${a}: PNG or SVG only (got ${t.type||"unknown"})`);if(t.size>n)throw new Error(`${a}: exceeds ${n/1024/1024} MB (${(t.size/1024/1024).toFixed(1)} MB)`);const o=await new Promise((c,u)=>{const h=new FileReader;h.onload=()=>c(String(h.result)),h.onerror=()=>u(new Error(`${a}: could not read the file`)),h.readAsDataURL(t)});return{content_type:t.type,size_bytes:t.size,data_base64:o.slice(o.indexOf(",")+1)}}function yP({identity:t}){const[n,a]=i.useState(""),[o,c]=i.useState(""),[u,h]=i.useState("#1d4ed8"),[m,x]=i.useState("#0f172a"),[v,N]=i.useState(null),[j,w]=i.useState(null),[_,S]=i.useState(""),[y,g]=i.useState(""),[p,k]=i.useState(""),[R,C]=i.useState(""),[E,P]=i.useState(null),[F,I]=i.useState(null),[M,$]=i.useState(""),[O,L]=i.useState(!1),z=async()=>{L(!0),$(""),P(null),I(null);try{const U=await DR(t,n,{client_name:o,primary_logo:v,secondary_logo:j,primary_colour:u,secondary_colour:m,titles:{ar:{title:_,...y&&{subtitle:y}},fr:{title:p},en:{title:R}}});P(U.preview)}catch(U){$(U instanceof Error?U.message:"Upload failed")}finally{L(!1)}},Y=async()=>{L(!0),$("");try{I(await $R(t,n))}catch(U){$(U instanceof Error?U.message:"Apply failed")}finally{L(!1)}},G=n.trim()&&o.trim()&&v&&tg.test(u)&&tg.test(m)&&_.length<=100&&y.length<=150&&p.length<=100&&R.length<=100;return e.jsxs("div",{children:[e.jsx(Se,{title:"White-Label Branding",description:"Upload the client's brand profile, preview the cover, then apply — the 2h SLA starts (US-19.3)"}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-2",children:[e.jsxs(B,{className:"gap-3 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Brand profile"}),e.jsxs("div",{className:"grid gap-2 px-4",children:[e.jsxs("label",{className:"text-sm",children:["Mandate",e.jsx(me,{value:n,onChange:U=>a(U.target.value),placeholder:"MND-2026-0001"})]}),e.jsxs("label",{className:"text-sm",children:["Client name",e.jsx(me,{value:o,onChange:U=>c(U.target.value),placeholder:"African Development Bank"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("label",{className:"text-sm",children:["Primary colour",e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("input",{type:"color",value:u,onChange:U=>h(U.target.value),"aria-label":"Primary colour picker",className:"size-9 rounded-md border border-border bg-secondary p-1"}),e.jsx(me,{value:u,onChange:U=>h(U.target.value),className:"font-mono text-xs"})]})]}),e.jsxs("label",{className:"text-sm",children:["Secondary colour",e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("input",{type:"color",value:m,onChange:U=>x(U.target.value),"aria-label":"Secondary colour picker",className:"size-9 rounded-md border border-border bg-secondary p-1"}),e.jsx(me,{value:m,onChange:U=>x(U.target.value),className:"font-mono text-xs"})]})]})]}),e.jsxs("label",{className:"text-sm",children:["Primary logo (PNG/SVG ≤5 MB)",e.jsx("input",{type:"file",accept:"image/png,image/svg+xml",className:"mt-1 block w-full text-sm text-muted-foreground file:mr-2 file:rounded-md file:border-0 file:bg-secondary file:px-2 file:py-1.5 file:text-xs file:text-foreground",onChange:U=>{var W;const ae=(W=U.target.files)==null?void 0:W[0];ae&&sg(ae,gP,"Primary logo").then(N,se=>$(se.message))}})]}),e.jsxs("label",{className:"text-sm",children:["Secondary logo (optional, ≤2 MB)",e.jsx("input",{type:"file",accept:"image/png,image/svg+xml",className:"mt-1 block w-full text-sm text-muted-foreground file:mr-2 file:rounded-md file:border-0 file:bg-secondary file:px-2 file:py-1.5 file:text-xs file:text-foreground",onChange:U=>{var W;const ae=(W=U.target.files)==null?void 0:W[0];ae&&sg(ae,vP,"Secondary logo").then(w,se=>$(se.message))}})]}),e.jsxs("label",{className:"text-sm",children:["AR title (≤100)",e.jsx(me,{dir:"rtl",lang:"ar",value:_,onChange:U=>S(U.target.value),maxLength:100})]}),e.jsxs("label",{className:"text-sm",children:["AR subtitle (≤150)",e.jsx(me,{dir:"rtl",lang:"ar",value:y,onChange:U=>g(U.target.value),maxLength:150})]}),e.jsxs("label",{className:"text-sm",children:["FR title (≤100)",e.jsx(me,{value:p,onChange:U=>k(U.target.value),maxLength:100})]}),e.jsxs("label",{className:"text-sm",children:["EN title (≤100)",e.jsx(me,{value:R,onChange:U=>C(U.target.value),maxLength:100})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{size:"sm",disabled:O||!G,onClick:()=>void z(),children:O?"Saving…":"Validate & save draft"}),E&&e.jsx(K,{size:"sm",variant:"outline",disabled:O,onClick:()=>void Y(),children:"Apply branding"})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[E&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Live cover preview"}),e.jsxs("div",{className:"mx-4 overflow-hidden rounded-lg border",style:{borderColor:E.cover_thumbnail.primary_colour},children:[e.jsxs("div",{className:"flex items-center gap-3 p-4",style:{background:E.cover_thumbnail.primary_colour},children:[e.jsx("div",{className:"grid size-12 place-items-center rounded bg-white/90 text-xs font-bold",style:{color:E.cover_thumbnail.primary_colour},children:"LOGO"}),e.jsxs("div",{children:[e.jsx("div",{dir:"rtl",lang:"ar",className:"text-lg font-bold text-white",children:E.cover_thumbnail.titles.ar.title}),e.jsx("div",{dir:"rtl",lang:"ar",className:"text-xs text-white/85",children:E.cover_thumbnail.titles.ar.subtitle})]})]}),e.jsxs("div",{className:"grid gap-0.5 bg-card p-3 text-sm",children:[e.jsx("div",{lang:"fr",className:"font-semibold",style:{color:E.cover_thumbnail.primary_colour},children:E.cover_thumbnail.titles.fr.title}),e.jsx("div",{lang:"en",className:"text-muted-foreground",children:E.cover_thumbnail.titles.en.title}),e.jsxs("div",{className:"mt-1 text-[10px] text-muted-foreground",children:["Footer attribution 8pt · logo ≥",E.template_constraints.logo_min_height_px,"px @ ",E.template_constraints.dpi," DPI"]})]})]}),e.jsxs("div",{className:"flex gap-2 px-4",children:[e.jsx("span",{className:"inline-block size-5 rounded border border-border",style:{background:E.cover_thumbnail.primary_colour},"aria-label":"Primary colour swatch"}),e.jsx("span",{className:"inline-block size-5 rounded border border-border",style:{background:E.cover_thumbnail.secondary_colour},"aria-label":"Secondary colour swatch"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Primary ",E.cover_thumbnail.primary_colour," · secondary ",E.cover_thumbnail.secondary_colour]})]})]}),e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Sample API envelope (AC5)"}),e.jsx("pre",{className:"mx-4 overflow-x-auto rounded-md border border-border bg-secondary/50 p-2.5 text-xs",children:JSON.stringify(E.sample_api_envelope,null,2)}),e.jsxs("p",{className:"px-4 text-xs text-muted-foreground",children:["Non-suppressible sections: ",E.template_constraints.non_suppressible_sections.join(" · ")]})]})]}),F&&e.jsxs(B,{className:"gap-1 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Applied ",e.jsx(V,{variant:"success",children:"2h SLA running"})]}),e.jsxs("p",{className:"px-4 text-sm",children:["Application document: ",e.jsx("span",{className:"font-mono text-xs",children:F.application_document_id??"—"})]}),F.re_application&&e.jsxs("p",{className:"px-4 text-sm text-muted-foreground",children:["Re-application — future PDFs only; ",F.free_regeneration_available?"free re-generation available for delivered documents":"re-generation not available"," (AC7)."]})]})]})]}),M&&e.jsx(H,{tone:"error",children:M})]})}const _P=["government","bilateral_donor","private"],os=t=>`$${t.toLocaleString("en-US")}`,ng=t=>t===null?"—":`${t.toLocaleString("en-US")} DA`;function bP({identity:t}){const[n,a]=i.useState(null),[o,c]=i.useState(""),[u,h]=i.useState(null),[m,x]=i.useState(null),[v,N]=i.useState(""),[j,w]=i.useState(""),[_,S]=i.useState(xc[0]),[y,g]=i.useState(""),[p,k]=i.useState(null),[R,C]=i.useState(!1),E=i.useCallback(()=>IR(t).then(a,M=>c(M instanceof Error?M.message:"Dashboard load failed")),[t]);i.useEffect(()=>{E()},[E]);const P=async M=>{h(M),x(null),N(""),w("");try{x(await MR(t,M))}catch($){N($ instanceof Error?$.message:"Detail load failed")}},F=async(M,$)=>{w(""),C(!0);try{await M(),u&&await P(u),await E()}catch(O){w(O instanceof Error?O.message:"Action failed")}finally{C(!1)}},I=async()=>{w(""),C(!0),k(null);try{const M=await VR(t);k({certification:M.certification,cutoff:M.data_cutoff_at,files:M.documents.map($=>$.filename)});for(const $ of M.documents){const O=new Blob([nh($)],{type:$.content_type}),L=URL.createObjectURL(O),z=document.createElement("a");z.href=L,z.download=$.filename,z.click(),URL.revokeObjectURL(L)}}catch(M){w(M instanceof Error?M.message:"Export failed")}finally{C(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Revenue & Contracts",description:"Contract values by segment, invoice ageing, reconciliation and the board export (US-19.6)",actions:e.jsx(K,{size:"sm",variant:"outline",disabled:R,onClick:()=>void I(),children:"Export board report (PDF + XLSX)"})}),(n==null?void 0:n.billing_banner)&&e.jsx("div",{className:"mt-3 rounded-md border border-warning/40 bg-warning/10 p-3 text-sm text-warning",role:"alert",children:n.billing_banner}),o&&e.jsx(H,{tone:"error",children:o}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-3 md:grid-cols-4",children:[["ytd","qtd","mtd"].map(M=>e.jsxs(B,{className:"gap-1 p-3",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:M}),e.jsx("div",{className:"text-lg font-bold",children:os(n.summary[M].total)}),e.jsx("div",{className:"grid gap-0.5 text-[11px] text-muted-foreground",children:_P.map($=>e.jsxs("div",{children:[$.replace("_"," "),": ",os(n.summary[M][$]??0)]},$))})]},M)),e.jsxs(B,{className:"gap-1 p-3",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Overdue receivables"}),e.jsx("div",{className:`text-lg font-bold ${n.overdue_receivables_usd>0?"text-destructive":""}`,children:os(n.overdue_receivables_usd)}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["ageing 0–30: ",os(n.ageing["0-30"])," · 31–60: ",os(n.ageing["31-60"])," · >60: ",os(n.ageing[">60"])]})]})]}),e.jsx(B,{className:"mt-4 overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Mandate"}),e.jsx(T,{children:"Organisation"}),e.jsx(T,{children:"Segment"}),e.jsx(T,{children:"Status"}),e.jsx(T,{className:"text-right",children:"Contract (USD)"}),e.jsx(T,{className:"text-right",children:"Contract (DZD)"}),e.jsx(T,{children:"Invoices"}),e.jsx(T,{children:"Reconciliation"})]})}),e.jsxs(ye,{children:[n.rows.map(M=>e.jsxs(ee,{className:"cursor-pointer",onClick:()=>void P(M.mandate_ref),children:[e.jsx(A,{className:"font-mono text-xs",children:M.mandate_ref}),e.jsx(A,{children:M.client_org}),e.jsx(A,{className:"text-muted-foreground",children:M.segment.replace("_"," ")}),e.jsx(A,{children:M.mandate_status}),e.jsx(A,{className:"text-right font-medium tabular-nums",children:os(M.contract_value_usd)}),e.jsx(A,{className:"text-right text-muted-foreground tabular-nums",children:ng(M.contract_value_dzd)}),e.jsx(A,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:[M.upfront_invoice,M.delivery_invoice].filter($=>$!==null).map($=>e.jsxs(V,{variant:$.overdue?"danger":$.status==="paid"?"success":"secondary",children:[$.kind," ",$.status]},$.invoice_id))})}),e.jsx(A,{children:M.reconciliation==="Reconciled"?e.jsx(V,{variant:"success",children:"reconciled"}):e.jsx(V,{variant:"warning",children:"pending"})})]},M.mandate_ref)),n.rows.length===0&&e.jsx(ee,{children:e.jsx(A,{colSpan:8,className:"py-3 text-center text-muted-foreground",children:"No revenue records yet."})})]})]})}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Generated ",new Date(n.generated_at).toLocaleString()]})]}),p&&e.jsxs(B,{className:"mt-4 gap-1 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Board export"}),e.jsx("p",{className:"px-4 text-sm",children:p.certification}),e.jsxs("p",{className:"px-4 text-xs text-muted-foreground",children:["Data cutoff ",new Date(p.cutoff).toLocaleString()," · downloaded: ",p.files.join(", ")]})]}),u&&e.jsxs("div",{className:"fixed inset-0 z-50",children:[e.jsx("button",{type:"button","aria-label":"Close detail slide-over",className:"absolute inset-0 bg-black/60",onClick:()=>h(null)}),e.jsxs("aside",{className:"absolute inset-y-0 right-0 w-full max-w-md overflow-y-auto border-l border-border bg-card p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-mono text-base font-semibold",children:u}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(m==null?void 0:m.client_org)??"…"," · ",(m==null?void 0:m.segment.replace("_"," "))??""]})]}),e.jsx(K,{size:"sm",variant:"outline",onClick:()=>h(null),children:"Close"})]}),v&&e.jsx(H,{tone:"error",children:v}),j&&e.jsx(H,{tone:"error",children:j}),m&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"mt-4 gap-1 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Fee breakdown"}),e.jsxs("dl",{className:"grid gap-1 px-3 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Base study"}),e.jsx("dd",{children:os(m.fee_breakdown.baseStudyUsd)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Additional lines"}),e.jsx("dd",{children:os(m.fee_breakdown.additionalLineFeesUsd)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"CAPEX adjustment"}),e.jsx("dd",{children:os(m.fee_breakdown.capexAdjustmentUsd)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Arabic summary"}),e.jsx("dd",{children:os(m.fee_breakdown.arabicSummaryUsd)})]}),m.scope_change_additions_usd>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Scope-change additions"}),e.jsx("dd",{children:os(m.scope_change_additions_usd)})]}),e.jsxs("div",{className:"mt-1 flex justify-between border-t border-border pt-1 font-semibold",children:[e.jsx("dt",{children:"Contract value"}),e.jsxs("dd",{children:[os(m.contract_value_usd)," · ",ng(m.contract_value_dzd)]})]})]}),m.dzd_rate&&e.jsxs("p",{className:"px-3 text-xs text-muted-foreground",children:["DZD rate ",m.dzd_rate.rate," at ",new Date(m.dzd_rate.at).toLocaleDateString()]})]}),e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Invoice history"}),e.jsxs("ul",{className:"grid gap-1.5 px-3",children:[m.invoice_history.map(M=>e.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md border border-border px-2.5 py-1.5 text-sm",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-mono text-xs",children:[M.invoice_id," · ",M.kind]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[os(M.amount_usd)," · due ",new Date(M.due_at).toLocaleDateString(),M.paid_at?` · paid ${new Date(M.paid_at).toLocaleDateString()}`:""]})]}),M.status==="paid"?e.jsx(V,{variant:"success",children:"paid"}):M.overdue?e.jsx(V,{variant:"danger",children:"overdue"}):e.jsx(K,{size:"sm",variant:"outline",disabled:R,onClick:()=>void F(()=>OR(t,u,M.invoice_id)),children:"Record payment"})]},M.invoice_id)),m.invoice_history.length===0&&e.jsx("li",{className:"text-sm text-muted-foreground",children:"No invoices yet."})]})]}),e.jsxs(B,{className:"mt-4 gap-2 py-3",children:[e.jsx("h3",{className:"px-3 text-sm font-semibold",children:"Delivery & cancellation"}),e.jsxs("div",{className:"grid gap-2 px-3",children:[e.jsx(K,{size:"sm",disabled:R,onClick:()=>void F(()=>zR(t,u)),children:"Record delivery — invoice remaining 50%"}),e.jsxs("label",{className:"text-sm",children:["Cancellation reason",e.jsx(Ie,{value:_,onChange:M=>S(M.target.value),children:xc.map(M=>e.jsx("option",{value:M,children:M},M))})]}),e.jsxs("label",{className:"text-sm",children:["Note",e.jsx(me,{value:y,onChange:M=>g(M.target.value),placeholder:"context for the audit trail"})]}),e.jsx(K,{size:"sm",variant:"outline",disabled:R,onClick:()=>void F(()=>Zj(t,u,{reason:_,note:y||null})),children:"Cancel mandate"})]})]})]})]})]})]})}const rg=t=>`$${t.toLocaleString("en-US")}`;function NP({identity:t,initialRef:n=""}){const[a,o]=i.useState(n),[c,u]=i.useState(null),[h,m]=i.useState(""),[x,v]=i.useState(""),[N,j]=i.useState(!1),[w,_]=i.useState(null),S=async g=>{m(""),u(null),_(null),v("");try{u(await Wp(t,g))}catch(p){m(p instanceof Error?p.message:"Load failed")}};i.useEffect(()=>{if(!n)return;let g=!0;return Wp(t,n).then(p=>{g&&(m(""),u(p),o(p.scr_ref),_(null),v(""))},p=>{g&&(m(p instanceof Error?p.message:"Load failed"),u(null),_(null))}),()=>{g=!1}},[t,n]);const y=async g=>{if(c){j(!0),m("");try{const p=await GR(t,c.scr_ref,g,g==="reject"?x:void 0);_({approved:g==="approve",freeze_version:p.freeze_version,supplemental_invoice_id:p.supplemental_invoice_id}),await S(c.scr_ref)}catch(p){m(p instanceof Error?p.message:"Decision failed")}finally{j(!1)}}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Scope Change Review",description:"Review a submitted SCR at the original freeze vintage — approve reopens parameterization, reject resumes the SLA",meta:c?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"SCR"}),e.jsx("span",{className:"font-mono",children:c.scr_ref})]}):void 0}),e.jsx(B,{className:"mt-4 gap-2 py-4",children:e.jsxs("div",{className:"flex gap-2 px-4",children:[e.jsx(me,{className:"max-w-64",value:a,onChange:g=>o(g.target.value),placeholder:"SCR-2026-0001"}),e.jsx(K,{size:"sm",variant:"outline",disabled:!a,onClick:()=>void S(a),children:"Load SCR"})]})}),h&&e.jsx(H,{tone:"error",children:h}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[e.jsx("h2",{className:"font-mono text-base font-semibold",children:c.scr_ref}),e.jsx(V,{variant:c.status==="pending"?"warning":c.status==="approved"?"success":"danger",children:c.status}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["on ",e.jsx("span",{className:"font-mono",children:c.mandate_ref})," (",c.mandate_status,") · submitted by ",c.submitted_by," at ",new Date(c.submitted_at).toLocaleString()]})]}),e.jsxs(B,{className:"mt-3 gap-2 py-4",children:[e.jsx("h3",{className:"px-4 text-sm font-semibold",children:"Requester's reason"}),e.jsx("blockquote",{className:"mx-4 border-l-2 border-border pl-3 text-sm text-muted-foreground",children:c.reason})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-2",children:[e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h3",{className:"px-4 text-sm font-semibold",children:"Original frozen scope (read-only)"}),e.jsx("ul",{className:"grid gap-1 px-4 text-sm",children:c.original_frozen.map(g=>e.jsxs("li",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono text-xs",children:g.hs6}),g.daps.high_protection?e.jsxs(V,{variant:"warning",children:["DAPS ",g.daps.rate_pct,"%"]}):e.jsxs("span",{className:"text-xs text-muted-foreground",children:["DAPS ",g.daps.rate_pct??"—","%"]})]},g.hs6))})]}),e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h3",{className:"px-4 text-sm font-semibold",children:"Added lines — preview at the original vintage"}),e.jsx("ul",{className:"grid gap-1.5 px-4 text-sm",children:c.added_lines.map(g=>e.jsxs("li",{className:"rounded-md border border-border px-2.5 py-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono text-xs",children:g.hs6}),g.daps.high_protection&&e.jsxs(V,{variant:"warning",children:["DAPS ",g.daps.rate_pct,"%"]})]}),e.jsx("div",{children:g.label_fr??"—"}),e.jsx("div",{dir:"rtl",lang:"ar",className:"text-muted-foreground",children:g.label_ar??"—"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Baseline CAS ",g.baseline_cas_score!==null?g.baseline_cas_score.toFixed(1):"—"]})]},g.hs6))})]})]}),e.jsxs(B,{className:"mt-4 gap-1 py-4",children:[e.jsx("h3",{className:"px-4 text-sm font-semibold",children:"Impact"}),e.jsxs("dl",{className:"grid gap-1 px-4 text-sm sm:grid-cols-2",children:[e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Estimated effort"}),e.jsxs("dd",{children:[c.estimated_hours," analyst-hours"]})]}),e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Supplemental fee"}),e.jsx("dd",{children:rg(c.supplemental_fee_usd)})]}),e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Revised contract"}),e.jsx("dd",{className:"font-semibold",children:rg(c.revised_fee_usd)})]}),e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Revised first-draft deadline"}),e.jsx("dd",{children:new Date(c.revised_deadline).toLocaleDateString()})]})]})]}),c.status==="pending"?e.jsxs(B,{className:"mt-4 gap-2 py-4",children:[e.jsx("h3",{className:"px-4 text-sm font-semibold",children:"Decision"}),e.jsxs("div",{className:"grid gap-2 px-4",children:[e.jsxs("label",{className:"text-sm",children:["Rejection reason (required to reject — audited)",e.jsx(me,{value:x,onChange:g=>v(g.target.value),placeholder:"why this belongs in a separate mandate"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{size:"sm",disabled:N,onClick:()=>void y("approve"),children:"Approve — extend scope"}),e.jsx(K,{size:"sm",variant:"outline",disabled:N||!x.trim(),onClick:()=>void y("reject"),children:"Reject — offer new mandate"})]})]})]}):w?e.jsx(H,{children:w.approved?`Approved — freeze extension v${w.freeze_version} written at the original acceptance timestamp; supplemental invoice ${w.supplemental_invoice_id}. The mandate is back in parameterization.`:"Rejected — the SLA clock resumed with pause credit; the requester has been offered a separate new mandate."}):e.jsxs(H,{children:["This SCR is already ",c.status,"."]})]})]})}const wP=t=>`$${t.toLocaleString("en-US")}`,SP={pending:"warning",approved:"success",rejected:"danger"};function CP({identity:t,onOpen:n}){const[a,o]=i.useState(""),[c,u]=i.useState([]),[h,m]=i.useState(null),[x,v]=i.useState(""),[N,j]=i.useState(null),[w,_]=i.useState(null),[S,y]=i.useState(!1),g=w===a?"error":N!==a?"loading":c.length===0?"empty":"ok",p=i.useCallback(async()=>qp(t,a?{status:a}:{}),[t,a]),k=i.useCallback(P=>{u(P.scrs),m(P.next_cursor)},[]);i.useEffect(()=>{let P=!0;return p().then(F=>{P&&(k(F),j(a),_(null))},F=>{P&&(v(F instanceof Error?F.message:"Unknown error"),_(a),j(null))}),()=>{P=!1}},[p,k,a]);const R=i.useCallback(()=>(j(null),_(null),p().then(k,P=>{v(P instanceof Error?P.message:"Unknown error"),_(a),j(null)})),[p,k,a]),C=i.useCallback(async()=>{if(h){y(!0);try{const P=await qp(t,{status:a||void 0,cursor:h});u(F=>[...F,...P.scrs]),m(P.next_cursor)}catch(P){v(P instanceof Error?P.message:"Unknown error"),_(a),j(null)}finally{y(!1)}}},[h,t,a]),E=c.filter(P=>P.status==="pending").length;return e.jsxs("div",{children:[e.jsx(Se,{title:"Scope Change Queue",description:"Every SCR across mandates, newest first · pending requests pause their mandate's clock",meta:g==="ok"?e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[c.length," shown"]}),e.jsxs("span",{children:[E," awaiting decision"]})]}):void 0,actions:e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:["Status",e.jsxs(Ie,{value:a,onChange:P=>o(P.target.value),"aria-label":"Filter by status",disabled:S,className:"w-32",children:[e.jsx("option",{value:"",children:"All"}),e.jsx("option",{value:"pending",children:"Pending"}),e.jsx("option",{value:"approved",children:"Approved"}),e.jsx("option",{value:"rejected",children:"Rejected"})]})]})}),g==="loading"&&e.jsx(H,{children:"Loading the queue…"}),g==="error"&&e.jsxs(H,{tone:"error",children:["Could not load the queue: ",x,e.jsx("div",{className:"mt-3",children:e.jsx(K,{size:"sm",onClick:()=>void R(),children:"Retry"})})]}),g==="empty"&&e.jsx(Ci,{icon:mb,title:a===""?"No scope-change requests yet":`No ${a} requests`,hint:"Requests arrive from the client portal; review is due within one business day (US-19.8 AC3)."}),g==="ok"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{className:"overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"SCR"}),e.jsx(T,{children:"Mandate · client"}),e.jsx(T,{children:"Added lines"}),e.jsx(T,{className:"text-right",children:"Revised fee"}),e.jsx(T,{children:"Status"}),e.jsx(T,{children:"Submitted"}),e.jsx(T,{children:"Decided"})]})}),e.jsx(ye,{children:c.map(P=>e.jsxs(ee,{onClick:()=>n(P.scr_ref),className:"cursor-pointer",children:[e.jsx(A,{className:"font-mono text-xs",children:P.scr_ref}),e.jsxs(A,{children:[e.jsx("div",{className:"font-mono text-xs",children:P.mandate_ref}),e.jsx("div",{className:"text-muted-foreground",children:P.client_org})]}),e.jsx(A,{className:"font-mono text-xs",children:P.added_lines.join(", ")}),e.jsx(A,{className:"text-right tabular-nums",children:wP(P.revised_fee_usd)}),e.jsx(A,{children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(V,{variant:SP[P.status],children:P.status}),P.sla_paused&&e.jsxs(V,{variant:"secondary",className:"gap-1",children:[e.jsx(ib,{size:11})," clock paused"]})]})}),e.jsx(A,{className:"text-muted-foreground",children:new Date(P.submitted_at).toLocaleDateString()}),e.jsx(A,{className:"text-muted-foreground",children:P.decided_at?e.jsxs(e.Fragment,{children:[e.jsx("div",{children:new Date(P.decided_at).toLocaleDateString()}),P.supplemental_invoice_id&&e.jsx("div",{className:"font-mono text-[11px]",children:P.supplemental_invoice_id})]}):"—"})]},P.scr_ref))})]})}),h&&e.jsx("div",{className:"mt-3",children:e.jsx(K,{variant:"outline",size:"sm",disabled:S,onClick:()=>void C(),children:S?"Loading…":"Load more"})})]})]})}const kP=/[؀-ۿݐ-ݿࢠ-ࣿﭐ-﷿ﹰ-]/,dl=t=>kP.test(t)?"rtl":"ltr",gi=t=>`${(t*100).toFixed(1)}%`,ag={generating:"secondary",generated:"warning",in_review:"warning",approved:"success"};function EP({identity:t}){const[n,a]=i.useState(null),[o,c]=i.useState(null),[u,h]=i.useState([]),[m,x]=i.useState(""),[v,N]=i.useState(""),[j,w]=i.useState(null),[_,S]=i.useState(null),[y,g]=i.useState("terminology-error"),[p,k]=i.useState(""),[R,C]=i.useState(""),[E,P]=i.useState([]),[F,I]=i.useState(!1),[M,$]=i.useState(""),O=async()=>{x("");try{const[W,se,ne]=await Promise.all([QR(t),Qp(t),Kp(t)]);a(W),c(se),h(ne.pending)}catch(W){x(W instanceof Error?W.message:"Fleet load failed")}},L=async W=>{x(""),$(""),P([]),S(null);try{w(await XR(t,W))}catch(se){x(se instanceof Error?se.message:"Load failed")}},z=j!==null&&(j.summary.state==="generated"||j.summary.state==="in_review"),Y=()=>{_!==null&&(P(W=>[...W,{id:Date.now(),sentence_index:_,flag_type:y,comment:p,correction:R||null}]),S(null),k(""),C(""))},G=async()=>{if(!(!j||E.length===0)){I(!0),x("");try{const{summary:W,correction_rate:se}=await YR(t,j.summary.mandate_ref,E.map(({sentence_index:ne,flag_type:q,comment:J,correction:le})=>({sentence_index:ne,flag_type:q,comment:J,correction:le})));$(se?`Review v${W.version} recorded — correction rate ${gi(se.rate)} (${se.corrected_terms}/${se.covered_terms} TM-covered terms corrected).`:`Review v${W.version} recorded.`),P([]),await L(j.summary.mandate_ref)}catch(W){x(W instanceof Error?W.message:"Submit failed")}finally{I(!1)}}},U=async()=>{if(j){I(!0),x("");try{await ZR(t,j.summary.mandate_ref),$("Review complete — the approved chapter is catalogued with the final package and the client notification released (once)."),await L(j.summary.mandate_ref)}catch(W){x(W instanceof Error?W.message:"Completion failed")}finally{I(!1)}}},ae=async(W,se)=>{I(!0),x("");try{const ne=await KR(t,W,se);$(se==="apply"?`Feedback applied — canon change ${ne.change_id} on ${ne.term_id}.`:`Feedback rejected — ${W} closed without a canon change.`),h(await(await Kp(t)).pending),c(await Qp(t))}catch(ne){x(ne instanceof Error?ne.message:"Resolve failed")}finally{I(!1)}};return e.jsxs("div",{children:[e.jsx(Se,{title:"Arabic Review & Terminology",description:"Side-by-side review of the Arabic executive summary, the correction-rate meter, and the translation-memory canon (US-19.7)",actions:e.jsx(K,{size:"sm",variant:"outline",disabled:F,onClick:()=>void O(),children:"Load fleet"})}),m&&e.jsx(H,{tone:"error",children:m}),M&&e.jsx(H,{children:M}),n&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"mt-4 gap-2 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["Correction-rate meter — fleet pooled, target ≤ ",gi(qR)]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-4 text-sm",children:[e.jsx("span",{className:"text-2xl font-semibold tabular-nums",children:gi(n.fleet.rate)}),e.jsx(V,{variant:n.fleet.rate>Xu?"danger":n.fleet.within_target?"success":"warning",children:n.fleet.rate>Xu?`above the ${gi(Xu)} escalation bar`:n.fleet.within_target?"within target":"above target"}),e.jsxs("span",{className:"text-muted-foreground",children:[n.fleet.total_corrected_terms,"/",n.fleet.total_covered_terms," covered terms corrected across ",n.fleet.reviewed," reviewed summar",n.fleet.reviewed===1?"y":"ies","."]})]})]}),e.jsx(B,{className:"mt-3 overflow-hidden py-0",children:e.jsxs(je,{children:[e.jsx(_e,{children:e.jsxs(ee,{children:[e.jsx(T,{children:"Mandate"}),e.jsx(T,{children:"State"}),e.jsx(T,{className:"text-right",children:"Words"}),e.jsx(T,{className:"text-right",children:"Flags"}),e.jsx(T,{children:"Rate"}),e.jsx(T,{children:"Escalation"})]})}),e.jsx(ye,{children:n.rows.map(W=>e.jsxs(ee,{children:[e.jsx(A,{children:e.jsx("button",{type:"button",className:"font-mono text-xs hover:text-primary hover:underline",onClick:()=>{N(W.mandate_ref),L(W.mandate_ref)},children:W.mandate_ref})}),e.jsx(A,{children:e.jsx(V,{variant:ag[W.state],children:W.state.replace("_"," ")})}),e.jsx(A,{className:"text-right tabular-nums",children:W.word_count??"—"}),e.jsx(A,{className:"text-right tabular-nums",children:W.flags}),e.jsx(A,{className:"tabular-nums",children:W.correction_rate?`${gi(W.correction_rate.rate)} (${W.correction_rate.corrected_terms}/${W.correction_rate.covered_terms})`:"—"}),e.jsx(A,{children:W.escalated===!0?e.jsx(V,{variant:"danger",children:"escalated"}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})]},W.mandate_ref))})]})})]}),e.jsx(B,{className:"mt-4 gap-2 py-4",children:e.jsxs("div",{className:"flex gap-2 px-4",children:[e.jsx(me,{className:"max-w-64",value:v,onChange:W=>N(W.target.value),placeholder:"MND-2026-0001"}),e.jsx(K,{size:"sm",variant:"outline",disabled:!v,onClick:()=>void L(v),children:"Load summary"})]})}),j&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[e.jsx("h2",{className:"font-mono text-base font-semibold",children:j.summary.mandate_ref}),e.jsx(V,{variant:ag[j.summary.state],children:j.summary.state.replace("_"," ")}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[j.summary.draft_word_count??"—"," draft words · canon snapshot ",j.summary.tm_snapshot.length," terms",j.summary.reviewer&&` · reviewer ${j.summary.reviewer}`]})]}),e.jsxs("div",{className:"mt-3 grid gap-4 lg:grid-cols-3",children:[e.jsx("div",{className:"grid gap-4 lg:col-span-2",children:e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h3",{className:"px-4 text-sm font-semibold",children:"Side-by-side review — French source ⇄ Arabic draft"}),e.jsx("ul",{className:"grid gap-1.5 px-4",children:j.alignment.map((W,se)=>{const ne=j.summary.flags.filter(q=>q.sentence_index===se);return e.jsxs("li",{className:`rounded-md border p-2.5 ${_===se?"border-primary bg-primary/10":"border-border"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"text-sm",children:W.source_sentence}),e.jsx("button",{type:"button",disabled:!z,onClick:()=>{S(se),k(""),C("")},className:"shrink-0 rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40",children:"Flag"})]}),e.jsx("p",{dir:"rtl",lang:"ar",className:`mt-1.5 text-sm ${W.arabic_sentence===null?"italic text-destructive":""}`,children:W.arabic_sentence??"— no aligned Arabic sentence (missing source content) —"}),ne.length>0&&e.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:ne.map(q=>e.jsxs("span",{className:"rounded-md bg-secondary px-2 py-0.5 text-xs",children:[q.flag_type,": ",q.comment,q.correction!==null&&e.jsxs(e.Fragment,{children:[" → ",e.jsxs("bdi",{dir:dl(q.correction),lang:dl(q.correction)==="rtl"?"ar":void 0,children:["“",q.correction,"”"]})]})]},q.flag_id))})]},se)})})]})}),e.jsx("div",{className:"grid content-start gap-4",children:e.jsxs(B,{className:"gap-2 py-4",children:[e.jsxs("h3",{className:"px-4 text-sm font-semibold",children:["Flag a sentence ",_!==null?`— #${_}`:""]}),z?_===null?e.jsx("p",{className:"px-4 text-sm text-muted-foreground",children:"Pick “Flag” on an aligned pair to annotate it."}):e.jsxs("div",{className:"grid gap-2 px-4",children:[e.jsxs("label",{className:"text-sm",children:["Flag type",e.jsx(Ie,{value:y,onChange:W=>g(W.target.value),children:WR.map(W=>e.jsx("option",{value:W,children:W.replace("-"," ")},W))})]}),e.jsxs("label",{className:"text-sm",children:["Comment (required)",e.jsx(me,{value:p,onChange:W=>k(W.target.value)})]}),e.jsxs("label",{className:"text-sm",children:["Corrected Arabic sentence (applied in place)",e.jsx("textarea",{dir:"rtl",lang:"ar",value:R,onChange:W=>C(W.target.value),rows:3,className:"mt-1 w-full rounded-md border border-border bg-secondary px-2 py-1.5 text-sm text-foreground"})]}),e.jsx(K,{size:"sm",variant:"outline",disabled:!p.trim(),onClick:Y,children:"Add to review"})]}):e.jsxs("p",{className:"px-4 text-sm text-muted-foreground",children:["This summary is “",j.summary.state.replace("_"," "),"” — flagging follows generation."]}),E.length>0&&e.jsx("ul",{className:"mt-2 grid gap-1 px-4 text-xs",children:E.map(W=>e.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md bg-secondary/60 px-2 py-1",children:[e.jsxs("span",{children:["#",W.sentence_index," · ",W.flag_type]}),e.jsx("button",{type:"button","aria-label":`Remove flag on sentence ${W.sentence_index}`,className:"text-muted-foreground hover:text-destructive",onClick:()=>P(se=>se.filter(ne=>ne.id!==W.id)),children:"✕"})]},W.id))}),e.jsxs("div",{className:"mt-2 flex gap-2 px-4",children:[e.jsxs(K,{size:"sm",disabled:F||E.length===0,onClick:()=>void G(),children:["Submit review (",E.length,")"]}),e.jsx(K,{size:"sm",variant:"outline",disabled:F||!z,onClick:()=>void U(),children:"Complete review"})]})]})})]})]}),o&&e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-2",children:[e.jsxs(B,{className:"gap-2 py-4",children:[e.jsxs("h2",{className:"px-4 text-base font-semibold",children:["TM canon — ",o.terms.length," terms"]}),e.jsx("ul",{className:"grid max-h-80 gap-1.5 overflow-y-auto px-4 text-sm",children:o.terms.map(W=>e.jsxs("li",{className:"rounded-md border border-border px-2.5 py-1.5",children:[e.jsx("div",{dir:"rtl",lang:"ar",className:"font-medium",children:W.canonical_ar}),e.jsx("div",{className:"mt-0.5 text-xs text-muted-foreground",children:W.variants.join(" · ")})]},W.term_id))})]}),e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Terminology feedback queue — chief economist only"}),u.length===0?e.jsx("p",{className:"px-4 text-sm text-muted-foreground",children:"No pending portal terminology feedback."}):e.jsx("ul",{className:"grid gap-1.5 px-4 text-sm",children:u.map(W=>e.jsxs("li",{className:"rounded-md border border-border px-2.5 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-mono",children:W.feedback_id}),e.jsxs("span",{children:[W.mandate_ref," · ",W.submitted_by]})]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"line-through decoration-destructive/60",children:W.term_as_used}),e.jsx("span",{"aria-hidden":!0,children:"→"}),e.jsx("bdi",{dir:dl(W.preferred_term),lang:dl(W.preferred_term)==="rtl"?"ar":void 0,className:"font-semibold",children:W.preferred_term})]}),W.ministry_doc_ref&&e.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground",children:["Ministry source: ",W.ministry_doc_ref]}),e.jsxs("div",{className:"mt-1.5 flex gap-2",children:[e.jsx(K,{size:"sm",disabled:F,onClick:()=>void ae(W.feedback_id,"apply"),children:"Apply to canon"}),e.jsx(K,{size:"sm",variant:"outline",disabled:F,onClick:()=>void ae(W.feedback_id,"reject"),children:"Reject"})]})]},W.feedback_id))})]})]}),o&&e.jsxs(B,{className:"mt-4 gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Canon changelog"}),e.jsx("ul",{className:"grid gap-1.5 px-4 text-sm",children:o.changelog.map(W=>e.jsxs("li",{className:"rounded-md border border-border px-2.5 py-1.5 text-xs",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{className:"font-mono",children:W.term_id}),e.jsx(V,{variant:W.origin==="portal-feedback"?"success":"secondary",children:W.origin})]}),e.jsxs("div",{dir:"rtl",lang:"ar",className:"mt-1 flex flex-wrap items-center gap-2",children:[W.before&&e.jsx("span",{className:"text-muted-foreground line-through",children:W.before.canonical_ar}),W.before&&e.jsx("span",{"aria-hidden":!0,children:"←"}),e.jsx("span",{className:"font-semibold",children:W.after.canonical_ar})]}),e.jsxs("div",{className:"mt-1 text-muted-foreground",children:[W.note," — approved by ",W.approved_by," at ",new Date(W.approved_at).toLocaleString(),"."]})]},W.change_id))})]})]})}function AP({workspaces:t,onEnter:n,recents:a=[],onOpenRecent:o}){return e.jsxs("div",{className:"mx-auto max-w-5xl py-10 sm:py-14",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{"aria-hidden":!0,className:"text-lg leading-none text-primary",children:"◆"}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Localize·DZ"})]}),e.jsxs("p",{className:"mt-2 max-w-xl text-sm leading-relaxed text-muted-foreground",children:["Operator console for Algeria's industrial-intelligence platform. Pick a section below, or press"," ",e.jsx("kbd",{className:"rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground",children:"⌘K"})," ","to jump straight to any page."]}),a.length>0&&e.jsxs("div",{className:"mt-7 flex flex-wrap items-center gap-2","aria-label":"Recent pages",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[e.jsx(ob,{size:12})," Continue"]}),a.map(c=>e.jsxs("button",{type:"button",onClick:()=>o(c.id),className:"rounded-md border border-border bg-card px-2.5 py-1 text-[13px] text-muted-foreground transition-colors hover:border-ring hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",children:[c.label,e.jsx("span",{className:"ml-1.5 text-[11px] text-muted-foreground/70",children:c.group})]},c.id))]}),e.jsx("div",{className:"mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:t.map(c=>{const u=c.icon;return e.jsxs(B,{className:"group cursor-pointer gap-0 p-5 transition-colors hover:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",onClick:()=>n(c.id),children:[e.jsx("div",{className:"flex size-10 items-center justify-center rounded-lg bg-primary/10 text-primary",children:e.jsx(u,{size:19})}),e.jsx("div",{className:"mt-3 text-[15px] font-semibold",children:c.label}),e.jsx("div",{className:"mt-1 text-[13px] leading-snug text-muted-foreground",children:c.description}),e.jsxs("div",{className:"mt-4 flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[c.pageCount," pages"]}),e.jsx(Am,{size:14,className:"transition-transform group-hover:translate-x-0.5"})]})]},c.id)})})]})}function RP({...t}){return e.jsx(rw,{"data-slot":"dialog",...t})}function PP({...t}){return e.jsx(lw,{"data-slot":"dialog-portal",...t})}function TP({className:t,...n}){return e.jsx(iw,{"data-slot":"dialog-overlay",className:ft("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",t),...n})}function LP({className:t,children:n,showCloseButton:a=!0,...o}){return e.jsxs(PP,{"data-slot":"dialog-portal",children:[e.jsx(TP,{}),e.jsxs(dw,{"data-slot":"dialog-content",className:ft("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",t),...o,children:[n,a&&e.jsxs(vw,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(bb,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function FP({className:t,...n}){return e.jsx(fw,{"data-slot":"dialog-title",className:ft("text-lg leading-none font-semibold",t),...n})}function DP({className:t,...n}){return e.jsx(pw,{"data-slot":"dialog-description",className:ft("text-sm text-muted-foreground",t),...n})}function $P(t,n){let a=0,o=-2;for(let c=0;c{const S=u.trim().toLowerCase();if(!S){const y=new Set(o.map(k=>k.id)),g=a.filter(k=>k.group==="Actions"),p=a.filter(k=>k.group!=="Actions"&&!y.has(k.id)).slice(0,12);return[...o.slice(0,5).map(k=>({...k,group:"Recent"})),...g,...p]}return a.map(y=>({i:y,s:$P(`${y.label} ${y.group}`.toLowerCase(),S)})).filter(y=>y.s>=0).sort((y,g)=>g.s-y.s||y.i.label.localeCompare(g.i.label)).slice(0,24).map(y=>y.i)},[a,o,u]),N=Math.min(m,Math.max(v.length-1,0)),j=S=>{S||(h(""),x(0)),n(S)},w=S=>{c(S),j(!1)},_=S=>{S.key==="ArrowDown"?(S.preventDefault(),x(Math.min(N+1,v.length-1))):S.key==="ArrowUp"?(S.preventDefault(),x(Math.max(N-1,0))):S.key==="Enter"&&v[N]&&(S.preventDefault(),w(v[N].id))};return e.jsx(RP,{open:t,onOpenChange:j,children:e.jsxs(LP,{className:"top-[16%] max-w-lg translate-y-0 overflow-hidden p-0",children:[e.jsx(FP,{className:"sr-only",children:"Search pages"}),e.jsx(DP,{className:"sr-only",children:"Jump to any console page or action by name."}),e.jsxs("div",{className:"flex items-center gap-2 border-b border-border px-3 pr-10",children:[e.jsx(qg,{size:15,className:"shrink-0 text-muted-foreground"}),e.jsx(me,{value:u,onChange:S=>{h(S.target.value),x(0)},onKeyDown:_,placeholder:"Jump to a page or run an action…",className:"h-11 border-0 shadow-none focus-visible:ring-0"})]}),v.length===0?e.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:"No matching page."}):e.jsx("div",{className:"max-h-72 overflow-y-auto p-1.5",children:v.map((S,y)=>e.jsxs("button",{type:"button",onMouseEnter:()=>x(y),onClick:()=>w(S.id),className:`flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors ${y===N?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/60 hover:text-foreground"}`,children:[e.jsx("span",{className:"truncate",children:S.label}),e.jsx("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:S.group}),y===N&&e.jsx(Am,{size:13,className:"shrink-0 text-muted-foreground"})]},S.id+S.group))}),e.jsxs("div",{className:"flex items-center gap-3 border-t border-border px-3 py-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("kbd",{className:"rounded border border-border bg-muted px-1 font-mono",children:"↑"}),e.jsx("kbd",{className:"rounded border border-border bg-muted px-1 font-mono",children:"↓"})," to move"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("kbd",{className:"rounded border border-border bg-muted px-1 font-mono",children:"↵"})," to open"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("kbd",{className:"rounded border border-border bg-muted px-1 font-mono",children:"esc"})," to close"]})]})]})})}function MP({...t}){return e.jsx(K2,{"data-slot":"popover",...t})}function OP({...t}){return e.jsx(X2,{"data-slot":"popover-trigger",...t})}function zP({className:t,align:n="center",sideOffset:a=6,...o}){return e.jsx(Y2,{children:e.jsx(Z2,{"data-slot":"popover-content",align:n,sideOffset:a,className:ft("z-50 w-72 rounded-lg border border-border bg-popover p-4 text-popover-foreground shadow-md outline-none","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",t),...o})})}function UP({consoles:t}){return e.jsxs(MP,{children:[e.jsxs(OP,{className:"inline-flex h-8 items-center gap-1.5 rounded-md border border-input bg-transparent px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-accent focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none","aria-label":"Console roles",children:[e.jsx(yb,{size:14,className:"text-muted-foreground"}),e.jsx("span",{className:"hidden sm:inline",children:"Roles"}),e.jsx(Sg,{size:13,className:"text-muted-foreground"})]}),e.jsxs(zP,{align:"end",className:"w-72 p-3",children:[e.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Acting as (console seam)"}),e.jsx("div",{className:"space-y-3",children:t.map(n=>e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n.label}),e.jsx(Ie,{value:n.value,onChange:a=>n.onChange(a.target.value),"aria-label":n.label,children:n.options.map(a=>e.jsx("option",{value:a.value,children:a.label},a.value))})]},n.label))})]})]})}const Jj="ldz.theme",pc=new Set;function ey(){try{const t=localStorage.getItem(Jj);return t==="dark"||t==="light"?t:null}catch{return null}}function BP(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function gc(){return ey()??BP()}function km(t){document.documentElement.dataset.theme=t,document.documentElement.style.colorScheme=t}function ty(){const t=gc()==="dark"?"light":"dark";try{localStorage.setItem(Jj,t)}catch{}km(t);for(const n of pc)n(t)}function HP(){km(gc()),typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: light)").addEventListener("change",()=>{if(ey()!==null)return;const t=gc();km(t);for(const n of pc)n(t)})}function VP(){const[t,n]=i.useState(gc);return i.useEffect(()=>(pc.add(n),()=>{pc.delete(n)}),[]),t}function GP(){const t=VP();return e.jsx("button",{type:"button","aria-label":t==="dark"?"Switch to light theme":"Switch to dark theme",title:t==="dark"?"Switch to light theme":"Switch to dark theme",onClick:ty,className:"rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:t==="dark"?e.jsx(jb,{size:18}):e.jsx(pb,{size:18})})}const sy="ldz.lastTabs",ny=6;function ry(){try{const t=localStorage.getItem(sy),n=t?JSON.parse(t):[];return Array.isArray(n)?n.filter(a=>typeof a=="string").slice(0,ny):[]}catch{return[]}}function WP(t){const n=[t,...ry().filter(a=>a!==t)].slice(0,ny);try{localStorage.setItem(sy,JSON.stringify(n))}catch{}return n}const lg={role:"aapi_officer",user_id:"officer-farida"},Zu={role:"platform_admin",user_id:"admin-1"},ig={role:"ceo",user_id:"ceo-yacine"},og={org_role:"org_admin",org_id:"org-aapi",user_id:"user-admin",display_name:"Farida Benali"},Ju=[{id:"opportunity",label:"Opportunity Intelligence",short:"Opportunity",description:"Card catalog, subscriber dashboards, delta review",icon:Ng},{id:"analysis",label:"Analysis & Models",short:"Analysis",description:"Financial models, BoM & suppliers, AfCFTA",icon:ab},{id:"data",label:"Data Platform",short:"Data",description:"Ingestion, connectors, CAS scoring, geospatial",icon:Rm},{id:"regulatory",label:"Regulatory & NLP",short:"Regulatory",description:"Rules, 51/49, gazette monitoring, extraction",icon:Xg},{id:"graph",label:"Ecosystem Graph",short:"Graph",description:"Anchors, supplier linkage, industrial base",icon:Vg},{id:"quality",label:"Data Quality",short:"Quality",description:"Quality dashboard, release certification, audit",icon:vg},{id:"aapi",label:"AAPI",short:"AAPI",description:"Investor inquiries, routing, success fees",icon:nm},{id:"mandate",label:"Bespoke Mandates",short:"Mandates",description:"Pre-feasibility workflow, white-label, revenue",icon:Ag},{id:"admin",label:"Platform Admin",short:"Admin",description:"API, trilingual reports, subscriptions",icon:vb}],vi=[{id:"opportunity",label:"Opportunity Cards",ws:"opportunity",icon:Ng,items:[{tab:"catalog",label:"Opportunity Cards"},{tab:"card",label:"Card Detail"},{tab:"dash-cards",label:"Subscriber Dashboard"},{tab:"dash-detail",label:"Full Card"},{tab:"dash-search",label:"Search"},{tab:"dash-trend",label:"CAS Trend"},{tab:"dash-delta",label:"Delta Feed"},{tab:"dash-seats",label:"Seat Admin"}]},{id:"delta",label:"Delta Intelligence",ws:"opportunity",icon:sb,items:[{tab:"delta",label:"Delta Review"},{tab:"delta-intel",label:"Delta Intelligence"},{tab:"delta-timeline",label:"Delta Timeline"},{tab:"delta-sla",label:"Delta SLA Monitor"},{tab:"delta-digest",label:"Digest Report"}]},{id:"financial",label:"Financial Modeling",ws:"analysis",icon:_b,items:[{tab:"fin-models",label:"Financial Models"},{tab:"fin-capex",label:"CAPEX Benchmark"},{tab:"fin-validation",label:"Model Validation"},{tab:"fin-delta",label:"Financial Delta"}]},{id:"bom",label:"BoM & Suppliers",ws:"analysis",icon:rb,items:[{tab:"bom-generate",label:"BoM Generation"},{tab:"bom-corpus",label:"Supplier Corpus"},{tab:"bom-landed",label:"Landed-Cost / CIF"},{tab:"bom-alternatives",label:"Supplier Alternatives"}]},{id:"afcfta",label:"AfCFTA",ws:"analysis",icon:db,items:[{tab:"afcfta-headroom",label:"Headroom"},{tab:"afcfta-rates",label:"Preferential Rates"},{tab:"afcfta-sizing",label:"Market Sizing"},{tab:"afcfta-dashboard",label:"AfCFTA Dashboard"},{tab:"afcfta-audit",label:"Coverage Audit"}]},{id:"data",label:"Ingestion & Pipeline",ws:"data",icon:Rm,items:[{tab:"health",label:"Ingestion Health"},{tab:"connectors",label:"Connectors"},{tab:"dictionary",label:"Dictionary"},{tab:"cas",label:"CAS Scoring"},{tab:"batch",label:"Batch Pipeline"}]},{id:"geo",label:"Geospatial",ws:"data",icon:fb,items:[{tab:"geo-map",label:"Wilaya Map"},{tab:"geo-zones",label:"Zone Registry"},{tab:"geo-siting",label:"Siting Recommendations"},{tab:"geo-logistics",label:"Logistics Corridors"},{tab:"geo-health",label:"Geo Pipeline Health"}]},{id:"regulatory",label:"Regulatory",ws:"regulatory",icon:Xg,items:[{tab:"rules",label:"Regulatory Rules"},{tab:"compliance",label:"51/49 Compliance"},{tab:"changelog",label:"Change-Log"}]},{id:"nlp",label:"NLP & OCR",ws:"regulatory",icon:gb,items:[{tab:"nlp-ocr",label:"OCR Benchmark"},{tab:"nlp-preprocess",label:"Pre-Processing"},{tab:"nlp-extract",label:"Extraction Review"},{tab:"nlp-schema",label:"Reg. Schema"},{tab:"nlp-monitor",label:"Gazette Monitor"},{tab:"nlp-daps",label:"DAPS Coverage"},{tab:"nlp-rescore",label:"Re-Scoring Audit"},{tab:"nlp-law",label:"Law/Mining"},{tab:"nlp-benchmark",label:"Benchmark Trend"},{tab:"nlp-tm",label:"Translation Memory"}]},{id:"graph",label:"Ecosystem Graph",ws:"graph",icon:Vg,items:[{tab:"graph-health",label:"Graph Health"},{tab:"graph-ingestion",label:"Anchor Ingestion"},{tab:"graph-review",label:"Graph Review"},{tab:"graph-suppliers",label:"Supplier Linkage"},{tab:"graph-gaps",label:"Input Gaps"},{tab:"graph-ecosystem",label:"Ecosystem"},{tab:"ib-scores",label:"Industrial Base"},{tab:"ib-methodology",label:"IB Weights"},{tab:"graph-refresh",label:"Graph Refresh"},{tab:"graph-profiles",label:"Anchor Profiles"}]},{id:"quality",label:"Data Quality",ws:"quality",icon:$g,items:[{tab:"q-dashboard",label:"Quality Dashboard"},{tab:"q-release",label:"Release Certification"},{tab:"q-audit",label:"Audit Log"}]},{id:"aapi",label:"AAPI",ws:"aapi",icon:nm,items:[{tab:"aapi-routing",label:"AAPI Routing"},{tab:"aapi-inquiry",label:"Investor Inquiries"},{tab:"aapi-linkage",label:"Linkage Tracker"},{tab:"aapi-schema",label:"Schema Registry"},{tab:"aapi-itest",label:"Integration Sign-Off"},{tab:"aapi-access",label:"Access Admin"},{tab:"aapi-fee",label:"Success-Fee"}]},{id:"mandate",label:"Mandate Workflow",ws:"mandate",icon:Ag,items:[{tab:"man-intake",label:"Intake"},{tab:"man-kanban",label:"Pipeline Kanban"},{tab:"man-workbench",label:"Workbench"},{tab:"scr-queue",label:"SCR Queue"},{tab:"man-scr",label:"SCR Review"},{tab:"man-arabic",label:"Arabic Review"}]},{id:"mandate-brand",label:"White-Label & Revenue",ws:"mandate",icon:nm,items:[{tab:"man-brand",label:"Brand Admin"},{tab:"man-revenue",label:"Revenue"}]},{id:"api",label:"API & Reports",ws:"admin",icon:ub,items:[{tab:"dfi-portal",label:"Developer Portal"},{tab:"dfi-admin",label:"API Credentials"},{tab:"dfi-feed",label:"DFI Data Feed"},{tab:"tri-jobs",label:"Trilingual Reports"},{tab:"tri-detail",label:"Report Detail"},{tab:"tri-sla",label:"SLA Monitor"}]},{id:"subscription",label:"Subscription Ops",ws:"admin",icon:vg,items:[{tab:"sub-provision",label:"Provisioning"},{tab:"sub-contracts",label:"Contract Status"},{tab:"sub-invoices",label:"Invoices"},{tab:"sub-flags",label:"Feature Flags"}]}],qP=[{role:"head_of_industrial_intelligence",label:"Head of Industrial Intelligence"},{role:"chief_economist",label:"Chief Economist"},{role:"senior_analyst",label:"Senior Analyst"},{role:"analyst",label:"Analyst"},{role:"ml_engineer",label:"ML Engineer"}],QP=[{role:"chief_economist",label:"Chief Economist"},{role:"head_of_industrial_intelligence",label:"Head of Industrial Intelligence"},{role:"engineering_lead",label:"Engineering Lead"},{role:"ml_engineer",label:"ML Engineer"},{role:"platform_admin",label:"Platform Admin"},{role:"subscriber",label:"Subscriber"}],KP=[{role:"mandate_requester",label:"Mandate Requester"},{role:"mandate_ops_manager",label:"Mandate Ops Manager"},{role:"senior_analyst",label:"Senior Analyst"},{role:"finance_officer",label:"Finance Officer"},{role:"arabic_reviewer",label:"Arabic Reviewer"},{role:"white_label_admin",label:"White-Label Admin"},{role:"tier3_advisory",label:"Tier-3 Advisory"},{role:"platform_admin",label:"Platform Admin"}];function XP(t){var n;return((n=vi.find(a=>a.items.some(o=>o.tab===t)))==null?void 0:n.ws)??"opportunity"}function YP(){const[t,n]=i.useState("home"),[a,o]=i.useState(null),[c,u]=i.useState("head_of_industrial_intelligence"),h={tier:"1",role:c,user_id:`console-${c}`},[m,x]=i.useState("chief_economist"),v={tier:"1",role:m,user_id:`console-${m}`},[N,j]=i.useState("mandate_ops_manager"),w={role:N,user_id:`console-${N}`},[_,S]=i.useState(null),[y,g]=i.useState(null),[p,k]=i.useState(null),[R,C]=i.useState(""),[E,P]=i.useState(!1),[F,I]=i.useState(ry),M=c==="chief_economist",$=t==="home";i.useEffect(()=>{const J=le=>{(le.metaKey||le.ctrlKey)&&le.key.toLowerCase()==="k"&&(le.preventDefault(),P(ke=>!ke))};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[]);const O=i.useMemo(()=>[...vi.flatMap(J=>J.items.filter(le=>le.tab!=="ib-methodology"||M).map(le=>{var ke;return{id:le.tab,label:le.label,group:((ke=Ju.find(Ce=>Ce.id===J.ws))==null?void 0:ke.label)??J.ws}})),{id:"action:new-intake",label:"New mandate intake",group:"Actions"},{id:"action:theme",label:"Toggle light / dark theme",group:"Actions"},{id:"action:home",label:"Go to Launchpad",group:"Actions"}],[M]),L=i.useMemo(()=>{const J=new Map(O.map(le=>[le.id,le]));return F.flatMap(le=>{const ke=J.get(le);return ke&&ke.group!=="Actions"?[ke]:[]})},[O,F]),z=i.useMemo(()=>Ju.map(J=>({...J,pageCount:vi.filter(le=>le.ws===J.id).reduce((le,ke)=>le+ke.items.filter(Ce=>Ce.tab!=="ib-methodology").length,0)})),[]),Y=J=>{var Ce;const le=J;n(le);const ke=(Ce=vi.find(Ae=>Ae.ws===le))==null?void 0:Ce.items.find(Ae=>Ae.tab!=="ib-methodology");o(ke?ke.tab:null)},G=J=>{o(J),n(XP(J)),I(WP(J))},U=J=>{P(!1),J==="action:theme"?ty():J==="action:home"?(n("home"),o(null)):G(J==="action:new-intake"?"man-intake":J)},ae=J=>{S(J),G("card")},W=J=>{g(J),G("dash-detail")},se=J=>{k(J),G("tri-detail")},ne=J=>{C(J),G("man-scr")},q=[{label:"Graph console",value:c,options:qP.map(J=>({value:J.role,label:J.label})),onChange:J=>{const le=J;u(le),a==="ib-methodology"&&le!=="chief_economist"&&o("ib-scores")}},{label:"Quality console",value:m,options:QP.map(J=>({value:J.role,label:J.label})),onChange:J=>x(J)},{label:"Mandate console",value:N,options:KP.map(J=>({value:J.role,label:J.label})),onChange:J=>j(J)}];return e.jsxs("div",{className:"min-h-svh bg-background text-foreground",children:[e.jsxs("header",{className:"sticky top-0 z-30 border-b border-border bg-background/85 backdrop-blur",children:[e.jsxs("div",{className:"flex h-14 items-center gap-3 px-4 lg:px-6",children:[e.jsxs("button",{type:"button",onClick:()=>{n("home"),o(null)},"aria-label":"Localize-DZ home",title:"Launchpad",className:"flex shrink-0 items-center gap-2 rounded-md px-1 py-1 focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",children:[e.jsx("span",{"aria-hidden":!0,className:"text-sm leading-none text-primary",children:"◆"}),e.jsx("span",{className:"text-sm font-semibold tracking-tight",children:"Localize·DZ"})]}),e.jsx("nav",{"aria-label":"Sections",className:"min-w-0 flex-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.jsx("div",{className:"flex h-14 items-center gap-0.5 overflow-x-auto",children:Ju.map(J=>{const le=!$&&t===J.id;return e.jsxs("button",{type:"button",onClick:()=>Y(J.id),"aria-current":le?"page":void 0,className:`relative flex h-14 shrink-0 items-center px-2.5 text-[13px] transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none ${le?"font-medium text-foreground":"text-muted-foreground hover:text-foreground"}`,children:[J.short,le&&e.jsx("span",{"aria-hidden":!0,className:"absolute inset-x-2 bottom-0 h-0.5 rounded-full bg-primary"})]},J.id)})})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx(GP,{}),e.jsxs(K,{variant:"outline",size:"sm",onClick:()=>P(!0),"aria-label":"Search (⌘K)",children:[e.jsx(qg,{size:14}),e.jsx("span",{className:"hidden md:inline",children:"Search"}),e.jsx("kbd",{className:"ml-1 hidden rounded border border-border bg-muted px-1 py-0.5 font-mono text-[10px] text-muted-foreground lg:inline",children:"⌘K"})]}),e.jsx(UP,{consoles:q})]})]}),!$&&e.jsx("div",{className:"flex h-10 items-center gap-4 overflow-x-auto border-t border-border/60 px-4 text-[13px] whitespace-nowrap [scrollbar-width:none] lg:px-6 [&::-webkit-scrollbar]:hidden","aria-label":"Section pages",children:vi.filter(J=>J.ws===t).map((J,le)=>{const ke=J.items.filter(Ce=>Ce.tab!=="ib-methodology"||M);return ke.length===0?null:e.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[le>0&&e.jsx("span",{"aria-hidden":!0,className:"h-4 w-px bg-border"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/70",children:J.label}),ke.map(Ce=>{const Ae=Ce.tab===a;return e.jsxs("button",{type:"button",onClick:()=>G(Ce.tab),"aria-current":Ae?"page":void 0,className:`relative flex h-10 shrink-0 items-center px-1 transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none ${Ae?"font-medium text-foreground":"text-muted-foreground hover:text-foreground"}`,children:[Ce.label,Ae&&e.jsx("span",{"aria-hidden":!0,className:"absolute inset-x-1 bottom-0 h-0.5 rounded-full bg-primary"})]},Ce.tab)})]},J.id)})})]}),e.jsx("main",{className:"mx-auto w-full max-w-6xl px-4 py-6 lg:px-6",children:$||a===null?e.jsx(AP,{workspaces:z,onEnter:Y,recents:L,onOpenRecent:J=>G(J)}):e.jsxs(e.Fragment,{children:[a==="catalog"&&e.jsx(MS,{onOpen:ae}),a==="card"&&e.jsx(QS,{cardId:_,tier:"1"}),a==="batch"&&e.jsx(XS,{}),a==="delta"&&e.jsx(ZS,{}),a==="dictionary"&&e.jsx(kS,{}),a==="health"&&e.jsx(xS,{identity:v}),a==="connectors"&&e.jsx(vS,{}),a==="rules"&&e.jsx(oC,{}),a==="compliance"&&e.jsx(uC,{}),a==="changelog"&&e.jsx(hC,{}),a==="fin-models"&&e.jsx(AC,{tier:"1"}),a==="fin-capex"&&e.jsx(TC,{tier:"1"}),a==="fin-validation"&&e.jsx(FC,{tier:"1"}),a==="fin-delta"&&e.jsx(DC,{tier:"1"}),a==="bom-generate"&&e.jsx(VC,{tier:"1"}),a==="bom-corpus"&&e.jsx(qC,{tier:"admin"}),a==="bom-landed"&&e.jsx(KC,{tier:"1"}),a==="bom-alternatives"&&e.jsx(ZC,{tier:"1"}),a==="afcfta-headroom"&&e.jsx(ck,{tier:"1"}),a==="afcfta-rates"&&e.jsx(dk,{tier:"1"}),a==="afcfta-sizing"&&e.jsx(uk,{tier:"1"}),a==="afcfta-dashboard"&&e.jsx(hk,{tier:"1"}),a==="afcfta-audit"&&e.jsx(fk,{}),a==="cas"&&e.jsx(bk,{}),a==="geo-map"&&e.jsx(zk,{tier:"1"}),a==="geo-zones"&&e.jsx(Vk,{tier:"1"}),a==="geo-siting"&&e.jsx(Gk,{}),a==="geo-logistics"&&e.jsx(Wk,{tier:"1"}),a==="geo-health"&&e.jsx(qk,{role:"platform_admin"}),a==="dash-cards"&&e.jsx(dE,{tier:"1",identity:og,onOpen:W}),a==="dash-delta"&&e.jsx(mE,{tier:"1"}),a==="dash-trend"&&e.jsx(hE,{tier:"1"}),a==="dash-search"&&e.jsx(xE,{tier:"1",onOpen:W}),a==="dash-seats"&&e.jsx(gE,{identity:og}),a==="dash-detail"&&e.jsx(vE,{cardId:y,tier:"1"}),a==="dfi-portal"&&e.jsx(PE,{}),a==="dfi-admin"&&e.jsx(TE,{}),a==="dfi-feed"&&e.jsx(LE,{}),a==="tri-jobs"&&e.jsx(OE,{onOpen:se}),a==="tri-detail"&&e.jsx(UE,{jobId:p}),a==="tri-sla"&&e.jsx(BE,{}),a==="sub-provision"&&e.jsx(XE,{}),a==="sub-contracts"&&e.jsx(ZE,{}),a==="sub-invoices"&&e.jsx(JE,{}),a==="sub-flags"&&e.jsx(e4,{}),a==="delta-intel"&&e.jsx(h4,{}),a==="delta-timeline"&&e.jsx(x4,{tier:"1"}),a==="delta-sla"&&e.jsx(p4,{}),a==="delta-digest"&&e.jsx(g4,{}),a==="aapi-routing"&&e.jsx($4,{identity:lg}),a==="aapi-inquiry"&&e.jsx(M4,{identity:lg}),a==="aapi-linkage"&&e.jsx(z4,{identity:ig}),a==="aapi-schema"&&e.jsx(U4,{identity:Zu}),a==="aapi-itest"&&e.jsx(H4,{identity:Zu}),a==="aapi-access"&&e.jsx(G4,{identity:Zu}),a==="aapi-fee"&&e.jsx(W4,{identity:ig}),a==="nlp-ocr"&&e.jsx(mA,{}),a==="nlp-preprocess"&&e.jsx(hA,{}),a==="nlp-extract"&&e.jsx(fA,{}),a==="nlp-schema"&&e.jsx(xA,{}),a==="nlp-monitor"&&e.jsx(pA,{}),a==="nlp-daps"&&e.jsx(gA,{}),a==="nlp-rescore"&&e.jsx(vA,{}),a==="nlp-law"&&e.jsx(jA,{}),a==="nlp-benchmark"&&e.jsx(yA,{}),a==="nlp-tm"&&e.jsx(_A,{}),a==="graph-health"&&e.jsx(bA,{identity:h}),a==="graph-ingestion"&&e.jsx(TA,{identity:h}),a==="graph-review"&&e.jsx(LA,{identity:h}),a==="graph-suppliers"&&e.jsx(DA,{identity:h}),a==="graph-gaps"&&e.jsx(IA,{identity:h}),a==="graph-ecosystem"&&e.jsx(VA,{identity:h,onOpenCard:ae}),a==="ib-scores"&&e.jsx(qA,{identity:h}),a==="ib-methodology"&&e.jsx(KA,{identity:h}),a==="graph-refresh"&&e.jsx(YA,{identity:h}),a==="graph-profiles"&&e.jsx(nR,{identity:h}),a==="q-dashboard"&&e.jsx(uR,{identity:v}),a==="q-release"&&e.jsx(pR,{identity:v}),a==="q-audit"&&e.jsx(gR,{identity:v}),a==="man-intake"&&e.jsx(eP,{identity:w}),a==="man-kanban"&&e.jsx(xP,{identity:w,onNavigateTab:J=>G(J)}),a==="man-workbench"&&e.jsx(pP,{identity:w}),a==="man-brand"&&e.jsx(yP,{identity:w}),a==="man-revenue"&&e.jsx(bP,{identity:w}),a==="scr-queue"&&e.jsx(CP,{identity:w,onOpen:ne}),a==="man-scr"&&e.jsx(NP,{identity:w,initialRef:R}),a==="man-arabic"&&e.jsx(EP,{identity:w})]})}),e.jsx(IP,{open:E,onOpenChange:P,items:O,recents:L,onNavigate:U})]})}const ZP=["executive-summary","market-analysis","cas-score-rationale","capex-estimation","financial-model-assumptions","regulatory-analysis","geospatial-siting","annexes"],JP=["factual-correction","assumption-query","additional-data-request","editorial"],cg=1e3,em=10*1024*1024,e3=["application/pdf","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],Mi=t=>`/portal/mandate/${encodeURIComponent(t)}`,dg=t=>he(`${Mi(t)}/dashboard`),t3=(t,n)=>he(`${Mi(t)}/documents/${encodeURIComponent(n)}/download`),s3=(t,n)=>be(`${Mi(t)}/comments`,n),n3=(t,n)=>be(`${Mi(t)}/terminology-feedback`,n),r3=(t,n)=>be(`${Mi(t)}/scope-change`,n),a3={first_draft_available:"success",under_review:"warning",final_package_available:"success",archived:"secondary"},l3={first_draft_available:"First draft available",under_review:"Under review",final_package_available:"Final package available",archived:"Archived"},ug=100,tm=t=>`${(t/1024).toFixed(0)} KB`,i3=t=>`$${t.toLocaleString("en-US")}`;function o3({token:t}){const[n,a]=i.useState(null),[o,c]=i.useState(""),[u,h]=i.useState(""),[m,x]=i.useState(!1),[v,N]=i.useState("executive-summary"),[j,w]=i.useState("factual-correction"),[_,S]=i.useState(""),[y,g]=i.useState(null),[p,k]=i.useState(""),[R,C]=i.useState(""),[E,P]=i.useState(""),[F,I]=i.useState(""),[M,$]=i.useState([]),[O,L]=i.useState(new Set),[z,Y]=i.useState(""),[G,U]=i.useState(!1),[ae,W]=i.useState(null);i.useEffect(()=>{let re=!0;return(async()=>{try{const Ee=await dg(t);re&&a(Ee)}catch(Ee){re&&c(Ee instanceof Error?Ee.message:"This link is invalid or has expired.")}})(),()=>{re=!1}},[t]);const se=async()=>{try{a(await dg(t))}catch(re){c(re instanceof Error?re.message:"Reload failed")}},ne=re=>{if(!e3.includes(re.type)){c(`Attachments must be PDF or XLSX — "${re.type||"unknown"}" is not accepted.`);return}if(re.size>em){c(`Attachments are capped at ${em/(1024*1024)} MB — "${re.name}" is ${tm(re.size)}.`);return}const Ee=new FileReader;Ee.onload=()=>{g({filename:re.name,content_type:re.type,size_bytes:re.size,data_base64:String(Ee.result).split(",")[1]??""}),c("")},Ee.readAsDataURL(re)},q=async()=>{x(!0),c(""),h("");try{const re=await s3(t,{section:v,type:j,text:_,attachment:y});h(`Comment ${re.comment.comment_id} recorded on ${v}.`),S(""),g(null),await se()}catch(re){c(re instanceof Error?re.message:"Comment failed")}finally{x(!1)}},J=async()=>{x(!0),c(""),h("");try{const re=await n3(t,{term_as_used:p,preferred_term:R,ministry_doc_ref:E.trim()===""?null:E.trim()});h(`Terminology feedback ${re.feedback.feedback_id} queued for the chief economist's review.`),k(""),C(""),P("")}catch(re){c(re instanceof Error?re.message:"Feedback failed")}finally{x(!1)}},le=()=>{const re=F.trim();if(re!==""){if(!/^\d{6}$/.test(re)){c("HS6 lines are six digits — e.g. 847989.");return}if(M.includes(re)){c(`${re} is already in the request.`);return}$(Ee=>[...Ee,re]),I(""),c("")}},ke=re=>{$(Ee=>Ee.filter(nt=>nt!==re)),L(Ee=>{const nt=new Set(Ee);return nt.delete(re),nt})},Ce=async()=>{x(!0),c(""),h("");try{const re=await r3(t,{additional_hs6_lines:M,reason:z,impact_acknowledged:!0,daps_acknowledged_lines:[...O]});W(re),$([]),Y(""),U(!1),L(new Set),await se()}catch(re){c(re instanceof Error?re.message:"Submission failed")}finally{x(!1)}},Ae=async re=>{x(!0),c("");try{const Ee=await t3(t,re),nt=URL.createObjectURL(new Blob([nh(Ee)],{type:Ee.content_type})),ct=document.createElement("a");ct.href=nt,ct.download=Ee.filename,ct.click(),URL.revokeObjectURL(nt),h(Ee.watermark_text!==null?`Downloaded ${Ee.filename} — watermarked “${Ee.watermark_text}”.`:`Downloaded ${Ee.filename}.`)}catch(Ee){c(Ee instanceof Error?Ee.message:"Download failed")}finally{x(!1)}};if(n===null)return e.jsxs("div",{className:"mx-auto w-full max-w-3xl px-4 py-10 lg:px-6",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Localize-DZ · Delivery portal"}),e.jsx("h1",{className:"mt-1 text-xl font-semibold tracking-tight",children:"Delivery portal"}),o?e.jsx("div",{className:"mt-4",children:e.jsx(H,{tone:"error",children:o})}):e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Loading your mandate…"})]});const Z=n.mandate,fe=Z.status_indicator==="under_review";return e.jsxs("div",{className:"mx-auto w-full max-w-4xl px-4 py-8 lg:px-6",children:[e.jsxs("header",{children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Localize-DZ · Delivery portal"}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-semibold tracking-tight",children:Z.client_org}),e.jsx("span",{className:"font-mono text-sm text-muted-foreground",children:Z.mandate_ref}),e.jsx(V,{variant:a3[Z.status_indicator],children:l3[Z.status_indicator]})]}),e.jsxs("p",{className:"mt-0.5 text-sm text-muted-foreground",children:["CAPEX bracket ",Z.capex_bracket]})]}),o&&e.jsx("div",{className:"mt-4",children:e.jsx(H,{tone:"error",children:o})}),u&&e.jsx("div",{className:"mt-4",children:e.jsx(H,{children:u})}),n.archived_message&&e.jsx("div",{className:"mt-4",children:e.jsx(H,{tone:"error",children:n.archived_message})}),fe&&Z.comment_deadline&&e.jsxs("div",{className:"mt-4 flex items-start gap-2.5 rounded-md border border-warning/40 bg-warning/10 p-3 text-sm",role:"status",children:[e.jsx(cb,{size:15,className:"mt-0.5 shrink-0 text-warning","aria-hidden":!0}),e.jsxs("p",{children:[e.jsx("span",{className:"font-medium text-warning",children:"Comments are open"})," until"," ",e.jsx("span",{className:"font-mono",children:new Date(Z.comment_deadline).toLocaleDateString()})," — 3 business days after the first-draft release. Everything you submit below reaches the analyst team directly."]})]}),Z.scope_sections&&e.jsxs(B,{className:"mt-4 gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Scope of this study"}),e.jsxs("div",{className:"px-4 text-sm",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Original scope"}),e.jsx("ul",{className:"mt-1 flex flex-wrap gap-1.5",children:Z.scope_sections.original.map(re=>e.jsx("li",{className:"rounded-md border border-border bg-secondary/60 px-2 py-0.5 font-mono text-xs",children:re},re))}),Z.scope_sections.extended.map(re=>e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Extended — approved ",e.jsx("span",{className:"font-mono normal-case",children:re.scr_ref})]}),e.jsx("ul",{className:"mt-1 flex flex-wrap gap-1.5",children:re.lines.map(Ee=>e.jsx("li",{className:"rounded-md border border-success/40 bg-success/10 px-2 py-0.5 font-mono text-xs text-success",children:Ee},Ee))})]},re.scr_ref))]})]}),e.jsxs(B,{className:"mt-4 gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Documents"}),n.documents.length===0?e.jsx("div",{className:"px-4",children:e.jsx(Ci,{icon:$g,title:"No documents released yet",hint:"The first draft appears here the moment it leaves review — this link stays valid for every later version."})}):e.jsx("ul",{className:"grid gap-1.5 px-4",children:n.documents.map(re=>e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border border-border px-3 py-2 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium",children:re.filename}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[re.kind," · ",re.stage," · ",e.jsx("span",{className:"font-mono",children:re.document_version})," · ",tm(re.size_bytes)]})]}),e.jsx("div",{className:"flex items-center gap-1.5",children:re.archived?e.jsx(V,{variant:"secondary",children:"cold storage"}):e.jsxs(e.Fragment,{children:[re.watermarked?e.jsx(V,{variant:"info",title:"Downloads carry a non-removable layer — drafts name you, final copies name the mandate.",children:"watermarked"}):e.jsx(V,{variant:"secondary",title:"Machine-readable output — the citation trail is its integrity seal.",children:"citation-sealed"}),e.jsx(K,{size:"sm",variant:"outline",disabled:m,onClick:()=>void Ae(re.document_id),children:"Download"})]})})]},re.document_id))}),n.revision_history.length>0&&e.jsxs("div",{className:"px-4 pt-1",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Revision history"}),e.jsx("ul",{className:"mt-1 grid gap-0.5 text-xs text-muted-foreground",children:n.revision_history.map((re,Ee)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"font-mono",children:re.document_version}),e.jsx("span",{children:new Date(re.created_at).toLocaleString()})]},`${re.document_id}-${Ee}`))})]})]}),e.jsxs(B,{className:"mt-4 gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Review comments"}),n.comments.length===0&&!fe?e.jsx("div",{className:"px-4",children:e.jsx(Ci,{icon:xb,title:"No comments yet",hint:"The comment form opens while the first draft is under review — 3 business days after its release."})}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"grid gap-1.5 px-4",children:n.comments.map(re=>e.jsxs("li",{className:"rounded-md border border-border px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-mono",children:re.section}),e.jsx(V,{variant:"outline",children:re.type.replace(/-/g," ")}),re.resolved_at!==null?e.jsx(V,{variant:"success",children:"resolved"}):e.jsx(V,{variant:"warning",children:"open"}),e.jsxs("span",{className:"ml-auto",children:[re.author," · ",new Date(re.posted_at).toLocaleString()]})]}),e.jsx("p",{dir:dl(re.body),lang:dl(re.body)==="rtl"?"ar":void 0,className:"mt-1.5",children:re.body}),re.attachment_filename&&e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:["Attachment: ",re.attachment_filename]})]},re.comment_id))}),e.jsxs("div",{className:"mt-2 grid gap-2 border-t border-border px-4 pt-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Leave a comment"}),!fe&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Comments are open only while the first draft is under review."}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-sm",children:["Report section",e.jsx(Ie,{className:"mt-1",value:v,disabled:!fe,onChange:re=>N(re.target.value),children:ZP.map(re=>e.jsx("option",{value:re,children:re.replace(/-/g," ")},re))})]}),e.jsxs("label",{className:"text-sm",children:["Comment type",e.jsx(Ie,{className:"mt-1",value:j,disabled:!fe,onChange:re=>w(re.target.value),children:JP.map(re=>e.jsx("option",{value:re,children:re.replace(/-/g," ")},re))})]})]}),e.jsxs("label",{className:"text-sm",children:["Comment (",cg-_.length," characters left)",e.jsx(fa,{className:"mt-1",value:_,disabled:!fe,rows:3,onChange:re=>S(re.target.value.slice(0,cg))})]}),e.jsxs("label",{className:"text-sm",children:["Attachment (optional — PDF/XLSX, ≤",em/(1024*1024)," MB)",e.jsx("input",{type:"file",disabled:!fe,onChange:re=>{var nt;const Ee=(nt=re.target.files)==null?void 0:nt[0];Ee&&ne(Ee)},className:"mt-1 w-full rounded-md text-sm text-muted-foreground file:mr-3 file:inline-flex file:h-7 file:rounded-md file:border-0 file:bg-secondary file:px-2 file:text-xs file:font-medium file:text-foreground focus-visible:outline-none"})]}),y&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Attached: ",e.jsx("span",{className:"font-medium text-foreground",children:y.filename})," (",tm(y.size_bytes),") —"," ",e.jsx("button",{type:"button",className:"underline focus-visible:outline-none",onClick:()=>g(null),children:"remove"})]}),e.jsx(K,{size:"sm",className:"w-fit",disabled:m||!fe||_.trim()==="",onClick:()=>void q(),children:"Submit comment"})]})]})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-2",children:[e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Terminology feedback"}),e.jsx("p",{className:"px-4 text-sm text-muted-foreground",children:"A term the study should use instead — the chief economist reviews every suggestion against the ministry canon."}),e.jsxs("div",{className:"grid gap-2 px-4",children:[e.jsxs("label",{className:"text-sm",children:["Term as used",e.jsx(me,{className:"mt-1",value:p,onChange:re=>k(re.target.value),placeholder:"pièce détachée"})]}),e.jsxs("label",{className:"text-sm",children:["Preferred term (Arabic)",e.jsx(me,{dir:"rtl",lang:"ar",className:"mt-1",value:R,onChange:re=>C(re.target.value),placeholder:"قطعة غيار"})]}),e.jsxs("label",{className:"text-sm",children:["Ministry document reference (optional)",e.jsx(me,{className:"mt-1",value:E,onChange:re=>P(re.target.value),placeholder:"JO n°…"})]}),e.jsx(K,{size:"sm",className:"w-fit",disabled:m||p.trim()===""||R.trim()==="",onClick:()=>void J(),children:"Send feedback"})]})]}),e.jsxs(B,{className:"gap-2 py-4",children:[e.jsx("h2",{className:"px-4 text-base font-semibold",children:"Scope change request"}),e.jsx("p",{className:"px-4 text-sm text-muted-foreground",children:"Adding lines pauses the SLA clock pending operations' review; approval bills a supplemental fee and extends the deadline."}),e.jsxs("div",{className:"grid gap-2 px-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(me,{value:F,onChange:re=>I(re.target.value),placeholder:"HS6 line (6 digits)"}),e.jsx(K,{size:"sm",variant:"outline",onClick:le,children:"Add"})]}),M.length>0&&e.jsx("ul",{className:"grid gap-1",children:M.map(re=>e.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md border border-border px-2.5 py-1.5 text-sm",children:[e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:O.has(re),className:"size-4 accent-primary",onChange:Ee=>L(nt=>{const ct=new Set(nt);return Ee.target.checked?ct.add(re):ct.delete(re),ct})}),e.jsx("span",{className:"font-mono text-xs",children:re})]}),e.jsx("button",{type:"button","aria-label":`Remove line ${re}`,className:"text-muted-foreground transition-colors hover:text-destructive focus-visible:outline-none",onClick:()=>ke(re),children:"✕"})]},re))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tick a line whose DAPS duty treatment exceeds 50% — the request is rejected while such a line goes unacknowledged."}),e.jsxs("label",{className:"text-sm",children:["Reason (",z.trim().length,"/",ug," characters — why these lines belong in this study)",e.jsx(fa,{className:"mt-1",value:z,rows:3,onChange:re=>Y(re.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:G,className:"size-4 accent-primary",onChange:re=>U(re.target.checked)}),"I understand approval bills a supplemental fee and shifts the delivery deadline."]}),e.jsx(K,{size:"sm",className:"w-fit",disabled:m||M.length===0||z.trim().lengthvoid Ce(),children:"Submit request"})]})]})]}),ae&&e.jsx("div",{className:"mt-4",children:e.jsxs(H,{children:["Scope change ",e.jsx("span",{className:"font-mono",children:ae.scr.scr_ref})," submitted — pending operations review. On approval: supplemental fee ",i3(ae.supplemental_fee_usd),", revised first-draft deadline ",new Date(ae.revised_deadline).toLocaleDateString(),"."]})})]})}const ay=document.getElementById("root");if(!ay)throw new Error("#root not found");HP();var hg;const c3=(hg=window.location.pathname.match(/^\/portal\/([A-Za-z0-9_-]+)/))==null?void 0:hg[1],d3=/^\/mandates\/[^/]+\/portal$/.test(window.location.pathname),mg=c3??(d3?new URLSearchParams(window.location.search).get("t")??"":void 0);G_.createRoot(ay).render(e.jsx(i.StrictMode,{children:mg?e.jsx(o3,{token:mg}):e.jsx(YP,{})}));